body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>The following code is an implementation of heapsort on an array</p>
<pre><code>public static void heapSort(int[] inputArray){
/* Creates an array A which will contain the heap */
/* A has size n+1 to allow 1-based indexing */
int n = inputArray.length;
int[] A = new int[n+1];
int temp = 0;
/* Copies the array inputArray into A, with inputArray[i] being stored in A[i+1] */
for(int i=0; i<n; i++){
A[i+1] = inputArray[i];
}
constructHeap(A, n, 1);
removeMax(A, n);
copyBack(A, inputArray);
}
/* Transforms A into a max-heap using a 'bottom-up' algorithm. */
public static void constructHeap(int[] A, int n, int i){
if(2*i>n) return;
constructHeap(A, n, 2*i);
constructHeap(A, n, 2*i+1);
bubbleDown(A, n, i);
}
/*recursively swaps parent/child relationships until the max-heap property is satisfied. */
public static void bubbleDown(int[] A, int n, int i){
if(2*i>n) return;
int leftChild = 2*i;
int rightChild = 2*i+1;
int max = leftChild;
if(rightChild<=n && A[max]<A[rightChild]){
max = rightChild;
}
if(A[i]<A[max]){
int temp = A[i];
A[i] = A[max];
A[max] = temp;
bubbleDown(A, n, max);
}
}
/* Performs a sequence of n 'remove-maximum' operations, storing the removed element at
each step in successively smaller indices of A */
public static void removeMax(int[] A, int i){
for(int i=n; i>0; i--){
int temp = A[1];
A[1] = A[i];
bubbleDown(A, i, 1);
A[i] = temp;
}
/* Copies the sorted values in A back into inputArray, with inputArray[i] getting
the value from A[i+1] */
public static void copyBack(int[] A, int[] inputArray){
for(int i=0; i<inputArray.length; i++){
inputArray[i] = A[i+1];
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T21:08:00.487",
"Id": "74490",
"Score": "2",
"body": "Welcome to CodeReview.SE ! You are suppose to provide some actual working code to review. In your case, it seems to be pretty close to working so it would be really helpful if you could tell us more about your issue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T21:32:12.543",
"Id": "74494",
"Score": "0",
"body": "Well as I began writing the code, I was working with a small array of size 10 containing elements in the range of [1, 100], and worked out the bugs until it worked. Then I subsequently tested the code on larger input files. When the input array has 999 values, it sorts just fine, but when I try with 100,000 values, I get an error at line 95, which is the recursive call to removeMax(A, i-1)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T21:54:34.993",
"Id": "74499",
"Score": "0",
"body": "In the future, be as specific as possible when describing the problem. An \"error\" isn't too helpful while `StackOverflowException` gives a big clue."
}
] |
[
{
"body": "<p>Your constructHeap method works in O(n), and you call in O(n) times from removeMax method, so your code works in O(n^2), so it is not a correct implementation of Heapsort.</p>\n\n<p>Comments:</p>\n\n<pre><code>public static void heapSort(int[] inputArray) {\n</code></pre>\n\n<p>Why do you need another array? Heapsort is in-place.</p>\n\n<pre><code> /* Creates an array A which will contain the heap */\n</code></pre>\n\n<p>Why do you need 1-based indexing? You don't seem to use it anywhere, and 0-based is more convenient.</p>\n\n<pre><code> /* A has size n+1 to allow 1-based indexing */\n int n = inputArray.length;\n\n\n int[] A = new int[n + 1];\n</code></pre>\n\n<p>You don't use this variable.</p>\n\n<pre><code> int temp = 0;\n\n /* Copies the array inputArray into A, with inputArray[i] being stored in A[i+1] */\n</code></pre>\n\n<p>You should replace this loop with System.arraycopy(...) call</p>\n\n<pre><code> for (int i = 0; i < n; i++) {\n A[i + 1] = inputArray[i];\n }\n constructHeap(A, n, 1);\n removeMax(A, n);\n copyBack(A, inputArray);\n}\n</code></pre>\n\n<p>Consider transforming such comments into valid javadoc.</p>\n\n<pre><code>/* Transforms A into a max-heap using a 'bottom-up' algorithm. */\npublic static void constructHeap(int[] A, int n, int i) {\n if (2 * i > n) {\n return;\n }\n constructHeap(A, n, 2 * i);\n constructHeap(A, n, 2 * i + 1);\n bubbleDown(A, n, i);\n}\n</code></pre>\n\n<p>Comment?</p>\n\n<pre><code>public static void bubbleDown(int[] A, int n, int i) {\n if (2 * i > n) {\n return;\n }\n int leftChild = 2 * i;\n int rightChild = 2 * i + 1;\n int max = leftChild;\n if (rightChild <= n && A[max] < A[rightChild]) {\n max = rightChild;\n }\n if (A[i] < A[max]) {\n int temp = A[i];\n A[i] = A[max];\n A[max] = temp;\n bubbleDown(A, n, max);\n }\n}\n\n /* Performs a sequence of n 'remove-maximum' operations, storing the removed element at\n each step in successively smaller indices of A */\n\npublic static void removeMax(int[] A, int i) {\n if (i == 0) {\n return;\n }\n int temp = A[1];\n A[1] = A[i];\n constructHeap(A, i, 1);\n A[i] = temp;\n</code></pre>\n\n<p>So you make O(n) recursive calls? This is causing StackOverflowException with large n and harming your running time. Consider transforming this tail recursion into a loop.</p>\n\n<pre><code> removeMax(A, i - 1);\n}\n\n /* Copies the sorted values in A back into inputArray, with inputArray[i] getting\n the value from A[i+1] */\n\npublic static void copyBack(int[] A, int[] inputArray) {\n</code></pre>\n\n<p>ditto</p>\n\n<pre><code> for (int i = 0; i < inputArray.length; i++) {\n inputArray[i] = A[i + 1];\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T21:44:10.603",
"Id": "74495",
"Score": "0",
"body": "Thanks for the help. I had meant to use bubbleDown() inside removeMax() instead of constructHeap(), so now that I've replaced that, the running time has gone to O(nlogn). Replacing the recursion with a loop did the trick with StackOverflowException as well. Thanks again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T21:29:06.670",
"Id": "43168",
"ParentId": "43165",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "43168",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T20:29:55.610",
"Id": "43165",
"Score": "4",
"Tags": [
"java",
"algorithm",
"performance"
],
"Title": "Implementation of HeapSort"
}
|
43165
|
<p>I'm pretty new to C# and have decided that I wanted to make a program that calculate the multiplication table of a selected number to practice on loops etc. I'm pretty satisfied, but I wondered if there is anything I can do to make the code better and more concise.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Multiplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Write a number and I'll calculate the multiplication table of the number");
int userValue_number = int.Parse(Console.ReadLine());
Console.WriteLine("How far do you want to go? E.g. 12, then {0} x 12 is the highest I will go ", userValue_number);
int userValue_length = int.Parse(Console.ReadLine());
int n = userValue_number;
int i = 1;
while (n <= (userValue_number * userValue_length))
{
Console.WriteLine("{0} x {1} = {2}", i, userValue_number, n);
n=n+userValue_number;
i++;
}
Console.ReadLine();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p><code>int.Parse</code> will throw an exception if input isn't an integer. Consider using <code>int.TryParse</code> instead.</p>\n\n<p>You should verify that the user doesn't enter a negative integer for the 2nd argument.</p>\n\n<p>Your while loop should be a for loop.</p>\n\n<p>A multiplication isn't much more expensive than an addition, especially compared with the performance cost of calling Console.WriteLine; so I'd use multiplication instead if that makes the code clearer:</p>\n\n<pre><code>for (int i = 1; i <= userValue_length ; ++i)\n{\n Console.WriteLine(\"{0} x {1} = {2}\", i, userValue_number, i * userValue_number);\n}\n</code></pre>\n\n<p>userValue_number is a strange mix of camelCase and using_underscores. camelCase is more conventional in C#. I think I'd rename those to chosenNumber and chosenTimes or something like that.</p>\n\n<p>The final Console.ReadLine(); is ugly and uncessary. You probably use it for debugging; instead (to inspect output from a debugger session before the console window auto-closes) put a debugger breakpoint on the final curly brace of main.</p>\n\n<p>Your message <code>E.g. 12, then {0} x 12 is ...</code> doesn't match your output <code>{0} x {1} = ...</code>; instead <code>i</code> should be the 2nd (not 1st) number in your output.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T22:49:36.680",
"Id": "74502",
"Score": "2",
"body": "Also, this version is not affected by infinite loops like OP's version (when userValue_number is 0)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T22:51:35.450",
"Id": "74503",
"Score": "1",
"body": "I'd upvote that if you post it as a separate answer (because I especially admire code reviews which find bugs)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T22:45:15.667",
"Id": "43174",
"ParentId": "43173",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "43174",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T22:34:36.613",
"Id": "43173",
"Score": "8",
"Tags": [
"c#",
"beginner"
],
"Title": "Simple C# multiplication table program"
}
|
43173
|
<p>I am trying to learn how to tell if my code will be better off creating a class as opposed to using many functions. I am a new Python programmer trying to get the hang of when classes should be implemented.</p>
<p>Determines whether the username is valid or invalid:</p>
<pre><code>def is_good_user(user):
is_user_good = True
if user in database:
print "Sorry! Username is taken! Create another."
is_user_good = False
if not 5 < len(user) < 25:
print "Username must be at least 6 characters!"
is_user_good = False
if is_ascii(some_string="") is not True:
print "Please create username that follows ASCII formatting."
is_user_good = False
return is_user_good
</code></pre>
<p>Determines whether the password is valid or invalid:</p>
<pre><code>def is_good_password(password):
count_upper, count_lower = 0, 0
for characters in password:
if characters.isupper():
count_upper += 1
if characters.islower():
count_lower += 1
is_password_good = True
if len(password) <= 10:
print "Password is too weak, must be more than 10 characters long!"
is_password_good = False
if set(database).intersection(password):
print "Password Must Contain Alphanumeric Characters!"
is_password_good = False
if count_upper < 1 or count_lower < 1:
print "Password must contain at least one uppercase and one lowercase character!"
is_password_good = False
return is_password_good
</code></pre>
<p>These two functions are amalgamated into one function to create a username and password:</p>
<pre><code>def create_user(database):
while True:
user = raw_input("Enter a New Username: ")
if is_good_user(user):
print "Great Job! Username Successfully Created! Time to Create a Password!"
break
print "That's not a good username, please try again!"
while True:
passcode = raw_input("Enter a New Password: ")
if is_good_password(passcode):
print "Welcome! Username & Password successfully created!"
break
print "That's not a good password, please try again!"
database[user] = passcode
make_digest(password=passcode, salt=None)
dump_data()
</code></pre>
<p>Should I add in a class for readability of my code? Being new at Python, I'd like to take up the challenge if adding a class is necessary.</p>
|
[] |
[
{
"body": "<p>It's a design choice.\nA class is \"meant to be\" a collection that encapsulates functionality and \"behavior\" in code. The purpose is to expose specifically an interface where a class's instances can live on their own. </p>\n\n<p>A function/method is an independent piece of code that in theory \"shouldn't\" relate to other pieces of code outside of it. </p>\n\n<p>So for the example you've described, you could create a class named \"User\". And user can include these functions as it's members.\nThis does make it more readable and easier to debug.<br>\nHowever do not take unrelated functions and dump them into a class just cuz!\nExamples are utility type functions, they could be kept in the vicinity of each other but should not be clubbed together as a class.</p>\n\n<p>An additional benefit of classes is that they can be Inherited from. So more complex classes can inherit the basic functionality and add to it, while using the features already in the base class. You can achieve a similar effect by having \"higher\" versions of functions that calls more basic level functions. There again at least in my design perspective, I make a class where the whole functionality will be inherited as opposed to functions that are stand-alone.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T23:34:21.920",
"Id": "43177",
"ParentId": "43175",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T23:20:23.817",
"Id": "43175",
"Score": "3",
"Tags": [
"python",
"beginner",
"classes"
],
"Title": "Using classes vs. using functions"
}
|
43175
|
<p>I'm making a game in Java with LWJGL and I just implemented jumping. I don't really think the code is particularly well written or very efficient. Here is the code of my <code>Camera</code> class:</p>
<pre><code>public void startJump(float height, float land){
jumpHeight = height;
jumpLand = land;
if(!falling && !jumping)
jumping = true;
}
private void jump(){ // called every frame
if(jumping){
if(y >= -jumpHeight){
y -= jumpSpeed;
}else{
jumping = false;
falling = true;
}
}
if(falling){
if(y <= -jumpLand){
y += jumpSpeed;
}else{
jumping = false;
falling = false;
}
}
}
</code></pre>
<p>If someone knows a cleaner or more efficient method please tell me!</p>
<p>EDIT:</p>
<p>I was thinking of using <code>jumping</code> and <code>!jumping</code> but this introduces a bug where if the jump key is held down then the player hovers in the air so unless your making a jet-pack use <code>jumping</code> and <code>falling</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T23:59:23.783",
"Id": "74509",
"Score": "2",
"body": "You got bad performance? the code is good after all. A question: if a player is `jumping` `falling` will never be true? and if a player is `falling` `jumping` will never be true? I Mean: can `jumping` and `falling` be true together?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T00:47:46.803",
"Id": "74514",
"Score": "0",
"body": "@MarcoAcierno My performance is fine, I was just wondering if there was a more efficient way rather than checking the player is jumping every frame. Also, falling and jumping will never be true at the same time so I have changed it to `jumping` and `!jumping`. Thank you for pointing that out."
}
] |
[
{
"body": "<p>After your comment, the only change i could say is to change</p>\n\n<pre><code>private void jump(){ // called every frame\n if(jumping){\n if(y >= -jumpHeight){\n y -= jumpSpeed;\n }else{\n jumping = false;\n falling = true;\n }\n }\n\n if(falling){\n</code></pre>\n\n<p>to</p>\n\n<pre><code>private void jump(){ // called every frame\n if(jumping){\n if(y >= -jumpHeight){\n y -= jumpSpeed;\n }else{\n jumping = false;\n falling = true;\n }\n }\n\n else if(falling){\n</code></pre>\n\n<p>To avoid to check falling too if it's jumping. But its a macro optimization (useless too maybe in this case.)\nBut really, this code is perfect how it is. So go ahead!</p>\n\n<p>Just got this idea in my mind: you could define a \"PlayerStatus\" enum with: Falling, Jumping but it will affect the logic of your game, change it only if you think you will need more status and maintain two boolean variables (or more if you add more conditions) will be hard. If you need only one turned on and others off.. it's a great way to do it:</p>\n\n<pre><code>enum PlayerStatus\n{\n FALLING,\n JUMPING\n}\n</code></pre>\n\n<p>and use the enum to change the status..</p>\n\n<pre><code>PlayerStatus status;\nstatus = PlayerStatus.FALLING;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T00:49:58.590",
"Id": "43187",
"ParentId": "43179",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "43187",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T23:50:52.937",
"Id": "43179",
"Score": "4",
"Tags": [
"java",
"opengl"
],
"Title": "OpenGL first person jumping code"
}
|
43179
|
<p>I'm working on a random number guessing game. I'm done with the code and it's working, but there is a part that I want to make better. I declared an instance of a <code>Guess</code> class I created, and now how to make this part more efficient.</p>
<pre><code>int counter = 0;
do
{
myGuess.UserGuess = GetUserGuess(); //read user guess
if (myGuess.Compair() == "match")
{
Console.WriteLine("\n\t Correct!You WIN !");
}
else if (myGuess.Compair() == "high")
{
if (counter < 3)
Console.WriteLine("\n\tTry a lower number,");
else
Console.WriteLine("\n\tSorry you LOSE !, The right number is " + myGuess.RndNum);
counter++;
}
else if (myGuess.Compair() == "low")
{
if (counter < 3)
Console.WriteLine("\n\tTry a higher number,");
else
Console.WriteLine("\n\tSorry you LOSE !, The right number is " + myGuess.RndNum);
counter++;
}
} while (myGuess.Compair() != "match" && counter < 4);
</code></pre>
<p>For example, I used the same message the same condition twice, which I think is not the best way. Any way to loop better than that?</p>
|
[] |
[
{
"body": "<p>You can use a switch statement instead of if else if else if.</p>\n\n<p>You don't need to test if (counter < 3) inside the do loop; instead you could exit the do loop when the count is too high.</p>\n\n<p>Similarly you could print the error message once if/after you exit the do loop unsuccessfully.</p>\n\n<p>So:</p>\n\n<pre><code>for (int counter = 0; counter < 3; ++counter)\n{\n myGuess.UserGuess = GetUserGuess(); //read user guess\n switch (myGuess.Compare()) \n {\n case \"match\":\n Console.WriteLine(\"\\n\\t Correct!You WIN !\");\n return true; // tell caller than the guess was successful\n case \"high\"\n Console.WriteLine(\"\\n\\tTry a lower number,\");\n break;\n case \"low\"\n Console.WriteLine(\"\\n\\tTry a higher number,\");\n break;\n default:\n throw new NotImplementedException(); // unexpected Compare result\n }\n}\nConsole.WriteLine(\"\\n\\tSorry you LOSE !, The right number is \" + myGuess.RndNum);\nreturn false;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T08:52:39.360",
"Id": "74552",
"Score": "1",
"body": "I like the switch option. I might also consider using enums instead of string literals as well as passing userGuess into the Compare method rather than a public property setter..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T00:22:52.663",
"Id": "43181",
"ParentId": "43180",
"Score": "3"
}
},
{
"body": "<p>I think a way to make this code generally more efficient and predictable is to have your classes have a more defined role. For example, it seems like you're defining an instance of Guess as myGuess, then externally loading in a random number (RndNum), and the current guess (UserGuess = GetUserGuess()).</p>\n\n<p>You should clearly define the goals for classes, such as:</p>\n\n<ul>\n<li>Manage the Game lifecycle.</li>\n<li>Handle user input, ensuring the user enters only numbers and is properly prompted, etc.</li>\n</ul>\n\n<p>In this way, your code might look more like this psuedo-code:</p>\n\n<pre><code>class GuessingGame\n{\n static void Main(string[] args)\n {\n game = new GuessingGame();\n game.run();\n }\n\n int numGuesses;\n int correctNumber;\n UserInputHandler userInputHandler;\n\n GuessingGame(numGuesses = 4)\n {\n Random random = new Random();\n this.correctNumber = random.Next(10);\n this.numGuesses = numGuesses;\n this.userInputHandler = new UserInputHandler();\n }\n\n void run()\n {\n for (int thisGuess = 0; thisGuess < numGuesses; ++thisGuess)\n {\n Console.WriteLine(string.Format(\"Guess #{0}!\\n\", thisGuess + 1));\n guess = this.userInputHandler.getGuess();\n if (guess < this.correctNumber)\n {\n Console.WriteLine(\"WRONG! Try a higher number!\");\n }\n else if (guess > this.correctNumber)\n {\n Console.WriteLine(\"WRONG! Try a lower number!\");\n }\n else\n {\n win();\n return();\n }\n }\n lose();\n }\n\n void win()\n {\n Console.WriteLine(\"You WIN! The number was indeed \" + this.correctNumber);\n }\n\n void lose()\n {\n Console.WriteLine(\"You LOSE! The number was \" + this.correctNumber);\n }\n}\n\n// UserInputHandler Source\nclass UserInputHandler\n{\n public int getGuess()\n {\n // Handle user input, and ensure the guesses are actually numbers.\n }\n}\n</code></pre>\n\n<p>The idea is that each class is responsible for encapsulating one piece of functionality around another class. The Main program entry point doesn't care about how the game works, the GuessingGame class doesn't care about interacting with the user at all, while the UserInputHandler class doesn't care about the correct answer, etc.</p>\n\n<p>I've also wrapped the win/loss messages into a single method, so that you're not repeating the victory message.</p>\n\n<p>Some benefits include:</p>\n\n<ul>\n<li>Having a clear understanding of the role of each class.</li>\n<li>Being able to assert that with unit tests easily.</li>\n<li>Code reuse. You could plug the UserInputClass into a different game that requires simple user input, for example.</li>\n<li>Collaboration. Properly scoped and documented code means other developers could jump into your project with less friction.</li>\n</ul>\n\n<p>Now this example is a bit much considering that a guessing game is fairly basic, but it's good practice for tackling larger projects.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T00:42:05.180",
"Id": "43183",
"ParentId": "43180",
"Score": "6"
}
},
{
"body": "<p>@ChrisW has a good answer. The code is clean.</p>\n\n<p>You could also consider having your comparison return an <code>int</code>:</p>\n\n<ul>\n<li><code>0</code> for the same</li>\n<li><code>-1</code> if the guess is less than the number</li>\n<li><code>1</code> if the guess is greater than the number</li>\n</ul>\n\n<p>It would basically be wrapping the <code>CompareTo</code> method for whatever your guess data type is. There are more <code>CompareTo</code> methods, but here are a couple examples:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/y2ky8xsk(v=vs.110).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/y2ky8xsk(v=vs.110).aspx</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/fyxd1d26(v=vs.110).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/fyxd1d26(v=vs.110).aspx</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T00:43:18.487",
"Id": "43185",
"ParentId": "43180",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "43183",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T00:03:35.353",
"Id": "43180",
"Score": "6",
"Tags": [
"c#",
"game",
"random",
"console"
],
"Title": "Random number guessing game"
}
|
43180
|
<p>I am relatively new to the Qt framework and I was wondering if I should delete pointers in my program. I know that, in C++, if memory is not return it could lead to memory leak, but I am not sure if the same applies to Qt. </p>
<pre><code>#include "mainwindow.h"
#include <QApplication>
#include <QTextEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QIcon>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget *w = new QWidget();
w->setWindowTitle("Music Player");
QIcon * mainwind_icon = new QIcon("MusicPlayer.png");
w->setWindowIcon(*mainwind_icon);
QPushButton * enter_button = new QPushButton();
QTextEdit * textbox = new QTextEdit();
QHBoxLayout * vlayout = new QHBoxLayout;
vlayout->addWidget(textbox);
vlayout->addWidget(enter_button);
w->setLayout(vlayout);
w -> show();
return a.exec();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T06:08:25.600",
"Id": "74540",
"Score": "2",
"body": "ratchet freak's answer is more relevant (and correct) to your specific Qt question. You don't need to delete anything manually if it's parented."
}
] |
[
{
"body": "<p>In Qt, there is a concept of parents and a hierarchy.</p>\n\n<p>In essence, it means that when a qobject owns another qobject (the other qobject's <code>parent</code> is the first) then the parent will take care of cleaning its children.</p>\n\n<p>There are 2 ways an object becomes a child of another: when it is set in the constructor or when reparented. The qwidget family automatically reparents widgets which you add to it</p>\n\n<p>Common use for the main function is to allocate the root statically and all the rest dynamically as child of the root:</p>\n\n<pre><code>int main(int argc, char *argv[])\n{\n QApplication a(argc, argv);\n QWidget w ();\n w.setWindowTitle(\"Music Player\");\n QIcon * mainwind_icon = new QIcon(\"MusicPlayer.png\");\n w.setWindowIcon(*mainwind_icon);\n\n QPushButton * enter_button = new QPushButton();\n QTextEdit * textbox = new QTextEdit();\n\n QHBoxLayout * vlayout = new QHBoxLayout;\n vlayout->addWidget(textbox);\n vlayout->addWidget(enter_button);\n\n w.setLayout(vlayout);\n\n w.show();\n return a.exec();\n}\n</code></pre>\n\n<p>The <code>setlayout</code> takes ownership of the <code>vlayout</code> and its children so the destructor of <code>w</code> will delete those as well</p>\n\n<p>When you are inside an event loop then you can delete a qobject by calling <code>deleteLater</code> on it which will schedule the object (and its children) for deletion. You can also connect a signal to it if needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T04:26:35.047",
"Id": "43201",
"ParentId": "43189",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "43201",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T01:11:50.583",
"Id": "43189",
"Score": "9",
"Tags": [
"c++",
"memory-management",
"qt"
],
"Title": "Deleting pointers in Qt5"
}
|
43189
|
<p>I'm more of an IT guy (no CS course) with a strong and passionate relationship with Unix and I love <a href="http://en.wikipedia.org/wiki/KISS_principle" rel="nofollow">KISS</a>.</p>
<p>I'm writing an application to help my coworkers with their daily tasks. Every now and then I get request from coworkers to add functionality to help them. Most of the time I will turn an Excel spreadsheet to a form based "module" in my application.</p>
<p>The application is built with PHP and runs on Apache, using <code>MultiViews</code> for "pretty-urls" and <code>FallbackResource /index.php</code>.</p>
<p>The folder structure looks like this:</p>
<blockquote>
<pre><code>app/
_views/
_errors/
401.php
403.php
404.php
user/
add.php
get.php
core/
config.php
user.php
hr/
department.php
.settings.php
bootstrap.php
lib/
z/
form.php
route.php
view.php
logs/
public/
css/
fonts/
images/
js/
index.php
user.php
</code></pre>
</blockquote>
<p><code>app/bootstrap.php</code> is prepended to every <code>.php</code> files in the <code>public/</code> folder.</p>
<pre><code><?php
// autoloader
set_include_path(implode(PATH_SEPARATOR, array(
get_include_path(),
dirname(__DIR__) . DIRECTORY_SEPARATOR .'lib',
__DIR__,
)));
spl_autoload_extensions('.php');
spl_autoload_register();
// application user stuff
session_start();
if (isset($_SESSION['username'])) {
$user = new core\user($_SESSION['username']);
define('LOGGED', true);
}
else {
$user = new core\user();
define('LOGGED', false);
}
function http_error($error) {
http_response_code($error);
$view = new z\view('_errors/'. $error .'.php');
die($view);
}
</code></pre>
<p>My controllers are in the <code>public/</code> folder and look like this:</p>
<pre><code><?php # /user.php ; controllers for /user(.*)
use z\form;
use z\route as main;
use z\view;
main::get('/user/add', function() use ($user) {
if (!LOGGED)
http_error(401);
if (!$user->allowed('user-add'))
http_error(403);
$view = new view('user/add.php');
die($view);
});
main::get('/user/%s', function($username) use ($user) {
$person = new core\user($username);
if ($person->notfound === true)
http_error(404);
if (!LOGGED)
http_error(401);
if (!$user->allowed('user-view'))
http_error(403);
$view = new view('user/get.php');
$view->person = $person;
if ($user->allowed('user-manage')) {
$view->procedures = $person->procedures();
$departments = hr\department::select();
array_shift($departments);
$view->departments = $departments;
}
die($view);
});
main::post('/user', function() use ($user) {
if (!LOGGED)
http_error(401);
if (!$user->allowed('user-add'))
http_error(403);
$form = new form($_POST);
if (core\user::insert(array(
'value1' => $form->field1->value,
'value2' => $form->field2->value,
...
))) {
main::redirect('/user/'. $form->username->value);
}
else {
$view = new view('user/add.php');
$view->error = true;
$view->message = 'Error message';
die($view);
}
});
...
http_error(404);
</code></pre>
<p>View 'user/get.php':</p>
<pre><code><?php $layout = 'html.php' ?>
<h1><?= $person->displayname ?></h1>
<p><?= $person->title ?></p>
<ul>
<li>Office: <?= $person->phone_office ?></li>
<li>Mobile: <?= $person->phone_mobile ?></li>
</ul>
<div class="tabs">
<ul class="tabs-nav">
<?php if ($user->allowed('user-manage-somestuff')): ?>
<li><a href="#tab-1">Tab 1</a></li>
<?php endif ?>
<?php if ($user->allowed('user-manage-someotherstuff')): ?>
<li><a href="#tab-2">Tab 2</a></li>
<?php endif ?>
<li><a href="#tab-3">Tab 3</a></li>
</ul>
<?php if ($user->allowed('user-manage-somestuff')): ?>
<div id="tab-1"></div>
<?php endif ?>
<?php if ($user->allowed('user-manage-someotherstuff')): ?>
<div id="tab-2"></div>
<?php endif ?>
<div id="tab-3"></div>
</div>
</code></pre>
<p>This is then wrapped in an 'html.php' layout by the view class.</p>
<p>The <code>core\config</code> class:</p>
<pre><code><?php
namespace core;
class config
{
private static
$__settings = false;
protected function __construct() {}
public static function get($key) {
if (!self::$__settings)
self::$__settings = include '../.settings.php';
$context = self::$__settings;
$pieces = explode('.', $key);
foreach ($pieces as $piece) {
if (!is_array($context) || !array_key_exists($piece, $context))
return false;
$context = &$context[$piece];
}
return $context;
}
}
</code></pre>
<p>The <code>core\user</code> class:</p>
<pre><code><?php
namespace core;
use z\db;
class user
{
public
$displayname,
$firstname,
$lastname,
$email,
$phone_office,
$phone_mobile,
$notfound = true;
protected
$_roles = [];
public function __construct($username = 'anonymous') {
$this->displayname = 'Guest';
$this->username = $username;
if ($this->username != 'anonymous')
$this->__init();
}
protected function __init() {
$db = db::instance(config::get('db'));
$stmt = $db->prepare("
SELECT * FROM users WHERE username = :username");
$stmt->execute(array(
':username' => $this->username
));
$rslt = $stmt->fetch();
if (!$rslt)
return false;
$this->firstname = $rslt['firstname'];
$this->lastname = $rslt['lastname'];
$this->displayname = $this->firstname .' '. $this->lastname;
...
}
public static function insert(array $user) {
$db = db::instance(config::get('db'));
$stmt = $db->prepare("
INSERT INTO users(field1, ...)
VALUES (:value1, ...)");
return $stmt->execute(array(
':value1' => $user['field1'],
...
));
}
...
}
</code></pre>
<p>The <code>hr\department</code> class:</p>
<pre><code><?php
namespace hr;
use core\config;
use z\db;
class department
{
public static function insert(array $department) {...}
public static function select($id = -1) {...}
public static function update(array $department) {...}
public static function delete($id) {...}
}
</code></pre>
<p>As the application is getting bigger, I would like some advice on my code. Can you see problems with the way I'm doing things?</p>
<p>Is this code "maintainable"? I wouldn't want my application to be removed if/when I leave and let my users in pain. My main concern here is if the guy who will replace me be able to understand and work with this code "easily". Note that I removed all code comments before posting but everything is documented in comments.</p>
<p>I'm also having a lot of difficulties trying to understand tests and how to write them, can someone explain to me how can I write tests for my application? and will I <em>really</em> benefit from writing/using them?</p>
<p>I spent a lot of time looking at PHP frameworks from Zend to Symphony, Kohana, CI, Laravel, Phalcon and many many others... I really liked some of the "micro-frameworks" like Slim and Lemonade but the file structure didn't make sense to me, why have such a complicated file structure and so many files/folders for such a simple thing?</p>
<p>Then I found a small PHP library <a href="https://github.com/bungle/web.php" rel="nofollow">web.php</a> and took it's route, view and form class/functions as a starting point to build my application.</p>
<p>About the view class, I can use a different layout from inside a controller like this:</p>
<pre><code>$view = new view('view.php', 'layout.php');
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T08:52:47.600",
"Id": "74909",
"Score": "0",
"body": "There have been a number of comments on your Reddit thread that reference various things will be new to you. This resource is probably your best bet as a starting point: http://www.phptherightway.com/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T09:40:52.180",
"Id": "74922",
"Score": "0",
"body": "I learned a lot from this website and can't thank enough it's author, it's clear, simple, I love it. But that was a few months ago. I think some of the practice I see are not really fit for the PHP \"side\" of a web application."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-19T16:27:09.250",
"Id": "109532",
"Score": "0",
"body": "IT doesn't really matter wether you use a framework or something else. The most important thing is to NOT write quick fixes and to have documentation. Not just inside your code, but a certain small 'Getting started' manual. That is the most important part in passing on software"
}
] |
[
{
"body": "<p>I wouldn't stress about tests if it's a smaller company, an internal application, and will not be distributed.</p>\n\n<p>Generally a framework is a good idea. It gives you everything that you're asking for.</p>\n\n<p>I'd recommend Yii for performance, but Cake because of its popularity, which makes it easily maintainable. So the next guy might already know it, and the documentation of the framework minimises your need to document. i.e. If he needs to do something he can just look on their site.</p>\n\n<p>The simplest and most effective way forward would be to move it into Cake.</p>\n\n<p>Was this application built proactively? Is it essential that you concern yourself with the future of this application?</p>\n\n<p>After looking at the code:</p>\n\n<p>There are some important structural problems in this application.</p>\n\n<p>First off you need to read up on PHP best practices. You shouldn't use short tags.</p>\n\n<p>You don't need the user and department classes. You should have a generic model class that will deal with these models, which can be extended if you need to do something special for a certain model. i.e. Object oriented with inheritance.</p>\n\n<p>I see the $_POST goes straight into your form class. Does it get cleaned in there?</p>\n\n<p>You are setting your layout in the view. What if you were doing something server side, such as browser detection, and then wanted to serve a different layout? You should set your layout where the logic is. In the controller.</p>\n\n<p>Definitely move this into a common and accessible framework. Cake or Code Igniter. I think Yii maybe a bit too steep of a learning curve.</p>\n\n<p>Also, because it is effectively business software, you will benefit from improved security within a framework.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T21:02:18.533",
"Id": "74623",
"Score": "0",
"body": "The application wasn't build proactively and my only concern about it's future is my fellow coworkers using it (loving it and thanking me for it) everyday. The application did catch a couple managers attention so maybe it's something that will evolve in the company, at that point I'm not sure.\n\n$_POST is sanitazed by the form class yes, I can also do validation but for the sake of making this post shorter didn't included them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T11:39:56.300",
"Id": "74931",
"Score": "0",
"body": "There's nothing wrong with using PHP short tags (`<?=`). They are actively recommended in the community driven coding style guide PSR-1: http://www.php-fig.org/psr/psr-1/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:27:02.870",
"Id": "74975",
"Score": "2",
"body": "That is not a recommendation. They are considered acceptable, but discouraged. What happens when you move files to a server with short tags off? Your code breaks, great! Use them, have fun ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-25T14:16:19.283",
"Id": "186427",
"Score": "1",
"body": "you lost me at \"I wouldn;t stress about tests\""
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T13:56:08.110",
"Id": "43218",
"ParentId": "43190",
"Score": "-1"
}
},
{
"body": "<p>I really like the current ideas. Following Unix and Kiss using existing solutions like <code>MultiViews</code>.</p>\n\n<p>Everything I can see looks okay to me. Except that it's not the same way as done in most frameworks there days. So the only thing I would recommend for now it so provide a readme.md pointing to the differences most developers would indent to find.</p>\n\n<p>E.g. document that Backend-Code (Controllers) are inside the <code>public</code> folder.\nDocument that there is no single entry point like one <code>index.php</code> but you are using <code>MultiViews</code> and prepending <code>app/bootstrap.php</code> to all <code>php</code> files. Such things.</p>\n\n<p>Beside that, you can follow PSR-2 (www.php-fig.org) as Coding Guideline, so this is already documented and PHP Developers familiar with PSR-2 won't struggle with code formatting.</p>\n\n<p>For your <code>config</code> class, I would reduce the logic inside the <code>get</code> method to keep it short. Read in configuration inside the <code>construct</code> and parse it within your get. Use recursion to walk deeper in the hierarchy, instead of using a reference you change in each iteration.</p>\n\n<p>I would recommend small parts instead of a framework for your work. So e.g. search on packagist.org for ready to use components. For your Models, I would recommend the ActiveRecord Design Pattern (en.wikipedia.org/wiki/Active_record_pattern), which is already partially implemented by yourself. Currently I'm using <a href=\"https://packagist.org/packages/php-activerecord/php-activerecord\" rel=\"nofollow\">ActiveRecord</a> to keep models slim and don't waste time with DB implementations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-22T16:10:00.293",
"Id": "114765",
"ParentId": "43190",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T01:16:53.010",
"Id": "43190",
"Score": "10",
"Tags": [
"php",
"object-oriented",
"mvc",
"file-structure"
],
"Title": "Intranet PHP application"
}
|
43190
|
<p>This code counts the number of nodes between any given two nodes in a circular linked list. Any feedback is appreciated:</p>
<pre><code>public class CountNodesBetweenTwoNodes {
Node first;
Node fifth;
private class Node<Item> {
Item item;
Node next;
}
public static void main(String[] args) {
CountNodesBetweenTwoNodes countNodes = new CountNodesBetweenTwoNodes();
countNodes.buildCircularList();
int noOfNodes = countNodes.countNodesBetweenTwoNodes(countNodes.getFirst(), countNodes.getFifth());
System.out.println("Number of Nodes is: "+noOfNodes);
}
private Node buildCircularList() {
first = new Node();
first.item = "First";
Node second = new Node();
second.item = "Second";
Node third = new Node();
third.item = "Third";
Node forth = new Node();
forth.item = "Forth";
fifth = new Node();
fifth.item = "Fifth";
first.next = second;
second.next = third;
third.next = forth;
forth.next = fifth;
fifth.next = first;
return first;
}
private int countNodesBetweenTwoNodes(Node firstNode, Node secondNode) {
int count = 0;
while(firstNode.next != secondNode) {
count++;
firstNode = firstNode.next;
}
return count;
}
public Node getFirst() {
return first;
}
public Node getFifth() {
return fifth;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T01:41:05.010",
"Id": "74516",
"Score": "3",
"body": "4th should be \"fourth\" ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T01:55:22.487",
"Id": "74517",
"Score": "0",
"body": "yeah! it was quick. :)"
}
] |
[
{
"body": "<p>Your program is really based only of case where you have 5 nodes. This make your code really hard to change if you want to have a \"list\" of node of a different size. </p>\n\n<ol>\n<li>The name of the class should represent a concept not an action, <code>CountNodesBetweenTwoNodes</code> could be something like <code>CircularList</code> or something like that. A name that would represent what the class is, not what it does.</li>\n<li><p>Personally, I find that re-using the first argument in the loop to iterate over the list is not what I would want. I would use a third <code>Node</code> variable to let to show that I'm iterating and that my <code>firstNode</code> will not change during this method.</p>\n\n<pre><code>private int countNodesBetweenTwoNodes(Node firstNode, Node secondNode) {\n int count = 0;\n\n while(firstNode.next != secondNode) {\n count++;\n firstNode = firstNode.next;\n }\n\n return count;\n}\n</code></pre></li>\n<li><p>I would rename the class variable <code>Node fifth</code> for <code>Node last</code>, what if you have more than five nodes ? Would you change your code ? I hope not, so by changing the name to represent that it's the last one, we are good to not limit our-self to five nodes.</p></li>\n<li><p>Since we changed the name of the variable, we should change <code>public Node getFifth()</code> too for <code>public Node getLast()</code>.</p></li>\n<li><p>You should always specify a visibility for you class variable. Currently, <code>first</code> and <code>fifth</code> are package visibility, they should be <code>private</code>.</p></li>\n<li><p>There is a bug in your class: you made your <code>countNodesBetweenTwoNodes</code> private. If I want to use your class myself, I could not use this method since I would not be in your class. You don't have this problem since you use the method in your <code>main</code> which is in the class. If you move your <code>main</code> method to another class, your program is not working anymore.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T02:01:16.260",
"Id": "43193",
"ParentId": "43191",
"Score": "10"
}
},
{
"body": "<p>Focusing directly on the countNodesBetweenTwoNodes</p>\n\n<blockquote>\n<pre><code> private int countNodesBetweenTwoNodes(Node firstNode, Node secondNode) {\n int count = 0;\n\n while(firstNode.next != secondNode) {\n count++;\n firstNode = firstNode.next;\n }\n\n return count;\n }\n</code></pre>\n</blockquote>\n\n<p>The method name is way too long... that's an AppleScript name! The arguments in a Java method count as part of the signature, so, your method is really calling it <code>countNodesBetweenTwoNodes Node Node</code>... it is quite sufficient to call it <code>countNodesBetween(Node, Node)</code>...</p>\n\n<p>Then, the parameters are Nodes, so there is no need to call them <code>firstNode</code> and <code>secondNode</code>, <code>first</code> and <code>second</code> would be fine.</p>\n\n<p>Alright, so, now we have the method:</p>\n\n<pre><code> private int countNodesBetween(Node first, Node second) {\n int count = 0;\n\n while(first.next != second) {\n count++;\n first = first.next;\n }\n\n return count;\n }\n</code></pre>\n\n<p>Now, about the real issues, what if <code>first == second</code>? Then the result should be <code>0</code>, but, in your case, it is <code>size</code> where `size is the number of members in the list.</p>\n\n<pre><code> private int countNodesBetween(Node first, Node second) {\n int count = 0;\n\n while(first != second) {\n count++;\n first = first.next;\n }\n\n return count;\n }\n</code></pre>\n\n<p>This changes the value that you are returning though.... but... what was the requirement?</p>\n\n<p>Was the requirement to get the number of steps to go from the first to the second, or the number of in-between nodes you have to visit?</p>\n\n<p>If it was the number of nodes you have to visit, then you have two places where the result is 0, when <code>first == second</code>, and also <code>first.next == second</code>...</p>\n\n<p>In a general sense, I have never encountered a reason why there has to be a full loop-count when the <code>first==second</code></p>\n\n<p>Finally, what if you are going the long way around? For example, what if someone does this?</p>\n\n<pre><code>countNodesBetween(mynode.next, mynode);\ncountNodesBetween(mynode, mynode.next);\n</code></pre>\n\n<p>Shouldn't the answer there be 1 for both situations (unless mynode.next == mynode)? </p>\n\n<p>To my mind, this method should look like:</p>\n\n<pre><code> private int countNodesBetween(final Node first, final Node second) {\n int count = 0;\n int size = 0;\n Node tmp = first;\n while(tmp != second) {\n count++;\n tmp = tmp.next;\n if (tmp == first) {\n throw new IllegalArgumentExcption(\"First and second nodes are not in the same list.\");\n }\n }\n if (count <= 1) {\n return count;\n }\n int size = count;\n while (tmp != second) {\n size++;\n tmp = tmp.next;\n }\n int back = count - size;\n return -back < count ? back : count;\n }\n</code></pre>\n\n<p>This code loops all the way around the loop, and it returns the distance between the nodes, where 'between' is defined as 'how many times do you have to move to get from the first to the second.</p>\n\n<p>It returns a negative number if the shortest distance is to go backward through the loop... or, put another way, the number of steps forward from the second node to the first.</p>\n\n<p>If that information is not relevant to you, you can stick with the simpler:</p>\n\n<pre><code> private int countNodesBetween(final Node first, final Node second) {\n int count = 0;\n int size = 0;\n Node tmp = first;\n while(tmp != second) {\n count++;\n tmp = tmp.next;\n if (tmp == first) {\n throw new IllegalArgumentExcption(\"First and second nodes are not in the same list.\");\n }\n }\n return count;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T02:19:51.830",
"Id": "43194",
"ParentId": "43191",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "43194",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T01:34:28.797",
"Id": "43191",
"Score": "7",
"Tags": [
"java",
"linked-list",
"circular-list"
],
"Title": "Counting number of nodes between two nodes"
}
|
43191
|
<p><a href="http://en.wikipedia.org/wiki/MapReduce" rel="nofollow">MapReduce</a> is a programming model and an associated implementation for processing and generating large data sets. Users specify a map function that processes a key/value pair to generate a set of intermediate key/value pairs, and a reduce function that merges all intermediate values associated with the same intermediate key.</p>
<p>The advantage of <a href="http://en.wikipedia.org/wiki/MapReduce" rel="nofollow">MapReduce</a> is that it allows for distributed processing of the map and reduction operations. Provided each mapping operation is independent of the other, all maps can be performed in parallel - though in practice it is limited by the data source and/or the number of CPUs near that data. Similarly, a set of 'reducers' can perform the reduction phase - all that is required is that all outputs of the map operation which share the same key are presented to the same reducer, at the same time. While this process can often appear inefficient compared to algorithms that are more sequential, MapReduce can be applied to significantly larger datasets than "commodity" servers can handle - a large server farm can use MapReduce to sort a petabyte of data in only a few hours. The parallelism also offers some possibility of recovering from partial failure of servers or storage during the operation: if one mapper or reducer fails, the work can be rescheduled — assuming the input data is still available.</p>
<p><strong>"Map" step:</strong> The master node takes the input, chops it up into smaller sub-problems, and distributes those to worker nodes. A worker node may do this again in turn, leading to a multi-level tree structure. The worker node processes that smaller problem, and passes the answer back to its master node.</p>
<p><strong>"Reduce" step:</strong> The master node then takes the answers to all the sub-problems and combines them in some way to get the output - the answer to the problem it was originally trying to solve.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T04:15:34.707",
"Id": "43197",
"Score": "0",
"Tags": null,
"Title": null
}
|
43197
|
MapReduce is an algorithm for processing huge datasets on certain kinds of distributable problems using a large number of nodes
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T04:15:34.707",
"Id": "43198",
"Score": "0",
"Tags": null,
"Title": null
}
|
43198
|
<p><a href="http://meta.codereview.stackexchange.com/questions/1561/the-java-8-tag-here-to-stay">Please see this discussion in Meta</a>: There is some debate about whether this tag should exist.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T04:20:22.007",
"Id": "43199",
"Score": "0",
"Tags": null,
"Title": null
}
|
43199
|
Java 8 - Release date in early 2014 - This tag is currently being discussed in Meta. Please see the tag Wiki text.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T04:20:22.007",
"Id": "43200",
"Score": "0",
"Tags": null,
"Title": null
}
|
43200
|
<p>I'm doing a lexical analyzer for my programming language and I don't know if I'm doing it right. Can anyone can help me with this or suggest a better way of doing it?</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
struct node
{
char character;
struct node *link;
}*front = NULL, *rear = NULL;
int isEmpty()
{
if(front == NULL)
return 1;
else
return 0;
}
char name[4] = "\0";
void enqueue(char character)
{
struct node *tmp;
tmp = (struct node *)malloc(sizeof(struct node));
if(tmp == NULL)
return;
tmp -> character = character;
tmp -> link = NULL;
if(front == NULL)
front = tmp;
else
rear -> link = tmp;
rear = tmp;
}
char dequeue()
{
struct node *tmp;
char character;
if(isEmpty())
return NULL;
tmp = front;
character = tmp -> character;
front = front -> link;
free(tmp);
return character;
}
char peek()
{
if(isEmpty())
return NULL;
return front -> character;
}
void display()
{
struct node *ptr;
ptr = front;
if(isEmpty())
return;
while(ptr != NULL)
{
printf("%c ", ptr -> character);
ptr = ptr -> link;
}
}
int issymbol(char c)
{
char symbols[] = {"!@#$%^&*()_-.?<>,+=-/\\"};
for(int b = 0; b < strlen(symbols); b++)
if(c == symbols[b])
return 0;
return 1;
}
int checkIdent(char ident)
{
if(issymbol(ident))
return 28;
else
return -2;
}
int automaton()
{
int i = 0;
char ident[50] = "\0";
char ch = '\0';
int next = 0;
while(1)
{
if(peek() == 'c') {
ident[i++] = dequeue();
if(peek() == 'a') {
ident[i++] = dequeue();
if(peek() == 's') {
ident[i++] = dequeue();
if(peek() == 'e') {
ident[i++] = dequeue();
if(isalpha(peek()))
return checkIdent(ch);
else if(isspace(peek()) || peek() == NULL) {
dequeue();
return 0;
}
} else
return -1;
} else
return -1;
} else
return -1;
}
else if(peek() == 'd') {
ident[i++] = dequeue();
if(peek() == 'o') {
ident[i++] = dequeue();
if(isalpha(peek())) {
for(int k = 0; k < next; k++)
name[k] = ident[k];
ch = ident[next + 1];
return checkIdent(ch);
}
if(isspace(peek()) || peek() == NULL) {
dequeue();
return 1;
}
} else
return -1;
}
else if(peek() == 'e') {
ident[i++] = dequeue();
ch = ident[0];
if(peek() == 'l') {
ident[i++] = dequeue();
if(peek() == 's') {
ident[i++] = dequeue();
if(peek() == 'e') {
ident[i++] = dequeue();
if(isspace(peek())) {
next = i;
ident[i++] = dequeue();
if(peek() == 'i') {
ident[i++] = dequeue();
if(peek() == 'f') {
ident[i++] = dequeue();
if(isalpha(peek())) {
for(int k = 0; k < next; k++)
name[k] = ident[k];
ch = ident[next + 1];
return checkIdent(ch);
}
if(isspace(peek()) || peek() == NULL) {
dequeue();
return 3;
}
}
else {
for(int k = 0; k < next; k++)
name[k] = ident[k];
ch = ident[next + 1];
return checkIdent(ch);
}
}
else if (isalpha(peek())) {
for(int k = 0; k < next; k++)
name[k] = ident[k];
ch = ident[next];
return checkIdent(ch);
}
return 2;
} else if(peek() == NULL)
return 2;
else if(isalpha(peek()))
return checkIdent(ch);
} else
return -1;
} else
return -1;
} else
return -1;
}
else
return -1;
}
}
void readSourceCode()
{
FILE *f = fopen("SAMPLE.nsf","r");
char c;
while((c = getc(f)) != EOF)
enqueue(c);
fclose(f);
}
void main()
{
clrscr();
readSourceCode();
while(isEmpty() != 1)
{
int i = automaton();
switch(i)
{
case 0: printf("CASE\n"); break;
case 1: printf("DO\n"); break;
case 2: printf("ELSE\n"); break;
case 3: printf("ELSE IF\n"); break;
case 28: printf("IDENT\n"); break;
default : printf("Invalid! %d", i);
}
//printf("%d\n", strlen(name));
/*if(i == 28 && name[0] != '\0')
{
for(int i = 0; i < strlen(name); i++)
printf("%c", name[i]);
}*/
}
getch();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T04:37:53.697",
"Id": "74528",
"Score": "1",
"body": "Isn't this just C code? I don't think it should be tagged with [c++]. Also, `main()` should be `int`, not `void`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T05:00:05.090",
"Id": "74529",
"Score": "0",
"body": "If you're planning on taking this any farther, unless you're doing it for academic pursuit/personal interest/school assignment, I would consider using something like lex to handle the lexing. Custom written lexers tend to get out of hand pretty quickly. Then again, custom ones also have a few advantages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T05:26:27.213",
"Id": "74533",
"Score": "0",
"body": "@Corbin, yes I'm doing this for my academic pursuit. But we are not allowed to use Lex or any software that generates lexical analyzers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T06:07:48.397",
"Id": "74539",
"Score": "4",
"body": "I am interested, how much of this was taught to you by your instructor? Specifically, did your instructor teach you to use `void main()`, compile C code as C++ code, etc.?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T06:20:57.620",
"Id": "74542",
"Score": "0",
"body": "Yes, my instructor in c programming taught us to use void main.. Haha"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T06:40:11.647",
"Id": "74543",
"Score": "1",
"body": "@user2745681 Could you join our [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) for a bit please? I have a few more questions to ask about your instructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T06:43:01.157",
"Id": "74544",
"Score": "0",
"body": "I have to finish this project before I join.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T06:54:50.097",
"Id": "74545",
"Score": "1",
"body": "@user2745681 I can help you out further in the chat room. Also, please do not edit in changes to your code, as it invalidates answers."
}
] |
[
{
"body": "<p>I think you're overcomplicating the problem by working a character at a time.</p>\n\n<ul>\n<li>Reading one character at a time using <code>getc()</code> is inefficient. You could fetch a bigger chunk at a time using <code>fread()</code>.</li>\n<li>Wrapping each character into a linked list node is wasteful. While each character normally takes one byte when stored in a large array or a string, your linked list node is likely to take more than eight bytes. On a 32-bit system, a <code>struct node</code> will probably use one byte for the character itself, four bytes for a pointer, and three wasted bytes in between to allow the pointer to be aligned at an address that is a multiple of four. On a 64-bit system, it would be even worse. Also, <code>malloc()</code> incurs some memory overhead for its bookkeeping (so that it remembers the size of the chunk of memory that will be liberated when <code>free()</code> is eventually called).</li>\n<li>Analyzing the text one character at a time is tedious. That's some of the deepest indentation I've seen in any code. If you keep the data as a string, you could use some string handling routines from the standard C library, such as <code>strsep()</code>.</li>\n</ul>\n\n<h3>Suggestion</h3>\n\n<p>I'll try to provide some guidance without giving away a complete solution to your <a href=\"/questions/tagged/homework\" class=\"post-tag\" title=\"show questions tagged 'homework'\" rel=\"tag\">homework</a>.</p>\n\n<p>The key insight is that it is possible to construct an automaton that works at a higher level than character-by-character.</p>\n\n<p>I'll start with <code>main()</code>.</p>\n\n<pre><code>/* Advice: The C standard says that main() must return an int, not void. */\nint main(int argc, char *argv[]) {\n /* Advice: Don't hard-code input filename. Accept a command-line parameter instead */\n if (argc < 2) {\n fprintf(stderr, \"Usage: %s FILENAME\\n\", argv[0]);\n return 1;\n }\n const char *filename = argv[1];\n\n /* Advice: Avoid global variables. Return a pointer instead. */\n char *program = readSourceCode(filename);\n if (!program) {\n perror(filename);\n return 1;\n }\n\n const char *cursor = program;\n while (*cursor) {\n /* Advice: What does your automaton do? Pick an informative name. */\n switch (consumeKeyword(&cursor)) {\n /* Advice: Avoid magic numbers. #define constants or use an enum. */\n case CASE: printf(\"CASE\\n\"); break;\n case DO: printf(\"DO\\n\"); break;\n case ELSE: printf(\"ELSE\\n\"); break;\n case ELSEIF: printf(\"ELSE IF\\n\"); break;\n default:\n if (isIdentifier(&cursor)) {\n printf(\"IDENT\\n\"); break;\n } else {\n printf(\"Invalid! %s\", cursor);\n }\n free(program);\n return 1;\n }\n }\n\n free(program);\n return 0;\n}\n</code></pre>\n\n<p>The first thing to get out of the way is <code>readSourceCode()</code>. See if you can implement this:</p>\n\n<pre><code>/**\n * Returns the contents of the specified file as a NUL-terminated string.\n * If any error occurs (e.g. file not found, permission denied, no free memory),\n * returns NULL, and errno will tell the reason.\n */\nchar *readSourceCode(const char *filename) {\n /* Hints: Use stat() or fstat() to find the file size.\n Allocate that many bytes, plus 1 for the '\\0'.\n Remember to fclose() when done!\n */\n …\n}\n</code></pre>\n\n<p>The main challenge is <code>consumeKeyword()</code>. As you can see, <code>main()</code> passes a \"cursor\" to <code>consumeKeyword()</code> — it does so by reference, so that <code>consumeKeyword()</code> can increment main's cursor.</p>\n\n<pre><code>enum keyword {\n NOT_A_KEYWORD,\n …\n};\n\n/**\n * Skips over any whitespace characters at the cursor, then looks for any\n * recognizable keywords. If a keyword is found, advances the cursor to\n * just beyond the end of the keyword. If no keyword is found, returns\n * NOT_A_KEYWORD and leaves the cursor in place.\n */\nenum keyword consumeKeyword(const char **cursor) {\n while (isspace(**cursor)) {\n (*cursor)++;\n }\n size_t advance;\n if ((advance = isKeyword(cursor, \"case\"))) {\n *cursor += advance;\n return CASE;\n } else if … {\n …\n } else {\n return NOT_A_KEYWORD;\n }\n}\n</code></pre>\n\n<p>You should be able to fill in the rest:</p>\n\n<pre><code>/**\n * If the specified keyword is found at the specified cursor position,\n * returns the length of the keyword. Otherwise, returns 0.\n */\nsize_t isKeyword(const char *const *cursor, const char *keyword) {\n /* Hint: With a for-loop, the entire function should take no more\n than four lines. */\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T05:18:51.677",
"Id": "74532",
"Score": "0",
"body": "Thanks for your answer! Do you have any idea how can I improve my function automaton() ??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T07:24:43.490",
"Id": "74547",
"Score": "0",
"body": "Your `main()` is not too far off, but I suggest rewriting everything else based on the outline I've added above."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T04:56:58.560",
"Id": "43203",
"ParentId": "43202",
"Score": "10"
}
},
{
"body": "<h1>Things you could improve:</h1>\n\n<h3>Compilation:</h3>\n\n<ul>\n<li><p>I am led to believe that you are compiling your code as C++ code.</p>\n\n<blockquote>\n<pre><code>tmp = (struct node *)malloc(sizeof(struct node));\n</code></pre>\n</blockquote>\n\n<p>That line right there would be unacceptable when compiling as C code. And considering that your question originally had <a href=\"/questions/tagged/c%2b%2b\" class=\"post-tag\" title=\"show questions tagged 'c++'\" rel=\"tag\">c++</a> on it, I am further convinced that you are compiling your C code as C++ code. <strong>Don't do that</strong>.</p>\n\n<p><a href=\"http://david.tribble.com/text/cdiffs.htm\" rel=\"nofollow noreferrer\">Here is a <em>very</em> long list</a> of the incompatibilities between ISO C and ISO C++. Those are the reasons you compile C code, as C code.</p>\n\n<p>If I happen to be wrong in my assumption that you are compiling C code as C++ code, you still should <a href=\"https://stackoverflow.com/q/605845/1937270\">not be casting the results of <code>malloc()</code></a>.</p></li>\n</ul>\n\n<h3>Variables/Initialization:</h3>\n\n<ul>\n<li><p>You shouldn't use global variables.</p>\n\n<blockquote>\n<pre><code>*front = NULL, *rear = NULL;\n</code></pre>\n</blockquote>\n\n<p>The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.</p>\n\n<p>To understand how the application works, you pretty much have to take into account every function which modifies the global state. That can be done, but as the application grows it will get harder to the point of being virtually impossible (or at least a complete waste of time).</p>\n\n<p>If you don't rely on global variables, you can pass state around between different functions as needed. That way you stand a much better chance of understanding what each function does, as you don't need to take the global state into account.</p>\n\n<p>So instead of using global variables, initialize the variables in <code>main()</code>, and pass them as arguments to functions if necessary.</p></li>\n<li><p>You aren't initializing your arrays properly.</p>\n\n<blockquote>\n<pre><code>char name[4] = \"\\0\";\n</code></pre>\n</blockquote>\n\n<p>You should be initializing all of your characters in the array at once.</p>\n\n<pre><code>char name[4] = {0};\n</code></pre></li>\n</ul>\n\n<h3>Efficiency:</h3>\n\n<ul>\n<li><p>You can use the <code>inline</code> keyword on some of your functions. The point of making a function <code>inline</code> is to hint to the compiler that it is worth making some form of extra effort to call the function faster than it would otherwise - generally by substituting the code of the function into its caller. As well as eliminating the need for a call and return sequence, it might allow the compiler to perform certain optimizations between the bodies of both functions.</p>\n\n<pre><code>inline int isEmpty(Node front)\n</code></pre></li>\n</ul>\n\n<h3>Returns:</h3>\n\n<ul>\n<li><p>You aren't returning a value from <code>main()</code>.</p>\n\n<blockquote>\n<pre><code>void main()\n</code></pre>\n</blockquote>\n\n<p>You should <strong>always</strong> <code>return</code> a value from <code>main()</code>. This is an indication of the status of your program, and whether or not it exited successfully. This is very important information when it comes to debugging.</p>\n\n<pre><code>int main(void)\n{\n ...\n return 0; // standard return code for successive exit\n}\n</code></pre></li>\n<li><p><code>NULL</code> isn't a <code>char</code>, so you shouldn't treat it as one when you <code>return</code> it.</p>\n\n<blockquote>\n<pre><code>char peek()\n{\n if(isEmpty())\n return NULL;\n return front -> character;\n}\n</code></pre>\n</blockquote>\n\n<p><code>return</code> the <code>NUL</code>-terminator character instead.</p>\n\n<pre><code>return '\\0';\n</code></pre></li>\n</ul>\n\n<h3>Syntax</h3>\n\n<ul>\n<li><p><code>typedef</code> your <code>struct</code>s, and declare and initialize them elsewhere.</p>\n\n<blockquote>\n<pre><code>struct node\n{\n char character;\n struct node *link;\n}*front = NULL, *rear = NULL;\n</code></pre>\n</blockquote>\n\n<p>The <code>typedef</code> means you no longer have to write <code>struct</code> all over the place. That not only saves some space, it also can make the code cleaner since it provides a bit more abstraction.</p>\n\n<pre><code>typedef struct\n{\n char character;\n struct node *link;\n} Node;\n</code></pre></li>\n<li><p>You can simplify your <code>NULL</code> checks.</p>\n\n<blockquote>\n<pre><code> if(front == NULL)\n</code></pre>\n</blockquote>\n\n<p>Since <code>NULL</code> is defined as <code>(void *)0</code>, we can treat is as a comparison to <code>0</code>.</p>\n\n<pre><code>if (!front)\n</code></pre></li>\n<li><p>Use ternary operators when you have simple <code>if-else</code> statements.</p>\n\n<blockquote>\n<pre><code> if(front == NULL)\n return 1;\n else\n return 0;\n}\n</code></pre>\n</blockquote>\n\n<p>The <a href=\"https://en.wikipedia.org/wiki/?:\" rel=\"nofollow noreferrer\">ternary conditional expression</a> is just as simple and verbose as your code, and a whole lot shorter.</p>\n\n<pre><code>return (!front) ? 1 : 0;\n</code></pre>\n\n<p>But since we are returning whether this function is true or not, we don't even have a need for the conditional expression at all.</p>\n\n<pre><code>return !front;\n</code></pre></li>\n<li><p>You don't accept any parameters for some of your functions, such as <code>main()</code>. If you do not take in any parameters, declare them as <code>void</code>.</p>\n\n<pre><code>int main(void)\n</code></pre></li>\n<li><p>You have a comparison between an <code>int</code> and a <code>void *</code>.</p>\n\n<blockquote>\n<pre><code>peek() == NULL\n</code></pre>\n</blockquote>\n\n<p>Compare to <code>0</code> instead.</p>\n\n<pre><code>0 == peek()\n</code></pre></li>\n</ul>\n\n<h3>Indentation</h3>\n\n<ul>\n<li><p>You are very inconsistent with your indenting.</p>\n\n<blockquote>\n<pre><code>if(front == NULL)\nfront = tmp;\nelse\nrear -> link = tmp;\nrear = tmp;\n</code></pre>\n</blockquote>\n\n<p>This isn't very readable. For one, you don't include braces, which is a whole 'nother debate within itself, but then you don't use indentation. Please do everyone that is trying to read your code a favor, and indent your code properly.</p></li>\n</ul>\n\n<h3>Comments:</h3>\n\n<ul>\n<li><p>Comments are very important to have in your source code. Your program has a lack of comments that explain why your code does what it does. You should add some so you other people can follow your code more easily.</p></li>\n<li><p>For the comments you do have...</p>\n\n<blockquote>\n<pre><code>//printf(\"%d\\n\", strlen(name));\n\n/*if(i == 28 && name[0] != '\\0')\n {\n for(int i = 0; i < strlen(name); i++)\n printf(\"%c\", name[i]);\n }*/\n</code></pre>\n</blockquote>\n\n<p>Remove them. Commented out code is really just useless clutter.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T05:13:03.293",
"Id": "74530",
"Score": "0",
"body": "Thanks for your answer! Do you have any idea how can I improve my function automaton() ??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T05:27:02.867",
"Id": "74534",
"Score": "0",
"body": "@user2745681 I'm still working on reviewing the code. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T05:33:01.127",
"Id": "74535",
"Score": "1",
"body": "@syb0rg If you really wanted to simplify the `if/else` redundancy, you could just do `return !front` instead of the ternary conditional :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T09:23:18.070",
"Id": "74554",
"Score": "1",
"body": "Does casting the result of `malloc()` really make it an invalid C program? The answers in the Stack Overflow question that you linked to don't even agree unanimously that casting is a bad idea. (Anyway, there are plenty of issues with the code that are more urgent than the `malloc()` cast.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T09:28:14.770",
"Id": "74555",
"Score": "1",
"body": "@200_success: It remains valid C code (i.e., barring other problems, a C compiler should accept the code). It's generally agreed that it's a bad idea in C though."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T05:02:07.200",
"Id": "43206",
"ParentId": "43202",
"Score": "15"
}
},
{
"body": "<h1>Approach</h1>\n\n<p>I would use arrays rather than an unnecessary linked list structure. In particular, have an array of the contents with an index into it (or pointer) and an array of your current token. This way you avoid the expensive overhead of allocating and deallocating all of the time, and you get cache locality. From a theoretical point of view, operating on characters is fine, but from a practical point of view, it's incredibly inefficient.</p>\n\n<hr>\n\n<p>Rather than doing character by character scanning, I would try to use more general rules and then back track to check for correctness. For example, you can keep scanning forward as long as you have an alphabetic character. Then, you can check the token to make sure it's an acceptable token. A very crude example of this:</p>\n\n<pre><code>char* contents = ...;\nchar* content_ptr = ...;\n\nchar* token = ...;\nchar* token_ptr = token;\n\nmemset(token, 0, token_size);\n\nwhile (isalpha(*content_ptr)) {\n *token++ = *content_ptr++;\n}\n\nif (is_valid_token(token)) {\n // do something with the token\n} else {\n // Parse error!\n}\n</code></pre>\n\n<p>So, if you had \"while cake\" your code would parse through the token \"while\", see that it's valid, store it somehow, and then continue on (the code to skip over non-tokens is not included in my example, but you could likely get away with just eating white space). When getting to \"cake\", you could go ahead and capture the entire thing, and only when you've captured the entire token see that it's a non-sense token and spit out an error. This way simplifies your processing since it allows you to think at a token level rather than an atom level.</p>\n\n<hr>\n\n<p>Really, if you're planning on continuing this much farther, I would consider using something like lex. You can just give it a set of rules, and it will build an automaton for you. DFAs are quite cumbersome to build by hand and if you decide to change rules, they get even more difficult to work with. By working at a rule level, you get to avoid that clutter. You can even pair lex with something like bison to create a full parser rather than just a lexer.</p>\n\n<hr>\n\n<h1>Technicalities</h1>\n\n<p>There are a few things wrong with your code from a technical point of view. A good place to start is compiling with a modern compiler with the warnings turned on and thinking long and hard if the warnings are worth ignoring (hint: they almost never are).</p>\n\n<p>A lot of things have been covered by others, so I will only post what I believe no one else has mentioned yet.</p>\n\n<hr>\n\n<pre><code>char peek()\n{\n if(isEmpty())\n return NULL;\n return front -> character;\n}\n</code></pre>\n\n<p><code>NULL</code> is not a valid value for a <code>char</code>. Yes, it's technically allowed, but it's a very bad idea. NULL is a possible value for a pointer, not a character. It would be like <code>int x = 'a';</code>. Yes, it's technically possible, but it's nonsensical. If you want NULL-like sentinel for a character, you can use a null character (<code>0</code>, or <code>'\\0'</code>).</p>\n\n<hr>\n\n<p>When possible, avoid non-standard parts of C. In particular, <code>conio.h</code> is going to tie you to very specific environments (in particular, Windows with either Turbo C compiler or Microsoft's Visual Studio's C compiler). <code>clrscr</code> is probably not worth tying yourself to windows over. In fact, I would consider this program clearing my terminal to be annoying. Let the terminal handle its own rendering.</p>\n\n<hr>\n\n<p>What if reading the file fails? readSourceCode() gives no indication of success or failure. Also, if the fopen call fails, the read on the is likely going to cause a segfault. You need to check error conditions more carefully.</p>\n\n<hr>\n\n<p>Globals have very, very few legitimate uses. Get out of the habit of using them as quickly as you can.</p>\n\n<hr>\n\n<p>Anytime you hard code a string like a file name, ask yourself if it should be a parameter instead. Instead of <code>readSourceCode</code> having the file path hard coded, it should be parameter.</p>\n\n<hr>\n\n<p>Actually, the filepath shouldn't be a parameter. A function should never create a resource it uses based on it's inputs. Rather than a filepath, you would want to pass readSourceCode a <code>FILE*</code>. That way it has one less responsibility in that it no longer has to handle opening/closing the file. It only has to handle reading it (look up single responsibility principle).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T05:35:08.563",
"Id": "74536",
"Score": "0",
"body": "Thanks for your answer @Corbin! But our professor told that we have to use a Finite Automaton for it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T05:35:37.677",
"Id": "74537",
"Score": "0",
"body": "@user2745681 Ah, ok :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T05:16:16.667",
"Id": "43207",
"ParentId": "43202",
"Score": "6"
}
},
{
"body": "<p>Right now, I think your <code>automaton</code> has an awful lot of code to just recognize 4 key words. A typical lexer will read an entire (potential) token, then compare it to a table of key words to see if it matches any of them.</p>\n\n<p>For example, let's assume a token must always consist of a letter followed by an arbitrary number of letters and/or digits. That's pretty easy to encode:</p>\n\n<pre><code>void read_ident(char *id, size_t max) { \n unsigned pos = 0;\n if (isalpha(peek())) \n while (isalnum(ch=getnext())&&pos < MAX)\n id[pos++] = ch;\n id[pos] = '\\0';\n}\n</code></pre>\n\n<p>Using this (or something similar) code to read some key words would end up quite a bit simpler:</p>\n\n<pre><code>static char const *table[] = {\n \"case\",\n \"do\",\n \"else\",\n \"if\"\n};\n\n#define elements(table) (sizeof(table)/sizeof(table[0]))\nchar buffer[256];\n\nread_ident(buffer, sizeof(buffer));\nfor (i=0; i<elements(table); i++)\n if (0 == strcmp(buffer, table[i])\n return i;\n// none of them matched\nreturn 28;\n</code></pre>\n\n<p>Note that (at least for the moment) I've had it recognize \"if\", rather than \"else if\", as a keyword. I'd recognize <code>else if</code> as two key words: an <code>else</code> followed by an <code>if</code>, rather than as a single key word (that happens to include a space). That's not the only way to do things, but it's generally simpler.</p>\n\n<p>For the moment, I've had it do a simple linear search through the table to find a (possible) keyword. Given the small number of key words you've given, that makes sense. If you had to deal with more key words, you might want to switch to a sorted table so you could use a binary search, or else to a hash table. If the 28 you used as a magic number elsewhere indicates you actually have 27 key words to recognize, a sorted table might improve speed a little, but a hash table is <em>probably</em> overkill.</p>\n\n<p>That brings us to one other point: returning \"magic\" numbers for the key words (0, 1, 2, 3, 28). You normally want to use an <code>enum</code> (or series of <code>#define</code>s) to give logical names to these instead of using the raw numbers directly:</p>\n\n<pre><code> enum { INVALID = -1, T_DO, T_CASE, T_IF, T_ELSE, T_ID};\n</code></pre>\n\n<p>Then the code that uses it can look a little more meaningful, like:</p>\n\n<pre><code>switch (token) { \n T_DO: printf(\"do\\n\"); break;\n T_CASE: printf(\"case\\n\"); break;\n T_IF: printf(\"if\\n\"); break;\n T_ELSE: printf(\"else\\n\"); break;\n T_ID: printf(\"ID\\n\"); break;\n T_INVALID:\n default: printf(\"Invalid\\n\"); break;\n}\n</code></pre>\n\n<p>Another possibility to consider (since you can make these contiguous and starting from 0) is to use them as an index into an array instead:</p>\n\n<pre><code>if (token >= 0 && token <= T_LAST)\n printf(\"%s\\n\", table[token]);\n</code></pre>\n\n<p>Note that for this, you can (and usually want to) re-use the same table you used to find keywords when tokenizing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T07:49:26.757",
"Id": "43209",
"ParentId": "43202",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "43206",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T04:35:23.433",
"Id": "43202",
"Score": "9",
"Tags": [
"c",
"homework"
],
"Title": "Lexical analyzer for a programming language"
}
|
43202
|
<p><a href="https://github.com/exebook/dnaof" rel="nofollow">https://github.com/exebook/dnaof</a></p>
<p>I created this simple inheritance tool for JavaScript, could any one with deep knowledge in JavaScript prototyped inheritance review it?</p>
<p>Here is the library itself:</p>
<pre><code>kindof = function(K) {
function X() {}
if (K != undefined) X.prototype = new K
X.can = X.prototype
return X
}
dnaof = function(x, f) {
var p = x.__proto__
x.__proto__ = p.__proto__
var r = p.__proto__[f].apply(x)
x.__proto__ = p
return r
}
</code></pre>
<p>And here is the example usage to demonstrate what it can do:</p>
<pre><code>require('./dnaof')
// create a kind of idiot without ancestor:
var idiot = kindof()
// tell what it can do:
idiot.can.say = function() { return this.name + ' can chat' }
idiot.can.rest = function() { console.log('bzzzz.z.z.z... (' + this.name + ')') }
// a new kind of smart inherits from a kind of idiot
var smart = kindof(idiot)
// he can also say something:
smart.can.say = function() {
// he can say something new, and he can say the same thing as an idiot can:
return dnaof(this, 'say') + ', ' + this.name + ' can talk'
}
// a kind of a genious can do the same things as an idiot and smart can, and even more:
var genious = kindof(smart)
genious.can.say = function() {
return dnaof(this, 'say') + ', ' + this.name + ' can discuss'
}
// instantiate three persons:
var bob = new idiot
var alice = new smart
var candy = new genious
// assign properties, because to make life simpler we do not initialize anything during creation:
bob.name = 'bob'
alice.name = 'alice'
candy.name = 'candy'
// let them talk:
console.log(bob.say())
console.log(alice.say())
console.log(candy.say())
// let them take some rest:
alice.rest(), bob.rest(), candy.rest()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T07:27:07.420",
"Id": "74548",
"Score": "1",
"body": "Just a tip, `__proto__` is non-standard. See here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T07:44:04.867",
"Id": "74549",
"Score": "0",
"body": "I know, but is there a better way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T06:09:14.967",
"Id": "75869",
"Score": "0",
"body": "Unfortunately, I would probably rewrite the whole library for something else, however here's a few hints. Rather than using `new` to setup the prototype chain, you can use `Object.create` in every modern browsers. Also, to dynamically get the *parent class*, you can do `Object.getPrototypeOf(Object.getPrototypeOf(this))`. With these changes you can stop using `__proto__`. Also, you should opt for a syntax that doesn't require you to write `obj.can` all the time to define new members."
}
] |
[
{
"body": "<p>From a once over, and borrowing from the comments:</p>\n\n<ul>\n<li><code>__proto__</code> is bad news, MDN mentions this in a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto\" rel=\"nofollow\">big red box of doom</a>.</li>\n<li>There is no means to pass parameters to the constructor, that does not make it simple</li>\n<li><code>X</code>, <code>x</code>, <code>k</code>, <code>r</code> and <code>p</code> are terrible variable names</li>\n<li><code>dnaof</code> is an unfortunate name</li>\n<li>lowerCamelCase is good for you, <code>kindof</code> -> <code>kindOf</code>, </li>\n<li>You can get the parent class thru <code>Object.getPrototypeOf(Object.getPrototypeOf(this))</code> in <code>dnaof</code></li>\n<li>I have mixed feelings about the <code>can</code> trick. It is shorter than typing <code>prototype</code>, but it's also a candidate for nameclashes.</li>\n<li>You have no comments at all in your code, combined with 1 letter variables that makes for not good code</li>\n<li>If I were to build an OO library, I would also play with <code>constructor</code> and add some support for private.</li>\n</ul>\n\n<p>All in all, this is something I would not mind using, but that I would hate to have to maintain.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-22T09:55:25.647",
"Id": "78490",
"Score": "0",
"body": "Thanks for comments. Actually I switched completely from using \"prototype\", now 'dnaof' will store each function super-call in it self."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T14:59:55.187",
"Id": "44979",
"ParentId": "43208",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T06:15:27.460",
"Id": "43208",
"Score": "3",
"Tags": [
"javascript",
"inheritance"
],
"Title": "dnaof() - inheritance made easy, my own make inheritance tool"
}
|
43208
|
<p>I did an implementation of the Tonelli-Shanks algorithm as defined on Wikipedia. I put it here for review and sharing purpose.</p>
<p><a href="http://en.wikipedia.org/wiki/Legendre_symbol" rel="nofollow">Legendre Symbol implementation</a>:</p>
<pre><code>def legendre_symbol(a, p):
"""
Legendre symbol
Define if a is a quadratic residue modulo odd prime
http://en.wikipedia.org/wiki/Legendre_symbol
"""
ls = pow(a, (p - 1)/2, p)
if ls == p - 1:
return -1
return ls
</code></pre>
<p><a href="http://en.wikipedia.org/wiki/Tonelli-Shanks_algorithm" rel="nofollow">Prime modular square root</a> (I just renamed the solution variable R to x and n to a):</p>
<pre><code>def prime_mod_sqrt(a, p):
"""
Square root modulo prime number
Solve the equation
x^2 = a mod p
and return list of x solution
http://en.wikipedia.org/wiki/Tonelli-Shanks_algorithm
"""
a %= p
# Simple case
if a == 0:
return [0]
if p == 2:
return [a]
# Check solution existence on odd prime
if legendre_symbol(a, p) != 1:
return []
# Simple case
if p % 4 == 3:
x = pow(a, (p + 1)/4, p)
return [x, p-x]
# Factor p-1 on the form q * 2^s (with Q odd)
q, s = p - 1, 0
while q % 2 == 0:
s += 1
q //= 2
# Select a z which is a quadratic non resudue modulo p
z = 1
while legendre_symbol(z, p) != -1:
z += 1
c = pow(z, q, p)
# Search for a solution
x = pow(a, (q + 1)/2, p)
t = pow(a, q, p)
m = s
while t != 1:
# Find the lowest i such that t^(2^i) = 1
i, e = 0, 2
for i in xrange(1, m):
if pow(t, e, p) == 1:
break
e *= 2
# Update next value to iterate
b = pow(c, 2**(m - i - 1), p)
x = (x * b) % p
t = (t * b * b) % p
c = (b * b) % p
m = i
return [x, p-x]
</code></pre>
<p>If you have any optimization or have found any error, please report it.</p>
|
[] |
[
{
"body": "<p>Good job! I don't have a lot to comment on in this code. You have written straightforward clear code whose only complexity stems directly from the complexity of the operation it is performing. It would be good to include some of your external commentary (such as the renames of <code>R</code> and <code>n</code>) in the code itself to make it easier for someone to follow the documentation on wikipedia. You may want to include some of that documentation as well.</p>\n\n<p>For reference, the rest of this review assumes that the code functions correctly; I don't have my math head on tonight.</p>\n\n<p>There appears to be one case of redundant code, unless <code>m</code> can ever be <code>1</code>, resulting in an empty range and thus no reassignment of <code>i</code>. Otherwise you can skip the assignment to <code>i</code> in the following:</p>\n\n<pre><code>i, e = 0, 2\nfor i in xrange(1, m):\n ...\n</code></pre>\n\n<p>There are a number of small <a href=\"http://en.wikipedia.org/wiki/Strength_reduction\">strength-reduction</a> optimizations you might consider, but in Python their impact is likely to be minimized - definitely profile before heading too deeply down the optimization path. For example in the following while loop:</p>\n\n<pre><code># Factor p-1 on the form q * 2^s (with Q odd)\nq, s = p - 1, 0\nwhile q % 2 == 0:\n s += 1\n q //= 2\n</code></pre>\n\n<p>Both operations on <code>q</code> can be reduced. The modulus can be rewritten as a binary and <code>q & 1</code>, and the division as a binary shift <code>q >>= 1</code>. Alternately, you can use <a href=\"http://docs.python.org/2/library/functions.html#divmod\">divmod</a> to perform both operations at once.</p>\n\n<p>Similarly, <code>2**(m - i - 1)</code> is identical to <code>1 << (m - i - 1)</code> for non-negative exponents.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T15:25:48.077",
"Id": "74750",
"Score": "0",
"body": "Thanks for the review, this is a really nice feedback. I will remove i assignment (I always though i was only defined inside the for loop). I will also change the `2**(m - i - 1)`. I prefer let other micro-optimization unchanged in order to have better code readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T15:28:57.570",
"Id": "74751",
"Score": "0",
"body": "Btw, i did not see how you would use divmod in the code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T03:18:47.090",
"Id": "74874",
"Score": "0",
"body": "It would look something like `while True: next_q, q_odd = divmod(q, 2); if q_odd: break; s += 1; q = next_q`. The tricky question is whether avoiding the separate divisions would pay for the extra operations in Python, not to mention the tradeoffs in terms of clarity."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T01:17:50.930",
"Id": "43267",
"ParentId": "43210",
"Score": "8"
}
},
{
"body": "<p>To enhance portability to python 3 use <code>//</code> instead of <code>/</code> everywhere in your code. You already do this in lines like <code>q //= 2</code>, but not in lines like <code>x = pow(a, (p + 1)/4, p)</code>. In fact, consider including <code>from __future__ import division</code>.</p>\n\n<p>Also, it seems that in a few benchmarks I did computing <code>2**x</code> was significantly slower than computing the equivalent <code>1<<x</code>. So that is another minor optimization that can be made.</p>\n\n<p>Finally, again for portability to python 3, you can replace the one use of <code>xrange</code> with <code>range</code>. I do not think there will be any significant performance loss in python 2 in this particular case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-25T22:10:52.683",
"Id": "349508",
"Score": "0",
"body": "I confirm that the above code does not run on Python 3."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-20T15:54:20.907",
"Id": "141934",
"ParentId": "43210",
"Score": "3"
}
},
{
"body": "<p>I know, this is a bit late but I have some more minor optmimization suggestions:</p>\n\n<ul>\n<li>in your <code>legendre_symbol</code> implementation, you compute <code>pow(a, (p - 1)/2, p)</code>. You don't need to subtract <code>1</code> from <code>p</code>, since <code>p</code> is odd. Also, you can replace <code>p/2</code> with <code>p >> 1</code>, which is faster.</li>\n<li>in your simple case handling, you can replace <code>p % 4</code> with <code>p & 3</code> and again, <code>pow(a, (p + 1)/4, p)</code> with <code>pow(a, (p + 1) >> 2, p)</code>. Since you have checked that <code>p & 3 == 3</code>, an equivalent solution would be <code>pow(a, (p >> 2) + 1, p)</code>, I would go for this one instead. It can make a difference when the right shift effectively reduces the byte size of <code>p</code>.</li>\n<li>there is another simple case you can check for: <code>p % 8 == 5</code> or the equivalent <code>p & 7 == 5</code>. In that case, you can compute <code>pow(a, (p >> 3) + 1, p)</code>, check if it is a solution (it is a solution if and only if <code>a</code> is quartic residue modulo <code>p</code>), otherwise multiply that with <code>pow(2, p >> 2, p)</code> to get a valid solution (and don't forget to calculate <code>% p</code> after the multiplication of course)</li>\n<li><p>in your <code>while</code>-loop, you need to find a fitting <code>i</code>. Let's see what your implementation is doing there if <code>i</code> is, for example, <code>4</code>:</p>\n\n<pre><code>pow(t, 2, p)\npow(t, 4, p) # calculates pow(t, 2, p)\npow(t, 8, p) # calculates pow(t, 4, p), which calculates pow(t, 2, p)\npow(t, 16, p) # calculates pow(t, 8, p), which calculates pow(t, 4, p), which calculates pow(t, 2, p)\n</code></pre>\n\n<p>do you see the redundancy? with increasing <code>i</code>, the number of multiplications grows quadratically, while it could just grow linear:</p>\n\n<pre><code>i, t2i, = 0, t\nfor i in range(1, m):\n t2i = t2i * t2i % p\n if t2i == 1:\n break\n</code></pre></li>\n<li><p>the last optimization is a rather simple one: I would just replace</p>\n\n<pre><code>t = (t * b * b) % p\nc = (b * b) % p\n</code></pre>\n\n<p>with</p>\n\n<pre><code>c = (b * b) % p\nt = (t * c) % p\n</code></pre>\n\n<p>which saves one multiplication</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-27T06:35:44.267",
"Id": "204442",
"ParentId": "43210",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "43267",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T07:53:48.977",
"Id": "43210",
"Score": "14",
"Tags": [
"python",
"algorithm",
"primes",
"mathematics"
],
"Title": "Tonelli-Shanks algorithm implementation of prime modular square root"
}
|
43210
|
<p>I've been a PHP procedural programmer for several years but I'm trying to learn OOP and I'm getting a bit confused with some patterns and principles. I would appreciate it if you could give me some tips and advice.</p>
<pre><code>interface LoginAuthenticator
{
public function authenticate(UserMapper $userMapper);
}
class UserAuthenticator implements LoginAuthenticator
{
private $user;
private $session;
public function __construct(User $user, Session $session)
{
$this->user = $user;
$this->session = $session;
}
public function authenticate(UserMapper $userMapper)
{
if (!$user = $userMapper->findByUsernameAndPassword($this->user->getUsername(), $this->user->getPassword()))
{
throw new InvalidCredentialsException('Invalid username or password!');
}
$this->logUserIn($user);
}
private function logUserIn(User $user)
{
$this->session->setValue('user', $user);
}
public function logUserOut()
{
$this->session->unsetValue('user');
$this->session->destroy();
}
}
try
{
$user = new User();
$user->setUsername($_POST['username']);
$user->setPassword($_POST['password'], new MD5());
$pdo = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$userAuth = new UserAuthenticator($user, new Session());
$userAuth->authenticate(new PdoUserMapper($pdo));
header('Location: index.php');
}
catch (InvalidArgumentException $e)
{
echo $e->getMessage();
}
catch (PDOException $e)
{
echo $e->getMessage();
}
catch (InvalidCredentialsException $e)
{
echo $e->getMessage();
}
</code></pre>
<p>Well, here is my first concern, the SRP: I don't really know if I should inject a Mapper into my <code>UserAuthenticator::authenticate</code> method or if I should create a <code>UserFinder</code> class and inject it instead. I don't know if it's a Mapper responsibility to find. What do you think ?</p>
<p>Furthermore, I'm also confused about the <code>$user</code> property: my <code>findByUsernameAndPassword</code> method returns a <code>User</code> object, so I have two <code>User</code>s instances in the same class: one injected and another returned by the Mapper. Should I inject just <code>$username</code> and <code>$password</code> instead of a <code>User</code> object in order to authenticate ?</p>
<p>I have also some wrappers classes like Session and MD5 but they are not needed to understand how my classes works.</p>
<p><strong>Edit</strong></p>
<p>My classes after changes and user related classes:</p>
<pre><code>interface Authenticator
{
public function authenticate(UserCredentials $userCredentials);
}
class LoginAuthenticator implements Authenticator
{
private $userMapper;
public function __construct(UserMapper $userMapper)
{
$this->userMapper = $userMapper;
}
public function authenticate(UserCredentials $userCredentials)
{
if (!$user = $this->userMapper->findByUsernameAndPassword($userCredentials->getUsername(), $userCredentials->getPassword()))
{
throw new InvalidCredentialsException('Invalid username or password!');
}
return $user;
}
}
class UserCredentials
{
private $username;
private $password;
public function getUsername()
{
return $this->username;
}
public function setUsername($username)
{
if (!is_string($username) || strlen($username) < 3)
{
throw new InvalidArgumentException('Invalid username.');
}
$this->username = $username;
}
public function getPassword()
{
return $this->password;
}
public function setPassword($password, Encryptor $encryptor)
{
if (!is_string($password) || strlen($password) < 8)
{
throw new InvalidArgumentException('Invalid password.');
}
$this->password = $encryptor->encrypt($password);
}
}
class User
{
private $id;
private $firstName;
private $lastName;
private $email;
private $username;
private $password;
public function getPassword()
{
return $this->password;
}
public function setPassword($password, Encryptor $encryptor)
{
$this->password = $encryptor->encrypt($password);
}
//more getters and setters
}
interface UserMapper
{
public function insert(User $user);
public function update(User $user);
public function delete($id);
public function findByUsernameAndPassword($username, $password);
public function findAll();
}
class PdoUserMapper implements UserMapper
{
private $pdo;
private $table = 'users';
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function insert(User $user)
{
$statement = $this->pdo->prepare("INSERT INTO {$this->table} VALUES(null, ?, ?, ?, ?)");
$userValues = array(
$user->getFirstName(),
$user->getLastName(),
$user->getEmail(),
$user->getUsername(),
$user->getPassword()
);
$statement->execute($userValues);
return $this->pdo->lastInsertId();
}
public function update(User $user)
{
$statement = $this->pdo->prepare("UPDATE {$this->table} SET name = ?, last_name = ?, email = ?, password = ? WHERE id = ?");
$userValues = array(
$user->getFirstName(),
$user->getLastName(),
$user->getEmail(),
$user->getPassword(),
$user->getId()
);
$statement->execute($userValues);
}
public function delete($id)
{
$statement = $this->pdo->prepare("DELETE FROM {$this->table} WHERE id = ?");
$statement->bindValue(1, $id);
$statement->execute();
}
public function findById($id)
{
$statement = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = ?");
$statement->bindValue(1, $id);
if (!$result = $statement->execute())
{
return null;
}
$user = new User();
$user->setId($result['id']);
$user->setFirstName($result['name']);
$user->setLastName($result['last_name']);
$user->setUsername($result['username']);
$user->setEmail($result['email']);
return $user;
}
public function findByUsernameAndPassword($username, $password)
{
$statement = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE username = ? AND password = ?");
$statement->bindValue(1, $username);
$statement->bindValue(2, $password);
$statement->execute();
if (!$result = $statement->fetch())
{
return null;
}
$user = new User();
$user->setId($result['id']);
$user->setFirstName($result['name']);
$user->setLastName($result['last_name']);
$user->setEmail($result['email']);
$user->setUsername($result['username']);
$user->setPassword($result['password'], new MD5());
return $user;
}
public function findAll()
{
$statement = $this->pdo->query("SELECT * FROM {$this->table}");
while ($result = $statement->fetch(PDO::FETCH_ASSOC))
{
$user = new User();
$user->setId($result['id']);
$user->setFirstName($result['name']);
$user->setLastName($result['last_name']);
$user->setUsername($result['username']);
$user->setEmail($result['email']);
$userCollection[] = $user;
}
return $userCollection;
}
}
try
{
$userCredentials = new UserCredentials();
$userCredentials->setUsername($_POST['username']);
$userCredentials->setPassword($_POST['password'], new MD5());
$pdo = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$loginAuth = new LoginAuthenticator(new PdoUserMapper($pdo));
$user = $loginAuth->authenticate($userCredentials);
$session = new Session();
$session->setValue('user', $user);
header('Location: index.php');
}
catch (InvalidArgumentException $e)
{
echo $e->getMessage();
}
catch (PDOException $e)
{
echo $e->getMessage();
}
catch (InvalidCredentialsException $e)
{
echo $e->getMessage();
}
</code></pre>
<p>One thing that is bothering me is the need to pass an Encryptor two times: to the User::setPassword method and to UserCredentials::setPassword method. If I need to change my encryption algorithm, I'll have to change it in more than one place, what leads me to think that I'm still making something wrong.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T08:57:25.857",
"Id": "74553",
"Score": "4",
"body": "Please consider changing from MD5 hashing to PHP 5.5's [password_hash](http://us2.php.net/password_hash) (see Example 2, using as high a cost as your server can afford) and [password_verify](http://us3.php.net/function.password_verify) functions, available in 5.3.7 via [password_compat](https://github.com/ircmaxell/password_compat). All of this is per the [PHP.net FAQ entry on Safe Password Hashing](https://www.php.net/manual/en/faq.passwords.php). This gives you BCrypt password hashing, and lets you store a single string with all the relevant information, auto-generates salts, etc."
}
] |
[
{
"body": "<p>You are right about your concerns regarding the mapper. A mappers job is to map, not to find. In this case its the job of a repository. The repository finds an entry in a database, uses the mapper to translate between the database fields and the model, and returns the model. I had some more detailed explanation about this <a href=\"https://codereview.stackexchange.com/questions/42498/repository-pattern-with-plain-old-php-object/42560#42560\">here</a>. </p>\n\n<p>The method <code>findByUsernameAndPassword</code> most likely would be a method of this repository, returning an authenticated user on success. </p>\n\n<p>I find the arguments in your <code>UserAuthenticator</code> a bit weird (not wrong) though. Currently this class reads as follows:</p>\n\n<ul>\n<li>The <code>UserAuthenticator</code> allows to authenticate a given set of <strong>credentials</strong> against <strong>different mappers</strong>.</li>\n<li>The <code>authenticate</code> methods authenticates the <code>UserAutheniticators</code> credentials against the passed mapper.</li>\n</ul>\n\n<p>Simplified, it is this:</p>\n\n<pre><code>$authenicator = new Authenticator($login, $password);\n$mapper = new PDOMapper();\n$authenticator->authenticate($mapper);\n</code></pre>\n\n<p>For me the last line really reads like <code>Authenticator authenticates mapper</code> using <code>$login</code>, and <code>$password</code>. Here, <code>Authenticator</code> actually does not resemble an class capably of authenticating users, it is missing a vital part. It represents <code>Credentials</code> which we later authenticate against a <code>$mapper</code>. </p>\n\n<p>Normally I would expect it the other way arround: </p>\n\n<ul>\n<li>The <code>UserAuthenticator</code> allows to authenticate <strong>different credentials</strong> against a given <strong>mapper</strong>.</li>\n<li>The <code>authenticate</code> methods authenticates the passed credentials against the previously set mapper.</li>\n</ul>\n\n<p>Simplified, this reads like this:</p>\n\n<pre><code>$mapper = new PDOMapper();\n$authenticator = new Authenticator($mapper);\n$authenticator->authenticate($login, $password);\n</code></pre>\n\n<p>Which reads like, <code>authenticator, authenticate $login and $password (using the $mapper)</code>. I feel this reads better and follows a more logical mental image on how we think this works.</p>\n\n<p>An analogy maybe would be a gatekeeper which demands your key card to enter a building. You usually pass the key card to the gatekeeper, not the gatekeeper to the key card. Out mental image here serves a gate keeper (your <code>UserAuthenticator</code>) who receives an key card reader (your mapper) at construction time (when he starts his shift). When someone arrives, he gives his key card (your <code>login</code> and <code>password</code>) to the gate keeper. </p>\n\n<p>Neither is wrong or right and it depends on your application requirements. I know popular frameworks to it otherwise too. There are pros and cons for either approach. I prefer the second approach though - feels more natural in most cases. Haven't seen many use-cases where credentials are tried against different mappers or repositories. Could elaborate here more if this really is your intended case.</p>\n\n<p>Your second concern comes from using a model for two different purposes: representing an invalid, unauthenticated user with pending authentication and later on for representing an existing, authenticated user. At this point I think this is more of a modeling issue: I'd either pass password and login name directly to <code>UserAuthenticator::authenticate</code> or create a new class <code>Credentials</code> for this. Your current approach poses one huge problem: you got two objects representing the same entity. Really really really avoid this at all costs.</p>\n\n<p>As another remark: your <code>UserAuthenticator</code> currently has two responsibilities: authentication and storing in a session. I'd move this to the service layer calling the authenticator. Of course this could be abstracted in a another layer (e.g. authentication storage adapter). This also reliefs the <code>UserAuthenticator</code> from performing logouts and so on. </p>\n\n<p>On last thing: your naming indicates you are logging in other entities then users, e.g. animals. The name <code>UserAuthenticator</code> says \"I'm the only class responsible for logging in users\". (Or you your 'admins' have to log-in by another adapter). While this might be true of course, I suppose your intention is rather more to provide different log-in facilities for users (and only users). Commonly this would result in a slightly different naming like: <code>interface LoginAdapterInterface</code>, <code>DatabaseLoginAdapter</code>, and so on.</p>\n\n<p><strong>Update</strong>:</p>\n\n<p>I have updated further explanation about the two modeling approaches inline.</p>\n\n<p>About using different mappers for different databases: That's the wrong place here. Databases should be hidden behind an database abstraction layer (DBAL) as PDO is for example. </p>\n\n<p>The key problem is that you're using mappers to access the database. Mappers really only map between the database fields and your model. A repository queries the database (or any other source) and uses the mapper to map the result to the model. It completely hides all information how and where data is stored. The remainder of the application should never know how / where the data is stored. They interact on the repository only. This could look like: </p>\n\n<pre><code> /- Mysql Mapper\nAuthenticator <-- User Repository <--- PDO Mapper\n \\- Mongo Mapper\n</code></pre>\n\n<p>This way keeps the responsibilities clean: The mapper doesn't need to know how to query a database (actually in most cases its completely database agnostic), the repository knows how to query a particular data source (e.g. database), and the authenticator looks for the provided user without knowing where it actually does come from. </p>\n\n<p>In my opinion it is particularly important to name the things right. If I read <code>Mapper</code> I know exactly what to expect. Mapper is a 'reserved' terms in regards to patterns:</p>\n\n<blockquote>\n <p>In software engineering, a design pattern is a general reusable\n solution to a commonly occurring problem</p>\n</blockquote>\n\n<p>If your code doesn't follow this I do become really confused. I have to do a lot of read-up, and stuff. Your code becomes a surprise, which generally is really bad in terms of maintainability. </p>\n\n<p>So If your mapper is actually a repository, please please name it as so. But then keep in mind that a repository is suggesting behavior too. </p>\n\n<p>On the <em>should the authenticator store to session</em> thing: The authenticator directly: no. Maybe you want to re-use it without storing users to a session directly (e.g. API-Calls, ...). Commonly it is the job of a <code>Service</code> to provide concrete login / logout functionality. This usually is a two-step process: authenticate the user at a authenticator, and on success, store the result in a session. This keeps your authenticators reusable for situations where you don't want to start a session.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T23:36:34.070",
"Id": "74859",
"Score": "0",
"body": "I see you answer questions from time to time, but I have never seen you on our [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor). It would be cool to see you on there. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T04:50:38.293",
"Id": "74888",
"Score": "0",
"body": "I'm not trying to authenticate against different mappers. I'm just trying to be flexible. I've created a Mapper interface and my authenticate method is waiting for any mapper. The idea is that you can pass any type of UserMapper (PdoUserMapper, MysqliUserMapper, MongoUserMapper and so on). I'm a bit confused. And about my Authenticator having two responsibilities, I'm not sure, but isn't a delegate responsibility ? My Authenticator uses a Session class to store session, so the real responsible is my Session class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T04:58:03.460",
"Id": "74891",
"Score": "0",
"body": "Anyway, am I on the right path ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T08:56:28.753",
"Id": "74911",
"Score": "0",
"body": "@Nyx: Don't model around flexibility, but around your mental image of the application and anticipated use-cases first (which still can be flexible of course). I have updated & extended my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T01:43:12.373",
"Id": "75132",
"Score": "0",
"body": "Ok, I'll make some changes to my classes. But I want to ask you one last thing: Could you talk a little about the respositories ? I would appreciate a short example code. What exactly a repository does ? I will update my code with my user related classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T08:11:52.803",
"Id": "75169",
"Score": "0",
"body": "There is a great explanation here: http://msdn.microsoft.com/en-us/library/ff649690.aspx ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:53:14.530",
"Id": "75329",
"Score": "0",
"body": "Thank you. I've updated my first post with my classes after some changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T21:03:06.493",
"Id": "75340",
"Score": "0",
"body": "Its worth a new question - enough has changed :). Also, this site ought to be more about CodeReview and not about Architecture. I suppose you do get better feedback about your architecture on programmers.stackexchange.com :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T21:20:48.507",
"Id": "75341",
"Score": "0",
"body": "I've updated instead of creating another question because I think that is good to other people to see how the code is evolving. Anyway, I really appreciate your tips and advice."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T16:04:54.850",
"Id": "43314",
"ParentId": "43211",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "43314",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T08:16:08.840",
"Id": "43211",
"Score": "5",
"Tags": [
"php",
"object-oriented"
],
"Title": "OOP UserAuthenticator Class"
}
|
43211
|
<p>I made a function which creates <a href="http://en.wikipedia.org/wiki/B%C3%A9zier_curve" rel="noreferrer">Bezier curves</a> of grade n. What do you think?</p>
<pre><code>float interpolate(float n1, float n2, float prec)
{
return n1 + ((n2-n1) * prec);
}
std::vector<Vector2f> make_bezier(const std::vector<Vector2f>& anchors, double accuracy=10000.0)
{
if(anchors.size()<=2)
return anchors;
std::vector<Vector2f> end;
end.push_back(anchors[0]);
for(float i=0.f; i<1.f; i+=1.f/accuracy)
{
std::vector<Vector2f> temp;
for(unsigned int j=1; j<anchors.size(); ++j)
temp.push_back(Vector2f(interpolate(anchors[j-1].x, anchors[j].x, i),
interpolate(anchors[j-1].y, anchors[j].y, i)));
while(temp.size()>1)
{
std::vector<Vector2f> temp2;
for(unsigned int j=1; j<temp.size(); ++j)
temp2.push_back(Vector2f(interpolate(temp[j-1].x, temp[j].x, i),
interpolate(temp[j-1].y, temp[j].y, i)));
temp = temp2;
}
end.push_back(temp[0]);
}
return end;
}
</code></pre>
|
[] |
[
{
"body": "<p>Just a few comments:</p>\n\n<pre><code>std::vector<Vector2f> make_bezier(const std::vector<Vector2f>& anchors, double accuracy=10000.0)\n</code></pre>\n\n<p>You're using <code>float</code> for all your other floating point variables. Unless there's some <em>really</em> good reason to use <code>double</code> here (for <code>accuracy</code>) I'd consider changing it to a <code>float</code> as well.</p>\n\n<pre><code>std::vector<Vector2f> end;\nend.push_back(anchors[0]);\n\nfor(float i=0.f; i<1.f; i+=1.f/accuracy)\n</code></pre>\n\n<p>I'd write this a bit differently. As it stands, <code>i</code> can accumulate rounding errors from one iteration of the loop to the next. I'd prefer to do something like:</p>\n\n<pre><code>for (int j=0; j<accuracy; j++) {\n float i = 1.0f/j;\n // ...\n</code></pre>\n\n<p>This way, each value of <code>i</code> is computed independently, and rounding from one iteration doesn't affect its value in the next.</p>\n\n<pre><code> std::vector<Vector2f> temp;\n for(unsigned int j=1; j<anchors.size(); ++j)\n temp.push_back(Vector2f(interpolate(anchors[j-1].x, anchors[j].x, i),\n interpolate(anchors[j-1].y, anchors[j].y, i)));\n</code></pre>\n\n<p>Literally <em>all</em> your calls to <code>interolate</code> (at least in this code) happen in pairs. That being the case, I think I'd rewrite it a bit to take a couple of <code>vector2f</code>s as parameters, and return a <code>vector2f</code> containing the interpolation on both the <code>x</code> and <code>y</code> components of the inputs. It also uses <code>i</code> as a third input. My immediate reaction would be to define <code>interpolate</code> as a lambda that captured <code>i</code>, and took the other two parameters as inputs.</p>\n\n<pre><code>vector2f interpolate(vector2f in1, vector2f const &in2) { \n in1.x = /* ... */;\n in1.y = /* ... */;\n return in1;\n}\n</code></pre>\n\n<p>With that in place, the loop above can be reduced to a fairly simple application of <code>std::transform</code>, something like this:</p>\n\n<pre><code> std::transform(anchors.begin(), anchors.end(), \n anchors.begin()+1, \n std::back_inserter(temp));\n</code></pre>\n\n<p>Of course, pretty much the same would happen here:</p>\n\n<pre><code> for(unsigned int j=1; j<temp.size(); ++j)\n temp2.push_back(Vector2f(interpolate(temp[j-1].x, temp[j].x, i),\n interpolate(temp[j-1].y, temp[j].y, i)));\n</code></pre>\n\n<p>...as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T19:52:14.413",
"Id": "43244",
"ParentId": "43215",
"Score": "11"
}
},
{
"body": "<p>Just a few notes:</p>\n\n<ul>\n<li><p>You could improve readability by adding whitespace between operators.</p>\n\n<p>For instance, in the <code>for</code> loop statement:</p>\n\n<pre><code>for (float i = 0.f; i < 1.f; i += 1.f/accuracy) {}\n</code></pre>\n\n<p>For this as well, I would have a constant in place of the <code>1.f/accuracy</code> to avoid performing the division operation each time (it's slow). Instead, you'll only be performing addition each time.</p>\n\n<p>Consider something like this:</p>\n\n<pre><code>const float stepsize = 1.f / accuracy;\n\nfor (float i = 0.f; i < 1.f; i += stepsize) {}\n</code></pre></li>\n<li><p>With an <code>std::vector</code>, you can use <a href=\"http://en.cppreference.com/w/cpp/container/vector/front\" rel=\"nofollow noreferrer\"><code>front()</code></a> to get the reference to the first element instead of using the index <code>0</code>:</p>\n\n<pre><code>end.push_back(anchors.front());\n</code></pre></li>\n<li><p>Prefer to use <a href=\"https://stackoverflow.com/questions/4849632/c-vectorintsize-type\"><code>std::size_type</code></a> when incrementing through an STL container. This guarantees that you can access every element of any container size, whereas an <code>unsigned int</code> or another integer type may not be large enough.</p>\n\n<p>Due to its length, this can be declared before the loop.</p>\n\n<pre><code>std::vector<Vector2f>::size_type j;\n\nfor (j = 1; j != temp.size(); ++j) {}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T10:21:11.727",
"Id": "74697",
"Score": "1",
"body": "Also I would not calculate 1.f/accuracy 10000 times. Maybe a variable float stepsize = 1.f/accuracy should be introduced."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T15:13:41.933",
"Id": "74747",
"Score": "0",
"body": "@MarcelBlanck: I've missed that as well. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T19:54:34.653",
"Id": "43245",
"ParentId": "43215",
"Score": "10"
}
},
{
"body": "<p>Apart from the things which already have been noted:</p>\n\n<p>You duplicate the interpolation loop in your body which violates DRY. The easy fix for that is to copy <code>anchors</code> into <code>temp</code>.</p>\n\n<p>Also rather than assigning <code>temp2</code> to <code>temp</code> which copies the vector you could use <a href=\"http://en.cppreference.com/w/cpp/container/vector/swap\" rel=\"nofollow\"><code>vector::swap</code></a> which swaps the contents of the two vectors in constant time.</p>\n\n<p>So your main body can be written as:</p>\n\n<pre><code>for (float k = 0.f; k < accuracy; ++k)\n{\n float i = k / accuracy;\n\n std::vector<Vector2f> temp(anchors);\n\n while (temp.size() > 1)\n {\n std::vector<Vector2f> temp2;\n\n for (unsigned int j = 1; j < temp.size(); ++j)\n temp2.push_back(Vector2f(interpolate(temp[j-1].x, temp[j].x, i),\n interpolate(temp[j-1].y, temp[j].y, i)));\n temp.swap(temp2);\n }\n end.push_back(temp.front());\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T07:19:16.307",
"Id": "43283",
"ParentId": "43215",
"Score": "5"
}
},
{
"body": "<p>The algorithm you are using works, but it will exhibit very poor performance as you increase the order of your Bézier curve. Let's say that you want to render <code>m</code> points and that you have <code>n</code> anchors, you are computing <code>n-1</code> + <code>n-2</code> + ... + <code>1</code> interpolations for <em>every</em> rendered point. So we are talking about an O(n²m) algorithm.</p>\n\n<p>If performance matters, you'll have to consider using the general formula with the binomial coefficients. The binomial coefficients can be precomputed so we can consider that they are given for free. Then for each rendered point you only need to traverse the list of anchors once, yielding an O(nm) algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T14:49:43.693",
"Id": "74742",
"Score": "0",
"body": "this seems like a good point, I would like to see more code in the review, but I think this fits."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T09:26:47.870",
"Id": "43289",
"ParentId": "43215",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "43244",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T12:43:52.940",
"Id": "43215",
"Score": "16",
"Tags": [
"c++",
"c++11",
"graphics"
],
"Title": "Bezier curves of grade n"
}
|
43215
|
<p>I have two snippets of code that I would like you to look at. I can't figure out which of the two is most efficient (or better practice, if applicable). I'm currently finding the row and column of a sprite in a sprite sheet in order to render it to the screen; which works find and dandy. However, I now have two algorithms:</p>
<pre><code>const double Testvalue = 155.0f; //This values changes, could be any natural number.
const double imageWidth = 614.0f;
const double SpriteAverageSize = 34.0f; //floor(value / spriteAverageSize) gives us max rows (which is this case is 18).
double numRows = floor(imageWidth / SpriteAverageSize);
double RowValue = ceil(Testvalue / numRows);
double ColumnValue = numRows - ((numRows * RowValue) - Testvalue);
//This will do the following operation:
//numRows = floor(614.0/ 34.0) -> floor(18.05..) -> 18.0.
//RowValue = ceil(155.0/ 18.0) -> ceil(8.611..) -> 9.0.
//ColumnValue = 18.0 - ((18.0 * 9.0) - 155.0) -> 18.0 - (162.0 - 155.0) -> 18.0 - 7.0 -> 11.0.
//Row: 9 ; Column: 11.
</code></pre>
<p>or</p>
<pre><code>const double Testvalue = 155.0f;
const double imageWidth = 614.0f;
const double SpriteAverageSize = 34.0f;
double RowValue = ceil(Testvalue / floor(imageWidth / SpriteAverageSize));
double ColumnValue = floor(imageWidth / SpriteAverageSize) - ((floor(imageWidth / SpriteAverageSize) * RowValue) - Testvalue);
//This will do the following operation:
//RowValue = ceil(155.0 / floor(614.0 / 34.0)) -> ceil(155.0 / floor(18.05..)) -> ceil(155.0 / 18.0) -> ceil(8,61..) -> 9.0.
//ColumnValue = floor(614.0 / 34.0) - ((floor(614.0 / 34.0) * 9.0) - 155.0) -> floor(18.05..) - ((floor(18.05..) * 9.0) - 155.0) -> 18.0 - ((18.0 * 9.0) - 155.0) -> 18.0 - 7.0 -> 11.0.
//Row: 9 ; Column: 11
</code></pre>
<p>To clarify, these two work perfectly (I have also implemented it as a method in my class to do the operation as I get the data from an XML file), I get the right row and column value as I've tested several times and implementing it works too. I would just like some tips on which of the two algorithms you'd prefer in a block of code and which of the two is more efficient?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T15:42:24.587",
"Id": "74573",
"Score": "0",
"body": "I am down-voting this because it's a) An \"A or B?\"-style question and b) because it is technically the exact same code (which you don't seem to be aware of), the only difference is that you have just extracted a variable in the first version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T16:09:07.330",
"Id": "74580",
"Score": "3",
"body": "@Sean The problem with \"Is A or B better?\" questions is that sometimes the answer might be C. If you posted more of the code people might find other ways to improve it. For example, from the posted code fragment I couldn't tell how `Testvalue` was set (it's defined as `const` but the comment says it changes); and I couldn't tell which variables are defined at global scope, and which are local variables."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T16:15:43.873",
"Id": "74581",
"Score": "0",
"body": "@ChrisW My question wasn't focused on improving the code, I simply wanted to know which of A or B a coder would prefer in their code. More code isn't necessary as what it does here is what it does in my software. Testvalue is set as const as the actual values would be gotten from a const vector<vector<int>> foo, so yes, the values do change as it traverses the 2D vector. I also specified at the bottom that it is implemented in a class, so it would be local variables to the class. However, I do understand where you are coming from."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T16:24:48.960",
"Id": "74583",
"Score": "2",
"body": "There seems to be a misunderstanding about what is considered to be on-topic for CodeReview here. It is clear in the [help/on-topic] that you should expect more than an A/B answer. When you asked your question you are saying yes to: *Do I want feedback about any or all facets of the code?*. No point in blaming other people for doing what you asked them to do"
}
] |
[
{
"body": "<p>I prefer the first one, because having the named variable <code>numRows</code>:</p>\n\n<ul>\n<li>Certainly makes the code more \"self-documenting\": it's easier for me (the programmer) to understand what the algorithm is doing</li>\n<li>May make the code faster: because you only do the <code>floor(imageWidth / SpriteAverageSize)</code> calculation once instead of three times (although it's possible that an optimizing compiler might be able to make that optimization itself, even without your 'hint' that it's a reused sub-expression)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T15:39:45.413",
"Id": "74572",
"Score": "0",
"body": "Thank you. That was very helpful. It makes sense for the first algorithm to be a more popular choice. It is definitely more self-documenting."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T14:35:02.127",
"Id": "43220",
"ParentId": "43216",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "43220",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T12:54:47.493",
"Id": "43216",
"Score": "2",
"Tags": [
"c++",
"mathematics"
],
"Title": "Two methods for finding a sprite in sprite sheet C++, which is better?"
}
|
43216
|
<p>I need to test my new functionality by sending about 100 requests in one time.</p>
<pre><code>public class MyTest {
// ...
@Test
public void test() throws Exception {
Runnable[] runners = new Runnable[size];
Thread[] threads = new Thread[size];
for(int i=0; i<threads.length; i++) {
runners[i] = new RequestThread(i);
}
for(int i=0; i<threads.length; i++) {
threads[i] = new Thread(runners[i]);
}
for(int i=0; i<threads.length; i++) {
threads[i].start();
}
while (!threadsAreDead(threads)) {}
}
private boolean threadsAreDead(Thread[] threads) {
for(int i=0; i<threads.length; i++) {
if (threads[i].isAlive()) return false;
}
return true;
}
}
class RequestThread implements Runnable {
public RequestThread(int id) {
this.id = id;
}
@Override
public void run() {
try {
b2b.execute(request);
} catch (B2BException e) {
// ...
}
}
}
</code></pre>
<p>Have you any idea how to optimize above code to send requests more 'in one time'? </p>
|
[] |
[
{
"body": "<p>Your test case looks relatively comprehensive in the sense that, yes, it fires off the 100 concurrent threads, but, you ask "how to make it more '<em>at the same time</em>' ?"</p>\n<p>There are two aspects I can suggest:</p>\n<ul>\n<li>Use an <code>ExecutorService</code></li>\n<li>Use a <code>CountDownLatch</code></li>\n</ul>\n<h2>ExecutorService</h2>\n<p>One of the novelties about the ExecutorService system is the concept of the Future, and it's foundation, the Callable class. The Callable interface is similar to the Runnable, except it can return a value, and throw an exception. These are two important differences.</p>\n<p>The exception thrown in a Callable is trapped, and then re-thrown when the Future's get() method is called. This means that exceptions in remote threads can be collected in the calling thread.</p>\n<p>In your case, throwing the exception is the most significant.</p>\n<p>Consider the following code that sets up your threads appropriately:</p>\n<pre><code>@Test\npublic void test() throws Exception {\n ExecutorService threads = Executors.newFixedThreadPool(size);\n List<Callable<Boolean>> torun = new ArrayList<>(size);\n for (int i = 0; i < size; i++) {\n torun.add(new Callable<Integer>() {\n public Boolean call() throws B2BException {\n b2b.execute(request);\n return Boolean.TRUE;\n }\n });\n }\n\n // all tasks executed in different threads, at 'once'.\n List<Future<Boolean>> futures = threads.invokeAll(torun);\n \n // no more need for the threadpool\n threads.shutdown();\n // check the results of the tasks...throwing the first exception, if any.\n for (Future<Boolean> fut : futures) {\n fut.get();\n }\n\n //check the threadpool is now in fact complete\n if (!threads.isShutDown()) {\n // something went wrong... our accounting is off...\n }\n\n}\n</code></pre>\n<p>OK, that is a better way of setting up the threads, and gets the exceptions to be thrown inside the test thread, rather than inside the remote threads.</p>\n<h2>CountDownLatch</h2>\n<p>If you are concerned that the threads should all be doing things more 'at the same time', and not worrying about start up time, etc. then consider <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html\" rel=\"noreferrer\">using a count-down latch</a>.</p>\n<p>This device is set with a counter, and, when triggered, it will count down by one, and then lock, until all the counts are counted down.</p>\n<p>You can use it in the above example code like:</p>\n<pre><code>@Test\npublic void test() throws Exception {\n ExecutorService threads = Executors.newFixedThreadPool(size);\n List<Callable<Boolean>> torun = new ArrayList<>(size);\n final CountDownLatch countdown = new CountDownLatch(size);\n for (int i = 0; i < size; i++) {\n toron.add(new Callable<Integer>() {\n public Boolean call() throws B2BException, InterruptedException {\n countdown.countDown();\n countdown.await();\n b2b.execute(request);\n return Boolean.TRUE;\n }\n });\n }\n\n // all tasks executed in different threads, at 'once'.\n List<Future<Boolean>> futures = threads.invokeAll(torun);\n \n // no more need for the threadpool\n threads.shutdown();\n // check the results of the tasks...throwing the first exception, if any.\n for (Future<Boolean> fut : futures) {\n fut.get();\n }\n\n //check the threadpool is now in fact complete\n if (!threads.isShutDown()) {\n // something went wrong... our accounting is off...\n }\n\n}\n</code></pre>\n<p>The above system will set up all the threads, so they are all 'runnable', and then only when every thread is established and ready, will the locks be released.</p>\n<p>You will still not get complete concurrent use, but it will/may be better having more threads start 'at once'.</p>\n<h2>Other....</h2>\n<p>You should consider using a custom ThreadFactory for the thread pool, like I <a href=\"https://codereview.stackexchange.com/a/43146/31503\">suggested in this answer</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T20:04:29.733",
"Id": "74615",
"Score": "0",
"body": "+1. `List<Callable<Boolean>>` could be `List<Callable<Void>>`. (`new Callable<Integer>()` looks inconsistent.) Check `CyclicBarrier` too, it was designed for these kind of problems."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T15:30:16.410",
"Id": "43225",
"ParentId": "43219",
"Score": "12"
}
},
{
"body": "<p><code>new Callable<Integer>()</code> wont work. <code>new Callable<Boolean>()</code> is the right approach here.</p>\n\n<pre><code>for (int i = 0; i < threadPoolSize; i++) {\n torun.add(new Callable<Boolean>() {\n public Boolean call() throws InterruptedException {\n countdown.countDown();\n countdown.await();\n // Your implementation\n return Boolean.TRUE;\n }\n });\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T18:42:55.487",
"Id": "427869",
"Score": "3",
"body": "Saying one is wrong and one is right is nice, but it doesn't help anybody understand why one is right or how they should choose in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T23:01:01.617",
"Id": "427892",
"Score": "0",
"body": "@chicks Thanks. hope it looks better now"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T18:35:34.100",
"Id": "221295",
"ParentId": "43219",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": "43225",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T14:15:25.157",
"Id": "43219",
"Score": "6",
"Tags": [
"java",
"multithreading"
],
"Title": "Sending n requests in one time"
}
|
43219
|
<p>I have this Python program for calculating Leibniz of 'pi'. I am not able to shorten it more. Can anyone here optimise/shorten it?</p>
<pre><code>s,a,b=0,[],[]
for i in range(int(input())):a.append(input())
for x in a:
for j in range(int(x)):s+=pow(-1,int(j))/((2*int(j))+1)
b.append(s)
s=0
for i in b:print("{0:.15f}".format(i))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T10:35:11.627",
"Id": "74699",
"Score": "4",
"body": "Code golfing is off-topic for Code Review — see [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T10:38:00.210",
"Id": "74700",
"Score": "0",
"body": "Your question is also unclear. I see some resemblance to the [Leibniz formula for π](http://en.wikipedia.org/wiki/Leibniz_formula_for_π), but I can't tell what your goal is."
}
] |
[
{
"body": "<p>This is only micro optimization, I don't think it will make a difference, but here you go anyway:</p>\n\n<pre><code>b=[]\nfor i in range(int(input())):\n s=sum([pow(-1,j)/(2*j+1) for j in range(int(input()))])\n b.append(\"{0:.15f}\".format(s))\nfor x in b:print(b)\n</code></pre>\n\n<ul>\n<li>Instead of 3 loops, there is only one</li>\n<li>Removed unnecessary intermediary variables</li>\n<li>Removed <code>int(j)</code>, <code>j</code> is already <code>int</code></li>\n<li>Removed extra brackets, for example <code>(2*int(j))+1</code> is the same as <code>2*j+1</code></li>\n<li>Removed an unnecessary <code>s=0</code></li>\n</ul>\n\n<p>You could of course write the whole thing on a single line, but now that's starting to hurt readability...</p>\n\n<pre><code>for x in [\"{0:.15f}\".format(sum([pow(-1,j)/(2*j+1) for j in range(int(input()))])) for i in range(int(input()))]:print(x)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T15:29:59.007",
"Id": "43224",
"ParentId": "43222",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "43224",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T15:10:38.657",
"Id": "43222",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"mathematics"
],
"Title": "Calculating Leibniz of Pi"
}
|
43222
|
<pre><code>def printTrg(rows):
r1 = [1]
r2 = [1, 1]
trg = [r1, r2]
r = []
if rows == 1:
r1[0] = str(r1[0])
print(' '.join(r1))
elif rows == 2:
for o in trg:
for a in range(len(o)):
o[a] = str(o[a])
print((' ')*(2-(a+1)), (' '.join(o)))
else:
for i in range(2, rows):
trg.append([1]*i)
for n in range(1, i):
trg[i][n] = (trg[i-1][n-1]+trg[i-1][n])
trg[i].append(1)
for x in range(len(trg)):
for y in trg[x]:
s = str(y)
r.append(s)
print((' ')*(rows-(x+1)), (' ' .join(r)))
r = []
</code></pre>
<p>I've been learning Python for a month, and developed this program that prints out the <a href="http://en.wikipedia.org/wiki/Pascal%27s_triangle" rel="noreferrer">Pascal triangle</a> with the number of rows you want. It works fine with 5 rows.</p>
<p>For example, it prints:</p>
<pre><code> 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
</code></pre>
<p>But with more rows, it begins to be a little unbalanced because you have more digits on each number.</p>
<p>For example, a 10 row triangle:`</p>
<pre><code> 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
</code></pre>
<p>If you could help me with the output, it would be great.</p>
<hr>
<p><strong>EDIT:</strong></p>
<pre><code>def generate_pascals_triangle(rows):
""" Returns a list of rows of a Pascal's Triangle with how many rows you want """
triangle = [[1], [1, 1]]
if rows == 1:
return triangle[0]
else:
for row_number in range(2, rows):
triangle.append([1]*row_number)
for number in range(1, row_number):
triangle[row_number][number] = (triangle[row_number-1][number-1]+triangle[row_number-1][number])
triangle[row_number].append(1)
return triangle
def difference_between_rows(row, next_row):
""" Returns the difference between two rows in the formatted way """
row_len = 0
next_row_len = 0
for number in row:
string_number = str(number)
row_len += (len(string_number)+1)
for number in next_row:
string_number = str(number)
next_row_len += (len(string_number)+1)
return (next_row_len-1) - (row_len-1)
def print_pascals_triangle(triangle):
""" Prints the Pascal's Triangle previously generated by generate_pascals_triangle in a formatted form """
for row in triangle:
difference = int((difference_between_rows(row, triangle[len(triangle)-1]))/2)
for number in range(len(row)):
row[number] = str(row[number])
print ((' ')*(difference), ' '.join(row))
if __name__ == '__main__': #credit to @alexwlchan
again = 'y'
while again == 'y':
rows = int(input('Enter the number of rows you want in your Pascal`s Triangle: '))
print_pascals_triangle(generate_pascals_triangle(rows))
again = input('Do it again ? <y/n> ')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T15:46:48.747",
"Id": "74575",
"Score": "0",
"body": "Welcome to Code Review! It's an OK first question you have here, to make it even better you could provide example input/output of your program and explain a little bit what \"Pascal Triangle\" is (or provide a wikipedia link) for those unfamiliar with the subject. Anything you can do to help the reviewers understand and review your code is appreciated!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T15:49:06.217",
"Id": "74576",
"Score": "0",
"body": "Regarding \"shortening\" code that's not *exactly* what we do around here. We mostly prefer *clean* code which does not *always* have to be the same as *short*. In this case though, it is possible that the cleaner version also will be the shorter version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T16:32:02.640",
"Id": "74585",
"Score": "0",
"body": "Nice edit you did, I just want to point out that \"If you could help me with the output, it would be great.\" is a bit off-topic here as that would technically be *modifying what the code does / adding a feature to the code*, Code Review is more about *how* the code does something. You can expect answers about how you can clean up the code, just don't *expect* answers about how to fix that output (that being said, if our answerers are extra friendly today they might have an idea about that too :) )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T22:02:18.130",
"Id": "74631",
"Score": "0",
"body": "I don't think you can really make the output work properly without knowing how many rows of the triangle you are going to be outputting. And if you do, the amount of spacing required is going to depend on the length of the largest integer you calculate, which could probably be computed mathematically but a simpler approach is to store your output in memory and then print it all at once with all the information you need."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T22:31:38.383",
"Id": "74637",
"Score": "0",
"body": "Actually the spaces required to centralize the rows just depends on te largest row that is the last one..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T05:45:50.337",
"Id": "75159",
"Score": "0",
"body": "@matheussilvapb Which you print last (*after* all the other rows) which is why I said you should keep everything in memory since a priori you cannot erase what you print once it's printed (you could, with most terminals, but that's not the point). It seems your edit addresses the problem, though, so all is well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-19T19:16:02.630",
"Id": "141267",
"Score": "0",
"body": "I wanted to eliminate a small error: use `again = raw_input('Do it again ? <y/n> ')` instead of `again = input('Do it again ? <y/n> ')`."
}
] |
[
{
"body": "<p>Some brief comments:</p>\n\n<ul>\n<li><p>Your variable names are quite short (often one letter), which makes the code harder to follow. Longer and more descriptive variable names would make it easier to read and debug (e.g., <code>trg</code> to <code>triangle</code>, <code>r1</code> to <code>row1</code>).</p>\n\n<p>The input to the function <code>printTrg</code> is <code>rows</code>, but we also have variables like <code>r</code>, <code>r1</code> and <code>r2</code> which look like rows. Perhaps this would be better named as <code>row_count</code>?</p>\n\n<p>The main style guide for Python is <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\"><strong>PEP 8</strong></a>, which is very readable and friendly. It gives advice on how you choose variable names, functions, and so on. In particular, for function names, it says:</p>\n\n<blockquote>\n <p>Function names should be lowercase, with words separated by underscores as necessary to improve readability.</p>\n</blockquote>\n\n<p>So you should rename the function <code>printTrg</code> to be <code>print_trg</code>, or even better <code>print_triangle</code>, to match the Python conventions.</p>\n\n<p>There's also something called a <strong>docstring</strong>, which is used in Python functions to explain what the function is supposed to do.\nThis usually occurs in triple quotes, directly below the <code>def</code> line.\nFor example, you might write:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def printTrg(rows):\n \"\"\"Prints Pascal's triangle up to the (rows)th row.\"\"\"\n ...\n</code></pre>\n\n<p>There's a more detailed explanation of docstrings in <a href=\"http://legacy.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><strong>PEP 257</strong></a>.</p></li>\n<li><p>Right now the code which generates Pascal's triangle, and the code which prints it to the console, are tightly bound together.\nYou might be better off splitting the two into two functions:</p>\n\n<ul>\n<li><code>generate_pascals_triangle(row_count)</code>, which would return the list of lists <code>trg</code> which your function already creates.</li>\n<li><code>print_pascals_triangle(triangle)</code>, which could take the output from <code>generate</code> and print it to the console.</li>\n</ul></li>\n<li><p>The <code>elif rows == 2</code> block is redundant, as the <code>else</code> block does exactly the same thing. The <code>range(2, rows)</code> never executes if <code>rows</code> is 2.</p>\n\n<p>While we're in the <code>else</code> block, I’m unclear why your range goes to <code>rows</code> in the first for loop, but to <code>len(trg)</code> in the second. Unless I've confused myself, these are always the same thing. And later in the same loop, you use <code>rows</code> to count the number of spaces you need.</p></li>\n<li><p>The way you generate the next row of Pascal's triangle (insert a list of 1s, update the entries, then put an extra 1 on the end) could be simplified. Since you’re making a list for the entries in that row, you could use a <strong>list comprehension</strong>. (If you're not familiar with these, then there are lots of good explanations on Google.)</p>\n\n<p>Here's a simple example of a function which takes the previous row of Pascal's triangle, works out which row you're in now (by looking at the length of the previous row), then generates the new row with a list comprehension:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def next_row(row):\n \"\"\"Returns the next row of Pascal's triangle.\"\"\"\n n = len(row)\n new_row = [row[0]] + [row[i] + row[i+1] for i in range(n - 1)] + [row[-1]]\n return new_row\n</code></pre>\n\n<p>We're still doing essentially the same thing, but this looks cleaner, and we've split up some more of the logic. This can make life easier when it comes to debugging.</p>\n\n<p>This also works if we give it the first row <code>[1]</code>, so we don't need to consider the cases <code>rows == 1</code> and <code>rows != 1</code> separately when we generate Pascal's triangle. Again, we're able to simplify some of the code.</p></li>\n<li><p>As you’ve pointed out, things get out of line if you print a large number of rows, as two and three digit numbers come in to play. If you split this into two functions, then you can play around with the printing without affecting the arithmetic (which works perfectly).</p></li>\n</ul>\n\n<p>So with all that in mind, here's how I might rewrite your code.\nFirst I have the function which I mentioned above, which takes one row of Pascal's triangle and returns the next:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def next_row(row):\n \"\"\"Returns the next row of Pascal's triangle.\"\"\"\n n = len(row)\n new_row = [row[0]] + [row[i] + row[i+1] for i in range(n - 1)] + [row[-1]]\n return new_row\n</code></pre>\n\n<p>Next, we have a function which just generates the entries of Pascal's triangle. Since we're not printing anything (that will come later), and the arithmetic for generating new rows is in another function, this is much shorter than before:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def generate_pascals_triangle(row_count):\n \"\"\"Returns the entries of Pascal's triangle.\"\"\"\n row1 = [1]\n triangle = [row1]\n for i in range(1, row_count):\n triangle.append(next_row(triangle[-1]))\n return triangle\n</code></pre>\n\n<p>If we wanted, we could supply the first entry (or even a whole first row) as an argument. You could see what happens if you make 2 the top entry, or started several levels deep. This is left for you to play with. (You may find this explanation of <a href=\"http://www.diveintopython.net/power_of_introspection/optional_arguments.html\" rel=\"nofollow noreferrer\">optional and named arguments</a> useful.)</p>\n\n<p>Finally, we come to the printing problem. We can use the logic from your <code>else</code> block, almost unmodified (just with more descriptive variable names):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def print_pascals_triangle(triangle):\n \"\"\"Prints the entries of Pascal's triangle.\"\"\"\n for row_no in range(len(triangle)):\n row = triangle[row_no]\n printed_row = []\n for entry in row:\n printed_row.append(str(entry))\n print (' ' * (len(triangle) - (row_no + 1)), ' '.join(printed_row))\n</code></pre>\n\n<p>If you wanted, that could become a little shorter using list comprehensions (I leave that as an exercise).</p>\n\n<p>Here's an idea for how you could solve the spacing issue: first, find the longest number in your triangle. (You don't need to examine every entry: which row will always contain the longest entry?) Then, add spaces to every number you print, so that they're always the same length.</p>\n\n<p>For example, if the longest entry was <code>2704156</code> (which you get in a 25-triangle), you would transform</p>\n\n<p><code>1</code> -> <code>_ _ _ 1 _ _ _</code></p>\n\n<p><code>15</code> -> <code>_ _ 1 5 _ _ _</code></p>\n\n<p><code>165</code> -> <code>_ _ 1 6 5 _ _</code></p>\n\n<p>and so on. I haven't tried that, so I don't know how good it looks, but it might be something for you to get you started.</p>\n\n<hr>\n\n<p><strong>ETA:</strong> One more comment, based on your updated code:</p>\n\n<p>At the end of the script, you have a little “interactive” section, which gets the user to give you a row count, and then you print their Pascal’s triangle.</p>\n\n<p>If you load this file with <code>import pascal-triangle</code> in a larger script, then you immediately get asked to start drawing Pascal triangles. This can be unhelpful (imagine if everything you <code>import</code>ed did that!).</p>\n\n<p>Instead, you can put this code inside a special <code>if</code> statement:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == '__main__':\n again = 'y'\n while again == 'y':\n rows = int(input('Enter the number of rows you want in your Pascal`s Triangle: '))\n print_pascals_triangle(generate_pascals_triangle(rows))\n again = input('Do it again ? <y/n> ')\n</code></pre>\n\n<p>Any code within this <code>if</code> statement is only used if the script is run directly; that is, if somebody types</p>\n\n<pre><code>$ python pascal-triangle.py\n</code></pre>\n\n<p>at a command prompt. If it gets loaded as <code>import pascal-triangle</code> in another script, then any code inside this <code>if</code> statement won’t be run. This means that you can reuse these functions later without any hassle.</p>\n\n<p>You can find out more in this Stack Overflow question: <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">https://stackoverflow.com/questions/419163/what-does-if-name-main-do</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T18:39:02.543",
"Id": "74599",
"Score": "0",
"body": "Man youre awesome, I'll try to do what you said, and get a more readable code. When I did this st first I was so lazy but i got it in 30 minutes. I'm pretty familiar with lists comprehensions but I'm not used to use that. pscl v2.0 is coming..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T19:34:59.063",
"Id": "74608",
"Score": "0",
"body": "when you use row[-1] what you want to get with minus 1 ? I think creating a whole function to get the next row is a bit unnecessary, and using that back in the generate function will be almost as long as before ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T19:41:59.680",
"Id": "74610",
"Score": "0",
"body": "@matheussilvapb: negative indexes in Python (such as `my_list[-1]`) count from the end of the list. So `my_list[-1]` gets the last item, `my_list[-2]` gets the second from the end, and so on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T21:57:59.717",
"Id": "74628",
"Score": "2",
"body": "I have converted the OP's answer into an edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T22:21:08.610",
"Id": "74636",
"Score": "0",
"body": "@alexwlchan awesome man, do you think I'm doing fine for a month with python ?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T17:15:23.757",
"Id": "43229",
"ParentId": "43223",
"Score": "19"
}
},
{
"body": "<p><em>Reviewing your edited code (Rev 7):</em></p>\n\n<p>Good job — it works!</p>\n\n<p>One nitpick: In <code>print_pascals_triangle()</code>, you use <code>int()</code> to round the result of division down to the nearest integer:</p>\n\n<pre><code>difference = int(difference_between_rows(…, …)/2)\n</code></pre>\n\n<p>To do integer division (rounding towards -∞), use the <code>//</code> operator for better performance and readability:</p>\n\n<pre><code>difference = difference_between_rows(…, …) // 2\n</code></pre>\n\n<h3>Easier way to centre a row</h3>\n\n<p>Basically, your goal is to ensure that every row is printed centre-aligned. You've done it by calculating how many spaces to prepend to each row. The easier way is to figure out the width of the longest line, then centre-align everything based on that width. An easy way to centre-align text is to call <a href=\"http://docs.python.org/3.2/library/stdtypes.html#str.center\" rel=\"noreferrer\"><code>str.center()</code></a>.</p>\n\n<pre><code>def print_pascals_triangle(triangle):\n def format_row(row):\n return ' '.join(map(str, row))\n triangle_width = len(format_row(triangle[-1]))\n for row in triangle:\n # Print each row, enter-aligned with the computed width\n print(format_row(row).center(triangle_width))\n</code></pre>\n\n<p>Eliminating <code>difference_between_rows()</code> makes it simpler and more efficient.</p>\n\n<h3>Making it more… triangular?</h3>\n\n<p>For larger inputs, the shape starts looking less like a triangle.</p>\n\n<blockquote>\n<pre><code>Enter the number of rows you want in your Pascal`s Triangle: 16\n 1 \n 1 1 \n 1 2 1 \n 1 3 3 1 \n 1 4 6 4 1 \n 1 5 10 10 5 1 \n 1 6 15 20 15 6 1 \n 1 7 21 35 35 21 7 1 \n 1 8 28 56 70 56 28 8 1 \n 1 9 36 84 126 126 84 36 9 1 \n 1 10 45 120 210 252 210 120 45 10 1 \n 1 11 55 165 330 462 462 330 165 55 11 1 \n 1 12 66 220 495 792 924 792 495 220 66 12 1 \n 1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1 \n 1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1 \n1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1\n</code></pre>\n</blockquote>\n\n<p>What's worse, the display no longer shows off how each entry is the sum of two neighbouring entries in the row above. Ideally, it should look like</p>\n\n<pre><code> 1 9 36\n ↘︎ ⊕ ↙︎ ↘︎ ⊕ ↙︎ \n1 10 45 \n</code></pre>\n\n<p>To achieve that spacing, you want every element to be given the same width — namely, the width necessary to accommodate the largest number in the triangle. The code above can be tweaked to implement that. Use a similar technique to ensure that each element is centred within the width allotted to it.</p>\n\n<pre><code>def print_pascals_triangle(triangle):\n largest_element = triangle[-1][len(triangle[-1]) // 2]\n element_width = len(str(largest_element))\n def format_row(row):\n return ' '.join([str(element).center(element_width) for element in row])\n triangle_width = len(format_row(triangle[-1]))\n for row in triangle:\n print(format_row(row).center(triangle_width))\n</code></pre>\n\n<blockquote>\n<pre><code>Enter the number of rows you want in your Pascal`s Triangle: 16\n 1 \n 1 1 \n 1 2 1 \n 1 3 3 1 \n 1 4 6 4 1 \n 1 5 10 10 5 1 \n 1 6 15 20 15 6 1 \n 1 7 21 35 35 21 7 1 \n 1 8 28 56 70 56 28 8 1 \n 1 9 36 84 126 126 84 36 9 1 \n 1 10 45 120 210 252 210 120 45 10 1 \n 1 11 55 165 330 462 462 330 165 55 11 1 \n 1 12 66 220 495 792 924 792 495 220 66 12 1 \n 1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1 \n 1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1 \n 1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T16:35:04.490",
"Id": "74765",
"Score": "0",
"body": "Just did this new way... can you explain more of the `map()` function and the `string.format()` function ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T18:24:14.380",
"Id": "74784",
"Score": "1",
"body": "[`map(func, iterable)`](http://docs.python.org/3.2/library/functions.html?highlight=map#map) returns another iterable that is a result of calling the function on each item. For example, `map(str, [1, 2, 3])` produces `[\"1\", \"2\", \"3\"]`. `string.format()` is a bit like the `sprintf()` function in C; it's best just to read the link to the `string.format()` documentation I linked to above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T07:32:53.713",
"Id": "74897",
"Score": "0",
"body": "You don't need `str.format()` after all! I forgot that `str.center()` existed."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T07:45:21.110",
"Id": "43285",
"ParentId": "43223",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "43229",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T15:25:32.113",
"Id": "43223",
"Score": "10",
"Tags": [
"python",
"mathematics",
"python-3.x",
"console",
"formatting"
],
"Title": "Pretty-print Pascal's triangle"
}
|
43223
|
<p>For a very simple databaseless website, I'm using an associative array to store logins like this:</p>
<pre><code>$logins = array(
'user' => 'password',
'user2' => 'password2',
);
</code></pre>
<p>I check login attemps using this code:</p>
<pre><code>$user = strtolower($_POST['username']);
$pass = $_POST['password'];
if(!isset($logins[$user]) or $logins[$user] != $pass){
// failed login
}else{
$_SESSION['username'] = $user;
}
</code></pre>
<p>What would the security vulnerabilities in this be?</p>
|
[] |
[
{
"body": "<p>Storing passwords is a very bad idea; if the source-code somehow leaks or the server gets compromised somehow the passwords will be leaked. Only a <em>hash</em> of the password should be stored - so the code can check for a match but never actually retain the full password longer than required (and not to disk - it should only need to briefly be in memory).</p>\n\n<p>Is the site at least using TLS? If not, replay attacks will likely work.</p>\n\n<p>Is there a reason you're not just using .htpasswd files? </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-26T03:31:15.813",
"Id": "55291",
"ParentId": "43226",
"Score": "5"
}
},
{
"body": "<p>In this response, I assume that you are making a little script for yourself and some friends, i.e. not a large or critical system (e.g. that could delete other files). So you want <em>some</em> security, but not to extreme measures.</p>\n<h2>Passwords in Plain Text</h2>\n<p>As pacifist mentioned, storing passwords as clear text is <em>always</em> a bad idea. If you're just making a little page for yourself and some friends, at least store the passwords hashed with a salt (a random string per user). You could then store your login data the following way:</p>\n<pre><code>$logins = array(\n 'user' => array('hash' => 'ae092...', 'salt' => 'a7#(ad~I$...'),\n);\n</code></pre>\n<p>Checking for a valid login would then be used the following way (using PHP's <code>crypt()</code> to make SHA-256 hashes):</p>\n<pre><code>// Added trim() so something like "user " becomes "user"\n$user = strtolower(trim($_POST['user']));\n$pass = $_POST['password'];\n\nif(isset($logins[$user]) && crypt($logins[$user]['salt'].$pass, 'SHA-256') == $logins[$user]['hash']) {\n // valid login!\n}\n</code></pre>\n<p>This is not much more difficult and already provides you a little more safety. <em>This is still not sufficiently safe for critical applications</em> – you can read <a href=\"https://security.stackexchange.com/a/31846\">all about password hashing</a> over at Security StackExchange. The linked answer covers a lot of aspects and is a great starting point.</p>\n<p>Again, the above code is a simple way of handling logins for a small, <em>non-critical</em> page.</p>\n<p>At the very worst, if you can't be bothered to give an individual salt to every user, add a global prefix/suffix to each password – a so-called <em>pepper</em>. You'll still be better off (preventing online rainbow table look-ups), because it doesn't take any knowledge at all to <a href=\"https://www.google.com/search?q=8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918\" rel=\"noreferrer\">search the SHA-256 hash of "admin"</a> and look up the results. However, searching the hash of <code>admin!OTdf-u23;)(#$@_!#Rlf</code> (where the text after admin would be your pepper) will most likely not return any results.</p>\n<h2>Brute Force</h2>\n<p>OK, but now let's assume your hashes/passwords don't ever leak. So, if I would want access, how would I proceed? I would just send probable passwords to the login form. You have no protection against abusive login attempts, so I can try as many passwords as I please. After the plain text storage of passwords, this is your weakest point, IMHO.</p>\n<p>If it's a small, trivial script, it's probably not worth implementing anything to block that as no one will bother, though if there could be some substantial damage, it might be best to block invalid login attempts after a while. You know how things are <em>now</em>, but maybe you'll pick a fight with the wrong guy later on, or an automatic script will pick up on your login form.</p>\n<p>A quick & dirty blocking mechanism is to keep an array of the number of invalid login attempts per IP address (<code>$logins = array('127.0.0.1' => 3)</code>). Once it reaches a certain number, you either block it permanently (if it's a small script and your friend is affected, he'll contact you) or you log the time and block it for a day or so.</p>\n<h2>Issues with Warnings</h2>\n<p>I recommend you output all warnings at least during development; this could help you find some issues. This can be done by adding <code>error_reporting(E_ALL)</code> to your login page.</p>\n<p>A few issues that will arise is the direct reference to $_POST without checking first; use <code>isset($_POST['user'])</code> to see if the key you're asking for exists in the first place.</p>\n<p>If you want to take it a step further, you could also do a check with <code>is_scalar()</code>, as sending an array as <code>$_POST['pass']</code> will make <code>crypt()</code> issue a warning. This is something a lot of websites tend not to cover, which allows an attacker to find out the full path of your server and possibly the inner workings of your scripts (say, if the error comes from /hidden_include_folder/validator.php, this file will be shown in the error).</p>\n<h2>Working with Files</h2>\n<p>You need to account for concurrent file modifications. Again, if this is just a little fun script, it's a risk you can take, but anything of substantial size and/or importance should really be handled with a database like MySQL, which accounts for concurrent modifications and handles them for you automatically.</p>\n<p>Note that keeping data in a file does not scale well; if you think the amount of data you're storing could grow a lot, consider setting up a database. I've seen it happen more than a few times that PHP reads a large file, then runs out of memory while writing to it, and the file ends up being empty – not a fun situation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-26T09:51:29.263",
"Id": "96900",
"Score": "1",
"body": "Nice answer! Welcome to [codereview.se], feel free to visit the \"regulars\" in [chat]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-26T11:08:23.760",
"Id": "96922",
"Score": "0",
"body": "Very good answer! +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-26T18:47:41.393",
"Id": "97037",
"Score": "0",
"body": ">1 MB is considered large for PHP?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-26T19:14:57.503",
"Id": "97045",
"Score": "0",
"body": "@JAB Background: I did a lot of patching for a CMS written in PHP that used flat files only. Things would start to be on the dangerous side after one or two megabytes for some users. However, I just did some tests on my machine and even processing a file of 23 MB wasn't even _slow_, so maybe concurrent modifications were always to blame, and never file size. Interesting!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-26T19:26:12.050",
"Id": "97048",
"Score": "0",
"body": "@ljacqu That would make more sense, then. I haven't really used PHP before, but 1MB seems a bit small in general for running into lack-of-memory issues unless you're operating off an embedded system or are, for some crazy reason, storing the entire contents of the file on a size-limited stack."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-26T09:10:54.113",
"Id": "55307",
"ParentId": "43226",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T16:06:31.890",
"Id": "43226",
"Score": "4",
"Tags": [
"php",
"array",
"security",
"form"
],
"Title": "Checking login from associative array vulnerabilities"
}
|
43226
|
<p>I am using the following code for calculating ranking and it is working great for not large data. But when it comes to large data, processing time takes almost a minute. Please can anyone suggest a better way or atleast a faster way to put the same mysql statement?</p>
<pre><code> SELECT id, Names, TOTALSCORE, Rank
FROM
(
SELECT t.*,
IF(@p = TOTALSCORE, @n, @n := @n + 1) AS Rank,
@p := TOTALSCORE
FROM(
SELECT id, Names,SUM(score) TOTALSCORE
FROM exam e1, (SELECT @n := 0, @p := 0) n
WHERE NOT EXISTS(
SELECT null FROM exam e2
WHERE e1.id = e2.id
AND e2.score/e2.Fullmark < 0.33
)
GROUP BY id
ORDER BY TOTALSCORE DESC
) t
) r
;
</code></pre>
<p>Fiddle is here:<a href="http://www.sqlfiddle.com/#!2/50ef8/4" rel="nofollow">ranking with ties and skipping rows on passmark condition</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T18:06:36.520",
"Id": "74596",
"Score": "0",
"body": "Can we assume that id is indexed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T18:15:46.390",
"Id": "74597",
"Score": "0",
"body": "Yes, we can assume that id is indexed."
}
] |
[
{
"body": "<p>First, let's confirm the intention of your query. According to my interpretation, it ranks students according to the sum of their exam scores, best students first, but disqualifying anyone who has ever failed an exam by scoring lower than 33%. (Why does the disqualification rule exist? Does failing an exam allow a student to take it again? If so, a fairer rule would be to disqualify students who have retaken an exam.)</p>\n\n<p>Next, I would like to point out problems in your schema. You included this table definition in your SQL Fiddle, which you should also have stated within the question itself (it's essential information for reviewing your code):</p>\n\n<pre><code>CREATE TABLE exam\n (`id` int, `Names` varchar(6), `Subject` varchar(8), `Exam` varchar(5), `Fullmark` int, `score` int)\n;\n</code></pre>\n\n<p>Naming the first column <code>id</code> is weird and tricky: at first glance, one would expect the <code>id</code> column of an <code>exam</code> table to identify an exam, but you use it as a student ID.</p>\n\n<p>That oddity is an indication of another anomaly: your schema is denormalized. There is a <em>M</em> : <em>N</em> relationship between students and exam scores. (Each student takes <em>M</em> exams; each exam is taken by <em>N</em> students.) There should be three tables:</p>\n\n<pre><code>CREATE TABLE student\n( id SERIAL PRIMARY KEY\n, `Names` VARCHAR(6) NOT NULL -- Probably too short\n);\n\n-- Using the long name to distinguish it from your exam table\nCREATE TABLE examination\n( id SERIAL PRIMARY KEY\n, `Subject` VARCHAR(8) NOT NULL\n, `Type` VARCHAR(5) NOT NULL\n, `Fullmark` INTEGER NOT NULL\n);\n\nCREATE TABLE examination_score\n( student_id INTEGER NOT NULL\n, examination_id INTEGER NOT NULL\n, `Score` INTEGER NOT NULL\n, FOREIGN KEY (student_id) REFERENCES student (id)\n, FOREIGN KEY (examination_id) REFERENCES examination (id)\n);\n</code></pre>\n\n<p>To populate the new tables, you would use the query</p>\n\n<pre><code>INSERT INTO student\n SELECT DISTINCT `id`, `Names`\n FROM exam;\n\nINSERT INTO examination (`Subject`, `Type`, `Fullmark`)\n SELECT DISTINCT `Subject`, `Exam`, `Fullmark`\n FROM exam\n ORDER BY `Subject`, `Exam`;\n\nINSERT INTO examination_score\n SELECT exam.id AS student_id\n , examination.id AS examination_id\n , exam.score AS score\n FROM exam\n INNER JOIN examination\n ON examination.`Subject` = exam.`Subject`\n AND examination.`Type` = exam.`Exam`\n AND examination.`Fullmark` = exam.`Fullmark`;\n</code></pre>\n\n<p>Notice that you misspelled \"Science\" in two different ways, as well as \"Mizo\" (whatever that is). The <code>PRIMARY KEY</code> constraint caught the misspelling of the student names \"Lawma\" and \"Thanga\".</p>\n\n<p>Verify that this query works:</p>\n\n<pre><code>SELECT student_id\n , SUM(`Score`) AS TOTALSCORE\n FROM examination_score AS e\n WHERE NOT EXISTS (\n SELECT dq.student_id\n FROM examination_score AS dq\n INNER JOIN examination\n ON examination.id = dq.examination_id\n WHERE\n dq.`Score` / `Fullmark` < 0.33\n AND dq.student_id = e.student_id\n )\n GROUP BY student_id\n ORDER BY TOTALSCORE DESC;\n</code></pre>\n\n<p>Compare its performance against the equivalent query based on the denormalized schema:</p>\n\n<pre><code>SELECT id, Names,SUM(score) TOTALSCORE\n FROM exam e1\n WHERE NOT EXISTS(\n SELECT null FROM exam e2\n WHERE e1.id = e2.id\n AND e2.score/e2.Fullmark < 0.33\n )\n GROUP BY id\n ORDER BY TOTALSCORE DESC;\n</code></pre>\n\n<p>My guess is that the revised query will be faster. The root cause is that you didn't have an index on the <code>id</code> column of your <code>exam</code> table. You could just create the index, but normalizing the schema and writing the appropriate <code>PRIMARY KEY</code> constraints would implicitly create such indexes, and is better practice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T18:42:42.187",
"Id": "74600",
"Score": "0",
"body": "Thanks very much for very useful information. In my real application, I used id, regd (for student id) which is a foreign key. I just don't want to include a student who fails in one or more subjects in my ranking. So those students who does not get ranking and are skipped. Students who pass in all subject (scoring more than 33 in each subject) get ranking. And you didn't include ranking ties in your alternative solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T18:48:08.540",
"Id": "74601",
"Score": "2",
"body": "When asking questions, please post your real code with enough details (such as indexes and foreign keys). It's a waste of time for both you and me to review a stripped-down example that ends up being irrelevant. (I understand the need to remove student data to respect their privacy, but your code should be real code.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T18:19:27.383",
"Id": "43234",
"ParentId": "43227",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "43234",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T16:23:07.593",
"Id": "43227",
"Score": "1",
"Tags": [
"performance",
"mysql",
"sql"
],
"Title": "Performance problem: Ranking with ties and skipping rows on passmark condition"
}
|
43227
|
<p>As part of learning C++, with special emphasis on C++11, I wanted to implement the equivalent of Boost's Variant (located <a href="http://www.boost.org/doc/libs/1_55_0/doc/html/variant.html">here</a>). My code is available at <a href="https://github.com/sonyandy/cpp-experiments/blob/master/include/wart/variant.hpp">variant.hpp</a>, with the current version given below.</p>
<p>How can <code>std::aligned_storage</code> be used portably? My current solution makes probably non-portable use of <code>static_cast</code>, though if it is portable, that information would be very valuable. The particular code is similar to <code>*static_cast<T*>(static_cast<void*>(&value))</code>, for <code>value</code> of type <code>typename std::aligned_storage<...>::type</code> (where <code>...</code> is not meant to indicate variadic templates).</p>
<p>I make some use of <code>static_assert</code>. In this particular use, would SFINAE be better? I understand SFINAE can be used to prune out overloads from the set of viable functions, but where I use <code>static_assert</code> I assume there would be only one viable function, though I would find valuable any examples of cases where there is more than one viable function.</p>
<p>I made much use of <code>std::forward</code>. Is it possible to get by with fewer uses?</p>
<p>I made use of <code>std::enable_if</code> on one of the constructor overloads to ensure that it would only be used when a move is intended (see <code>variant(U&& value, typename detail::variant::enable_if_elem<U, T...>::type* = nullptr, typename detail::variant::enable_if_movable<U>::type* = nullptr)</code>). Without both of the <code>enable_if</code>s, this contructor would be used when the copy constructor <code>variant(variant const&)</code> is instead intended, even though the former results in an eventual compiler error. Is there a better way to force this behavior? One solution I tried was including <code>variant(variant&)</code> as an overload that just delgates to <code>variant(variant const& rhs)</code> - it would be selected over <code>variant(U&&)</code>, while <code>variant(U&&)</code> is preferred over <code>variant(variant const&)</code> by the overload rules. What is the general best practice when using <code>T&&</code> for some newly introduced <code>T</code> when move semantics, instead of a universal reference, are intended?</p>
<p>I still need to add multivisitors, though I am having some trouble with this in the general case (using variadic templates). Something interesting that came up when implementing the <code>variant</code> class was implicit conversions between <code>variant</code>s that only involved rearranging the template arguments or where the lvalue template arguments are a superset of the rvalue template arguments.</p>
<p>Any and all comments, questions, or advice is very much appreciated.</p>
<pre><code>#ifndef WART_VARIANT_HPP
#define WART_VARIANT_HPP
#include <type_traits>
#include <utility>
#include "math.hpp"
namespace wart {
template <typename... T>
class variant;
namespace detail {
namespace variant {
template <typename... T>
using variant = wart::variant<T...>;
template <typename T>
using is_movable = typename std::integral_constant
<bool,
std::is_rvalue_reference<T&&>::value && !std::is_const<T>::value>;
template <typename T, typename U = void>
using enable_if_movable = std::enable_if<is_movable<T>::value, U>;
template <typename... Types>
using union_storage = typename std::aligned_storage
<math::max_constant<std::size_t,
sizeof(Types)...>::value,
math::lcm_constant<std::size_t,
std::alignment_of<Types>::value...>::value>::type;
template <typename... Types>
using union_storage_t = typename union_storage<Types...>::type;
template <typename Elem, typename... List>
struct elem;
template <typename Head, typename... Tail>
struct elem<Head, Head, Tail...>: std::true_type {};
template <typename Elem, typename Head, typename... Tail>
struct elem<Elem, Head, Tail...>: elem<Elem, Tail...>::type {};
template <typename Elem>
struct elem<Elem>: std::false_type {};
template <typename Elem, typename... List>
struct elem_index;
template <typename Head, typename... Tail>
struct elem_index<Head, Head, Tail...>:
std::integral_constant<int, 0> {};
template <typename Elem, typename Head, typename... Tail>
struct elem_index<Elem, Head, Tail...>:
std::integral_constant<int, elem_index<Elem, Tail...>::value + 1> {};
template <bool... List>
struct all;
template <>
struct all<>: std::true_type {};
template <bool... Tail>
struct all<true, Tail...>: all<Tail...>::type {};
template <bool... Tail>
struct all<false, Tail...>: std::false_type {};
template <typename Elem, typename... List>
using enable_if_elem = std::enable_if<elem<Elem, List...>::value>;
template <typename F, typename... ArgTypes>
using common_result_of =
std::common_type<typename std::result_of<F(ArgTypes)>::type...>;
struct destroy {
template <typename T>
void operator()(T&& value) {
using type = typename std::remove_reference<T>::type;
std::forward<T>(value).~type();
}
};
struct copy_construct {
void* storage;
template <typename T>
void operator()(T const& value) {
new (storage) T(value);
}
};
template <typename... T>
struct copy_construct_index {
void* storage;
template <typename U>
int operator()(U const& value) {
new (storage) U(value);
return elem_index<U, T...>::value;
}
};
struct move_construct {
void* storage;
template <typename T>
typename enable_if_movable<T>::type operator()(T&& value) {
new (storage) T(std::move(value));
}
};
template <typename... T>
struct move_construct_index {
void* storage;
template <typename U>
typename enable_if_movable<U, int>::type operator()(U&& value) {
new (storage) U(std::move(value));
return elem_index<U, T...>::value;
}
};
struct copy_assign {
void* storage;
template <typename T>
void operator()(T const& value) {
*static_cast<T*>(storage) = value;
}
};
template <typename... T>
struct copy_assign_reindex {
variant<T...>& variant;
template <typename U>
void operator()(U const& value) {
if (variant.which_ == elem_index<U, T...>::value) {
*static_cast<U*>(static_cast<void*>(&variant.storage_)) = value;
} else {
variant.accept(destroy{});
new (&variant.storage_) U(value);
variant.which_ = elem_index<U, T...>::value;
}
}
};
struct move_assign {
void* storage;
template <typename T>
typename enable_if_movable<T>::type operator()(T&& value) {
*static_cast<T*>(storage) = std::move(value);
}
};
template <typename... T>
struct move_assign_reindex {
variant<T...>& variant;
template <typename U>
typename enable_if_movable<U>::type operator()(U&& value) {
if (variant.which_ == elem_index<U, T...>::value) {
*static_cast<U*>(static_cast<void*>(&variant.storage_)) = std::move(value);
} else {
variant.accept(destroy{});
new (&variant.storage_) U(std::move(value));
variant.which_ = elem_index<U, T...>::value;
}
}
};
}
}
template <typename... T>
class variant {
int which_;
detail::variant::union_storage_t<T...> storage_;
public:
template <typename F>
using result_of = detail::variant::common_result_of<F, T...>;
template <typename F>
using result_of_t = typename result_of<F>::type;
template <typename U>
variant(U const& value,
typename detail::variant::enable_if_elem<U, T...>::type* = nullptr):
which_{detail::variant::elem_index<U, T...>::value} {
new (&storage_) U(value);
}
template <typename U>
variant(U&& value,
typename detail::variant::enable_if_elem<U, T...>::type* = nullptr,
typename detail::variant::enable_if_movable<U>::type* = nullptr):
which_{detail::variant::elem_index<U, T...>::value} {
new (&storage_) U(std::move(value));
}
variant(variant const& rhs):
which_{rhs.which_} {
rhs.accept(detail::variant::copy_construct{&storage_});
}
template <typename... U>
variant(variant<U...> const& rhs,
typename std::enable_if<
detail::variant::all<detail::variant::elem<U, T...>::value...>::value
>::type* = nullptr):
which_{rhs.accept(detail::variant::copy_construct_index<T...>{&storage_})} {}
variant(variant&& rhs):
which_{rhs.which_} {
std::move(rhs).accept(detail::variant::move_construct{&storage_});
}
template <typename... U>
variant(variant<U...>&& rhs,
typename std::enable_if<
detail::variant::all<detail::variant::elem<U, T...>::value...>::value
>::type* = nullptr):
which_{std::move(rhs).accept(detail::variant::move_construct_index<T...>{&storage_})} {}
~variant() {
accept(detail::variant::destroy{});
}
variant& operator=(variant const& rhs) & {
using namespace detail::variant;
static_assert(all<std::is_nothrow_copy_constructible<T>::value...>::value,
"all template arguments T must be nothrow copy constructible in class template variant");
if (this == &rhs) {
return *this;
}
if (which_ == rhs.which_) {
rhs.accept(copy_assign{&storage_});
} else {
accept(destroy{});
rhs.accept(copy_construct{&storage_});
which_ = rhs.which_;
}
return *this;
}
template <typename... U>
variant& operator=(variant<U...> const& rhs) & {
using namespace detail::variant;
static_assert(all<std::is_nothrow_copy_constructible<T>::value...>::value,
"all template arguments T must be nothrow copy constructible in class template variant");
rhs.accept(copy_assign_reindex<T...>{*this});
return *this;
}
variant& operator=(variant&& rhs) & {
using namespace detail::variant;
static_assert(all<std::is_nothrow_move_constructible<T>::value...>::value,
"all template arguments T must be nothrow move constructible in class template variant");
if (this == &rhs) {
return *this;
}
if (which_ == rhs.which_) {
std::move(rhs).accept(move_assign{&storage_});
} else {
accept(detail::variant::destroy{});
std::move(rhs).accept(move_construct{&storage_});
which_ = rhs.which_;
}
return *this;
}
template <typename... U>
variant& operator=(variant<U...>&& rhs) & {
using namespace detail::variant;
static_assert(all<std::is_nothrow_copy_constructible<T>::value...>::value,
"all template arguments T must be nothrow copy constructible in class template variant");
std::move(rhs).accept(move_assign_reindex<T...>{*this});
return *this;
}
template <typename F>
result_of_t<F> accept(F&& f) const& {
using namespace detail::variant;
using call = result_of_t<F&&> (*)(F&& f, union_storage_t<T...> const&);
static call calls[] {
[](F&& f, union_storage_t<T...> const& value) {
return std::forward<F>(f)(*static_cast<T const*>(static_cast<void const*>(&value)));
}...
};
return calls[which_](std::forward<F>(f), storage_);
}
template <typename F>
result_of_t<F> accept(F&& f) & {
using namespace detail::variant;
using call = result_of_t<F&&> (*)(F&& f, union_storage_t<T...>&);
static call calls[] {
[](F&& f, union_storage_t<T...>& value) {
return std::forward<F>(f)(*static_cast<T*>(static_cast<void*>(&value)));
}...
};
return calls[which_](std::forward<F>(f), storage_);
}
template <typename F>
result_of_t<F> accept(F&& f) && {
using namespace detail::variant;
using call = result_of_t<F> (*)(F&& f, union_storage_t<T...>&&);
static call calls[] {
[](F&& f, union_storage_t<T...>&& value) {
return std::forward<F>(f)(std::move(*static_cast<T*>(static_cast<void*>(&value))));
}...
};
return calls[which_](std::forward<F>(f), std::move(storage_));
}
friend
struct detail::variant::copy_assign_reindex<T...>;
friend
struct detail::variant::move_assign_reindex<T...>;
};
}
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T17:39:13.187",
"Id": "74591",
"Score": "0",
"body": "Also per our help center, this is not the site for code that doesn't do what it is supposed to do. Does your code **work**?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T21:17:31.127",
"Id": "74625",
"Score": "4",
"body": "If by \"work\", you mean, \"does it compile?\", it compiles with clang++ version 3.3, but does not compile with g++ version 4.8.2 due to an interaction between parameter packs and lambdas. The CMakeLists.txt file selects clang++ unconditionally. If by \"work\", you mean \"is it portable?\", then no, it may not be portable. This is due to the way I use `std::aligned_storage`. Advice on portable use of the associated `type` would be very helpful. If by \"work\", you mean \"does it satisfy the original intent?\", the answer is yes, though I would very much like stylistic and best-practice advice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T01:47:54.603",
"Id": "75133",
"Score": "0",
"body": "The use of `std::forward` looks fine, I can't see any place where you could not use it. I prefer `static_assert` as it allows you to give better error messages. Portability is potentially a problem, as there is no guarantee all pointers are aligned on the same boundary (so `void *` and `T*` may have different requirements), but this would be very unusual these days. I don't know how boost gets around this, or if they just ignore it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T03:14:30.237",
"Id": "75144",
"Score": "0",
"body": "@Yuushi, first, thank you for taking the time to review this. I think they just ignore any non-portable stuff (http://www.boost.org/doc/libs/1_55_0/boost/variant/detail/cast_storage.hpp). I did find a portable solution (https://github.com/sonyandy/cpp-experiments/blob/master/include/wart/union/detail/union.hpp) that uses a technique similar to what `std::tuple` uses, but with `union`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T03:21:40.773",
"Id": "75145",
"Score": "0",
"body": "No problem. The only other thing I'd add is that the file seems a bit \"busy\" and there are things in it that are potentially useful in their own right (traits that you've defined like `is_movable` and `enable_if_movable`, for example) that could potentially live somewhere else. Unfortunately, the number of C++ reviewers around here with the knowledge needed to give you good feedback on this is probably in the single digits, as the code is fairly complex."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-13T05:13:17.730",
"Id": "151029",
"Score": "0",
"body": "What for do you use ref-qualifier for assignment and move-assignment operators?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-08T04:49:53.653",
"Id": "175656",
"Score": "0",
"body": "When I wrote [my implementation (GPL3)](https://github.com/themanaworld/tmwa/blob/master/src/sexpr/variant.hpp), I wrote a separate `Union<T...>` template first and then made `Variant<T...>` on top of that. I didn't use `std:aligned_storage` at all, I'm not sure if it existed at the time (boost variant certainly didn't support C++11 then). [The actual storage is here](https://github.com/themanaworld/tmwa/blob/master/src/sexpr/union.hpp#L58) - it's just a union with empty ctors/dtors to allow non-POD types."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-08T04:56:01.727",
"Id": "175657",
"Score": "0",
"body": "That said, one major failure of my implementation is that I didn't demand `noexcept` move constructors to satisfy the never-empty guarantee."
}
] |
[
{
"body": "<p>There's a lot here, so I'm going to split my review into pieces. I want to start by just focusing on the metafunction section. Metafunctions may be short, but they're very powerful and important to get right - but in terms of correctness and usefulness.</p>\n\n<p>To start with:</p>\n\n<pre><code>template <typename T>\nusing is_movable = typename std::integral_constant\n <bool,\n std::is_rvalue_reference<T&&>::value && !std::is_const<T>::value>;\n\ntemplate <typename T, typename U = void>\nusing enable_if_movable = std::enable_if<is_movable<T>::value, U>;\n</code></pre>\n\n<p>The first one is simply wrong. You're using this metafunction to check if a type is move constructible (in <code>move_construct</code>)... but you're doing this by just checking if it's neither an lvalue reference nor <code>const</code>. You're not actually checking anything relating to move construction. Just because something is an rvalue reference does not mean that you can move from it. And just because something is an lvalue reference does not mean that you cannot. Consider two simple classes:</p>\n\n<pre><code>struct No {\n A(A&& ) = delete;\n};\n\nstruct Yes { };\n</code></pre>\n\n<p>As the name suggests, <code>No</code> is not move constructible. Your metafunction says it is. Also, <code>Yes&</code> is move constructible but your metafunction says no. </p>\n\n<p>The correct implementation would be to simply use the standard type trait <a href=\"http://en.cppreference.com/w/cpp/types/is_move_constructible\" rel=\"nofollow\"><code>std::is_move_constructible</code></a>.</p>\n\n<p>Secondly, the alias there is questionable. Typically, we'd use aliases to <em>avoid</em> having to write the <code>typename ::type</code> cruft. You're not doing that, and the resulting call isn't that much more concise. Compare:</p>\n\n<pre><code>typename enable_if_movable<T>::type // yours with alias\nstd::enable_if_t<is_moveable<T>::value> // just using enable_if without alias\nstd::enable_if_t<std::is_move_constructible<T>::value> // just stds\n</code></pre>\n\n<p>I would prefer the last version personally. Note that I'm using the C++14 alias here. If you don't have a C++14 compiler, it is absolutely worth it to start your metafunction library with all of them. They are simply to write:</p>\n\n<pre><code>template <bool B, typename T = void>\nusing enable_if_t = typename std::enable_if<B, T>::type;\n</code></pre>\n\n<p>Moving onto:</p>\n\n<pre><code>template <typename Elem, typename... List>\nstruct elem;\n</code></pre>\n\n<p>There is no way that anybody will know what <code>elem</code> does here. I didn't until I read the implementation. A much better name for this would be <code>contains</code>. But I'll get back to implementation in a moment.</p>\n\n<p>First, let's start with:</p>\n\n<pre><code>template <bool... List>\nstruct all;\n</code></pre>\n\n<p><code>all</code> is super useful. So are its close relatives <code>any</code> and <code>none</code>. The way you wrote <code>all</code> is fine and works, but doesn't make it easier to write the other two. A good way of writing these out is to use @Columbo's <code>bool_pack</code> trick:</p>\n\n<pre><code>template <bool...> struct bool_pack;\n\ntemplate <bool f, bool... bs>\nusing all_same = std::is_same<bool_pack<f, bs...>, bool_pack<bs..., f>>;\n</code></pre>\n\n<p>That's just your helper. You can use that to implement all the rest easily:</p>\n\n<pre><code>template <bool... bs>\nusing all_of = all_same<true, bs...>;\n\ntemplate <bool... bs>\nusing none_of = all_same<false, bs...>;\n\ntemplate <bool... bs>\nusing any_of = std::integral_constant<bool, !none_of<bs...>::value>;\n</code></pre>\n\n<p>And once we have that, we can reimplement <code>contains</code> as a one-liner:</p>\n\n<pre><code>template <typename Elem, typename... List>\nusing contains = any_of<std::is_same<Elem, List>::value...>;\n</code></pre>\n\n<p>Similarly to before, I don't see the value in <code>enable_if_elem</code>. And <code>common_result_of</code> should take the <em>type</em>, not just yield the metafunction:</p>\n\n<pre><code>template <typename F, typename... ArgTypes>\nusing common_result_of =\n std::common_type_t<std::result_of_t<F(ArgTypes)>::...>;\n</code></pre>\n\n<p>Although it's more readabile to just stick that in your <code>variant</code> itself:</p>\n\n<pre><code>// no need to use anything in detail::, unless you need to \n// write your own aliases for common_type_t and result_of_t\ntemplate <typename F>\nusing result_of = std::common_type_t<std::result_of_t<F(T)>...>;\n</code></pre>\n\n<p>Now onto the usage. Throughout, you use these metafunctions in the return type:</p>\n\n<pre><code>template <typename T>\ntypename enable_if_movable<T>::type operator()(T&& value);\n</code></pre>\n\n<p>Or as a dummy pointer:</p>\n\n<pre><code>template <typename U>\nvariant(U const& value,\n typename detail::variant::enable_if_elem<U, T...>::type* = nullptr)\n</code></pre>\n\n<p>But in both cases, I find it a lot easier to parse complex template expressions if you put the SFINAE logic as an unnamed final template parameter:</p>\n\n<pre><code>template <typename T,\n typename = std::enable_if_t<std::is_move_constructible<T>::value>\n >\nvoid operator()(T&& value);\n\ntemplate <typename U,\n typename = std::enable_if_t<contains<U, T...>::value>\n >\nvariant(U const& value);\n</code></pre>\n\n<p>The consistency helps understanding too. The dummy pointer argument is a confusing hack leftover from C++03. There's no need for it anymore. Especially when you need <em>two</em> dummy pointers:</p>\n\n<pre><code> template <typename U,\n typename = std::enable_if_t<contains<U, T...>::value &&\n std::is_move_constructible<U>::value>\n >\n variant(U&& value);\n</code></pre>\n\n<p>Side note on this guy. It doesn't actually do what you want. This isn't an arbitrary rvalue reference - it's a forwarding reference. In fact, we can even combine the two constructors here in one go:</p>\n\n<pre><code>template <typename U,\n typename V = std::remove_reference_t<U>,\n typename = std::enable_if_t<contains<V, T...>::value &&\n std::is_constructible<V, U&&>::value>\n >\nvariant(U&& value)\n: which_{elem_index<V, T...>::value}\n{\n new (&storage_) V(std::forward<U>(value)); \n}\n</code></pre>\n\n<p>Note that this also solves another problem with your code - namely that you never check if a class is copy constructible. What if you wanted to stick something like <code>unique_ptr</code> in your variant. Move constructible, but not copy constructible - but you <em>never</em> checked that in your code. Important - otherwise your users would just get cryptic error messages.</p>\n\n<p>I think this concludes the metafunction portion. I will write a review of <code>variant</code> itself a bit later. Hope you find this helpful. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-17T11:56:47.457",
"Id": "97226",
"ParentId": "43230",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T17:26:44.443",
"Id": "43230",
"Score": "11",
"Tags": [
"c++",
"c++11",
"template-meta-programming",
"variant-type"
],
"Title": "Clone of Boost Variant"
}
|
43230
|
<p>I hacked together this little <a href="http://data.stackexchange.com/codereview/query/172183/more-than-one-answer-by-the-same-user">query on the Data Explorer</a></p>
<p>The query finds questions where an answerer has posted two or more answers (which in itself is not necessarily a bad thing), it gives you the link to the question, information about which user posted the multiple answers, and how many answers by that user that was posted.</p>
<pre><code>select question.Id as [Post Link],
answer.owneruserid as [User Link],
count(answer.id) as answers
from Posts question
join Posts answer on (answer.parentid = question.id)
where answer.OwnerUserId != 0
group by answer.OwnerUserId,
question.id, answer.owneruserid
having count(answer.id) >= 2
order by answers desc
</code></pre>
<p>The last two <code>group by</code> clauses seem quite useless to me in a way, as they will always only be one unique version of them after grouping by <code>answer.OwnerUserId</code>. My experience from mySQL is that it simply picks a seemingly random value if not grouping by it, but in the SEDE I get this result:</p>
<blockquote>
<p>Column 'Posts.Id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.</p>
</blockquote>
<ul>
<li>Is there a way to remove these extra <code>GROUP BY</code>'s? Or is adding these "the way it's supposed to be done"?</li>
<li>How is this SQL overall, regarding performance, naming, structure, conventions and everything?</li>
<li>Are there any alternative ways to rewrite this query?</li>
</ul>
|
[] |
[
{
"body": "<p><strong>General MySQL/MSSQL comparison</strong></p>\n\n<p>In regards to the rules for aggregate functions... you have <code>count(answer.id)</code> as one of your select values. As a consequence, you need a group by.</p>\n\n<p>The group by must consist of every value that is used as part of any non-aggregate select value, or as part of the order-by.</p>\n\n<p>MySQL's handling for this is 'wrong', and SQLServer is 'right'. I have seen MySQL do this, but, in reality, any system with non-deterministic behaviour is broken, and there is no way to make it deterministic unless you do the group-by right.</p>\n\n<p><strong>Columns in the Group By</strong></p>\n\n<p>You only need two columns in the group-by, <code>question.Id</code>, and <code>answers.OwnerUserId</code></p>\n\n<p>You have three columns because you have the <code>answers.OwnerUserId</code> twice... which is pointless.</p>\n\n<p><strong>Other suggestions</strong></p>\n\n<ul>\n<li>You should, in general, use the same capitalization as the database schema for your tables/columns. Even if the database is case-insensitive.</li>\n<li>You should use all the value predicates you can when running SQL queries. For example, in your code, even though the only place where the conditions <code>answer.ParentId = questionid and answer.OwnerUserID != 0</code> happens for questions, and answers, you should also add the predicates <code>question.PostTypeId = 1 and answer.PostTypeId = 2</code> (because that is what really makes a question a question, and an answer an answer).</li>\n</ul>\n\n<p>You should bookmark <a href=\"https://meta.stackexchange.com/questions/2677/database-schema-documentation-for-the-public-data-dump-and-sede\">the SEDE Schema documentation</a>...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T19:35:25.673",
"Id": "74609",
"Score": "2",
"body": "Rather, MySQL is [broken by default](http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html), but can be made sane if you care to configure it with [`ONLY_FULL_GROUP_BY`](http://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_only_full_group_by). _(`SELECT complaint FROM mysql_rants`)_"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T07:29:35.647",
"Id": "74685",
"Score": "0",
"body": "Would there be any difference in doing for example `MIN(question.id)` instead of doing an additional GROUP BY for that column?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T11:18:45.213",
"Id": "74706",
"Score": "0",
"body": "huge difference... That would return all users who have answered more than 1 answer on any questions, and the ID of the first question the user answered"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T18:51:37.970",
"Id": "43237",
"ParentId": "43235",
"Score": "3"
}
},
{
"body": "<p>You don't need to perform any join at all.</p>\n\n<pre><code>SELECT ParentId AS [Post Link]\n , OwnerUserId AS [User Link]\n , COUNT(Id) AS Answers\n FROM Posts\n WHERE\n ParentId IS NOT NULL -- ← Answers only\n AND OwnerUserId <> 0\n GROUP BY ParentId, OwnerUserId\n HAVING Count(id) > 1\n ORDER BY Answers DESC;\n</code></pre>\n\n<p>Your instinct probably tells you that you need a <code>JOIN</code> to obtain the question titles. However, in Stack Exchange Data Explorer, there is a special feature: provide a <code>PostId</code> in a column named <code>[Post Link]</code>, and it will take care of the presentation for you (implicitly doing a <code>JOIN</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T19:00:59.080",
"Id": "43239",
"ParentId": "43235",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "43237",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T18:23:21.997",
"Id": "43235",
"Score": "8",
"Tags": [
"sql",
"stackexchange"
],
"Title": "More than one answer by the same user"
}
|
43235
|
<p>I wrote a little command line nerdy game, which helps you learn the basics of binary numbers. I would be happy to hear your comments:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define CHARSIZE 10
void printbitssimple(int);
void createbitshape(int, char[]);
int guess_num_from_binary(void);
int guess_binary_from_num(void);
int main(void)
{
int play_on = 1;
int ans;
char response[CHARSIZE];
printf("\n\t The BitShape Game \n");
while(play_on)
{
printf("Enter a choice, which game you would like to play:\n");
printf("1 - Guess a number from it's bit shape ...\n");
printf("2 - Given an integer type in it's bit shape ...\n");
printf("3 - Exit the game\n");
fgets(response, CHARSIZE, stdin);
printf("Printing s: %s\n", response);
switch(atoi(response)){
case 1:
printf("Guess a number from it's bit shape ...\n");
/* if correct guess_num_from_binary returns 0 */
ans = guess_num_from_binary();
if (! ans) {
printf("\nThat's Correct!\n");
} else {
printf("\nThat's Wrong! The correct answer is %d\n", ans);
}
break;
case 2:
printf("Play version 2\n");
guess_binary_from_num();
break;
case 3:
printf("Good bye\n");
play_on = 0;
break;
default:
printf("Did not understand your input...\n");
break;
}
}
return 0;
}
/* Print n as a binary number */
void printbitssimple(int n)
{
unsigned int i;
/* printf("The sizeof of n is %ld\n", sizeof(n));*/
i = 1<<(sizeof(n) * 2 - 1);
while (i > 0)
{
if (n & i) /* check if any of the bits of n is not 0 .*/
printf("1");
else
printf("0");
i >>= 1;
}
}
/*similar to printbitssimple, but instead of Printing
* write the bitshape into a string */
void createbitshape(int n, char bitshp[]){
unsigned int i;
/* printf("The sizeof of n is %ld\n", sizeof(n));*/
int c = 0;
i = 1<<(sizeof(n) * 2 - 1);
while (i > 0)
{
if (n & i) /* check if any of the bits of n is not 0 .*/
{
//printf("1");
bitshp[c] = '1';
}
else
{
//printf("0");
bitshp[c] = '0';
}
i >>= 1;
c=c+1;
}
bitshp[c] = '\0';
}
/*show the user a bit shape and compare the input*/
int guess_num_from_binary(void){
int random_num ;
char ans[8];
srand(time(NULL));
random_num = rand() % 100 + 1;
printf("Here is the number:\n");
printbitssimple(random_num);
printf("\nEnter your answer\n");
fgets(ans, 6, stdin);
printf("\n");
printf("you typed: %s \n", ans);
if ( atoi(ans) == random_num ) {
return 0;
} else {
return random_num;
}
}
/*show the user an integer and compare the bit input */
int guess_binary_from_num(void){
int random_num ;
char ans[20];
char bitshp[8];
srand(time(NULL));
random_num = rand() % 100 + 1;
printf("Here is the number: %d\n", random_num);
printf("\nEnter your answer\n");
fgets(ans, 20, stdin);
printf("\n");
createbitshape(random_num, bitshp);
if (! strncmp(bitshp, ans, 8)){
printf("That's correct ! \n");
return 1;
} else {
printf("you typed: %s \n", ans);
printf("the correct answer is : %s \n", bitshp);
printf("\n");
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Things you did well:</h1>\n\n<ul>\n<li><p>When you didn't take in parameters to a function, you declared them <code>void</code>.</p></li>\n<li><p>Good use of comments.</p></li>\n</ul>\n\n<h1>Things you could improve:</h1>\n\n<h3>Refactoring:</h3>\n\n<ul>\n<li><p>You can simplify your function <code>printbitssimple(int n)</code>.</p>\n\n<blockquote>\n<pre><code>void printbitssimple(int n) \n{\n unsigned int i;\n /* printf(\"The sizeof of n is %ld\\n\", sizeof(n));*/\n i = 1<<(sizeof(n) * 2 - 1);\n while (i > 0) \n {\n if (n & i) /* check if any of the bits of n is not 0 .*/\n printf(\"1\");\n else\n printf(\"0\");\n i >>= 1;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Utilize the power of a <code>for</code> loop and the <a href=\"https://en.wikipedia.org/wiki/?%3a\">ternary conditional expression</a>. Note that my method will prepend some additional <code>0</code>'s to the beginning of the output.</p>\n\n<pre><code>void printbitssimple(int n)\n{\n for (unsigned bit = 1u << 31; bit != 0; bit >>= 1)\n {\n putchar((n & bit) ? '1' : '0');\n }\n}\n</code></pre></li>\n<li><p>You can do the same with your method <code>createbitshape()</code>.</p>\n\n<blockquote>\n<pre><code>void createbitshape(int n, char bitshp[]){\n unsigned int i;\n /* printf(\"The sizeof of n is %ld\\n\", sizeof(n));*/\n int c = 0;\n i = 1<<(sizeof(n) * 2 - 1);\n\n while (i > 0) \n {\n if (n & i) /* check if any of the bits of n is not 0 .*/\n {\n //printf(\"1\");\n bitshp[c] = '1';\n }\n else\n {\n //printf(\"0\");\n bitshp[c] = '0';\n }\n i >>= 1;\n c=c+1;\n }\n bitshp[c] = '\\0';\n}\n</code></pre>\n</blockquote>\n\n<p>Here's my implementation.</p>\n\n<pre><code>void createbitshape(int n, char bitshp[])\n{\n int c = 0;\n for (unsigned bit = 1u << 31; bit != 0; bit >>= 1, c++)\n {\n bitshp[c] = ((n & bit) ? '1' : '0');\n }\n bitshp[c] = '\\0';\n}\n</code></pre></li>\n</ul>\n\n<h3>Syntax/Styling:</h3>\n\n<ul>\n<li><p>Use <code>puts()</code> instead of <code>printf()</code> when you aren't formatting a string.</p>\n\n<blockquote>\n<pre><code>printf(\"Here is the number:\\n\");\n</code></pre>\n</blockquote>\n\n<pre><code>puts(\"Here is the number:\");\n</code></pre></li>\n<li><p>You have some superfluous space in your code.</p>\n\n<blockquote>\n<pre><code>int main(void) \n{\n\nint play_on = 1;\nint ans;\nchar response[CHARSIZE];\n\n\nprintf(\"\\n\\t The BitShape Game \\n\");\n</code></pre>\n</blockquote>\n\n<p>I am all for space, but to an extent. Use only one space between your separate \"blocks\" of code.</p></li>\n</ul>\n\n<h3>Variables:</h3>\n\n<ul>\n<li><p><em>Always</em> initialize variables.</p>\n\n<blockquote>\n<pre><code>int random_num;\nchar ans[20];\n</code></pre>\n</blockquote>\n\n<p>Non-static variables (local variables) are <em>indeterminate</em>. Reading them prior to assigning a value results in undefined behavior.</p>\n\n<pre><code>int random_num = 0;\nchar ans[20] = {0};\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T19:28:01.673",
"Id": "43242",
"ParentId": "43238",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "43242",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T18:54:56.210",
"Id": "43238",
"Score": "5",
"Tags": [
"c",
"game"
],
"Title": "Binary numbers game"
}
|
43238
|
<p>AWK is an interpreted programming language designed for text processing and typically used as a data extraction and reporting tool. It is a standard feature of most Unix-like operating systems. Awk was originally developed by Alfred Aho, Brian Kernighan and Peter Weinberger in 1977 and updated in 1985.</p>
<p>When asking questions about data processing using awk, please include complete input and desired output.</p>
<h3>Some frequently occurring themes</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/314384/parse-csv-file-using-gawk">Parsing CSV with awk</a></li>
<li><a href="http://stackoverflow.com/questions/2222150/extraction-of-data-from-a-simple-xml-file">Processing HTML/XML with awk</a></li>
<li><a href="http://stackoverflow.com/questions/3528659/shell-variable-interpreted-wrongly-in-awk">Using shell variables in awk</a></li>
</ul>
<h3>Books</h3>
<ul>
<li><a href="http://cm.bell-labs.com/cm/cs/awkbook/" rel="nofollow">The AWK Programming Language</a> by Aho, Kernighan & Weinberger</li>
<li><a href="http://www.oreilly.com/catalog/awkprog3" rel="nofollow">Effective AWK, 3rd edition</a> by Robbins (see 'The GNU AWK Users Guide' below)</li>
<li><a href="http://www.oreilly.com/catalog/sed2" rel="nofollow">Sed & Awk, 2nd edition</a> by Dougherty & Robbins </li>
</ul>
<h3>Resources</h3>
<ul>
<li><a href="http://awk.info" rel="nofollow">Awk.Info</a></li>
<li><a href="http://www.gnu.org/software/gawk/manual/" rel="nofollow">The GNU Awk User's Guide</a></li>
<li><a href="http://www.opengroup.org/onlinepubs/9699919799/utilities/awk.html" rel="nofollow">POSIX specification of awk</a></li>
<li><a href="http://backreference.org/2010/02/10/idiomatic-awk/" rel="nofollow">Idiomatic awk</a></li>
</ul>
<h3>Related tags</h3>
<ul>
<li><a href="/questions/tagged/sed" class="post-tag" title="show questions tagged 'sed'" rel="tag">sed</a> (A kindred tool often mentioned in the same breath)</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T21:03:55.110",
"Id": "43250",
"Score": "0",
"Tags": null,
"Title": null
}
|
43250
|
AWK is an interpreted programming language designed for text processing and typically used as a data extraction and reporting tool.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T21:03:55.110",
"Id": "43251",
"Score": "0",
"Tags": null,
"Title": null
}
|
43251
|
<p>I'm learning Python (coming from Java) so I decided to write KMeans as a practice for the language. However I want to see how could one improve the code and making it shorter and yet readable. I still find the code rather long. Also if you have comments regarding conventions or proper practices, I would really appreciate it.</p>
<pre><code>import numpy as np
from numpy import linalg as LA
def main():
#data = np.arange(20).reshape( (4,5) )
file_name = "/Users/x/Desktop/tst.csv"
with open(file_name) as f:
ncols = len(f.readline().split(","))
data = np.loadtxt(file_name, delimiter=",", usecols=range(0,ncols-1))
kmeans = KMeans()
kmeans.cluster(data, 3, 200)
print kmeans.means
class KMeans:
def __init__(self):
self.means = None
self.data_assignments = None
#data is a 2D Numpy array
def cluster(self, data, numClusters, iterations):
if numClusters < 1:
raise Exception("The number of clusters should be larger than 0.")
if numClusters > data.shape[0]:
raise Exception("The number of clusters is beyond the number of rows.")
#Pick random means
randomMeansIndices = np.random.choice( range( data.shape[0] ),
size=numClusters, replace=False )
for i in randomMeansIndices:
if self.means is not None:
self.means = np.vstack( ( self.means, data[ i ] ) )
else:
self.means = data[ i ]
for iteration in xrange(iterations):
#Data assignment
self.data_assignments = {}
for row in data:
distances = {}
meanID = 0
for mean in self.means:
distances[meanID] = LA.norm(mean - row)
meanID += 1
nearestMean = min( distances, key=lambda x: distances[x] )
if nearestMean in self.data_assignments:
self.data_assignments[nearestMean] = np.vstack( (self.data_assignments[nearestMean], row) )
else:
self.data_assignments[nearestMean] = row
#Update the means
self.means = None
for mean_data_matrix in self.data_assignments.values():
if mean_data_matrix.ndim == 1:
mean_data_matrix = mean_data_matrix.reshape((1,-1)) #reshape to make it 2D
if self.means is None:
self.means = np.mean( mean_data_matrix, axis=0 ) #the first updated mean vector
else:
newMean = np.mean( mean_data_matrix, axis=0 ) #updated mean vector
self.means = np.vstack( (self.means, newMean) )#add an updated mean
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T02:16:12.680",
"Id": "75366",
"Score": "0",
"body": "From a mathematical standpoint, I don't think you should raise an exception if the number of clusters is not within the number of rows. Zero clusters would result in no clustering, while having `> numRows` clusters would simply result in some of the clusters being empty. Not a cause for error."
}
] |
[
{
"body": "<p>You use <code>vstack</code> a lot to build arrays row by row, with the additional complication of initializing the array variable to <code>None</code>, which needs a special case in your loops then. This complication could be avoided by intializing to zero-height 2D array instead, but in any case repeated <code>vstack</code> use is inefficient because it copies the array every time. Better options are:</p>\n\n<ul>\n<li>Collect rows in a list and <code>vstack</code> the list in the end. Good approach when you don't know the height of the array in advance.</li>\n<li>Initialize array to right size and assign into rows.</li>\n<li>Best of all, create array at once by a vectorized operation.</li>\n</ul>\n\n<p>For example this</p>\n\n<pre><code>self.means = None\nfor i in randomMeansIndices:\n if self.means is not None:\n self.means = np.vstack( ( self.means, data[ i ] ) )\n else:\n self.means = data[ i ]\n</code></pre>\n\n<p>could be done in one line, as you can index arrays with arrays:</p>\n\n<pre><code>self.means = data[randomMeansIndices]\n</code></pre>\n\n<p>This code could avoid the loop</p>\n\n<pre><code>distances = {}\nmeanID = 0\nfor mean in self.means:\n distances[meanID] = LA.norm(mean - row)\n meanID += 1\nnearestMean = min( distances, key=lambda x: distances[x] )\n</code></pre>\n\n<p>by computing all the norms at once (NumPy 1.8 required). <code>argmin</code> gives the index of the minimum.</p>\n\n<pre><code>distances = LA.norm(self.means - row, axis=1)\nnearestMean = np.argmin(distances)\n</code></pre>\n\n<hr>\n\n<p>The <code>KMeans</code> class has no purpose other than holding the result of clustering. The <code>cluster</code> method could be a stand-alone function instead and just <code>return means, data_assignments</code>. If you prefer to access the two items by name, use a <code>collections.namedtuple</code> as the return value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T20:27:29.003",
"Id": "43333",
"ParentId": "43253",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T21:21:43.297",
"Id": "43253",
"Score": "4",
"Tags": [
"python",
"numpy",
"clustering"
],
"Title": "KMeans in the shortest and most readable format"
}
|
43253
|
<p>I've been doing a simple implementation of a to-do list to learn how to use Knockout.js. I would like a general review of what I've done so far (not much). It's my first application in JavaScript and I've never been very good at Html and CSS, so feel free to give a lot general good things to do, or not to do. </p>
<p>My application is not just one to-do list, you can have multiple lists. There is no back-end for the moment, so there is no save option. I'm wondering if my actual implementation would be difficult to add a back-end service to store information.</p>
<p>I'm using bootstrap as a CSS framework, so my CSS file is really small.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function Task(data){
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone);
this.editable = ko.observable(false);
}
function ListTask(data){
this.title = ko.observable(data.title);
this.tasks = ko.observableArray([]);
this.editable = ko.observable(false);
}
function ViewModel() {
var self = this;
self.listVisible = ko.observable(true);
self.itemsListVisible = ko.observable(false);
self.listTask = ko.observableArray([]);
self.newTaskText = ko.observable();
self.newListText = ko.observable();
self.allSelected = ko.observable(false);
self.tasks = ko.observableArray([]);
self.addListTask = function(){
self.listTask.push(new ListTask({title: self.newListText()}));
self.newListText("");
};
self.toggleEditableList = function(list){
list.editable(!list.editable());
};
self.showList = function(list){
self.listVisible(false);
self.itemsListVisible(true);
self.tasks(list.tasks());
};
self.backToMenu = function(){
self.listVisible(true);
self.itemsListVisible(false);
self.tasks([]);
};
self.addTask = function(){
self.tasks.push(new Task({title : this.newTaskText()}));
self.newTaskText("");
};
self.remove = function(task){
self.tasks.remove(task);
};
self.selectAll = function(){
var all = self.allSelected();
ko.utils.arrayForEach(self.tasks(),function(entry){
entry.isDone(!all);
});
return true;
};
self.toggleEditable = function(task){
task.editable(!task.editable());
};
}
ko.applyBindings(new ViewModel());</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.margin-top-10{
margin-top: 10px;
}
.padding-bottom-5{
padding-bottom: 5px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Simple data bind </title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/todo.css">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap-theme.min.css">
</head>
<body>
<div class="container">
<h1>Todo List</h1>
<div data-bind="visible: listVisible">
<form data-bind="submit: addListTask">
<div class="margin-top-10">
Add list: <input data-bind="value: newListText" placeholder="Humm a new list?" />
<button type="submit" class="btn btn-primary btn-sm">Add</button>
</div>
</form>
<ul data-bind="foreach : listTask" class="margin-top-10">
<li class="padding-bottom-5"><span data-bind="text: title, visible: !editable(), click: $parent.toggleEditableList"></span><input data-bind="value: title, visible: editable, hasFocus: editable" /></span> <button class="btn btn-sm" data-bind="click: $parent.showList">Show</button></li>
</ul>
</div>
<div id="listItems" data-bind="visible: itemsListVisible">
<form data-bind="submit: addTask">
<div class="margin-top-10">
Add task: <input data-bind="value: newTaskText" placeholder="What needs to be done?" />
<button type="submit" class="btn btn-primary btn-sm">Add</button>
</div>
</form>
<div class="row">
<div class="col-lg-6">
<table class="table table-hover table-condensed" >
<thead>
<tr>
<th class="col-lg-2"><input type="checkbox" data-bind="click: selectAll, checked: allSelected"/></th>
<th class="col-lg-5">Title</th>
<th class="col-lg-5">Delete</th>
</tr>
</thead>
<tbody data-bind="foreach: tasks">
<tr data-bind="css: { active : isDone()}">
<td class="col-lg-2"><input type="checkbox" data-bind="checked: isDone" /></td>
<td class="col-lg-5"><span data-bind="text: title, visible: !editable(), click: $parent.toggleEditable"></span><input data-bind="value: title, disable: isDone, visible: editable, hasFocus: editable" /></td>
<td class="col-lg-5"><a href="#" data-bind="click: $parent.remove"><span class="glyphicon glyphicon-trash"></span></a></td>
</tr>
</tbody>
</table>
<button class="btn btn-primary btn-sm" data-bind="click: backToMenu">Back</button>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="script/todo.js"></script>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
</body></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:48:14.080",
"Id": "75216",
"Score": "0",
"body": "You can fairly easy save and load files using HTML5, so that would take care of your backend problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:50:28.380",
"Id": "75217",
"Score": "0",
"body": "@Max Didn't know that, but I will add a backend in later part of my personal project. But it could be a good intermediate if I don't want to add a backend."
}
] |
[
{
"body": "<p>Nice job.</p>\n\n<ol>\n<li><p>Try to load Todo.html without Todo.js. Such situation could happen after some incorrect changes. In my opinion it is better to show only initially required elements(inputs) by default.</p></li>\n<li><p>There is no need to use jquery and bootstrap.</p></li>\n<li><p>It is possible to add duplicate\\empty item.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T10:43:14.050",
"Id": "75187",
"Score": "1",
"body": "There is no need for the JavaScript part of bootstrap at least :) The styles currently are required."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:54:49.820",
"Id": "75222",
"Score": "1",
"body": "@yarix Welcome to Code Review! I'll try to see what I can do about #1, but I'm not quite sure what should be done. #2 In fact, I need bootstrap for my style and jQuery is required by bootstrap if I remember correctly. #3 Well I have not a clear rule about empty/duplicate items. This was just an exercise to learn knockoutJS, but it is a good point."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T10:13:26.213",
"Id": "43498",
"ParentId": "43255",
"Score": "-1"
}
},
{
"body": "<p>Don't have time to do a full review but you probably want to reorganize your <code>style</code> and <code>script</code> loading. This will allow the browser to download the stylesheets concurrently while downloading+executing your scripts.</p>\n\n<p>Also you probably want to load <code>jQuery</code> before <code>knockout</code> as knockout will delegate to the more robust <code>jQuery</code> method where applicable. In the <a href=\"https://github.com/knockout/knockout/releases/tag/v3.1.0\">press release</a> for <a href=\"https://github.com/knockout/knockout/releases/tag/v3.1.0\"><code>knockout@3.1</code></a> they claim you won't have to load jQuery first. Also note, there's no advantage to loading <code>knockout</code> in head afaik as it won't actually apply the templates (<code>.applyBindings</code>) until the content ready event.</p>\n\n<p>Also you probably want to point to a single version of jQuery to prevent something going awry between jQuery (quite unlikely I guess but worth considering)..</p>\n\n<pre><code><head>\n <meta charset=\"utf-8\" />\n <title>Simple data bind </title>\n <link rel=\"stylesheet\" href=\"http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"css/todo.css\">\n <link rel=\"stylesheet\" href=\"http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap-theme.min.css\">\n</head>\n<body>\n\n <!-- content -->\n <script src=\"http://code.jquery.com/jquery-1.11.0.js\"></script>\n <script src=\"http://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js\"></script>\n</body>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:02:58.383",
"Id": "75226",
"Score": "0",
"body": "Thanks for the answer! It still a bit foggy when it come to what should be loaded first and where! This helps in getting it for now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:10:21.110",
"Id": "75231",
"Score": "1",
"body": "Agreed its not always intuitive check out https://developers.google.com/speed/articles/include-scripts-properly"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:35:10.507",
"Id": "43510",
"ParentId": "43255",
"Score": "7"
}
},
{
"body": "<p>From staring a while at your code;</p>\n\n<p><strong>Grokking</strong></p>\n\n<ul>\n<li><p>Your HTML stretches really wide sometimes, for maintainability I would indent more:</p>\n\n<pre><code><td class=\"col-lg-5\"><span data-bind=\"text: title, visible: !editable(), click: $parent.toggleEditable\"></span><input data-bind=\"value: title, disable: isDone, visible: editable, hasFocus: editable\" /></td>\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code><td class=\"col-lg-5\">\n <span data-bind=\"text: title, visible: !editable(), click: $parent.toggleEditable\">\n </span><input data-bind=\"value: title, disable: isDone, visible: editable, hasFocus: editable\" />\n</td>\n</code></pre></li>\n</ul>\n\n<p><strong>Naming</strong></p>\n\n<ul>\n<li>I would have named <code>ListTask</code> -> <code>TaskList</code></li>\n<li>You have <code>addTask</code>, but then you have <code>remove</code>, that should have been <code>removeTask</code></li>\n<li><code>addTask()</code> does not add a given task, it creates a new blank task, I would call it <code>addNewTask()</code> or <code>newTask()</code> or <code>addBlankTask</code></li>\n<li><code>listVisible</code> and <code>itemsListVisible</code> are unfortunate, I would go for <code>listsListVisible</code> and <code>taskListVisible</code>, in general I would either call every task a <code>task</code> or an <code>item</code>, otherwise you can mix up the reader</li>\n<li>I was surprised to find that <code>selectAll</code> really sets the <code>isDone</code> flag for every task, I think that should be reflected in the name. (I wonder also why you would want this)</li>\n</ul>\n\n<p><strong>Organization</strong></p>\n\n<ul>\n<li><code>addTask</code> should have been in the prototype of <code>ListTask</code>/<code>TaskList</code></li>\n<li><code>backToMenu</code> should be part of the controller, but you have to add to <code>ViewModel</code> because of <code>data-bind=\"click: backToMenu\"</code> in the HTML. I do not like this from a maintenance perspective, I would have added the listener through JS so that you can see in 1 place what this function is bound to.</li>\n<li>Far worse is all the JavaScript ( all be it short one liners ) inside your HTML. having JavaScript in your HTML deprives the maintainers from tools ( no syntax highlighting, linting, breakpoints(!) ) </li>\n</ul>\n\n<p><strong>Minutiae</strong></p>\n\n<ul>\n<li>JSHint.com cannot find anything wrong with your code</li>\n</ul>\n\n<p><strong>In the end</strong></p>\n\n<p>Call me old fashioned, but you are breaking MVC; your HTML contains far too much controller related functionality. I would not mind maintaining your JavaScript at all, it is pretty good. But I would definitely not want to maintain the app :\\</p>\n\n<p>A fiddle is <a href=\"http://jsfiddle.net/konijn_gmail_com/D6WQe/\">here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T02:42:31.350",
"Id": "75525",
"Score": "1",
"body": "Thanks for the review and for all the advices. I guess that breaking the MVC part could be a result of my understanding so far of knockout. This is my first JavaScript application so it may be cause by my inexperience in this too. I'll take some time to digest all the information!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:59:41.473",
"Id": "43651",
"ParentId": "43255",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "43651",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T21:45:33.550",
"Id": "43255",
"Score": "20",
"Tags": [
"javascript",
"html",
"knockout.js",
"to-do-list"
],
"Title": "Simple to-do list as a single page application"
}
|
43255
|
<p>I am working through K&R for review and I thought that I would write some of my own routines for conversion of binary strings to int and int to binary string. I realize this is reinvetning the wheel; I am just doing this for fun. Also, I am attempting to follow this coding style <a href="https://www.kernel.org/doc/Documentation/CodingStyle" rel="nofollow">CodingStyle.txt</a>. Any and all critiques are welcomed.</p>
<pre><code>#include <mybin.h>
#include <limits.h>
#include <errno.h>
/*
Parameters:
s - String with a maximum of 63 binary digits
Return:
- Decimal value of the binary string pointed to by s
Error:
- Negative returned on error check errno
*/
signed long binstr2int(char *s)
{
signed long rc;
for (rc = 0; '\0' != *s; s++) {
if (rc > (LONG_MAX/2)) {
errno = ERANGE;
return -1;
} else if ('1' == *s) {
rc = (rc * 2) + 1;
} else if ('0' == *s) {
rc *= 2;
} else {
errno = EINVAL;
return -1;
}
}
return rc;
}
/*
Parameters:
num - The number to convert to a binary string
s - Pointer to a memory region to return the string to
len - Size in bytes of the region pointed to by s
Return:
- Pointer to the beginning of the string
Error:
- NULL returned on error check errno
*/
char *int2binstr(unsigned long num, char *s, int len)
{
if (len < 2) {
errno = ERANGE;
*s = '\0';
return s;
} else if (0 == num) {
s[--len] = '\0';
s[--len] = '0';
return s + len;
} else {
for (s[--len] = '\0'; 0 != num; num >>= 1) {
if (0 == len) {
errno = ERANGE;
*s = '\0';
return s;
} else if (num & 1) {
s[--len] = '1';
} else {
s[--len] = '0';
}
}
}
return s + len;
}
</code></pre>
<p><strong>Edit 1:</strong>
Okay, here is the revised code. Most of the suggestions I agree with. I did retain filling the buffer from end to beginning because it seems like a logical flow to me and requires one less variable to deal with. </p>
<ul>
<li>The do while suggestion was spot on. The for loop was unusual and the do while consumed one of the conditionals making the code easier to read.</li>
<li>The names of the functions have been revised so they are not misleading</li>
<li>The functions now handle unsigned long ints</li>
<li>ul2binstr now returns NULL on error. So this needs to be checked. </li>
<li>Also the string parameter was in binstr2ul was made const</li>
<li>The len parameter was changed to size_t type</li>
</ul>
<hr>
<pre><code>/*
Parameters:
s - String with a maximum of log2(ULONG_MAX) binary characters
num - Memory address to store the result in
Return:
- Status integer
Error:
- Negative returned on error check errno
*/
int binstr2ul(const char *s, unsigned long *num)
{
unsigned long rc;
for (rc = 0; '\0' != *s; s++) {
if (rc > (ULONG_MAX/2)) {
errno = ERANGE;
return -1;
} else if ('1' == *s) {
rc = (rc * 2) + 1;
} else if ('0' == *s) {
rc *= 2;
} else {
errno = EINVAL;
return -1;
}
}
*num = rc;
return 0;
}
/*
Parameters:
num - The number to convert to a binary string
s - Pointer to a memory region to return the string to
len - Size in bytes of the region pointed to by s
Return:
- Pointer to the beginning of the string
Error:
- NULL returned on error check errno
*/
char *ul2binstr(unsigned long num, char *s, size_t len)
{
if (0 == len) {
errno = EINVAL;
return NULL;
} else {
s[--len] = '\0';
}
do {
if (0 == len) {
errno = ERANGE;
return NULL;
} else {
s[--len] = ((num & 1) ? '1' : '0');
}
} while ((num >>= 1) != 0);
return s + len;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:48:01.510",
"Id": "74840",
"Score": "2",
"body": "I see that you have edited in your revised code into your question. That is fine, just understand that your revised code is unlikely to get a review, and that it would be better to post it as a new question. See [this meta post](http://meta.codereview.stackexchange.com/q/1482/27623) for more information."
}
] |
[
{
"body": "<p>In int2binstr the comment says, \"NULL returned on error check errno\" but you don't return NULL on error: instead you return a pointer to an empty string.</p>\n\n<p>Also, I find it unusual that int2binstr writes its result at the end of the passed-in buffer, instead of at the beginning.</p>\n\n<p>Also, why use <code>long</code> in the first function but <code>unsigned long</code> in the second function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T22:58:24.020",
"Id": "74641",
"Score": "0",
"body": "Right, thanks. I fixed the comment to say empty string. Going backwards was just a choice. I guess it could go the other way too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T23:03:40.473",
"Id": "74642",
"Score": "0",
"body": "Also, the unsigned parameter was used so that an arithmetic shift would not happen. That may be a bad assumption, so I could change the direction in which the string is processed and do a left shift and make the parameters consistent."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T22:43:11.367",
"Id": "43258",
"ParentId": "43256",
"Score": "3"
}
},
{
"body": "<p>It makes sense for the two functions to be symmetrical - ie that you can call\nthem in turn to swap between integer and string representations. So I would\nmake <code>binstr2int</code> produce an <code>unsigned long</code> of full range returned through a\nparameter and have the function return the status (0/-1):</p>\n\n<pre><code>int binstr2int(const char *s, unsigned long &num);\n</code></pre>\n\n<p>Note that <code>s</code> can be <code>const</code>.</p>\n\n<p>In <code>int2binstr</code> I think the characters should be moved to the beginning of the\nstring - this is what all other C string functions do (or at least I'm\nignorant of any that do not). Also, your code is a bit awkward in\nthat it treats 0 separately from all other numbers. This is a case where a\n<code>do {...} while</code> loop makes sense as it can handle the zero case as any other\nnumber and test for zero once it has done it:</p>\n\n<pre><code>char* int2binstr(unsigned long num, char *s, size_t size)\n{\n long len = (long) size - 1;\n do {\n if (len <= 0) {\n errno = ERANGE;\n return NULL;\n }\n s[--len] = (num & 1) ? '1' : '0';\n } while ((num >>= 1) != 0);\n\n long n = (long) size - len - 1;\n memmove(s, s + len, n);\n s[n] = '\\0';\n return s;\n}\n</code></pre>\n\n<p>Here you can see that the tests for a short input string and for \n<code>num == 0</code> are handled naturally. Also I moved the string into place after\ncreating it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T03:03:47.263",
"Id": "43270",
"ParentId": "43256",
"Score": "6"
}
},
{
"body": "<p>I have only taken a quick look at binstr2int...</p>\n\n<p>If you ask me, a function called xxx2int should return an integer. Messed up function names like this cost time, because everybody has to read up how to use it. And the code where it is used becomes less and less literal if naming like this is the overall practice.</p>\n\n<p>Then</p>\n\n<pre><code>signed long rc;\nfor (rc = 0; '\\0' != *s; s++) {\n</code></pre>\n\n<p>is a tricky use of for, but it is not what a reader expects from a for-loop (the first statement should initiialize something that has to do with the loop conditions) and this may lead to errors if someone refactors or debugs the code. Do not use standard expressions in a tricky way without reason. What you wanted to communicate to a reader was maybe:</p>\n\n<pre><code>signed long rc = 0;\nwhile (0 != *s)\n{\n // ...\n s++;\n}\n</code></pre>\n\n<p>If you contribute somewhere or work on a team, the code and all naming has to be contradiction-free and fully literal in usage, this is high priority.</p>\n\n<hr>\n\n<p>An additional Note for <strong>Steve</strong> in the comments (if this might be allowed one time, because it fit's the topic, but not the comment space):</p>\n\n<p>Hi Steve, personally I do not think K&R is a good reference for production code. And I just have taken a look at chapter 2.1 and have not seen K&R using the third statement for another variable than the one in the first statement. K&R use extreme complex stuff in the middle statement of for-loops in this chapter. Wrapping your head around stuff like this is awesome for learning!</p>\n\n<p>But it is really bad for team owned code. Back in the 70s there was not much thinking about new concepts like code smells, SOLID, KISS, architecture and so on. These concepts grew with programming experience in the community. A clean, understandable, fast to read and trap-free codebase is pure gold for a company and a devs everyday life. That's why my favorite books on this topic are \"Refactoring\" from Fowler/Beck and \"Clean Code\" from Martin, while yes - on the unitversity I had also a K&R C Programming Language in my pocket.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T11:48:11.043",
"Id": "74709",
"Score": "0",
"body": "Doesn't \"little-endian\" apply to the way in which the bytes within integers are arranged? If so, how does that affect strings, or affect the OP's string-building or string-parsing functions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T12:28:55.427",
"Id": "74713",
"Score": "0",
"body": "There are cases where it applies to both byte order and bit order in bytes. So I used the term. Nevertheless I am wrong, because the endianess is ok in Steves code, and I will remove the part in my answer. - But the rest still applies, a function called str2Int returning a long is the main problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T02:11:52.113",
"Id": "74871",
"Score": "0",
"body": "I agree on the for loop, but I was going through K&R 2nd and saw similar usage in section 2.1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-20T19:57:25.290",
"Id": "78188",
"Score": "0",
"body": "Hi Steve, I think while K&R might be nice for learning, it's not so great for production code. See my explanation above in the note to the answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T10:10:07.767",
"Id": "43291",
"ParentId": "43256",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T22:24:19.673",
"Id": "43256",
"Score": "7",
"Tags": [
"c",
"converting",
"reinventing-the-wheel"
],
"Title": "Binary string to integer and integer to binary string"
}
|
43256
|
<p>Looking at the code, is this a proper example of encapsulation?</p>
<p><strong>additionalComputer.php (class)</strong></p>
<pre><code><?php
/** Counts up the Number of Additional PC Options
* and stores them into an array then sends them to the view.
*/
class additionalComputer {
protected function displayMenu() {
$addtpcs= [];
for ($i=0; $i <= 100; $i++) {
$addtpcs[$i] = $i;
}
return $addtpcs;
}
}
</code></pre>
<p><strong>additionalPCs.php (Class)</strong></p>
<pre><code><?php
class additionalPCs extends additionalComputer {
public function display() {
return $this->displayMenu();
}
}
</code></pre>
<p><strong>IndexController.php (Controller)</strong></p>
<pre><code><?php
class IndexController extends \BaseController {
Protected $layout = 'master';
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
/** Wayne - 03-02-2014 - Moved for loop to a method within its own class. */
$numberofpcs = new additionalPCs();
$addtpcs=$numberofpcs->display();
$this->layout->content = View::make('index')->with('addtpcs', $addtpcs)->with('businesstypelist', businesstype::dropdown())->with('contracttermlist',ContractTerm::dropdown());
}
</code></pre>
<p>Would you provide me with a "yes you are correct," "good but you forgot X," or "no you are screwed up and this is why"?</p>
<p>Here is another example I just wrote for someone of what I believe to be using encapsulation. They requested to be able to change their meta tags based upon the page name. Is this using proper encapsulation? This was the very first OOP programming script that I have actually written after everything that I have read and studied.</p>
<pre><code>/**
* The very first thing that you want to do is to get your page name. To do this we are going to create two classes and a couple of methods within those classes.
* The next thing you want to do is send that pagename to another class for returning your meta keywords. To do this we are going to create two additional classes and a couple of methods within those classes.
* The third thing you are going to want to do is to instanitate the classes on the page and get the information.
* Note: If you are using an MVC Framework like Laravel then you will want to remove the ?>.
* Note 2: There are two different classes for security. The protected function ensures that only the class itself can change the method within the class. This is why we have to use a retrieval class and method called a getter. This ensures that nobody from outside the function can change the original purpose of the method.
* Note 3: There are 5 different files in this one document.
*/
<?php
/**
* Class 1 named class.pageName.php
* This holds the protected method and returns the current page name. This is a page by itself.
*/
class pageName {
protected function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
}
?>
<?php
/**
* Class 2 named class.getPageName.php
* This calls the protected method in the first class and gets the URL from it
*/
require_once('class.pageName.php');
class getPageName extends pageName {
public function getName() {
return $this->curPageName();
}
}
?>
<?php
/**
* Class 3 named class.metaKeywords.php
* This takes the page name from the previous class and then outputs what keywords you want based upon the switch case statement.
*
*/
class metaKeywords {
private $metakeywords;
protected function meta($url) {
switch($url) {
case "keywordset1.php":
$metakeywords = "My, first, set, of, keywords";
break;
case "keywordset2.php":
$metakeywords = "My, second, set, of, keywords";
break;
default:
$metakeywords = "This,is,default";
}
return $metakeywords;
}
}
?>
<?php
/**
* Class 4 named class.getMetaKeywords.php
* This retrieves the information from the protected function of metaKeywords.
*/
require_once('class.metaKeywords.php');
class getMetaKeywords extends metaKeywords {
public function getKeywords($url) {
return $this->meta($url);
}
}
?>
<?php
/**
* Index page named index.php or default.php (Whatever your host accepts)
* This is the code that contacts the classes and makes then work.
*/
require_once('class.getPageName.php');
require_once('class.getMetaKeywords.php');
$curpage = new getPageName();
$pagename = $curpage->getName();
$metakeywords = new getMetaKeywords();
$keywords = $metakeywords->getKeywords($pagename);
echo $keywords; // This will echo out your keywords. Simply put it in something like
// echo "<meta name=\"keywords\" content=\"$keywords\">";
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T22:57:40.277",
"Id": "74640",
"Score": "0",
"body": "Hi welcome to Code Review! We would need a more information on what your application is doing. This will help in reviewing your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T23:24:57.083",
"Id": "74644",
"Score": "0",
"body": "@Marc-Andre: All I am doing is taking a for loop and sending it to a View. In the view it displays 0 - 100 in the drop down menu. That all works. I am merely trying to teach myself about encapsulation that I hear so much about and I am told I should be doing but nobody yet has been able to tell me how to do it without being overly complicated about it. I started reading tutorials and wrote this simple example. I am merely wondering if this is an example of encapsulation so I know whether or not I am on the correct track."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:08:29.267",
"Id": "74646",
"Score": "0",
"body": "Nobody knows? This is the third place I have asked. I have everyone telling me that I should do it but does nobody else practice it? I asked on regular stack overflow and they told me to put the question here. I don't need assistance with getting function to work. I merely need to know whether or not what I have is a good example of encapsulation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:09:39.697",
"Id": "74647",
"Score": "3",
"body": "Wait a bit your question is still young and a lot of regular users are not online."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T13:48:22.557",
"Id": "75404",
"Score": "0",
"body": "Well its been 3 days. My guess is that nobody actually knows whether these are examples of encapsulation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T13:53:47.067",
"Id": "75405",
"Score": "0",
"body": "There is a lot of factors for a question to be popular/answered. I might guess that reviewing an application for an example of encapsulation is not as fun as reviewing a question about some performance or just a general review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T02:50:46.127",
"Id": "75526",
"Score": "0",
"body": "In fact, you could add explanation about what how do you think this code is a good example of encapsulation. This would to see what is your understanding and where could we help you."
}
] |
[
{
"body": "<p>Encapsulation is such an old term from the C++ days. Nowadays it's more <strong>SOLID</strong> principles that you should build your PHP code on.</p>\n\n<p>I'm going to say it in 2 different ways.</p>\n\n<ol>\n<li><p>Yes, it takes a bit of sense of Encapsulation. <em>However</em>, it's very messy as an example. The best example would have been better with a student with its properties and a simple index.php that calls it and set the object with properties and then you call get functions to retrieve the attributes.</p></li>\n<li><p>Encapsulation in a OOP view is basically information hiding. So that's why I said yes/semi you are ok with what you have done, <em>however</em> the entire structure behind it doesn't show OOP itself with an end goal for any of us to actually say \"no you are wrong\" because you achieve something that should be done as a pure loop inside a single file. There is no object definition to create a class to show this. I am aware after explaining it to Marc that what you want to do is to loop and display but you don't need a class for that and using a class as an example for encapsulation to do a <code>for</code> loop example will just confuse yourself in the long run.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-18T15:06:01.427",
"Id": "95406",
"Score": "0",
"body": "I totally agree with you! The problem with making code to show something is it's will normally be over complicated for the problem \"solved\" by the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-30T02:11:18.870",
"Id": "97647",
"Score": "0",
"body": "My apologies. I never received an email stating that this was responded to. I had given up on it being responded to. Thanks for the answer. Makes sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-30T04:54:57.647",
"Id": "97657",
"Score": "0",
"body": "@scrfix maybe you didnt check back often. Sometimes I dont get emails also, so I check manually."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:26:19.753",
"Id": "46083",
"ParentId": "43257",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "46083",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T22:38:59.733",
"Id": "43257",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"mvc",
"laravel"
],
"Title": "Simple application to experience encapsulation"
}
|
43257
|
<p>I want to have a like system on my website on multiple pages like "news", "comments", "forum posts" etc. So I was wondering what was the best way to do it between:</p>
<ul>
<li>having like tables for each of my "modules" (news, comments...)</li>
<li><p>having one table like :</p>
<p>table: likes<br>
id (int) | page_id (varchar) | user_id (int)</p></li>
</ul>
<p>which would have those datas:</p>
<pre><code>5 | news_5576 | 676
6 | comment_6564 | 676
7 | forum_656 | 787
</code></pre>
<p>And I would get the number of likes of a module with his id and type:</p>
<pre><code>$type = 'comment';
$id = 6564;
$query = "SELECT COUNT(*) FROM likes WHERE page_id = '$type_$id'";
</code></pre>
<p>What do you think is <b>the best idea</b>?</p>
|
[] |
[
{
"body": "<p>This design violates <em>first normal form</em>, which is a concept that states that each data field should contain an atomic value (using type and ID together makes this a composite value).</p>\n\n<p>This makes certain types of queries more difficult, and you'll use more database space and suffer query performance.</p>\n\n<p>Store the type in one column, and the ID in another. If you have <em>many</em> tables, you might consider breaking it out so each module type has a corresponding \"likes\" table (e.g. <code>news</code> and <code>news_likes</code>. This uses significantly less space and makes maintenance easier, but makes some queries harder (such as \"show me all my likes\").</p>\n\n<p>Using a single-table notation is acceptable, but by breaking the type and ID out, you can use an <code>enum</code> and an <code>int</code> instead of a <code>var char</code>, which will improve query speed on full-table scans, and use less space on disk.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:22:54.383",
"Id": "74653",
"Score": "0",
"body": "I was also thinking about the last solution and for the reason you quoted: \"show me all my likes\". But yes, it would take more space. In fact, I'm wondering this because the last developer of the website used \"comment_id\" for another module (comment system)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:39:47.197",
"Id": "74659",
"Score": "0",
"body": "In my blog, which isn't yet online, I used the latter method; one table with an enum and id column. It works a treat, and queries are simple and easy to expand on."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:16:59.350",
"Id": "43263",
"ParentId": "43259",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "43263",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T22:43:18.250",
"Id": "43259",
"Score": "0",
"Tags": [
"php",
"mysql"
],
"Title": "Like system with MySQL on multiple types of pages"
}
|
43259
|
<p>For CS class, I had to reverse the digits of an integer from the input. This is my solution:</p>
<pre><code>System.out.println(new StringBuilder(new Integer(new Scanner(System.in).nextInt()).toString()).reverse().toString());
</code></pre>
<p>My main question is this: is this too golfed?</p>
<p>Obviously I could simply add whitespace and comments, but is this level of directness practical?</p>
<p>Also, is there a better way to do this? Perhaps something like the following:</p>
<blockquote>
<pre><code>final String string = new Integer(new Scanner(System.in).nextInt()).toString();
for (int i = string.length(); i != -1; System.out.print((i-- != 0) ? string.charAt(i) : "\n"));
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:13:29.047",
"Id": "74648",
"Score": "9",
"body": "Well if you want all your program in one line this is excellent. If you want maintainable and readable code this is really not a good way to go!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:16:05.440",
"Id": "74649",
"Score": "2",
"body": "Hi, I have downvoted your question. Please see our [help/on-topic] to see what we're all about. You could edit the question to include working code that you want peer reviewed; a golfed one-liner isn't going to get you much of a useful code review ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:27:59.677",
"Id": "74654",
"Score": "0",
"body": "@Mat'sMug I didn't really mean to golf it; I just don't like to have (let me count) up to four middlemen variables. I am sort of asking to ungolf it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:29:18.480",
"Id": "74655",
"Score": "0",
"body": "@Marc-Andre Yeah. Can you help with that in an answer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T07:37:37.373",
"Id": "74899",
"Score": "0",
"body": "Just wondering. What do you need to reverse an integer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:27:36.023",
"Id": "74994",
"Score": "0",
"body": "@Piotr It's for AP Computer Science, but I know a good bit of Java, so I like to have some fun."
}
] |
[
{
"body": "<p>In Java, and in Code Review, the preference is for creating both highly readable, and highly efficient code.</p>\n\n<p>It is an almost bizarre fact, that one leads to the other.</p>\n\n<p>your code has one efficiency, and that is space-on-disk.... it is neither readable, nor high-performance.</p>\n\n<pre><code>System.out.println(new StringBuilder(new Integer(new Scanner(System.in).nextInt()).toString()).reverse().toString());\n</code></pre>\n\n<ul>\n<li><p>For a start, having to scroll off the page means you have to read with your mouse, not with your eyes.</p></li>\n<li><p>Secondly, it is very hard to evaluate what parenthesis match when they are all clumped together.</p></li>\n</ul>\n\n<p>Breaking your code down (which should not be necessary), we have:</p>\n\n<blockquote>\n<pre><code>int valinput = new Scanner(System.in).nextInt();\nString stringinput = new Integer(valinput).toString();\nString reversed = new StringBuilder(stringinput).reverse().toString();\nSystem.out.println(reversed);\n</code></pre>\n</blockquote>\n\n<p>Now, you need error handling on the Scanner, and it needs to be closed as well. Without that, you have a program that is ugly when a user types in <code>123.0</code>.</p>\n\n<p>Since you have no error handling, you may as well just junk the lines with the Integer...</p>\n\n<p>And, there is no reason to convert the StringBuilder to a String directly...</p>\n\n<p>Without error handling, you can:</p>\n\n<pre><code>System.out.println(new StringBuilder().append(scanner.nextInt()).reverse());\n</code></pre>\n\n<p>That is, effectively equivalent to your code, but it has different error-condition characteristics..</p>\n\n<p>Also, it is, suprisingly, quite readable, and fast.</p>\n\n<p>Now, all you need is the try/catch for the scanner, and you are sorted.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:41:37.210",
"Id": "74660",
"Score": "0",
"body": "Along the lines of being clear and concise, I think `String.valueOf(valInput)` is much nicer than `new Integer(valinput).toString()`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:17:42.867",
"Id": "43264",
"ParentId": "43261",
"Score": "17"
}
},
{
"body": "<blockquote>\n <p>@Mat'sMug I didn't really mean to golf it; I just don't like to have\n (let me count) up to four middlemen variables. I am sort of asking to\n ungolf it.</p>\n</blockquote>\n\n<p>Well this is the root of all one-liner code. You don't want middlemen variables, but why ? Breaking the code with middlemen variables is the <strong>first</strong> step to have readable code. There is a tons of reasons to have middlemen variables. Debugging will be easier, changing implementation of functionality will be easier, re-factoring the code will be easier and your code will be easier to test (That is very very important).</p>\n\n<p>Let's see what you have :</p>\n\n<blockquote>\n<pre><code> System.out.println(new StringBuilder(new Integer(new Scanner(System.in).nextInt()).toString()).reverse().toString());\n</code></pre>\n</blockquote>\n\n<p>Let's start by breaking this :</p>\n\n<pre><code>Scanner input = new Scanner(System.in);\nint integerToReverse = input.nextInt();\nStringBuilder reverser = new StringBuilder();\nreverser.append(integerToReverse);\nreverser.reverse();\nString reversed = reverser.toString();\nSystem.out.println(reversed);\n</code></pre>\n\n<p>By breaking this in smaller steps, we can observe what have goes wrong. I've added middlemen variables, but you can observe but I don't need an <code>Integer</code>. </p>\n\n<p>By breaking the code, you could see that you can extract the code that reverse the int. If you need to reverse multiple times, you could just call the method with the <code>int</code> to reverse and you won't need duplicated code. This will help to encapsulate everything in his own \"box\" and you could changed each box more easily. </p>\n\n<p>What if the user doesn't input an <code>int</code> ? There is a chance that the user doesn't input an integer. Your code isn't ready for that. You should read the documentation for <code>Scanner.nextInt()</code> and come up with something that will be more solid. </p>\n\n<p><em>Note</em> :</p>\n\n<p>I though that you had a bug in your code. I was reading as you were building a <code>StringBuilder</code> with an <code>Integer</code>. This would be a bug, but it turns out that I was wrong. This is one of the consequence of one liner. You can't read it right at first. Everything is so compact that you need to de-compact it in your head or in code to understand it. This lead to bug by people that won't understand your code, change it because they need to add something (functionality, logging,etc) and will break it because they didn't break it at the right place. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T08:03:56.677",
"Id": "74688",
"Score": "0",
"body": "This might be too much for a comment, but won't middlemen variables get messy and use more memory/slow GC?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T09:32:21.007",
"Id": "74694",
"Score": "3",
"body": "@SimonKuang your concern is valid. Apparently they do require collection by the GC: http://stackoverflow.com/questions/19268406/java-optimization-local-variable-vs-instance-variable However, as mentioned there, premature optimization is undesirable. *We should focus on readability first*, and optimize only when a bottleneck is detected."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T11:34:45.763",
"Id": "74708",
"Score": "1",
"body": "In a small program like this they very very small overhead is negligible. And as joeytwiddle said, readability is a much more important factor in most cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T13:09:40.073",
"Id": "74719",
"Score": "0",
"body": "With code this simple, it probably is better to duplicate. You may need to call it with different `int`s, but it's equally likely that you may need additional string processing in some of those instances, so why not leave the caller responsible for creating its own StringBuilder? You're essentially only encapsulating `append` and `reverse`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T14:15:03.293",
"Id": "74738",
"Score": "2",
"body": "@nmclean For a CS class, I'm no so sure that duplicating is the way to go. Yes you're essentially encapsulating `append` and `reverse` but the major is that you're also encapsulating a functionality. You're organizing your code."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T01:06:35.343",
"Id": "43266",
"ParentId": "43261",
"Score": "8"
}
},
{
"body": "<p>Why not throw in some arithmetics?</p>\n\n<pre><code>private static String reverseInt(int i) {\n StringBuilder sb = new StringBuilder();\n for(int d = i; d != 0; d /=10) {\n sb.append(d % 10);\n }\n return sb.toString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T08:29:00.930",
"Id": "43286",
"ParentId": "43261",
"Score": "6"
}
},
{
"body": "<p>While using a String operation on this is probably the easiest and the fastest way to reverse an interger, you could also do it without casting</p>\n\n<p>NOTE: this only works with integers, not with any decimal numbers.</p>\n\n<pre><code>int number = 12345;\nint result = reverseInteger(number);\n\npublic int reverseInteger(int number) {\n int reverse = 0;\n\n while(number > 0) {\n reverse *= 10;\n reverse += number % 10;\n number /= 10;\n }\n\n return reverse;\n}\n\n// To get a String as result, use String.valueOf(reverse);\n\n/*\n-- start --\nreverse = 0\nnumber = 12345\n-- first run --\nreverse = 0 * 10 + 5 = 5\nnumber = 1234\n-- second run --\nreverse = 5 * 10 + 4 = 54\nnumber = 123\n-- third run --\nreverse = 54 * 10 + 3 = 543\nnumber = 12\n-- fourth run --\nreverse = 543 * 10 + 2 = 5432\nnumber = 1\n-- fifth run --\nreverse = 5432 * 10 + 1 = 54321\nnumber = 0\n*/\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T11:36:11.640",
"Id": "75743",
"Score": "1",
"body": "That way you lose zeros at the end, e.g. `reverseInteger(12300)` gives you `321`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T19:40:05.270",
"Id": "75927",
"Score": "0",
"body": "Darn you're right ... I forgot how I used to fix that. You could do it by checking the length and adding zeroes, but that'll take you back to String-operations or it'd add a lot more code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T19:42:57.313",
"Id": "75929",
"Score": "0",
"body": "For reversing an Integer, this doesn't matter. If you would want to keep the preceding zeroes, for some String operation, you won't be able to use this code"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T15:39:18.463",
"Id": "43310",
"ParentId": "43261",
"Score": "2"
}
},
{
"body": "<p>You could also go the character array route, which is the fastest in runtime. Here is a version that works with negative numbers:</p>\n\n<pre><code>public String reverseString(String str) {\n if (str == null) return null;\n char[] chars = str.toCharArray();\n int rightmost = (chars[0] == '-') ? 0 : 1;\n for (int i = (rightmost + 1) % 2; i < chars.length / 2; i++) {\n int tmp = chars[i];\n chars[i] = chars[chars.length - rightmost - i];\n chars[chars.length - rightmost - i] = tmp;\n }\n return new String(chars);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T19:16:24.710",
"Id": "75046",
"Score": "0",
"body": "Does this work with negative numbers?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T19:18:01.137",
"Id": "75048",
"Score": "0",
"body": "So `-1234` would become `4321-`. What happens if you parse this to a number?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:09:45.720",
"Id": "43342",
"ParentId": "43261",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "43264",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:03:41.580",
"Id": "43261",
"Score": "15",
"Tags": [
"java",
"strings"
],
"Title": "Reversing the digits of an integer"
}
|
43261
|
<p>I'd already asked for my code to be reviewed earlier here</p>
<p><a href="https://codereview.stackexchange.com/questions/42514/first-chess-project">First Chess project</a>)</p>
<p><a href="https://github.com/darkryder/Chess-python" rel="nofollow noreferrer">Full code</a></p>
<p>Considering the suggestions put forth for that question, I spent a day and refactored my whole code. For those who have seen my previous question/code, could you you point out anything which I have as of yet not improved upon?</p>
<p>For everyone else, all I want to know is whether I am on the right track while programming in python. Could you please tell me if there is something unpythonic in my code? What parts are not written in the way "good Python code" is meant to be written? Here is a snippet I feel is not really good: </p>
<h2>1. Taking input from user</h2>
<p>This is in the main loop:</p>
<pre><code>input_read=False
if len(m)==4:
X1,Y1,X2,Y2 = m # assigning final co-ordinates
m=[] # empty the buffer input list
input_read=True
if not input_read:
events=pygame.event.get()
for event in events:
if event.type == pygame.QUIT: # Quitting
exit(0)
if event.type == pygame.MOUSEBUTTONUP: pressed= False # get ready for next click
if event.type == pygame.MOUSEBUTTONDOWN and not pressed:
pressed=True
if event.button==1:
if len(m)==2: # add second click co-ordinates
pos = pygame.mouse.get_pos()
x = pos[0]/80+1
y = pos[1]/80+1
m.extend([x,y])
else:
pos = pygame.mouse.get_pos() # add first click co-ordinates
x = pos[0]/80+1
y = pos[1]/80+1
j=checkPositionToPieceDict((x,y)) # Checks that the first click has a piece
if j: # of your colour and selects it.
if j.colour==colour:
selectedPiece=j
m.extend([x,y])
</code></pre>
<p>Could you please just go through the code and tell me if this is how Python is written in the industry?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:45:01.203",
"Id": "74662",
"Score": "2",
"body": "As a first impression, I would say get rid of all the [magic numbers](http://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad) in your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T11:01:15.120",
"Id": "74703",
"Score": "0",
"body": "But I think that there aren't that many magic numbers over there in the code, and the ones that are there are obviously clear. Correct me if I'm wrong but I can add comments at the corresponding code line to remind me why i used those hard coded numbers, however they won't be a problem the way magic numbers are considered to be as they have a very limited functionality scope...that is, only in this scope, and hence are not used anywhere else, where i might forget to alter them"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T09:54:18.457",
"Id": "75183",
"Score": "2",
"body": "@darkryder The meaning of `80` is not obvious to me, at first I thought it might be the number of columns in a standard console. If it's the size of a graphic in pixels, you should introduce `GraphicWidth` and `GraphicHeight` constants instead. Else if you wanted to change the size of the graphic later on you'd need to look at all those 80 and figure out which refer to the graphic size. Use two constants so you don't hardcode the assumption that graphics are square."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:02:09.860",
"Id": "75298",
"Score": "1",
"body": "Well something very important: PEP-8 http://legacy.python.org/dev/peps/pep-0008/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:39:59.923",
"Id": "75417",
"Score": "0",
"body": "@CodesInChaos : points noted. Can you suggest anything else which should be changed? What I really wanted to know was whether I am on the right track on how python is being used/ should be used in the industry during actual implementation of big projects ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:40:27.707",
"Id": "75418",
"Score": "0",
"body": "@Schoolboy : points noted. Can you suggest anything else which should be changed? What I really wanted to know was whether I am on the right track on how python is being used/ should be used in the industry during actual implementation of big projects ?"
}
] |
[
{
"body": "<p>This code seems much better than before, so congrats. Here are a few more things to adjust:</p>\n\n<ol>\n<li><p>Move your main game loop into a function and call it in an if block like this:</p>\n\n<pre><code>if __name__ = \"__main__\":\n #call your main function\n</code></pre>\n\n<p>This is so that people (including yourself) importing your module don't immediately get a chess window popping up.</p></li>\n<li><p>You factored out the <code>Piece</code> baseclass from all of the pieces, simplifying that code quite a bit. This is good! But now you should finish the job of merging the different coloured pieces into the same class. They are extremely close to identical. You can pass in all of the values that distinguish them (colour, position, etc.) in the <code>__init__</code> method when you initialize them.</p></li>\n<li><p>At this point, with the number of global variables and global functions operating on those variables, you should group them into a <code>GameState</code> object to encapsulate them.</p></li>\n<li><p>I will second the recommendations to replace numbers that are clearly constants with variables to improve readability, as well as follow the style guidelines in PEP 8.</p></li>\n</ol>\n\n<p>Beyond that, I think the changes we're looking at are either implementation specific (you would do it differently depending on what this is supposed to accomplish, and what your goals are), are too minor to bring up one by one, or down to personal coding style.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T23:19:22.997",
"Id": "43657",
"ParentId": "43262",
"Score": "2"
}
},
{
"body": "<p>Since you ask about production (industry) use, there is a long list.</p>\n\n<p>Regarding the code design:</p>\n\n<p>If we look carefully, there are 3 attributes that define a piece:</p>\n\n<ul>\n<li>Color: Black, White</li>\n<li>Piece Type: Bishop, King, Knight, Pawn, Queen, Rook</li>\n<li>Position on Board: (A-H, 1-8)</li>\n</ul>\n\n<p>Here on I shall refer to Color` as <em>color</em>, Piece Type as <em>type</em> and Position on board as <em>pos</em>.</p>\n\n<p>Your code is not DRY (<strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself)</p>\n\n<p>You are repeating yourself in code, like <code>BlackPawn.check</code> is the same as <code>WhitePawn.check</code>. This means if there is some problem in one such place you need to change the code everywhere to fix it. Trust me, it's not a good idea!</p>\n\n<p>As the black and white pieces behave the same except for the killing which \ndepends on the color, the class hierarchy can be changed to something like:</p>\n\n<pre><code>Piece\n Bishop\n King\n Knight\n Pawn\n Queen\n Rook\n</code></pre>\n\n<p>That sorts the <em>type</em> system. </p>\n\n<p>Now pass the other 2 attributes that define a piece: <em>color</em> and <em>pos</em> in it's\ninitializer. The image's name can be calculated from the type and color. Do\nthis calculation in the <code>Piece</code> class, upon initialization. Make each subclass\ndefine the common part of the image name as a class attribute and add a <code>'_b'</code> \nto it when the piece is black.</p>\n\n<p>You might want to add a class that manages or represent the chess-board\nThat class check if the move is out of bounds, hitting another piece etc. This\nway your Pieces only have to tell the board what moves are valid for it from\nthis position. Let the board decide if the pieces can make that move.</p>\n\n<p>Also for pieces that travel a path, give it a nested list, of the moves that\nmay become invalid if this one is. Like a bishop on B2 can't go to E5 if there\nis a pawn on D4. All moves till D4 are valid (different color) but not those\nbeyond D4.</p>\n\n<p>Relating code-style (in a production environment, Readability Matters!):</p>\n\n<p>Note that I spent 200 minutes listing everything line by line like:</p>\n\n<ul>\n<li>Never use triple quoted strings for single line comments as you have on\nlines 422, 433. They are fine for comments without indent as on line 181.</li>\n</ul>\n\n<p>Here's a much shorter list:</p>\n\n<ul>\n<li><p>It would be hard to test this code. For tips on testable code see <a href=\"https://stackoverflow.com/a/4710719/1931274\">this</a>\nanswer.</p></li>\n<li><p>Use the space-bar key in places other than the indentation, like around \noperators.</p></li>\n<li><p>Break up long lines across multiple lines.</p></li>\n<li><p>Follow <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a>.</p></li>\n<li><p>Read <a href=\"http://docs.python-guide.org/en/latest/\" rel=\"nofollow noreferrer\">these</a> docs.</p></li>\n<li><p>One statement per line. Don't follow up an <code>if</code> statement with a statement simply because it's the only one. </p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-15T06:46:00.913",
"Id": "121542",
"Score": "0",
"body": "No problem. Posts should be free of noise, especially lengthy ones like this one."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T13:05:10.390",
"Id": "43702",
"ParentId": "43262",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "43702",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:12:49.147",
"Id": "43262",
"Score": "3",
"Tags": [
"python",
"pygame"
],
"Title": "First Chess Project (ver 1.1)"
}
|
43262
|
<p>I've been trying to understand the original MVC implementation (<a href="http://heim.ifi.uio.no/~trygver/2003/javazone-jaoo/MVC_pattern.pdf" rel="nofollow">the Xerox Parc's one</a>). I'm sure it has flaws, but it's simple code to practice/learn the original MVC.</p>
<p><a href="http://jsfiddle.net/2D4ST/" rel="nofollow">Working example</a></p>
<p><strong>View (index.html):</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Person</title>
</head>
<body>
<h1 id="person-name" contenteditable="true"></h1>
<p>Birth Date: <span id="person-birth-date" contenteditable="true"></span></p>
<p>Age: <span id="person-age"></span></p>
<code id="json-model-representation"></code>
<script src="model-person.js"></script>
<script src="controller-person.js"></script>
<script src="main.js"></script>
</body>
</html>
</code></pre>
<p><strong>Model (model-person.js):</strong></p>
<pre><code>var ModelPerson = (function () {
'use strict';
var ModelPerson = function (name, birthDate) {
this.name = name;
this.birthDate = birthDate;
};
ModelPerson.prototype.getName = function () {
return this.name;
};
ModelPerson.prototype.setName = function (name) {
this.name = name;
};
ModelPerson.prototype.getBirthDate = function () {
return this.birthDate;
};
ModelPerson.prototype.setBirthDate = function (birthDate) {
this.birthDate = birthDate;
};
ModelPerson.prototype.getAge = function () {
var dateDifference = new Date(Date.now() - this.birthDate.getTime());
return Math.abs(dateDifference.getFullYear() - 1970);
};
return ModelPerson;
}());
</code></pre>
<p><strong>Controller (controller-person.js):</strong></p>
<pre><code>var ControllerPerson = (function () {
'use strict';
var controller;
var ControllerPerson = function (modelPerson) {
controller = this;
controller.modelPerson = modelPerson;
};
ControllerPerson.prototype.initialize = function () {
document.getElementById('person-name').addEventListener('blur', function () {
controller.modelPerson.setName(this.textContent);
controller.updateView();
});
document.getElementById('person-birth-date').addEventListener('blur', function () {
controller.modelPerson.setBirthDate(new Date(this.textContent));
controller.updateView();
});
controller.updateView();
};
ControllerPerson.prototype.updateView = function () {
document.getElementById('person-name').textContent = this.modelPerson.getName();
document.getElementById('person-birth-date').textContent = this.modelPerson.getBirthDate();
document.getElementById('person-age').textContent = this.modelPerson.getAge();
document.getElementById('json-model-representation').textContent = JSON.stringify(controller.modelPerson);
};
return ControllerPerson;
}());
</code></pre>
<p><strong>Instantiation (main.js):</strong></p>
<pre><code>(function () {
'use strict';
var modelPerson = new ModelPerson('John Doe', new Date('1987-09-11')),
controllerPerson = new ControllerPerson(modelPerson);
controllerPerson.initialize(); }());
</code></pre>
<p>My model is the mental object model. My controller handles events and update the Model. The view is "dumb" and just presents the content.</p>
<p>Do you think it's like the original MVC? What's wrong? What am I missing?</p>
|
[] |
[
{
"body": "<p>I am assuming you are used to getters/setters because you are experienced in another language, please don't do this. Performance matters, there is no good reason to download all those functions for no good reason, <code>model-person.js</code> should be</p>\n\n<pre><code>var ModelPerson = (function () {\n 'use strict';\n\n var ModelPerson = function (name, birthDate) {\n this.name = name;\n this.birthDate = birthDate;\n };\n\n ModelPerson.prototype.getAge = function () {\n var dateDifference = new Date(Date.now() - this.birthDate.getTime());\n return Math.abs(dateDifference.getFullYear() - 1970);\n };\n\n return ModelPerson;\n}());\n</code></pre>\n\n<p>Also, <code>updateView</code> does not belong in the controller, it should be part of your view class which should contain all view related logic.</p>\n\n<p>Furthermore, I think in the original pattern, the model actually updates the view, meaning that the controller should not be done the one doing <code>controller.updateView();</code>, that should be handled implicitly by <code>controller.modelPerson.setName(this.textContent);</code></p>\n\n<p>Personally, I like your approach better, I think the controller should decide when the UI gets updated.</p>\n\n<p>Finally, there is the matter of the element id's like <code>person-name</code>, you use them more than once so you should use a constant. Now the question is, should this constant be defined in Model, View or Controller ? I personally define these id's in the View class and then the controller asks the View what the element is, so that it can attach the listener. I dont think the MVC pattern goes into this detail, so it's up to you.</p>\n\n<p>Other than that, your code is very readable and easy to follow.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:23:20.200",
"Id": "43614",
"ParentId": "43265",
"Score": "2"
}
},
{
"body": "<p>Look into PureMVC. In it, Views are termed \"Mediators\" which is a better idea conceptually.</p>\n\n<p>The Mediator is the thing that takes an underlying UI, or small set of UI items, and gives it an external interface so a controller can come around and be unaware (as best as is possible) to how and what is being done on the screen.</p>\n\n<p>In your case, a controller would like to say to the mediator something as simple as <code>.updatePerson(person)</code> and be on his way. There is a balancing act between the default behavior of a mediator and the power you would like to give to the controller.</p>\n\n<p>Considerations that come into play are the anticipated longevity of the mediator (reuseablity) - which would dictate a 'dumber' mediator exposing many adjustments, and a customized mediator with built in behavior and therefore less reusability.</p>\n\n<p>The principle is to make mediators as dumb as possible, but no dumber. The controllers are the smart ones of the system, and really ARE your 'app', with the model coming in second place.</p>\n\n<p>Mediators responsibilities: To create/paint itself (manage the underlying UI control), to react to data being fed to it, and to emit UI events in a sensible manner that will invoke controllers who see the source of specialized event messages and act accordingly.</p>\n\n<p>Controllers should be stateless (think of them as master functions), as such they are autonomous and atomic. Many MVC-ish systems bundle controllers or create a grand master controller. I think that utimately, this is bad. Every controller should be a 'class' and have its own file. The names of controllers (can, [more on that later]) correspond to event names, events from the mediators or the model.</p>\n\n<p>Likewise, many MVCs use a 'grand View' trying to encapsulate the entire swaths of the UI in one manager, this too I think is bad. Most UI parts are complex enough to justify their own MEDIATORS, with the exception of perhaps simple buttons or a submenu item. In practice, I would use a mediator for every submenu, and have a mediator for every input box, but likely not for every text-display area.</p>\n\n<p>Mediators do not have to correspond directly to UI controls like this, they can also address meta-concerns like overall control coloring, focus or other things that cross control boundaries. Take a layered approach. You could therefore use simple mediators that would display data, and then higher-level mediators that would color or highlight or decorate things depending on that data.</p>\n\n<p>Controllers are the least reusable members of the system, but that doesn't mean they cannot be genericized enough to be reused. Which brings to mind a cheat that can be done to minimize having many mundane controllers...</p>\n\n<p>Imagine a typical model change event. To be eligible for this type of technique the dataset for this particular model partition has to be small, so lets pick 'app settings' or subset thereof. Normally a model change event will invoke a controller whose job it is - is to figure out which mediators it needs to reflect the change in the UI. But if you use 'smart mediators' who also listen for events and understand how to implement the data packet, or parts of that which concern themselves, you can do without the controller on that level.</p>\n\n<p>But you have to use a data packet in the message because we do not want the mediator to query the model as this would create a dependency. You might object and say the dependency is already there because the mediator has to understand the data packet (a representation of a model partition) -- true, but if you walk up to the model you have to know HOW TO ASK for your packet, which is a dependency. You don't know the path in the model to your particular partition, nor should you, so go away, go back to your life as a stupid mediator.</p>\n\n<p>Data and the Model\nLets say our model has People, Places and Things. When you get right down to it, on the core level, the model is just a CRUD/store, and your data should exist generically down there, be it XML or JSON -- even if the data is remote in a DB, you should be dealing with a layer that expresses everything in a generic format.</p>\n\n<p>The next layer up, you have a CRUD for your data types, this is what I mean by model partitions. Here is where I am going with this -- imagine your 'Person' is in your UI, the user makes changes to person and emits an event.</p>\n\n<p>First, what is the name of the event?? \"PersonChange\"? \"UpdatePerson\"? \"UIPersonChange\"?</p>\n\n<p>Remember when I said the Mediators (aka Views) are supposed to be dumb as possible. This is done both for reuse, but also for simplification. The smarter a mediator is, the more it knows about the outside world, the more dependencies you are creating, and the tighter your coupling is getting. Its not death, but it is what we want to avoid.</p>\n\n<p>So we try to not let a mediator know what it type of data 'has' -- in the hard coded sense, and by extension the mediator should not know what type of message to emit, until its creation. We try to parameterize these things as best as possible, keeping the mediator generic internally.</p>\n\n<p>This means we should not be handing a mediator a 'PersonClass' but a clump of data that we (in the outside world) already know the mediator knows how to parse because of the parms we used to construct the mediator. (All of this is in my opinion of course, but see if you agree...)</p>\n\n<p>If we let mediators know (in their guts in hardcode) about Persons, we are creating dependencies between the model and the mediators, we are going against the whole point of things. Foot, meet bullet.</p>\n\n<p>Now, dont get me wrong, some of this type of thing is, to a degree, in a practical sense, unavoidable, but I want to use this to demonstrate a principle at work here...</p>\n\n<p>Go back to the controllers. What makes them special? They are the dumping ground for dependencies. Read that again. Dependencies are part of life, but now at least they all reside in one place! Now we are on the flip side of the coin -- what are the concerns about controllers...</p>\n\n<p>We want controllers to be as thin, lean and focused as possible. This is why from a controllers perspective, we want the mediators and model to be smarter so we dont have to do much work. Why do we want to be thin, are we just lazy? No, we want to be thin in order to make it legible what our core purpose is, and because we are really the most complex part of the system it is important to be uncluttered. If we have a weak mediator or a weak model partition then our code is going to get infected with fiddlings and each of those fiddlings is yet another dependency.</p>\n\n<p>Bridges\nWhenever one component in an MVC has dealings with another we want that transaction to be as simple and straightforward as possible -- better known as minimizing your external interface. Everything you offer to the outside world is a dependency when it gets used, and dependencies are the enemy. They make a system brittle.</p>\n\n<p>This is probably one of the top ten mistakes people make when making application code (library code is different though). You are down there in the code and you start offering things to the world \"just in case\". Hard to blame you since it FEELS like you are doing a \"thorough job\" and dammit, you deserve a pat on the back for covering all the bases. After all, you are on a roll now, and \"knocking things out\". Just look at all these options!</p>\n\n<p>Before you know it the black box you created with all its knobs and dials, is getting hard to figure out - was it lever A then switch B?? Oh, nevermind. Then when you go to use it, once you DO figure it out (again), why you would feel downright rude if you didn't jack yourself into at least SOME of those bells and whistles you worked so hard on.</p>\n\n<p>Pretty soon there are extension cords lying everywhere, and your budget on zip ties is going through the roof.</p>\n\n<p>And you realize that you've created this beautiful woman, except that, every so often, she bites your head clean off, and there is really nothing you can do about it because --- well, its complicated.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-29T17:27:58.793",
"Id": "58418",
"ParentId": "43265",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T00:43:47.123",
"Id": "43265",
"Score": "3",
"Tags": [
"javascript",
"design-patterns",
"mvc",
"controller"
],
"Title": "Xerox Parc MVC implementation"
}
|
43265
|
<p>I was just writing code, and wanted to make a piece that removes everything after the character <code>?</code> if it's found within the URL.</p>
<pre><code>if (strstr($url, "?")) {
$url = strstr($url, "?", true);
}
</code></pre>
<p>Can I make this any shorter? It doesn't feel right to type the "same thing" twice with <code>strstr</code>.</p>
|
[] |
[
{
"body": "<p>You're using the same variable for two different purpose. It would be readable with separate variables:</p>\n\n<pre><code>$urlWithoutParameters = strstr($url, \"?\", true); \nif ($urlWithoutParameters !== FALSE) {\n // if you need additional processing\n}\n</code></pre>\n\n<p>It might be safer to use PHP's built-in <a href=\"http://php.net/parse_url\"><code>parse_url</code></a> function which could help handling invalid inputs too:</p>\n\n<blockquote>\n <p>On seriously malformed URLs, <code>parse_url()</code> may return <code>FALSE</code>.</p>\n</blockquote>\n\n<p>From <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em>:</p>\n\n<blockquote>\n <p>By using a standard library,\n you take advantage of the knowledge of the experts who wrote it and the\n experience of those who used it before you.</p>\n</blockquote>\n\n<p>(It's mostly a Java book but it applies here.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T05:42:29.487",
"Id": "43277",
"ParentId": "43269",
"Score": "6"
}
},
{
"body": "<p>Doing a quick test, as follows, shows that using <code>explode()</code> is about 4 times as fast as calling strstr() twice. </p>\n\n<pre><code>$url = \"http://google.com/test.php?somevar=laksd\";\n$url2 = \"http://google.com/test.php?somevar=laksd\";\n\n$start = microtime();\nfor($i = 0; $i <= 2000000; $i++){\n if (strstr($url, \"?\")) {\n $url = strstr($url, \"?\", true);\n }\n}\n$end = microtime();\n\necho \"took \" . ($end - $start) . \"<br>\";\n\n$start = microtime();\nfor($i = 0; $i <= 2000000; $i++){\n $url = explode(\"?\", $url2);\n $url = $url[0];\n}\n$end = microtime();\n\necho \"took \" . ($end - $start) . \"<br>\";\n\nprint_r($url);\n</code></pre>\n\n<p>The output is as follows:</p>\n\n<pre><code>2000000 iterations of strstr took 0.573858\n2000000 iterations of explode took 0.132764\nhttp://google.com/test.php\n</code></pre>\n\n<p>However, unless you have hundreds of millions of visitors to your site, you don't have to hyper optimize this way. If its purely from an aesthetic point of view, then I would say just do:</p>\n\n<pre><code>$url = explode(\"?\", $url);\n$url = $url[0];\n</code></pre>\n\n<p>In PHP 5.4 and greater, you can access the array element directly (<a href=\"http://php.net/manual/en/language.types.array.php#example-88\" rel=\"nofollow\">http://php.net/manual/en/language.types.array.php#example-88</a>):</p>\n\n<pre><code>$url = explode(\"?\", $url)[0];\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:27:14.463",
"Id": "43422",
"ParentId": "43269",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T02:29:11.987",
"Id": "43269",
"Score": "3",
"Tags": [
"php",
"strings",
"url"
],
"Title": "Removing everything after a certain character"
}
|
43269
|
<p>I've two working ways to do so, but which one should I use?</p>
<p>Common part: <code>var textarea = document.getElementById("textarea");</code></p>
<p>First way:</p>
<pre><code>function updateStatusBar() {
var text = textarea.value;
statusBar.value = "Words: " + (text ? text.match(/\b\S+\b/g).length : "0") +
" Characters: " + text.replace(/\s/g, "").length +
" / " + text.replace(/\n/g, "").length;
}
</code></pre>
<p>and second way:</p>
<pre><code>function updateStatusBar() {
var text = textarea.value;
statusBar.value = "Words: " + (text.split(/\b\S+\b/).length - 1) +
" Characters: " + text.replace(/\s/g, "").length +
" / " + text.replace(/\n/g, "").length;
}
</code></pre>
<p>Please review the <code>Words:</code> counting code. Which one should I use?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T10:34:54.083",
"Id": "74698",
"Score": "0",
"body": "I would strongly recommend you, to count your characters by using something like: `textarea.innerText.length`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T11:05:37.660",
"Id": "74705",
"Score": "0",
"body": "newlines aren't characters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-07T00:39:02.947",
"Id": "407904",
"Score": "0",
"body": "note that if you are doing this for textarea input validation, there is a native character counter in HTML5. Granted, characters aren't necessarily words. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/text"
}
] |
[
{
"body": "<p>A few comments on this...</p>\n\n<p><em>What is a character?</em> In your code, you are only counting non-spaces as characters. But, if the user enters <code>a a</code> that counts as 10 characters to me.....</p>\n\n<p>From my perspective, Characters can just be <code>text.length</code>.</p>\n\n<p>Still your definition appears to be 'non-space characters'. Using that definition....</p>\n\n<p>Now, about the regex. You describe 2 ways to count words, and one way to count non-space characters, and then, for some odd reason, you count newlines as well.</p>\n\n<p>So, if I were to suggest that the best way to do it was with just one big, and few small regex... ? The big regex is the most complicated to run because it needs to do more complicated matching on a larger value. By stripping the value sooner, you can make it faster.</p>\n\n<p>Note, you do not need the <code>\\b</code> word boundary markers when dealing with either <code>\\s+</code> or <code>\\S+</code>.</p>\n\n<pre><code>//Function declaration, will be hoisted for 'addEventListener'\n//Most of the work is done to have this work for multiple text area's\nfunction updateStatus(){\n\n var text = this.value,\n // replace all words with an x\n xWords = text.replace(/\\S+/g, \"x\"),\n //Replace those x's\n noWords = xWords.replace(/x/g, \"\"),\n //Get rid of newlines from just the spaces.\n noNewLines = noWords.replace(/\\n/g, \"\");\n //You could consider a template function here..\n statusBar.textContent = \"Length: \" + text.length +\n \" Words: \" + (xWords.length - noWords.length) +\n \" Characters: \" + (text.length - noWords.length) +\n \" / \" + (noWords.length - noNewLines.length); \n}\n</code></pre>\n\n<p>The above creates successively smaller string values, and compares the difference in length to compute the result....</p>\n\n<p>Sometimes Plan C is the better option.</p>\n\n<p>With the help of Konijn we/I have put together this jsfiddle <a href=\"http://jsfiddle.net/RD49Y/\" rel=\"nofollow\">which shows it in operation</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-07T00:33:47.413",
"Id": "407903",
"Score": "0",
"body": "`newline` is not a character and `.` is not a word (put a `.` on a new line)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T05:40:59.203",
"Id": "43276",
"ParentId": "43274",
"Score": "1"
}
},
{
"body": "<p>The key difference between the two approaches is essentially these lines,\ncounting the words in <code>text</code>:</p>\n\n<pre><code>text ? text.match(/\\b\\S+\\b/g).length : \"0\"\n// ... versus ...\ntext.split(/\\b\\S+\\b/).length - 1\n</code></pre>\n\n<p>First of all, the first expression will crash for a non-empty text without words, for example <code>:!@#$</code>. Because a non-empty text is \"true\", but the <code>.match</code> will return null, so you'll get a null pointer exception in <code>.length</code>.</p>\n\n<p>Secondly, I suggest a simpler and more intuitive regular expression to match words:</p>\n\n<pre><code>/\\w+/g\n</code></pre>\n\n<p>That is, match a non-empty sequence of <em>word characters</em>.</p>\n\n<p>You could use this as <code>text.match(/\\w+/g)</code> (notice the \"g\" flag) or as <code>text.split(/\\w+/)</code>. When using <code>match</code>, you need to check if the result is <code>null</code> or not, as you already did.</p>\n\n<p>As for which way is better, using <code>match</code> or <code>split</code>,\nI would argue for <code>match</code>:</p>\n\n<ul>\n<li>It's more intuitive: it matches the character sequences you're interested in, and then count the occurrences.</li>\n<li>It's probably more efficient: splitting implies creating an array of the results, but if you only need the size of the array (the count of elements), then it sounds like a waste.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-07T00:29:21.337",
"Id": "407902",
"Score": "0",
"body": "`I want a solution.` returns \"2 words\", i.e. it don't work. See https://codepen.io/rhroyston/pen/ebrveB. I came up with the answer below. ...It boiled down to handling multiple spaces, tabs, and end-of-sentence characters such as a period, `.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-07T21:12:26.903",
"Id": "408047",
"Score": "0",
"body": "@RonRoyston As I wrote, I intentionally excluded words that would be single-letter. So getting 2 words for \"I want a solution.\" is no surprise. This is a very old post, and I don't remember anymore why I wanted to exclude such words. I rewrote it now, thanks for bringing this to my attention."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-07T22:26:02.780",
"Id": "408054",
"Score": "0",
"body": "honestly, that \\W\\w+, or whatever regex you originally had was quite a stunner to me. Very nice. Simple always wins. ...however, a word counter has gotta account for words and ignore characters that are not words. ...in any case, appreciate the input."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-03-03T06:49:07.487",
"Id": "43281",
"ParentId": "43274",
"Score": "4"
}
},
{
"body": "<ol>\n<li>Replace <code>tab</code> and <code>newline</code> and sentence ending characters, e.g. <code>.</code>, with <code>space</code> character.</li>\n<li>Split the resulting string on <code>space</code> character.</li>\n<li><code>.trim()</code> each item and <code>.push</code> to new array if it is not an empty string.</li>\n</ol>\n\n<p>The <code>.length</code> of that new array provides your word count. See it in action here/below (test by adding several spaces between words and by using several line breaks):</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.querySelector(\"textarea\").addEventListener('keyup', count);\n\nfunction count(){\n var resultArray = [];\n var str = this.value.replace(/[\\t\\n\\r\\.\\?\\!]/gm,' ');\n var wordArray = str.split(\" \");\n for (var i = 0; i < wordArray.length; i++) {\n var item = wordArray[i].trim();\n if(item.length > 0){\n resultArray.push(item);\n }\n }\n document.querySelector(\"span\").innerText = resultArray.length;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><textarea rows=\"8\" cols=\"40\"></textarea>\n<p><span>0</span> words.</p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-07T00:15:06.290",
"Id": "211004",
"ParentId": "43274",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "43281",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T04:43:07.593",
"Id": "43274",
"Score": "4",
"Tags": [
"javascript",
"strings",
"regex"
],
"Title": "Counting the words in a textarea"
}
|
43274
|
<p>Can anyone help improve the performance of my query? When I run it, it locks the database for 5 to 10 minutes.</p>
<pre><code>SELECT
u.username,
u.email,
u.created_at,
p.firstname,
p.lastname,
p.address,
p.address_2,
p.city,
p.country,
p.state,
p.zip,
p.phone,
p.phone_2,
u.last_ip,
u.last_login_at,
u.auto_login,
u.registration_page,
s.product_name
FROM
users AS u
Left Join subscriptions AS s ON u.id = s.user_id
Left Join profiles AS p ON u.id = p.user_id
where u.registration_page='Chris_Cleanse' and
u.id not in (select user_id from goal_sheets) and
u.id not in(select user_id from sheet_user_popup_not_adam) and
s.expired=TRUE ORDER BY u.id DESC;
</code></pre>
<p><a href="https://i.imgur.com/R1PYdeI.png" rel="nofollow noreferrer">Here is the output of <code>EXPLAIN SELECT</code></a>:
<img src="https://i.stack.imgur.com/1OCV9.png" alt="enter image description here"></p>
|
[] |
[
{
"body": "<p>I don't see anything unreasonable about the query itself.</p>\n\n<p>However, if I'm interpreting the output of <code>EXPLAIN</code> correctly, the anti-join with <code>sheet_user_popup_not_adam</code> is being done using a full table scan. Run</p>\n\n<pre><code>SHOW INDEXES FROM sheet_user_popup_not_adam;\n</code></pre>\n\n<p>If no index exists on the <code>user_id</code> column, then run</p>\n\n<pre><code>CREATE INDEX sheet_user_popup_not_adam_user_id ON sheet_user_popup_not_adam (user_id);\n</code></pre>\n\n<p>Maybe that should be <code>CREATE UNIQUE INDEX …</code> instead, if appropriate. Hopefully the performance should improve after you create the index.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T02:50:03.193",
"Id": "74872",
"Score": "2",
"body": "On further thought, could you post the output of `SHOW INDEXES` for all of the tables in this query? In particular, I'm curious about `SHOW INDEXES FROM subscriptions`, and why the query planner acts as it does."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T02:34:24.947",
"Id": "43359",
"ParentId": "43287",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "43359",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T09:07:48.193",
"Id": "43287",
"Score": "5",
"Tags": [
"performance",
"mysql",
"sql"
],
"Title": "Query performance of a SELECT statement using WHERE and NOT IN"
}
|
43287
|
<p>I've recently made a set of interfaces/classes to work with converting a spreadsheet into an object but I utilise an empty interface in my design:</p>
<p>I have my interface which defines what a spreadsheet object should have:</p>
<pre><code>public interface IParsedSpreadsheet<TEntity> where TEntity: IParsedRow
{
int Columns { get; set; }
int Pages { get; set; }
Dictionary<string, int> Map { get; set; }
List<string> ColumnHeaders { get; set; }
List<TEntity> RowList { get; set; }
List<TEntity> ParseSheet(IFileStorage storage);
List<String> ObtainColumnHeaders(IFileStorage storage);
}
</code></pre>
<p>As you can see it take a type parameter which must implement IParsedRow which is my empty interface:</p>
<pre><code>public interface IParsedRow
{
//Marker Interface
}
</code></pre>
<p>Here is an abstract class declaration that implements the interface:</p>
<pre><code>public abstract class AbstractParsedSpreadsheet<TEntity> : IParsedSpreadsheet<TEntity>, IEnumerable<TEntity> where TEntity : IParsedRow, new()
</code></pre>
<p>One of the important parts of this class is the <code>Map</code>. This has a list of column headers that should appear in a spreadsheet and also the index of the column they appear in.</p>
<p>Any concrete implementation of <code>IParsedRow</code> will have a number of properties each of which must be named after a column header in the spreadsheet it will represent. I use the Map along with reflection to determine that the spreadsheet headers match up to the <code>TEntity</code>'s properties exactly to let me know that the uploaded spreadsheet is valid for the map it is being put against.</p>
<p>Here is my abstract class in full (note I use NPOI as a wrapper to easily parse a spreadsheet. NPOI is an open source spreadsheet framework for .NET):</p>
<pre><code> /// <summary>
/// Abstract, generic class that only accepts a type parameter which implements IParsedRow for use in its internal row collection.
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public abstract class AbstractParsedSpreadsheet<TEntity> : IParsedSpreadsheet<TEntity>, IEnumerable<TEntity> where TEntity : IParsedRow, new()
{
public int Columns { get; set; }
public int Pages { get; set; }
public Dictionary<string, int> Map { get; set; }
public List<string> ColumnHeaders { get; set; }
public List<TEntity> RowList { get; set; }
/// <summary>
/// Single parametised constructor which will perform all work needed to make an object from a spreadsheet.
/// Used on the front end this might have a dropdown list of all "maps" or spreadsheet types you can upload.
/// and then the act of uploading will create a storage item. If the spreadsheet in the storage item doesnt match
/// up to the map then an error will be thrown.
/// </summary>
/// <param name="validationMap">this should hold the names of the columns in the spreadsheet (and also the TEntities properties) and the column index in which the column name resides in</param>
/// <param name="storage">this object has a property which refers to a file location and is used by NPOI to load up a spreadsheet for checking and parsing.</param>
public AbstractParsedSpreadsheet(Dictionary<string,int> validationMap, IFileStorage storage)
{
this.Map = validationMap;
//Check validation map against properties of TEntity
if (!this.CheckMapMatchesRowType())
{
throw new InvalidDataException("Invalid Map/Type parameter used");
}
//Obtain column headers from spreadsheet
this.ColumnHeaders = ObtainColumnHeaders(storage);
//Check validationMap against column headers
if (!CheckHeadersAgainstMap())
{
throw new InvalidDataException("Invalid Spreadsheet/Map used");
}
//Parse spreadsheet into RowList if all of the above pass.
this.RowList = ParseSheet(storage);
}
/// <summary>
/// This method takes in an IFileStorage implementation and uses it to locate and open a spreadsheet.
/// It then reads formthe spreadsheet, calling another function to create objects of type TEntity
/// and adds them into a list which belongs to this class.
/// </summary>
/// <param name="storage"></param>
/// <returns></returns>
public List<TEntity> ParseSheet(IFileStorage storage)
{
List<TEntity> ListOfRows = new List<TEntity>();
HSSFWorkbook hssfbook;
using (FileStream file = new FileStream(storage.StorageLocation, FileMode.Open, FileAccess.Read))
{
hssfbook = new HSSFWorkbook(file);
}
ISheet sheet = hssfbook.GetSheetAt(0);
foreach (IRow row in sheet)
{
if (row.RowNum == 0)
{
continue;
}
else
{
ListOfRows.Add(CreateEntityFromRow(row));
}
}
return ListOfRows;
}
/// <summary>
/// Bit of a complicated one - Accepts an IRow implementing object (those used by the NPOI spreadsheet classes)
/// looks up the column index of each cell in a row and maps it using the local Map variable (dictionary of string to int)
/// to a string value. This value can then be used to dynamically obtain a property name from TEntity using .NET Reflection.
/// The value of the current cell is then set to that property on TEntity before being continuing to the next cell.
/// After the entire object is populated it returns it.
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public TEntity CreateEntityFromRow(IRow row)
{
TEntity retVal = new TEntity();
Type entity = typeof(TEntity);
int propertyCount = entity.GetProperties().Count();
foreach (ICell c in row)
{
//Looks up the column index of the current cell and Maps it to the corresponding value in the Map dictionary to
//obtain the correct property name in TEntity that this value needs to be set for.
string columnName = this.Map.Where(d => d.Value == c.ColumnIndex).Select(e => e.Key).First();
switch (c.CellType)
{
case CellType.STRING:
retVal.GetType().GetProperty(columnName).SetValue(retVal, c.StringCellValue.ToString(), null);
break;
case CellType.NUMERIC:
retVal.GetType().GetProperty(columnName).SetValue(retVal, c.NumericCellValue, null);
break;
case CellType.BOOLEAN:
retVal.GetType().GetProperty(columnName).SetValue(retVal, c.BooleanCellValue, null);
break;
case CellType.BLANK:
case CellType.ERROR:
case CellType.FORMULA:
case CellType.Unknown:
default:
break;
}
}
return retVal;
}
/// <summary>
/// Looks up the generic parameter for this class, instatiates it and checks that its properties match the map.
/// It then checks to ensure that the map contains the correct number of entries for the number of properties on
/// the generic type.
/// </summary>
/// <returns></returns>
public bool CheckMapMatchesRowType()
{
Type entity = typeof(TEntity);
var properties = entity.GetProperties();
if (properties.Count() != Map.Count)
{
return false;
}
foreach (var i in properties)
{
if (!Map.Keys.Contains(i.Name.ToLower())){
return false;
}
}
return true;
}
/// <summary>
/// Gets the top row of any spreadsheet (which is normally where the headers are)
/// </summary>
/// <param name="storage"></param>
/// <returns></returns>
public virtual List<string> ObtainColumnHeaders(IFileStorage storage)
{
HSSFWorkbook hssfbook;
List<string> ColumnHeaders = new List<string>();
using (FileStream file = new FileStream(storage.StorageLocation, FileMode.Open, FileAccess.Read))
{
hssfbook = new HSSFWorkbook(file);
}
ISheet sheet = hssfbook.GetSheetAt(0);
IRow row = sheet.GetRow(0);
foreach (ICell c in row)
{
switch (c.CellType)
{
case CellType.STRING:
ColumnHeaders.Add(c.StringCellValue.ToString().Replace(" ", string.Empty));
break;
case CellType.NUMERIC:
case CellType.BOOLEAN:
case CellType.BLANK:
case CellType.ERROR:
case CellType.FORMULA:
case CellType.Unknown:
default:
break;
}
}
return ColumnHeaders;
}
/// <summary>
/// Checks that the headers obtained from the spreadsheet passed in are valid against the map that has been passed in
/// also checks that the count of both of them matches.
///
/// </summary>
/// <returns></returns>
public virtual bool CheckHeadersAgainstMap(){
if (ColumnHeaders.Count != this.Map.Values.Count)
{
return false;
}
foreach (string i in this.ColumnHeaders)
{
if (!this.Map.Keys.Contains(i.ToLower()))
{
return false;
}
}
return true;
}
/// <summary>
/// Make the RowList propert of the class it's enumerable.
/// </summary>
/// <returns></returns>
public IEnumerator<TEntity> GetEnumerator()
{
foreach (TEntity t in this.RowList)
{
if (t == null)
{
break;
}
yield return t;
}
}
[ExcludeFromCodeCoverage]
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
</code></pre>
<p>How can I improve my design? Is my use of an empty interface in this case a code smell? Should I just remove it and allow <code><TEntity></code> to be of any type as the mapping functions will catch it anyway and throw an exception?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T13:30:20.560",
"Id": "74723",
"Score": "1",
"body": "Why don't you use reflection on `TEntity` to deduce the `validationMap` instead of receiving it on construction, and failing on any discrepency?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T13:31:57.160",
"Id": "74724",
"Score": "0",
"body": "That... Is a pretty damn good idea!\nEDIT: Not too sure it will work now. The map is passed in to determine the column index, as I don't want this being hard coded in the order of the properties of TEntity (I want to be able to pass it in as a parsed text file from which the map will be created) I can't see how I can make it work."
}
] |
[
{
"body": "<p>An empty interface <em>is</em> a code smell. In C# you can use <a href=\"http://msdn.microsoft.com/en-us/library/aa288454%28v=vs.71%29.aspx\">attributes</a> to mark a class instead of making it implement an empty interface.</p>\n\n<p>As I suggested in my comment, you can use reflection to build your <code>Map</code> instead of receiving it as input, and failing on discrepancy. With the power of attributes, you can add functionality by marking which properties you want to map, which to ignore, maybe add metadata (like the column index):</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.Class)]\npublic class ParsedRowAttribute : Attribute {\n}\n\n[AttributeUsage(AttributeTargets.Property)]\npublic class ParsedCellAttribute : Attribute {\n public ParsedCellAttribute(int columnIndex) {\n this.ColumnIndex = columnIndex;\n }\n\n public int ColumnIndex { get; set; }\n}\n</code></pre>\n\n<p>If you want to add the column index from an outside source, you can use it as overrides to the code, so you can still count on the class to tell you which properties it externalizes, and validate the override mapping to see there are no typos there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T13:48:43.460",
"Id": "74726",
"Score": "0",
"body": "Thanks. So can you specify that a particular Type Parameter must be decorated with a specific attribute (e.g. where TEntity : ParsedRowAttribute)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T13:51:49.393",
"Id": "74727",
"Score": "0",
"body": "@Rondles No, you can't. If you wanted to ensure that, you'd have to do a check somewhere- probably the constructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T13:53:38.510",
"Id": "74728",
"Score": "0",
"body": "Right I see. Well after all of this I have realised that my interface could actually do with at least one property which is row number which I've realised i'll need for anything which is a Row. So I guess that eliminates the code smell. Although attributes have intrigued me now as I think other parts of my code can benefit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T13:56:31.610",
"Id": "74729",
"Score": "0",
"body": "@Rondles That sounds sensible, though in general you should make sure your mentality is \"I need this property so an interface is the right tool for the job\" rather than \"I want an interface, so what would be a nice property to put on it?\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T13:58:55.673",
"Id": "74731",
"Score": "0",
"body": "@BenAaronson I did feel like a bit of a fraud doing it, BUT I will genuinely use it (in fact I drew it into my domain design but overlooked it when building the classes and interfaces). Which raises another question, if you cant specify that a type must be decorated by an attribute but instead check for it elsewhere (like the constructor) is this itself not adding a different code smell?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T14:02:22.020",
"Id": "74734",
"Score": "0",
"body": "@Rondles Why do you consider that a code smell?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T14:04:48.777",
"Id": "74735",
"Score": "0",
"body": "Well the use of type constraints is a language feature, built to help restrict the use of Type Parameters at compile time. Having to code in a check that a specific Attribute is being used will result in a runtime error if it doesn't. (Unless of course I'm missing some sort of compile time trick you can pull?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T14:10:49.623",
"Id": "74736",
"Score": "1",
"body": "@Rondles While compile time errors are preferable to run time, I'm not sure that really falls under the realm of code smells. Having said that, this isn't exactly the normal use for an attribute. Perhaps you should think about whether any specific marking in code of a Parsed Row is really needed at all. In my experience, classes like these (e.g. Model classes in ASP.NET MVC) don't have any special marking. Conceptually all you're really saying is that it has publically accessible properties"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T14:16:58.917",
"Id": "74740",
"Score": "0",
"body": "@BenAaronson I agree. Which is why I was initially considering removing the IParsedRow interface as a solution to the code smell. As I'm now using it, the point has been invalidated but this has still been a though provoking conversation for me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-23T17:38:20.367",
"Id": "135683",
"Score": "0",
"body": "A key difference between interfaces and attributes is that interfaces make promises on behalf of an implementing class *and any class derived from it*, while attributes are applicable only to the class applying them, and not to descendants thereof. If characteristics should be inherited, use interfaces; if not, use attributes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-23T21:19:47.173",
"Id": "135753",
"Score": "0",
"body": "@supercat AFAIK attributes can be inherited"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-24T17:31:55.450",
"Id": "135925",
"Score": "0",
"body": "@UriAgassi: Code which checks for the existence of attributes can check to see exactly where they occur, and thus make them behave as if they are inherited or not as it sees fit. In general, however, if a base type sets an attribute one way and a derived type sets it another, code which looks for the attribute will only find out about the base-type one if it explicitly looks for it. By contrast, if a type implements an interface, there's no mechanism by which a derived type can \"unimplement\" it."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T13:44:21.373",
"Id": "43301",
"ParentId": "43288",
"Score": "11"
}
},
{
"body": "<p>It may appear to some as code smell, but it's a practice in use in the .net framework defined as 'marker interfaces'.</p>\n\n<p><code>IReadOnlySessionState</code> is one of these and as per the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.sessionstate.ireadonlysessionstate%28v=vs.110%29.aspx\">documentation</a>:</p>\n\n<blockquote>\n <p>Specifies that the target HTTP handler requires only read access to\n session-state values. This is a marker interface and has no methods.</p>\n</blockquote>\n\n<p>So, to answer your question, is this a code smell? perhaps it depends who you ask. In my opinion, if it's good enough 'pattern' for the .net framework, it's good enough for me.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.sessionstate.ireadonlysessionstate(v=vs.110).aspx\">http://msdn.microsoft.com/en-us/library/system.web.sessionstate.ireadonlysessionstate(v=vs.110).aspx</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T14:44:49.987",
"Id": "74741",
"Score": "1",
"body": "I too noticed the framework using some marker interfaces which still doesn't make them not a code smell =p, but at the same time they do enable polymorphism and constraints better than attributes do!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:46:33.920",
"Id": "74778",
"Score": "1",
"body": "I also think how you are using the interface indicates if it is a code smell or not. For instance if I have 2 empty interfaces that implement a common generic interface for the soul purpose of differentiating the implemented classes for dependency injection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-24T23:07:27.333",
"Id": "427046",
"Score": "0",
"body": "I remember Java also supplying marker interfaces for sorting algorithms to detect which strategy to use depending on the availability of the interface. So they are common, but are they still relevant in today's programming world... I wouldn't know even if you asked me."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T14:42:24.300",
"Id": "43306",
"ParentId": "43288",
"Score": "15"
}
}
] |
{
"AcceptedAnswerId": "43301",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T09:19:12.423",
"Id": "43288",
"Score": "11",
"Tags": [
"c#",
"object-oriented",
"generics",
"interface"
],
"Title": "Empty Interface usage - Is this a code smell?"
}
|
43288
|
<p>I was assigned the task of copying some subsums from a given EXCEL-Sheet into the executing EXCEL-Sheet. </p>
<p>This had to be done with an EXCEL-Macro, so non-programmers can easily use it. There was the need to compare the final sum of copied values to the sum of values in the given sheet, as it's about business critical finance.</p>
<p>What can be said about the readability and maintainability?</p>
<p>Enough talk, here's the code. I am inserting <code><hr></code> to divide the code into it's logical parts. That should make it more readable.</p>
<pre><code>Sub TelekomRechnungEinlesen()
Dim lastSetTelekomRow As Long
Dim lastSetNovatecRow As Long
Dim iterator As Long
Dim novatecSumColumn As String
Dim mobilenumberSpalte As String
Dim subSumFlag As String
Dim bereichsSpalte As String
Dim bereichsWert As String
Dim telekomSumColumn As String
Dim mobilenumber As String
Dim NTmobilenumber As String
' used worksheet shortcuts
Dim TKSheet As Worksheet
Dim NTSheet As Worksheet
' final comparison required stuff
Dim novatecSum As Double
Dim telekomSum As Double
Dim closeflag As Boolean
mobilenumberSpalte = "D"
bereichsSpalte = "F"
novatecSumColumn = "E"
telekomSumColumn = "O"
bereichsWert = "Telekom Deutschland GmbH"
</code></pre>
<hr>
<pre><code>' Select Target worksheet
Workbooks(1).Worksheets(1).Activate
Set NTSheet = ActiveSheet
lastSetNovatecRow = LastRowInGivenSheet(NTSheet)
NTSheet.Range(novatecSumColumn & "2:" & novatecSumColumn & lastSetNovatecRow).Value = ""
' Open file dialog
FileToOpen = Application.GetOpenFilename _
(Title:="Bitte Telekomrechnung auswählen", _
FileFilter:="Excel Files *.xls (*.xls),")
If FileToOpen = False Then
MsgBox "Keine Datei ausgewählt", vbExclamation, "Fehler!"
Exit Sub
Else
Workbooks.Open Filename:=FileToOpen
End If
Workbooks(2).Worksheets(3).Activate
Set TKSheet = ActiveSheet
lastSetTelekomRow = LastRowInGivenSheet(TKSheet)
tCol = novatecSumColumn
' Start Data Transfer
For tkI = 2 To lastSetTelekomRow
iterator = 2
subSumFlag = TKSheet.Range(bereichsSpalte & tkI).Value
mobilenumber = TKSheet.Range(mobilenumberSpalte & tkI).Value
While (iterator <= lastSetNovatecRow)
NTmobilenumber = NTSheet.Range("C" & iterator).Value
If mobilenumber = NTmobilenumber And subSumFlag = bereichsWert Then
' Copy the subtotal
NTSheet.Range(tCol & iterator).Value = NTSheet.Range(tCol & iterator).Value + TKSheet.Range(telekomSumColumn & tkI).Value
' Copy some additional stuff
NTSheet.Range("A" & iterator) = TKSheet.Range("C" & tkI).Value
NTSheet.Range("B" & iterator) = TKSheet.Range("B" & tkI).Value
' mark as taken into account
TKSheet.Range("A" & tkI & ":" & telekomSumColumn & tkI).Interior.Color = RGB(200, 200, 80)
End If
iterator = iterator + 1
Wend
Next tkI
</code></pre>
<hr>
<pre><code>telekomSum = WorksheetFunction.SumIf(TKSheet.Range(bereichsSpalte & "2:" & bereichsSpalte & lastSetTelekomRow), _
bereichsWert, TKSheet.Range(telekomSumColumn & "2:" & telekomSumColumn & lastSetTelekomRow))
novatecSum = WorksheetFunction.sum(NTSheet.Range(tCol & "2:" & tCol & lastSetNovatecRow))
closeflag = True
If Abs(telekomSum - novatecSum) >= 0.01 Then
' Error Message
MsgBox "Summen stimmen nicht überein. " & _
"Bitte überprüfen Sie die eingepflegten Verträge und Mobilfunknummern:" & vbCrLf & "NovaTec: " & _
novatecSum & "€" & vbCrLf & "Telekom: " & gesamt & "€" & vbCrLf & vbCrLf & _
"Doppelte Mobilfunknummern wurden in Ihrem Excel-Sheet markiert." & vbCrLf & _
"Diese sind Hauptfehlerursache. Bitte beseitigen Sie eventuell doppelte Einträge" & _
vbCrLf & vbCrLf & "Außerdem wurden in der Angegebenen Rechnung alle einbezogenen Subtotalen markiert" _
, vbExclamation, "INFO:"
' Prevent closing of imported file
closeflag = False
' Troubleshooting help for user
NTSheet.Range("C2:C" & lastSetNovatecRow).Select
Selection.FormatConditions.Delete
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlDuplicate
Selection.FormatConditions(1).Interior.Color = RGB(255, 40, 80)
End If
If closeflag Then
' Close without saving
Workbooks(2).Close (False)
End If
' Show compared values in the opened worksheet
NTSheet.Range(tCol & lastSetNovatecRow + 2).Value = novatecSum
NTSheet.Range("D" & lastSetNovatecRow + 2).Value = "NovaTec Summe"
NTSheet.Range(tCol & lastSetNovatecRow + 3).Value = telekomSum
NTSheet.Range("D" & lastSetNovatecRow + 3).Value = "Telekom Summe"
NTSheet.Range(tCol & lastSetNovatecRow + 4).Formula = "= " & tCol & lastSetNovatecRow + 2 & "-" & tCol & lastSetNovatecRow + 3
NTSheet.Range("D" & lastSetNovatecRow + 4).Value = "Differenz:"
End Sub
</code></pre>
<hr>
<pre><code>Function LastRowInGivenSheet(ByVal sheet As Worksheet) As Long
Dim found As Boolean
Dim LastRow As Long
LastRow = 1
found = False
While Not found
If sheet.Range("A" & (LastRow + 1)).Value = "" Then
found = True
Else
LastRow = LastRow + 1
End If
Wend
LastRowInGivenSheet = LastRow
End Function
</code></pre>
<p>I apologize for the variable naming... I decided to make the "configurable" variables German, as they should be maintainable by non-english speakers, in case the conditions and columns change ...</p>
|
[] |
[
{
"body": "<p>The indentation in <code>TelekomRechnungEinlesen</code> makes it hard to tell where it starts and where it ends. <code>Sub</code> and <code>End Sub</code> define a scope - anything in between should have a <kbd>Tab</kbd>:</p>\n\n<pre><code>Sub TelekomRechnungEinlesen()\n\n Dim lastSetTelekomRow As Long\n Dim lastSetNovatecRow As Long\n\n Dim iterator As Long\n Dim novatecSumColumn As String\n\n Dim mobilenumberSpalte As String\n Dim subSumFlag As String\n Dim bereichsSpalte As String\n Dim bereichsWert As String\n Dim telekomSumColumn As String\n\n Dim mobilenumber As String\n Dim NTmobilenumber As String\n\n ' used worksheet shortcuts\n Dim TKSheet As Worksheet\n Dim NTSheet As Worksheet\n\n ' final comparison required stuff\n Dim novatecSum As Double\n Dim telekomSum As Double\n Dim closeflag As Boolean\n</code></pre>\n\n<p>I used to do that too in VB6/VBA: declare all my variables at the top. I stopped doing that after seeing the benefits of <em>declaring variables as close as possible to their usage</em>. Sticking declarations at the top of a procedure is ok if your procedure is a 5-liner or similar. Clearly, that's not the case here. Let's see...</p>\n\n<hr>\n\n<pre><code>Dim mobilenumberSpalte As String\nmobilenumberSpalte = \"D\"\n\nDim bereichsSpalte As String\nbereichsSpalte = \"F\"\n\nDim novatecSumColumn As String\nnovatecSumColumn = \"E\"\n\nDim telekomSumColumn As String\ntelekomSumColumn = \"O\"\n\nbereichsWert = \"Telekom Deutschland GmbH\"\n</code></pre>\n\n<p>These aren't really variables, they're more like constants. Declaring them as such clears a bunch of declarations and assignments from the function:</p>\n\n<pre><code>Private Const MobileNumberSpalte As String = \"D\"\nPrivate Const BereichsSpalte As String = \"F\"\nPrivate Const NovatecSumColumn As String = \"E\"\nPrivate Const TelekomSumColumn As String = \"O\"\n</code></pre>\n\n<hr>\n\n<p>What the procedure actually does:</p>\n\n<ul>\n<li>Activate the first sheet of the first opened workbook, keep a reference to the active sheet.</li>\n<li>Get the last row with data on that sheet.</li>\n<li>Clear values of <code>[E2:Ex]</code>, where <code>x</code> is the last row with data.</li>\n</ul>\n\n<p>Break here. Scratch <code>LastRowInGivenSheet</code> and take a look at <a href=\"https://stackoverflow.com/a/11169920/1188513\">this fabulous Stack Overflow answer</a>:</p>\n\n<blockquote>\n <h3>Find Last Row in a Column</h3>\n \n <p>To find the last Row in Col E use this:</p>\n\n<pre><code>With Sheets(\"Sheet1\")\n LastRow = .Range(\"E\" & .Rows.Count).End(xlUp).Row\nEnd With\n</code></pre>\n \n <p><sub><a href=\"https://stackoverflow.com/questions/11169445\">https://stackoverflow.com/questions/11169445</a></sub></p>\n</blockquote>\n\n<p>How about extracting functions out of that monster?</p>\n\n<pre><code>Private Function FindAndActivateFirstWorksheet() As Worksheet\n\n If Workbooks.Count = 0 Then Exit Function 'return Nothing\n\n Dim result As Worksheet\n Set result = Workbooks(1).Worksheets(1)\n\n result.Activate\n Set FindAndActivateFirstWorksheet = result\n\nEnd Function\n\nPrivate Function GetLastDataRow(xlSheet As Worksheet, Optional column As String = \"A\") As Long\n GetLastDataRow = xlSheet.Range(column & xlSheet.Rows.Count).End(xlUp).Row\nEnd Function\n</code></pre>\n\n<p>Clearing the contents of a <code>Range</code> object is as easy as calling <a href=\"http://msdn.microsoft.com/en-us/library/office/ff835589(v=office.15).aspx\" rel=\"nofollow noreferrer\"><code>Range.ClearContents()</code></a>.</p>\n\n<p>So, moving on:</p>\n\n<ul>\n<li>Bring up a <code>FileDialog</code>, open any Excel file that the user selects.</li>\n<li>Activate the 3rd sheet in the 2nd workbook (the one we just opened?) and keep a reference to the active sheet.</li>\n</ul>\n\n<p>This should also be extracted in its own function that returns a <code>Worksheet</code> object, or <code>Nothing</code> if the user, say, cancelled out of the <code>FileDialog</code>. I believe your code... blows up if that happens, right? And what if the user opens a workbook that doesn't have the layout you're expecting, or if a user has inserted a worksheet and the one you're expecting 3rd is now 4th?</p>\n\n<p>If possible, give the 3rd worksheet a specific name, and refer to that sheet by its name in code, and then gracefully handle the case where the expected sheet name isn't found in the selected workbook file; it's also likely that the workbooks that work with this macro are all called a certain specific way - you can validate that <em>before opening the workbook file</em>.</p>\n\n<p>Activating the 1st sheet in the 1st book and returning it, is pretty much like activating the 3rd sheet in the 2nd book and returning it, no?</p>\n\n<pre><code>Private Function FindAndActivateWorksheet(xlWorkbook As Workbook, Optional ByVal sheetIndex As Long, Optional ByVal sheetName As String) As Worksheet\n\n Dim isIndex As Boolean\n isIndex = Not IsMissing(sheetIndex)\n If Not isIndex And IsMissing(sheetName) Then\n isIndex = True\n sheetIndex = 1\n End If \n\n Dim result As Worksheet\n If isIndex Then\n Set result = xlWorkbook.Worksheets(sheetIndex)\n Else\n Set result = xlWorkbook.Worksheets(sheetName)\n End If\n\n result.Activate\n Set FindAndActivateWorksheet = result\n\nEnd Function\n</code></pre>\n\n<p>Now you can use that to find and activate the Nth sheet of any workbook, or to find and activate a sheet with a specific name, in any workbook - just pass in the workbook instance and what you're looking for. If there's an error (most likely something like an <code>index out of range</code> error), it's up to the caller to handle it.</p>\n\n<hr>\n\n<p>The procedure is doing a lot more. Isolate each thing it does, extract it into a procedure or function; when you're done, it will read like plain English... or German. And you'll have a bunch of tiny little functions that do pretty much one single thing, with a \"master\" procedure at a high abstraction level, that anyone that can read could grasp and understand what it's doing, at a glance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T02:35:33.177",
"Id": "43360",
"ParentId": "43290",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "43360",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T09:37:25.617",
"Id": "43290",
"Score": "19",
"Tags": [
"vba",
"excel"
],
"Title": "Importing data from an external EXCEL-Sheet"
}
|
43290
|
<p>I am creating a service (<code>FaultTolerantCommunication</code>) that wraps a call to a (web) service. Its responsibility is to switch the endpoint URL in the event of a <code>TimeoutException</code>.</p>
<p>Currently the web service is a soap web service but I am attempting to make it reusable for other remote services such as a JSON based web service, for example.</p>
<p>I am looking for a review on the design. I have not really done any defensive programming yet in terms of argument validation and null checking but please feel free to suggest improvements on this too.</p>
<p>The idea is for the client code to call the service as below:</p>
<p>I would probably extract an interface from <code>FaultTolerantCommunication</code> and inject an instance using an IoC container.</p>
<p><strong>Client Code:</strong></p>
<pre><code>var faultTolerantCommunication = new FaultTolerantCommunication<FooRequest, FooResponse, ISoapClient>(this.serviceCaller);
FooResponse response = faultTolerantCommunication.Request(request, this.soapClient);
</code></pre>
<p><strong>Fault Tolerant Communication</strong></p>
<pre><code> /// <summary>
/// Fault Tolerant Communication. Recurses to fall over web service endpoints in event of timeout.
/// </summary>
public class FaultTolerantCommunication<TRequest, TResponse, TClient>
where TRequest : FooRequest, new()
where TResponse : FooResponse, new()
where TClient : ISoapClient
{
private readonly Configuration config;
private readonly FooIntegration FooIntegration;
private readonly ExceptionLogger exceptionLogger;
private TClient client;
private readonly SoapClientSwitcher<TClient> switcher;
public FaultTolerantCommunication(FooIntegration FooIntegration)
{
// Read the config during construction.
config = new ConfigReader().Read();
// Constructor inject FooIntegration
this.FooIntegration = FooIntegration;
// Exception Logger
this.exceptionLogger = new ExceptionLogger("FaultTolerantCommunication");
// Generic SoapClient
this.client = default(TClient);
// Soap Client Switcher
switcher = new SoapClientSwitcher<TClient>(config);
}
/// <summary>
/// Do a single request.
/// </summary>
/// <param name="request">The Request</param>
/// <param name="client">The Client</param>
/// <returns>The Response</returns>
private TResponse DoRequest(TRequest request, TClient client)
{
// Set the endpoint soap client.
FooIntegration.ChangeEndPoint(client);
// Call the service
FooResponse response = this.FooIntegration.DoTransaction(request);
// Return the response
return (TResponse)response;
}
/// <summary>
/// Recursively fall back to secondary and stand-in endpoints on TimeoutException
/// </summary>
/// <param name="request">The Request</param>
/// <param name="client">The Client</param>
/// <returns>The Response</returns>
public TResponse Request(TRequest request, TClient client)
{
try
{
return DoRequest(request, client);
}
catch (TimeoutException timeoutException)
{
// Log the time out
exceptionLogger.DbLogException(timeoutException);
// Change endpoint
this.client = switcher.Switch(this.client);
FooIntegration.ChangeEndPoint(client);
// Recurse
return Request(request, client);
}
}
}
</code></pre>
<p><strong>Soap Client Switcher</strong></p>
<pre><code>internal class SoapClientSwitcher<TClient> where TClient : ISoapClient
{
private readonly Configuration config;
internal SoapClientSwitcher(Configuration config)
{
this.config = config;
}
internal TClient Switch(TClient client)
{
if (client is SoapClient)
{
client = (TClient)new SoapClientFactory().GetSecondarySoapClient(config);
return client;
}
if (client is SecondarySoapClient)
{
client = (TClient)new SoapClientFactory().GetStandInSoapClient(config);
return client;
}
if (client is StandInSoapClient)
{
client = (TClient)new SoapClientFactory().GetPrimarySoapClient(config);
return client;
}
return client;
}
}
</code></pre>
<p><strong>ISoapClient</strong></p>
<pre><code>public interface ISoapClient : IClient<string, string>
{
string EndPointUrl { get; set; }
}
</code></pre>
<p><strong>IClient</strong></p>
<pre><code>public interface IClient<TRequest, TResponse>
{
TResponse Transaction(TRequest transaction);
}
</code></pre>
<p><strong>Soap Client Factory</strong></p>
<pre><code>public class SoapClientFactory
{
private ISoapClient soapCient;
public ISoapClient GetPrimarySoapClient(Configuration configuration)
{
soapCient = new SoapClient(configuration);
return soapCient;
}
public ISoapClient GetSecondarySoapClient(Configuration configuration)
{
soapCient = new SecondarySoapClient(configuration);
return soapCient;
}
public ISoapClient GetStandInSoapClient(Configuration configuration)
{
soapCient = new StandInSoapClient(configuration);
return soapCient;
}
}
</code></pre>
<p><strong>Soap Client</strong></p>
<pre><code>public class SoapClient : ISoapClient
{
private wsSoapClient client;
private string password;
public SoapClient(Configuration configuration)
{
// Some Config reading which is omitted for brevity
EndpointAddress address = SetEndPoint(settings);
client = new wsSoapClient(binding, address);
}
protected virtual EndpointAddress SetEndPoint(AppSettingsSection settings)
{
EndpointAddress address = new EndpointAddress(settings.Settings["EndpointUrl"].Value);
return address;
}
public string Transaction(string transaction)
{
Console.WriteLine("Calling real soapClient");
return client.Transaction(transaction, password);
}
public string EndPointUrl { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T11:28:33.767",
"Id": "76443",
"Score": "0",
"body": "What happens with `Request` if all endpoints fail? You should at least limit the recursion level. Timeouts can occur even if the endpoint is still 'up' due to heavy load - switching every new request to the next endpoint will most likely bring that one down too and so on....Some sort of load-balancing, maybe detect if the time it takes to get a reply degrades, might help remove some of the timeouts. Do all endpoint have the same 'capacity'/ability to handle the same number of clients?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T10:32:58.950",
"Id": "76674",
"Score": "0",
"body": "If all endpoints fail it keeps switching until one of them works. In theory, one of the endpoints should be always up. They are endpoints I do not control so I cannot comment on their ability to handle clients. I like your idea about timing replies. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T17:30:57.393",
"Id": "76784",
"Score": "1",
"body": "I get your point about \"keep trying\" but I don't think that recursion is the way to go - think how \"nice\" a 60 levels deep call-stack looks; I'd use a do-while loop instead. Also, retrying until \"one endpoint works\" is OK only for small/infrequent timeouts but if your machine loses network connectivity, you might retry for a (very) long time and, potentially worse, block the calling code while you do that - you should at least build-in the option to retry for up to X seconds. Or implement some async mechanism and give the calling code the chance to abort the call."
}
] |
[
{
"body": "<ol>\n<li><p>For this:</p>\n\n<blockquote>\n<pre><code>public TResponse Request(TRequest request, TClient client)\n{\n try\n {\n return DoRequest(request, client);\n }\n catch (TimeoutException timeoutException)\n {\n // Log the time out\n exceptionLogger.DbLogException(timeoutException);\n\n // Change endpoint\n this.client = switcher.Switch(this.client);\n FooIntegration.ChangeEndPoint(client);\n\n // Recurse\n return Request(request, client);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>If I'm right </p>\n\n<blockquote>\n<pre><code>return Request(request, client);\n</code></pre>\n</blockquote>\n\n<p>should be</p>\n\n<pre><code>return Request(request, this.client);\n</code></pre>\n\n<p>Are you sure that the <code>Request</code> method needs the <code>TClient</code> parameter at all? The class has a <code>client</code> field but it is never used. I guess you should use the field here and remove the method parameter.</p>\n\n<p>Furthermore, <code>FooIntegration.ChangeEndPoint(client)</code> looks unnecessary here, since the called <code>Request</code> method also calls <code>FooIntegration.ChangeEndPoint(client)</code>.</p></li>\n<li><p>If you're planning to unit-test your code, dependencies, like <code>new ConfigReader()</code> and <code>new ExceptionLogger()</code> will make it harder because you can't use mocked/dummy implementations with predefined values/behaviour. I'd have a <code>Configuration</code> and an <code>ExceptionLogger</code> etc. constructor parameter instead and create these objects in a factory method.</p></li>\n<li><p>This method actually doesn't switch anything:</p>\n\n<blockquote>\n<pre><code>internal TClient Switch(TClient client)\n</code></pre>\n</blockquote>\n\n<p>It just returns the next client. The client parameter could be called <code>currentClient</code> while the return value is the <code>nextClient</code>. I would name the method <code>getNextClient</code>.</p></li>\n<li><p><code>FaultTolerantCommunication</code> does not seem thread-safe. (If you are planning to use it from multiple threads you should handle that.)</p></li>\n<li><blockquote>\n<pre><code>client = (TClient)new SoapClientFactory().GetSecondarySoapClient(config);\nreturn client;\n</code></pre>\n</blockquote>\n\n<p>It's unnecessary to change the value of this local variable right before the function returns. The following is the same:</p>\n\n<pre><code>return (TClient) new SoapClientFactory().GetSecondarySoapClient(config);\n</code></pre>\n\n<p>(You might don't need the casting too.)</p></li>\n<li><p>Comments like this are rather noise:</p>\n\n<blockquote>\n<pre><code>// Read the config during construction.\nconfig = new ConfigReader().Read();\n\n// Constructor inject FooIntegration\nthis.FooIntegration = FooIntegration;\n\n// Exception Logger\nthis.exceptionLogger = new ExceptionLogger(\"FaultTolerantCommunication\");\n</code></pre>\n</blockquote>\n\n<p>What they say is obvious from the code itself. I'd remove them. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p>Usage of <code>this.</code> doesn't seem consistent:</p>\n\n<blockquote>\n<pre><code>config = new ConfigReader().Read();\nthis.FooIntegration = FooIntegration;\nthis.exceptionLogger = new ExceptionLogger(\"FaultTolerantCommunication\");\nthis.client = default(TClient);\nswitcher = new SoapClientSwitcher<TClient>(config);\n</code></pre>\n</blockquote>\n\n<p>If not necessary I'd remove them. I'm not familiar with C# IDEs but if they can show fields and local variables with different colors <code>this.</code> is usually unnecessary.</p></li>\n<li><p>I'd use lowercase first letter for the field name here:</p>\n\n<blockquote>\n<pre><code>private readonly FooIntegration FooIntegration;\n</code></pre>\n</blockquote>\n\n<p>It would be consistent with the other fields and wouldn't be the same as the type.</p></li>\n<li><p>The <code>soapClient</code> field is never read:</p>\n\n<blockquote>\n<pre><code>public class SoapClientFactory\n{\n private ISoapClient soapCient;\n\n public ISoapClient GetPrimarySoapClient(Configuration configuration)\n {\n soapCient = new SoapClient(configuration);\n return soapCient;\n }\n ...\n}\n</code></pre>\n</blockquote>\n\n<p>You could use a local variable or just return:</p>\n\n<pre><code>public ISoapClient GetPrimarySoapClient(Configuration configuration)\n{\n return new SoapClient(configuration);\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T01:13:29.310",
"Id": "44543",
"ParentId": "43292",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "44543",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T10:48:40.233",
"Id": "43292",
"Score": "8",
"Tags": [
"c#",
"recursion",
"web-services",
"timeout",
"soap"
],
"Title": "Web service proxy that switches endpoint URLs in the event of a TimeoutException"
}
|
43292
|
<p>I wrote this simple HTML parser in Ruby.</p>
<p>Basically I have a folder that has files. Every file has crawled web pages. The only addition within these files is before the HTML content there is a page metadata, <code>#URL</code> is one of them.</p>
<p>What I am aiming is to have two files:</p>
<p>1)Will contain: currentURL, destinationURL, description</p>
<p>2)Will contain: currentURL, destinationURL, word, count</p>
<p>So if I did that for this current page and assuming that href that I am looking at is:</p>
<p><code><a href="http://stackoverflow.com" title="professional and enthusiast programmers">Stack Overflow</a></code></p>
<p>1st file would have</p>
<p>codereview,stackexchange.com, <a href="http://stackoverflow.com">http://stackoverflow.com</a>, Stack Overflow</p>
<p>2nd file would have</p>
<p>codereview,stackexchange.com, <a href="http://stackoverflow.com">http://stackoverflow.com</a>, Stack, 1</p>
<p>codereview,stackexchange.com, <a href="http://stackoverflow.com">http://stackoverflow.com</a>, Overflow, 2</p>
<p>However my code works really slow. It has been longer than an hour and still parsing a file with size of 31MB.</p>
<p>My code is:</p>
<pre><code>beginning_time = Time.now
folder = "allParts/"
extension = "*.dat"
urlMet = "#URL:"
newLine = "\n"
files = Dir[folder+extension]
hrefTag = "<a href=\""
qtMark = "\""
descStart = "\">"
hrefEnd = "</a>"
firstOutput = "firstOut.txt"
secondOutput = "secondOut.txt"
File.open(firstOutput, 'w') {}
File.open(secondOutput, 'w') {}
countFile = 1
for file in files do
puts file + "#: "+countFile.to_s
countFile++
File.open(file, "r") do |f|
source = ""
f.each_line do |line|
dest = ""
desc = ""
if line.include? urlMet
source = line[/#{urlMet}(.*?)#{newLine}/m, 1]
end
if line.include? hrefTag
dest = line[/#{hrefTag}(.*?)#{qtMark}/m, 1]
descStIn = line.rindex(descStart)
descEndIn = line.rindex(hrefEnd)
desc = line[descStIn+2..descEndIn-1]
end
if (source != "" && dest != "")
occur = Hash.new(0)
mainEntry = "original-url=\"" + source +
"\", dest-url=\"" + dest + "\""
descEntry = ""
if (desc != nil && desc != "")
descEntry = ", desc=\"" + desc + "\""
words = desc.split(' ')
words.each { |word| occur[word] += 1 }
end
firstEntry = mainEntry+descEntry+"\n\n"
File.open(firstOutput, 'a') { |file|
file.write(firstEntry)
}
occur.each { |word, occurrance|
wordEntry = ", word=\"" + word +
"\", count=" + occurrance.to_s
secondEntry = mainEntry+wordEntry+"\n\n"
File.open(secondOutput, 'a') { |file|
file.write(secondEntry)
}
}
end
end
end
end
end_time = Time.now
puts "Time elapsed #{(end_time - beginning_time)} seconds"
</code></pre>
|
[] |
[
{
"body": "<p>You are trying to parse HTML with regexes, which is widely considered to be a bad idea. For example, all these tags would have equivalent link text and target URL:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><!-- \"normal\" -->\n<a href=\"http://example.com\">Link Text</a>\n<!-- more than one space before the attribute -->\n<a href=\"http://example.com\">Link Text</a>\n<!-- tags split across multiple lines -->\n<a\n href=\"http://example.com\">\n Link Text\n</a>\n<!-- universal attribute \"id\" in front of the \"href\" -->\n<a id=\"foo\" href=\"http://example.com\">Link Text</a>\n<!-- different quote character -->\n<a href='http://example.com'>Link Text</a>\n</code></pre>\n\n<p>A line-based parser will fail here, and a regex-based parser will be very difficult to write correctly. So <em>please</em> use an existing HTML parser. The result will be fast and elegant, but as I don't use Ruby I can't give examples.</p>\n\n<hr>\n\n<p>Let's move on to coding style. You are using multiple naming styles: <code>beginning_time</code> and <code>newLine</code>. Whatever you do, <em>be consistent</em>, although I'd recommend <code>snake_case</code> for variable names.</p>\n\n<p>Some of your variable names contain abbreviations where none are necessary: <code>quote_character</code> is probably better than <code>qtMark</code>, <code>descStart</code> would probably be better described as <code>description_start</code>.</p>\n\n<p>You used many variables to make your regexes appear more modular, but they are not. Your regexes will become more readable if you write them down directly rather than assembling them. You could also specify them outside of your loops:</p>\n\n\n\n<pre class=\"lang-ruby prettyprint-override\"><code>href_regex = /href=\"([^\"]+)\"/\n</code></pre>\n\n<p>Points to note here:</p>\n\n<ul>\n<li><code>[^\"]+</code> is generally preferable over <code>.*?</code></li>\n<li>The <code>/m</code> option was highly unnecessary, because you process your input line by line. So there is no way that your <code>.</code> could ever match a newline in your original regex. </li>\n</ul>\n\n<p>In your regexes, you used <code>#{…}</code> interpolation a lot. Strangely you didn't do any of that when assembling other strings, instead using less readable concatenation. E.g. we could rewrite</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>mainEntry = \"original-url=\\\"\" + source + \n\"\\\", dest-url=\\\"\" + dest + \"\\\"\"\n</code></pre>\n\n<p>as</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>main_entry = \"original-url=\\\"#{source}\\\", dest-url=\\\"#{dest}\\\"\"\n</code></pre>\n\n<p>This is still pretty unreadable because of those pesky escapes – using the alternate <code>%Q()</code> literal syntax we could simplify this to:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>main_entry = %Q(original-url=\"#{source}\", dest-url=\"#{dest}\")\n</code></pre>\n\n<p>… and ditto in the similar cases.</p>\n\n<p>A snippet like</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>words = desc.split(' ')\nwords.each { |word| occur[word] += 1 }\n</code></pre>\n\n<p>could be improved in two ways:</p>\n\n<ol>\n<li>get rid of the unnecessary variables. The code is already sufficiently self-documenting with the <code>word</code> parameter to the block</li>\n<li>rename <code>occur</code> to something sensible like <code>word_count</code></li>\n</ol>\n\n<p>You declare your <code>source</code> variable outside of the <code>each_line</code> loop. It would be better to declare your variables as close to their point of usage as possible. Furthermore, you initialize them with the empty string. I (as a Ruby newbie) would probably initialize them to <code>nil</code> instead. This has the further advantage that we can remove those <code>line.include? \"some string\"</code> tests which do not even guarantee that the regex will match. The <code>String#[Regex, capture]</code> method returns either the string matched by that capture group, or <code>nil</code> – which is exactly what we want.</p>\n\n<p>Don't re-open a file all the time inside a tight loop, this is quite expensive. Open the file once, write to it multiple times. This will probably remove your main performance bottleneck.</p>\n\n<p>If we stuff all this advice into your code, we might end up with the following refactoring:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>start_time = Time.now\n\nfile_count = 1\n\nFile.open(\"firstOut.txt\", 'w') do |out1|\n File.open(\"secondOut.txt\", 'w') do |out2|\n for file_name in Dir[\"allParts/*.dat\"] do\n puts \"#{file_name}#:#{file_count}\"\n file_count++\n\n File.open(file_name, \"r\") do |file|\n file.each_line do |line|\n source = line[/#URL:(.*?)\\n/, 1]\n destination = line[/<a href=\"([^\"]+)\"/, 1]\n\n if (source != nil && destination != nil)\n word_count = Hash.new(0)\n main_entry = %Q(original-url=\"#{source}\", dest-url=\"#{dest}\")\n\n description_start = line.rindex('\">') + 2\n description_end = line.rindex('</a>') - 1\n description = line[description_start .. description_end]\n if (description != nil && description != \"\")\n out1.write(%Q(#{main_entry}, desc=\"#{desc}\"\\n\\n)) \n description.split(' ').each do |word|\n word_count[word] += 1\n end\n else\n out1.write(%Q(#{main_entry}\\n\\n)) \n end\n\n word_count.each do |word, count|\n out2.write(%Q(#{main_entry}, word=\"#{word}\", count=#{count}\\n\\n)) \n end\n end\n end\n end\n end\n end\nend\n\nputs \"Time elapsed #{Time.now - start_time} seconds\"\n</code></pre>\n\n<p>Note that this can be improved further – the high level of indentation suggests we should extract some parts as separate functions. I further want to reiterate that I'm not a proficient Rubyist, so there might be some egregious oversights in the above code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T13:12:46.343",
"Id": "74720",
"Score": "0",
"body": "I am new to Ruby. Thanks for pointing out many things. Most of my code(as you might have guessed from having different naming conventions) is copied and pasted from another source.\n\nThank you very much for writing so detailed answer. I have a question, I tried to google HTML parser but all I can find is 3rd party libraries. Are you telling me to use in-built library that comes with Ruby? If so what is the library name/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T14:52:08.053",
"Id": "74743",
"Score": "1",
"body": "By the way about this part \"You declare your source variable outside of the each_line loop. It would be better to declare your variables as close to their point of usage as possible.\"\nThe reason why source was declared outside of the scope is because at the beginning of the file you get the source, declaring it right next to where it was used would only return null."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T12:59:53.733",
"Id": "43297",
"ParentId": "43293",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "43297",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T11:01:02.770",
"Id": "43293",
"Score": "1",
"Tags": [
"ruby",
"html",
"strings",
"parsing"
],
"Title": "Ruby html href parser working slow"
}
|
43293
|
<p>I've implemented <code>PeersContainer</code> class with all operations that I need. I need something like multimap in concurrent environment, moreover I need remove entities automatically on timeout. So, I decide to use <code>Cache<Long, BlockingDeque<Peer>></code> combined with <code>Striped<ReadWriteLock></code>. Also I use two caches which can transfer entities between each other.</p>
<p><em><strong>Question:</em></strong> <em>Is all those operations thread-safe in my context?</em></p>
<p>If it isn't thread safe, please, provide an example which demonstrate scenario where I'll get inconsistent data.</p>
<pre><code>public class PeersContainer {
private final static int MAX_CACHE_SIZE = 100;
private final static int STRIPES_AMOUNT = 10;
private final static int PEER_ACCESS_TIMEOUT_MIN = 30;
private final static PeersContainer INSTANCE;
static {
INSTANCE = new PeersContainer();
}
public static PeersContainer getInstance() {
return INSTANCE;
}
private Striped<ReadWriteLock> stripes = Striped.lazyWeakReadWriteLock(STRIPES_AMOUNT);
private final Cache<Long, BlockingDeque<Peer>> peers = CacheBuilder.newBuilder()
.maximumSize(MAX_CACHE_SIZE)
.expireAfterAccess(PEER_ACCESS_TIMEOUT_MIN, TimeUnit.MINUTES)
.removalListener(new RemovalListener<Long, BlockingDeque<Peer>>() {
public void onRemoval(RemovalNotification<Long, BlockingDeque<Peer>> removal) {
if (removal.getCause() == RemovalCause.EXPIRED) {
//send logOut response to all use'r {@code Peer} objects.
for (Peer peer : removal.getValue()) {
//peer.sendLogOutResponse();
}
}
}
})
.build();
private final Cache<Long, UserAuthorities> authToRestore = CacheBuilder.newBuilder()
.maximumSize(MAX_CACHE_SIZE)
.expireAfterWrite(PEER_ACCESS_TIMEOUT_MIN, TimeUnit.MINUTES)
.build();
public BlockingDeque<Peer> getPeers(long sessionId) {
Lock lock = stripes.get(sessionId).readLock();
peers.cleanUp();
lock.lock();
try {
return peers.asMap().get(sessionId);
} finally {
lock.unlock();
}
}
public boolean addPeer(Peer peer) {
long key = peer.getSessionId();
Lock lock = stripes.get(key).writeLock();
lock.lock();
try {
BlockingDeque<Peer> userPeers = peers.getIfPresent(key);
if (userPeers == null) {
userPeers = new LinkedBlockingDeque<Peer>();
peers.put(key, userPeers);
}
UserAuthorities authorities = restoreSession(key);
if (authorities != null) {
peer.setAuthorities(authorities);
}
return userPeers.offer(peer);
} finally {
lock.unlock();
}
}
public void removePeer(Peer peer) {
long sessionId = peer.getSessionId();
Lock lock = stripes.get(sessionId).writeLock();
peers.cleanUp();
lock.lock();
try {
UserAuthorities authorities = null;
if (peers.getIfPresent(sessionId) != null) {
authorities = peers.getIfPresent(sessionId).getFirst().getAuthorities();
authToRestore.put(sessionId, authorities);
peers.getIfPresent(sessionId).remove(peer);
}
} finally {
lock.unlock();
}
}
public void removePeers(long sessionId) {
Lock lock = stripes.get(sessionId).writeLock();
lock.lock();
try {
peers.invalidate(sessionId);
authToRestore.invalidate(sessionId);
} finally {
lock.unlock();
}
}
private UserAuthorities restoreSession(long sessionId) {
Lock lock = stripes.get(sessionId).readLock();
peers.cleanUp();
authToRestore.cleanUp();
lock.lock();
try {
BlockingDeque<Peer> activePeers = peers.getIfPresent(sessionId);
return (activePeers != null && !activePeers.isEmpty()) ? activePeers.getFirst().getAuthorities() : authToRestore.getIfPresent(sessionId);
} finally {
lock.unlock();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<h1>1. Thread safety</h1>\n\n<p>From a concurrency stand-point, I don't see any issue with the code: reading is guarded by the <code>readLock</code>, all the updates are guarded by the <code>writeLock</code>, and you're using thread-safe <code>BlockingDeque</code>s for the values.</p>\n\n<p>However, you're returning the actual <code>BlockingDeque<Peer></code> from the <code>Cache</code> in <code>getPeers()</code>, so you're not mandating going through your <code>PeersContainer</code> to manipulate the values. You depend on how the other objects collaborate.</p>\n\n<h1>2. Other considerations</h1>\n\n<p>From a more general stand-point, I'd make a few changes:</p>\n\n<h2>1. Consistent API usage</h2>\n\n<blockquote>\n<pre><code>public BlockingDeque<Peer> getPeers(long sessionId) {\n Lock lock = stripes.get(sessionId).readLock();\n peers.cleanUp();\n lock.lock();\n try { \n return peers.asMap().get(sessionId);\n } finally {\n lock.unlock();\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Why use <code>asMap()</code>? I'd stay with :</p>\n\n<pre><code>return peers.getIfPresent(sessionId);\n</code></pre>\n\n<h2>2. Intermixing blocks</h2>\n\n<p>Especially with locks, I like them close to where I use them. So instead of</p>\n\n<blockquote>\n<pre><code>Lock lock = stripes.get(sessionId).readLock();\npeers.cleanUp();\nlock.lock();\n</code></pre>\n</blockquote>\n\n<p>I'd write</p>\n\n<pre><code>peers.cleanUp();\nLock lock = stripes.get(sessionId).readLock();\nlock.lock();\n</code></pre>\n\n<h2>3. Multiple look-ups</h2>\n\n<p>Even if <code>Cache</code> is fast, no need to abuse it :). In <code>removePeer()</code>:</p>\n\n<blockquote>\n<pre><code>UserAuthorities authorities = null;\nif (peers.getIfPresent(sessionId) != null) {\n authorities = peers.getIfPresent(sessionId).getFirst().getAuthorities();\n authToRestore.put(sessionId, authorities);\n peers.getIfPresent(sessionId).remove(peer);\n}\n</code></pre>\n</blockquote>\n\n<p>can be replaced by (also fixing the unconditional <code>getFirst()</code> call):</p>\n\n<pre><code>BlockingDeque<Peer> userPeers = peers.getIfPresent(sessionId);\nif (userPeers != null && !userPeers.isEmpty()) {\n UserAuthorities authorities = userPeers.getFirst().getAuthorities();\n authToRestore.put(sessionId, authorities);\n userPeers.remove(peer);\n}\n</code></pre>\n\n<h2>4. Excessive <code>cleanUp</code></h2>\n\n<p>I understand you don't want to wait for Guava to decide when the removals should actually happen, but forcing it on every access might be overkill (and create more contention), and you still depend on a call to <code>PeersContainer</code> to trigger the clean-up.</p>\n\n<p>You could use some form of scheduler to call a global <code>PeersContainer.cleanUp()</code> method every minute, instead.</p>\n\n<hr>\n\n<p>Updated to answer the comment.</p>\n\n<h2>Unencapsulated modifications</h2>\n\n<p>By returning the actual <code>BlockingDeque<Peer></code> from the <code>Cache</code> in <code>getPeers()</code>, you leave the possibility to modify the <em>shared</em> collection outside of the <code>PeersContainer</code> context, which may or not have an impact depending on the \"friendliness\" of the code using that data. If it's under your control and you never modify (even by accident) the collection, then it should be fine.</p>\n\n<p>Otherwise, there are obviously 2 types of modifications:</p>\n\n<ul>\n<li>removing a <code>Peer</code>: OK, it's not there anymore, but to the <code>PeersContainer</code> it's not that big a deal, it can also happen if the entry expires in the cache</li>\n<li>adding a <code>Peer</code>: it won't have its <code>authorities</code> set, which means it might erase a <code>UserAuthorities</code> saved in the <code>authToRestore</code> cache by the removal of a previous <code>Peer</code> for the same session. Is it critical? I don't know, it's your application.</li>\n</ul>\n\n<h2>Cache expiration</h2>\n\n<p>From the <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/index.html?com/google/common/cache/CacheBuilder.html\" rel=\"nofollow\"><code>CacheBuilder</code> javadoc</a>:</p>\n\n<blockquote>\n <p>If expireAfterWrite or expireAfterAccess is requested entries may be evicted on each cache modification, on occasional cache accesses, or on calls to Cache.cleanUp(). Expired entries may be counted by Cache.size(), but will never be visible to read or write operations.</p>\n</blockquote>\n\n<p>Even if your cache doesn't have enough write activity, with enough read activity the expired entries will eventually be removed. But even if they're not removed yet, the <code>Cache</code> will <strong>never</strong> return entries once they're expired (it wouldn't be doing a very good job otherwise).</p>\n\n<p>The only reason why you may need to call <code>cleanUp()</code> in your case is because of the nature of your <code>RemovalListener</code>: you want to send some information back to the peer, so you want to do it in a timely manner after the entry has expired. It's up to you to define what \"timely\" means depending on your requirements, but in my opinion, it could be something between 15 seconds and 5 minutes.</p>\n\n<p>Anyway, the way it's implemented now, if you have a single, inactive peer (so no calls at all to the methods of <code>PeersContainer</code>), it'll never receive a logout, whereas with a scheduled task it would happen no matter what. And on the other hand, if you have enough activity in the application, the clean-up will happen naturally with the writes or numerous reads, and an extra, scheduled <code>cleanUp</code> call won't cost much, whereas calling <code>cleanUp()</code> on each and every call will cause contention because the clean-up needs to sequentially lock all the segments in the <code>Cache</code> to clean them one by one.</p>\n\n<hr>\n\n<p>Another round.</p>\n\n<p>You don't really need a <code>ReadWriteLock</code>:</p>\n\n<ul>\n<li>the <code>readLock</code> in <code>getPeers()</code> is useless since the <code>Cache</code> itself is thread-safe</li>\n<li>the one in <code>restoreSession()</code> is also useless because it's already guarded by the <code>writeLock</code> in <code>addPeer()</code>, its caller.</li>\n</ul>\n\n<p>So you could simplify a bit by using a simple <code>Lock</code>. The only parts you really need to guard by a lock are the ones where you modify the 2 <code>Caches</code>s.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T15:20:15.900",
"Id": "74749",
"Score": "0",
"body": "thanks for broad response. 1) Outside the `PeerContainer` I should only iterate the collection, that's why a implemented `get` method. Of course I can return a copy of `BlocckingDeque`, but I can't imagine scenario when it's harmful. Can you help? 4) As I understand `Cache` proceeds cleanups only on write operations. Then to force cache to return actual data on read operations I should cleanup explicitly. Am I wrong?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:12:26.077",
"Id": "74767",
"Score": "0",
"body": "Answer updated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T08:55:09.967",
"Id": "74910",
"Score": "1",
"body": "I've gotten a new insight after reading your other SO questions and sleeping on it: answer updated again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T09:23:37.193",
"Id": "74916",
"Score": "0",
"body": "thanks I'll do that. But I still can't grasp how the second cache will be helpfull for me/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T09:32:57.033",
"Id": "74918",
"Score": "0",
"body": "By \"the 2 caches\", I meant `peers` and `authToRestore`, not the extra cache in http://stackoverflow.com/a/22155141/1350869."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T14:29:01.133",
"Id": "43304",
"ParentId": "43295",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "43304",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T12:45:46.307",
"Id": "43295",
"Score": "8",
"Tags": [
"java",
"multithreading",
"concurrency",
"guava"
],
"Title": "Cache<Long, BlockingDeque<Peer>> combined with Striped<ReadWriteLock>: is it thread-safe"
}
|
43295
|
<p>I have a module (in file dialect.rb) defined as such:</p>
<pre><code>require 'dialect/generators/elements'
module Dialect
def self.included(caller)
caller.extend Dialect::Generator::Element
end
def self.version
"Dialect v#{Dialect::VERSION}"
end
end
</code></pre>
<p>Then I have the file dialect/generators/elements.rb, which looks like this:</p>
<pre><code>module Dialect
module Generator
module Element
puts Dialect.version
end
end
end
</code></pre>
<p>If I run my app, I get:</p>
<pre><code>/lib/dialect/generators/elements.rb:7:in `<module:Element>':
undefined method `version' for Dialect:Module (NoMethodError)
</code></pre>
<p>My question/problem is: I didn't understand why the Element module could not find the version method here.</p>
<p>How I call Dialect is like this:</p>
<pre><code>require 'dialect'
class PageTest
include Dialect
end
</code></pre>
<p>So you can see Dialect is mixed-in to an existing class. It's when this class is instantiated that I get the error above.</p>
<p>When I try a simple IRB session doing what appears to be this same logic, this all seems to work:</p>
<pre><code>irb(main):001:0> module Dialect
irb(main):002:1> def self.version
irb(main):003:2> puts "Version number"
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> module Dialect
irb(main):007:1> module Generator
irb(main):008:2> module Element
irb(main):009:3> puts Dialect.version
irb(main):010:3> end
irb(main):011:2> end
irb(main):012:1> end
Version number
</code></pre>
<p>Here I get the "Version number" text back, which tells me (I think?) that Dialect::Generator::Element can call the method version on Dialect.</p>
<p>The issue ended up being corrected by simply moving my require statement to the end, like this:</p>
<pre><code>module Dialect
def self.included(caller)
caller.extend Dialect::Generator::Element
end
def self.version
"Dialect v#{Dialect::VERSION}"
end
end
require 'dialect/generators/elements'
</code></pre>
<p>Having the require statement at the end solves the problem I was having.</p>
<p>The question then becomes: is this a good way to do this? I feel like making my logic depend on where the require statement goes seems like a bad idea.</p>
|
[] |
[
{
"body": "<p>The <code>require</code> line in the first file means that ruby runs the <em>second</em> file before the first file, which is <em>before</em> the <code>version</code> method is declared...</p>\n\n<p>Doing it the other way around will work, since only when <code>included</code> is called is the module <code>Element</code> is required.</p>\n\n<p>dialect/dialect.rb:</p>\n\n<pre><code>module Dialect\n def self.included(caller)\n caller.extend Dialect::Generator::Element\n end\n\n def self.version\n \"Dialect v#{Dialect::VERSION}\"\n end\nend\n</code></pre>\n\n<p>dialect/generators/elements.rb: </p>\n\n<pre><code>require 'dialect/dialect'\n\nmodule Dialect\n module Generator\n module Element\n\n puts Dialect.version\n\n end\n end\nend\n</code></pre>\n\n<p>Alternatively, you could also write a file declaring only the version:</p>\n\n<p>dialect/version.rb:</p>\n\n<pre><code>module Dialect \n def self.version\n \"Dialect v#{Dialect::VERSION}\"\n end\nend\n</code></pre>\n\n<p><strong>Edit</strong></p>\n\n<p>To answer your question - this is <em>not</em> a good way to do this. The problem you encountered with the <code>require</code> hints to <em>circular dependency</em> - <code>Dialect</code> calls <code>Element</code>, which uses <code>Dialect</code> on its creation.</p>\n\n<p>The correct resolution is to break this dependency by using my <code>version.rb</code> suggestion above, so the code will look like this:</p>\n\n<p>dialect/version.rb:</p>\n\n<pre><code>module Dialect \n def self.version\n \"Dialect v#{Dialect::VERSION}\"\n end\nend\n</code></pre>\n\n<p>dialect/generators/elements.rb: </p>\n\n<pre><code>require 'dialect/version'\n\nmodule Dialect\n module Generator\n module Element\n\n puts Dialect.version\n\n end\n end\nend\n</code></pre>\n\n<p>dialect/dialect.rb:</p>\n\n<pre><code>require 'dialect/version'\nrequire 'dialect/generators/elements'\n\nmodule Dialect\n def self.included(caller)\n caller.extend Dialect::Generator::Element\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T13:18:26.830",
"Id": "43300",
"ParentId": "43296",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T12:53:35.347",
"Id": "43296",
"Score": "1",
"Tags": [
"ruby",
"modules"
],
"Title": "Calling a Class Method on a Module"
}
|
43296
|
<p>I use the following code <code><div><?php echo $obj->text; ?></div></code> in while loop.</p>
<p>Is this the best way?</p>
<p>Is there a better way, either to optimize or replace this code?</p>
<pre><code><?php
$akhbarkotah1 = $conn->prepare("SELECT text,time FROM small WHERE active='0' ORDER BY time DESC LIMIT 10");
$akhbarkotah1->execute();
while($obj = $akhbarkotah1->fetch(PDO::FETCH_OBJ)){
?>
<div><?php echo $obj->text; ?></div>
<?php
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T18:36:22.483",
"Id": "74791",
"Score": "0",
"body": "Does this code work?"
}
] |
[
{
"body": "<p>It looks like you don't really need to exit out of the PHP tag on this one.</p>\n\n<pre><code><?php\n $akhbarkotah1 = $conn->prepare(\"SELECT text,time FROM small WHERE active='0' ORDER BY time DESC LIMIT 10\");\n $akhbarkotah1->execute();\n while($obj = $akhbarkotah1->fetch(PDO::FETCH_OBJ)){\n echo \"<div>\" . $obj->text . \"</div>\";\n }\n?>\n</code></pre>\n\n<p>This simplifies the code and shortens it. I think that I have the Syntax Correct. I am rather new to PHP myself but I am pretty sure that this will work exactly the same.</p>\n\n<p>If you leave your code the other way you should indent the HTML to match what is inside the PHP since it is really inside the PHP (kind of/sort of) like this</p>\n\n<pre><code><?php\n $akhbarkotah1 = $conn->prepare(\"SELECT text,time FROM small WHERE active='0' ORDER BY time DESC LIMIT 10\");\n $akhbarkotah1->execute();\n while($obj = $akhbarkotah1->fetch(PDO::FETCH_OBJ)){\n?>\n <div><?php echo $obj->text; ?></div>\n<?php\n }\n?>\n</code></pre>\n\n<p>I personally don't like the way that this looks though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T15:13:06.677",
"Id": "74746",
"Score": "0",
"body": "thanks , but i have more than a <div> tag html code about 10 line in whaile loop and i dont write here and my main question is for about replace a code for while, for example foreach or dont using loop and ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T15:16:57.170",
"Id": "74748",
"Score": "2",
"body": "then you probably want to post the full code. because what you have here can be simplified to what I showed you. you can put that same echo line that I used into the while statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T15:29:11.817",
"Id": "74752",
"Score": "0",
"body": "my problem is using another code replace while($obj = $akhbarkotah1->fetch(PDO::FETCH_OBJ))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T16:19:41.187",
"Id": "74759",
"Score": "0",
"body": "what do you mean \"code replace\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T16:21:56.897",
"Id": "74761",
"Score": "0",
"body": "i want save array in variable and call with $var[0]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:55:47.437",
"Id": "74780",
"Score": "0",
"body": "so in other words you want us to tell you how to code this using a `For Each`? because that is **OFF-TOPIC** on this site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T18:24:27.503",
"Id": "74785",
"Score": "0",
"body": "no , i say for each is an example. So While is optimize and best way for fetch?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T14:58:23.177",
"Id": "43307",
"ParentId": "43305",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "43307",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T14:36:22.307",
"Id": "43305",
"Score": "4",
"Tags": [
"php"
],
"Title": "Building <div>text</div> inside a while loop"
}
|
43305
|
<p>C++11 is great. Probably one of the most beautiful features (in my opinion) is the so-called range-based-for-loop.
Instead of</p>
<pre><code>for ( std::size_t i(0); i < range.size(); ++i )
{
// do something to range[i];
}
</code></pre>
<p>or</p>
<pre><code>for ( Range::iterator it(range.begin()); it != range.end(); ++it )
{
// do something to *it;
}
</code></pre>
<p>or simplified with C++11 auto:</p>
<pre><code>for ( auto it(range.begin()); it != range.end(); ++it )
{
// do something to *it;
}
</code></pre>
<p>we can say this:</p>
<pre><code>for ( auto& entry : range )
{
// do something with entry.
}
</code></pre>
<p>This is very expressive: We talk about the entry, rather than the i^th position in the range or the iterator pointing to an entry. However, this syntax lacks the ability of having subranges (e.g. ignoring the last entry). In a series of small helper structs / methods, I want to add this functionality in a clean way.</p>
<p>So much for my motivation ;-) Now, for the real deal.</p>
<p>In this post, I address conditions on the entries of <code>range</code>. Basically, the helper code should perform the equivalent of</p>
<pre><code>for ( auto& entry : range )
{
if ( condition(entry) )
{
// do something to entry.
}
}
</code></pre>
<p>but without that level of indentation.</p>
<p>Here is the code for ConditionalRange:</p>
<pre><code>template <typename Range, typename Runnable>
ConditionalRange<Range, Runnable> makeConditionalRange(Range& range, Runnable&& condition)
{
static_assert(std::is_same<decltype(condition(*std::declval<Range>().begin())), bool>::value, "Condition must return a boolean value.");
return ConditionalRange<Range, Runnable>(range, std::forward<Runnable>(condition));
}
template <typename Range, typename Runnable>
struct ConditionalRange
{
public:
friend ConditionalRange makeConditionalRange<>(Range&, Runnable&&);
public:
using iterator_type = ConditionalIterator<decltype(std::declval<Range>().begin()), Runnable>;
iterator_type begin() const
{
auto b = range.begin();
while ( b != range.end() && !condition(*b) )
{
++b;
}
return ConditionalIterator<decltype(std::declval<Range>().begin()), Runnable>(b, range.end(), condition);
}
iterator_type end() const
{
return ConditionalIterator<decltype(std::declval<Range>().begin()), Runnable>(range.end(), range.end(), condition);
}
private:
ConditionalRange(Range& range_, Runnable&& condition_)
:
range(range_),
condition(std::forward<Runnable>(condition_))
{
}
private:
Range& range;
Runnable condition;
};
</code></pre>
<p>This is the helper struct for the iterator:</p>
<pre><code>template <typename Iterator, typename Runnable>
struct ConditionalIterator
{
private:
Iterator iterator;
Iterator end;
const Runnable& condition;
public:
ConditionalIterator(Iterator b, Iterator e, const Runnable& r)
:
iterator(b),
end(e),
condition(r)
{
}
auto operator*() -> decltype(*iterator)
{
return *iterator;
}
ConditionalIterator& operator++()
{
do
{
++iterator;
}
while ( iterator != end && !condition(*iterator) );
return *this;
}
bool operator==(const ConditionalIterator& second)
{
return iterator == second.iterator;
}
bool operator!=(const ConditionalIterator& second)
{
return !(*this == second);
}
};
</code></pre>
<p>The intended usage is:</p>
<pre><code>std::vector<int> ns{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for ( const auto& n : makeConditionalRange(ns, [](int a) { return a % 2 == 0; }) )
{
std::cout << n << " ";
}
std::cout << "\n";
</code></pre>
<p>Demo: <a href="http://ideone.com/XCgCny">click here!</a></p>
<p>What are weaknesses of my approach? With what kind of arguments does it fail, although it shouldn't in the perfect world?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T16:20:54.367",
"Id": "74760",
"Score": "1",
"body": "I can see no weaknesses, but I think you should consider renaming makeConditionalRange with something that focuses on client code appearance, not on \"making a conditional range\". By that, I mean that client code should look like this instead: `for(const auto& n: iterate_if(ns, [](int a) { return a % 2 == 0; }) )`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:37:27.323",
"Id": "74773",
"Score": "1",
"body": "So does the intent here differ significantly from a Boost [`filter_iterator`](http://www.boost.org/doc/libs/1_55_0/libs/iterator/doc/filter_iterator.html)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:39:50.827",
"Id": "74776",
"Score": "0",
"body": "@JerryCoffin No it doesn't. I simply haven't looked into Boost ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T18:40:48.603",
"Id": "74793",
"Score": "0",
"body": "Also potentially interesting: http://codereview.stackexchange.com/questions/35997/c-linq-like-library"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T01:43:06.353",
"Id": "74865",
"Score": "0",
"body": "@stefan: Since boost is the proving ground for libraries before they move into the standard. You should probably start using boost."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T01:48:47.260",
"Id": "74866",
"Score": "1",
"body": "The most common test for iterators `operator!=` optimize this over `operator==`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T13:30:03.297",
"Id": "74946",
"Score": "0",
"body": "@LokiAstari Sure, operator!= is more common. But I guess the compiler is smart enough to perform this optimization. After all, it's inline-able. Concerning boost: I'm not a big fan. I'm much more a fan of having a small set of self-written helpers for which I can guarantee correctness. I don't want to rely on another library for which there are several versions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T01:38:03.777",
"Id": "75129",
"Score": "2",
"body": "@stefan: To be blunt that's silly. Its like saying I don't wont to buy a car from the standard manufacturers because I want to build one that runs off seaweed myself to guarantee that it does not cause pollution. The problem is your set of libraries are going to be infinitely more buggy than boost because you only have one set of eyes looking at them. Boost has thousands of people checking and validating the code fixing and providing feedback to make sure the correct idioms are used correctly. Read: http://stackoverflow.com/a/149305/14065"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T01:39:18.780",
"Id": "75130",
"Score": "0",
"body": "@stefan: Additionally. Its worth watching because the next set of additions to `ST2` will be coming from boost. So you have to learn about that anyway if you want to stay up to date on the standard library."
}
] |
[
{
"body": "<p>You can use braces to return from your functions. That way, you won't have to repeat long and cumbersome types (DRY, as much as possible). For example, <code>ConditionalRange::end</code>:</p>\n\n<pre><code>iterator_type end() const\n{\n return { range.end(), range.end(), condition };\n}\n</code></pre>\n\n<p>Also, you probably want your function to accept C-style arrays too. Therefore, you should use <code>std::begin</code> and <code>std::end</code> instead of calling the member functions:</p>\n\n<pre><code>iterator_type end() const\n{\n return { std::end(range), std::end(range), condition };\n}\n</code></pre>\n\n<p>With that (everywhere in your code) and some trivial changes, your code will also work for C-style arrays (tested <a href=\"http://coliru.stacked-crooked.com/a/c86df29b547c6267\">here</a> and it works fine).</p>\n\n<h2>Naming your function</h2>\n\n<p>The name <code>makeConditionalRange</code> is quite long. The function you created already exists in other libraries and programming languages (Python comes to my mind) under the name <code>filter</code>. You should consider changing its name in order for many users to recognize the name at first glance (moreover, it will be shorter).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T16:19:45.283",
"Id": "43316",
"ParentId": "43308",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T15:07:31.343",
"Id": "43308",
"Score": "15",
"Tags": [
"c++",
"c++11"
],
"Title": "Making C++11 range-based for loops a bit more useful"
}
|
43308
|
<p>I am looking over some existing code (see below). The problem of grouping in the same place the presentation logic of some fields (like price, currency) was solved as extension methods on <code>int</code>, <code>double</code>, and so on...</p>
<p>I do not really like this. What do you think? How could it be done more elegantly and even unit testable?</p>
<pre><code>namespace RestApi.Services.Helpers
{
using System;
using System.Globalization;
using System.Web.Mvc;
using Contracts.Fg;
using FrontEnd.CommonServices.Localization;
public enum QuoteDisplayType
{
BidAsk,
Difference,
Other
}
public static class CommonFormatterExtensions
{
private static ILocalizationService localizationService;
private static ILocalizationService LocalizationService
{
get { return localizationService ?? (localizationService = DependencyResolver.Current.GetService<ILocalizationService>()); }
}
private const string NoInformationText = "---";
private const string MarketLocalizationKey = "FormatAmountExtensions.MarketQuote";
private const string PercentageSymbol = "%";
private const string CurrencyCodeEuro = "EUR";
private const string CurrencyCodeUsDollar = "USD";
private const string CurrencyCodeBritishPound = "GBP";
private const string CurrencyCodeDutchGuilder = "NLG";
private const string SymbolEuro = "€";
private const string SymbolDollar = "$";
private const string SymbolDutchGuilders = "fl";
private const string SymbolBritishPound = "£";
private const string FormatWithMinTwoDecimals = "#,##0.00###";
private const string FormatWithAllTrailingDecimalZeroesSupressed = "#,##0.#####";
/// <summary>
/// Returns a formatted number for securities. When no fractions (decimals) are present, the number is formatted without decimals.
/// Note that altough we (topline) currrently do not support fractions (decimals) in security holdings, we do receive the number as a 'double' from Topline, and therefore also support the formatting of fractions.
/// </summary>
/// <param name="amount">amount to be formatted</param>
/// <returns>a string represented the formatted number</returns>
public static string FormattedNumberOfSecurities(this double amount)
{
return amount.Equals(0)
? NoInformationText
: amount.ToString(FormatWithAllTrailingDecimalZeroesSupressed, CultureInfo.CurrentCulture);
}
public static string FormattedNumberOfSecurities(this double? amount)
{
return amount.HasValue ? amount.Value.FormattedNumberOfSecurities() : NoInformationText;
}
public static string FormattedNumberOfSecurities(this int amount)
{
return amount.Equals(0)
? NoInformationText
: amount.ToString(FormatWithAllTrailingDecimalZeroesSupressed, CultureInfo.CurrentCulture);
}
public static string FormattedNumberOfSecurities(this int? amount)
{
return amount.HasValue ? amount.Value.FormattedNumberOfSecurities() : NoInformationText;
}
/// <summary>
/// Returns a formatted price for a security. Result has at least 2 decimals and max 5 decimals.
/// </summary>
/// <param name="amount">amount (price) to be formatted</param>
/// <param name="mainsecurityType">main security type of the security for which the price is to be formatted</param>
/// <param name="amountCurrencyCode">currency in which the security is traded</param>
/// <param name="quoteDisplayType">whether or not it is a bid/ask quote</param>
/// <returns>a string represented the formatted price</returns>
public static string FormattedSecurityPrice(this double amount, Hoofdfondstype mainsecurityType, string amountCurrencyCode, QuoteDisplayType quoteDisplayType = QuoteDisplayType.Other)
{
string formattedAmount;
if (amount.Equals(0))
{
//should only be applicable to Bid/Aks quotes.
formattedAmount = quoteDisplayType == QuoteDisplayType.BidAsk ? LocalizationService.Localize(MarketLocalizationKey) : NoInformationText;
}
else
{
formattedAmount = amount.ToString(FormatWithMinTwoDecimals, CultureInfo.CurrentCulture);
if (amountCurrencyCode != CurrencyCodeEuro && mainsecurityType != Hoofdfondstype.Indices && quoteDisplayType != QuoteDisplayType.Difference)
// Security prices and quotes are always shown with a currency indication, except when in EURO or when security is an index.
// A price difference is never displayed with a currency indication.
{
formattedAmount = AddCurrencyIndication(amountCurrencyCode, formattedAmount);
}
if ((quoteDisplayType != QuoteDisplayType.Difference) &&
(mainsecurityType == Hoofdfondstype.Coupons || mainsecurityType == Hoofdfondstype.Obligatie ||
mainsecurityType == Hoofdfondstype.ObligatieEmissies))
// Price of coupons and bonds is displayed as percentage, except when the price reflects a difference.
{
formattedAmount = String.Format(CultureInfo.CurrentCulture, "{0} {1}", formattedAmount,
PercentageSymbol);
}
}
return formattedAmount;
}
/// <summary>
/// Returns a formatted price for a security. Result has at least 2 decimals and max 5 decimals.
/// </summary>
/// <param name="amount">nullable amount (price) to be formatted</param>
/// <param name="mainsecurityType">main security type of the security for which the price is to be formatted</param>
/// <param name="amountCurrencyCode">currency in which the security is traded</param>
/// <returns>a string represented the formatted price or three dashes if no value is available</returns>
public static string FormattedSecurityPrice(this double? amount, Hoofdfondstype mainsecurityType, string amountCurrencyCode)
{
return amount.HasValue
? amount.Value.FormattedSecurityPrice(mainsecurityType, amountCurrencyCode)
: NoInformationText;
}
private static string AddCurrencyIndication(string amountCurrencyCode, string formattedAmount)
{
switch (amountCurrencyCode)
{
case CurrencyCodeUsDollar:
formattedAmount = SymbolDollar + " " + formattedAmount;
break;
case CurrencyCodeEuro:
formattedAmount = SymbolEuro + " " + formattedAmount;
break;
case CurrencyCodeDutchGuilder:
formattedAmount = SymbolDutchGuilders + " " + formattedAmount;
break;
case CurrencyCodeBritishPound:
formattedAmount = SymbolBritishPound + " " + formattedAmount;
break;
default:
formattedAmount = amountCurrencyCode + " " + formattedAmount;
break;
}
return formattedAmount;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The big switch statement in <code>AddCurrencyIndication</code> is a pretty good sign of where to start. If you had to add another type of currency, you'd have to go in and add new cases, which violates the open/close principle. There's a lot of places where you either do already, or potentially in the future, have to go in and add new items or logic when a new currency is added. So what you probably want is a formatter class for each currency: <code>EuroFormatter</code>, <code>UsDollarFormatter</code>, etc.</p>\n\n<p>You would probably have an interface <code>ICurrencyFormatter</code> with at least <code>FormattedSecurityPrice</code> as a non-static public member on it.</p>\n\n<p>It looks like you have some logic that is common, so you can put that in an abstract base class. If it's something that might change for specific currencies (I notice the check for if the currency is Euros inside <code>FormattedSecurityPrice</code> for example) then you can make it virtual and override where needed in the specific class. </p>\n\n<p>Your const strings can be replaced with overrideable properties, so for example instead of</p>\n\n<pre><code>private const string SymbolEuro = \"€\";\n</code></pre>\n\n<p>You'd have in <code>CurrencyFormatterBase</code>:</p>\n\n<pre><code>protected abstract string Symbol { get; }\n</code></pre>\n\n<p>And inside <code>EuroFormatter</code>:</p>\n\n<pre><code>protected override string Symbol { get { return \"€\"; } }\n</code></pre>\n\n<p>Depending on how they're used, it's possible that some of your methods, like <code>FormattedNumberOfSecurities</code> might be appropriate to keep as extension methods. But really most of those look like they should probably be regular static or instance methods.</p>\n\n<p>You also have a bit of repetition within the <code>FormattedNumberOfSecurities</code> overloads. You might consider pulling some of the common logic out into a private method. For example you could convert whatever type is passed in to string, then pass that string along to a private method that deals with the formatting and handling of nulls.</p>\n\n<p>A final thing to investigate would be whether <code>Hoofdfondstype</code> and <code>QuoteDisplayType</code> could be refactored into classes with their own functionality which could be called out to rather than having to do complex logic based on which one you have. But that's a more wide-ranging change and I couldn't really recommend whether or not it's a good idea in this particular situation without seeing a lot more of the project's code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:28:15.620",
"Id": "43321",
"ParentId": "43309",
"Score": "10"
}
},
{
"body": "<p>I like the use of comments in this code snippet. They are explaining why a certain piece of code is done a certain way, rather than what it is doing.</p>\n\n<p>I'm not sure about using extension methods for this functionality, it kind of feels like its abusing the feature.</p>\n\n<p>I would have probably made an interface IFormatter, which could then be injected as a singleton from an IoC container as required. With the <code>CurrencyInformation</code> class I mention below, it is possible to add currencies without ever having to touch this code again.</p>\n\n<p>For starters, I would move the currency information into its own class. As part of that I would pass:</p>\n\n<pre><code>public class CurrencyInformation\n{\n public string CurrencyCode { get; private set; }\n public string Symbol { get; private set; }\n\n public CurrencyInformation(string currencyCode, string symbol)\n {\n // Null and empty string checks\n // assign to properties\n }\n\n public string Format(string formattedAmount)\n {\n return string.Format(\"{0} {1}\", CurrencyCode, formattedAmount);\n }\n}\n</code></pre>\n\n<p>This will eliminate a number of constants from the extension class and replace them with a simple IDictionary. This makes it much easier to add more currencies in the future.</p>\n\n<pre><code>private static IDictionary<string, CurrencyInformation> Currencies = new Dictionary<string, CurrencyInformation>\n {\n {\"EUR\", new CurrencyInformation(\"EUR\", \"€\")},\n // fill in rest of currencies\n }\n</code></pre>\n\n<p>The <code>AddCurrencyIndication</code> method now looks like this</p>\n\n<pre><code> private static string AddCurrencyIndication(string amountCurrencyCode, string formattedAmount)\n {\n\n if (!Currencies.ContainsKey(amountCurrencyCode)) return string.Format(\"{0} {1}\", amountCurrencyCode, formattedAmount);\n\n return Currencies[amountCurrencyCode].Format(formattedAmount);\n }\n</code></pre>\n\n<p>Having this class also allows the formatting to be different for different currencies (i.e. using <a href=\"http://www.dfa.cornell.edu/treasurer/cashoperations/cashmanagement/internationalfunds/conversion.cfm\">\",\" instead of \".\" to separate dollars and cents</a></p>\n\n<p>If you do move this class to not be extension methods, you could actually inject all the information from a config file, so you'd never have to touch any of these classes, but this technique is a little beyond this review.</p>\n\n<p>I like that you've used ternary operations for your formatting functions, it makes things easy to read. I would suggest fixing the formatting so they are all formatted the same. This way, people who are reading it in the future don't have to keep changing their brain between the two. The format I like is:</p>\n\n<pre><code>return <condition>\n ? <true>\n : <false>;\n</code></pre>\n\n<p>My last item is in <code>FormattedSecurityPrice</code>. This is the only method you've used an if/else in the entire class. I would change this to either exit early (add a return in the if part, and remove the else) or change it to a ternary operator like the rest of the class. The else part could be moved to its own method to allow for this to happen.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:32:09.827",
"Id": "43322",
"ParentId": "43309",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T15:39:00.867",
"Id": "43309",
"Score": "10",
"Tags": [
"c#",
"formatting"
],
"Title": "Value formatters (for entities like price, currencies so on)"
}
|
43309
|
<p>This function updates the user last login date on the user collection. I guess there are too many brackets and much spaghetti. How can I shorten this code?</p>
<pre><code>(function () {
'use strict';
var database = require('mongodb');
var util = require('util');
var constants = require('../constants');
var dbhelper = {
updateLastSeenDate: function (me) {
database.connect(constants.variables.connection, function (err, db) {
if (err) {
db.close();
throw err;
}
var bsonID = database.BSONPure.ObjectID(me);
var collection = db.collection('users');
collection.findOne({
_id: bsonID
}, function (err, result) {
if (result) {
result.lastLoginDate = Date.now();
collection.update({
_id: bsonID
}, result, function (err, u) {
if (err) {
db.close();
throw err;
}
util.log('Update complete: updateLastSeenDate');
db.close();
}); //end of update
}
});
});
}
};
module.exports = dbhelper;
}());
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T16:07:15.783",
"Id": "74757",
"Score": "1",
"body": "Welcome to Code Review! Your question only contains code. Could you edit it with a proper context ? You could specify what your code is doing, what you think is the major point that need refactoring (note that we could do general review but if you a special point you can mention it)."
}
] |
[
{
"body": "<p>Here's some points. I commented directly in the code.</p>\n\n<pre><code>(function () {\n 'use strict';\n\n //Why do you use `database` instead of `mongo` or `mongodb`.\n //It can become confusing later in the code when you are using `db`.\n //It will be hard to tell the diffence between database and db.\n var database = require('mongodb');\n var util = require('util');\n\n var constants = require('../constants');\n\n var dbhelper = {\n //`me` Will it be you all the time ?\n //You should think a more meaningful name such as `logedInUserId`\n updateLastSeenDate: function (me) {\n //Do you really want to connect and close the database everything you want to update a field ?\n //You should consider keeping the connection alive and share it across the whole process.\n database.connect(constants.variables.connection, function (err, db) {\n if (err) {\n db.close();\n throw err;\n }\n var bsonID = database.BSONPure.ObjectID(me);\n var collection = db.collection('users');\n\n //nesting calls to async function is affecting readability, testability and maintability.\n //You should consider using workflow library such as async\n collection.findOne({\n _id: bsonID\n }, function (err, result) {\n if (result) {\n result.lastLoginDate = Date.now();\n\n //Here's another nested call\n collection.update({\n _id: bsonID\n }, result, function (err, u) {\n //Using async you could handle errors in only one place.\n if (err) {\n db.close();\n throw err;\n }\n util.log('Update complete: updateLastSeenDate');\n db.close();\n });\n }\n });\n });\n }\n };\n\n module.exports = dbhelper;\n}());\n</code></pre>\n\n<p>I would use async <a href=\"https://github.com/caolan/async#waterfall\" rel=\"nofollow\">https://github.com/caolan/async#waterfall</a>, change a few variable names and share the connection. Since node.js in single threaded you can open only one connection and share it to all your modules.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T01:18:34.600",
"Id": "74863",
"Score": "0",
"body": "how can i do \"keeping the connection alive\", can you prefer a sample"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T13:46:48.440",
"Id": "74952",
"Score": "0",
"body": "You could check this answer http://stackoverflow.com/a/14464750/327004 and there's an example here https://groups.google.com/forum/#!msg/node-mongodb-native/mSGnnuG8C1o/SOnHKH07h_sJ"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T21:01:22.487",
"Id": "43336",
"ParentId": "43312",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T16:00:35.943",
"Id": "43312",
"Score": "1",
"Tags": [
"javascript",
"optimization",
"node.js",
"mongodb"
],
"Title": "Update user's last login date"
}
|
43312
|
<p>Here is my code: </p>
<pre><code>$sql = <<<END
Select Sum(p)/Sum(w)*100 as present FROM attendance group by month
END;
$query = mysql_query($sql) or die($sql . ' - ' . mysql_error());
$names = array();
while ($row = mysql_fetch_array($query)) {
$names[] = $row[0];
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T16:28:03.317",
"Id": "74762",
"Score": "0",
"body": "Don't use mysql_* functions, are deprecated. Use mysqli_* or PDO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T16:31:24.137",
"Id": "74763",
"Score": "0",
"body": "@geomo I know that I shouldn't. As I understand mysql_function better, so I use it. However there might be time when I must move to PDO or mysqli."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T09:37:25.690",
"Id": "74920",
"Score": "2",
"body": "@MawiaHL: That time has come... that time was yesterday, to be honest. It's been three years(!) since `mysql_*` [was first put up for deprecation](http://thread.gmane.org/gmane.comp.php.devel/66726), and not a moment too soon. Saying you're reluctant to change because the old extension feels familiar is understandable, but that attitude is like us still living in caves, because it felt familiar to our cave-men ancestors. Moving with the times is what gets you ahead"
}
] |
[
{
"body": "<p>Regardless of how well you know the <code>mysql_*</code> functions, you shouldn't use them. There are counterparts within PDO. See <a href=\"https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php/12860046#12860046\">this answer</a> on stackoverflow for why.</p>\n\n<p>This is how you'd do that in PDO:</p>\n\n<pre><code>$db = new PDO(\"mysql:localhost;dbname=database\", $user, $password);\n\n// set the default for ->fetch() and ->fetchAll() to associative array\n$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);\n// throw an exception instead of an error on fail\n$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\n\ntry {\n $sql = \"(select sum(p) / sum(w) * 100) as present from attendance group by month\";\n\n // make sure you have php5-mysqlnd installed.\n // (MySQL native driver. It makes upgrading PHP easy as there's no library conflicts).\n // You can also work with different versions of MySQL without errors.\n $names = $db->query($sql)->fetchAll();\n\n // array_column will take an associative array and a key and flatten it into an array\n return array_column($names, \"present\");\n} catch (PDOException $e) {\n echo \"<pre>\" . $e->getTraceAsString() . \"</pre>\";\n}\n</code></pre>\n\n<p>For error-handling, you should really use exceptions. Otherwise, check the value of <code>$db->errorInfo()</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:01:43.917",
"Id": "43319",
"ParentId": "43315",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "43319",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T16:13:11.723",
"Id": "43315",
"Score": "2",
"Tags": [
"php",
"mysql"
],
"Title": "Better way to load Mysql query in PHP Array"
}
|
43315
|
<p>I have created a PHP login system based off of <a href="https://defuse.ca/php-pbkdf2.htm" rel="nofollow">this site</a>. My main concern is: Is it secure? I chose that because to me it looked secure, but a 2nd or 3rd opinion never hurts. The idea of the project is to have something I can just pull into a new project directory and start off from there depending on my needs so it so it does have a few unused files.</p>
<p><strong>Authentification Class</strong></p>
<pre><code><?php
class authentification extends SQLQUERY
{
/*
* Hash code taken from:
* Password hashing with PBKDF2.
* Author: havoc AT defuse.ca
* www: https://defuse.ca/php-pbkdf2.htm
*/
/*
* Authentifications EXCEPTIONS (1000)
* 1001 : Login already exists
* 1002 : Email already exists
* 1003 : Current user is not a guest (for registration)
* 1004 : Submitted registration password is too common
* 1005 : Submitted registration password is too short
* 1100 : User password not in correct format (when this is raised, we force user to enter a new password, if it was valid to start with)
* This allows for including this code with an existing database
* 1101 : User password is expired
* 1102 : User is not properly activated
* 1200 : Access violation - User is not admin
*
*/
// These constants may be changed without breaking existing hashes.
const PBKDF2_HASH_ALGORITHM = "sha256";
const PBKDF2_ITERATIONS = 1000;
const PBKDF2_SALT_BYTES = 24;
const PBKDF2_HASH_BYTES = 24;
const HASH_SECTIONS = 4;
const HASH_ALGORITHM_INDEX = 0;
const HASH_ITERATION_INDEX = 1;
const HASH_SALT_INDEX = 2;
const HASH_PBKDF2_INDEX = 3;
const MINIMUM_PASS_LENGTH = 1;
const ADMIN_CAN_LOGIN = 1; //DISABLED RETURNS WRONG PASSWORD ON ALL ADMIN LOGIN ATTEMPTS
const SESSION_TIMEOUT = 86400; //IN SECONDS
const DEFAULT_LANG_ID = "dl_basicl"; //Session key for default language
public $login = '';
public $email = '';
public $pass = '';
private $sess_id = '';
private $user_id = -1;
public function __construct($db, $login, $email, $pass, $user_id = -1)
{
SQLQUERY::__construct($db);
$this->login = $login;
$this->email = $email;
$this->pass = $pass;
//for when it is already known from a global
$this->user_id = $user_id;
//set user session
$this->sess_id = session_id();
if(!$this->sess_id) {
$this->sess_id = $PHPSESSID;
}
}
/**
*
* @return boolean checks if CheckCredentials are valid.
*/
public function login()
{
$this->sess_clear();
if($this->CheckCredentials()){
$this->sess_write();
$this->auth_user_update_date();
$this->auth_user_login_count();
return true;
}
return false;
}
/**
*
* @return boolean Logs the user out
*/
public function logout()
{
return $this->sess_delete();
}
/**
*
* @return array returns the user infos
* Array returns id, login, user_level, default_lang, email
*/
public function checkuser()
{
$this->sess_clear();
$id = $this->sess_read();
$this->user_id = $id ? $id : -1;
$this->auth_user_update_date();
return $this->get_user_infos();
}
/**
*
* @return boolean Gets whether user should login or if it is first admin setup
*/
public function shouldLogAdmin()
{
if($this->IsLoginAdmin())
{
return $this->HasPassword();
}
else
{
//if it is not an admin, return false
throw new Exception("Current user is not an admin", 1200);
}
}
/**
*
* @return boolean Sets the first admin password
*/
public function setAdminPassword()
{
$rs = SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthUpdateFirstAdminPass()), array($this->create_hash(), $this->login));
return true;
}
/**
* Updates password through user id from the panel
* @return boolean updates a new password based on the user id
*/
public function updatePassword()
{
$rs = SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthUpdatePassword()), array($this->create_hash(), $this->user_id));
return true;
}
/**
*
* @return boolean Sets a new password for an expired account
*/
public function setNewPassword()
{
if($this->is_common_pass($this->pass))
{
throw new Exception("Submitted registration password is too common", 1004);
}
if(strlen($pass) < self::MINIMUM_PASS_LENGTH)
{
throw new Exception("Submitted registration password is too short", 1005);
}
$rs = SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthUpdateNewPassword()), array($this->create_hash(), $this->login));
return true;
}
/**
*
* @return boolean True on user registration
*/
public function registerUserWithAdmin( $login, $email, $pass)
{
$register = $this->create_new_user($login, $email, $pass);
return $register;
}
/**
*
* @param int $active Default new user active status - 1 if unset anywhere.
* @return boolean
*/
public function registerUser($active = 1)
{
//if not, check if user can register (is not logged in already)
if($this->user_id != -1)
{
throw new Exception("Current user is not a guest (for registration)", 1003);
}
//if not register a new user
$register = $this->create_new_user($active, $this->login, $this->email, $this->pass);
if($register)
{
$this->user_id = $register;
}
return true;
}
/**
* Checks if a given email actually exists for an active non-admin user in the system
* @return boolean
*/
public function emailExists()
{
$rs = SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthUsersByEmail()), array($this->email));
while(isset($rs->fields) && !$rs->EOF)
{
if($rs->fields[1] > 0)
{
return true;
}
$rs->MoveNext();
}
return false;
}
/**
* @TODO email can login
* Allows the user to login through a mail sent in his email
* This is no less secure than letting them reset their password
* Login count validation blocks further login attempts
* @return boolean
*/
public function emailLogin()
{
/*$this->sess_clear();
if( @TODO email can login ){
$this->sess_write();
$this->auth_user_update_date();
$this->auth_user_login_count();
return true;
}*/
return false;
}
/***********************************
* NON-PUBLIC FUNCTIONS START HERE *
***********************************/
/**
*
* @return String The encoded password with the format: algorithm:iterations:salt:hash
*/
private function create_hash()
{
$pass = $this->pass;
//create unique salt
$salt = base64_encode(mcrypt_create_iv(self::PBKDF2_SALT_BYTES, MCRYPT_DEV_URANDOM));
return self::PBKDF2_HASH_ALGORITHM . ":" . self::PBKDF2_ITERATIONS . ":" . $salt . ":" .
base64_encode( $this->pbkdf2(self::PBKDF2_HASH_ALGORITHM,$pass,$salt,self::PBKDF2_ITERATIONS,self::PBKDF2_HASH_BYTES,true) );
}
/**
*
* @param String $good_hash
* @return boolean Validates the given password
*/
private function validate_password($good_hash)
{
$params = explode(":", $good_hash);
if(count($params) < self::HASH_SECTIONS)
{
return false;
}
$pbkdf2 = base64_decode($params[self::HASH_PBKDF2_INDEX]);
return $this->slow_equals( $pbkdf2, $this->pbkdf2($params[self::HASH_ALGORITHM_INDEX],$this->pass, $params[self::HASH_SALT_INDEX], intval($params[self::HASH_ITERATION_INDEX]),strlen($pbkdf2),true));
}
/**
*
* @param String $a
* @param String $b
* @return boolean Compares two strings $a and $b in length-constant time.
*/
private function slow_equals($a, $b)
{
$diff = strlen($a) ^ strlen($b);
for($i = 0; $i < strlen($a) && $i < strlen($b); $i++)
{
$diff |= ord($a[$i]) ^ ord($b[$i]);
}
return $diff === 0;
}
/**
* PBKDF2 key derivation function as defined by RSA's PKCS #5: https://www.ietf.org/rfc/rfc2898.txt
* @param String $algorithm - The hash algorithm to use. Recommended: SHA256
* @param String $password - The password.
* @param String $salt - A salt that is unique to the password.
* @param int $count - Iteration count. Higher is better, but slower. Recommended: At least 1000.
* @param int $key_length - The length of the derived key in bytes.
* @param boolean $raw_output - If true, the key is returned in raw binary format. Hex encoded otherwise.
* @return String A $key_length-byte key derived from the password and salt.
*
* Test vectors can be found here: https://www.ietf.org/rfc/rfc6070.txt
*
* This implementation of PBKDF2 was originally created by https://defuse.ca
* With improvements by http://www.variations-of-shadow.com
*/
private function pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false)
{
$algorithm = strtolower($algorithm);
if(!in_array($algorithm, hash_algos(), true))
{
die('PBKDF2 ERROR: Invalid hash algorithm.');
}
if($count <= 0 || $key_length <= 0)
{
die('PBKDF2 ERROR: Invalid parameters.');
}
$hash_length = strlen(hash($algorithm, "", true));
$block_count = ceil($key_length / $hash_length);
$output = "";
for($i = 1; $i <= $block_count; $i++) {
// $i encoded as 4 bytes, big endian.
$last = $salt . pack("N", $i);
// first iteration
$last = $xorsum = hash_hmac($algorithm, $last, $password, true);
// perform the other $count - 1 iterations
for ($j = 1; $j < $count; $j++) {
$xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
}
$output .= $xorsum;
}
if($raw_output)
{
return substr($output, 0, $key_length);
}
else
{
return bin2hex(substr($output, 0, $key_length));
}
}
/**
*
* @return integer Checks password and username for login method. If found, returns the id
*/
private function CheckCredentials()
{
if($this->CanLogin())
{
$rs = SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthGetUserPassword()), array($this->login));
if(!$rs->EOF){
if($this->validate_password($rs->fields[1]) && $rs->fields[2] > 0)
{ //check if password is good and user is not inactive
$this->user_id = $rs->fields[0];
if($rs->fields[2] == 2)
{//if pass is correct but was set to expire, provoke change
throw new Exception("Password has expired", 1101);
}
if($rs->fields[2] >= 3)
{//if pass is correct but user is not yet verified
throw new Exception("User is not properly activated", 1102);
}
return true;
}
elseif($rs->fields[1] == $this->pass )
{//if pass is in plain text in db then it must be changed
throw new Exception("Password format is incorrect", 1100);
}
}
}
return false;
}
/**
* Checks if attempting to log in as admin and returns false if cannot admin login
* Normal users can still log in
*
* @return boolean Returns if the login can login and always fails if ADMIN_CAN_LOGIN is 0
*/
private function CanLogin()
{
$alogin = $this->IsLoginAdmin();
if(self::ADMIN_CAN_LOGIN == 0 && $alogin)
{
return false;
}
return true;
}
/**
*
* @return boolean Returns whether the login is admin or not
*/
private function IsLoginAdmin()
{
$rs = SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthGetRootUsers()), array());
while($rs->fields && !$rs->EOF)
{
if($this->login == $rs->fields[0])
{
return true;
}
$rs->MoveNext();
}
return false;
}
/**
*
* @return boolean Returns whether the login has a password
*/
private function HasPassword()
{
$rs = SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthGetUserPassword()), array($this->login));
if(strlen($rs->fields[1]) > 0)
{
return true;
}
return false;
}
/**
*
* @return integer Returns the id_user from active sessions table accordingly his session id
*/
private function sess_read()
{
$rs = SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthUserActiveSession()), array($this->sess_id));
if(!$rs->EOF)
{
return $rs->fields[0];
}
return false;
}
/**
*
* @return boolean Writes the session id and user id to the table
*/
private function sess_write()
{
$ip_address = $_SERVER["REMOTE_ADDR"];
$file = $_SERVER["REQUEST_URI"];
if(!$file) {
$file= $_SERVER["SCRIPT_NAME"];
}
SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthDeleteActiveSession()), array($this->sess_id));
//insert
SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthInsertSession()), array($this->user_id, $this->sess_id, $file));
return true;
}
/**
*
* @return boolean Flushes a session
*/
private function sess_delete()
{
SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthDeleteActiveSession()), array($this->sess_id));
return true;
}
/**
*
* @param date $time
* @return boolean Clears expired sessions
*/
private function sess_clear()
{
SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthDeleteOldSession()), array(self::SESSION_TIMEOUT));
return true;
}
/**
* Updates the user_id variable only for the object
*
* @return boolean true when the user is not a guest
*/
private function update_user()
{
$this->user_id = sess_read();
if(!$this->user_id)
{
$this->user_id = -1;
return false;
}
return true;
}
/**
*
* @return boolean Updates user session date
*/
private function auth_user_update_date()
{
$date = date("YmdHis");
$file = $_SERVER["REQUEST_URI"];
if(!$file) {
$file= $_SERVER["SCRIPT_NAME"];
}
SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthUpdateSession()), array($file, $this->sess_id, $this->user_id));
//if not a guest
if($this->user_id > 0){
SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthUpdateUserLastSeen()), array($this->user_id));
//SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthUpdateUserActive()), array(1, $this->user_id));
}
return true;
}
/**
*
* @return boolean Updates user login count
*/
private function auth_user_login_count()
{
//if not a guest
if($this->user_id > 0){
SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthUpdateUserLoginCount()), array($this->user_id));
}
return true;
}
/**
*
* @return array The user infos
*/
private function get_user_infos()
{global $lang;
$arr = array();
if($this->user_id == -1)
{
//load guest infos
$arr["id"] = -1;
$arr["login"] = isset($lang) ? $lang["guest"] : "guest";
$arr["user_level"] = 0;
$arr["default_lang"] = isset($_SESSION["lrdl"]) ? $_SESSION["lrdl"] : 1;
$arr["email"] = "";
}
else
{
$rs = SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthGetUserInfos()), array($this->user_id));
//rs has id, login, user_level, default_lang, email
while(isset($rs->fields) && !$rs->EOF)
{
$arr["id"] = $rs->fields[0];
$arr["login"] = $rs->fields[1];
$arr["user_level"] = $rs->fields[2];
$arr["default_lang"] = $rs->fields[3];
$arr["email"] = $rs->fields[4];
$rs->MoveNext();
}
}
return $arr;
}
/**
*
* @return integer The newly create user ID. False if none.
* @throws Exception 1001, 1002, 1004
*/
private function create_new_user($active, $login, $email, $pass = "")
{
$rs = SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthGetDupeRegistrations()), array($this->login, $this->email));
if($rs->fields && !$rs->EOF){
if($rs->fields[1] == $this->login)
{
throw new Exception("Login already exists", 1001);
}
else
{
throw new Exception("Email already exists", 1002);
}
}
else
{
if($pass == "")
{
$this->pass = $this->random_password();
}
else
{
if($this->is_common_pass($pass))
{
throw new Exception("Submitted registration password is too common", 1004);
}
if(strlen($pass) < self::MINIMUM_PASS_LENGTH)
{
throw new Exception("Submitted registration password is too short", 1005);
}
}
$pass = $this->create_hash();
$default_lang = isset($_SESSION[self::DEFAULT_LANG_ID]) ? $_SESSION[self::DEFAULT_LANG_ID] : 1;
$rs = SQLQUERY::Execute(SQLQUERY::Prepare(SQLQUERY::AuthInsertNewUser()), array($active, $default_lang, $login, $pass, $email));
return SQLQUERY::LastID();
}
return false;
}
/**
*
* @return string A random password
*/
private function random_password()
{
//make sure random pass is at least 8 characters long
$min = self::MINIMUM_PASS_LENGTH;
if($min < 8)
{
$min = 8;
}
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < $min; $i++)
{
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
if($this->is_common_pass($pass))
{
return $this->random_password();
}
else
{
return implode($pass); //turn the array into a string
}
}
/**
* Checks if a password is in the top 1050 common passwords list
* @param string password The password to check
* @return bool True if the password is common
*/
private function is_common_pass($pass)
{
$common_password = array("char limit");
if( in_array($pass, $common_password) )
{
return true;
}
return false;
}
}
?>
</code></pre>
<p><strong>SQL Query Class</strong></p>
<pre><code><?php
/**
* SQL Queries
* This is meant to be used with ADODB which allows setting params
*/
class SQLQUERY {
private $db;
public function __construct($db) {
$this->db = $db;
}
/**
*
* @param String $sql
* @return Object Returns object created by prepare statement
*/
public function Prepare($sql)
{
return $this->db->Prepare($sql);
}
/**
*
* @param Object $o Object that has been prepared
* @param array $array Array of parameters
* @return RecordSet The result of the query.
*/
public function Execute($o, $array)
{
return $this->db->Execute($o, $array);
}
/**
* @return RecordSet The last inserted id.
*/
public function LastID()
{
return $this->db->Insert_ID();
}
/********************************************
* START OF QUERIES LIST *
********************************************/
protected function AuthGetUserPassword()
{
return "SELECT id, password, active FROM ".USERS_TABLE." WHERE login = ".$this->db->Param('a')."";
}
protected function AuthUpdateUserLastSeen()
{
return "UPDATE ".USERS_TABLE." SET date_last_seen = NOW() WHERE id = ".$this->db->Param('a')."" ;
}
protected function AuthUpdateUserLoginCount()
{
return "UPDATE ".USERS_TABLE." SET login_count = login_count + 1 WHERE id = ".$this->db->Param('a')."" ;
}
protected function AuthUpdateUserActive()
{
return "UPDATE ".USERS_TABLE." SET active = ".$this->db->Param('a')." WHERE id = ".$this->db->Param('b')." and active = ".$this->db->Param('c')." ";
}
protected function AuthUserActiveSession()
{
return "SELECT id_user FROM ".ACTIVE_SESSIONS_TABLE." WHERE session = ".$this->db->Param('a')."" ;
}
protected function AuthDeleteActiveSession()
{
return "DELETE FROM ".ACTIVE_SESSIONS_TABLE." WHERE session = ".$this->db->Param('a')." " ;
}
protected function AuthDeleteOldSession()
{
return "DELETE FROM ".ACTIVE_SESSIONS_TABLE." WHERE UNIX_TIMESTAMP(update_date) < UNIX_TIMESTAMP(now())-".$this->db->Param('a')." " ;
}
protected function AuthInsertSession()
{
return "INSERT INTO ".ACTIVE_SESSIONS_TABLE." (id_user, session, file, update_date)
VALUES ( ".$this->db->Param('a').", ".$this->db->Param('b').", ".$this->db->Param('c').", NOW()) ";
}
protected function AuthUpdateSession()
{
return "UPDATE ".ACTIVE_SESSIONS_TABLE."
SET update_date = NOW(), file=".$this->db->Param('a')."
WHERE session=".$this->db->Param('b')." AND id_user = ".$this->db->Param('c')."";
}
protected function AuthGetRootUsers()
{
return "SELECT login FROM ".USERS_TABLE." WHERE user_level = 100";
}
protected function AuthGetUserInfos()
{
return "SELECT id, login, user_level, default_lang, email FROM ".USERS_TABLE." WHERE id = ".$this->db->Param('a')." ";
}
protected function AuthUpdateFirstAdminPass()
{
return "UPDATE ".USERS_TABLE." SET date_registration = NOW(), password=".$this->db->Param('a')." WHERE login=".$this->db->Param('b')." AND user_level = 100 AND password = '' ";
}
protected function AuthUpdatePassword()
{//updates through ID
return "UPDATE ".USERS_TABLE." SET password=".$this->db->Param('a')." WHERE id=".$this->db->Param('b')." ";
}
protected function AuthUpdateNewPassword()
{//updates through login (which is unique key in DB) and user cannot have been deactivated purposefully
return "UPDATE ".USERS_TABLE." SET password=".$this->db->Param('a').", active = 1 WHERE login=".$this->db->Param('b')." AND active > 1 ";
}
protected function AuthUsersByEmail()
{
return "SELECT login, active FROM ".USERS_TABLE." WHERE email = ".$this->db->Param('a')." AND user_level < 100";
}
protected function AuthGetDupeRegistrations()
{
return "SELECT id, login, email FROM ".USERS_TABLE." WHERE login = ".$this->db->Param('a')." OR email = ".$this->db->Param('b')." ";
}
protected function AuthInsertNewUser()
{
// a b c d e
return "INSERT INTO ".USERS_TABLE." (active, default_lang, date_registration, user_level, login, password, email)
VALUES ( ".$this->db->Param('a').", ".$this->db->Param('b').", NOW(), 1, ".$this->db->Param('c').", ".$this->db->Param('d').", ".$this->db->Param('e').") ";
}
}
?>
</code></pre>
<p>Most of the above is called by the auth.php script in the root directory.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:18:30.500",
"Id": "74770",
"Score": "3",
"body": "Hi @MrJack, welcome to Code Review! You've posted a lot of code here! I suggest that you break this code down to _manageable_ modules you want us to review, and put each in a different question. No one will read all this code, and give you a coherent answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:19:22.210",
"Id": "74771",
"Score": "1",
"body": "Oh, i'm reading it alright, and there's a *lot* to say..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:35:43.293",
"Id": "74772",
"Score": "0",
"body": "@UriAgassi - I agree, it is big, but I couldn't decide what to chop off. I figured with the whole thing, anyone could paste it into an editor. The 30 000 character limit really limited my options to have both specific areas and the whole class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:38:45.747",
"Id": "74774",
"Score": "2",
"body": "@MrJack the fact that you have so much in one class is another issue. You should split your classes up under the SoC principle and use a PSR0/4 autoloader."
}
] |
[
{
"body": "<h3>Preamble</h3>\n<p>As a matter of security, I can safely say that you would fail a professional security audit in seconds. You should be including the hashing library as an external component. You also need to forget everything you know about querying databases and start again.</p>\n<p>Also, look at Model-View-Controller. The fact you have a templating engine and separate classes for Database work implies that you are attempting MVC, but the implementation itself is nothing like MVC.</p>\n<h3>SQLQUERY</h3>\n<p>As for the code here itself, your <code>SQLQUERY</code> class leaves a lot to be desired.</p>\n<p>First: the naming. <code>SQLQUERY</code> makes me instantly think that this is a subclass of <code>PDOStatement</code>. But it isn't. It's a wrapper around a PDO object.</p>\n<p>Consider the following:</p>\n<pre><code>class DatabaseWrapper {\n\n private $db;\n const USERS_TABLE = "`users`";\n\n public function __construct(PDO $db) {\n $this->setInstance($db);\n }\n\n public function &getInstance() {\n return $this->db;\n }\n\n protected function setInstance(PDO $db) {\n $this->db = $db;\n }\n\n}\n</code></pre>\n<ol>\n<li>It type-hints the database object in the constructor for dependency injection.</li>\n<li>It allows you to get a direct reference to the PDO object that is injected.</li>\n<li>Likewise, it also allows to you set it later (and allows classes that extend it to do the same)</li>\n<li>The users table is a class constant.</li>\n</ol>\n<h3>As for your queries themselves...</h3>\n<p>You're going to have to <strong>never, under any circumstances, use string interpolation</strong> (which is not <em>too</em> much of an issue in your implementation, except for the fact that you are using your controller as a model and your model as an array...)</p>\n<p>Remove the <code>->Param()</code> method and instead use <code>$this->db->prepare()</code>.</p>\n<p>This means that:</p>\n<pre><code>protected function AuthUsersByEmail()\n{\n return "SELECT login, active FROM ".USERS_TABLE." WHERE email = ".$this->db->Param('a')." AND user_level < 100";\n}\n</code></pre>\n<p>Would instead become:</p>\n<pre><code>protected function getUsersByEmail($email, $level = 100) {\n $sql = "SELECT login, active FROM ". static::USERS_TABLE . " WHERE email = ? AND user_level < ?";\n return $this->prepare($sql, [$email, $level]);\n}\n</code></pre>\n<p>Where prepare is the following:</p>\n<pre><code>protected function prepare($sql, array $bindings = []) {\n try {\n $prepare = $this->db->prepare($sql);\n $prepare->execute($bindings);\n return $prepare->fetchAll();\n } catch (PDOException $e) {\n throw new RuntimeException("prepare failed: $sql, " . $e->getMessage());\n }\n}\n</code></pre>\n<h1>In short, you should make your SQLQUERY class into a model that fetches data for you.</h1>\n<p>Also something I've noticed is that your entire project will be generating notices like <em>crazy</em> because of poor PHP.</p>\n<ol>\n<li><code>parent::__construct()</code> should be used to call a parent constructor. using <code>SQLQUERY::__construct()</code> implies that it is a static method, and PHP will complain.</li>\n<li><code>protected</code> functions are <em><strong>not</strong></em> <code>static</code>! In your entire authentication class, you are simply trying to call protected (and hence internal) functions from the global scope as public static methods.</li>\n</ol>\n<p>This system would need a fairly hefty redesign in order to be considered for use in production environments.</p>\n<p>You need to split up your files, and huge files are pretty much unreadable. Look at <a href=\"https://getcomposer.org\" rel=\"noreferrer\">composer</a> for autoloading your classes.</p>\n<p>Also, have you tried using the built-in password hashing functions that PHP provides? (<code>password_hash</code>, <code>password_verify</code>, <code>password_needs_rehash</code>). You should really stick with vetted implementations of cryptographic functions that have been extensively peer-reviewed.</p>\n<p>I strongly, strongly recommend that you consult <a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md\" rel=\"noreferrer\">PSR0</a>, <a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md\" rel=\"noreferrer\">PSR1</a> and <a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide-meta.md\" rel=\"noreferrer\">PSR2</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T18:28:28.557",
"Id": "74786",
"Score": "0",
"body": "Thanks for the feedback, will definitely change the SQLQUERY class ASAP - makes a lot of sense. Will also look at composer, however, I have not been getting any notices so I will look if my error settings fail to trigger that before changing it.\n\nThe main reason I haven’t looked into the built-in functions too much is that I read they require php 5.5 which is not what the prod server this might eventually run on uses (5.3)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T20:09:21.503",
"Id": "74799",
"Score": "0",
"body": "@MrJack composer has a package for php5.5 password functions already. it's `ircmaxell/password-compat`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:44:26.927",
"Id": "43323",
"ParentId": "43317",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "43323",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T16:40:19.187",
"Id": "43317",
"Score": "9",
"Tags": [
"php",
"mysql",
"security",
"authentication"
],
"Title": "Login system based off of another site"
}
|
43317
|
<p>To learn Python, I've been working through <a href="http://learnpythonthehardway.org/book/" rel="nofollow">Learn Python the Hard Way</a>, and to exercise my Python skills I wrote a little Python Hangman game (PyHangman - creative, right?):</p>
<pre><code>#! /usr/bin/env python2.7
import sys, os, random
if sys.version_info.major != 2:
raw_input('This program requires Python 2.x to run.')
sys.exit(0)
class Gallows(object):
def __init__(self):
'''Visual of the game.'''
self.state = [
[
'\t _______ ',
'\t | | ',
'\t | ',
'\t | ',
'\t | ',
'\t | ',
'\t________|_',
],
[
'\t _______ ',
'\t | | ',
'\t O | ',
'\t | ',
'\t | ',
'\t | ',
'\t________|_',
],
[
'\t _______ ',
'\t | | ',
'\t O | ',
'\t | | ',
'\t | | ',
'\t | ',
'\t________|_',
],
[
'\t _______ ',
'\t | | ',
'\t O | ',
'\t \| | ',
'\t | | ',
'\t | ',
'\t________|_',
],
[
'\t _______ ',
'\t | | ',
'\t O | ',
'\t \|/ | ',
'\t | | ',
'\t | ',
'\t________|_',
],
[
'\t _______ ',
'\t | | ',
'\t O | ',
'\t \|/ | ',
'\t | | ',
'\t / | ',
'\t________|_',
],
[
'\t _______ ',
'\t | | ',
'\t O | ',
'\t \|/ | ',
'\t | | ',
'\t / \\ | ',
'\t________|_',
]
]
def set_state(self, misses):
'''Sets the current visual being used.'''
image = ''
state = self.state[misses] # set state to the list of desired gallows image
# construct gallows image into str from list
for piece in state:
image += piece + '\n'
return image
class Wordlist(object):
def __init__(self):
'''Set the length of the wordlist.'''
self.numLines = sum(1 for line in open('test.txt'))
def new_word(self):
'''Choose a new word to be guessed.'''
stopNum = random.randint(0, self.numLines-1) # establish random number to be picked from list
# extract word from file
with open('test.txt') as file:
for x, line in enumerate(file):
if x == stopNum:
word = line.lower().strip() # remove endline characters
return word
def set_blanks(word):
'''Create blanks for each letter in the word.'''
blanks = []
for letter in word:
# Don't hide hyphens
if letter == '-':
blanks += '-'
else:
blanks += '_'
return blanks
def check_letter(word, guess, blanks, used, missed):
'''Check if guessed letter is in the word.'''
newWord = word
# If the user presses enter without entering a letter
if guess.isalpha() == False:
raw_input("You have to guess a letter, silly!")
# If the user inputs multiple letters at once
elif len(list(guess)) > 1:
raw_input("You can't guess more than one letter at a time, silly!")
# If the user inputs a letter they've already used
elif guess in used:
raw_input("You already tried that letter, silly!")
# replace the corresponding blank for each instance of guess in the word
elif guess in word:
for x in range(0, word.count(guess)):
blanks[newWord.find(guess)] = guess
newWord = newWord.replace(guess, '-', 1) # replace already checked letters with dashes
used += guess # add the guess to the used letter list
#If the guess is wrong
else:
missed = True
used += guess
return blanks, used, missed
def new_page():
'''Clears the window.'''
os.system('cls' if os.name == 'nt' else 'clear')
def reset(image, wordlist):
wrongGuesses = 0 # number of incorrect guesses
currentImg = image.set_state(wrongGuesses) # current state of the gallows
word = wordlist.new_word() # word to be guessed
blanks = set_blanks(word) # blanks which hide each letter of the word until guessed
used = [] # list of used letters
return wrongGuesses, currentImg, word, blanks, used
def play(image, currentImg, wrongGuesses, word, blanks, used):
missed = False
new_page()
print currentImg
for x in blanks:
print x,
print '\n'
for x in used:
print x,
print '\n'
guess = raw_input("Guess a letter: ")
blanks, used, missed = check_letter(word, guess.lower(), blanks, used, missed)
if missed == True and wrongGuesses < 6:
wrongGuesses += 1
currentImg = image.set_state(wrongGuesses)
play(image, currentImg, wrongGuesses, word, blanks, used)
elif missed == False and blanks != list(word) and wrongGuesses != 7:
play(image, currentImg, wrongGuesses, word, blanks, used)
elif blanks == list(word):
endgame('win', word)
else:
endgame('lose', word)
def endgame(result, word):
new_page()
if result != 'lose':
print "Congratulations, you win!"
print "You correctly guessed the word '%s'!" % word
else:
print "Nice try! Your word was '%s'." % word
while True:
play_again = raw_input("Play again? [y/n]")
if 'y' in play_again.lower():
return
elif 'n' in play_again.lower():
sys.exit(0)
else:
print "Huh?"
def main():
image = Gallows()
wordlist = Wordlist()
new_page()
print("\nWelcome to Hangman!")
print("Guess the word before the man is hung and you win!")
raw_input("\n\t---Enter to Continue---\n")
new_page()
while True:
misses, currentImg, word, blanks, used = reset(image, wordlist)
play(image, currentImg, misses, word, blanks, used)
if __name__ == '__main__':
main()
</code></pre>
<p>So what do you all think? This is the second iteration of the program, as the first one <a href="https://bbs.archlinux.org/viewtopic.php?id=177291" rel="nofollow">was a mess</a>, but I think I've got it all worked out a bit better now.</p>
<p>One of the things that I still think is messy is how I had the game loop after you guessed a letter, as it simply calls itself again. Is there a better way to do that?</p>
<p>Any tips on making my code more pythonic is appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:14:40.310",
"Id": "74768",
"Score": "0",
"body": "A bit of a naive question why is '\\' escaped in the right leg but not in the left arm ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:45:15.320",
"Id": "74777",
"Score": "0",
"body": "Hm, good question. I'm not sure why I originally did that, but removing it doesn't seem to break anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T16:56:44.817",
"Id": "82790",
"Score": "0",
"body": "Here's a [followup question](http://codereview.stackexchange.com/questions/47240/2-player-in-a-python-hangman-game)."
}
] |
[
{
"body": "<p>Python supports multi-line string literals. You could use those instead of using a list to encode your state image.</p>\n\n<pre><code>a = r\"\"\" 'hello' \\n\n more \"\"\"\nprint a\n</code></pre>\n\n<hr>\n\n<p>You have multiple methods called <code>set_XXX()</code> that return values instead of storing a value. The names of these methods could be changed to better describe what they are doing.</p>\n\n<hr>\n\n<p><code>Wordlist.new_word()</code> will continue to iterate over the entire file even after the selected word is found. Putting the <code>return</code> where you create the <code>word</code> variable will break the loop once you have the value you want.</p>\n\n<hr>\n\n<p><code>Wordlist</code> uses a hard coded string for the file name, that is specified in two different places. If you want to change to a different file, you have to remember to change both cases. This is a simple example, that may seem trivial, but this type of error is hard to track down when the code becomes larger and more complicated.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T18:48:37.063",
"Id": "43326",
"ParentId": "43318",
"Score": "4"
}
},
{
"body": "<p>I'll get a few trivial comments out of the way before addressing some serious concerns about the flow of control in your program.</p>\n\n<h3>User experience</h3>\n\n<p>Overall, the application feels like it's nicely put together. I enjoyed playing it while writing this review.</p>\n\n<ul>\n<li>The past participle of the verb \"to hang\" is \"hung\", but when talking about executions, it should be \"hanged\". (\"Hung\" isn't completely unacceptable usage, though.)</li>\n<li><code>endgame()</code> should not clear the screen. For me, part of the fun of playing Hangman is to see the final state of the game, and clearing the screen denies me that pleasure.</li>\n</ul>\n\n<h3>Python 3 compatibility</h3>\n\n<p>You explicitly check that the game is running on Python 2. With a few changes, all related to <code>input()</code> and <code>print()</code>, you can also get it to run on Python 3.</p>\n\n<ul>\n<li><p>Put the following shim at the top, then replace all <code>raw_input()</code> calls with <code>input()</code>.</p>\n\n<pre><code>if sys.version_info.major < 3:\n # Compatibility shim\n input = raw_input\n</code></pre></li>\n<li><p>Replace all <code>print \"string\"</code> with <code>print(\"string\")</code></p></li>\n<li><p>However, the following printing code, which uses a trailing comma to suppress the newline in Python 2, requires special treatment:</p>\n\n<pre><code>for x in blanks:\n print x,\nprint '\\n'\nfor x in used:\n print x,\nprint '\\n'\n</code></pre>\n\n<p>I suggest the following replacement code, which takes a better approach even if you weren't interested in Python 3:</p>\n\n<pre><code>print(' '.join(blanks))\nprint(' '.join(used))\n</code></pre></li>\n</ul>\n\n<h3>Wordlist</h3>\n\n<ul>\n<li>Buried in the middle of a long program, you hard-coded <code>\"test.txt\"</code>. That's bad for maintainability; hard-coding the same filename twice is even worse. Instead, the <code>WordList</code> constructor should take a filename parameter.</li>\n<li>You might have a file descriptor leak in the constructor, since you <code>open()</code> the file not using a <code>with</code> block or calling <code>close()</code>. Therefore, you <a href=\"https://stackoverflow.com/a/7396043/1157100\">rely on the garbage collector</a> to trigger the closing, which won't necessarily happen in all Python interpreters.</li>\n<li>No need to assign the variable <code>word</code>. Just <code>return line.lower().strip()</code>.</li>\n</ul>\n\n<h3>Gallows</h3>\n\n<ul>\n<li><code>Gallows.set_state()</code> is a misnomer. The <code>Gallows</code> object doesn't actually keep any state! A more accurate name would be <code>Gallows.get_image()</code>.</li>\n<li>I would prefer it if <code>Gallows</code> did keep track of the number of wrong guesses, and had methods <code>.increment_count()</code> and <code>.is_hanged()</code>. Currently, you hard-code 6 as a limit in <code>play()</code>, a number that you hope is consistent with the number of images available in <code>Gallows</code> (minus one for the initial image).</li>\n</ul>\n\n<h3>Interaction between <code>reset()</code>, <code>check_letter()</code>, and <code>play()</code></h3>\n\n<ul>\n<li>You pass clusters of variables around a lot. Those are actually state variables, so these three functions would be better as members of a class.</li>\n<li><code>check_letter()</code> should not take <code>missed</code> as a parameter. It's an output, not an input.</li>\n<li><p>The way <code>check_letter()</code> handles correct guesses is clumsy. I would write</p>\n\n<pre><code># replace the corresponding blank for each instance of guess in the word\nelif guess in word:\n for index, char in enumerate(word):\n if char == guess:\n blanks[index] = guess\n used += guess # add the guess to the used letter list\n</code></pre></li>\n</ul>\n\n<h3>Flow of control</h3>\n\n<p>All the critiques above are minor details. The most important problem with the code, in my opinion, is that <strong>you are misusing recursive function calls as a kind of goto.</strong></p>\n\n<p>To see a symptom of the problem, play a few rounds, then hit <kbd>Ctrl</kbd><kbd>C</kbd>. Notice that the stack trace is very deep — it contains one call to <code>play()</code> for every guess ever made in the history of the program, including previous rounds. It is inappropriate to keep such state around in the call stack.</p>\n\n<p>The remedy is to use loops for looping.</p>\n\n<p>Here's how I would write it (without making too many of the recommended changes listed above).</p>\n\n<pre><code>def play(word):\n \"\"\" Play one game of Hangman for the given word. Returns True if the\n player wins, False if the player loses. \"\"\"\n gallows = Gallows()\n wrong_guesses = 0 # number of incorrect guesses\n blanks = set_blanks(word) # blanks which hide each letter of the word until guessed\n used = [] # list of used letters\n\n while True:\n new_page()\n print(gallows.get_image(wrong_guesses))\n print(' '.join(blanks))\n print(' '.join(used))\n\n guess = input(\"Guess a letter: \")\n blanks, used, missed = check_letter(word, guess.lower(), blanks, used)\n\n if blanks == list(word):\n return endgame(True, word)\n elif missed and wrong_guesses >= 6:\n return endgame(False, word)\n elif missed:\n wrong_guesses += 1\n\ndef endgame(won, word):\n print('')\n if won:\n print(\"Congratulations, you win!\")\n print(\"You correctly guessed the word '%s'!\" % word)\n else:\n print(\"Nice try! Your word was '%s'.\" % word)\n return won\n\ndef play_again():\n while True:\n play_again = input(\"Play again? [y/n] \")\n if 'y' in play_again.lower():\n return True\n elif 'n' in play_again.lower():\n return False\n else:\n print(\"Huh?\")\n\n\ndef main(words_file='test.txt'):\n wordlist = Wordlist(words_file)\n\n new_page()\n print(\"\\nWelcome to Hangman!\")\n print(\"Guess the word before the man is hanged and you win!\")\n input(\"\\n\\t---Enter to Continue---\\n\")\n new_page()\n\n while True:\n play(wordlist.new_word())\n if not play_again():\n break\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T08:04:13.573",
"Id": "43383",
"ParentId": "43318",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "43383",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T16:45:17.100",
"Id": "43318",
"Score": "7",
"Tags": [
"python",
"game",
"python-2.x",
"hangman"
],
"Title": "Python Hangman program"
}
|
43318
|
<p>I'm working on a WPF app which uses ReactiveUI and Rx, there's part of the
workflow that watches two data sources (<code>ReferenceData</code> and <code>PredictedData</code> properties on
a View Model) and an area of that data source (<code>FocusArea</code> property) which is used to show
a line graph of that data. </p>
<p>Sometimes there can be a lot of data (and sometimes both data sources change at the same time), and building the line graphs can take a while. So it's done on a background thread.
I'm also using the Ramer–Douglas–Peucker algorithm to approximate the graph for display (the <code>ReduceGraphPoints</code> method, which returns <code>Task<List<Point>></code>). So the final graph is only updated when the line data for both data streams are calculated and simplified.</p>
<p>Once the calculation is started, the Loading property of the View Model is updated so we can mark the current graph as about-to-be-replaced</p>
<p>The code I have for that bit of functionally at the moment is:</p>
<pre><code>this.WhenAny(me => me.ReferenceData,
me => me.PredictedData,
me => me.FocusArea,
(refData, predictedData, area) => new { ReferenceData = refData.Value, PredictedData = predictedData.Value, Area = area.Value })
.Where(x => !x.Area.IsEmpty)
.Do(_ => Loading = true)
.Throttle(TimeSpan.FromMilliseconds(50))
.Select(x => Observable.FromAsync(token => Task.Run(() =>
{
var refPoints = x.ReferenceData.GetPointsInRange(x.Area.Range).ToList();
var reducedRef = ReduceGraphPoints(refPoints, token);
var predictedPoints = x.PredictedData.GetPointsInRange(x.Area.Range).ToList();
var reducedPredicted = ReduceGraphPoints(predictedPoints, token);
return new { ReferencePoints = reducedRef.Result, PredictedPoints = reducedPredicted.Result };
}, token)))
.Switch()
.Subscribe(x =>
{
ReferencePoints = x.ReferencePoints;
PredictedPoints = x.PredictedPoints;
Loading = false;
});
</code></pre>
<p>So I'm looking for feedback from any Rx experts on this. Things like the use of the Do method, and the cancellation token. Most of the methods called use
<code>ThrowIfCancellationRequested</code> on the token, but I'm ignoring the cancellation exception because if it has been cancelled, then <code>Switch()</code> will already be watching
the next IObservable and won't care about the old one - is that the best way of doing this?</p>
|
[] |
[
{
"body": "<p>When Switch unsubscribes from the previous Observable to connect to the new one, FromAsync should signal the cancellation token and also correctly eat the ThrowOnCancellation exception. </p>\n\n<p>While it'd probably be better to try to use a ReactiveCommand to model the loading bool (which might not be easy given the cancelation and Switch), if this code works for you it should be fine.</p>\n\n<p>Make sure to specify RxApp.MainThreadScheduler for the Throttle though, it's more efficient</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T03:04:58.953",
"Id": "43362",
"ParentId": "43320",
"Score": "4"
}
},
{
"body": "<pre><code>return new { ReferencePoints = reducedRef.Result, PredictedPoints = reducedPredicted.Result };\n</code></pre>\n\n<p>You can use <code>await</code> here, so that you're not unnecessarily blocking a thread. This would require you to change the lambda to <code>async</code> and then change the line to:</p>\n\n<pre><code>return new { ReferencePoints = await reducedRef, PredictedPoints = await reducedPredicted };\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:48:12.397",
"Id": "43951",
"ParentId": "43320",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "43362",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T17:10:30.093",
"Id": "43320",
"Score": "11",
"Tags": [
"c#",
"system.reactive"
],
"Title": "ReactiveUI and Rx background calculations with cancellation"
}
|
43320
|
<p>In an effort to reduce the images being used on the page, I've manipulated box-shading, etc. to make a "vector" looking monitor/ipad look. </p>
<p>This is great and all, gets the job done, however, seems there is still a large load draw on the box-shading rendering. Is there a better method or tweak to this method that would be a better approach?</p>
<p><a href="http://jsfiddle.net/darcher/Kc5n8/1/" rel="nofollow"><strong>Original Demo</strong></a> |
<a href="http://jsfiddle.net/darcher/Kc5n8/2/" rel="nofollow"><strong>Updated Demo</strong></a></p>
<p><strong>HTML</strong></p>
<pre class="lang-html prettyprint-override"><code><div class="vid">
<a href="#" class="vidlink"></a>
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre class="lang-css prettyprint-override"><code>.vid{
max-width:800px;
width:80%;
margin:0 auto}
.vidlink{
margin-top:50px;
background:url('img/vidbg.svg') no-repeat;
background-position:50%;
background-size:cover;
border:1px solid rgba(0,0,0,.6);
box-shadow:0 0 0 25px #fff,
0 0 5px 27px #777;
border-radius:5px 5px 0 0;
display:block;
margin-bottom:-5px;
padding:25% 0}
.vidlink:before{
content:" ";
position:relative;
left:50%;
top:50%;
margin:-40px 0 0 -40px;
padding:28px 40px;
background:url('img/icon/play.svg') no-repeat;
background-size:75px;
background-position:50%}
.vidlink:hover:before{
background:url('img/icon/play-hover.svg') no-repeat;
background-size:75px;
background-position:50%}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T20:23:01.913",
"Id": "74802",
"Score": "0",
"body": "Minor note : it's iPad and not ipad. I have no idea about what I could change your title to, but you don't need `review of`. Good result, it has a good look. Just for curiosity, why do you want your video links to look like an iPad ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T09:26:04.227",
"Id": "74917",
"Score": "0",
"body": "@Marc-Andre misread initially, mine is not to question why, mine is but to do or... you get the idea, Client wants what the client wants. I ended up using border-image and opting out of IE10 support for the \"iPad\" look. Turns out removing all box-shadow's from the source shaved a full second off load time of the page."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-17T19:18:35.683",
"Id": "134425",
"Score": "0",
"body": "Achieving the same thing without images doesn't necessarily mean you're making it faster. The heavy use of CSS features (like box-shadows, transition) have quite an impact on page load times as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-17T19:26:32.567",
"Id": "134430",
"Score": "0",
"body": "That it does, in this particular instance there was already a fair amount of HTTP Requests on the page, so was trying to limit that. I should rewrite this though, I see various ways to improve it."
}
] |
[
{
"body": "<p>Your code is perfectly valid, according to the HTML and CSS validators at W3C:</p>\n\n<blockquote>\n <p><a href=\"http://validator.w3.org/check\" rel=\"nofollow\">HTML Validator</a><br>\n <a href=\"http://jigsaw.w3.org/css-validator/\" rel=\"nofollow\">CSS Validator</a></p>\n</blockquote>\n\n<p>However, there are a couple things you could improve.</p>\n\n<p><strong>HTML:</strong></p>\n\n<p>I assume you already know to always specify the doctype and character encoding in your HTML files. The character encoding is not required by the validator, but it is good to always include it:</p>\n\n<pre><code><!DOCTYPE HTML>\n<head>\n <meta charset=\"utf-8\">\n <title>Page Title</title>\n</head>\n</code></pre>\n\n<p>Your CSS is difficult to read because of your indentation and your use of braces. All of your indentation should match, not have some blocks at the nested indentation level, and some at their proper level. Also, most CSS files use braces like this:</p>\n\n<pre><code>.vid {\n max-width:800px;\n width:80%;\n margin:0 auto;\n}\n</code></pre>\n\n<p>Not like this:</p>\n\n<pre><code>.vid{\n max-width:800px;\n width:80%;\n margin:0 auto}\n</code></pre>\n\n<h1>Edit</h1>\n\n<p>After clarification in the comments, this is a valid CSS style, but I still prefer the above style.</p>\n\n<h1>End Edit</h1>\n\n<p>The CSS validator does not require that you have a semi-colon <code>;</code> after the very last item, but you should to keep things all the same style.</p>\n\n<p>Overall, your code is good and the UI is beautiful. These are just a few things you could improve on and a few tips that just because they are so important, they deserve to be here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-03T15:16:44.793",
"Id": "137498",
"Score": "0",
"body": "I do not agree with your criticism of the OP's style of indentation. It is not that uncommon to indent related selectors like this. In fact, Sass offers an output style (nested) that is very similar to this. I may not *like* the style, but the OP uses it consistently."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-03T16:07:59.817",
"Id": "137509",
"Score": "0",
"body": "This is just easier for me to read in large scale stylesheet files. Formatting is, for the most part, preference. When i have an additional developer working in my projects I run prettify in sublime text 3 and it formats similar to your liking."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-03T16:27:35.577",
"Id": "137517",
"Score": "0",
"body": "Yup, it's valid, I actually use your preferred formatting in the updated fiddle, even with the semicolon on the last property."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-03T03:04:48.890",
"Id": "75541",
"ParentId": "43330",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T20:07:26.133",
"Id": "43330",
"Score": "8",
"Tags": [
"html",
"css",
"video"
],
"Title": "Creating an iPad-style video frame with CSS and without images"
}
|
43330
|
<p>I'm working through some exercises to sharpen my Ruby skills. The following code is how I solved this particular question. I'd like to know what other developers think of this solution. I'm self taught, which means: I'm not getting any feedback as I learn, so I just want to make sure that I'm learning the <em>right</em> way to do things. And I'd like to get a gauge of what <em>professional</em> developers think of my code.</p>
<blockquote>
<p><strong>Ranking System</strong><br>
[<strong>1</strong>-terrible] [<strong>2</strong>-not good] [<strong>3</strong>-ok] [<strong>4</strong>-good] [<strong>5</strong>-very good]</p>
</blockquote>
<ol>
<li>Is the answer code elegant? (score and feedback)</li>
<li>What tips can you suggest to improve the answer?</li>
<li>How's the readability of the code? (score and feedback)</li>
<li>Can you suggest a simpler and alternative answer?</li>
</ol>
<p><strong>Ruby</strong></p>
<pre><code>class Book
def title
@title
end
def title=(title)
special_words = %w(and in the of a an)
formatted_title = []
@title = title.split.each_with_index do |w,i|
case
when i == 0
formatted_title << w.capitalize
when i > 0 && !special_words.include?(w)
formatted_title << w.capitalize
when special_words.include?(w)
formatted_title << w
end
end
@title = formatted_title.join(" ")
end
end
</code></pre>
<p><strong>Rspec</strong></p>
<pre><code>describe Book do
before do
@book = Book.new
end
describe 'title' do
it 'should capitalize the first letter' do
@book.title = "inferno"
@book.title.should == "Inferno"
end
it 'should capitalize every word' do
@book.title = "stuart little"
@book.title.should == "Stuart Little"
end
describe 'should capitalize every word except...' do
describe 'articles' do
specify 'the' do
@book.title = "alexander the great"
@book.title.should == "Alexander the Great"
end
specify 'a' do
@book.title = "to kill a mockingbird"
@book.title.should == "To Kill a Mockingbird"
end
specify 'an' do
@book.title = "to eat an apple a day"
@book.title.should == "To Eat an Apple a Day"
end
end
specify 'conjunctions' do
@book.title = "war and peace"
@book.title.should == "War and Peace"
end
specify 'prepositions' do
@book.title = "love in the time of cholera"
@book.title.should == "Love in the Time of Cholera"
end
end
describe 'should always capitalize...' do
specify 'I' do
@book.title = "what i wish i knew when i was 20"
@book.title.should == "What I Wish I Knew When I Was 20"
end
specify 'the first word' do
@book.title = "the man in the iron mask"
@book.title.should == "The Man in the Iron Mask"
end
end
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T03:23:40.427",
"Id": "74879",
"Score": "0",
"body": "i'd say specs -- 4, code -- 3. i'd answer more fully but I don't have anything to add to Phillip's solution, which I like a lot other than the word \"titlieze\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T03:25:26.083",
"Id": "74880",
"Score": "0",
"body": "@Jonah Thanks for your input. I agree about \"titlieze\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-28T12:05:42.463",
"Id": "124371",
"Score": "0",
"body": "I use [this tool](http://www.booktitlecapitalization.com/) for my blog to auto-capitalize titles, but if you look at the source code, you can see how they wrote it in javascript following the Chicago Manual of Style rules for title capitalization."
}
] |
[
{
"body": "<p>Your code is readable, but it doesn't feel very \"rubyish\" to me. I think that's due to needing to setup and track some extra variables and track the index of the word in question -- having to case it depending on the index, etc.</p>\n\n<p>It also bugs me a little bit that <code>title=</code> is doing so much. This is how I would have written it:</p>\n\n<pre><code>class Book\n def title\n @title\n end\n\n def title=(title)\n @title = titlieze(title)\n end\n\n private\n def titlieze(title)\n stop_words = %w(and in the of a an)\n title.capitalize.split.map{|w| stop_words.include?(w) ? w : w.capitalize}.join(' ')\n end\n\nend\n</code></pre>\n\n<p>I used <code>stop_words</code> instead of <code>special_words</code> since that's a common naming scheme for search applications (ie. words you ignore when searching). I'd be tempted to move that into a constant or some other configuration, but it works fine for this.</p>\n\n<p>Rspec output:</p>\n\n<pre><code>$ rspec -f d foo_spec.rb\n\nBook\n title\n should capitalize the first letter\n should capitalize every word\n should capitalize every word except...\n conjunctions\n prepositions\n articles\n the\n a\n an\n should always capitalize...\n I\n the first word\n\nFinished in 0.00261 seconds\n9 examples, 0 failures\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T20:39:30.693",
"Id": "74804",
"Score": "0",
"body": "It does? Did you change your test from when it was on stackoverflow? It's passing on my system using Ruby 2."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T20:42:17.723",
"Id": "74805",
"Score": "0",
"body": "Hey thanks. Sorry about that, I made a mistake copying your code. It works well and is very nice. Thank you for your feedback. +1"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T20:35:52.983",
"Id": "43334",
"ParentId": "43331",
"Score": "11"
}
},
{
"body": "<p>Your indentation is a bit inconsistent, making the code hard to read.</p>\n\n<p>This short method</p>\n\n<pre><code>def title\n @title\nend\n</code></pre>\n\n<p>… is commonly written using meta-programming.</p>\n\n<p>The <code>title=</code> method could be improved by shortening it. There is too much reassignment going on: making an empty <code>formatted_title</code>, appending each word to it, then setting <code>@title</code>, but — just kidding! — we still have to re-join the words into a string! Better to <a href=\"https://stackoverflow.com/q/4697557/1157100\">do the job right the first time</a>.</p>\n\n<p>I also think that the code would be easier to understand by collapsing the three cases into two. Then you could easily state exactly <em>when</em> a word should be capitalized.</p>\n\n<pre><code>class Book\n attr_reader :title\n\n # Define this constant array just once\n @@SPECIAL_WORDS = %w(and in the of a an)\n\n def title=(title)\n @title = title.split.each_with_index.map do |w,i|\n case \n when i == 0 || !@@SPECIAL_WORDS.include?(w)\n # Capitalize the first word and all subsequent non-special words\n w.capitalize\n else\n w\n end\n end.join(' ')\n end\nend\n</code></pre>\n\n<p>Consider leaving words that already have internal capitalization unchanged (e.g. \"iPhone\").</p>\n\n<p>Also consider that you might already have a <a href=\"https://stackoverflow.com/a/1791922/1157100\"><code>String.titleize()</code></a> if you're using ActiveSupport.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T20:50:18.893",
"Id": "74807",
"Score": "0",
"body": "Whats the reason for creating a class variable constant? Are you just assuming that the special words may need to available to other methods on the Book class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T20:56:42.433",
"Id": "74809",
"Score": "0",
"body": "Just to emphasize that it never changes. I don't feel strongly about that particular piece of advice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T20:58:40.253",
"Id": "74810",
"Score": "0",
"body": "So you're saying a constant within the method itself may suffice?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:59:34.523",
"Id": "74848",
"Score": "0",
"body": "Sure, that could work too."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T20:43:26.320",
"Id": "43335",
"ParentId": "43331",
"Score": "3"
}
},
{
"body": "<p>Though I am not a professional developer, I will venture one suggestion: learn how to use String methods and regexes to fullest advantage. Sometimes it is necessary to use <code>split</code>, <code>partition</code>, etc. to convert a string to an array of strings (possibly single-character strings), manipulate the array elements, then re<code>join</code> them into a string, but there is a lot you can do by working on the string directly. Here, for example, you can use <a href=\"http://www.ruby-doc.org/core-2.1.0/String.html#method-i-gsub\" rel=\"nofollow\">String#gsub</a> with a block:</p>\n\n<pre><code>str = \"to eat an apple a day\" \nsw = %w[and in the of a an]\n\nstr.capitalize.gsub( /\\S+/ ) { |w| sw.include?(w) ? w : w.capitalize }\n #=> \"To Eat an Apple a Day\"\n</code></pre>\n\n<p>Edit: initially I had <code>...gsub( /\\w+/ )...</code>. I am grateful to @feed_me_code for the suggestion to use <code>\\S</code> rather than <code>\\w</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:43:01.417",
"Id": "75483",
"Score": "1",
"body": "+1 @Cary your suggestion: *\"learn how to use String methods and regexes to fullest advantage\"* is great. I wanted to add that instead of `\\w+` boundary.. Consider `\\S` Any non-whitespace character. This takes into account strings with punctuation. Consider this: `str = \"the girl's voyage back to earth\"` Thanks again for your advice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T06:55:36.387",
"Id": "75548",
"Score": "0",
"body": "Good point, feed. Will edit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T03:25:14.877",
"Id": "43365",
"ParentId": "43331",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "43334",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T20:12:41.377",
"Id": "43331",
"Score": "11",
"Tags": [
"strings",
"ruby",
"unit-testing"
],
"Title": "Proper capitalization for book titles"
}
|
43331
|
<p>I use the following code: <code>fetchAll</code> and <code>for($mich=0;$mich<10;$mich++)</code>.</p>
<p>Is this the best way?</p>
<p>Is there a better way, either to optimize or replace this code?</p>
<pre><code><?php
include("cache/phpfastcache.php");
phpFastCache::setup("storage","auto");
$cache = phpFastCache();
$products = $cache->get("product_page");
if($products == null) {
$akhbarkotah1 = $conn->prepare("SELECT text,time FROM small WHERE active='0' ORDER BY time DESC LIMIT 10");
$akhbarkotah1->execute();
$products = $akhbarkotah1->fetchAll();
$cache->set("product_page", $products,30);
}
for($mich=0;$mich<10;$mich++){
$text1 =$products[$mich][0];
$time1 =$products[$mich][1];
?>
<a class="lastnews">
<div id="lastnews_title" class="YekanBlack10" style="width:585px;">
<div><?php echo $text1; ?></div>
<div class="YekanRed10" style="text-align:left">
<?php echo timeTonow($time1); ?>
</div>
<div style="border-bottom:2px solid #7c0000;height:5px;"></div>
</div>
</a>
<?php
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T21:34:15.923",
"Id": "74819",
"Score": "0",
"body": "Does your *actual* code have this [non-]indentation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T21:48:38.700",
"Id": "74822",
"Score": "0",
"body": "i indent code , its not important"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T21:55:34.100",
"Id": "74824",
"Score": "7",
"body": "it actually *is* important, if you want readable/maintainable code. Indentation plays a very important part in making code structure obvious."
}
] |
[
{
"body": "<p>Using <code>fetchAll</code> usually is not a problem. There are some things to optimize here in my opinion:</p>\n\n<ul>\n<li><p>Use a <code>foreach</code> loop instead of <code>for</code> loop. Your result is already limited. No need to duplicate this here. This removes the iterator counter and assignment:</p>\n\n<pre><code>foreach ($products as $product) {\n $text1 = $product[0];\n $time1 = $product[1];\n?>\n</code></pre></li>\n<li><p>Using the Object fetch mode (returns objects instead of indexed arrays) makes this even more readable and saves you the name assignments:</p>\n\n<pre><code>foreach ($products as $product) {\n // $product->text1; $product->time1;\n?>\n</code></pre></li>\n<li><p>Though I'd recommend to remove these. Introducing numbers in variable names usually suggests there is a second one. E.g. <code>time2</code>.</p></li>\n<li>As @mat's mug pointed out, indentation is very important. Same goes for empty lines. There are great to structure your code in logical blocks. For this example here, I'd have an empty line after setting up the cache and one after loading the products. </li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T14:46:26.027",
"Id": "74957",
"Score": "0",
"body": "Thank you very much , can you help me for change to object fetch? i change $akhbarkotah1->fetchAll(); to $akhbarkotah1->fetch(PDO::FETCH_OBJ); and $text1 = $product[0]; to $text =$product->text; is this true?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T14:55:13.860",
"Id": "74959",
"Score": "0",
"body": "`fetch` returns a single entry only. You want all entries of the result-set: `fetchAll` should be used here (same argument though). This will return you an array of objects, one object for every row of the result-set. For detailed questions and howtos StackOverflow is the right place to ask :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:25:10.357",
"Id": "74973",
"Score": "0",
"body": "i ask this problem in : http://stackoverflow.com/questions/22176016/using-the-object-fetch-mode-with-foreach"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T23:43:34.617",
"Id": "43354",
"ParentId": "43338",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "43354",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T21:24:15.173",
"Id": "43338",
"Score": "2",
"Tags": [
"php",
"pdo"
],
"Title": "Are fetchAll() and for() good choices for my code?"
}
|
43338
|
<p>I'm new to PHP security and have made this login file:</p>
<pre><code><?php
header('Content-type: application/javascript');
$hostname_localhost = "";
$database_localhost = "";
$username_localhost = "";
$password_localhost = "";
$salt1 = "";
$salt2 = "";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = clean($_POST['username']);
$password = $_POST['password'];
$sha1_password = sha1($salt1.$password.$salt2);
$query_search = "select * from users where username = '".$username."' AND password = '".$sha1_password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
if($rows == 0) {
echo "No Such User Found";
} else {
$result = mysqli_query($localhost,"select * from users where username = '".$username."'");
while ($row = mysqli_fetch_array($result)) {
echo $row['id'];
}
}
function clean($string){
if (get_magic_quotes_gpc()) $string = stripslashes($string);
return mysql_real_escape_string($string);
}
?>
</code></pre>
<p>You'll probably all find a million things wrong with it but I need all the help I can get!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:45:27.393",
"Id": "74837",
"Score": "0",
"body": "There are most definitely things wrong. It appears you followed an old tutorial, so consider finding one that was recently written next time. (Here is one)(http://www.sunnytuts.com/article/login-and-registration-with-object-oriented-php-and-pdo) that covers the most important bases, and it looks like it covers security in the second part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T09:40:00.107",
"Id": "74921",
"Score": "0",
"body": "`mysql_connect` + `mysqli_fetch_array`... ? which extension are you using, `mysql_*` or `mysqli_*`? Note that it is requested you post _working_ code on this site, as code-REVIEW is all about having an extra pair of eyes pass over your code to _improve_ things, not to _fix_ things"
}
] |
[
{
"body": "<p>I don't know PHP, but it looks like you have an SQL injection vulnerability here:</p>\n\n<pre><code>$query_search = \"select * from users where username = '\".$username.\"' AND password = '\".$sha1_password. \"'\";\n</code></pre>\n\n<p>And here:</p>\n\n<pre><code>\"select * from users where username = '\".$username.\"'\"\n</code></pre>\n\n<p>What if <code>$username</code> is <code>' OR 1=1</code>?</p>\n\n<p>To fix this issue I suggest using <a href=\"http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php\" rel=\"nofollow\">prepared statements</a> for your queries and bind the parameters to your <code>$username</code> and <code>$password</code> values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T13:18:08.143",
"Id": "74942",
"Score": "1",
"body": "While you've pointed out the biggest issue with the OP's code (quite rightly), I don't know if your answer really qualifies as Code review. Sure, you've pointed out a security issue, but what is needed to plug the leak? Also note that `mysql_real_escape_string` would prevent `' OR 1=1` from messing up the where clause, since it escapes the `'` char"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:02:58.083",
"Id": "74984",
"Score": "0",
"body": "Oh correct, I forgot to point out how to fix it. About `mysql_real_escape_string`, sorry, as I stated *\"I don't know PHP\"*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T19:57:27.607",
"Id": "75051",
"Score": "1",
"body": "Well, `mysql_real_escape_string` _is_ part of [the mysql C API](http://dev.mysql.com/doc/refman/5.0/en/c-api-function-overview.html), too. I believe most languages that come with mysql extensions/adapters/connectors out of the box have implemented an escaping function at some point. But that's just me being pedantic. Bottom line is: you are right: there is an injection vulnerability, still. I just wanted to let you know that this answer, to me, is sort of in the middle between a comment and and an actual answer, hence no vote (down or up)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:24:03.940",
"Id": "75056",
"Score": "0",
"body": "@EliasVanOotegem Yeah, I was in doubt too. I first added it as comment, then posted as answer because I think it points out the major flaw there (from my knowledge)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:15:35.187",
"Id": "43345",
"ParentId": "43339",
"Score": "5"
}
},
{
"body": "<p><strong><em>Warning</em></strong><Br>\nThis is a code-review (CR) site. Though my answer/review may seem harsh at points, it is my firm belief that CR can, and should, be tough. <a href=\"https://codereview.meta.stackexchange.com/questions/810/guidelines-for-new-users-proposal-tag\">I've explained my reasoning at length here</a>.<br>\nIt is not my intention to hurt yours or anyone else's feelings, be advised that some criticisms may be phrased badly, or bluntly. It is important, then, to keep in mind that my only goal is to help.</p>\n\n<p>Due to the fact that much of CR is criticizing other peoples code, you may get the impression that I see myself as the light of the world, and only source of\n<em>\"good code\"</em>. Not so. Some critiques are subjective (such as which extension I recommend: <code>PDO</code> and not <code>mysqli_*</code>). TMTOWTDI and to each his own.</p>\n\n<hr>\n\n<p>The first thing that is <em>\"bad\"</em> (as in: not good practice), is that you're not using the right MySQL extension. What is in fact outright <strong>wrong</strong> is that you're not consistently using a single extension throughout. Most of the time, you're using the <code>mysql_*</code> extension (which is <em>really</em>, <strong>really</strong> bad, <a href=\"http://thread.gmane.org/gmane.comp.php.devel/66726\" rel=\"nofollow noreferrer\">mkay</a>). But then out of the blue you have this, shall we say, <em>moment of clarity</em>, and you use the MySQL Improved extension (or <code>mysqli_*</code>):</p>\n\n<pre><code>//all your code using mysql_*\n$result = mysqli_query($localhost,\"select * from users where username = '\".$username.\"'\");\nwhile ($row = mysqli_fetch_array($result)) {\n echo $row['id'];\n}\n//reverting back to deprecated extension\n</code></pre>\n\n<p>The help section of this site specifically request you post <em>actual, working</em> code to review. If you need this code fixed/debugged: set about trying yourself and, if you can't seem to get it to work, post a question on SO.<br>\nPlease clarify (by editing your posted code) which extension you're actually using. Also mention any notices, errors or warnings you get, if any.<br>\nRegardless of what extension you choose: make sure it's <em>not</em> deprecated, use it as was intended and <strong>be consistent</strong>.</p>\n\n<p>The second thing is the use of <em>magic quotes</em>. Like the <code>mysql_*</code> extension, <a href=\"http://www.php.net/magic_quotes\" rel=\"nofollow noreferrer\">these have been deprecated</a> for quite some time and have been <strong><em>removed</em></strong> since PHP 5.4.0. Do not use them. Ever. No, seriously. Stop. I'm not joking. Honest.</p>\n\n<p>Third item on the agenda: at no point are you bothering to check if there is any POST data to be processed, You just blindly assume <code>$_POST['username']</code> will be there. That <em>can</em> issue notices (undefined index E_NOTICE).<Br>\nAdding an <code>if (!isset($_POST['username']) || !isset($_POST['password'])) exit();</code> isn't a lot of work, and prevents all this.<br>\nI would assume you're <code>include</code>-ing this file as part of a bigger script, and in case that script <em>does</em> check for <code>isset</code> params, then you should be good, but if that's the case: be careful with that <code>header</code> business. If the headers are already sent, you'll get an error.</p>\n\n<p>Which brings us neatly on to point four: <code>header('Content-type: application/javascript');</code>? Why? What? How? Why are you setting a header that makes <em>no sense</em>? As far as I can tell, you're only echoing text, a more suitable header, then, would be: </p>\n\n<pre><code>header('Content-Type: text/plain');\n</code></pre>\n\n<p>If you are going to add markup to the output, change that header to:</p>\n\n<pre><code>header('Content-Type: text/html');\n</code></pre>\n\n<p>Fifth: <code>mysql_connect(...) or trigger_error(mysql_error(),E_USER_ERROR);</code> vs <code>$query_exec = mysql_query($query_search) or die(mysql_error());</code>. Why are you using that horrible <code>or</code>? and why use <code>trigger_error</code> the first time 'round, only to then switch to that <em>equally horrible</em> <code>die</code>?<br>\nIf the db connection failed, then the app failed. <code>throw new RuntimeException('Could not connect to db');</code> from a function that returns a db connection is what you could do, or simply <code>exit(1);</code><br>\nWhatever you do: <strong>be consistent</strong>.</p>\n\n<p>Lastly, and most importantly: as a result of the things mentioned above, and the fact you're simply concatenating <em>barely</em> validated POST data into a query: <em>You are vulnerable to injection attacks</em>. <a href=\"http://bobby-tables.com/\" rel=\"nofollow noreferrer\">This site explains what they are</a>.<br>\nAn easy, reliable and safe way to prevent this sort of attack is to use <em>prepared statements</em>. An example of how this is done with <code>PDO</code> would be:</p>\n\n<pre><code>$dsn = 'mysql:host=127.0.0.1;dbname=default_db';\n$user = 'root';\n$pass = 'DoNotUseRootUserIfYouDoNotNeedRootAccess';\n$pdo = new PDO(\n $dsn,\n $user\n $pass,\n array(//more options here\n PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION\n PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ\n )\n);\n//no quotes, no data, just the query as-is\n$stmt = $pdo->prepare(\n 'SELECT * \n FROM users\n WHERE username = :uname\n AND password = :pass'\n);\n$stmt->execute(\n array(\n ':uname' => $_POST['username'],\n ':pass' => sha1($salt1.$_POST['password'].$salt2)\n )\n);\nif (!($row = $stmt->fetch()))\n{\n echo 'User not found';\n}\nelse\n{\n do\n {\n echo $row->id, PHP_EOL;\n }while($row = $stmt->fetch());\n}\n</code></pre>\n\n<p>Just browse through the documentation for <a href=\"http://www.php.net/manual/en/class.pdo.php\" rel=\"nofollow noreferrer\">the <code>PDO</code> class</a>, or work out how to use prepared statements using <a href=\"http://www.php.net/manual/en/book.mysqli.php\" rel=\"nofollow noreferrer\">the <code>mysqli_*</code> extension</a>. It's not very hard, and I'd be happy to review your attempts at it, but I don't really like <code>mysqli</code> all too much, so I'm not posting an example here.<br>\nTo help you choose between the two extensions, there's <a href=\"http://www.php.net/manual/en/mysqlinfo.api.choosing.php\" rel=\"nofollow noreferrer\">a special choose-an-api page can be found here</a></p>\n\n<p>The reason why I prefer <code>PDO</code>, in case you are wondering is simply because its API is clean, and consistent: it's OO-only, whereas <code>mysqli_*</code> offers both a procedural and OO API. That, to my eye, makes for messy code.<br>\n<code>mysqli_*</code> uses a bit too much pass-by-reference in its methods:</p>\n\n<pre><code>$foo = 123;\n$mysqliStmt->bindParam('i', $foo);//REFERENCE to $foo\n$foo = 678;\n$mysqliStmt->execute();//will use CURRENT value of $foo -> 678\n</code></pre>\n\n<p>It, once again, has to do with <strong>being consistent</strong>.</p>\n\n<p>Last thoughts:<br>\nGiven that you're still new to PHP, I'll leave it at this. Spend some time on the doc pages, and if it all gets a bit much, perhaps look at the unofficial coding standards: <a href=\"http://www.php-fig.org/\" rel=\"nofollow noreferrer\">at PHP-FIG</a>. All major players (Zend, Symfony, Doctrine, Drupal, Joomla... the list is on the site) subscribe to these standards. Since I've repeated it many times before here, if you want to be consistent, too: try and adopt these coding standards.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T09:57:10.407",
"Id": "43390",
"ParentId": "43339",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "43390",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T21:24:43.620",
"Id": "43339",
"Score": "2",
"Tags": [
"php",
"beginner",
"mysql",
"security"
],
"Title": "Login code probably not secure"
}
|
43339
|
<p>I submitted this problem for an interview, and I was wondering if I could have done better. My solution works, and I solved in about 12-15 minutes. I feel like I did a bad job with the code. Please be honest.</p>
<p>Here is the question:</p>
<blockquote>
<p>Given a non-negative number represented as an array of digits, plus
one to the number. Also, the numbers are stored such that the most
significant digit is at the head of the list.</p>
</blockquote>
<p>In particular, what stumped me was the fact that I'd get the right answer, but have the initial index (at 0) in sometimes empty with the answer on the other half, and couldn't figure out a quick half to shift all the elements to the left without using extra storage.</p>
<pre><code>public int[] plusOne(int[] digits) {
int[] toRet=new int[digits.length+1];
int[] temp=null;
for(int i=toRet.length-1; i>=0; i--){
if(i-1>=0){
toRet[i]=digits[i-1];
}
}
for(int i=toRet.length-1; i>=0; i--){
if(toRet[i]+1 == 10){
toRet[i]=0;
}
else{
toRet[i] = toRet[i]+1;
break;
}
}
if(toRet[0]==0){
temp = new int[toRet.length-1];
for(int i=1; i<toRet.length;i++){
temp[i-1] = toRet[i];
}
return temp;
}
else{
return toRet;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The goal in my answer is code conciseness. Order of magnitude of runtime is the length of the array, which would only need to be re-created if the new array has additional digits. If you're only adding +1, it's somewhat simpler to perform the carry operation.</p>\n\n<pre><code>public int[] plusOne(int[] digits) {\n if (digits == null) return null;\n if (digits.length == 0) return new int[] {1};\n for (int i = digits.length - 1; i >= 0; i--) {\n if (digits[i] != 9) {\n digits[i]++;\n return digits;\n } else digits[i] = 0;\n }\n int[] retVal = new int[digits.length + 1];\n retVal[0] = 1;\n for (int i = 1; i < retVal.length; i++) digits[i] = 0;\n return retVal;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:41:25.420",
"Id": "74834",
"Score": "0",
"body": "in the corner case of the overflow, digits should be copied to retVal"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:42:42.613",
"Id": "74836",
"Score": "0",
"body": "int[] values are automatically initialized to 0 @vals"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:46:44.943",
"Id": "74838",
"Score": "0",
"body": "never mind @vals. done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:49:48.993",
"Id": "74841",
"Score": "0",
"body": "I mean for (int i = 1; i < retVal.length; i++) retVal[i] = digits[i-1];"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:50:49.007",
"Id": "74843",
"Score": "0",
"body": "@La-comadreja Your code doesn't work. Pass int[] a={9, 9} as input, the answer should be {1, 0, 0}"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:52:53.960",
"Id": "74844",
"Score": "0",
"body": "@bazang what do you get?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:53:21.773",
"Id": "74845",
"Score": "0",
"body": "@vals if the 1 could be added earlier, it is and the list is returned. Hence the way I wrote the end."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:32:20.217",
"Id": "43346",
"ParentId": "43343",
"Score": "1"
}
},
{
"body": "<h1>What you did well</h1>\n<p>I like that you have:</p>\n<ul>\n<li>decently named varaibles</li>\n<li>you use good backward looping through the data</li>\n<li>the formatting and style is good.</li>\n</ul>\n<h1>Issues</h1>\n<ul>\n<li>you are doing a lot of manual copying... <code>Arrays.copyOf()</code> is your friend.</li>\n<li>you should be declaring variables where you need them, not at the beginning of the method (<code>temp</code>).</li>\n<li>the algorithm is not a natural fit for the problem.... too complicated, and that is why there is the odd offset in your results.</li>\n</ul>\n<h1>Alternative...</h1>\n<p>Consider this code alternative, which uses a standard adder-with-carry:</p>\n<pre><code>public static final int[] addOne(int[] digits) {\n int carry = 1;\n int[] result = new int[digits.length];\n for (int i = digits.length - 1; i >= 0; i--) {\n int val = digits[i] + carry;\n result[i] = val % 10;\n carry = val / 10;\n }\n if (carry == 1) {\n result = new int[digits.length + 1];\n result[0] = 1;\n }\n return result;\n}\n</code></pre>\n<p>The carry is initialized with the value-to-add <code>1</code>, and it is added to the least significant value.</p>\n<p>If the overall addition results in a carry still, then we add a new digit to the result, and, because the sub being added is a 1, we can make assumptions about the result.</p>\n<h1>Edit:</h1>\n<p>My test code:</p>\n<pre><code>public static void main(String[] args) {\n System.out.println(Arrays.toString(addOne(new int[]{})));\n System.out.println(Arrays.toString(addOne(new int[]{1})));\n System.out.println(Arrays.toString(addOne(new int[]{9})));\n System.out.println(Arrays.toString(addOne(new int[]{3, 9, 9})));\n System.out.println(Arrays.toString(addOne(new int[]{3, 9, 9, 9})));\n System.out.println(Arrays.toString(addOne(new int[]{9, 9, 9, 9})));\n System.out.println(Arrays.toString(addOne(new int[]{9, 9, 9, 8})));\n}\n</code></pre>\n<p>and my results:</p>\n<blockquote>\n<pre><code>[1]\n[2]\n[1, 0]\n[4, 0, 0]\n[4, 0, 0, 0]\n[1, 0, 0, 0, 0]\n[9, 9, 9, 9]\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T23:02:53.723",
"Id": "74850",
"Score": "1",
"body": "I like that. It's even more generalizable to make \"carry\" into an explicit parameter so you can add any one-digit number, not just 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T23:20:13.130",
"Id": "74857",
"Score": "0",
"body": "@rolfl can you test your code with {3, 9, 9}; I don't think it works."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T01:51:12.273",
"Id": "74867",
"Score": "0",
"body": "Just realised from your solution that int arrays are initialized with 0s... don't think I've ever explicitly relied on this part of the JLS. :) If I was working on the solution as you, I will also check that the array is not empty so that my method doesn't return 1 for it... but this could be just me. ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:22:32.467",
"Id": "75032",
"Score": "0",
"body": "@rolfl I thought by saying 'new' in the if carry==1, you are essentially allocating a new slab of memory of the array, so it would lose the previous memory that variable was assigned to, yet somehow it retains it, how so?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:26:34.387",
"Id": "75035",
"Score": "0",
"body": "@bazang The only time the carry will `==1` after the while loop is when all the input digits are `9`. Inside the loop the `carry` is reset to `carry = val / 10` which will only ever be 1 if val is 10 (or more, which should never happen)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:50:38.063",
"Id": "80193",
"Score": "0",
"body": "@bazang: If you like the site and have time feel free to help [graduating it](http://meta.codereview.stackexchange.com/q/1572/7076). I'm sure that you can find another useful questions and answers on the site to [vote on](http://meta.codereview.stackexchange.com/q/612/7076)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T19:16:16.993",
"Id": "80207",
"Score": "1",
"body": "@palacsint absolutely, I'd love to help out.I like it here."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:57:28.967",
"Id": "43349",
"ParentId": "43343",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "43349",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:10:09.010",
"Id": "43343",
"Score": "10",
"Tags": [
"java",
"algorithm",
"interview-questions"
],
"Title": "Add one to a number represented as an array of digits"
}
|
43343
|
<p>I wrote some Python code to solve the following problem. I'm curious to see if someone else can find a better solution, or critique my solution.</p>
<p>How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.</p>
<pre><code>class SmartStack:
def __init__(self):
self.stack= []
self.min = []
def stack_push(self,x):
self.stack.append(x)
if len(self.min) != 0:
if x < self.stack_min():
self.min.append(x)
else:
self.min.append(x)
def stack_pop(self):
x = self.stack.pop()
if x == self.stack_min():
self.min.pop()
return x
def stack_min(self):
return self.min[-1]
def main():
print "Push elements to the stack"
list = range(10)
stack = SmartStack()
for i in list:
stack.stack_push(i)
print "Print stack and stack minimum"
print stack.stack
print stack.stack_min()
print "Push -1 to stack, print stack and stack minimum"
stack.stack_push(-1)
print stack.stack
print stack.stack_min()
print "Pop from stack, print stack and stack minimum"
print stack.stack_pop()
print stack.stack
print stack.stack_min()
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:10:54.253",
"Id": "74964",
"Score": "1",
"body": "Your requirements sound impossible to me unless you make some additional assumptions. Proof: The optimal comparison sorting algorithm (given a simple comparer and nothing more) has runtime Ω(n*log(n)). If you push all elements and then use alternating calls to `min` and `pop` you get back a sorted list in time O(n), which is a contradiction. => The only way to have O(1) for all of `push`, `pop` and `min` is going beyond a simple comparer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T19:55:24.237",
"Id": "75050",
"Score": "0",
"body": "@CodesInChaos No, you can't use this for sorting because there is no function to pop the minimum off the stack."
}
] |
[
{
"body": "<p>This assumes your stack has integer values, or values that can be translated in constant time to integers. If you're creating the stack from scratch and building the class yourself, create an array of integers where the indices are the values of the elements, and the values at those indices are the number of elements in the stack with those values. Also create another stack representing the set of number values, sorted with the lowest values in front. Then push() of a new min also adds an element to the new stack, pop() of the lowest value is also a pop of the new stack. I do think you need another data structure to keep track of the sorting in constant time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T23:03:23.047",
"Id": "74851",
"Score": "0",
"body": "Even with the integers only restriction, the operations are not always O(1): when the counting bin of your minimum gets to 0 you need to search for the new minimum, which is going to be an O(n) operation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T23:05:04.253",
"Id": "74853",
"Score": "0",
"body": "read the answer again. Not with a 2nd stack which is sorted and contains one element per value contained in the stack."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T07:35:04.573",
"Id": "74898",
"Score": "0",
"body": "How would you maintain the array in sorted order with constant time push and pop?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:51:28.623",
"Id": "43348",
"ParentId": "43344",
"Score": "0"
}
},
{
"body": "<p>Your implementation fails if there are duplicates values in the stack:</p>\n\n<pre><code>def main():\n stack = SmartStack()\n stack.stack_push(1)\n stack.stack_push(1)\n stack.stack_push(3)\n stack.stack_pop()\n stack.stack_pop()\n print(stack.stack_min())\n</code></pre>\n\n<blockquote>\n<pre><code>$ ./smartstack \nTraceback (most recent call last):\n File \"./smartstack\", line 35, in <module>\n main()\n File \"./smartstack\", line 32, in main\n print(stack.stack_min())\n File \"./smartstack\", line 23, in stack_min\n return self.min[-1]\nIndexError: list index out of range\n</code></pre>\n</blockquote>\n\n<p>Suggested fix:</p>\n\n<pre><code>def stack_push(self,x):\n self.stack.append(x)\n if not self.min or x <= self.stack_min():\n self.min.append(x)\n</code></pre>\n\n<p>The naming is redundant: methods of the <code>SmartStack</code> class shouldn't need to have \"stack_\" in their names.</p>\n\n<p>If you are targeting Python 2, be sure to use new-style classes (i.e., <code>SmartStack</code> should have <code>object</code> as a superclass).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T00:10:27.807",
"Id": "43355",
"ParentId": "43344",
"Score": "4"
}
},
{
"body": "<p>Your code will not return min value when you pop from stack. The \"min\" stack is not properly maintained. if the value to be inserted is not smaller than the one in min stack, you have to insert the \"min.append(self.stack_min())\". Please change the following for it to work as expected.\nSuggested fix:</p>\n\n<pre><code> else:\n self.min.append(self.stack_min())\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-04T07:29:27.817",
"Id": "191221",
"ParentId": "43344",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "43355",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:15:01.160",
"Id": "43344",
"Score": "5",
"Tags": [
"python",
"stack"
],
"Title": "Retrieve min from stack in O(1)"
}
|
43344
|
<p>I have a function that reads a string like this</p>
<pre><code>(AnimalCount+HumanCount)
</code></pre>
<p>and the result of this function is an array of strings</p>
<pre><code>[ "(" , "AnimalCount" , "+" , "HumanCount" , ")" ]
</code></pre>
<p>Now, I have done 2 functions in order to do this:</p>
<p>The first one to check if a given char is "special" from the input string</p>
<pre><code>function Validate(Character: Char): Boolean;
begin
Validate:= Character in [',' , '+' , '-' , '*' , '/' , '(' , ')' , '^' ,
'[' , ']' , '%' , '&' , '=' , '<' , '>' , ' ' ,
'.' , ';' , ':'];
end;
</code></pre>
<p>The second one to separate the strings from the input:</p>
<pre><code>function GetToken(Chain:String):ArrayofString;
Var NTokens,i,j:Integer;
begin
NTokens:=0;
SetLength(Result,0);
For i := 1 to Length(Chain) do
if Validate(Chain[i]) then
begin
Inc(NTokens);
setlength(Result,NTokens+1);
Result[NTokens]:=Chain[i];
Inc(NTokens);
end
else
begin
If Length(Result)<NTokens+1 then
begin
setlength(Result,NTokens+1);
Result[NTokens]:='';
end;
Result[NTokens]:=Result[NTokens]+Chain[i];
end;
end;
</code></pre>
<p>Additionally, I had to put this after <code>type</code> to make it work this way:</p>
<pre><code>Arrayofstring = array of String;
</code></pre>
<p>This functions are working, but I wonder if there is any way to improve it even further. I am new to Delphi, so any help would be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:47:24.330",
"Id": "74839",
"Score": "0",
"body": "Please can you specify in which ways you want this to be improved?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:53:42.583",
"Id": "74846",
"Score": "0",
"body": "@DavidHeffernan thanks for sending me here btw, well, i just wonder if the result i am getting could be achieved in fewer steps, like i said i am new to delphi and programming in general"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:58:24.807",
"Id": "74847",
"Score": "1",
"body": "I'd use TStringList or TStrings for the output. I'd always pass string args by const for perf reasons. I'd avoid building strings char by char and use a single Copy() to make new items."
}
] |
[
{
"body": "<ol>\n<li><p><code>Validate</code> is a misleading name for what the function does. It does not validate anything - rather it checks if the given character is one of a special set. So it should be named <code>IsSpecial</code> or <code>IsTokenDelimiter</code>.</p></li>\n<li><p>Growing an array one entry at a time is quite a bit of overhead. <a href=\"https://stackoverflow.com/questions/5755998/appending-one-element-to-a-dynamic-array\">There are some ways of mitigating this</a>.</p></li>\n<li><p>Consider creating a local variable like <code>currentCharacter</code> in which <code>Chain[i]</code> - this would make it a little bit easier to read.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T08:26:32.717",
"Id": "43384",
"ParentId": "43347",
"Score": "4"
}
},
{
"body": "<p>Delphi is a nice language in that it is not case sensetive. However, I would still encourage you to stick to one casing. Decide on if you want to use <code>if</code> or <code>If</code> and stick to that. (My personal opinion: Use all lowercase). This also goes for <code>var</code> and <code>for</code> in your code.</p>\n\n<hr>\n\n<p>Your code has a bit of inconsistent spacing. Take a look at this line for example:</p>\n\n<pre><code>Result[NTokens]:=Result[NTokens]+Chain[i];\n</code></pre>\n\n<p>I would write this as:</p>\n\n<pre><code>Result[NTokens] := Result[NTokens] + Chain[i];\n</code></pre>\n\n<p>I also think that you can use more spaces in your function header for <code>GetToken</code> (compare it with <code>Validate</code>). And also use a space after each comma (in parameter lists and variable declarations).</p>\n\n<hr>\n\n<p>Your <code>Validate</code> method is quite good. I agree with ChrisWue that the naming could be better.</p>\n\n<p>As for your GetToken method, that can be drastically improved.</p>\n\n<p>Instead of appending char-by-char to the <code>Result[NTokens]</code> string, consider using a <code>var Current: String</code>, add the chars to that string and then when you encounter the next token separator you add the <code>Current</code> to the result.</p>\n\n<p>Regarding your Result, instead of using an array of String, consider the class <code>TStrings</code> or <code>TStringList</code>.</p>\n\n<p>Speaking of TStringList, that actually has support for using delimiters. See <a href=\"https://stackoverflow.com/questions/1335027/delphi-stringlist-delimiter-is-always-a-space-character-even-if-delimiter-is-se\">this SO question</a> for an example.</p>\n\n<p>If you want to do this yourself (which can be good practice), I would suggest returning a <code>TStringList</code> and calling the add method to add new strings to it. Here's a start for you on returning TStringList, as it's been a while since I used Delphi you will have to fix my mistakes and possibly change some stuff to make it work.</p>\n\n<pre><code>Result := TStringList.Create;\nCurrent := \"\";\nfor i := 1 to Length(Chain) do\nif IsTokenDelimiter(Chain[i]) then\nbegin\n if (Length(Current) > 0) then\n Result.Add(Current);\n Result.Add(Chain[i]);\n Current = \"\";\nelse\n begin\n Current = Current + Chain[i];\n end; \n</code></pre>\n\n<p>If you want to learn more about using built-in systems, take a look around at the TStringList class and see if it's delimiter system can simplify things for you. Perhaps it can't, in which case you might want to google for other Delphi classes that <em>can</em>. It's been a while since I've used Delphi, so I can't recommend a specific something that I know would work for you.</p>\n\n<p>Lastly, I would like you to think about why you need this feature. Where does your string come from? If it's input from the user, then it's probably fine (although you might want to seperate the user inputs). If it is result from a function that you wrote, use a <strong>record</strong>, an <strong>object</strong> or a <strong>class</strong> type. Really, learn how to write your own records and objects and classes! They will simplify many things for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-14T13:13:32.260",
"Id": "94556",
"Score": "1",
"body": "Returning a TStringList as a function result is considered bad practice because it could create a memory leak if an exception occurs within your function after you created that object. Using an array of string is better in this regard because it is reference counted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-14T13:54:16.313",
"Id": "94560",
"Score": "0",
"body": "@dummzeuch Good advice. It's been way too long since I used Delphi apparently :) Welcome to Code Review!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T12:05:55.547",
"Id": "43398",
"ParentId": "43347",
"Score": "4"
}
},
{
"body": "<p>Here is a function for delimited string to TStringList conversion from my utilities library:</p>\n\n<pre><code>function DelimitedStringToStringList\n ( const ADelimitedString: String;\n const ADelimiter : Char ): TStringList;\nvar\n I : NativeInt;\n SeparatedString : String;\nbegin\n\n SeparatedString := '';\n Result := TStringList.Create;\n\n for I := 1 to Length ( ADelimitedString ) do\n begin\n\n if ADelimitedString [I] = ADelimiter then\n begin\n\n if SeparatedString <> '' then\n begin\n Result.Add ( SeparatedString );\n SeparatedString := '';\n end;\n\n end\n else\n SeparatedString := SeparatedString + ADelimitedString [I];\n\n end;\n\n if SeparatedString <> '' then\n Result.Add ( SeparatedString );\n\nend;\n</code></pre>\n\n<p>You may derive your own solution from this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-25T12:36:34.917",
"Id": "45303",
"ParentId": "43347",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "43398",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T22:44:16.253",
"Id": "43347",
"Score": "6",
"Tags": [
"beginner",
"strings",
"delphi"
],
"Title": "Produce an array of strings from a single string"
}
|
43347
|
<p>Here's a novel-length summary of the issue:</p>
<p>I'm trying to write a VB.net program to help me collect remote site statistics from system-generated logs, but I'm a little like a carpenter who only knows how to use a hammer, and my project has turned into a bit of a monstrosity; as embarrassing as my code is, I would really love to get some professional opinions on how I can make it more streamlined and efficient, and generally less embarrassing.</p>
<p>Here's the basic rundown of relevant program functionality:</p>
<ol>
<li>The user can select up to five plaintext log files, each of which can be relatively long (the longest I have available for testing is 26k lines).</li>
<li>The program reads through every line of each file in turn, using <code>IO.File.ReadLines</code>, looking for relevant entries (in this case, every time a terminal goes UP or DOWN), and records the information in an "entry" object, which is stored in a list of entry objects. (At this point, I do a lot with the entries, but I'm going to focus just on one activity for this question).</li>
<li>To find individual site outages, the program reads through the list of entries until it finds the first "DOWN" entry. It records the site ID, the site's group ID, and the outage start time. At this point, things start to get grossly inefficient.</li>
<li>After it has collected the information listed in step 3, it records the current entry list index as a bookmark, then proceeds to look through all the following indices until it finds the next entry with that site ID; if that entry has an "UP" status, then it records that entry time as the outage end time, and calculated the total duration of the outage, then it goes back to the bookmark to look for the next outage start time. If it's a "DOWN" status, it scraps the current outage and goes back to the bookmark to look for the next outage start time. All of this information (and that recorded from step 3) is recorded in an "outage" object, and stored in a list of outages. This step takes an extremely long time.</li>
<li>The program then goes through the list of outages, and checks to see if the site ID is contained in a dictionary(of string, array). If so, it adds the outage duration to the dictionary value array index 0, and it adds 1 to the array index 1. This way, I can keep track of the total outage duration for that site, and the total number of outages.</li>
<li>Once all the outages have been added to the dictionary of sites, the program runs through that dictionary and calculates the average downtime of each site, and puts the results into another dictionary(of string,integer) to associate the site ID with its average downtime. It also adds each average downtime to a list (called "sorter"). This next part is really sloppy, but I don't know how to do it better (or at all).</li>
<li>The "sorter" list is then sorted in descending order. When the average outage times are graphed (xval is index, yval is average duration in minutes), it only plots durations greater than the value in sorter(9); my intent was to graph only the top ten sites (by average downtime), because thousands can be present in a single log file and graphing all of them would be unreadable. However, there are many many problems with doing it this way, and I don't know how to do it better when the values are stored in a dictionary. Likewise, I can't store them in a list(of array), because I'd need to store strings and integers in the same array (unless there's a way around mixing types like that?).</li>
</ol>
<p>Here are the specific questions I have:</p>
<ol>
<li><p>Is there a more efficient way to perform these searches without resorting to so many time-consuming nested loops?</p></li>
<li><p>Is there a more efficient and effective way to sort my outages by the outage duration (integer), while still keeping that duration associated with the site ID (string)?</p></li>
</ol>
<hr>
<pre><code>Public Sub avgdowntimepersite(ByVal type As DataVisualization.Charting.SeriesChartType)
Dim stats As New Dictionary(Of String, Integer)
Dim sorter As New List(Of Integer)
Dim outages As New List(Of outage)
Dim sites As New Dictionary(Of String, Array)
Dim x = 0 'This is a bookmark to return to after finding the start and stop times of an outage.
For i = 0 To searchedlist.Count - 2
Dim entry = searchedlist(i)
Dim newoutage As New outage
newoutage = Nothing
If entry.status = "Down" Then 'Find the first "Down" status in the list of search results.
newoutage.termid = entry.termid 'Gather as much info as you can from the "Down" status.
newoutage.popid = entry.popid
newoutage.starttime = entry.dtg
x = i 'Set the bookmark index to the index at which the "Down" status was found.
For a = i + 1 To searchedlist.Count - 2 'Go to the next line and start searching for the next status for this site.
Dim findend = searchedlist(a) 'If the searchresult termid matches the termid of the current outage...
If findend.termid = newoutage.termid And findend.status = "Up" Then '...and the status is "Up"...
newoutage.endtime = findend.dtg '...collect the end time of the outage...
newoutage.duration = newoutage.endtime - newoutage.starttime '...and calculate the duration, in minutes.
outages.Add(newoutage) 'Finally, add the new outage to the list of outages.
i = x + 1 'Go to one line after the bookmark to start looking for the next outage.
ElseIf findend.termid = newoutage.termid And findend.status = "Down" Then 'If the searchresult termid matches the outage termid, but it's another "Down" status...
newoutage = Nothing '...scrap the current outage as unresolveable...
i = x '...and go back to the bookmark and start looking for the next outage.
Continue For
End If
Next
End If
Next
If outages.Count > 0 Then 'If there were actually outages found by the above loop...
sites.Add(outages(0).termid, {outages(0).duration.Minutes, 1}) 'Add the first outage to the list of sites. Format is: termid,(total duration, total # of outages)
For i = 1 To outages.Count - 1
Dim item As String = outages(i).termid
If sites.ContainsKey(item) Then 'If the current outage is already in the dictionary of sites...
sites(item)(0) = sites(item)(0) + outages(i).duration.Minutes '...add the duration of the current outage to the total outage duration for that site...
sites(item)(1) += 1 '...and increase that site's total number of outages by one.
Else
sites.Add(item, ({outages(i).duration.Minutes, 1}))
End If
Next
End If
For Each tml In sites
stats.Add(tml.Key, (tml.Value(0) / tml.Value(1))) 'Calculate the average duration of each outage, and add it to the "stats" dictionary.
sorter.Add((tml.Value(0) / tml.Value(1)))
Next
sorter.Sort()
sorter.Reverse()
If stats.Count > 0 Then
outagechart.Series.Clear()
outagechart.Series.Add("avgpersite")
outagechart.Series(0).ChartType = type
outagechart.Series(0).Color = Color.Lime
outagechart.ChartAreas(0).AxisY.LabelStyle.ForeColor = Color.Gold
outagechart.ChartAreas(0).AxisX.LabelStyle.Angle = 45
outagechart.ChartAreas(0).AxisX.LabelStyle.ForeColor = Color.Gold
outagechart.ChartAreas(0).AxisX.Interval = 1
outagechart.ChartAreas(0).AxisX.IntervalType = DataVisualization.Charting.DateTimeIntervalType.NotSet
End If
For Each tml In stats
If tml.Value > sorter(9) Then
outagechart.Series(0).Points.AddXY(tml.Key, tml.Value)
outagechart.Series(0).IsXValueIndexed = True
End If
Next
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T02:10:23.040",
"Id": "74870",
"Score": "0",
"body": "What does the data look like in searchedlist? What kind of class is entry? What does the outage class look like? One way to help cut down on the loops is keep a record of each siteid's status in a collection. Read through the searchedlist once and as each siteid gets a down then and up record that outage time for that siteid."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:49:54.310",
"Id": "75004",
"Score": "0",
"body": "\"entry\" and \"outage\" are both public structures I created (I'm sorry if that's not specific enough; I don't know a more detailed way of describing it without pasting the whole thing), and \"searchedlist\" is just a list of the \"entry\" structures. I did it this way so the user can narrow their search to a specific site or timeframe before initiating the averaging and graphing subs (such as the one I included in the question) in the hopes of cutting down the time necessary for graphing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T17:08:24.623",
"Id": "75011",
"Score": "0",
"body": "Sorry, I couldn't fit this on the above comment: I tried building the outages in a single loop through the searchedlist, but I couldn't figure out how to effectively keep track of each outage for each site as the loop progressed. For instance if Site A is down at 18:59, Site B is down at 18:59, Site C is down at 19:00 Site B is up at 19:00, Site B is down at 19:01, how do I keep track of each site's individual outages in just one loop? In this example, site B has multiple outages before site A or Site C ever come up. I think there must be a way to handle this that I'm just not familiar with."
}
] |
[
{
"body": "<p>It seems to me that the main thing you need to do is sort out your logic.</p>\n\n<p>The way I'd expect things to work would be that for any given site, a <code>DOWN</code> entry indicates that site has gone down, and it's counted as remaining down until you see an <code>UP</code> entry for the same site. If you see a number of <code>DOWN</code> messages for one site without an intervening <code>UP</code> message, it just means the site went down, and remained down.</p>\n\n<p>That does not seem to fit your description though. Based on how you've described the logic, it sounds like when/if you see two <code>DOWN</code> messages for a given site, you (effectively) re-start the search from the latter of the two. That would mean that given N consecutive <code>DOWN</code> entries for one site, you count the site as being down only from the <em>last</em> of these messages until the following <code>UP</code> message (for the same site). If that's the case, you can speed up the search quite a bit by simply keeping track of the most recently-seen <code>DOWN</code> entry for a given site, and when you see an <code>UP</code> message for that site, you then enter it (along with the preceding <code>DOWN</code> message to the outages collection.</p>\n\n<p>Either way, it sounds like your complexity is currently (roughly) O(N<sup>2</sup>), but can be reduced to O(N), which is likely to give quite a large improvement. I don't think it makes a lot of sense spend much time looking at the code itself until it's clear what logic it really implements, and (especially) that the logic it implements represents a good way to solve your problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:36:03.543",
"Id": "75001",
"Score": "0",
"body": "Sorry, I was trying to abstract our system's eccentricities out of the problem as much as possible, because it can get convoluted. When I see a DOWN entry for a site, and the next entry for that site is also a DOWN, that means that the site came up at some point, and it may not have been logged for any number of reasons; as a result, this particular \"Outage\" would be invalid. The DOWN status only occurs if a site is already UP, but it can also occur if the system recording the logs reboots, at which point, it may register every single site as DOWN, then immediately as UP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:49:23.870",
"Id": "75003",
"Score": "0",
"body": "@Liesmith: In that case, the second technique I described should work (with, perhaps, a little massaging to deal with the situation where the log recording system reboots)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T17:20:25.180",
"Id": "75012",
"Score": "0",
"body": "Thanks, but if I understand correctly, wouldn't this run into issues when a single site has multiple legitimate outages in a single file? My code is trying to collect the number and duration of each outage for each site, then average the downtime each site experienced. The end result is I want to be able to show \"Site A had ten registered outages, but the average downtime was only one minute; Site B had two outages, and the average was an hour\". These are satellite communications sites, so these statistics can hopefully aid in troubleshooting RF issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T17:53:25.217",
"Id": "75021",
"Score": "0",
"body": "At least as I understand your description, no there shouldn't be a problem (though maybe I wasn't entirely clear: after you find a transition from `DOWN` to `UP`, you'd create an outage object, then repeat until the end of the file."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T07:29:37.213",
"Id": "43379",
"ParentId": "43350",
"Score": "7"
}
},
{
"body": "<p>Aside from the issues identified in @JerryCoffin's answer, I see a number of things in your code:</p>\n\n<ul>\n<li>Your naming convention seems to be <code>alllowercase</code>... it's consistent, but hard to read. VB.NET standards would call for <code>PascalCasing</code>.</li>\n<li>The procedure's name doesn't say what it's doing: <code>AvgDownTimePerSite</code> would perhaps be a nice name for an <code>IEnumerable(Of Double)</code>; good method names start with a <em>verb</em>.</li>\n<li>The method is doing too many things, which makes it harder to read and harder to maintain.</li>\n</ul>\n\n<p>I would try to break it down into multiple, small steps:</p>\n\n<ul>\n<li>The first <code>For</code> loop gives you your <code>outages</code> data. That's one thing - make that a function that returns an <code>IEnumerable(Of outage)</code>.</li>\n<li>In another function, iterate the <code>outages</code> and perform that other looping logic, return <code>sites</code>.</li>\n<li>Compute and return the <code>stats</code> (the chart's data).\n<ul>\n<li>I'm not sure I understand the <code>sorter</code> and the logic behind <code>If tml.Value > sorter(9)</code>.</li>\n</ul></li>\n<li>Create and populate a chart.</li>\n<li>Format the chart.</li>\n</ul>\n\n<p>The more <em>focused-on-a-single-task</em> a method is, the easier it is to identify the code that needs to change and tell it from the code that can remain untouched. </p>\n\n<p>With more cohesive code, you can more easily identify areas that can be improved, or rewrite parts that need to be reimplemented - the steps remain the same (e.g. \"get outages data\"), but the implementation can improve - for example you <em>might</em> want to try and see what LINQ can do for you (I do C#, I'm not even going to try LINQ in VB.NET!), to replace the <code>For</code> and <code>For Each</code> loops.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:40:23.597",
"Id": "75083",
"Score": "0",
"body": "Thanks! These are the practices I lack while trying to teach myself. Along with @JerryCoffin's suggestions, I think I may need to re-write the bulk of the program with these better practices in mind. The \"sorter\" logic is a sloppy attempt to graph only the sites with the longest outages. The \"sorter\" list contains only the average outage times, separated from their sites. I then graph every site with a larger average downtime than the 10th-longest time in the \"sorter\" list. It's awful, but I think a solution will become evident once I rework the code with your and Jerry's suggestions in mind."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:09:25.310",
"Id": "43448",
"ParentId": "43350",
"Score": "7"
}
},
{
"body": "<p>I'm not understanding everything but you might be able to change your first pass into a single for loop by keeping track of things a different way.</p>\n\n<pre><code>Dim newOutage As New outage\nDim lastDownItem As New Dictionary(Of Integer, Outage)\n\nFor Each entry In searchedlist\n If entry.status = \"Down\" Then\n newOutage = New outage\n\n newoutage.termid = entry.termid\n newoutage.popid = entry.popid\n newoutage.starttime = entry.dtg\n\n If lastDownItem.ContainsKey(entry.termid) Then\n lastDownItem(entry.termid) = newoutage\n Else\n lastDownItem.Add(entry.termid, newoutage)\n End If\n Else If entry.status = \"Up\" Then\n If lastDownItem.ContainsKey(entry.termid) Then\n newoutage = lastDownItem(entry.termid)\n lastDownItem.Remove(entry.termid)\n\n newoutage.endtime = findend.dtg\n newoutage.duration = newoutage.endtime - newoutage.starttime\n outages.Add(newoutage) \n Else\n ' Error?\n End If\n End If\nNext\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T16:22:08.117",
"Id": "45634",
"ParentId": "43350",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T23:06:43.033",
"Id": "43350",
"Score": "8",
"Tags": [
"optimization",
"strings",
"vb.net",
"hash-map"
],
"Title": "Collect and calculate average times from log, then display top 10 longest durations"
}
|
43350
|
<p>I've been reading <a href="http://www.cis.upenn.edu/~bcpierce/tapl/">Types and Programming Languages</a> and I wanted to try to implement the first language in Haskell to understand it properly</p>
<p>I have barely written any Haskell before and not used Parsec so I would grateful for any feedback on this code</p>
<p>Here are some specific points I am unsure about</p>
<ol>
<li>Is my main function sensible?</li>
<li>Can the eval function be expressed any better?</li>
<li>I'm unhappy with functionParser and ifParser. How can I code these better. In particular can the ifParser be coded in an applicative style?</li>
</ol>
<p>If there's anything else you consider odd don't hesitate to mention it</p>
<pre><code>import Control.Monad
import System.Environment
import Text.ParserCombinators.Parsec
data Term = TmTrue
| TmFalse
| TmIf Term Term Term
| TmZero
| TmSucc Term
| TmPred Term
| TmIsZero Term
| TmError
deriving Show
main :: IO[()]
main = do
args <- getArgs
forM args (\arg -> case parseArith arg of
Left e -> print e
Right term -> print $ eval term)
isNumerical :: Term -> Bool
isNumerical term = case term of
TmZero -> True
TmSucc subterm -> isNumerical subterm
TmPred subterm -> isNumerical subterm
_ -> False
eval :: Term -> Term
eval term = case term of
TmTrue -> TmTrue
TmFalse -> TmFalse
TmZero -> TmZero
TmIf term1 term2 term3 -> case eval term1 of
TmTrue -> eval term2
TmFalse -> eval term3
_ -> TmError
TmIsZero subterm -> case eval subterm of
TmZero -> TmTrue
t2 | isNumerical t2 -> TmFalse
_ -> TmError
TmPred TmZero -> TmZero
TmPred (TmSucc subterm) -> eval subterm
TmSucc subterm -> case eval subterm of
t2 | isNumerical t2 -> TmSucc t2
_ -> TmError
_ -> TmError
parseArith :: String -> Either ParseError Term
parseArith input = parse arithParser "Failed to parse arithmetic expression" input
arithParser :: GenParser Char st Term
arithParser = try( ifParser )
<|> try( succParser )
<|> try( predParser )
<|> try( isZeroParser )
<|> try( trueParser )
<|> try( falseParser )
<|> try( zeroParser )
trueParser :: GenParser Char st Term
trueParser = string "true" >> return TmTrue
falseParser :: GenParser Char st Term
falseParser = string "false" >> return TmFalse
zeroParser :: GenParser Char st Term
zeroParser = char '0' >> return TmZero
functionParser :: String -> (Term -> Term) -> GenParser Char st Term
functionParser name funcTerm = do
string $ name ++ "("
term <- arithParser
char ')'
return $ funcTerm term
succParser :: GenParser Char st Term
succParser = functionParser "succ" TmSucc
predParser :: GenParser Char st Term
predParser = functionParser "pred" TmPred
isZeroParser :: GenParser Char st Term
isZeroParser = functionParser "iszero" TmIsZero
ifParser :: GenParser Char st Term
ifParser = do
string "if"
spaces
term1 <- arithParser
spaces
string "then"
spaces
term2 <- arithParser
spaces
string "else"
spaces
term3 <- arithParser
return $ TmIf term1 term2 term3
</code></pre>
|
[] |
[
{
"body": "<p>Where you used <code>case</code> you could have used pattern matching. This yields more idiomatic code in many cases.</p>\n\n<pre><code>isNumerical :: Term -> Bool\nisNumerical TmZero = True\nisNumerical (TmSucc subterm) = isNumerical subterm\nisNumerical (TmPred subterm) = isNumerical subterm\nisNumerical _ = False\n\neval :: Term -> Term\neval TmTrue = TmTrue\neval TmFalse = TmFalse\neval TmZero = TmZero\neval (TmIf term1 term2 term3) = evalIf (eval term1) term2 term3\neval (TmIsZero subterm) = evalIsZero $ eval subterm\neval (TmPred subterm) = evalPred $ eval subterm\neval (TmSucc subterm) = evalSucc $ eval subterm\neval TmError = TmError\n\nevalIf :: Term -> Term -> Term -> Term\nevalIf TmTrue a _ = eval a\nevalIf TmFalse _ b = eval b\nevalIf _ _ _ = TmError\n\nevalIsZero :: Term -> Term\nevalIsZero TmZero = TmTrue\nevalIsZero term\n | isNumerical term = TmFalse\n | otherwise = TmError\n\nevalPred :: Term -> Term\nevalPred TmZero = TmZero\nevalPred t@(TmSucc subterm) = t\nevalPred _ = TmError\n\nevalSucc :: Term -> Term\nevalSucc term\n | isNumerical term = TmSucc term\n | otherwise = TmError\n</code></pre>\n\n<p>Note the complex terms are farmed off to their own functions. This makes testing easier. Especially as the runtime gets more complex.</p>\n\n<p>You asked about <code>main</code>'s type. If you use <code>forM_</code> you can define it as <code>main :: IO ()</code>.</p>\n\n<p>As for Applicative:</p>\n\n<pre><code>functionParser :: String -> (Term -> Term) -> GenParser Char st Term\nfunctionParser name funcTerm = funcTerm <$> (string (name ++ \"(\")\n *> arithParser\n <* char ')')\nifParser :: GenParser Char st Term\nifParser = TmIf <$> (string \"if\" *> spaces *> arithParser)\n <*> (spaces *> string \"then\" *> spaces *> arithParser)\n <*> (spaces *> string \"else\" *> spaces *> arithParser)\n</code></pre>\n\n<p>Also, the last 'try' should not be used. 'try' means to attempt a parse and do not consume the input if it failed. The last parse action is the end of the parse so there is no need to leave the input in the parser.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-26T19:45:50.300",
"Id": "79224",
"Score": "0",
"body": "This is excellent. Thanks!! If you want to see the finished code it's here http://goo.gl/tS3MoF"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-26T22:01:25.923",
"Id": "79258",
"Score": "0",
"body": "I did not have time to add this part. Consider using an error monad.type TAPLArithResult = Either String Term\n\neval :: Term -> TAPLArithResult\neval (TmIf term1 term2 term3) = do\n term1' <- eval term1\n evalIf term1' term2 term3\neval (TmIsZero subterm) = eval subterm >>= evalIsZero\neval (TmPred subterm) = eval subterm >>= evalPred\neval (TmSucc subterm) = eval subterm >>= evalSucc\n-- The next one will not be triggered unless a new value is added to Term\neval _ = Left \"unknown supported type in eval\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-26T22:01:55.430",
"Id": "79259",
"Score": "0",
"body": "Sorry for the horrible formatting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-26T22:03:15.630",
"Id": "79260",
"Score": "0",
"body": "If this were a real language, TAPLArithResult would probably be an ErrorT using Either and IO. By using the type synonym you make it easy to change your mind later."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T23:56:22.067",
"Id": "45272",
"ParentId": "43351",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "45272",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T23:16:42.553",
"Id": "43351",
"Score": "5",
"Tags": [
"beginner",
"haskell",
"parsec"
],
"Title": "Using Parsec for simple arithmetic language"
}
|
43351
|
<p>I want to write code that does backward stepwise selection using cross-validation as a criterion.</p>
<p>I have only started learning R a month ago and I have almost zero programming experience prior to that. Hence, I would appreciate any comments on the code.</p>
<p>(I understand that there are issues with the backward stepwise selection process itself.) </p>
<pre><code>rm(list=ls())
library(forecast)
library(fpp)
set.seed(1)
x1<-c(1:500)*runif(20,min=0,max=200)
x2<-c(1:500)*runif(20,min=0,max=200)
library(caret)
data(credit)
score <- credit$score
log.savings <-log(credit$savings+1)
log.income <-log(credit$income+1)
log.address<- log(credit$time.address+1)
log.employed <- log(credit$time.employed+1)
##################################
#Input
full.model<- score ~ log.savings + log.income + log.address + log.employed + x1 +x2
# 1. Start with the full model
counter=1
full <- lm(full.model)
scopevars<- attr(full$terms, "predvars") # list of model predicotrs
n <- length(full$residuals); # sample size
current_best <- full #what is the currenly the best model ? that would be our full model for now
while(T){ #process until we break the loop
best_cv <- CV(current_best)[1] #the CV of the current_best model
temp <- summary(current_best) #summary output of the current_best model
p <- dim(temp$coefficients)[1] # current model's size
rnames <- rownames(temp$coefficients) # list of terms in the current model
compare <- matrix(NA,p,1) # create a matrix to store CV information
rownames(compare) <- rnames #name the matrix
#create a loop that drops one predictor at a time and calculates the CV of the regression when that predictor is dropped
#put all the information into "compare"
#drop the variable that has the lowerst CV when it is dropped.
for (i in 2:p) {
drop_var <- rnames[i] #variable to be deleted
f <- formula(current_best) #current formula
f <- as.formula(paste(f[2], "~", paste(f[3], drop_var, sep=" - "))) # modify the formula to drop the chosen variable (by subtracting it)
new_fit <- lm(f) # fit the modified model
compare[i]<-CV(new_fit)[1]
}
remove_var <-rownames(compare)[which.min(compare)] #drop is the varibale that is associate with the lowerst CV
update_cv <- compare[which.min(compare)]
if(update_cv>best_cv) break #we should not continue if dropping a variable will not improve Cv
write(paste("--- Dropping",counter, remove_var , update_cv, "\n"), file="") # output the variables we are dropping.
f <- formula(current_best) #current formula
f <- as.formula(paste(f[2], "~", paste(f[3], remove_var , sep=" - "))); # modify the formula to drop the chosen variable (by subtracting it)
current_best <- lm(f)# we now have a new best model
counter=counter+1 #update our counter
next
} #end the while loop
print(current_best)
CV(current_best)
</code></pre>
|
[] |
[
{
"body": "<p>Your code is good. I could not find important corrections to be made. I could find only some small cosmetic improvements - nothing serious.</p>\n\n<p>For example. You do not need the <code>caret</code> package loaded for this task. You do not need to use <code>next</code> at the end of the <code>while</code> loop. It is good practice to keep your code in width of 80 characters. It improves readability a lot. See my code attached.</p>\n\n<pre><code>rm(list=ls())\ngc()\n\nlibrary(forecast)\nlibrary(fpp)\n\nset.seed(1)\nx1 <- c(1:500) * runif(20, min=0, max=200)\nx2 <- c(1:500) * runif(20, min=0, max=200)\n\ndata(credit)\nscore <- credit$score \nlog.savings <- log(credit$savings+1)\nlog.income <- log(credit$income+1)\nlog.address <- log(credit$time.address+1)\nlog.employed <- log(credit$time.employed+1)\n\n\n################################## \n\n#Input\nfull.model <- score ~ log.savings + log.income + log.address +\n log.employed + x1 +x2\n\n\n# 1. Start with the full model \ncounter <- 1L\nfull <- lm(full.model)\n\nscopevars <- attr(full$terms, \"predvars\") # list of model predicotrs\nn <- length(full$residuals) # sample size\ncurrent_best <- full #what is the currenly the best model?\n # that would be our full model for now\n\nwhile(T) { #process until we break the loop\n\n best_cv <- CV(current_best)[1] #the CV of the current_best model\n temp <- summary(current_best) #summary output of the current_best model \n p <- dim(temp$coefficients)[1] # current model's size\n\n rnames <- rownames(temp$coefficients) # list of terms in the current model\n\n compare <- matrix(NA,p,1) # create a matrix to store CV information \n rownames(compare) <- rnames #name the matrix \n\n # create a loop that drops one predictor at a time and calculates\n # the CV of the regression when that predictor is dropped \n # put all the information into \"compare\"\n # drop the variable that has the lowest CV when it is dropped.\n\n for (i in 2:p) { \n drop_var <- rnames[i] #variable to be deleted \n f <- formula(current_best) #current formula \n f <- as.formula(paste(f[2], \"~\", paste(f[3], drop_var, sep=\" - \")))\n # modify the formula to drop the chosen variable (by subtracting it)\n new_fit <- lm(f) # fit the modified model \n compare[i] <- CV(new_fit)[1]\n }\n\n remove_var <- rownames(compare)[which.min(compare)]\n # drop is the varibale that is associate with the lowest CV\n update_cv <- compare[which.min(compare)]\n\n if (update_cv > best_cv) break # we should not continue\n # if dropping a variable will not improve CV\n\n write(paste(\"--- Dropping\", counter, remove_var , update_cv, \"\\n\"), file=\"\")\n # output the variables we are dropping\n\n f <- formula(current_best) #current formula\n f <- as.formula(paste(f[2], \"~\", paste(f[3], remove_var , sep=\" - \")))\n # modify the formula to drop the chosen variable (by subtracting it)\n current_best <- lm(f) # we now have a new best model\n counter <- counter + 1L # update our counter\n} #end the while loop \n\nprint(current_best)\nCV(current_best)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T10:33:53.500",
"Id": "43847",
"ParentId": "43352",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "43847",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T23:21:44.987",
"Id": "43352",
"Score": "2",
"Tags": [
"beginner",
"r"
],
"Title": "Backwards stepwise regression code in R (using cross-validation as criteria)"
}
|
43352
|
<p>I am a relative beginner to Python and as such I've been working on little things here and there in the office that strike me as something interesting that might be fun to try and code a solution.</p>
<p>Recently, I was working with some cell phone data and decided to write a little script that would triangulate a cell phone location from ping strengths/XY locations from 3 different towers. As we only get one cell tower data returns in a exigence request anyway, this was pretty much a practice problem for me, which I would love to check the accuracy on anyway.</p>
<p>As such, I was just looking for some critical feedback on any parts of this that could be written cleaner or functionally more efficient than what i have. It works fine if all the correct values are entered for all user inputs but I am not sure how to keep things moving along if an invalid value is entered. Right now, I just exit out of the script if a invalid number is entered and the user would have to start over. I would like to be able to loop(?) back through with the correct value after a prompt of some sort.</p>
<p><strong>Part 1</strong></p>
<p>User inputs (this was going to be a tool/script to be run from someones desktop in the shell)for tower signal strengths and then standardizing those inputs. I pulled all the math off another thread <a href="https://stackoverflow.com/questions/10329877/how-to-properly-triangulate-gsm-cell-towers-to-get-a-location">here</a>.</p>
<pre><code>try:
s1=float (raw_input ("please enter signal strength number 1" + "-->" + " "))
s2=float (raw_input ("please enter signal strength number 2" + "-->" + " "))
s3=float (raw_input (" please enter signal strength number 3" + "-->" + " "))
except (EOFError,ValueError,TypeError):
oops2 = raw_input("An unusuable value was entered for the signal strength, Press ENTER and try again")
print oops2
exit()
if s1 < 0.31 or s1 > 99:
badinput = raw_input("Signal strength #1 is invalid,\
please enter a value between 0.31 - 99. Press ENTER and try again")
print badinput
exit()
if s2 < 0.31 or s2 > 99:
badinput = raw_input("Signal strength #2 is invalid, please enter a value between 0.31 - 99. Press ENTER and try again")
print badinput
exit()
if s3 < 0.31 or s3 > 99:
badinput = raw_input("Signal strength #3 is invalid, please enter a value between 0.31 - 99. Press ENTER and try again")
print badinput
exit()
print "_______________"
print ""
else:
def signal_strength(s1,s2,s3):
w1=float(s1)/(s1+s2+s3)
return w1
tower1_strength=signal_strength(s1,s2,s3)
print ("standardized signal strength for tower #1-->") + (" ") + str(tower1_strength)
def signal_strength2(s1,s2,s3):
w2=float(s2)/(s1+s2+s3)
return w2
tower2_strength=signal_strength2(s1,s2,s3)
print ("standardized signal strength for tower #2-->") + (" ") + str(tower2_strength)
def signal_strength3(s1,s2,s3):
w3=float(s3)/(s1+s2+s3)
return w3
tower3_strength=signal_strength3(s1,s2,s3)
print ("standardized signal strength for tower #3-->") + (" ") + str(tower3_strength)
print "_______________"
print ""
</code></pre>
<p><strong>Part II</strong></p>
<p>User inputs to select which three towers to choose the XY data for, which is held in a dictionary. Right now I just have three sample values in the dictionary rather than all the cell tower xy's located in my AOI.</p>
<pre><code># sample dictionary for cell carrier tower ID:X,Y Coordinates (Decimal Degrees), will use carrier ID's as key
longitude = {1:-89.928573,2:-89.813409,3:-89.825694}
latitude = {1:43.899751,2:43.913357,3:43.82814}
try:
ID1 = int(raw_input ("Carrier ID for tower #1" + "-->" + " "))
ID1x= longitude[ID1]
ID1y = latitude[ID1]
ID2 = int(raw_input ("Carrier ID for tower #2" + "-->" + " "))
ID2x = longitude[ID2]
ID2y = latitude[ID2]
ID3 = int(raw_input ("Carrier ID for tower #3" + "-->" + " "))
ID3x = longitude[ID3]
ID3y = latitude[ID3]
except Exception,e:
oops = raw_input ("An invalid Tower ID# was used,Please use the Carrier/Provider supplied identification number. Press ENTER and try again")
print oops
exit()
#Need to figure out how to loop back through the Tower ID# (and signal strength for that matter) data entry chunk after exception, if possible
print "_______________"
print ""
def user_x(tower1_strength,tower2_strength,tower3_strength,tx1,tx2,tx3):
x_location=float(tower1_strength*tx1)+(tower2_strength*tx2)+(tower3_strength*tx3)
return x_location
X_Coord=user_x(tower1_strength,tower2_strength,tower3_strength,ID1x,ID2x,ID3x)
print ("the X coordinate for the position is-->") + (" ") + str(X_Coord)
def user_y(tower1_strength,tower2_strength,tower3_strength,ty1,ty2,ty3):
y_location=float(tower1_strength*ty1)+(tower2_strength*ty2)+(tower3_strength*ty3)
return y_location
Y_Coord=user_y(tower1_strength,tower2_strength,tower3_strength,ID1y,ID2y,ID3y)
print ("the Y coordinate for the position is-->") + (" ") + str(Y_Coord)
print "_______________"
print ""
ty = raw_input ("thank you")
print ty
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T21:43:40.737",
"Id": "74858",
"Score": "0",
"body": "@Conor Yes, that is fine...I did fail to mention that I would like to convert it to an Arcpy script or tool at some point in the future (which led me to post here) but I just wanted to get the Python part of it down first...I feel more comfortable in Arcpy than straight python."
}
] |
[
{
"body": "<p><em>Let's start with part I :</em></p>\n\n<p><strong>Don't repeat yourself</strong></p>\n\n<p>You can define small functions to avoid duplicating code for all signals.</p>\n\n<p>Also, you can use the relevant data structure to store information. For instance, the strength of the signal go by 3, let's put them in the same object (let's say a list to keep things simple).</p>\n\n<p>Finally, your attempt to write function for standardisation of signals was nice. However, you end up writing and computing the same things many times. You could compute the sum just once.</p>\n\n<p><strong>Make things simple for the user</strong></p>\n\n<p>Instead of asking for 3 inputs and then exit if something goes wrong, you can check each and every input as it is provided so that the user does not go through the hassle of providing many values only to get rejected because the first was invalid. Also, you do not need to exit if the input is not valid, you can just ask again.</p>\n\n<p>Taking the following comments into account, Part I becomes :</p>\n\n<pre><code>def get_signal_strength_from_user(i):\n \"\"\" Prompt the user to get a signal strength. Loops til a valid value (float in the right range) is provided and return it.\"\"\"\n while True:\n try:\n s = float(raw_input(\"Please enter signal strength number \" + str(i) + \" --> \"))\n except (EOFError,ValueError,TypeError):\n raw_input(\"An unusuable value was entered for the signal strength, Press ENTER and try again\")\n continue\n if 0.31 <= s <= 99:\n return s # s has a valid value\n else:\n raw_input(\"Signal strength is invalid (value should be in [0.31 - 99]. Press ENTER and try again\")\n\n\n# Using variables :\ns1,s2,s3 = (get_signal_strength_from_user(1), get_signal_strength_from_user(2), get_signal_strength_from_user(3))\nprint(\"Signals strength is \", s1, s2, s3)\n\nsum_signal = s1+s2+s3\nw1,w2,w3 = s1/sum_signal, s2/sum_signal, s3/sum_signal\nprint(\"Standardized signals strength is \", w1, w2, w3)\n\n\n# Using lists :\nnb_src = 3\n\nsignals = [get_signal_strength_from_user(i+1) for i in range(nb_src)]\nprint(\"Signals strenght is \", signals)\n\nsum_signal = sum(signals)\nstandard_signals = [s/sum_signal for s in signals]\nprint(\"Standardized signals strength is \", standard_signals)\n</code></pre>\n\n<p>I've done it using lists and different variables so that you can pick whatever is easier for you.</p>\n\n<p><em>Now for part II :</em></p>\n\n<p>I don't really understand why you need to user to pick 3 towers out of 3 towers.</p>\n\n<p><strong>Correctness</strong></p>\n\n<p>Also, I'd like to point out that your algorithm will not work if the same tower (or if 2 towers at the same location - which is roughly the same) is used more than once. Indeed, localisation on a plan with relative strenght from 2 sources only gives you the direction as the mathematical property you are using is right for any point of a line.</p>\n\n<p>My feeling is that even more than that, the towers should not be aligned because this could lead to (at least) 2 distinct points in most cases.</p>\n\n<p>The fact that this does not seem obvious from the code lead me to think that maybe the maths behind are wrong too.</p>\n\n<p>Anyway, let's go back to the code.</p>\n\n<p><strong>Don't repeat yourself</strong></p>\n\n<p>It might not seem obvious because the names of the parameters are changed but you have defined the same function twice.</p>\n\n<pre><code>def user_c(tower1_strength,tower2_strength,tower3_strength,c1,c2,c3):\n c = float(tower1_strength*c1) + (tower2_strength*c2) + (tower3_strength*c3)\n return c\n</code></pre>\n\n<p>(<code>c</code> stands for coordinate here).</p>\n\n<p>Also, the conversion and the temporary variable are not useful here, the argument names do not need to be that long and the function could be renamed :</p>\n\n<pre><code>def mean(s1,s2,s3,c1,c2,c3):\n return s1*c1 + s2*c2 + s3*c3\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T10:19:45.603",
"Id": "74924",
"Score": "0",
"body": "@ josay Like i said, data from towers from an exigence request is returned from the carrier for only one tower so this was really just a practice exercise for myself in writing some code to solve a real world scenario. I will never get the chance to field test it or get the rsquared value but wanted the python practice. Thanks for the tips as i will incorporate them in a rewrite. I knew there was a way to simplify it...just wasnt experienced enough to get there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T11:53:39.683",
"Id": "74936",
"Score": "0",
"body": "@ josay....the tower xy's were to be held in a dictionary. The ones listed are just 3 of many, i just wasnt in the mood to put them all in on the chance that there was a better way to do that part of it. Like i said, i just pulled the math from another thread on triangulating cell towers, and the results when i ran the script seem ok but i will never know for sure. There would never be two cell towers at the same location owned by the same carrier so that wont be an issue, the idea would be to use the three closest towers, regardless of how distant they would be to one another or the target."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T15:26:28.883",
"Id": "76036",
"Score": "0",
"body": "@josay...I may not be reading that last part right where you substitute the parameter \"c\" for coordinate for my two parameters for the x and y coordinate. I don't think this will work, will it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T15:32:56.127",
"Id": "76040",
"Score": "0",
"body": "Well, the fact is that from a logical/mathematical point of view, you've defined the same function twice. Sure it does have different names and the parameters have a different name too but the computation itself is using the same formula. From a mathematical point of view, f(x) = x*x and g(y) = y*y for instance are just different ways to write the square function. I am not sure if I made it clear so please let me know if you have issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T18:43:44.517",
"Id": "76343",
"Score": "0",
"body": "I guess i was confused by the substitution of one value, c, for the two lat/long x and y coordinate values in my function. I haven't had time to play around with the edits you suggested but I do intend on giving them a try at some point in the future. I will keep you posted on what I find here..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T09:48:12.827",
"Id": "43389",
"ParentId": "43353",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "43389",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T21:15:57.727",
"Id": "43353",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-2.x",
"geospatial"
],
"Title": "Improving a triangulation test script"
}
|
43353
|
Maintainability refers to the nature, methods, theory and art of maximizing the ease with which an asset may be sustained, modified or enhanced throughout the duration of its expected useful life.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T00:38:14.923",
"Id": "43357",
"Score": "0",
"Tags": null,
"Title": null
}
|
43357
|
<p>I'm trying to parse a CSV file into objects. I've already got a very efficient CSV parser (SuperCSV). The problem arises when trying to create the object with the data that is being read out.</p>
<p>I've got a nested <code>foreach</code> that iterates firstly through a map (that represents a CSV row) and then through each key within the map (which represents a column for that row) to create an object.</p>
<pre><code>for(Map<String, Object> csvRow : csvRows){
Contact contact = new Contact();
contact.setContactId(nextContactId);
for(String key : csvRow.keySet())
{
contact.setDetails(key, csvRow.get(key));
contactList.addContact(contact);
}
nextContactId++;
}
</code></pre>
<p>My problem arises in that the above code takes roughly 10 seconds to run. This is with a CSV input of about 2MB, but this service has to handle a file of 200MB (at least) efficiently.
The reason I'm stuck is that the code below runs in roughly 1.6 seconds but only creates a single instance of a Contact object (which is fair enough) and I do see why this is occurring.</p>
<pre><code>Contact contact = new Contact();
for(Map<String, Object> csvRow : csvRows){
contact.setContactId(nextContactId);
for(String key : csvRow.keySet())
{
contact.setDetails(key, csvRow.get(key));
contactList.addContact(contact);
}
nextContactId++;
}
</code></pre>
<p>Obviously if I do the latter, I end up with a single instance of a Contact object at the end instead of the many thousands that I should have. However I have had code similar to the latter create and save the objects in about 1.6 seconds (using a <code>while</code> loop rather than the first <code>foreach</code>) so I know it's possible.</p>
<pre><code>while( (readCsvRow() != null) {
Contact contact = new Contact();
contact.setContactId(nextContactId);
for(String header : headers){
if(csvRow.get(header) != null)
{
contact.setDetails(header, csvRow.get(header));
contactList.addContact(contact);
}
}
nextContactId++;
}
</code></pre>
<p>Edit 1:</p>
<pre><code>@Entity
@Table(name="CONTACT")
public class Contact {
@Id
@GeneratedValue(generator = "contactSequence")
@SequenceGenerator(name = "contactSequence", sequenceName = "CONTACT_SEQ")
@Column(name="rowId")
private Long rowId;
@Column(length=255)
@NotNull
private Long contactId;
@Column(length=255)
@NotNull
private String detailKey;
@Column(length=255)
@NotNull
private String detailValue;
@Generated(value=GenerationTime.INSERT)
@Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime dateCreated;
@Generated(value=GenerationTime.ALWAYS)
@Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime dateModified;
@ManyToOne
@JoinColumn(name="contactListJoinId")
private ContactList contactList;
public void setDetails(String detailKey, Object detailValue){
this.detailKey = detailKey;
this.detailValue = (String) detailValue;
}
public Long getRowId() {
return rowId;
}
public void setRowId(Long rowId) {
this.rowId = rowId;
}
public Long getContactId() {
return contactId;
}
public void setContactId(Long contactId) {
this.contactId = contactId;
}
public String getDetailKey() {
return detailKey;
}
public void setDetailKey(String detailKey) {
this.detailKey = detailKey;
}
public String getDetailValue() {
return detailValue;
}
public void setDetailValue(String detailValue) {
this.detailValue = detailValue;
}
public LocalDateTime getDateCreated() {
return dateCreated;
}
public void setDateCreated(LocalDateTime dateCreated) {
this.dateCreated = dateCreated;
}
public LocalDateTime getDateModified() {
return dateModified;
}
public void setDateModified(LocalDateTime dateModified) {
this.dateModified = dateModified;
}
public ContactList getContactList() {
return contactList;
}
public void setContactList(ContactList contactList) {
this.contactList = contactList;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
</code></pre>
<p>SOLUTION: The answer marked as correct gave me an idea on how to fix my issue. It was entirely correct that creating a <code>Map</code> per row and passing the entire thing back to my class was causing a massive memory overhead. Basically I rewrote my CSVHelper class to allow it to only parse one row at a time and pass back the <code>Map</code> representing that row to the method. This fixed my problem instantly and I'm now reading the 2MB file in 1.6 seconds again.</p>
|
[] |
[
{
"body": "<h2>Map.Entry<....></h2>\n<p>HashMaps (Maps in general) require time to do key lookups.</p>\n<p>You can save a significant number of these by changing your inner loop:</p>\n<blockquote>\n<pre><code>for(String key : csvRow.keySet())\n{\n contact.setDetails(key, csvRow.get(key));\n contactList.addContact(contact);\n}\n</code></pre>\n</blockquote>\n<p>to be:</p>\n<pre><code>for(Map.Entry<String,Object> me : csvRow.entrySet())\n{\n contact.setDetails(me.getKey(), me.getValue());\n contactList.addContact(contact);\n}\n</code></pre>\n<p>This will save a bunch of time, but the actual amount will need to be measured.</p>\n<h2>Profile</h2>\n<p>There is little in your code that has any other performance impact other than the Contact.</p>\n<p>You need to supply that Contact's code, or alternatively profile it yourself.</p>\n<h2>Memory</h2>\n<p>OK, I have seen this before.</p>\n<p>Consider your code, it reads say 100,000 records from file.</p>\n<p>First things first, are you using RegEx/SubString to break the columns out of the CSV?</p>\n<p>If you are, <a href=\"https://codereview.stackexchange.com/a/33990/31503\">you may be hanging on to a lot more memory than you may realize</a>.</p>\n<p>Secondly, you are creating 100,000 Maps.</p>\n<p>Each Map is an object, and it creates a HashTable for the values. Each Map.Entry is an object, etc. So, with, say, 100,000 maps, and each one, with say 10 columns, is 512 bytes, it amounts to 50 MB.</p>\n<p>Your for-loop is creating all of this infrastructure in memory, and that is a slow process.</p>\n<p>The while-loop, I presume, has just a single row in memory at any one time, so the memory management is simpler, faster, smaller, and generally works.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T03:18:48.600",
"Id": "74876",
"Score": "0",
"body": "I've just tried that. Any performance increase was negligible. I'm sure that the issue is around where I'm creating a new Contact object. Thanks for your suggestion though, I'll leave it in the codebase, every little bit helps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T03:25:42.003",
"Id": "74881",
"Score": "0",
"body": "Contact is just a POJO with a one-to-many relationship to a ContactList object. But I posted the code above"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T03:40:41.267",
"Id": "74885",
"Score": "0",
"body": "I'm using a 3rd party library called SuperCSV to parse the CSV file, and it is pretty efficient. I know that the bulk of the processing time is spent in the creation of the Contact object. What would you suggest, if I'm trying to reduce the memory footprint of my Map's"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T03:15:34.047",
"Id": "43364",
"ParentId": "43361",
"Score": "8"
}
},
{
"body": "<ol>\n<li><p>I guess you are running out of memory, try increase the heap size. For example, if it's 512MB... then, storing 200 MB data with the object overheads could use it all.</p></li>\n<li><p>You could also check how much time spent your JVM with garbage collection. <a href=\"https://en.wikipedia.org/wiki/VisualVM\" rel=\"nofollow\">VisualVM is good for that</a>, it's bundled with Oracle's JDK.</p></li>\n<li><blockquote>\n<pre><code>for(Map<String, Object> csvRow : csvRows){\n Contact contact = new Contact();\n contact.setContactId(nextContactId);\n for(String key : csvRow.keySet())\n {\n contact.setDetails(key, csvRow.get(key));\n contactList.addContact(contact);\n }\n nextContactId++;\n}\n</code></pre>\n</blockquote>\n\n<p>Are you sure that adding the same <code>contact</code> instance to the list as many time as many columns a row has is deliberate here? Shouldn't <code>addContact</code> be after the for loop?</p>\n\n<p>If <code>contactList</code> is a <code>java.util.List</code> it will store one <code>Contact</code> object for each row but the <code>Contant</code> object's <code>detailKey</code> and <code>detailValue</code> will contain only data of the last column.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T03:46:53.003",
"Id": "74887",
"Score": "0",
"body": "1. If I place the `new` and the `setContactId` inside the 2nd for loop I do indeed overflow the heap. But its just a time issue at the moment. \n2. This is all being tested in unit tests, so I have `currentTimeMillis()` calls measuring how long things are taking. \n3. Each Contact object represents a separate piece of contact information, and it all has to go into the ContactList. These disparate pieces of information can be made whole by a wrapper object I have. ContactList should store a Contact object for each Key in the map."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T03:40:17.087",
"Id": "43366",
"ParentId": "43361",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "43364",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T03:04:17.123",
"Id": "43361",
"Score": "8",
"Tags": [
"java",
"performance",
"parsing",
"memory-management"
],
"Title": "Object Creation during loops"
}
|
43361
|
<p>My first crack at clojure... if you have time to provide input, I'd appreciate it. I'm as much interested in style as proper usage. I'm just getting started.</p>
<p>The task to start with an vector of N zeros, and then "scramble" it by: Select 2 items in the vector. If one is less than 4, and the other is greater than -4, increment one and decrement the other -- so that the sum of the vector remains the same.</p>
<ul>
<li><p>am I abusing let?</p></li>
<li><p>this generates a sequence of vectors, and I take the last one. Is there a better way to iterate and get the last result?</p></li>
<li><p>what tricks that I've missed?</p></li>
<li><p>this is just a small sample ;) but what community standards and practices have I missed?</p></li>
</ul>
<p><strong>code</strong></p>
<pre><code>(defn level [c] (let [n+ (rand-int (count c))
n- (rand-int (count c))
v+ (inc (nth c n+))
v- (dec (nth c n-))
go (and (not= n+ n-) (< v+ 4) (> v- -4))
]
(if go (assoc (assoc c n+ v+) n- v-) c)
))
(defn rseq [n]
(let [first (vec (repeat n 0))]
(last (take (* n 2) (iterate level first)))))
(rseq 16)
(deftest rseq-sum-equals-2
(let [actual (rseq 16)]
(is (= 0 (apply + actual)))))
(run-tests 'ursound.core)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T04:52:51.063",
"Id": "74889",
"Score": "0",
"body": "There's no code yet, you mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T04:56:46.157",
"Id": "74890",
"Score": "0",
"body": "lol hrm ok first question... how do I get stackexchange to not collapse my code? ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-06T12:36:02.337",
"Id": "92243",
"Score": "1",
"body": "You have a couple of off-by-one errors. To comply with your description, `go` should be bound to `(and (not= n+ n-) (<= v+ 4) (>= v- -4))`."
}
] |
[
{
"body": "<p>I am also relatively new to Clojure, but here are my first thoughts:</p>\n\n<ul>\n<li><p>I like that you work with a vector, because random access of vectors with <em>(nth)</em> and <em>assoc</em> is faster. I also like your naming. thanks for providing a deftest, but please, user a proper inlining.</p></li>\n<li><p><em>(assoc)</em>'s do not need to be nested: <code>(assoc (assoc c n+ v+) n- v-)</code> is the same as <code>(assoc c n+ v+ n- v-)</code>.</p></li>\n<li><p><code>(last (take n x))</code> can be written as <code>(nth x n)</code>.</p></li>\n<li><p>Warning: you use the name <em>'first</em> in yout <em>(let)</em>, but this name is already defined in <em>clojure.core</em>.</p></li>\n<li><p>For a style guide, please see <a href=\"https://github.com/bbatsov/clojure-style-guide\" rel=\"nofollow\">https://github.com/bbatsov/clojure-style-guide</a></p></li>\n</ul>\n\n<p>That is all for now, and I hope you found some advice useful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:59:03.560",
"Id": "76168",
"Score": "0",
"body": "Excellent! Those are all good points! Thank you for the reference to the style guide... I'm sort of drifting into clojure sideways ;) but right away I'm seeing lots of good tips in there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-06T12:31:03.367",
"Id": "92242",
"Score": "1",
"body": "@RobY ... and write `(c ` *x* `)` instead of `(nth c ` *x* `)`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T22:48:28.647",
"Id": "44007",
"ParentId": "43368",
"Score": "1"
}
},
{
"body": "<p>Sorry to necro-bump this, but there's a key thing I noticed about your code that hinders readablity. </p>\n\n<p>You aren't \"abusing\" <code>let</code>, I think that would be difficult, but your bindings are definitely misaligned. Ideally, all of your bindings should line up. Many IDE's enforce/highly recommend this, and it has the added benefit of allowing tools to manage parentheses for you based on indentation (so code kind of resembles Python). In your case, your code would become:</p>\n\n<pre><code>(defn level [c] (let [n+ (rand-int (count c))\n n- (rand-int (count c))\n v+ (inc (nth c n+))\n v- (dec (nth c n-))\n go (and (not= n+ n-) (< v+ 4) (> v- -4))\n ]\n</code></pre>\n\n<p>One other thing I noticed is, contrary to most other \"language families\", in Lisps, braces are recommended to be on the same line instead of taking up a line to themselves. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-24T21:38:46.217",
"Id": "129231",
"ParentId": "43368",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "44007",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T04:51:33.903",
"Id": "43368",
"Score": "1",
"Tags": [
"beginner",
"clojure"
],
"Title": "Scamble a vector, preserving the sum"
}
|
43368
|
<p>I've created this thin wrapper class for a socket project that I'm working on. Can someone review my class and give me some points on if I'm on right track?</p>
<pre><code>#include <iostream>
#include <WinSock2.h>
const int MAX_RECV_LEN = 8096;
const int MAX_MSG_LEN= 1024;
const int PORT_NUM = 1200;
class Sokect
{
private:
Sokect(){}
void setSocketID(int socketFb){socketID = socketFb;}
int portNum;
int socketID;
int blockFlag;
int bindFlag;
public:
Sokect(int);
~Sokect(){
closesocket(socketID);
}
void setReuseAddr(int);
void getReuseAddr(int);
void setKeepAlive(int);
void getKeepAlive(int);
void setLingerOnOff(bool);
void getLingerOnOff(bool);
void setLingerSecond(int);
void getLingerSecond(int);
void setSocketBlockFlag(int);
void getSocketBlockFlag(int);
//size of send & Receive Buffer
void setSendBufferSize(int);
void getSendBufferSize(int);
void setReceiveBuffferSize(int);
void getReceiveBuffferSize(int);
int getSocketID() {return socketID;}
int getPortNum() {return portNum;}
friend ostream& operator<<(ostream&,mySocket&);
//get systems error
void detectErrorOpenWinSocket(int*,string&);
void detectErrorSetSocketOption(int*,string&);
void detectErrorGetSocketOption(int*,string&);
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T02:00:11.453",
"Id": "75136",
"Score": "0",
"body": "You may want to look at my versions. It may give you some ideas: [part1](http://codereview.stackexchange.com/questions/38402/stream-that-opens-an-http-get-and-then-acts-like-a-normal-c-istream) [part2](http://codereview.stackexchange.com/questions/38455/http-stream-part-2-a-stream-that-opens-an-http-get-and-then-acts-like-a-normal-c)"
}
] |
[
{
"body": "<p>There are at least a few things I think I'd do differently, at any rate.</p>\n\n<pre><code>const int MAX_RECV_LEN = 8096;\nconst int MAX_MSG_LEN= 1024;\nconst int PORT_NUM = 1200;\n</code></pre>\n\n<p>The ALL_CAPS convention was originally invented for macros. At least as far as I can tell, it was originally for function-like macros, to give a subtle warning that it might evaluate its argument more than once, so you needed to be careful about exactly how and where you applied it (especially to arguments that might have side effects).</p>\n\n<p>It really doesn't make sense for a situation like this, so I'd prefer to avoid it. Regardless of the exact names you choose, it's probably better to avoid putting these variables in the global namespace any way. I'd consider wrapping the entire class in a namespace instead.</p>\n\n<pre><code>private:\n Sokect(){}\n</code></pre>\n\n<p>Assuming your compiler is recent enough to support it, I'd prefer to use <code>=delete;</code> to ensure that a ctor can't be accessed, rather than defining it as private.</p>\n\n<p>[ ... ]</p>\n\n<pre><code>void setReuseAddr(int);\nvoid getReuseAddr(int);\nvoid setKeepAlive(int);\nvoid getKeepAlive(int);\nvoid setLingerOnOff(bool);\nvoid getLingerOnOff(bool);\nvoid setLingerSecond(int);\nvoid getLingerSecond(int);\nvoid setSocketBlockFlag(int);\nvoid getSocketBlockFlag(int);\n</code></pre>\n\n<p>I think rather than embedding these directly into the socket itself, I'd create a separate <code>socket_options</code> (or something similar) struct to hold them. This would allow (for example) storing an entire set of options together, so you can set all the options for a particular socket at once.</p>\n\n<pre><code>//size of send & Receive Buffer\nvoid setSendBufferSize(int);\nvoid getSendBufferSize(int);\nvoid setReceiveBuffferSize(int);\nvoid getReceiveBuffferSize(int);\n</code></pre>\n\n<p>Likewise, I'd probably create a small class just to handle the buffering. Then the socket class could just contain two buffer instances, one for receiving and one for sending.</p>\n\n<pre><code>//get systems error \nvoid detectErrorOpenWinSocket(int*,string&);\nvoid detectErrorSetSocketOption(int*,string&);\nvoid detectErrorGetSocketOption(int*,string&);\n</code></pre>\n\n<p>These seem to me like they merit at least a little more explanation of what they're actually supposed to be/do.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T06:02:12.443",
"Id": "43374",
"ParentId": "43369",
"Score": "8"
}
},
{
"body": "<ol>\n<li><p>The class name is misspelled - should be <code>Socket</code> rather than <code>Sokect</code></p></li>\n<li><p>Consider putting your constant definitions as static members into the class like this:</p>\n\n<pre><code>class Socket\n{\n private:\n static const int MAX_RECV_LEN = 8096;\n static const int MAX_MSG_LEN = 1024;\n static const int PORT_NUM = 1200;\n ....\n}\n</code></pre></li>\n<li><p>You haven't shown the actual implementation but my suspicion is that <code>PORT_NUM</code> should probably be renamed to <code>DEFAULT_PORT_NUM</code> - I assume the user will be able configure the port.</p></li>\n<li><p>I'm not sure what the point is to make the default constructor private in your case. You have declared a constructor which takes an int as parameter - this is enough to prevent the compiler from generating the default constructor in the first place so you can just leave it out (assuming your intention is to prevent a user of your class calling the default constructor).</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T07:03:26.433",
"Id": "43376",
"ParentId": "43369",
"Score": "8"
}
},
{
"body": "<p>It's not clear what the <code>int</code> parameter is/means, which is passed to the constructor: is it a port number, a socket handle, or what?</p>\n\n<p>The class seems to be missing some useful functions: including listen, accept, connect, send, and recv.</p>\n\n<p>I'm not sure why you have 3 detectError methods: I'd get they're all wrappers around the same WSAGetLastError API.</p>\n\n<p>I don't see how <code>void getSendBufferSize(int)</code> can get the size: the <code>int</code> needs to be the return code, or a reference parameter; and perhaps it should be <code>size_t</code> not <code>int</code>.</p>\n\n<p>Maybe your 'set option' functions should return bool if they can fail; if they don't return bool then how is the user to know whether they should call the detectError method?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T02:05:42.167",
"Id": "75138",
"Score": "1",
"body": "Hopefully the wrapper would never expose anything so low level. The point would be to make using it error free not to simply provider a wrapper around a set of C functions and then expose them directly in the interface."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T08:40:57.870",
"Id": "43385",
"ParentId": "43369",
"Score": "4"
}
},
{
"body": "<p>Your public single-argument constructor <code>Sokect(int);</code> absolutely must be marked <code>explicit</code> unless you wish to allow passing int values where <code>Sokect</code> objects are expected. See some of <a href=\"https://stackoverflow.com/a/121163\">these</a> <a href=\"https://stackoverflow.com/a/121216\">answers</a> for more detail on how this works.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:59:46.360",
"Id": "75296",
"Score": "0",
"body": "My apologies. I was thinking backwards (your point is perfectly valid). You are correct. Though Spy would need to take Socket by const reference in your comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:42:59.797",
"Id": "75311",
"Score": "0",
"body": "@LokiAstari No worries. Good point on the missing `const` from my earlier `void Frob(const Sokect&)` accepting `Frob(5)` example."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T13:12:50.690",
"Id": "43402",
"ParentId": "43369",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "43374",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T05:00:47.303",
"Id": "43369",
"Score": "7",
"Tags": [
"c++",
"c++11",
"windows"
],
"Title": "Socket wrapper class"
}
|
43369
|
<p>This seems a bit redundant to me, but I'm not sure of how else I might be able to write this. Normally I'd use a <code>switch</code> statement, but I don't think that'll work here. I realize I could also do this in a <code>for</code> loop, but the main heart of the question is what's inside the loop itself. "<code>arr</code>" is an array, just in case it's not obvious.</p>
<pre><code>var i = 0, x = arr.length;
while (i < x) {
if (typeof arr[i] === 'object' && !Array.isArray(arr[i])) {
attr = arr[i];
}
else if (typeof arr[i] === 'string') {
text = arr[i];
}
else if (typeof arr[i] === 'object' && Array.isArray(arr[i])) {
child = arr[i];
}
i++;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T13:05:42.350",
"Id": "74941",
"Score": "2",
"body": "`Array.isArray` will also work with non-objects. You don't need to check if it's an object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:11:40.583",
"Id": "75069",
"Score": "0",
"body": "I'd remove the `x` variable altogether; since `arr.length` is short and clear enough by itself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:47:39.353",
"Id": "75095",
"Score": "0",
"body": "@Prinzhorn Ah yes, good point. Duly noted and update in my dev environment. Thank you!\n\n@Zar If I don't cache `arr.length` to `l`, doesn't it have to calculate `arr.length` on each iteration?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:33:54.277",
"Id": "75249",
"Score": "0",
"body": "What should happen if `typeof arr[i]` is neither `string` nor `object`? (For instance, numbers, booleans, and `undefined`.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T21:26:26.870",
"Id": "75343",
"Score": "0",
"body": "@Zack The function that this loop is in serves a very specific purpose, and in my particular case there won't be any numbers or booleans. So if the values aren't a `string` or `object` they are just ignored, which is my intention."
}
] |
[
{
"body": "<p>I think at the very least I'd rearrange the cases to make the dichotomy between <code>Array.isArray</code> and <code>!Array.isArray</code> more direct and apparent:</p>\n\n<pre><code>while (i < x) {\n if (typeof arr[i] === 'string') {\n text = arr[i];\n }\n else if (typeof arr[i] === 'object') {\n if (Array.isArray(arr[i])) {\n child = arr[i];\n }\n else {\n attr = arr[i];\n }\n }\n i++;\n}\n</code></pre>\n\n<p>That's not really a lot shorter but I think it makes the intent rather more clear (at least assuming I've divined the real intent correctly).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T06:11:33.360",
"Id": "43375",
"ParentId": "43371",
"Score": "15"
}
},
{
"body": "<p>Along with @jerrycoffin and @RobertoBonvallet's <code>Array.isArray</code> suggestions, I would write this as a <code>for</code> loop 10 times out of 10 (this is the conventional for loop case afterall). I tend to use <code>for</code> loops whenever I'm iterating every item of a single collection and a <code>while</code> loop for any other purpose (but either can always be written as the other so w/e floats your boat).</p>\n\n<p>I would also probably cache the result of <code>typeof arr[i]</code> and if I were using <code>arr[i]</code> anywhere else in the loop I would probably make a variable for it as well. I usually consider using a <code>switch</code> if I use 3 or more <code>typeof item</code> so if you extend further that may be something to consider</p>\n\n<p>Also <code>x</code> is a cryptic name for a loop control variable. Use <code>l</code>, <code>len</code> or <code>length</code> - don't worry about variable name length as you'll usually end up minifying your code if you're writing anything substantial.</p>\n\n<p>That said</p>\n\n<pre><code>var type, current;\n\nfor (var i = 0, length = arr.length; i < length; i++) {\n current = arr[i];\n type = typeof current;\n if (type === 'string') {\n text = current;\n }\n else if(Array.isArray(current)) { // @RobertoBonvallet's observation\n child = current;\n }\n else if (type === 'object') {\n attr = current;}\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:03:49.403",
"Id": "75274",
"Score": "0",
"body": "Confusingly enough, in JavaScript, defining `i` and `length` inside the `for` loop construct doesn't limit their scope, as demonstrated by [this fiddle](http://jsfiddle.net/ej882/)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:16:15.790",
"Id": "75275",
"Score": "0",
"body": "Javascript has function scope"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:24:59.353",
"Id": "75276",
"Score": "0",
"body": "That's irrelevant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:30:39.497",
"Id": "75279",
"Score": "0",
"body": "All that fiddle is pointing out is that JS has function level scope"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:35:49.923",
"Id": "75285",
"Score": "0",
"body": "What it points out is that `i` defined inside the for loop's construct is also defined outside of the loop, which is not case in at least some other programming languages, such as C."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:41:36.940",
"Id": "75287",
"Score": "0",
"body": "Ya that is part of the reason for the ol' [crockford paradigm of declaring all local variables at the top of the function](http://javascript.crockford.com/code.html)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T07:14:05.527",
"Id": "43377",
"ParentId": "43371",
"Score": "12"
}
},
{
"body": "<p>+1 to <em>@Jerry</em> and three minor notes:</p>\n\n<ol>\n<li><blockquote>\n<pre><code>var i = 0, x = arr.length;\n</code></pre>\n</blockquote>\n\n<p>I'd put the variable declarations to separate lines. From <em>Code Complete 2nd Edition</em>, p759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom, instead\n of top to bottom and left to right. When you’re looking for a specific line of code,\n your eye should be able to follow the left margin of the code. It shouldn’t have to\n dip into each and every line just because a single line might contain two statements.</p>\n</blockquote></li>\n<li><p>I would use longer variable names than <code>x</code>. 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>So, <code>arrayLength</code> would be a readable name here.</p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Avoid Mental Mapping</em>, p25)</p></li>\n<li><p>I'd have started the refactoring with creating a local variable for the result of <code>typeof arr[i] === 'object'</code>. It's used twice.</p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>; <em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em>)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:53:57.860",
"Id": "75098",
"Score": "2",
"body": "You are completely correct, thanks for pointing out the above. FWIW, I *do* adhere to the coding guidlines as noted in point #1, but for the sake of this example I was just trying to keep it to the least number of lines since it was already longer than it needed to be. As for point #3, I actually removed the 2nd instance of `Array.isArray()` since it wasn't needed, per @Prinzhorn's suggestion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T16:51:06.747",
"Id": "75272",
"Score": "0",
"body": "I disagree with using `arrayLength` for the length, I think it's unnecessarily long. I'd go for `l`, `len`, or `length`, unless the code is more complex."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T07:19:36.390",
"Id": "43378",
"ParentId": "43371",
"Score": "11"
}
},
{
"body": "<p>It seems to me a switch statement <strong>would</strong> work here.</p>\n\n<pre><code>for (i=0;arr[i];i++) {\n switch(typeof arr[i]{\n case 'string':\n text = arr[i];\n break;\n case 'object':\n if (Array.isArray(arr[i])) {\n child = arr[i];\n } else {\n attr = arr[i];\n }\n break;\n }\n}\n</code></pre>\n\n<p>This construct of for initializes i once, checks if there is an element arr[i] in the while section and sets the incrementation.</p>\n\n<p>Switch checks the type of arr[i] only once. This seems to me to be succinct and will probably prove to be faster.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T13:43:56.107",
"Id": "74950",
"Score": "1",
"body": "You have some syntax errors"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T23:11:41.700",
"Id": "75105",
"Score": "0",
"body": "Despite the syntax errors, I still get the meaning. I had actually thought of that last night after making this post. ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T12:03:03.000",
"Id": "43397",
"ParentId": "43371",
"Score": "1"
}
},
{
"body": "<p>I would do it this way:</p>\n\n<pre><code>arr.forEach(function (item) {\n if (Array.isArray(item)) {\n attr = item;\n }\n else if (typeof item === 'object') {\n child = item;\n }\n else if (typeof item === 'string') {\n text = item;\n }\n});\n</code></pre>\n\n<p>By using <code>arr.forEach</code> there is no need to subscript (<code>arr[i]</code>). You just get passed the <code>item</code>.</p>\n\n<p><code>Array.isArray</code> works just fine with anything you pass it, so there is no need to check before if the thing is or isn't an object.</p>\n\n<p>By checking “arrayness” first, then you know for sure that if <code>typeof item === 'object'</code> it is not an array. It simplifies the logic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T23:02:42.753",
"Id": "75100",
"Score": "0",
"body": "Excellent suggestion. I actually had no idea that this even existed. However, since it's only compatible with IE9+, I'm afraid I can't use it. It needs to be compatible with older version as well (which I admittedly did not mention in my post). Upvoting anyway for its usefulness. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T14:27:53.280",
"Id": "43406",
"ParentId": "43371",
"Score": "15"
}
},
{
"body": "<p>By using the prototype name string instead of the typeof function we can get a more accurate check of the variable type. For instance:</p>\n\n<pre><code>variable[\"__proto__\"][\"constructor\"][\"name\"]\n\nvar Array = []; //returns \"Array\"\nvar Object = {}; //returns \"Object\"\nvar Array = new Array(); // returns \"Array\"\n</code></pre>\n\n<p>With this we no longer have to have an additional logical statement to check if our our objects are arrays in disguise or actually an object.</p>\n\n<p>Using a reverse while loop means that array.length doesn't have to be evaluated each increment and reduces character wastage. It does make the logic more confusing to write in controlled sequential cases, but in this case is fine</p>\n\n<pre><code>var i=arr.length;\nwhile(i--){switch(arr[i].__proto__.constructor.name;){\n case'Object':{attr = arr[i]; break;}\n case'String':{text = arr[i]; break;}\n case'Array':{child = arr[i]; break;}\n default:{break;}}}\n</code></pre>\n\n<p>or a more readable version:</p>\n\n<pre><code>var myArray = [150,\"Entry\",{\"x\":15,\"y\":26}]; //input array\nvar index = myArray.length; //evaluate the length of the array\n\nwhile(index--) //decrement the index while it's greater than 0\n{\n var type = myArray[index][\"__proto__\"][\"constructor\"][\"name\"];//what type is this variable\n switch(type)\n {\n case:'Object': //if object\n {\n attr = myArray[index]; //set attribute to field\n break;\n }\n case:'String': //if string\n {\n text = myArray[index]; //set text to field\n break;\n }\n case:'Array': //if array\n {\n child = myArray[index]; //set child to field\n break;\n }\n default:\n {\n console.log(\"Error, entry does not match requested types\");\n break;\n }\n }\n}\n</code></pre>\n\n<p>Using a quasi-referance object array to start with would be a lot more obvious way to do this though, it seems a rather backwards way to extract relevant information from an unsorted array than to just pick items out of your choosing.</p>\n\n<pre><code>var myArray = \n{\n \"values\":[150,160,170],\n \"name\":\"entry\",\n \"coord\":{\"x\":15,\"y\":26}\n}\n\n//then\n\nattr = myArray[\"coord\"]; \ntext = myArray[\"name\"]; \nchild = myArray[\"values\"];\n\n//or\n\nattr = myArray.coord; \ntext = myArray.name; \nchild = myArray.values; \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T00:43:29.113",
"Id": "75122",
"Score": "0",
"body": "If I do a reverse while loop using `(index--)`, won't it exclude the `0` index?? I kinda need that. ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T01:53:31.957",
"Id": "75135",
"Score": "0",
"body": "@DondeEstaMiCulo nope see http://stackoverflow.com/questions/6867876/javascript-i-vs-i"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T02:23:01.370",
"Id": "75140",
"Score": "0",
"body": "@megawac Oh yeah, thanks for pointing that out. I was thinking about `--index`. D'oh!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T09:23:46.930",
"Id": "75176",
"Score": "1",
"body": "it performs the decrement before the function, which means it'll perform index[0] and you dont have to subtract one from the array length. Quite handy really :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T14:29:20.100",
"Id": "43407",
"ParentId": "43371",
"Score": "2"
}
},
{
"body": "<p>I'm going to suggest something a bit different.</p>\n\n<p>Lets step back and look at what you are trying to do. You seem to want to extract the elements of the array according to their type. </p>\n\n<p>Now your code will only find the last element in the array that is of the given type. If there are two strings in the array then the first one will be ignored. This may of course be what you want, but it doesn't provide for a good reusable solution. Sometimes you may want the first in the list, other times all of them. </p>\n\n<p>I would suggest creating a reusable groupBy function</p>\n\n<pre><code>function groupBy(arr, fn) {\n return arr.reduce(function(result, item) {\n var group = fn(item);\n result[group] = result[group] || [];\n result[group].push(item);\n return result;\n }, {});\n}\n</code></pre>\n\n<p>Then you can use this function to group your array by type :</p>\n\n<pre><code>function getType(item) {\n var type = typeof item,\n isArray = Array.isArray(item);\n\n return (type === 'object' && !isArray) ? 'obj' :\n (type === 'string') ? 'string' : \n (type === 'object' && isArray) ? 'array' :\n 'none';\n}\n\nvar result = groupBy(arr, getType); \n</code></pre>\n\n<p>You can then access the types you need through the object. If you want the first item in the list of that particular type :</p>\n\n<pre><code>text = result.string && result.string[0];\nchild = result.array && result.array[0];\nattr = result.obj && result.obj[0];\n</code></pre>\n\n<p>If you want the last item :</p>\n\n<pre><code>text = result.string && result.string[result.string.length - 1];\nchild = result.array && result.array[result.child.length - 1];\nattr = result.obj && result.obj[result.attr.length - 1];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:28:35.713",
"Id": "75077",
"Score": "1",
"body": "I was going to write something along these lines when I saw your answer. The fact that the code as written only returns the \"last of each type\" really bothered me too. This seems like a big improvement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T00:37:26.663",
"Id": "75120",
"Score": "0",
"body": "The reason why I wrote it the way I did is because the format of the array (in my case) will always be in order of: `[attr, text, child]`, and will only include, at max, 3 values. The loop only serves one purpose inside a function which pulls out some other information from the original array that is passed as a parameter. I realize that without any context it's hard to know what my intentions are. +1 for the excellent advice none-the-less."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T16:02:38.853",
"Id": "75262",
"Score": "0",
"body": "@DondeEstaMiCulo I see, couldn't you just do attr=arr[0]; text=arr[1]; child=arr[2] in that case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T21:31:14.717",
"Id": "75345",
"Score": "0",
"body": "@MongusPong If the array was always `[object, string, array]` then yes, but the values are optional, so it could be something like `[object, array]` or `[string]` or `[array]`, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T22:52:33.747",
"Id": "75352",
"Score": "0",
"body": "@DondeEstaMiCulo It does feel quite fragile to be relying on the type to identify the value. Supposing a change came along that meant there were two different strings in the array. What does the code that populates this array do? Is there no way that could create an object with the data already correctly identified rather than an array?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T23:56:21.700",
"Id": "75355",
"Score": "0",
"body": "@MongusPong I agree, without any context it does feel a bit fragile indeed. This loop is inside a function that is called recursively. It's part of a custom templating system that I'm writing for myself. [This post](http://stackoverflow.com/questions/22120175/create-html-with-javascript-from-a-multidimensional-array) might shed a little light on what I'm doing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T00:00:26.963",
"Id": "75356",
"Score": "0",
"body": "I should mention that I am removing the first string in the arrays (in my other post) since it's required and determines the type of element to be created. The rest of the values are optional and are handled by the loop on this post."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T14:49:34.717",
"Id": "43410",
"ParentId": "43371",
"Score": "7"
}
},
{
"body": "<p>I have to say, everyone really had some great suggestions. So I ended up using something from everyone's answers... I think for <strong>my</strong> particular situation, the following loop is best:</p>\n\n<pre><code>// arr = [{'id':12}, \"Test\", [{'id':42}, \"Another Test\"]];\n\nvar attr,\n child,\n i,\n len = arr.length,\n text;\n\nfor (i = 0; i < len; i++) {\n var curVal = arr[i];\n\n switch (typeof curVal) {\n case 'string':\n text = curVal;\n break;\n case 'object':\n if (Array.isArray(curVal)) {\n child = curVal;\n }\n else {\n attr = curVal;\n }\n break;\n }\n}\n</code></pre>\n\n<p><br>Just a couple notes:</p>\n\n<ul>\n<li>I almost <em>always</em> use <code>for</code> loops, especially since I almost <em>always</em> forget to increment my counter in a <code>while</code> loop, lol.</li>\n<li>I ended up using a <code>switch</code> statement because I might add a boolean to the array, and I think it makes it easier to read (IMHO).</li>\n<li>I upvoted everyone whose suggestions I used. Thanks for all of your input!</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T01:19:03.910",
"Id": "43473",
"ParentId": "43371",
"Score": "0"
}
},
{
"body": "<p>Here is how I would do it. I'm trading a little efficiency for a lot of readability.</p>\n\n<pre><code>for (var i = 0; i < arr.length; i++) {\n var thisItem = arr[i];\n var thisType = typeof thisItem;\n if (thisType == 'string') { text = thisItem; }\n if (thisType == 'object' && Array.isArray(thisItem)) { child = thisItem; }\n if (thisType == 'object' && !Array.isArray(thisItem)) { attr = thisItem; }\n}\n</code></pre>\n\n<p>It would be more efficient to declare variables outside the loop. Also, one if, else if conditional statement would evaluate less conditional statements as opposed to listing them out individually like I did here. Also, declaring thisItem and thisType in the loop is not needed but does help clarify what is going on and makes the following statements more readable. In my opinion, this approach is more succinct and much easier to read than the other solutions. Also, a for loop makes more sense here than a while loop.</p>\n\n<p>However, after some thought I agree with @bhiqa that an object should be used in this situation. In most cases if you're using <code>typeof</code> then your code can be written better. But I also realize that's not what the op asked for.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:55:00.940",
"Id": "75294",
"Score": "2",
"body": "Welcome to Code Review! Could you explain exactly what you're trading in term of efficiency ? In my opinion, a review should explain why we are changing the op code, so that the op can choose the \"better\" option or learn a new concept by your answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T20:16:11.983",
"Id": "75335",
"Score": "0",
"body": "I wrote a 'more succinct' solution. It would be more efficient to declare variables outside the loop. Also, one `if, else if` conditional statement would evaluate less conditional statements as opposed to listing them out individually like I did here. Also, declaring `thisItem` and `thisType` in the loop is not needed but does help clarify what is going on and makes the following statements more readable. In my opinion, this approach is more succinct and much easier to read than the other solutions. Also, a for loop makes more sense here than a while loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T20:31:42.243",
"Id": "75336",
"Score": "1",
"body": "I don't disagree with you at all, and you should add this to your answer since this is exactly what I wanted from you : a good explanation of what you were doing! At Code Review we want to the review the code of the op to make him better, not just the code! Adding explanation is a good way to help the OP and clarify why he could choose your solution over an other one!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:25:25.520",
"Id": "43528",
"ParentId": "43371",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "43473",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T05:42:16.267",
"Id": "43371",
"Score": "10",
"Tags": [
"javascript"
],
"Title": "Is there a more succinct way of writing this simple JavaScript loop?"
}
|
43371
|
<p>Can I make this program that extracts text data from a file (size in MBs) even better performance-wise? I need to reduce the execution time.</p>
<pre><code>import java.io.*;
public class ReadData {
public static void main(String[] args) {
FileReader input = null;
BufferedReader br = null;
try {
input = new FileReader("C:/Projects/Test/HPCamDrv.log");
br = new BufferedReader(input);
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
input.close();
br.close();
}
catch (IOException x) {
x.printStackTrace();
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T06:46:49.227",
"Id": "74896",
"Score": "5",
"body": "The majority of the time it will probably spend in printing it to stdout - which is very likely the console in most cases unless you have some redirection going on. If that is not what you are actually doing then you should post the real code you are using. Because this program you have written is not all that useful as it stands. On most *nix systems you have `cat` and on Windows `type` which do exactly the same thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T08:25:53.643",
"Id": "74905",
"Score": "0",
"body": "You may try to increase the buffer-size. Depending on your file-system that may reduce the IO-overhead. (You use the default, which seams to be 8192 bytes)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T10:10:19.810",
"Id": "74923",
"Score": "0",
"body": "What file-size are you expecting?"
}
] |
[
{
"body": "<p>It's a pretty small and straight-forward program and not really much to improve on. ChrisWue also brings up the good point that printing to <code>stdout</code> for every line is costly but if you need to print it to <code>stdout</code> there's not much to do about it.</p>\n\n<p>But one thing you can actually do is implement Java's <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow\">try-with resources</a> which will ensure your resources are closed at the end of the statement, so you can get rid of all your <code>.close()</code> calls and your <code>finally</code> block.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T07:47:15.187",
"Id": "43381",
"ParentId": "43372",
"Score": "3"
}
},
{
"body": "<p>Your question asks about data extraction, but the code actually just prints the file to <code>System.out</code> with possible <kbd>Carriage return</kbd>/<kbd>Newline</kbd> translation. Frankly, you haven't asked a very good question (it doesn't do what you claim, and it lacks specific details about how poor your performance is or how you measured it), but there is some code to be reviewed anyway.</p>\n\n<p>Your exception handling is wrong. What happens if <code>new FileReader(…)</code> throws an exception?</p>\n\n<p>There is some hidden work being done that you may not be aware of.</p>\n\n<ul>\n<li>As I alluded to above, <code>BufferedReader.readLine()</code> accepts either <kbd>Carriage return</kbd>, <kbd>Newline</kbd>, or some combination of the two as a line termination marker. Then, <a href=\"http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#println%28java.lang.String%29\" rel=\"nofollow noreferrer\"><code>System.out.println()</code></a> will print each line, using the Java default line termination character. If you don't need this normalization of the line termination, don't call <code>.readLine()</code>. Just repeatedly read to a <code>char[]</code> buffer and write it out. Then you also wouldn't be creating a <code>String</code> for each line.</li>\n<li><a href=\"http://docs.oracle.com/javase/7/docs/api/java/io/FileReader.html\" rel=\"nofollow noreferrer\"><code>FileReader</code></a> might also be doing some extraneous work. It creates an <code>InputStreamReader</code> that translates bytes into chars using the system default character encoding. Assuming you don't care about such transcoding, you could work with <code>byte[]</code> arrays instead.</li>\n<li>If you just want to funnel data from a source to a sink as efficiently as possible, <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#copy%28java.nio.file.Path,%20java.io.OutputStream%29\" rel=\"nofollow noreferrer\"><code>java.nio.file.Files.copy()</code></a> is probably your best bet.</li>\n</ul>\n\n<p>That said, the code you wrote is pretty standard and is fast enough for most purposes, and you usually don't need to resort to the hacks I mentioned above. If you're seeing a performance problem, it's probably because your <code>System.out</code> is attached to your console, and console output is slow. (Sometimes <a href=\"https://stackoverflow.com/q/21947452/1157100\">surprisingly so</a>!) Try redirecting your <code>System.out</code> to <code>/dev/null</code> or <code>NUL:</code> to measure your input and output bottlenecks separately.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T08:50:08.037",
"Id": "43386",
"ParentId": "43372",
"Score": "3"
}
},
{
"body": "<p>If you must do <code>System.out.println()</code> then build everything in a <code>new StringBuilder</code> first so that your console io comes way down. Really, you need to decide what it is you're trying to actually accomplish. This code snippet looks like a homework assignment not a real attempt at a professional solution.</p>\n\n<p>To also balance with memory considerations, use a modulo counter with reset on the buffer</p>\n\n<pre><code>try {\n int count = 0;\n StringBuilder builder = new StringBuilder();\n input = new FileReader(\"C:/Projects/Test/HPCamDrv.log\");\n br = new BufferedReader(input);\n String str;\n\n while ((str = br.readLine()) != null) {\n builder.append(str);\n if(count++ % 100) {\n System.out.println(builder);\n builder = new StringBuilder(); // or builder.setLength(0);\n }\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T17:20:03.230",
"Id": "43424",
"ParentId": "43372",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T05:49:40.010",
"Id": "43372",
"Score": "4",
"Tags": [
"java",
"performance",
"io"
],
"Title": "Extracting text data from a file"
}
|
43372
|
<p>Goal: Create a combination of emails based from inputted first name, last name, middle name, and a domain. Add in common separators. Then I'll check which one is correct with the rapportive API. This is the first part of the bigger script.</p>
<p>If you are given the <code>string</code> variables</p>
<pre><code>{fn}
{ln}
{fi}
{li}
{mi}
{mn}
</code></pre>
<p>How would you create the following?</p>
<pre><code>{fn}
{ln}
{fn}{ln}
{fn}.{ln}
{fi}{ln}
{fi}.{ln}
{fn}{li}
{fn}.{li}
{fi}{li}
{fi}.{li}
{ln}{fn}
{ln}.{fn}
{ln}{fi}
{ln}.{fi}
{li}{fn}
{li}.{fn}
{li}{fi}
{li}.{fi}
{fi}{mi}{ln}
{fi}{mi}.{ln}
{fn}{mi}{ln}
{fn}.{mi}.{ln}
{fn}{mn}{ln}
{fn}.{mn}.{ln}
{fn}-{ln}
{fi}-{ln}
{fn}-{li}
{fi}-{li}
{ln}-{fn}
{ln}-{fi}
{li}-{fn}
{li}-{fi}
{fi}{mi}-{ln}
{fn}-{mi}-{ln}
{fn}-{mn}-{ln}
{fn}_{ln}
{fi}_{ln}
{fn}_{li}
{fi}_{li}
{ln}_{fn}
{ln}_{fi}
{li}_{fn}
{li}_{fi}
{fi}{mi}_{ln}
{fn}_{mi}_{ln}
{fn}_{mn}_{ln}
</code></pre>
<p>at the moment I am solving it by creating an <code>array</code> for each permutation </p>
<pre><code>fi_perms = [fi].product ['_' + li,
'_' + ln,
'-' +li,
'-' ln,
'.' + li,
'.' + ln,
li,
ln,
mi '_' ln,
mi '-' ln,
mi + '.' + ln,
mi + ln]
fn_perms = [fn].product ['_' + li,
'_' + ln,
'_' + mi '_' + ln,
'_' + mn '_' + ln,
'-' + li,
'-' + ln,
'-' + mi + '-' + ln,
'-' + mn + '-' ln,
'.' + li,
'.' + ln,
'.' + mi '.' +ln,
'.' + mn '.' ln,
li,
ln,
mi + ln,
ln,
mi + ln,
mn + ln]
li_perms = [li].product ['_' + fi,
'_' + fn,
'-' + fi,
'-' + fn,
'.' + fi,
'.' + fn,
fi,
fn]
ln_perms = [ln].product [ln,
'_' + fi,
'_' + fn,
'-' + fi,
'-' + fn,
'.' + fi,
'.' + fn,
fi,
fn]
</code></pre>
<p>because I will be using it later by adding it to another array like so</p>
<pre><code>perms = li_perms + ln_perms + fi_perms + fn_perms
permutations = []
perms.count.times do |i|
perms.each do |perm|
permutations[i] = perm.join
end
end
permutations[0] = ['fn.mn.ln']
</code></pre>
<p>Is there a better of doing this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T09:12:24.700",
"Id": "74914",
"Score": "1",
"body": "Is there any pattern in the expected permutations?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T10:32:39.407",
"Id": "74925",
"Score": "0",
"body": "shouldn't the second `{fn}{mi}{ln}` be `{fn}.{mi}{ln}`? and is the order required in that way exactly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T17:38:36.487",
"Id": "75018",
"Score": "0",
"body": "@Vogel612 it does not have to be exact."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T17:59:42.903",
"Id": "75026",
"Score": "4",
"body": "Wild guess here — first name, last name, first initial, last initial, middle initial, middle name? What are you _really_ trying to accomplish, and why don't you ask that instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:23:20.117",
"Id": "75033",
"Score": "1",
"body": "@200_success Create a combination of emails based from inputted first name, last name, middle name, and a domain. Add in common separators. Then I'll check which one is correct with the rapportive API. This is the first part of the bigger script."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T04:06:53.503",
"Id": "75532",
"Score": "0",
"body": "This question is completely clear given his last comment, and should be re-opened."
}
] |
[
{
"body": "<p>Since your list is not \"all permutation\", but is painstakingly built by hand, I would not suggest using array's <code>permutation</code> API or something like that, but keep the curated mode you are using.</p>\n\n<p>I would suggest building it in a more readable way. In your way of <code>[fi].product[...]</code> it is very hard to follow which permutation exists, and which doesn't. The first list you show is more readable, and if you name your atoms correctly (<code>first_name</code> instead of <code>fn</code>), it makes it trivial to understand what you are trying to do. I would suggest building your permutation table as a string like this:</p>\n\n<pre><code>name_permutations = <<PERMS\n{last_initial}{first_name}\n{last_initial}.{first_name}\n{last_initial}{first_initial}\n{last_initial}.{first_initial}\n{first_initial}{middle_initial}{last_name}\n{first_initial}{middle_initial}.{last_name}\n{first_name}{middle_initial}{last_name}\n{first_name}.{middle_initial}.{last_name}\n{first_name}{middle_name}{last_name}\n{first_name}.{middle_name}.{last_name}\n{first_name}-{last_name}\n{first_initial}-{last_name}\n{first_name}-{last_initial}\n{first_initial}-{last_initial}\n{last_name}-{first_name}\n{last_name}-{first_initial}\n{last_initial}-{first_name}\n{last_initial}-{first_initial}\n...\nPERMS\n</code></pre>\n\n<p>And then use substitutions to get all permutations:</p>\n\n<pre><code>name_permutations.gsub('{first_name}', first_name)\n .gsub('{last_name}', last_name)\n .gsub('{middle_name}', middle_name)\n .gsub('{first_initial}', first_initial)\n .gsub('{middle_initial}', middle_initial)\n .gsub('{last_initial}', last_initial)\n .split($/)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T06:55:57.160",
"Id": "75723",
"Score": "0",
"body": "I like this approach for the question posed, although I think the all possible permutations of names, initials, and separators is a more interesting problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T07:29:56.113",
"Id": "75725",
"Score": "1",
"body": "@Jonah - For that you could `(1..9).map{ |i| [fi,fn,mi,mn,li,ln,'.','-','_'].permutations(i).map(&:join) }.flatten` (http://www.ruby-doc.org/core-2.1.1/Array.html#method-i-permutation)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T14:34:17.547",
"Id": "75764",
"Score": "0",
"body": "Good point that's clever"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T03:35:53.387",
"Id": "75965",
"Score": "0",
"body": "@UriAgassi just a minor error that `permutations` should be singular `permutation`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:21:14.857",
"Id": "43748",
"ParentId": "43373",
"Score": "3"
}
},
{
"body": "<p>Edit: I've made some changes to try to improve the readability of my answer.</p>\n\n<p>You could just create a few simple helper methods. Here's an example, based on the assumption that ordering is not important. Rather than the usual approach of presenting the code and then showing how it is used, I have reversed those steps, as the code is so simple that most readers will be able to glean it merely from its application.</p>\n\n<p>There are two helper methods, <code>gen</code> and <code>middle_with_seps</code>, The variables <code>fn</code>, <code>mn</code> and <code>ln</code> refer to \"first name\", \"middle name\" and \"last name\". The first, middle and last initials are: <code>fi = fn[0]</code>, <code>mi = mn[0]</code> and <code>li = ln[0]</code>. The constants should be self-explanatory. (The application of the code is best appreciated when one of <a href=\"https://archive.org/details/Wild_Bill_Hickok\" rel=\"nofollow\">these</a> is playing in the background.) </p>\n\n<p><strong>Application</strong></p>\n\n<pre><code>fn, mn, ln = 'Wild', 'Bill', 'Hickok'\n\ngen([fn, fi], DASH_USCORE , [ln, li] ) +\ngen([ln, li], DASH_USCORE , [fn, fi] ) +\ngen(li , DOT , fn ) +\ngen(li , NOSPACE_DOT , fi ) +\ngen(fn , middle_with_seps(mi, DASH_USCORE + NOSPACE_DOT), ln ) +\ngen(fn , middle_with_seps(mn, DASH_USCORE + NOSPACE_DOT), ln ) +\ngen(fi , middle_with_seps(mi, DASH_USCORE + NOSPACE) , ln ) +\ngen(fi , middle_with_seps(mi+'.', NOSPACE) , ln )\n\n#=> [\"Wild_Hickok\", \"Wild_H\", \"Wild-Hickok\", \"Wild-H\",\n# \"W_Hickok\", \"W_H\", \"W-Hickok\", \"W-H\",\n# \"Hickok_Wild\", \"Hickok_W\", \"Hickok-Wild\", \"Hickok-W\",\n# \"H_Wild\", \"H_W\", \"H-Wild\", \"H-W\",\n# \"H.Wild\", \"HW\", \"H.W\",\n# \"Wild_B_Hickok\", \"Wild-B-Hickok\", \"WildBHickok\", \"Wild.B.Hickok\",\n# \"Wild_Bill_Hickok\", \"Wild-Bill-Hickok\",\"WildBillHickok\",\"Wild.Bill.Hickok\",\n# \"W_B_Hickok\", \"W-B-Hickok\", \"WBHickok\",\n# \"WB.Hickok\"] \n</code></pre>\n\n<p><strong>Code</strong></p>\n\n<pre><code>NOSPACE = ['']\nDOT = ['.']\nNOSPACE_DOT = NOSPACE + DOT\nDASH_USCORE = ['-', '_']\n\nfi, mi, li = fn[0], mn[0], ln[0]\n\ndef combine_strings(s1, s2, s3) \"#{s1}#{s2}#{s3}\" end\n\ndef gen(left_strings, seps, right_strings)\n left_strings = [left_strings].flatten\n seps = [seps].flatten\n right_strings = [right_strings].flatten\n left_strings.each_with_object([]) { |l,a| seps.each { |sep|\n right_strings.each { |r| a << combine_strings(l, sep, r) } } }\nend\n\ndef middle_with_seps(m, seps)\n seps.each_with_object([]) { |s,a| a << combine_strings(s, m, s) } \nend\n</code></pre>\n\n<p><strong>Explanation</strong></p>\n\n<p><code>gen()</code>'s arguments are as follows:</p>\n\n<ul>\n<li><code>left_strings</code> : an array of strings for the left end of the string</li>\n<li><code>seps</code> : an array of separators (e.g., '', '.', '-', etc.)</li>\n<li><code>right_strings</code>: an array of strings for the right end of the string</li>\n</ul>\n\n<p>If <code>left_strings</code>, <code>seps</code> or <code>right_strings</code> is entered as a string, rather than an array of strings, it is converted to an array containing itself. <code>gen</code> constructs an array of strings, one for each combination of strings taken from <code>left_strings</code>, <code>seps</code> and <code>right_strings</code>.</p>\n\n<p><code>middle_with_seps</code>'s arguments are as follows:</p>\n\n<ul>\n<li><code>m</code> is the middle name or initial</li>\n<li><code>seps</code> is the same as for the method <code>gen</code></li>\n</ul>\n\n<p><code>middle_with_seps</code> creates an array of separators that is passed as the argument <code>seps</code> in <code>gen()</code> when the middle name or initial is to be included. Each element of that array is the (string) value of <code>m</code> bracketed by a separator (except in one case where the initial <code>'B'</code> is converted to <code>'B.'</code> (<code>'WB.Hickok'</code>). For example,</p>\n\n<pre><code>middle_with_seps(mi, DASH_USCORE + NOSPACE) #=> [\"_B_\", \"-B-\", \"B\"]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T07:08:57.987",
"Id": "77209",
"Score": "0",
"body": "Why are you giving such unreadable names to your variables and functions? Your code is very hard to read, and you need to tell us the `la` is an array for the left end of the string, instead of calling it `left_end_strings` or something more meaningful - this _is_ code-review, after all..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T18:54:42.517",
"Id": "77261",
"Score": "0",
"body": "@Uri, there was a method to my madness, even if I have miscalculated, as I appear to have done (for the author of code is usually not the best one to judge its readability). My intent was for the lines beginning `gen([fn, fi], ['_', '-']...` to tell the reader at a glance what the two helpers did. That wouldn't have worked if I had `generate_combinations([first_name, last_name], ['_', '-']...` as lines would have wrapped or required horizontal scrolling, defeating the purpose. I've made some changes to my answer. I welcome suggestions for further improvement. Thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T00:32:08.923",
"Id": "44481",
"ParentId": "43373",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "43748",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T05:54:26.753",
"Id": "43373",
"Score": "8",
"Tags": [
"ruby",
"strings",
"array",
"combinatorics"
],
"Title": "Generate permutations with symbols"
}
|
43373
|
<p>I would very much appreciate a general review of my PHP code which grabs information from a mySQL database and also inserts some information into the database.</p>
<p><strong>Overview :</strong></p>
<ol>
<li><p>Users go to <strong><em>/main.php</em></strong> and answer math questions. The 20 math questions are pulled from the database. The answers are pulled at the same time but they are not inserted into the html at this point.</p></li>
<li><p>User answers math questions. If they leave any blank or it doesn't validate as a number they will receive an error with PHP.</p></li>
<li><p>Once they entered all numbers and the token validation passes, I insert their answers into a row in my database for record. I also include the IP address and the cookie currently, but will likely add options for names at a later date. </p></li>
<li><p>After the insert into database I redirect them to <strong><em>results.php</em></strong> where I echo their answers using the <strong>$_SESSION</strong> vars I saved earlier, and they can than match up their answers with the correct answers.</p></li>
</ol>
<p>So would just like you to point out anything I'm doing that's dumb, stupid, incorrect, or just plain insane. As well as any other advice you have.</p>
<p>Lastly, and pretty importantly, is there any better and/or shorter way I can write my <strong>$addToPlayersAnswers</strong> statement? It's pretty long.</p>
<p><img src="https://i.stack.imgur.com/dzWof.jpg" alt="Example"></p>
<hr>
<p><strong>main.php</strong> <em>(where user answers the questions and then submits his/her answers)</em></p>
<pre><code><?php
session_start();
require '../abovepublic/file.php'; // just contains sql password, username, etc for $connect... it's above/outside the public html folder, is that good?
require 'someFunctionsAndStuff.php';
$requiredInputFields = ['token'];
for ($i = 1; $i < 21; $i += 1) {
array_push($requiredInputFields, 'qora'.$i);
}
if (!empty($_POST)) {
if (allFieldsFilled($requiredInputFields)) {
if ($_SESSION['token'] === $_POST['token']) {
if (veryifyAllIntegers()) {
$iii = getUserIp();
$iiii = session_id();
// here I'm saving all the post vars as session so I can echo them on the
// redirect to the new page
for ($yty = 1; $yty < 21; $yty += 1) {
$_SESSION['qora'.$yty] = $_POST['qora'.$yty];
}
// here I'm inserting all the user's answers into the database
$addToPlayersAnswers = "INSERT INTO PlayersAnswers(Cookie, IP, Answer1, Answer2, Answer3, Answer4, Answer5, Answer6, Answer7, Answer8, Answer9, Answer10, Answer11, Answer12, Answer13, Answer14, Answer15, Answer16, Answer17, Answer18, Answer19, Answer20) VALUES ('$iiii','$iii',".$_POST['qora1'].",".$_POST['qora2'].",".$_POST['qora3'].",".$_POST['qora4'].",".$_POST['qora5'].",".$_POST['qora6'].",".$_POST['qora7'].",".$_POST['qora8'].",".$_POST['qora9'].",".$_POST['qora10'].",".$_POST['qora11'].",".$_POST['qora12'].",".$_POST['qora13'].",".$_POST['qora14'].",".$_POST['qora15'].",".$_POST['qora16'].",".$_POST['qora17'].",".$_POST['qora18'].",".$_POST['qora19'].",".$_POST['qora20'].")";
$QRYPlayersAnswers = mysqli_query($connect, $addToPlayersAnswers);
header('Location: http://www.example.com/resultspage.php');
exit;
}
}
else {
echo 'error 00045';
}
}
}
$token = crypt(microtime(true), '$5$rounds=1275$KJEJIOjslje82323ljsK234d$');
$_SESSION['token'] = $token;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Math Game</title>
</head>
<body>
<form method="POST" name="theform">
<table>
<thead><tr><th>Questions</th><th>Your Answers</th><th>Correct?</th></tr></thead>
<tbody>
<?php HTMLform($theQuestions); ?>
</tbody>
</table>
<input name="token" type="hidden" value="<?php echo htmlspecialchars($token); ?>">
<input type="submit" value="DONE!" />
</form>
</body>
</html>
</code></pre>
<p><strong>results.php</strong> <em>(where user is redirected after they filled out the answers and form validation is correct)</em></p>
<pre><code><?php
session_start();
require '../abovepublic/file.php';
require 'someFunctionsAndStuff.php';
function HTMLformCompleted($theQuestions, $theAnswers) {
$i = 1;
foreach ($theQuestions as $theindex => $singlequestion) {
echo '<tr><td><label for="qora' . $i . '">' . $singlequestion . '</label></td><td><input name="qora' . $i . '" id="qora' . $i . '" type="text" value="'.$_SESSION["qora".$i].'"></td><td class="qorac qora' . $i . '">' . $theAnswers[$theindex] . '</td></tr>';
$i += 1;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Math Game</title>
</head>
<body>
<form>
<table>
<thead><tr><th>Questions</th><th>Your Answers</th><th>Correct?</th></tr></thead>
<tbody>
<?php HTMLformCompleted($theQuestions, $theAnswers); ?>
</tbody>
</table>
</form>
</body>
</html>
</code></pre>
<p><strong>someFunctionsAndStuff.php</strong> (<em>includes some functions and stuff so it doesn't clutter up other files even more</em>)</p>
<pre><code><?php
$theQuestions = array();
$theAnswers = array();
$STMTquestions = 'SELECT Question, Answer FROM QUESTIONS WHERE Number<21';
$QRYquestions = mysqli_query($connect, $STMTquestions);
while ($getQuestions = mysqli_fetch_array($QRYquestions, MYSQLI_ASSOC)) {
array_push($theQuestions, $getQuestions['Question']);
array_push($theAnswers, $getQuestions['Answer']);
}
function HTMLform($theQuestions) {
$i = 1;
foreach ($theQuestions as $singlequestion) {
echo '<tr><td><label for="qora' . $i . '">' . $singlequestion . '</label></td><td><input name="qora' . $i . '" id="qora' . $i . '" type="text"></td><td class="qorac qora' . $i . '"></td></tr>';
$i += 1;
}
}
function verifyAllIntegers() {
$displayError = false;
for($i = 1; $i < 21; $i += 1) {
$_POST['qora'.$i] = filter_var($_POST['qora'.$i], FILTER_SANITIZE_NUMBER_INT);
if (!filter_var($_POST['qora'.$i], FILTER_VALIDATE_INT)) {
$displayError = true;
}
}
if ($displayError) {
echo 'All answers must be valid numbers';
return false;
}
else {
return true;
}
}
function allFieldsFilled($requiredInputFields) {
$displayError = false;
foreach($requiredInputFields as $field) {
if (strlen(trim($_POST[$field])) < 1) {
$displayError = true;
}
}
if ($displayError) {
echo "All questions must be answered";
return false;
}
else {
return true;
}
}
function getUserIp() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$userip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$userip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
$userip = $_SERVER['REMOTE_ADDR'];
}
return $userip;
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>Starting from the top…</p>\n\n<p>Common <strong>idioms for repeating a loop</strong> 20 times are:</p>\n\n<pre><code>for ($i = 0; $i < 20; $i++) {\n # Do something\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for ($i = 1; $i <= 20; $i++) {\n # Do something\n}\n</code></pre>\n\n<p>What you wrote, with 21, is something I'd consider weird and jarring. (The same comment applies to your SQL query — you should write <code><= 20</code> instead.)</p>\n\n<hr>\n\n<p><code>allFieldsFilled()</code> has a <strong>side-effect</strong> of displaying an error message. The side-effect in itself is a bad idea, but the fact that you call <code>allFieldsFilled()</code> before the HTML output even start means that you'll generate malformed HTML. It seems like you made your own trap and walked right into it.</p>\n\n<p>Same goes for <code>verifyAllIntegers()</code>.</p>\n\n<hr>\n\n<p><code>$iii</code> and <code>$iiii</code> are <strong>poor variable names</strong>.</p>\n\n<hr>\n\n<p>Your <strong>table design</strong>, with one column for each of the 20 answers, is poor. As it is, the table is already unacceptably wide. What happens if you later want to change the program to ask 50 questions? That would necessitate a schema alteration. If you've ever worked in a company, you'll know that such operations are dreaded by developers and database administrators alike.</p>\n\n<p>A reasonable schema might look something like this:</p>\n\n<pre><code>CREATE TABLE Quiz\n( id INTEGER\n, questionNumber INTEGER NOT NULL\n, questionText VARCHAR(32) NOT NULL\n, answerText NUMERIC NOT NULL\n, PRIMARY KEY (id, questionNumber)\n);\n\nCREATE TABLE QuizAdministration\n( id INTEGER\n, quizId SERIAL PRIMARY KEY\n, username VARCHAR(32) NOT NULL\n, cookie VARCHAR(32) NOT NULL\n, ip DECIMAL(39,0) NOT NULL\n, time TIMESTAMP NOT NULL\n, FOREIGN KEY (quizId) REFERENCES Quiz (id)\n);\n\nCREATE TABLE PlayerAnswers\n( quizAdministrationId INTEGER NOT NULL\n, questionNumber INTEGER NOT NULL\n, answer NUMERIC\n, FOREIGN KEY (quizAdministrationId) REFERENCES QuizAdministration (id)\n);\n</code></pre>\n\n<p>Each time a player submits a quiz, insert one row into the <code>QuizAdministration</code> table and 20 dependent rows into <code>PlayerAnswers</code>.</p>\n\n<hr>\n\n<p>Why are <code>HTMLform()</code> and <code>HTMLformCompleted()</code> defined in different places? They are very similar to each other. Similar enough that you might want to <strong>merge them into one function</strong> that works in two modes.</p>\n\n<p>Composing the HTML for table rows using string concatenation makes me nervous about <strong>HTML injection attacks</strong>. Do you need to call <code>htmlentities()</code> to escape the question and answer text or not? If not, then you need to write a comment justifying why such escaping is not necessary.</p>\n\n<hr>\n\n<p>Having <strong>global variables</strong> <code>$theQuestions</code> and <code>$theAnswers</code> <strong>defined via inclusion</strong> of <code>someFunctionsAndStuff.php</code> is surprising. Instead, the included file should define a function that returns those data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T10:54:02.857",
"Id": "74927",
"Score": "0",
"body": "No, creating a new table each time a person takes a quiz would be even worse than what you have now. I'll add more detail to the answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T10:23:59.197",
"Id": "43391",
"ParentId": "43387",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "43391",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T09:28:38.817",
"Id": "43387",
"Score": "5",
"Tags": [
"beginner",
"php5",
"mysqli"
],
"Title": "Arithmetic quiz using PHP5 and mySQLi"
}
|
43387
|
<p>I noticed, that accelerometer and gyrometer sensor data tend to have problems. The gyrometer is not very precise and the accelerometer is getting problems with vibrations. I built a quadrocopter (to be honest more then one). My first one had a poor frame and the motors (very big ones) were vibrating a lot, because the fix-plates were flexible. </p>
<p>So I was thinking about a software solution to compensate all the built-problems. I used an approach similiar to neural networks in which (sigmoid or other) transfer functions are used to anneal to a solution. </p>
<p>For quadcopters it is easy. The position to hold is normally always the straight/horizontal (equilibrium) one (if no rc input interfering). In this position the accelerometer shouldn't ideally appear much acceleration and give out values close to pitch=0 and roll=0. So I decided that my gyrometer stats, should anneal the faster to the accelerometer values, the closer it is to equilibrium position. In other scenarios I rely more to the gyrometer values (strong vibration or strong g-forces), which means the annealing rate goes down massivly.</p>
<p>I tested this approach and I think it is working for me. The attitude is stored in a Vector3f and contains the fused values of the gyrometer and the accelerometer. The raw sensor readings can be filtered previously of course before they get fused like here (high/low path for gyro/accelerometer). </p>
<p>I built a very poor model which is vibrating like hell at some degree of throttle, but it is stabilizing itself without flipping or crashs. Just the motors are sometimes upregulated, which results in increasing the height. At the moment I built already better models, but I still think about how to make it better. I mean there are a lot of filter-implementations out there, but I think that e.g. the Kalman filter wouldn't be able to compensate for problems like very strong vibrations and the complementary filter would be a total desaster. Maybe this is even helpful for someone. </p>
<p>In this example I used an annealing rate of 20. To calculate the absolute attitude from the gyrometer you have to keep in mind the angular velocity. This is why I used a timer. The attitude based on the accelermoter can be calculated and filtered easily by known methods. </p>
<pre><code>/*
* Fuses two sensor values together by annealing angle_1 to angle_2
* in every time step by a given rate value.
*/
inline float smaller_float(float value, float bias) {
return value < bias ? value : bias;
}
inline float activ_float(float x, float force_mod = 20.f){
float val = (180.f - smaller_float(abs(force_mod * x), 179.9f) ) / 180.f;
return val / sqrt(1 + pow(val, 2));
}
inline float anneal_float(float angle_cor, float angle_fix, uint32_t time, float rate) {
return angle_cor += wrap180_float(angle_fix-angle_cor)*((float)time/1000.f)*rate;
}
// All sensor readouts works with absolute attitude in degrees:
void Device::update_inertial() {
m_pInert->update();
// Update sensor data
read_gyro();
read_accel();
// Compensate yaw drift a bit with the help of the compass
uint32_t time = m_iTimer != 0 ? m_pHAL->scheduler->millis() - m_iTimer : INERTIAL_TIMEOUT;
m_iTimer = m_pHAL->scheduler->millis();
// Calculate absolute attitude from relative gyrometer changes
m_vAttitude.x += m_vGyro.x * (float)time/1000.f; // Pitch
m_vAttitude.x = wrap180_float(m_vAttitude.x);
m_vAttitude.y += m_vGyro.y * (float)time/1000.f; // Roll
m_vAttitude.y = wrap180_float(m_vAttitude.y);
m_vAttitude.z += m_vGyro.z * (float)time/1000.f; // Yaw
m_vAttitude.z = wrap180_float(m_vAttitude.z);
// Calculate absolute attitude from relative gyrometer changes
m_vAttitude.x = anneal_float(m_vAttitude.x, m_vAccel.x, time, activ_float(m_vAccel.x, 20.f) );
m_vAttitude.y = anneal_float(m_vAttitude.y, m_vAccel.y, time, activ_float(m_vAccel.y, 20.f) );
}
</code></pre>
<p>Edit: This is my slightly modified version</p>
<pre><code>inline float pow2_f(float fVal) {
return fVal * fVal;
}
inline float wrap180_f(float x) {
return x < -180.f ? (x + 360.f) : (x > 180.f ? (x - 360.f) : x);
}
/*
* This function changes the function parameter (for performance reasons)
*/
inline Vector3f wrap180_V3f(Vector3f &vec) {
vec.x = wrap180_f(vec.x);
vec.y = wrap180_f(vec.y);
vec.z = wrap180_f(vec.z);
return vec;
}
inline float sigm_f(float x, float mod = 20.f){
float val = (180.f - smaller_f(abs(mod * x), 179.9f) ) / 180.f;
return val / sqrt(1 + pow2_f(val) );
}
/*
* Fuses two sensor values together by annealing angle_fuse to angle_ref
* mod: Determines the slope (decay) of the sigmoid activation function
* rate: Determines how fast the annealing takes place
*/
inline Vector3f anneal_V3f( Vector3f &angle_fuse,
const Vector3f &angle_ref, float time, float mod, float rate) {
float fR = rate * time;
angle_fuse.x += (angle_ref.x-angle_fuse.x) * fR * sigm_f(angle_ref.x, mod);
angle_fuse.y += (angle_ref.y-angle_fuse.y) * fR * sigm_f(angle_ref.y, mod);
angle_fuse.z += (angle_ref.z-angle_fuse.z) * fR * sigm_f(angle_ref.z, mod);
angle_fuse = wrap180_V3f(angle_fuse);
return angle_fuse;
}
void Device::update_inertial() {
m_pInert->update();
// Update sensor data
read_gyro();
read_accel();
// Calculate time (in s) passed
float time_s = time_elapsed_s();
// Calculate attitude from relative gyrometer changes
m_vAttitude += m_vGyro * time_s;
// For yaw changes the compass could be used as reference,
// otherwise take the gyrometer
if(COMPASS_FOR_YAW) {
m_vAccel.z = -read_comp(0, 0);
} else {
m_vAccel.z = m_vAttitude.z;
}
// Calculate absolute attitude from relative gyrometer changes
m_vAttitude = anneal_V3f(m_vAttitude, m_vAccel, time_s, 20.f, 5.f);
}
</code></pre>
|
[] |
[
{
"body": "<p>A few notes:</p>\n\n<pre><code>inline float smaller_float(float value, float bias) {\n return value < bias ? value : bias;\n}\n</code></pre>\n\n<p>This seems intended to do exactly the same thing as <code>std::min</code> in the standard library. You're probably better off using the standard version.</p>\n\n<pre><code>inline float activ_float(float x, float force_mod = 20.f){\n float val = (180.f - smaller_float(abs(force_mod * x), 179.9f) ) / 180.f;\n return val / sqrt(1 + pow(val, 2));\n}\n</code></pre>\n\n<p>I'm not sure about the name you've used here, and specifically why you'd use <code>activ</code> instead of <code>active</code>. Obviously, you'd want to incorporate the previous change, and use <code>std::min</code> here. Along with that, I'd at least consider <code>val * val</code> rather than <code>pow(val, 2)</code>. <code>pow</code> is good for arbitrary exponents, but for a fixed exponent of 2 can waste a fair amount of time, and doesn't (at least IMO) improve readability at all.</p>\n\n<p>[ ... ]</p>\n\n<pre><code>// Compensate yaw drift a bit with the help of the compass\nuint32_t time = m_iTimer != 0 ? m_pHAL->scheduler->millis() - m_iTimer : INERTIAL_TIMEOUT;\nm_iTimer = m_pHAL->scheduler->millis();\n</code></pre>\n\n<p>I think I'd prefer to move most of this into a function, so this came out something like:</p>\n\n<pre><code>uint32_t time = delta_time();\n</code></pre>\n\n<p>I also question the use of <code>uint32_t</code> here. Do you <em>really</em> need the result to be exactly 32 bits, or would <code>uint_least32_t</code> or <code>uint_fast32_t</code> really express your intent better?</p>\n\n<pre><code> // Calculate absolute attitude from relative gyrometer changes\n m_vAttitude.x += m_vGyro.x * (float)time/1000.f; // Pitch\n m_vAttitude.x = wrap180_float(m_vAttitude.x);\n\n m_vAttitude.y += m_vGyro.y * (float)time/1000.f; // Roll\n m_vAttitude.y = wrap180_float(m_vAttitude.y);\n\n m_vAttitude.z += m_vGyro.z * (float)time/1000.f; // Yaw\n m_vAttitude.z = wrap180_float(m_vAttitude.z);\n</code></pre>\n\n<p>I think I'd move this repeated code into a function, so this would come out something like:</p>\n\n<pre><code>float millis = time / 1000.f;\nm_vAttitude.x = foo(m_vGyro.x, millis);\nm_vAttitude.y = foo(m_vGyro.y, millis);\nv_vAttitude.z = foo(m_vGyro.z, millis);\n</code></pre>\n\n<p>...and probably move <em>that</em> all into a function as well, so the top-level call was something like:</p>\n\n<pre><code>m_vAttitude = foo(m_vGyro, time);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:58:00.060",
"Id": "75331",
"Score": "0",
"body": "The tip with \"uint_fast32_t\", .. is really interesting!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T17:46:04.420",
"Id": "43425",
"ParentId": "43393",
"Score": "6"
}
},
{
"body": "<p>In addition to what Jerry Coffin said, I would suggest renaming <code>active_float</code> and <code>anneal_float</code> to <code>active</code> and <code>anneal</code>. Since you are using C++, you don't need to have different names for the same function taking different types, you can provide overloads when needed. Generally, you provide different names only in C, and had you followed the C convention, your functions would probably have been named <code>activef</code> and <code>annealf</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:30:48.423",
"Id": "43515",
"ParentId": "43393",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "43425",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T10:41:07.630",
"Id": "43393",
"Score": "8",
"Tags": [
"c++",
"arduino"
],
"Title": "Gyrometer/accelerometer sensor fusion with sigmoid transfer function"
}
|
43393
|
<p>I am making a PHP script which fetches the data of the emails whose sending date and time has been reached and then send emails to those records. I am following the steps below and integrating it in an API, that is.</p>
<p><a href="https://github.com/infusionsoft/PHP-iSDK" rel="nofollow">GitHub code</a></p>
<p>Steps: </p>
<ol>
<li>Get the communication records whose time has reached.</li>
<li>Run the loop of above and get the email addresses.</li>
<li>Run the loop of email addresses and send emails.</li>
</ol>
<p>This is my PHP code:</p>
<pre><code><?php
include('iSDK/src/isdk.php');
$myApp = new iSDK();
// Test Connnection
if ($myApp->cfgCon("connectionName")) {
echo "Connected...";
} else {
echo "Not Connected...";
}
$query = mysql_query('SELECT * FROM `emails` WHERE `senddate` <= NOW()');
while ($row = mysql_fetch_assoc($query)) {
$conDat = array('Email' => $row['email']);
$conID = $myApp->addCon($conDat);
$clist = array($conID);
$email = $myApp->sendEmail($clist, 'kamranasadi431@gmail.com', '~Contact.Email~',
'ccAddresses', 'bccAddresses', 'contentType', 'JK', 'htmlBody', 'txtBody');
}
?>
</code></pre>
<p>What changes should be made in it?</p>
|
[] |
[
{
"body": "<blockquote>\n<pre><code>// Test Connnection\nif ($myApp->cfgCon(\"connectionName\")) {\n echo \"Connected...\";\n} else {\n echo \"Not Connected...\";\n}\n</code></pre>\n</blockquote>\n\n<p>Does it make sense to continue the program and run the SQL query if it's not connected? If not stop it somehow.</p>\n\n<blockquote>\n<pre><code>$query = mysql_query('SELECT * FROM `emails` WHERE `senddate` <= NOW()');\nwhile ($row = mysql_fetch_assoc($query)) {\n $conDat = array('Email' => $row['email']);\n $conID = $myApp->addCon($conDat);\n $clist = array($conID);\n $email = $myApp->sendEmail($clist, 'kamranasadi431@gmail.com', '~Contact.Email~', 'ccAddresses', 'bccAddresses', 'contentType', 'JK', 'htmlBody', 'txtBody');\n}\n</code></pre>\n</blockquote>\n\n<p>The <code>$email</code> variable is unused here. If it's not neccesary remove it:</p>\n\n<pre><code>$myApp->sendEmail($clist, '...', '...', 'ccAddresses', 'bccAddresses', 'contentType', 'JK', 'htmlBody', 'txtBody');\n</code></pre>\n\n<p>Anyway, you might want to print out some log file about the sending errors/successes for debugging or reporting purposes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T11:45:29.383",
"Id": "74933",
"Score": "0",
"body": "Is my code performing the actions which am supposed to do? or is there something wrong in logic.?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T11:49:56.237",
"Id": "74934",
"Score": "0",
"body": "@Kamran: I've found only these things. It looks OK although I have no time to test it and I'm not familiar with the used APIs (iSDK, MySQL)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T11:27:10.127",
"Id": "43395",
"ParentId": "43394",
"Score": "2"
}
},
{
"body": "<ol>\n<li>Use PDO, not mysql_* as they are deprecated and dangerous.</li>\n<li>Break up your code into functions, this makes it easier to call and test.</li>\n<li>Throw and catch exceptions.</li>\n<li>You can omit the ending ?></li>\n</ol>\n\n<p><strong>NOTE</strong>: This is untested code as I don't have the isdk.php file.</p>\n\n<pre><code> <?php\n\n require('iSDK/src/isdk.php');\n\n $iSDK = new iSDK();\n\n try{\n checkConnection($iSDK);\n performQuery($iSDK, getDBConnection(\"\", \"\", \"\", \"\"));\n } catch(RuntimeException $e){\n die($e->getMessage());\n }\n\n function checkConnection(&$iSDK){\n # Throw an exception if we don't have a connection, otherwise return true\n if (!$iSDK->cfgCon(\"connectionName\")) {\n throw new RuntimeException('Could not obtain connection.');\n }\n }\n\n function performQuery(&$iSDK, $PDO){\n $sth = $PDO->prepare(\"SELECT * FROM `emails` WHERE `senddate` <= NOW()\");\n $sth->setFetchMode(PDO::FETCH_ASSOC); # setting the fetch mode\n $sth->execute();\n\n while($row = $sth->fetch()) {\n $conDat = array('Email' => $row['email']);\n $conID = $iSDK->addCon($conDat);\n $clist = array($conID);\n $email = $iSDK->sendEmail($clist, 'kamranasadi431@gmail.com', '~Contact.Email~', 'ccAddresses', 'bccAddresses', 'contentType', 'JK', 'htmlBody', 'txtBody');\n }\n }\n\n function getDBConnection($host, $dbname, $user, $pass){\n try {\n return new PDO(\"mysql:host=$host;dbname=$dbname\", $user, $pass);\n } catch(PDOException $e) {\n die($e->getMessage());\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T11:52:12.713",
"Id": "76686",
"Score": "0",
"body": "This code is having some syntax error, check it. you can get ISDK from here https://github.com/infusionsoft/PHP-iSDK"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T14:06:28.960",
"Id": "76710",
"Score": "0",
"body": "Even if I had the iSDK lib, I don't have your Db structure, nor am I going to rebuild it. As I stated, \"This is untested code as I don't have the isdk.php file.\". If this has errors, post them and I will deduce and fix."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T14:59:08.760",
"Id": "76720",
"Score": "0",
"body": "function performQuery(&iSDK, $PDO){\n $sth = $PDO->(\"SELECT * FROM `emails` WHERE `senddate` <= NOW()\"); These lines indicating syntax error. I tried to solve it but could not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T15:20:32.370",
"Id": "76726",
"Score": "0",
"body": "\"&iSDK\" is a reference to a constant. Correct way is \"&$iSDK\". Simple fix. noticed I missed the prepare on $PDO in line after that, also fixed. I just tried the code and it ran with no syntax error: http://i.imgur.com/Oc2bsAC.png (exited out with caught exception)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T15:50:33.430",
"Id": "76735",
"Score": "0",
"body": "didn't get what you did with $PDO?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T15:59:35.663",
"Id": "76739",
"Score": "0",
"body": "$PDO is an instance of the PHP PDO class (see http://us1.php.net/manual/en/pdostatement.fetch.php for example). Don't use the [**deprecated**](http://us2.php.net/mysql_query) mysql_* functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T16:12:58.057",
"Id": "76744",
"Score": "0",
"body": "Certainly welcome ^_^"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T01:14:46.460",
"Id": "76852",
"Score": "0",
"body": "I believe call by reference is depreciated also."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T14:09:53.973",
"Id": "76934",
"Score": "0",
"body": "@azngunit81 - call time pass by reference will raise a warning as of 5.3 and a fatal error as of 5.4, but only on a function call, not its definition. So my code above is correct (references in function definition, not function body or function call)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T14:15:30.400",
"Id": "76935",
"Score": "1",
"body": "@jsanc623 good call"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-14T14:35:20.100",
"Id": "76938",
"Score": "0",
"body": "@azngunit81 - see: http://i.imgur.com/R6JYjma.png for a sample."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:54:37.983",
"Id": "43524",
"ParentId": "43394",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T10:42:08.783",
"Id": "43394",
"Score": "4",
"Tags": [
"php",
"email"
],
"Title": "To send the email on some given date and time"
}
|
43394
|
<p>I was a PHP developer and I started writing a product in C# without studying the basic structure. Now, I have around 100+ views with similar code. After 1 year into development, I now realize that something is not right.</p>
<p>How can I separate the server tags when they are so intertwined in the code? Is it okay to use server side variables like this?</p>
<p>PS: I am not using Razor in my product.</p>
<p><strong>/Views/Emp/EditEmp.aspx</strong></p>
<pre><code><% if(HttpContext.Current.User.IsInRole("Manager")) { %>
<div class="small right" style="margin:5px 0 10px 0;">
<a class="btn" href="/Emp/Edit"><i class="icon-double-angle-left"></i>Back to Emp Info</a>
</div>
<% } %>
<div>. ..... .. .. ...</div>
<script type="text/javascript">
$(document).ready(function () {
EmpWorkingDays = [<%= Model.SundayWorkingTime %>, <%= Model.MondayWorkingTime %>, <%= Model.TuesdayWorkingTime %>, <%= Model.WednesdayWorkingTime %>, <%= Model.ThursdayWorkingTime %>, <%= Model.FridayWorkingTime %>, <%= Model.SaturdayWorkingTime %>];
<% if(Model != null && Model.Holidays != null){
foreach(EmpHoliday eh in Model.Holidays.ToList()) { %>
Holidays.push({date:new Date("<%: eh.Date.Year %>", "<%: eh.Date.Month - 1 %>", "<%: eh.Date.Day %>",0,0,0,0).getTime(), holiday:"<%: eh.Holiday %>"});
<% }
} %>
});
</script>
<% if(Model != null && Model.Holidays != null) {
foreach(EmpHoliday eh in Model.Holidays){ %>
<div class="editor-label"><%= eh.Date.ToString("dd/MMM/yyyy") %></div>
<div class="editor-field"><%= eh.Holiday %></div>
<% } %>
<div class="clear"></div>
<% } %>
</code></pre>
|
[] |
[
{
"body": "<p>This is how I see server variables and local variables interacting. There is not really any other way to get the values between the two that I'm aware of.</p>\n\n<p>As for the code, I one minor point:change <code>Emp</code> to <code>Employee</code> for variable names. This will eliminate confusion in the future from you, or anybody else reading the code (what does Emp mean?)</p>\n\n<p>Other than that, this is really easy code to read. Keep it up.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T17:42:36.957",
"Id": "43631",
"ParentId": "43399",
"Score": "5"
}
},
{
"body": "<p>Yes, that is how I would typically do it. </p>\n\n<p>As an alternative concept which I also like to consider at times is using <code>JavascriptSerializer</code> to convert a list to an array.</p>\n\n<p>It would go something like:</p>\n\n<pre><code><%\nModel\n.Holidays\n.ToList()\n.Select(eh => new {\n date: new Date(eh.Date.Year, eh.Date.Month - 1,eh.Date.Day,0,0,0,0),\n holiday: eh.Holiday\n});\n\nvar serializer = new System.Web.Script.Serialization.JavaScriptSerializer();\n%>\n\nvar Holidays = <%= serializer.Serialize(array) %>;\n</code></pre>\n\n<p>Following this line of thought you could create a method on your Model to accomplish the same thing for the working days variable. i.e.</p>\n\n<pre><code><%\nclass MyModel {\n\n public IEnumerable<WorkingDays> GetWorkingDays() {\n yield return Model.SundayWorkingTime;\n yield return Model.MondayWorkingTime;\n // etc\n }\n}\n\nEmpWorkingDays = <%= serializer.Serialize(Model.GetWorkingDays()) %>;\n%>\n</code></pre>\n\n<h3>Using existing MVC helper methods</h3>\n\n<p>When creating links in the view I always like to use the built in MVC helper methods such as <code>Url.Content</code> or <code>Url.Action</code>. This means that if the site is installed in a sub directory the correct link will be created automatically for you. i.e. <code>mysite.com/subdir/Emp/Edit</code>. </p>\n\n<p>If you currently deployed the solution you have your links would break with a 404 Not found.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:54:45.007",
"Id": "43646",
"ParentId": "43399",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T12:26:58.850",
"Id": "43399",
"Score": "9",
"Tags": [
"c#",
"javascript",
"asp.net-mvc-4"
],
"Title": "Accessing server side variables in views and JavaScript"
}
|
43399
|
<p>Is it possible to simplify the code below?</p>
<pre><code>dynamic model = GetExpandoObject(); //model type of ExpandoObject
var result = model.FirstOrDefault(x => x.Key == "node").Value;
if (result != null)
{
result = ((ExpandoObject)result).FirstOrDefault(x => x.Key == "children");
if (result != null)
{
result = ((IList<object>)((KeyValuePair<string, object>)result).Value).FirstOrDefault();
if (result != null)
{
if (result != null)
{
result = ((ExpandoObject)result).FirstOrDefault(x => x.Key == "node").Value;
if (result != null)
{
result = ((ExpandoObject)result).FirstOrDefault(x => x.Key == "stuff");
}
}
}
}
}
</code></pre>
<p>Maybe it is possible to implement similar logic with Linq? Any thoughts?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:22:07.993",
"Id": "74993",
"Score": "1",
"body": "please let us know if we are on the right track here @sreginogemoh"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:32:22.667",
"Id": "75036",
"Score": "1",
"body": "Keep in mind that `FirstOrDefault` on an `IEnumerable` of reference types can return null. Many of those `.Value` calls are vulnerable to `NullReferenceException`s."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:03:11.617",
"Id": "75053",
"Score": "0",
"body": "`dynamic model = …; model.FirstOrDefault(…)` How can this compile? `FirstOrDefault()` is an extension method and those don't work on `dynamic`."
}
] |
[
{
"body": "<p>The first thing that pops out is the repetitive calls that look like this:</p>\n\n<blockquote>\n <p>result = ((ExpandoObject)result).FirstOrDefault(x => x.Key == \"node\").Value;</p>\n</blockquote>\n\n<p>Which are all similar. Half of your calls end in <code>.Value</code> and the other half don't. Which brings up a question on my part, since I don't understand <code>var</code> in C# well enough. So, you can put that in a separate function:</p>\n\n<pre><code>/**\n * You'll have to fill in the return type and come up with a super\n * cool name.\n */\nvar getObj(String key)\n{\n return ((ExpandoObject)result).FirstOrDefault(x => x.Key == key);\n}\n\n// Combine with an assignment in the condition statement, and\n// you can do this:\nif((result = getObj(key)) != null) { ... }\n</code></pre>\n\n<p>Upon further inspection, we can improve this slightly as well.</p>\n\n<pre><code>bool getObj(String key, out var result)\n{\n result = ((ExpandoObject)result).FirstOrDefault(x => x.Key == key);\n return result != null;\n}\n\n// So you can do things like:\nif(getObj(key, out result)) { ... }\n</code></pre>\n\n<p>The second thing that pops out is the quintuple nested if statement. The rule of thumb I've heard before is to have 2-3 nested loops/ifs at most. It looks like you're traversing an XML-like structure, in which case I would almost always go with a recursive method to find the child node you're looking for. In my experience, you do this by passing the object to search along with a queue of nodes. The only downside here is that you're looking for a specific piece of data in a specific place, so you have to know all of the steps to get there(which you do in this case).</p>\n\n<pre><code>// I'm making some assumptions here.\nExpandoObject find(Queue<String> queue, ExpandoObject tree)\n{\n if(getObj(queue.Dequeue, out tree))\n {\n return find(queue, tree);\n }\n else if (queue.Count > 0)\n {\n // We couldn't find an intermediate node, so we want \n //to return null to show our failure\n return null; \n }\n else \n {\n return tree; // May be null!\n }\n} \n</code></pre>\n\n<p>Finally, the IList seems to get in the way. It's unlike the other function calls you're making, because it's using the node's <code>Value</code> instead of its <code>Key</code>. However, if we revisit our <code>getObj</code> function, we might be able to resolve that. AS you can see below, if we pass it a key equal to <code>\"\"</code>, we don't look up the key, but instead set the result to the <code>Value</code> instead.</p>\n\n<pre><code>bool getObj(String key, out var result)\n{\n if(key.Equals(\"\"))// If there is no key, get the value\n {\n result = ((IList<object>)((KeyValuePair<string, object>)result).Value).FirstOrDefault();\n }\n else // If there is a key, use it!\n {\n result = ((ExpandoObject)result).FirstOrDefault(x => x.Key == key);\n }\n return result != null;\n}\n</code></pre>\n\n<p>Then the question becomes, how do we call all of this to make it work? I'll start with the first line of your code:</p>\n\n<pre><code>dynamic model = GetExpandoObject(); //model type of ExpandoObject\n\nQueue<String> queue;\nqueue.Enqueue(\"node\");\nqueue.Enqueue(\"\");\nqueue.Enqueue(\"children\");\nqueue.Enqueue(\"\");\nqueue.Enqueue(\"node\");\nqueue.Enqueue(\"\");\nqueue.Enqueue(\"stuff\");\n\nExpandoObject result = find(queue, model);\nif(result != null)\n{\n // Success! do what you will with it.\n}\n</code></pre>\n\n<p>And the caveat, of course, is that I can't compile any of this, run it, or verify the sanity of any of it. At the very least, I hope it gives you some ideas or will work for you with a few tweaks.</p>\n\n<p>It's my personal preference to always explicitly name the types of things in C#. <code>dynamic</code> and <code>var</code> are wonderful and have their place, but I only use them for one-liners. Carrying around a <code>var</code> for a long time through nested statements can be a pain to debug and maintain when you revisit this code.</p>\n\n<p>Unfortunately, I don't know much about linq - well, I know it, but I haven't used it enough to have that intuition on when and how to use it really effectively - so I can't provide a solution that uses linq.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T14:37:57.800",
"Id": "74955",
"Score": "2",
"body": "`var` has **nothing** to do with `dynamic`. `var` is simply *implicit typing* - the actual type is inferred from the type of the assignment, and that's resolved at compile-time (you get IntelliSense and can even get the IDE to tell you what `var` stands for by hovering the variable with your mouse cursor). `dynamic`, however, is resolved at run-time. **That's** something you don't want to carry around for a long time through nested statements. Using `var` has zero caveats and reduces redundant code like `MyObject foo = new MyObject()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:14:16.783",
"Id": "74988",
"Score": "1",
"body": "@Mat'sMug Thanks for the clarification! I'll admit, C# is a language I only use in my spare time(and wish I could use it on the job)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:12:17.110",
"Id": "75054",
"Score": "0",
"body": "Combining `bool` and `out` makes sense when the default value is also valid. But here, `null` indicates failure, so there is no reason for the separate `bool` result."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T14:31:39.867",
"Id": "43408",
"ParentId": "43400",
"Score": "3"
}
},
{
"body": "<p><code>FirstOrDefault</code> <em>is</em> a LINQ extension method (see <a href=\"http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject%28v=vs.110%29.aspx\">ExpandoObject Extension Methods</a>), so you <em>are</em> using LINQ!</p>\n\n<p>@Ryan's answer looks like it's addressing the structural issue with your code, got my +1.</p>\n\n<p>I'd like to add that you should <strong>avoid reusing the same variable for a different meaning</strong>.</p>\n\n<p>It's very hard for me to tell, but it looks like the code is abusing <code>dynamic</code> - the code compiles and runs <em>because</em> the type of <code>result</code> is <code>dynamic</code> and thus resolved at run-time, and yet you're taking every opportunity at casting it back into an <code>ExpandoObject</code>, so that you get compile-time knowledge of the type you're working with.</p>\n\n<p>Doing this would \"cut\" the <code>dynamic</code> and have <code>var</code> evaluate to <code>ExpandoObject</code> straight from the start:</p>\n\n<pre><code>var result = model.FirstOrDefault(x => x.Key == \"node\").Value as ExpandoObject;\n</code></pre>\n\n<p>and then you could simply do:</p>\n\n<pre><code>if (result != null)\n{\n result = result.FirstOrDefault(x => x.Key == \"children\");\n</code></pre>\n\n<p>However the constant re-assignation of <code>result</code> to a different value is not helping readability, I suggest you put a meaningful name to each step.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T14:57:17.787",
"Id": "43411",
"ParentId": "43400",
"Score": "5"
}
},
{
"body": "<p>you could make it a little less cluttered by putting the result into the if statement like this</p>\n\n<pre><code>dynamic model = GetExpandoObject(); //model type of ExpandoObject\n\nvar result = model.FirstOrDefault(x => x.Key == \"node\").Value;\n\nif (result = null)\n{\n}else{\n if(((ExpandoObject)result).FirstOrDefault(x => x.Key == \"children\") = null)\n {\n //result is already what it should be.\n } else {\n if (((IList<object>)((KeyValuePair<string, object>)result).Value).FirstOrDefault() = null)\n {\n result = ((ExpandoObject)result).FirstOrDefault(x => x.Key == \"children\");\n } else {\n if (((ExpandoObject)result).FirstOrDefault(x => x.Key == \"node\").Value = null)\n {\n result = ((IList<object>)((KeyValuePair<string, object>)result).Value).FirstOrDefault();\n } else {\n result = ((ExpandoObject)result).FirstOrDefault(x => x.Key == \"stuff\");\n }\n }\n }\n}\n</code></pre>\n\n<p>the innermost else statement should still check <code>((ExpandoObject)result).FirstOrDefault(x => x.Key == \"stuff\")</code> for nulls depending on what you are doing with the result. if something else checks for nulls later than I guess you shouldn't worry about it here.</p>\n\n<p>the way I did it here makes sure that you are really only assigning to the variable twice at most, the first initialization of the variable and then again if there is a deeper node that needs to be assigned to it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:54:53.067",
"Id": "74978",
"Score": "2",
"body": "C# won't cast references to bool as a test-for-null: it needs explicit comparison i.e. `!= null`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:58:51.083",
"Id": "74980",
"Score": "0",
"body": "@ChrisW, that should work then, you could get rid of the variable all together"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:01:21.670",
"Id": "74981",
"Score": "1",
"body": "And now you got caught by the reuse of `result` - it *needs* to be reassigned for it to work. This code isn't equivalent to the OP's."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:02:00.850",
"Id": "74982",
"Score": "1",
"body": "I think your newer code doesn't work because, unlike the OP, each statement isn't reassigning to / reusing the result variable. In fact you're using result in your expressions but you deleted its first definition/assignment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:02:05.517",
"Id": "74983",
"Score": "0",
"body": "@Mat'sMug I was just looking at that. give me a second guys..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:03:09.927",
"Id": "74985",
"Score": "0",
"body": "the result needs to be assigned at the deepest level possible. I think rewrite is in order."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:03:21.113",
"Id": "74986",
"Score": "0",
"body": "Your first answer might have been legal if instead of `if (result = expression)` you had written `if ((result = expression) != null)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:13:53.857",
"Id": "74987",
"Score": "0",
"body": "@ChrisW, sorry I was working on changing the answer, does this look a little better, or do I still need to change the if statements?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:34:21.883",
"Id": "75000",
"Score": "0",
"body": "I think it looks worse than, and probably not the same functionality as, the OP's code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:56:50.490",
"Id": "75006",
"Score": "0",
"body": "@ChrisW it looks the same to me, except that I am not assigning to the `result` variable every step, only when I can't go any farther."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T17:01:51.800",
"Id": "75008",
"Score": "0",
"body": "In the OP's code but not in yours, if the expression involving \"node\" returns null then the value in result is null. I don't much want to code review your answer in further detail."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:46:47.403",
"Id": "43416",
"ParentId": "43400",
"Score": "2"
}
},
{
"body": "<p>In your code, the variable result is just of type <code>object</code> because the compiler doesn't know what the result of <code>FirstOrDefault</code> is going to be.</p>\n\n<p>Below I've used explicit typing using <code>T</code> for clarity and so that <code>var</code> doesn't evaluate to <code>object</code></p>\n\n<p>I created this extension method so that you wouldn't have to cast the object everytime you wanted to use it... this takes care of that before it returns</p>\n\n<pre><code>public static class ExtensionMethods\n{\n public static T FirstOrDefault<T>(this ExpandoObject eo, string key)\n {\n object r = eo.FirstOrDefault(x => x.Key == key).Value;\n return (r is T) ? (T)r : default(T);\n }\n}\n</code></pre>\n\n<p>What follows is a re-implementation of the original post's code using the above method</p>\n\n<pre><code>ExpandoObject model = GetExpandoObject();\n\nvar someExpandoObject = model.FirstOrDefault<ExpandoObject>(\"node\");\nif (someExpandoObject == null) return;\n\nvar kvp = someExpandoObject.FirstOrDefault<KeyValuePair<string, object>>(\"children\");\nif (kvp.Equals(default(KeyValuePair<string, object>))) return;\n\nvar ilo = kvp.Value as IList<object>;\nif (ilo == null) return;\n\nsomeExpandoObject = ilo.FirstOrDefault() as ExpandoObject;\nif (someExpandoObject == null) return;\n\nsomeExpandoObject = someExpandoObject.FirstOrDefault<ExpandoObject>(\"node\");\nif (someExpandoObject == null) return;\n\nobject finalResult = someExpandoObject.FirstOrDefault<object>(\"stuff\");\n</code></pre>\n\n<p>What follows is another possible implementation using nested <code>if</code> statements instead of multiple <code>return</code> statements.</p>\n\n<pre><code>ExpandoObject model = GetExpandoObject();\n\nExpandoObject someExpandoObject;\nKeyValuePair<string, object> kvp;\nIList<object> ilo;\nobject finalResult;\n\nif ((someExpandoObject = model.FirstOrDefault<ExpandoObject>(\"node\")) != null)\n{\n if (!(kvp = someExpandoObject.FirstOrDefault<KeyValuePair<string, object>>(\"children\")).Equals(default(KeyValuePair<string, object>)))\n {\n if ((ilo = kvp.Value as IList<object>) != null)\n {\n if ((someExpandoObject = ilo.FirstOrDefault() as ExpandoObject) != null)\n {\n if ((someExpandoObject = someExpandoObject.FirstOrDefault<ExpandoObject>(\"node\")) != null)\n finalResult = someExpandoObject.FirstOrDefault<object>(\"stuff\");\n }\n }\n }\n}\n</code></pre>\n\n<p>Update:\nUsing a newer feature of C# <a href=\"https://davefancher.com/2014/08/14/c-6-0-null-propagation-operator/\" rel=\"nofollow noreferrer\">null-propagation</a>, we can string all these calls together. Now we no longer need to save each object down the chain (unless we want to).</p>\n\n<p>Here is an implementation using null-propagation.</p>\n\n<pre><code>object finalResult = ((model.FirstOrDefault<ExpandoObject>(\"node\")\n ?.FirstOrDefault<KeyValuePair<string, object>>(\"children\").Value as IList<object>)\n ?.FirstOrDefault() as ExpandoObject)\n ?.FirstOrDefault<object>(\"stuff\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:18:02.353",
"Id": "74990",
"Score": "0",
"body": "the way I understand the OP is that they want the deepest node.value that exists. your code doesn't look like it will accomplish this. but is good sounds code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:21:37.587",
"Id": "74992",
"Score": "2",
"body": "Congratulations, you've earned my last vote for the day! Good job at removing all the `if` blocks :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:33:14.767",
"Id": "74997",
"Score": "0",
"body": "@Malachi I'm not sure what the OP is trying to do exactly... a diagram of this object structure would have been helpful. I guess if he needs to go deeper he can loop :D."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:33:36.837",
"Id": "74998",
"Score": "0",
"body": "@Mat'sMug Thanks! It is shorter code, and less messy that way... as-long as he doesn't want early returns, it is the way to go."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-03-04T16:14:28.993",
"Id": "43418",
"ParentId": "43400",
"Score": "8"
}
},
{
"body": "<p>I would take advantage of using <code>dynamic</code>. It will throw <code>RuntimeBinderException</code> when a property doesn't exist, so you can just catch that:</p>\n\n<pre><code>dynamic model = GetExpandoObject();\n\ndynamic result = null;\n\ntry\n{\n result = model.node.children.node.stuff;\n}\ncatch (RuntimeBinderException)\n{\n}\n</code></pre>\n\n<p>Using exceptions unnecessarily is not great, but I think it's better than your overly verbose code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:09:15.160",
"Id": "43434",
"ParentId": "43400",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "43418",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T12:53:09.000",
"Id": "43400",
"Score": "15",
"Tags": [
"c#",
".net",
"linq"
],
"Title": "Finding elements inside ExpandoObject"
}
|
43400
|
<p>I have a script that sends multiple commands after logging in a remote machine via SSH.</p>
<p>Problem is, it's barely readable. I've tried quoting everything with "", but it's terrible (everything appears in pink), and here documents are just as bad (everything appears in gray). I'm using Gedit as an editor, but I tried Emacs as well.</p>
<p>Can I make the editor parse the remotely executed code as code?</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/bash
function remoteExec()
{
echo "remote execution starting"
ssh -n "$1" << 'EOF'
#the following code is _not_ highlighted by real editors
currIt=\"$2\" #I hope this parameter is passed correctly
while [ "$currIt" -lt 5 ]; do
echo "hello"
currIt=$(($currIt + 1))
done
EOF
}
</code></pre>
<p>I'd rather not create a separate script just for these lines, because then I'd have to copy it on the remote machine, or pipe it, and I have arguments too.</p>
<p>EDIT: as Glenn noticed, as far as highlighting goes, there isn't much to do. I'm open to solutions putting the code in a separate script. I need to transfer the code to the remote host then, and pass it the necessary arguments.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T14:39:03.217",
"Id": "74956",
"Score": "1",
"body": "As far as I understood that question, you are asking about: \"How can I make my Editor parse strings as code?\". Is that correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T14:49:39.343",
"Id": "74958",
"Score": "0",
"body": "Not really. I need a readable way to execute some lines of code on a remote machine, possibly without creating a new script. The fact that the editor does not parse the current code as such makes it not readable."
}
] |
[
{
"body": "<p>You're quoting the heredoc terminator, so $2 will certainly not be expanded</p>\n\n<p>When you want to pass multiple commands to ssh, wrap them as a single script to an interperter, thus ssh sees one single command.</p>\n\n<p>Lots of whitespace for readability.</p>\n\n<p>And yes, not much opportunity for syntax highlighting.</p>\n\n<p>Since you need variable expansion within the script, you need to worry about quoting variables you want to be expanded on the remote host. I changed the while loop to a for loop to minimize the number of <code>$</code>-signs to escape.</p>\n\n<p>If the script you want to send is more complex, be careful about how you use single and double quotes.</p>\n\n<pre><code>function remoteExec()\n{\n echo \"remote execution starting\"\n ssh -n \"$1\" << EOF\n bash -c '\n for (( currIt=\"$2\"; currIt < 5; currIt++ )); do\n echo \"hello\"\n done\n '\nEOF\n}\n</code></pre>\n\n<hr>\n\n<p>Given an arbitrary number of args:</p>\n\n<pre><code>function remoteExec()\n{\n local host=$1\n local startIt=$2\n local quotedArgs\n shift 2\n for arg in \"$@\"; do\n quotedArgs+=\"\\\"$arg\\\" \"\n done\n\n echo \"remote execution starting\"\n ssh -n \"$host\" << EOF\n bash -c '\n for (( currIt=\"$startIt\"; currIt < 5; currIt++ )); do\n echo \"hello\"\n done\n args=( $quotedArgs )\n printf \"%s\\n\" \"\\${args[@]}\" # escape this sigil\n '\nEOF\n}\n\nremoteExec host 3 arg1 arg2 \"this is arg3\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T16:19:24.983",
"Id": "74991",
"Score": "0",
"body": "Thanks for making it more generic. I'm starting to think that using a separate script instead of a heredoc would make this more readable. How would you do that? Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T17:23:28.600",
"Id": "75014",
"Score": "1",
"body": "`scp local_script.sh $host:/path/to/script.sh; ssh -n $host \"chmod u+x /path/to/script.sh && /path/to/script.sh $arg1 $arg2\"`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T17:26:00.537",
"Id": "75015",
"Score": "0",
"body": "Both of your scripts misinterpret `$2` in a single-quoted context, i.e. literally."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:58:42.087",
"Id": "75086",
"Score": "0",
"body": "@200_success is it ok if on local I double quote variables like `./myScript.sh \"$1\" \"$2\"` but in ssh commands I don't and just write `ssh -n user@host \"cd $dir;./myScript.sh $1 $2\"`? BTW In the second case the script hangs after I give it the password... Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:11:25.277",
"Id": "75089",
"Score": "1",
"body": "@200_success, no they don't: a heredoc is essentially a double-quoted string. It's just like this: `x=foo; y=\"this is '$x'\"; echo \"$y\"`. Or, are you suggesting the OP wants to send a literal `$2`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T00:58:26.437",
"Id": "75123",
"Score": "0",
"body": "I stand corrected!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:38:05.820",
"Id": "75253",
"Score": "0",
"body": "@glennjackman Is that pure bash syntax? What escaping do I need to use if I want to use the `currIt` variable inside the loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T16:16:43.167",
"Id": "75268",
"Score": "0",
"body": "Just escape the dollar: `echo \"\\$currIt\"`"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:50:01.220",
"Id": "43417",
"ParentId": "43403",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "43417",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T13:22:26.887",
"Id": "43403",
"Score": "2",
"Tags": [
"bash"
],
"Title": "Bash pass multiple commands to SSH and make readable"
}
|
43403
|
<p>I sent a PR to a repo the other day and want to make sure I have the right idea for URI validation.</p>
<pre><code>function validateURI(files) {
//...
// files can be either a string or an array of paths
// validates the relative path exists or is an http(s) URI
// returns a filtered list of valid paths
// (e.g.) ["../dne.js", "//cdn.jsdelivr.net/jquery/2.1.0/jquery.min.js"] => ["//cdn.jsdelivr.net/jquery/2.1.0/jquery.min.js"]
if(typeof files !== "object") files = [files]; //wrap string
var local = grunt.file.expand(opt, files),
remote = _.map(files, path.normalize).filter(function(path) { //for loading from cdn
return /^((http|https):)?(\\|\/\/)/.test(path); //is http, https, or //
});
return _.uniq(local.concat(remote));
}
</code></pre>
|
[] |
[
{
"body": "<p>Very interesting,</p>\n\n<p>I only have 1 snarky comment, if <code>files</code> is an array of 'paths', maybe you should call it <code>paths</code> ;)</p>\n\n<p>Also, as a user of this function, I might want to override your regex so you might want to provide support for that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T15:57:37.060",
"Id": "75425",
"Score": "0",
"body": "Good point on the optional user validator, that could definitely be useful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T14:08:09.587",
"Id": "43601",
"ParentId": "43405",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T14:15:31.230",
"Id": "43405",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"grunt.js"
],
"Title": "Validate that a relative path exists or is an external URI"
}
|
43405
|
<p>According to my lecture notes, there are benefits to refactoring the code from original code to refactor code.</p>
<p>Reasons for refactoring:</p>
<blockquote>
<p>Replace Temp with Query</p>
<ul>
<li>You are using many temporary variables to
hold the result of an expression</li>
<li>This can result in long methods, since the
(temp) values are available only in local
scope</li>
<li>Queries, in the form of method invocation,
means that the value is available from any
method in the class.</li>
</ul>
<p>Look for a temporary variable that is assigned to once</p>
<ul>
<li>Declare the temp as final</li>
<li>Compile</li>
<li>Extract the right-hand side of the assignment into a method</li>
<li>Compile and test</li>
</ul>
</blockquote>
<p>Original code</p>
<pre><code>double basePrice = _quantity * _itemPrice;
if (basePrice > 1000)
return basePrice * 0.95;
else
return basePrice * 0.98;
</code></pre>
<p>Refactored code</p>
<pre><code>if (basePrice() > 1000)
return basePrice() * 0.95;
else
return basePrice() * 0.98;
...
double basePrice() {
return _quantity * _itemPrice;
}
</code></pre>
<p>What are the benefits from this refactor? Please enlightened me as I can't see what the benefits to refactoring the code are in this case.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T14:59:11.420",
"Id": "74960",
"Score": "0",
"body": "Honestly, neither can I. Are you sure this is your lecture's notes? Refactoring basePrice into a method and calling that twice only makes things worse IMO, in case it's a multithreaded environment and a value has changed in between the calls."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:03:17.333",
"Id": "74962",
"Score": "7",
"body": "This question appears to be off-topic because the answer is not yes to all the [on-topic questions](http://codereview.stackexchange.com/help/on-topic). Especially \"Did I write that code?\" and \"Is it actual code from a project rather than pseudo-code or example code?\" I think [programmers.se] is a better place for this question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:06:35.670",
"Id": "74963",
"Score": "0",
"body": "Actually we're having a small discussion in [chat] concerning that.. you are welcome to join"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:11:42.580",
"Id": "74965",
"Score": "0",
"body": "@all I have added the reasons as to why my lecture notes suggested the refactor"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:13:31.420",
"Id": "74967",
"Score": "0",
"body": "The first change I'd apply is not using `double` for money."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:16:24.493",
"Id": "74968",
"Score": "0",
"body": "@CodesInChaos may your word reach god in heaven above, so that he punishes use of `double` and `float` for the job of `decimal`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:17:42.093",
"Id": "74969",
"Score": "0",
"body": "@CodesInChaos why wouldnt you use double for money ??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:18:08.733",
"Id": "74970",
"Score": "0",
"body": "@SimonAndréForsberg its psedou-code from my lecture slies"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:18:35.080",
"Id": "74971",
"Score": "4",
"body": "Because it's a binary floating point type, and thus can't represent values like `0.1` or `0.98` exactly. This propagates to wrong rounding. In most languages `double` can also give different results depending on the machine or global rounding modes."
}
] |
[
{
"body": "<p>You have misunderstood one thing that your lecturer said, extracting a calculation to a method does not mean that you should call it multiple times within the same method!</p>\n\n<p>You are probably doing <code>double basePrice = _quantity * _itemPrice;</code> on more than one place in your code, the idea is that each of those places should be <code>double basePrice = calcBasePrice();</code> which makes your code above:</p>\n\n<pre><code>double basePrice = calcBasePrice();\nif (basePrice > 1000)\n return basePrice * 0.95;\nelse\n return basePrice * 0.98;\n\ndouble calcBasePrice() {\n return _quantity * _itemPrice;\n}\n</code></pre>\n\n<p>Other suggestions:</p>\n\n<ul>\n<li><p>To perform calculations on money, you want <strong>exact</strong> precision. <code>double</code> does not have exact percision. You should use <code>BigDecimal</code> instead.</p></li>\n<li><p><code>basePrice()</code> is not a good method name, I changed that in my code above to <code>calcBasePrice()</code></p></li>\n<li><p>Ident your code properly, as I've done above.</p></li>\n</ul>\n\n<p>Also, this code:</p>\n\n<pre><code>if (basePrice > 1000)\n return basePrice * 0.95;\nelse\n return basePrice * 0.98;\n</code></pre>\n\n<p>Can use the ternary operator:</p>\n\n<pre><code>return basePrice > 1000 ? basePrice * 0.95 : basePrice * 0.98;\n</code></pre>\n\n<p>Or to make it clearer, you can use a <code>factor</code> variable.</p>\n\n<pre><code>double factor = (basePrice > 1000 ? 0.95 : 0.98);\nreturn basePrice * factor;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:22:53.523",
"Id": "43414",
"ParentId": "43409",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "43414",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T14:46:13.420",
"Id": "43409",
"Score": "-2",
"Tags": [
"c#"
],
"Title": "How does this refactored code make my code better?"
}
|
43409
|
<p>I have multiple models which all have the same functions in my framework. I decided to create one "parent" model and all of my other models would extend and inherit its functions like <a href="http://pastebin.com/55NjGqmS" rel="nofollow">this</a>.</p>
<p>My other models would be like this:</p>
<pre><code>class Games_model extends MY_Model {
protected $table = 'games';
protected $_default_select = array();
protected $_default_join = array();
public function __construct() {
$this->_default_select = array(
$this->table.'.*',
$this->table.'.id as id',
$this->table.'.name as name',
'categories.id as cat_id',
'categories.name AS cat_name'
);
$this->_default_join = array('categories', 'categories.id = fiches.console_id', 'left');
}
}
</code></pre>
<p>Here's how I use it:</p>
<pre><code>$this->games_model->limit(30,0)->where(array('categorie_id' => 1))->get_list()->result();
</code></pre>
<p>Is it a better idea to do like that or to have all the code of <code>MY_Model</code> in <code>Games_model</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-24T17:24:59.157",
"Id": "89206",
"Score": "0",
"body": "Always a good idea have intermediate layer of classes that hold the same behaviour for child classes, but read my answer below for more details of your implementation."
}
] |
[
{
"body": "<p>Well, having a parent model that is extended for all your model classes is always a good idea if they all share the same behaviour and help you with your development. I have implemented a similar approximation within my models and I'm doing something similar to what you do, but instead of writing the query in the controller, I call to the model to handle the retrieve of the data. </p>\n\n<p>Doing as you do it, you have to write all the time the same kind of query in your controller, losing the MVC pattern. Let's say you want to retrieve the values of categories, in a point of your controller you'd have:</p>\n\n<pre><code>$this->games_model->limit(30,0)->where(array('categorie_id' => 1))->get_list()->result();\n</code></pre>\n\n<p>If you want to retrieve the categories in other line of your controller, you'll have to write the same sentence, and... what if, in some point of your development, you wanted to change the field categorie_id to, let's say, super_categorie_id? You'd have to do it in all the calls in your application code... You lost all the value the M in MVC is offering, isolate management of data in the Model layer.</p>\n\n<p>So, I'd keep the extension, but writing the methods for reading with is proper filters INSIDE of the child class, and pass it only the data not needed for filtering (as limit) as a parameter, and set them to a default.</p>\n\n<p>I don't know if I clearly explained myself, any doubt write a comment, ;D</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-24T17:23:46.800",
"Id": "51632",
"ParentId": "43412",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "51632",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:08:14.150",
"Id": "43412",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"codeigniter",
"framework"
],
"Title": "Using one parent model and other extending it in a PHP framework"
}
|
43412
|
<p>Can someone help me further optimize the following Cython code snippets? Specifically, <code>a</code> and <code>b</code> are <code>np.ndarray</code> with <code>int</code> value (range(256)) in them. They are one dimension arrays with dynamic length. <code>resultHamming</code> is a one-dimension array with float value in it (dynamic length). <code>bits</code> is an <code>int</code> list (size 256).</p>
<p>The function is to compare two dynamic length bit vector, and return a similarity value as the distance of the two, where the length of each vector is a multiple of 2048-bit (256 bytes). I want to find the best match between these two bit vector by comparing each 2048-bit block, where each bit vector is represented as <code>ndarray</code> (read the bit sequence byte by byte, thus each position is range from 0 to 2^8 = 256). Rule for matching is to find global minimum distance between all block pairs and allow one block in A to be matched with more than one block in B if they have smaller distance. Always compare the smaller size vector against the larger one.</p>
<p>The following code assumes <code>b</code> vector is smaller. We can limit <code>resultHamming</code> to be smaller than size of <code>numArrayB</code> and only record <code>numArrayB</code> smallest distance value, but need to track the current size when inserting new value into it. Even with current case (record all the pairwise distance), we actually know the final size of <code>resultHamming</code> at the beginning.</p>
<pre><code>def compare(a, b):
cdef double dis, hammingTotal = 0
cdef int numArrayA = int(a.size/256)
cdef int numArrayB = int(b.size/256)
cdef int i, j, k, l, index
bits = list(xrange(256))
# Prepare a bit number table for fast query
for l in xrange(256):
# nnz() counts the number of 1s in value
bits[l] = nnz(l)
resultHamming = []
for i in xrange(numArrayB):
# Count the number of 1-bits in i-th block of B
onesB = sum(bits[b[k+256*i]] for k in xrange(256))
for j in xrange(numArrayA):
# Count the number of 1-bits in j-th block of A
onesA = sum(bits[a[k+256*j]] for k in xrange(256))
# Calculate the hamming distance between i-th block of B and j-th block of A
hammingCur = sum(bits[b[i*256+k] ^ a[j*256+k]] for k in xrange(256))
dis = (hammingCur) / (onesA + onesB)
# Insertion current dis to resultHamming with sorted order
k = len(resultHamming) - 1
if dis >= resultHamming[-1]:
resultHamming.append(dis)
else:
resulthamming.append(resultHamming[k])
while k > 0 and resultHamming[k-1] > dis:
resultHamming[k] = resultHamming[k-1]
k -= 1
resultHamming[k] = dis
# Extract k smallest distance from the distance array
for k in xrange(numArrayB):
hammingTotal += resultHamming[k]
return round(hammingTotal/(numArrayB), 3)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:13:32.640",
"Id": "75492",
"Score": "0",
"body": "What are you trying to achieve here? What is the specification of your function `compare`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T22:13:57.487",
"Id": "75507",
"Score": "0",
"body": "Update the specification and code a little bit. Previously, the rule does not allow one block in A to be matched with several blocks in B, thus it would be even more tricky to find the final k smallest distance value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T23:11:58.837",
"Id": "75513",
"Score": "0",
"body": "The way you have put it, distance from A to B differs from the distance from B to A. What are you looking for? In addition, I wonder, why are you normalizing hamming distance with the number of set bits in each block? As a general rule for optimizing with cython, try to avoid python function calls if possible, i.e. replace pythonic sum with numpy sum, replace bit number table with numpy array, etc..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T06:30:50.020",
"Id": "75547",
"Score": "0",
"body": "Compare(A, B) tries to find the best block by block match between A and B. The above code assume B.size is smaller than A.size, there is an extra step (I omit for space) to switch A and B if B.size > A.size, or add another block to put A in outer layer for loop (Always put the smaller size input in outer layer for loop, and compare the smaller one against the larger one). Since I am choosing dis values globally from the pairwise distance matrix, compare(A,B) should equal to compare(B,A). The flaw exists in answer 1 though. The intention and problem of normalizing is covered in comments below."
}
] |
[
{
"body": "<p>As a general rule for optimizing with cython, try to avoid python function calls if possible, i.e. replace pythonic <code>sum</code> with numpy <code>sum</code> or explicit for loop, replace bit number table with numpy array, and try to declare types for all variables. </p>\n\n<p>You can also precalculate most of the variables used in distance calculation and use a separate array to hold minimum distances for each block. I quickly put something together and got the code below. </p>\n\n<p>Just wondering, what is the rationale for normalizing the distance with the number of set bits?</p>\n\n<pre><code>import cython\nimport numpy as np\ncimport numpy as np\n\ncdef bitCount(unsigned char value):\n cdef count = 0\n while(value):\n value &= value - 1\n count += 1\n return(count)\n\n\ndef compare(np.ndarray[np.uint8_t, ndim=1, mode='c'] a, \n np.ndarray[np.uint8_t, ndim=1, mode='c'] b):\n\n cdef int nblocksA = int(a.size/256)\n cdef int nblocksB = int(b.size/256)\n cdef int i, j, k\n\n cdef double partial_hamming_distance\n\n # Prepare a bit number table for fast query\n cdef np.ndarray[np.uint8_t, ndim=1] bits = np.zeros(256, dtype=np.uint8)\n for i in range(256):\n bits[i] = bitCount(i) \n\n cdef np.ndarray[np.float_t, ndim=1] min_distances = np.ones(nblocksB,\n dtype=np.float)\n min_distances *= 1000000\n\n cdef np.ndarray[np.float_t, ndim=1] set_bitsA = np.zeros(nblocksA, dtype=np.float)\n for i in range(nblocksA):\n for k in range(256):\n set_bitsA[i] += bits[a[k + 256 * i]]\n\n cdef np.ndarray[np.float_t, ndim=1] set_bitsB = np.zeros(nblocksB, dtype=np.float)\n for i in range(nblocksB):\n for k in range(256):\n set_bitsB[i] += bits[b[k + 256 * i]]\n\n for i in range(nblocksB):\n for j in range(nblocksA):\n partial_hamming_distance = 0\n\n for k in range(256):\n partial_hamming_distance += (bits[b[i*256+k] ^ a[j*256+k]] \n / (set_bitsB[i] + set_bitsA[j]))\n\n if partial_hamming_distance < min_distances[i]:\n min_distances[i] = partial_hamming_distance\n\n return np.sum(min_distances)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T05:52:59.917",
"Id": "75544",
"Score": "0",
"body": "Thanks for the beautiful code style and cython advice. You definitely got my intention. 1) Does it better if use np.empty for ndarray initialization? 2) You have three 2+ layer for loops, what about merging them into one? 3) Your partial hamming_distance computation logic is my original version. There might be a flaw: assume A=(a1,a2), B=(b1,b2). And the pairwise distance matrix is: (b1,a1)=46, (b1,a2)=64, (b2,a1)=78, (b2,a2)=85. The above code would return (46+87)/2=62, b1,b2 both match with a1; but a better match would be return (46+64)/2=55, a1,a2 both match b1, compare(a,b)!=compare(b,a)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T07:05:53.577",
"Id": "75549",
"Score": "0",
"body": "Sorry I failed to put all my words in above comments. The distance got from above is not global minimum. And The reason for normalizing the distance like is mainly to return the final distance in scale of 1 instead of 2048. The above code is actually from a fuzzy hashing algorithm called mvHash-B. It might be problematic in case where (set_bitsB[i]+set_bitsA[j]) > 2048 since each block would have 2048 bits at most. BTW, the parameter type of function bitCount() is unsigned char, what's the range of \"value\" here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T08:46:23.170",
"Id": "75555",
"Score": "0",
"body": "@RainLee 1. np.empty is even better choice and will be marginally faster than initializing values with zero. \n2. the first two for loops precalculate number of set bits in each block. And the third one does the actual calculation. You might merge second for loop with the actual calculation since its iterating over the same range. 3. I will look into it when I have some more time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T08:53:28.623",
"Id": "75557",
"Score": "0",
"body": "@RainLee Oh, unsigned char represents an unsigned 8bit value [0, 256)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T13:58:21.387",
"Id": "75601",
"Score": "1",
"body": "@RainLee Also... you can compile cython with `cython -a MODULE.py`. This will generate html showing each line of source code colored white through various shades of yellow. The darker the yellow color, the more dynamic Python behaviour is still being performed on that line. For each line that contains some yellow, you need to add more static typing declarations."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T00:27:13.670",
"Id": "43659",
"ParentId": "43413",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "43659",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T15:18:41.813",
"Id": "43413",
"Score": "7",
"Tags": [
"python",
"optimization",
"performance",
"array",
"cython"
],
"Title": "Optimize Cython code with np.ndarray contained"
}
|
43413
|
<p>I've decided to make an implementation of the C++11 class <code>function</code>. I was checking that I have done everything correctly and have not missed anything:</p>
<pre><code>template < typename > class function;
template < typename _Ret, typename... _Args > class function<_Ret(_Args...)>
{
public:
typedef _Ret result_type;
typedef function<result_type(_Args...)> _Myt;
typedef result_type(*pointer)(_Args...);
function()
: _f_ptr(nullptr)
{
}
template < typename _Fn_Ty > function(_Fn_Ty &&_Fn)
: _f_ptr(reinterpret_cast<pointer>(_Fn))
{
}
function(pointer &&_Fn)
: _f_ptr(_Fn)
{
}
function(const _Myt &_Rhs)
: _f_ptr(_Rhs.f_ptr)
{
}
function(_Myt &&_Rhs)
: _f_ptr(_Rhs.f_ptr)
{
}
~function()
{
}
_Myt &assign(pointer &&_Fn)
{
_f_ptr = _Fn;
return *this;
}
_Myt &operator=(pointer &&_Fn)
{
return assign(_Fn);
}
template < typename _Fn_Ty > _Myt &assign(_Fn_Ty &&_Fn)
{
_f_ptr = reinterpret_cast<pointer>(_Fn);
return *this;
}
template < typename _Fn_Ty > _Myt &operator=(_Fn_Ty &&_Fn)
{
return assign<_Fn_Ty>(_Fn);
}
result_type operator()(_Args... _Arguments)
{
if (_f_ptr == nullptr)
{
throw std::exception("nullptr found instead of function");
}
return _f_ptr(_Arguments...);
}
pointer &ptr() const
{
return _f_ptr;
}
operator pointer &() const
{
return _f_ptr;
}
private:
pointer _f_ptr;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T17:42:48.230",
"Id": "75019",
"Score": "3",
"body": "Maybe you could provide a compilable online example where you use your `function` to store (and then run) a function pointer, a pointer-to-member-function, a stateless lambda, a stateful lambda and a `bind` expression? [Look here](http://en.cppreference.com/w/cpp/utility/functional/function) for inspiration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T19:38:48.790",
"Id": "75049",
"Score": "4",
"body": "In every one of your questions you use reserved identifiers and some people have commented on it yet you still do it. Is the habit too strong to break?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:39:41.177",
"Id": "75082",
"Score": "0",
"body": "@Rapptz - I've kind of got used to it even though it is a bad habit. Woops :O"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:43:21.487",
"Id": "75084",
"Score": "3",
"body": "another recurring theme in your questions here: you like reimplementing Standard Library functionality, which is a great learning tool. But it would be better if you first carefully checked things like all member functions and their signatures against the Standard before posting Code to Review. That, better naming and a few test cases to show that your implementation has at least *a chance* of being correct, would go a long way for people to review your code more carefully. That's why online compilers exist!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T00:21:55.337",
"Id": "75117",
"Score": "1",
"body": "This doesn't compile when testing with basic lambdas, like `function<int(int)> f = [](int i) -> int { return i * 2; };`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:23:37.300",
"Id": "75305",
"Score": "0",
"body": "Since you don't seem to pay any attention to the advice we give you (and continue to create usable code) I see little point in bothering to review this code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:28:40.533",
"Id": "75306",
"Score": "0",
"body": "@LokiAstari - When you mean 'you don't seem to pay any attention to the advice we give you (and continue to create usable code)' - does that mean reserved identifiers? If so, it's a habit I got into, but I promise I will try and stop"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-16T21:26:28.877",
"Id": "401266",
"Score": "0",
"body": "This is Code Review, not Test My Code For Me. You should post code that, to the best of your knowledge after a fair (read: any) attempt, passes tests for the functionality it purports to implement. That is how you do \"_checking that I have done everything correctly and have not missed anything_\". The point I see on this site is to review *how* you did it and whether there might be cases you didn't consider - not just to get other people to check *if* it works for very basic cases. It's important when writing library code to maintain a baseline of tests in parallel."
}
] |
[
{
"body": "<p>Your code has no chance of working, because the only non-static data member of your <code>function<void(void)></code> is a single pointer of type <code>void (*)(void)</code>. There's no room to store any other kind of functor.</p>\n\n<p>In other words, you've implemented the concept of \"function pointer wrapped in a struct\", but you haven't implemented anything like <code>std::function</code> yet.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-03T07:31:50.670",
"Id": "83081",
"ParentId": "43423",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T17:15:29.920",
"Id": "43423",
"Score": "1",
"Tags": [
"c++",
"c++11",
"reinventing-the-wheel"
],
"Title": "std::function implementation"
}
|
43423
|
<p>I started to learn PHP OOP recently and searched the web for some practical exercises and I found one that said to build a select input that is generated and populated with options by the object. I just want to ask for some opinions on code quality. Could it be done better? What is the biggest flaw? </p>
<p>The class:</p>
<pre><code>class completeSelect{
private $setIn;
private $option;
public function __construct($val = array()) {
$this->setIn=$val;
$this->buildOptions();
}
public function buildOptions()
{
$this->option = "";
foreach($this->setIn as $value)
{
$this->option .= '<option value="'.$value.'">'.$value.'</option>';
}
return $this->option;
}
public function BuildSelect() {
$bs = '<select name="select_brwoser">';
$bs .= $this->option;
$bs .= '</select>';
return $bs;
}
}
</code></pre>
<p>The output:</p>
<pre><code>require_once("class.php");
$n = new completeSelect(array("Mozilla","Opera","Internet Explorer"));
echo $n->buildSelect();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:11:54.007",
"Id": "75027",
"Score": "0",
"body": "`I found one that said to build a select input that is generated and populated with options by the object.` I'm wondering if it's your code ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:13:42.623",
"Id": "75028",
"Score": "0",
"body": "i just wrote it :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:14:47.360",
"Id": "75029",
"Score": "0",
"body": "Superfluous whitespace between the last two functions in the class is slightly annoying (no biggie), I don't do PHP so can't quite comment about the rest - looks pretty neat to my non-PHP eyes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:16:12.837",
"Id": "75030",
"Score": "0",
"body": "@PhpJunior Good, was just making sure! +1 the context is clear and well explained!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:24:16.540",
"Id": "75034",
"Score": "0",
"body": "@Mat's Mug This went better than I tought."
}
] |
[
{
"body": "<p>A few minors:</p>\n<ol>\n<li><p>Your spacing is a bit inconsistent (e.g. missing spaces here <code>completeSelect{</code> and here <code>$this->setIn=$val;</code>)</p>\n</li>\n<li><p>Your naming convention is a bit inconsistent as well. I don't do much PHP but class names are usually <code>PascalCase</code>. You should decide whether your methods should be <code>camelCase</code> or <code>PascalCase</code> (you have <code>buildOptions</code> vs <code>BuildSelect</code>).</p>\n</li>\n<li><p>You have a typo here <code>select_brwoser</code> - should probably be <code>select_browser</code></p>\n</li>\n<li><p>Your interface into the class is not quite clear. You build your options on construction yet the method to do so is public. Am I supposed to call it again - if so under which circumstances? If the class is immutable (e.g. you can't add more values for the options) then why not simply build the entire select in the first place and cache it?</p>\n<p>A possible change would be to make the <code>buildXYZ</code> methods private and build on construction (assuming the class is immutable) and have public <code>getXYZ</code> methods instead which return the cached value for the options or the select respectively.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:42:59.753",
"Id": "43429",
"ParentId": "43427",
"Score": "6"
}
},
{
"body": "<p>IMHO, it's pretty good.\nI would check this out:</p>\n\n<ul>\n<li><p>The class name should be: *<em>C</em>*ompleteSelect</p></li>\n<li><p>All the methods should be the first letter in lower case. (*<em>b</em>*uildSelect)</p></li>\n<li><p>I think the return in the buildOptions function could be avoid.</p></li>\n<li><p>What if I have more than one select in the page? They all have the same name <code>name=\"select_brwoser\"</code></p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T16:05:25.617",
"Id": "75266",
"Score": "0",
"body": "well , this is an exercise so the last point does not really matter at the moment , i guess every select with it's own object giving it it's name :-? , anyway i've noted your remarks , thanks for your feedback"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:16:36.797",
"Id": "43514",
"ParentId": "43427",
"Score": "2"
}
},
{
"body": "<p>I made a few changes - namely normalizing the styling (PascalCase classname, lower_case properties, camelCase methods) and spacing. I then made the buildOptions() function shorter and renamed it to generateOption() as that is more adept to what it does. I also added an InvalidArgumentException in the construct that is tripped whenever you pass in an empty array.</p>\n\n<pre><code>class CompleteSelect{\n private $options_set;\n private $select;\n\n public function __construct($option_values = array()){\n if(count($option_values) == 0){\n throw new InvalidArgumentException('Options set is empty in CompleteSelect::__construct()');\n }\n\n $this->options_set = $option_values;\n }\n\n public function buildSelect($name = 'select_browser'){\n $this->select = '<select name=\"'.$name.'\">';\n foreach($this->options_set as $value){\n $this->select .= $this->generateOption($value);\n }\n\n return ($this->select . '</select>');\n }\n\n private function generateOption($value){\n return '<option value=\"'.$value.'\">'.$value.'</option>';\n }\n}\n\ntry{\n $n = new CompleteSelect();\n echo $n->buildSelect();\n} catch(InvalidArgumentException $e){\n echo $e->getMessage();\n}\n\ntry{\n $n = new CompleteSelect(array(\"Mozilla\",\"Opera\",\"Internet Explorer\"));\n echo $n->buildSelect();\n} catch(InvalidArgumentException $e){\n echo $e->getMessage();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T16:14:14.410",
"Id": "75267",
"Score": "0",
"body": "You're very welcome!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:28:53.667",
"Id": "43520",
"ParentId": "43427",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "43520",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:02:56.707",
"Id": "43427",
"Score": "6",
"Tags": [
"php",
"beginner"
],
"Title": "Select input that is generated and populated with options"
}
|
43427
|
<p>I'm writing a pretty complicated piece of UI with angularjs. I've been using angular for about 2 weeks. I'm going to post the controllers I feel are the most confusing to read, and am wondering the following:</p>
<ul>
<li>Could these be more "angular" (done in a more angular way?)</li>
<li>Is it normal to have this much logic in controllers? They are only modifying scope, and don't hit any external services (yet) or touch the HTML.</li>
<li>Should any of these controllers be directives?? Everything I've needed to do works completely fine in a controller so far.</li>
</ul>
<p>If I need to include the HTML as well, let me know. Sorry if this is too much code, but you don't have to read all of it.</p>
<p>Edit: I'm creating a segment builder, which segments users in my application based on stuff they've done on our website. This is the UI for picking segments. For example, a segment could be 'Last visit' 'Greater than' 2 'days ago' and 'Last visit' 'Less than' 1 'weeks ago'. This is for building the dynamic UI for check boxes, lists, etc to choose them.</p>
<pre><code>.controller('ConditionCtrl', ['$scope', function($scope) {
$scope.$on('segment_deleted', function(bogus_event, event_key, segment_index) {
if ($scope.event.key == event_key && $scope.segment_index == segment_index) $scope.condition_checked = false;
});
$scope.condition_checked = $scope.events[$scope.event.key]
&& $scope.events[$scope.event.key].segments[$scope.segment_index].conditions[$scope.condition.key] != null;
$scope.condition_check_changed = function() {
if ($scope.condition_checked)
{
$scope.get_or_create_condition($scope.event.key, $scope.segment_index, $scope.condition)
}
else
{
$scope.delete_condition($scope.event.key, $scope.segment_index, $scope.condition.key)
}
}
$scope.show_comparison_content = function() {
return $scope.condition_checked && $scope.condition["content_type_0"] == "comparison";
}
$scope.show_other_content = function() {
return $scope.condition_checked && $scope.condition["content_type_0"] != "comparison";
}
}])
.controller('ComparisonCtrl', ['$scope', '$rootScope', function($scope, $rootScope) {
var get_content_value_sets = function()
{
return $scope.events[$scope.event.key].segments[$scope.segment_index].conditions[$scope.condition.key].content_value_sets;
}
var clear_empty_sets = function()
{
if (find_comparison_set_by_value(null).set != null)
{
$scope.events[$scope.event.key].segments[$scope.segment_index].conditions[$scope.condition.key].content_value_sets = [];
}
}
var find_comparison_set_by_value = function(value)
{
var index = -1;
var found_set = null;
$.each(get_content_value_sets(), function(i, set)
{
if (set['0'] == value) {
found_set = set;
index = i;
}
});
return {index: index, set: found_set};
}
clear_empty_sets();
var set_result = find_comparison_set_by_value($scope.comparsion_value.id)
$scope.comparison_checked = set_result.set != null;
$scope.get_set_index = function() {
return find_comparison_set_by_value($scope.comparsion_value.id).index;
}
$scope.$on('update_index_needed', function() {
$scope.set_index = $scope.get_set_index();
})
$scope.comparison_check_changed = function() {
if ($scope.comparison_checked)
{
var current_length = get_content_value_sets().length;
$scope.set_index = current_length;
get_content_value_sets().push({'0': $scope.comparsion_value.id, '1': null, '2': null})
}
else
{
var set_result = find_comparison_set_by_value($scope.comparsion_value.id);
if (set_result.set != null)
{
get_content_value_sets().splice(set_result.index, 1)
$rootScope.$broadcast('update_index_needed')
}
}
}
}])
.controller('ListContentCtrl', ['$scope', function($scope){
$scope.select2Options = {
createSearchChoice: function(term, data) {
if ($(data)
.filter(function() {
return this.text.localeCompare(term)===0;
}).length===0)
{
return {id:term, text:term};
}
},
placeholder: 'Select or enter a value',
multiple: false,
data: $scope.event.values,
selectOnBlur: true,
allowClear: true
};
var add_row = function() {
if (!$scope.condition.allow_multi) return;
if ($scope.selected_value != null && !$scope.added_row)
{
$scope.events[$scope.event.key].segments[$scope.segment_index].conditions[$scope.condition.key].content_value_sets.push({'1': null, '2': null, '3': null})
$scope.added_row = true;
}
}
add_row();
$scope.update_value = function() {
var new_val = ''
if ($scope.selected_value != null && $scope.selected_value.text != null)
{
new_val = $scope.selected_value.text;
}
$scope.events[$scope.event.key].segments[$scope.segment_index].conditions[$scope.condition.key].content_value_sets[$scope.inner_set_index][$scope.position] = new_val;
add_row();
}
}])
.controller('TextContentCtrl', ['$scope', function($scope){
var add_row = function() {
if (!$scope.condition.allow_multi) return;
if ($scope.selected_value != null && $scope.selected_value != '' && !$scope.added_row)
{
$scope.events[$scope.event.key].segments[$scope.segment_index].conditions[$scope.condition.key].content_value_sets.push({'1': null, '2': null, '3': null})
$scope.added_row = true;
}
}
add_row();
$scope.update_value = function() {
var new_val = ''
if ($scope.selected_value != null && $scope.selected_value != null)
{
new_val = $scope.selected_value;
}
$scope.events[$scope.event.key].segments[$scope.segment_index].conditions[$scope.condition.key].content_value_sets[$scope.inner_set_index][$scope.position] = new_val;
add_row();
}
}])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:51:20.473",
"Id": "75040",
"Score": "0",
"body": "What are your code doing ? We would need a bit more of context."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:53:32.257",
"Id": "75041",
"Score": "0",
"body": "Sorry! I guess that would help. I'm creating a segment builder, which segments users in my application based on stuff they've done on our website. This is the UI for picking segments. For example, a segment could be 'Last visit' 'Greater than' 2 'days ago' and 'Last visit' 'Less than' 1 'weeks ago'. This is for building the dynamic UI for check boxes, lists, etc to choose them"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:54:42.317",
"Id": "75042",
"Score": "1",
"body": "Well thanks for the explanation, but you should add it to the question! It will be more visible for everyone!"
}
] |
[
{
"body": "<p>That code is hard too grok, I find it stretches too much horizontally. From that perspective : </p>\n\n<ul>\n<li><p>Don't skip newlines for <code>if</code> blocks, it is okay to skip the curly braces\n<br>No:</p>\n\n<pre><code>if ($scope.event.key == event_key && $scope.segment_index == segment_index) $scope.condition_checked = false;\n</code></pre>\n\n<p><br>Yes:</p>\n\n<pre><code>if ($scope.event.key == event_key && $scope.segment_index == segment_index)\n $scope.condition_checked = false;\n</code></pre></li>\n<li><p>If all parameters are coming from the same object, consider just passing the object\n<br>Hard to read:</p>\n\n<pre><code>$scope.get_or_create_condition($scope.event.key, $scope.segment_index, $scope.condition);\n</code></pre>\n\n<p><br>Easier to read:</p>\n\n<pre><code>$scope.get_or_create_condition($scope);\n</code></pre>\n\n<p><br>Easiest to read ( assuming you would use <code>this</code> in <code>$scope</code> )</p>\n\n<pre><code>$scope.get_or_create_condition();\n</code></pre></li>\n<li>lowerCamelCase is good for you: <code>get_or_create_condition</code> -> <code>getOrCreateCondition</code>, personally I would not put the fact that that the function either creates or gets in the function name (TMI), I would simply call it <code>getCondition</code></li>\n<li>It is better to always stick to <code>dot notation</code> so <code>$scope.condition[\"content_type_0\"]</code> -> <code>$scope.condition.content_type_0</code></li>\n<li><p>I have reviewed a number of angular submissions, I've never seen anything like this:</p>\n\n<pre><code>$scope.events[$scope.event.key].segments[$scope.segment_index].conditions[$scope.condition.key].content_value_sets[$scope.inner_set_index][$scope.position] = new_val;\n</code></pre>\n\n<p>You need to think about simplifying your object/data structure!</p></li>\n</ul>\n\n<p>Furtermore, not related to horizontal challenges:</p>\n\n<ul>\n<li>You should compare to <code>null</code> with <code>!==</code> not with <code>!=</code> as you do, or, if you can get away with it, use falsey comparisons like <code>if (set_result.set)</code></li>\n<li>You are missing a boatload of semicolons, please use a site like jshint.com to fix those</li>\n<li><p>This: <br></p>\n\n<pre><code>var new_val = ''\nif ($scope.selected_value != null && $scope.selected_value != null)\n{\n new_val = $scope.selected_value;\n}\n</code></pre>\n\n<p>could be:</p>\n\n<pre><code>var new_val = $scope.selected_value || '';\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T21:26:22.457",
"Id": "80919",
"Score": "0",
"body": "thank you however i feel like the majority of this response is stylistic issues which don't actually affect anything and are very objective. the only useful help here was to simplify my object/data structure, but i can't because that is the object/data structure. it's a significantly complicated query builder tree. however, thank you for taking the time to read my submission"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T23:02:07.550",
"Id": "80925",
"Score": "0",
"body": "A large part of code review is to make sure that other people can maintain your code. Your code is too hard to read. If you were to address the style issues, then maybe we could find issues that are not related to style."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T23:07:47.883",
"Id": "81427",
"Score": "0",
"body": "sort of, i think mostly those are personally preferences. camel case vs underscore, semicolons or no semi colons, triple equals vs double. it's the same shit"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T00:42:12.733",
"Id": "81643",
"Score": "0",
"body": "right, that is the object structure, which i thought was a valid criticism. you still have not explained any way to reduce the complexity of the object structure. however, i will split that in to two lines with a temp variable for making it more readable."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T13:49:49.473",
"Id": "43600",
"ParentId": "43430",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T18:43:38.377",
"Id": "43430",
"Score": "4",
"Tags": [
"javascript",
"angular.js"
],
"Title": "Segment builder"
}
|
43430
|
<p>I'm learning Ruby and working through some exercises. I completed the following exercise without truly understanding why and how it works. I know that's an embarrassing thing to say but I feel like my subconscious mind wrote the code and conscious me (or maybe unconscious me you could say) is having trouble understanding why and how it works and if it's even written correctly.</p>
<p>I would appreciate if someone can run through this code and give me a breakdown of how it works and if you think it's written well.</p>
<p><strong>My Code</strong></p>
<pre><code>class Temperature
class << self
def from_fahrenheit temp
Temperature.new({f: temp})
end
def from_celsius temp
Temperature.new({c: temp})
end
end
def initialize(options={})
@f = options[:f]
@c = options[:c]
end
def in_fahrenheit
return @f if @f
(@c * (9.0 / 5.0)) + 32
end
def in_celsius
return @c if @c
(@f - 32) * 5.0 / 9.0
end
end
class Celsius < Temperature
def initialize temp
super(c: temp)
end
end
class Fahrenheit < Temperature
def initialize temp
super(f: temp)
end
end
</code></pre>
<p><strong>Rspec Test</strong></p>
<pre><code>describe Temperature do
describe "can be constructed with an options hash" do
describe "in degrees fahrenheit" do
it "at 50 degrees" do
Temperature.new(:f => 50).in_fahrenheit.should == 50
end
describe "and correctly convert to celsius" do
it "at freezing" do
Temperature.new(:f => 32).in_celsius.should == 0
end
it "at boiling" do
Temperature.new(:f => 212).in_celsius.should == 100
end
it "at body temperature" do
Temperature.new(:f => 98.6).in_celsius.should == 37
end
it "at an arbitrary temperature" do
Temperature.new(:f => 68).in_celsius.should == 20
end
end
end
describe "in degrees celsius" do
it "at 50 degrees" do
Temperature.new(:c => 50).in_celsius.should == 50
end
describe "and correctly convert to fahrenheit" do
it "at freezing" do
Temperature.new(:c => 0).in_fahrenheit.should == 32
end
it "at boiling" do
Temperature.new(:c => 100).in_fahrenheit.should == 212
end
it "at body temperature" do
Temperature.new(:c => 37).in_fahrenheit.should be_within(0.1).of(98.6)
end
end
end
end
describe "can be constructed via factory methods" do
it "in degrees celsius" do
Temperature.from_celsius(50).in_celsius.should == 50
Temperature.from_celsius(50).in_fahrenheit.should == 122
end
it "in degrees fahrenheit" do
Temperature.from_fahrenheit(50).in_fahrenheit.should == 50
Temperature.from_fahrenheit(50).in_celsius.should == 10
end
end
describe "utility class methods" do
end
# Here's another way to solve the problem!
describe "Temperature subclasses" do
describe "Celsius subclass" do
it "is constructed in degrees celsius" do
Celsius.new(50).in_celsius.should == 50
Celsius.new(50).in_fahrenheit.should == 122
end
it "is a Temperature subclass" do
Celsius.new(0).should be_a(Temperature)
end
end
describe "Fahrenheit subclass" do
it "is constructed in degrees fahrenheit" do
Fahrenheit.new(50).in_fahrenheit.should == 50
Fahrenheit.new(50).in_celsius.should == 10
end
it "is a Temperature subclass" do
Fahrenheit.new(0).should be_a(Temperature)
end
end
end
end
</code></pre>
|
[] |
[
{
"body": "<p>For someone who wasn't conscious when he wrote this code, it looks quite nice :)</p>\n\n<p>Some observations:</p>\n\n<p><strong>Tests should do only one thing</strong></p>\n\n<p>This is OK in most of your tests, but you got a little 'lazy' at the last two tests - make a different test for each <code>should</code>. You could use RSpec's <a href=\"https://www.relishapp.com/rspec/rspec-core/docs/subject/one-liner-syntax\">one-liner</a> syntax, just for the fun of it:</p>\n\n<pre><code> describe \"in degrees celsius\" do\n subject { Temperature.from_celsius(50) }\n\n its (:in_celsius) { should == 50 }\n its (:in_fahrenheit) { should == 122 }\n end\n</code></pre>\n\n<p><strong>Meaningful Names</strong></p>\n\n<p>Again, in most cases, you are doing fine, and there may even be good arguments to say that <code>@f</code> and <code>@c</code> are clear enough in context, but there really is no reason not to call them <code>@fahrenheit</code> and <code>@celsius</code>. <code>temp</code> is also a quirk you should fix...</p>\n\n<p><strong>When things don't change</strong></p>\n\n<p>After you create a <code>Temperature</code> instance, its <code>celsius</code> and <code>fahrenheit</code> values will never change, so there is no reason why you should continue to calculate them - simply store the result in the appropriate member:</p>\n\n<pre><code> def in_fahrenheit\n return @f if @f\n @f = (@c * (9.0 / 5.0)) + 32\n end\n</code></pre>\n\n<p>You can even make this shorter, using the <code>||=</code> operator, which will compute and assign the member if it is not assigned:</p>\n\n<pre><code> def in_fahrenheit\n @f ||= (@c * (9.0 / 5.0)) + 32\n end\n</code></pre>\n\n<p>This is looking more and more like a getter function, and really, since it calls for the state of the instance, you don't need to imply there is ever a calculation, simply call it <code>fahrenheit</code>:</p>\n\n<pre><code>def fahrenheit\n @fahrenheit ||= (@celsius * (9.0 / 5.0)) + 32\nend\n</code></pre>\n\n<p><strong>Have a consistent style</strong></p>\n\n<p>In your code you call methods with hashes with three different styles:</p>\n\n<pre><code>Temperature.new({f: temp})\nsuper(c: temp)\nTemperature.new(:c => 50).in_celsius.should == 50\n</code></pre>\n\n<p>All of these styles work, but it is better to choose one, and stick with it. When using a hash in method, my favorite is the second style (<code>Temperature.new(f: temp)</code>)</p>\n\n<p><strong>Use language features</strong></p>\n\n<p>Since Ruby 2.0, <a href=\"http://dev.af83.com/2013/02/18/ruby-2-0-keyword-arguments.html\">named parameters</a> are supported, and you are encouraged to use it. It will give you free validation, as any parameter which is not one of those you declared, an error will be issued:</p>\n\n<pre><code>def initialize(celsius: nil, fahrenheit: nil)\n @fahrenheit = fahrenheit\n @celsius = celsius\nend\n</code></pre>\n\n<p>One last point, regarding your <code>Celsius</code> and <code>Fahrenheit</code> classes, I personally don't see any utility in having them, since they add no logic besides a construction convenience, and may even confuse, since their name implies they support only one scale or the other...</p>\n\n<p>So now, your class will look like this:</p>\n\n<pre><code>class Temperature\n\n class << self\n def from_fahrenheit fahrenheit\n Temperature.new(fahrenheit: fahrenheit)\n end\n\n def from_celsius celsius\n Temperature.new(celsius: celsius)\n end\n end\n\n def initialize(celsius: nil, fahrenheit: nil)\n @fahrenheit = fahrenheit\n @celsius = celsius\n end\n\n def fahrenheit\n @fahrenheit ||= (@celsius * (9.0 / 5.0)) + 32\n end\n\n def celsius\n @celsius ||= (@fahrenheit - 32) * 5.0 / 9.0\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:00:27.737",
"Id": "75470",
"Score": "0",
"body": "+1. I'd probably pre-calculate C/F values in initialization to avoid ugly memoizations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:18:54.050",
"Id": "75475",
"Score": "0",
"body": "@Uri Thank you for your time. I think your answer is fantastic and all of your points valid. I appreciate all of your suggestions and the links too. I'd like to point out that I did not write the test spec. So using (named params) `(celsius: nil, fahrenheit: nil)` would require I change the test spec which isn't allowed. Regardless I will use these techniques in my personal work. Thanks again. +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T20:07:42.590",
"Id": "75489",
"Score": "0",
"body": "You can still use named params, only you won't be able to change parameter names: `def initialize(c: nil, f: nil)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T22:22:12.873",
"Id": "75508",
"Score": "0",
"body": "One question about your `initialize` - what if the user gives values for both `celsius` and `fahrenheit` and the two are inconsistent, e.g., `Temperature.new(fahrenheit: 98.6, celsius: 0)`? There should be some sort of consistency check."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T04:54:40.830",
"Id": "75536",
"Score": "0",
"body": "@pjs You are absolutely right, there should also be a check for someone giving _no_ values."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T18:19:05.013",
"Id": "43634",
"ParentId": "43431",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "43634",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T19:41:34.917",
"Id": "43431",
"Score": "6",
"Tags": [
"ruby",
"converting"
],
"Title": "Converting between Fahrenheit and Celsius"
}
|
43431
|
<p>I'm interested in optimizing my code. Can someone help me understand the best way to trim this code down with DRY methodology?</p>
<p>So I've got these two classes here preforming WMI queries on two separate Win32 classes. My questions are:</p>
<ol>
<li>Should I keep them separated in different classes based on the Win32 class for organizational purposes?</li>
<li>Should I use a parent partial class and split these into different files?</li>
<li>Should I use methods with optional parameters or overloads in order to reduce the number of classes here?</li>
<li>Why is the selected method best?</li>
</ol>
<p></p>
<pre><code>public class Win32OperatingSystem
{
public ulong GetFreePhysicalMemory()
{
return GetProperty("FreePhysicalMemory");
}
public ulong GetTotalVirtualMemorySize()
{
return GetProperty("TotalVirtualMemorySize");
}
public ulong GetFreeVirtualMemory()
{
return GetProperty("FreeVirtualMemory");
}
private ulong GetProperty(string propertyName)
{
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM Win32_OperatingSystem");
using (var enu = moSearcher.Get().GetEnumerator())
{
if (!enu.MoveNext()) return 0;
return BytesToMegaBytes((ulong)enu.Current[propertyName]);
}
}
private ulong BytesToMegaBytes(ulong bytes)
{
return bytes / (ulong)1024;
}
}
public class Win32ComputerSystem
{
public string GetName()
{
return GetProperty("Name");
}
public string GetManufacturer()
{
return GetProperty("Manufacturer");
}
public string GetModel()
{
return GetProperty("Model");
}
private string GetProperty(string propertyName)
{
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM Win32_ComputerSystem");
using (var enu = moSearcher.Get().GetEnumerator())
{
if (!enu.MoveNext()) return "Unable to retrieve " + propertyName + " from Win32_ComputerSystem!";
return enu.Current[propertyName].ToString();
}
}
}
</code></pre>
<h3>Questions in this series</h3>
<p>This is the first question in the series.</p>
<p><a href="https://codereview.stackexchange.com/questions/43598/should-i-refactor-for-dry">First iteration of DRY refactoring</a></p>
<p><a href="https://codereview.stackexchange.com/questions/43719/next-instance-of-dry-refactoring/43735?noredirect=1#43735">Second iteration of DRY refactoring.</a></p>
<p><a href="https://codereview.stackexchange.com/questions/43777/adding-generics-and-or-enums">Genericizing PropertyValues</a></p>
|
[] |
[
{
"body": "<p>How about leveraging <code>Enum.ToString()</code>?</p>\n\n<p>Given these two enums:</p>\n\n<pre><code>public enum Win32OperatingSystem\n{\n FreePhysicalMemory,\n TotalVirtualMemorySize,\n FreeVirtualMemory\n}\n\npublic enum Win32ComputerSystem\n{\n Name,\n Manufacturer,\n Model\n}\n</code></pre>\n\n<p>Now you can have a simple method:</p>\n\n<pre><code> public ulong SelectWin32Property(Win32OperatingSystem property)\n {\n var propertyName = property.ToString();\n var moSearcher = new ManagementObjectSearcher\n (\"SELECT \" + propertyName + \" FROM Win32_OperatingSystem\");\n using (var enu = moSearcher.Get().GetEnumerator())\n {\n if (!enu.MoveNext()) return 0;\n return BytesToMegaBytes((ulong)enu.Current[propertyName]);\n }\n }\n</code></pre>\n\n<p>If you wanted an overload that takes a <code>Win32ComputerSystem</code> parameter, you'd have to deal with the different return value:</p>\n\n<pre><code> public string SelectWin32Property(Win32ComputerSystem property)\n {\n var propertyName = property.ToString();\n var moSearcher = new ManagementObjectSearcher\n (\"SELECT \" + propertyName + \" FROM Win32_ComputerSystem\");\n using (var enu = moSearcher.Get().GetEnumerator())\n {\n if (!enu.MoveNext()) return \"Unable to retrieve \" + propertyName + \" from Win32_ComputerSystem!\";\n return enu.Current[propertyName].ToString();\n }\n }\n</code></pre>\n\n<p>The easiest would probably be to box the numeric types into a <code>string</code>, so all overloads would return a <code>string</code> representation of their values. This might not be practical, but at least you don't need to write a new method nor to change your interface to support a new property.</p>\n\n<p>Alternatively you could box results in an <code>object</code>, but that wouldn't be pretty, I'd much prefer dealing with a <code>string</code> than exposing <code>object</code>.</p>\n\n<p>The ideal would be to avoid boxing the numeric return types altogether, so the methods <em>have to live in separate classes</em> - this is where generics come handy:</p>\n\n<pre><code>public abstract class Win32QueryBase<TResult, TProperty>\n{\n public abstract TResult SelectWin32Property(TProperty property);\n}\n</code></pre>\n\n<p>This can be implemented by this class:</p>\n\n<pre><code>public class Win32OperatingSystemQuery : Win32QueryBase<ulong, Win32OperatingSystem>\n{\n public override ulong SelectWin32Property(Win32OperatingSystem property)\n {\n // ...\n }\n}\n</code></pre>\n\n<p>And this class:</p>\n\n<pre><code>public class Win32ComputerSystemQuery : Win32QueryBase<string, Win32ComputerSystem>\n{\n public override string SelectWin32Property(Win32ComputerSystem property)\n {\n // ...\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:27:22.577",
"Id": "75058",
"Score": "1",
"body": "I'm not sure if your abstract class is very useful, but I love your enum. (I always love enums!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:08:01.460",
"Id": "75066",
"Score": "0",
"body": "Please bear with me here as I'm new to generics. Let me see if I understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:36:18.970",
"Id": "75079",
"Score": "0",
"body": "The ManagementObject.Item property (inevitably used in the implementation) is already returning a (boxed) `Object`; so IMO your `SelectWin32Property` method could return an `object` i.e. `return enu.Current[propertyName]`, and let the caller (or a wrapper method like the GetComputerString and/or GetOperatingSystemMegabytes methods in my answer) do the casting of that object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:38:31.343",
"Id": "75081",
"Score": "0",
"body": "@ChrisW interesting... can you tell I don't do WMI very often? :) - if it's all boxed-up already, then I'd still try to expose the appropriate type to client code, so as to not expose `object` in my API... but that could be a debatable concern."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:43:27.397",
"Id": "75085",
"Score": "2",
"body": "I too would avoid exposing `object` in my public API: I'd expose it in my private SelectWin32Property method. E.g. you could have several enum types (one for properties which return strings, another for properties which return longs), have a corresponding public method for each enum type, call the private SelectWin32Property method from the public method, and cast from object inside the implementation of the public method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:28:13.367",
"Id": "75092",
"Score": "0",
"body": "Let me see if I understand.\n\n public class Win32OperatingSystemQuery : Win32QueryBase<ulong, Win32OperatingSystem> \n\nmeans that Win32OperatingSystemQuery inherits from Win32QueryBase. In this case we're saying our return type will be a ulong and the Win32 class will be Win32OperatingSystem\n\n public override ulong SelectWin32Property(Win32OperatingSystem property)\n\nHere we would replace property with \"FreeVirtualMemory\" or whatever and inside the braces we'd put something like my current GetProperty method. Is that correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T23:08:40.853",
"Id": "75103",
"Score": "0",
"body": "@GabrielW if you change `GetProperty` to take a parameter of the same type as `TProperty` (/the enum), then yeah ;)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:22:34.333",
"Id": "43435",
"ParentId": "43432",
"Score": "6"
}
},
{
"body": "<blockquote>\n <p>Should I keep them separated in different classes based on the Win32 class for organizational purposes?</p>\n</blockquote>\n\n<p>Clean Code also suggest small classes. They have different <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">responsibility</a>, so I think they are fine.</p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 10: Classes</em>, <em>Classes Should Be Small!</em>)</p>\n\n\n\n<blockquote>\n <p>Should I use a parent partial class and split these into different files?</p>\n</blockquote>\n\n<p>Please don't! It would be useful to remove the duplication of <code>GetProperty</code> but using inheritance for that is an overkill. There is a better solution: composition. Create a <code>PropertyGetter</code> class and move the getter logic into that:</p>\n\n<pre><code>public class PropertyGetter {\n\n public string GetStringProperty(string propertyName, string tableName)\n {\n ManagementObjectSearcher moSearcher = new ManagementObjectSearcher\n (\"SELECT \" + propertyName + \" FROM \" + tableName);\n using (var enu = moSearcher.Get().GetEnumerator())\n {\n if (!enu.MoveNext()) {\n return \"Unable to retrieve \" + propertyName + \" from \" + tableName;\n }\n return enu.Current[propertyName].ToString();\n }\n }\n\n private ulong GetUlongProperty(string propertyName, string tableName) {\n ...\n }\n}\n</code></pre>\n\n<p>The use that class from <code>Win32ComputerSystem</code> and <code>Win32OperatingSystem</code>:</p>\n\n<pre><code>public class Win32ComputerSystem\n{\n private PropertyGetter propertyGetter;\n\n public Win32ComputerSystem(PropertyGetter propertyGetter)\n {\n this.propertyGetter = propertyGetter; // TODO: check null\n }\n\n public string GetName()\n {\n return propertyGetter.GetStringProperty(\"Name\", \"Win32_ComputerSystem\");\n }\n ...\n}\n</code></pre>\n\n<p>See also: <em>Effective Java, Second Edition</em>, <em>Item 16: Favor composition over inheritance</em></p>\n\n<p>In the <code>PropertyGetter</code> class you could eliminate some duplication from the <code>Get*Property</code> methods if you extract out the duplicated logic to a private method(s).</p>\n\n<hr>\n\n<p>Another note: returning <code>0</code> or an error message instead of the expected value seems a little bit dangerous. </p>\n\n<blockquote>\n<pre><code>if (!enu.MoveNext()) return 0;\n... \nif (!enu.MoveNext()) return \"Unable to retrieve \" + propertyName + \" from Win32_ComputerSystem!\";\n</code></pre>\n</blockquote>\n\n<p>If that's an exceptional case an exception might be better. Clients of these classes might use these values as valid data and you just postpone the error which makes debugging harder. (<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:40:09.907",
"Id": "75059",
"Score": "0",
"body": "I'm not quite sure what you are getting at having the PropertyGetter take an instance of a PropertyGetter??"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:24:42.223",
"Id": "43436",
"ParentId": "43432",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>Should I keep them separated in different classes based on the Win32 class for organizational purposes?</p>\n</blockquote>\n\n<p>Not necessarily.</p>\n\n<p>The difference between 'computer' and 'operating system' seems to me non-obvious: for example, why is 'memory size' a property of 'operating system' not of 'computer'?</p>\n\n<p>Speaking as a hypothetical user of your API, it isn't clear to me which class I'd want/expect to access for each property.</p>\n\n<p>Furthermore, the implementation of each class is very similar, and has the same dependencies (they both use ManagementObjectSearcher in their implementation).</p>\n\n<p>Therefore IMO you might as well combine them into a single class.</p>\n\n<pre><code>public class Win32System\n{\n #region Get megabytes from Win32_OperatingSystem\n\n public ulong GetFreePhysicalMemory()\n {\n return GetOperatingSystemMegaBytes(\"FreePhysicalMemory\");\n }\n\n public ulong GetTotalVirtualMemorySize()\n {\n return GetOperatingSystemMegaBytes(\"TotalVirtualMemorySize\");\n }\n\n public ulong GetFreeVirtualMemory()\n {\n return GetOperatingSystemMegaBytes(\"FreeVirtualMemory\");\n }\n\n private ulong GetOperatingSystemMegaBytes(string propertyName)\n {\n ManagementObjectSearcher moSearcher = new ManagementObjectSearcher\n (\"SELECT \" + propertyName + \" FROM Win32_OperatingSystem\");\n using (var enu = moSearcher.Get().GetEnumerator())\n {\n if (!enu.MoveNext()) return 0;\n return BytesToMegaBytes((ulong)enu.Current[propertyName]);\n }\n }\n\n private ulong BytesToMegaBytes(ulong bytes)\n {\n return bytes / (ulong)1024;\n }\n\n #endregion\n #region Get strings from Win32_ComputerSystem\n\n public string GetName()\n {\n return GetComputerString(\"Name\");\n }\n\n public string GetManufacturer()\n {\n return GetComputerString(\"Manufacturer\");\n }\n\n public string GetModel()\n {\n return GetComputerString(\"Model\");\n }\n\n private string GetComputerString(string propertyName)\n {\n ManagementObjectSearcher moSearcher = new ManagementObjectSearcher\n (\"SELECT \" + propertyName + \" FROM Win32_ComputerSystem\");\n using (var enu = moSearcher.Get().GetEnumerator())\n {\n if (!enu.MoveNext()) return \"Unable to retrieve \" + propertyName + \" from Win32_ComputerSystem!\";\n return enu.Current[propertyName].ToString();\n }\n }\n\n #endregion\n}\n</code></pre>\n\n<p>As a further exercise you could now refactor the GetOperatingSystemMegaBytes and GetComputerString methods, so that they share a common implementation/subroutine, e.g. as follows:</p>\n\n<pre><code> private string GetComputerString(string propertyName)\n {\n object rc = GetManagementObject(propertyName, \"Win32_ComputerSystem\");\n return rc.ToString();\n }\n\n private ulong GetOperatingSystemMegaBytes(string propertyName)\n {\n object rc = GetManagementObject(propertyName, \"Win32_OperatingSystem\");\n return BytesToMegaBytes((ulong)rc);\n }\n\n private object GetManagementObject(string propertyName, string tableName)\n {\n ManagementObjectSearcher moSearcher = new ManagementObjectSearcher\n (\"SELECT \" + propertyName + \" FROM \" + tableName);\n using (var enu = moSearcher.Get().GetEnumerator())\n {\n if (!enu.MoveNext())\n throw new YourChoiceOfException();\n return enu.Current[propertyName];\n }\n }\n</code></pre>\n\n<p>Other comments:</p>\n\n<ul>\n<li>The public methods could be public properties instead (however see comments below this answer)</li>\n<li>There's something wrong with the BytesToMegaBytes method: it should be called KiloBytesToMegaBytes; or it should be dividing by <code>(1024*1024)</code>.</li>\n<li>IMO the Get methods should throw an exception on failure, instead of returning nonsense values such as <code>0</code> or an error-message string.</li>\n<li>The whole class could be <code>static</code>, with its methods all <code>static</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:12:12.697",
"Id": "75070",
"Score": "0",
"body": "Good answer. I was going to also recommend properties, but found that they'd really be methods in disguise; I don't like a property getter that makes a WMI query."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:20:38.013",
"Id": "75073",
"Score": "0",
"body": "Can you explain (or link to an article which explains) why one shouldn't use a property to e.g. wrap a WMI query?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:21:57.857",
"Id": "75074",
"Score": "1",
"body": "Sure, see [this SO answer](http://stackoverflow.com/a/1294189/1188513), first point is *\"The getters should be simple and thus unlikely to throw exceptions. Note that this implies no network (or database) access. Either might fail, and therefore would throw an exception.\"*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T07:41:05.293",
"Id": "76208",
"Score": "0",
"body": "I don't like the fact that you have to use the same conversion per data type. This is redundant and should be avoided."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T09:31:05.007",
"Id": "76220",
"Score": "0",
"body": "@alzaimar I don't understand your comment. Do you mean the fact that GetOperatingSystemMegaBytes is used in the implementation of two different properties i.e. GetFreePhysicalMemory and GetTotalVirtualMemorySize? And what is the solution you prefer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T10:00:24.390",
"Id": "76224",
"Score": "0",
"body": "@ChrisW: Forget about it, it was too early for me. I should never comment before the first sip of coffee. Sorry."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:52:21.507",
"Id": "43445",
"ParentId": "43432",
"Score": "3"
}
},
{
"body": "<p>I would first move the property retrieval to a small generic class</p>\n\n<pre><code>public class PropertyReader<T>\n{\n private string _win32Class;\n\n public PropertyReader(string win32Class)\n {\n _win32Class = win32Class;\n }\n\n public T GetProperty(string propertyName)\n {\n string query = \"SELECT {0} from {1}\";\n using (var moSearcher = new ManagementObjectSearcher(string.Format(query, propertyName, _win32Class)))\n {\n using (var collection = moSearcher.Get())\n {\n using (var enu = collection.GetEnumerator())\n {\n if (!enu.MoveNext() || enu.Current[propertyName] == null)\n {\n return default(T);\n }\n return AdjustResult(enu.Current[propertyName]);\n }\n }\n }\n }\n\n protected virtual T AdjustResult(object obj)\n {\n return (T)obj;\n }\n}\n</code></pre>\n\n<p>This class does all the job and returns a default value in case the property is unknown (whether that is a bad design or wanted can be changed later). Now, in order to return a string property, simply call</p>\n\n<pre><code>public GetStringProperty (string propertyName)\n{\n return new PropertyReader<string>().GetProperty(propertyName);\n}\n</code></pre>\n\n<p>The same applies to any datatype which does not require result conversion e.g. to megabytes or date time formatting.</p>\n\n<pre><code>public GetBoolProperty (string propertyName)\n{\n return new PropertyReader<bool>().GetProperty(propertyName);\n}\n</code></pre>\n\n<p>For the <code>ulong</code> and <code>DateTime</code> properties, create a derived class and overwrite the <code>AdjustResult</code> method:</p>\n\n<pre><code>public class UnsignedInt64PropertyReader : PropertyReader<ulong>\n{\n public UnsignedInt64PropertyReader(string win32Class) : base(win32Class) {}\n\n private static ulong KiloBytesToMegaBytes(ulong kiloBytes)\n {\n return kiloBytes / (ulong)1024;\n }\n\n protected override ulong AdjustResult(object obj)\n {\n return KiloBytesToMegaBytes(base.AdjustResult(obj));\n }\n}\n\npublic class DateTimePropertyReader : PropertyReader<DateTime> \n{\n public DateTimePropertyReader(string win32Class) : base(win32Class) {}\n\n protected override ulong Value(object obj)\n {\n return ManagementDateTimeConverter.ToDateTime(obj.ToString());\n }\n}\n</code></pre>\n\n<p>This will remove almost all code redundancies as requested. Hope this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T08:26:50.490",
"Id": "43778",
"ParentId": "43432",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "43436",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T19:49:27.930",
"Id": "43432",
"Score": "5",
"Tags": [
"c#",
"optimization"
],
"Title": "Class Seperation vs Polymorphism"
}
|
43432
|
<p>I have a checking function that checks the correct type for a class Check_Annotation, I was wondering if there is a better way to implement this, my current code right now is:</p>
<pre><code>def _check_list_or_tuple (self, param, annot, value, check_history):
assert isinstance(value, type(annot)), "AssertionError: 'x' failed annotation check(wrong type): value = {}, was type {} ...should be type {}".format(value, type_as_str(value), type_as_str(annot))
if len(annot) == 1 and type(annot[0]) != list and type(annot[0])!= tuple and inspect.isfunction(annot[0]) == False:
for x in value :
check_history = ''
check_history += str(annot[0])
assert type(x) == annot[0], "AssertionError: 'x' failed annotation check(wrong type): value = {}, was type {} ...should be type {} \nlist[{}] check: {}".format(x, type_as_str(x), annot[0], annot.index(annot[0])+1, check_history)
elif type(annot[0]) == list or type(annot[0]) == tuple or inspect.isfunction(annot[0]) == True:
for i in range(len(value)):
self.check(param, annot[0], value[i])
elif len(annot) > 1:
check_history = ''
check_history += str(annot[0])
assert type (value[0]) == annot[0], "AssertionError: 'x' failed annotation check(wrong type): value = {}, was type {} ...should be type {} \nlist[{}] check: {}".format(value[0], type_as_str(value[0]), annot[0], annot.index(annot[0])+1, check_history)
check_history = ''
check_history += str(annot)
assert len(annot) == len(value), "AssertionError: 'x' failed annotation check(wrong number of elements): value = {} \nannotation had {} elements[{}]".format(value, len(annot), check_history)
for x in value[1:]:
check_history = ''
check_history += str(annot[1])
assert type(x) == annot[1], "AssertionError: 'x' failed annotation check(wrong type): value = {}, was type {} ...should be type {} \nlist[{}] check: {}".format(x, type_as_str(x), annot[1], annot.index(annot[1])+1, check_history)
</code></pre>
<p>To me it is a bit rough on implementation and repetitive code. Does anyone have an idea of a shorter way to go about doing this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T20:43:31.180",
"Id": "75337",
"Score": "0",
"body": "I don't think you need to initialize check_history at all. Just have `check_history = str(annot[X])`"
}
] |
[
{
"body": "<p>I don't have time to check all of this, but here are some ideas ...\n - place long strings in parenthesis and break them up into multiple lines\n - if those strings are used more than once, use variables for them\n - break out the for loops as a separate function</p>\n\n<pre><code>type_error_msg = (\"AssertionError: 'x' failed annotation check(wrong type):\"\n \" value = {}, was type {} ...should be type {}\")\nlist_error_msg = (\"AssertionError: 'x' failed annotation check(wrong type):\"\n \" value = {}, was type {} ...should be type {} \\nlist[{}] check: {}\")\nelem_number_error_msg = (\"AssertionError: 'x' failed annotation check(wrong \"\n \"number of elements): value = {} \\nannotation had {} elements[{}]\")\n\ndef _check_values(value, annot, index):\n for x in value:\n check_history = ''\n check_history += str(annot1)\n assert type(x) == annot, self.list_error_msg.format(x, \n type_as_str(x), annot, index, check_history)\n\ndef _check_list_or_tuple (self, param, annot, value, check_history): \n assert isinstance(value, type(annot)), self.type_error_msg.format(value, \n type_as_str(value), type_as_str(annot))\n if (len(annot) == 1 and type(annot[0]) != list and \n type(annot[0])!= tuple and inspect.isfunction(annot[0]) == False):\n self._check_values(value, annot[0], 1)\n elif (type(annot[0]) == list or type(annot[0]) == tuple or \n inspect.isfunction(annot[0]) == True):\n for i in range(len(value)):\n self.check(param, annot[0], value[i])\n elif len(annot) > 1:\n check_history = ''\n check_history += str(annot[0])\n assert type (value[0]) == annot[0], self.list_error_msg.format(\n value[0], type_as_str(value[0]), annot[0], \n annot.index(annot[0])+1, check_history)\n check_history = ''\n check_history += str(annot)\n assert len(annot) == len(value), self.elem_number_error_msg.format(\n value, len(annot), check_history)\n self._check_values(value[1:], annot[1], 2)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:00:26.383",
"Id": "43446",
"ParentId": "43437",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:26:27.090",
"Id": "43437",
"Score": "1",
"Tags": [
"python",
"algorithm"
],
"Title": "Better implementation of checking function"
}
|
43437
|
<p>I have an array of objects. Each object has two properties, <code>id</code> and <code>quantity</code>.</p>
<p>I wrote a function to add an object to the array. But the function must check if the object already exists within the array. If it does exist the function must increment the <code>quantity</code> property. Otherwise it must add a new object.</p>
<p>Is there an idiomatic way to achieve the same result? I feel that looping over the array to compare the id of the object at index against the id passed as argument is not the right approach.</p>
<p>I am also suspicious of the <code>found = false</code> temporary variable.</p>
<p>Finally, in Ruby we are encouraged to break down long methods into smaller ones. I am aware that JavaScript is not the same, but I feel that this could be further refactored.</p>
<pre><code>addItem = function(id, items) {
var found, i;
found = false;
i = 0;
while (i < items.length) {
if (id === items[i].id) {
items[i].quantity++;
found = true;
break;
}
i++;
}
if (!found) {
return items.push({
id: id,
quantity: 1
});
}
};
</code></pre>
|
[] |
[
{
"body": "<p>Why are you using an array to do the job of a map? Use the right data structures....</p>\n\n<p>... instead, use a hashmap (associative array) of <code>[id, quantity]</code>. If <code>id</code> exists in hashmap, then increment up the value at <code>hashmap[id]</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:09:55.613",
"Id": "75088",
"Score": "2",
"body": "Brief answers which do not explain why a suggestion is better are often converted to comments on CodeReview. I have taken the liberty of expressing why this 'obvious' suggestion is better than what the oP has... please feel free to revise if you want to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:53:45.517",
"Id": "75097",
"Score": "0",
"body": "I'm not sure I understand this answer. Do you mean to create a hash or arrays? Like `{[1, 1], [2, 1]}` etc...?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T23:09:39.620",
"Id": "75104",
"Score": "0",
"body": "@JumbalayaWanton - [see this quick blog about it](http://blog.xkoder.com/2008/07/10/javascript-associative-arrays-demystified/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T23:45:14.183",
"Id": "75109",
"Score": "0",
"body": "@rolfl OK. I think I understand. I could use `{ id: [id, quantity] }`... so, assuming ids 1 and 2, with values 1 and 1 respectively, I would do `{ 1: [1, 1], 2: [2, 1] }`. Then I can check for the presence of the id in the hash... sorry to sound like a dunce, but this is new stuff for me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T02:23:08.140",
"Id": "75141",
"Score": "0",
"body": "You don't need the array as the value, just the quantity: `{ \"1\": 1, \"2\": 1, \"3\": 1, ... }`. Then your `addItem` function is simply `addItem = function(id, items) { if (items[id]) items[id]++; else items[id] = 1; }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T02:49:27.620",
"Id": "75143",
"Score": "0",
"body": "@david yes, thank you, in particular for `if (item[id])`. I had figured that out (that I did not need the array). I have other properties that I omitted; and if I wish to use them I will need an array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T07:24:05.827",
"Id": "75162",
"Score": "1",
"body": "This is essentially the same thing that I say in the bottom of my answer, where I link to [this SO question](http://stackoverflow.com/questions/3042886/set-data-structure-of-java-in-javascript-jquery) that shows how it can be done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:04:29.377",
"Id": "75208",
"Score": "0",
"body": "@JumbalayaWanton Thanks, in the end though I strongly recommend that you go with the Set/Map approach that the SO question shows."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-07T06:20:42.170",
"Id": "407916",
"Score": "0",
"body": "and what to do if you need the keys in sorted order, I am storing time series where I can get multiple updates to the same timestamp or I can get a new timestamp"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:41:29.473",
"Id": "43441",
"ParentId": "43438",
"Score": "9"
}
},
{
"body": "<p>I also don't like the <code>found</code> variable, I think you should extract that part to a <code>indexOf</code> method to return the index of the item you want to change, as you only seem to want to do <code>items[i].quantity++;</code> once. This way you can <code>return</code> the index directly. I would also use a <code>for</code> loop rather than <code>while</code>, as you're looping through a fixed number of items.</p>\n\n<pre><code>indexOf = function(id, items) {\n var i = 0;\n var len = items.length;\n for (i = 0; i < len; i++) {\n if (id === items[i].id) {\n return i;\n }\n }\n return -1;\n}\n</code></pre>\n\n<p>This way you can call your <code>indexOf</code> function from your <code>addItem</code> function and check if the return value is -1, if it is then you call <code>items.push</code>, if it's not -1 then you perform <code>items[index].quantity++;</code>.</p>\n\n<p>Instead of using an array structure, you could use more of a <code>Set</code> structure, which can be implemented in JavaScript as seen in <a href=\"https://stackoverflow.com/questions/3042886/set-data-structure-of-java-in-javascript-jquery\">this StackOverflow question</a>, assuming that your <code>id</code> can easily be converted to a string.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:01:24.257",
"Id": "75062",
"Score": "0",
"body": "Thanks. `id` is already a string. Can I ask you why a `for` loop is preferred to a `while` loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:04:55.287",
"Id": "75063",
"Score": "0",
"body": "Also, doesn't adding this method now require two loops? I would still need the loop inside the `addItem` method to increment the quantity at index, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:06:36.807",
"Id": "75064",
"Score": "0",
"body": "@JumbalayaWanton When you iterate over an array index-by-index, programmers are more used to for-loops. Technically they have about the same performance, but for-loop is more compact, as the initialization, condition-check and increment is done on the same line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:07:54.883",
"Id": "75065",
"Score": "1",
"body": "@JumbalayaWanton No, you don't need to use a loop inside `addItem`, just increment the quantity at the index stored in the `index` variable (that you retreived from the `indexOf` function), as long as that index is >= 0 (meaning that a match was found)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:41:47.263",
"Id": "43442",
"ParentId": "43438",
"Score": "7"
}
},
{
"body": "<p>I don't really like that found flag. Also using while or for loops ads a bit of extra code to write to get the value of an arrays items. I would use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\">filter</a> method for this case.</p>\n\n<pre><code>addItem = function(id, items) {\n var foundItem = items.filter(function(item) {\n return item.id === id;\n })[0];\n\n if (foundItem) {\n foundItem.quantity++;\n } else {\n //return the new length here cause that is what you did\n return items.push({\n id: id,\n quantity: 1\n });\n }\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:35:22.997",
"Id": "43451",
"ParentId": "43438",
"Score": "7"
}
},
{
"body": "<p>You don't need to use the <code>found</code> variable. Use <code>return</code> when done.</p>\n\n<p>You can also use <code>for</code> instead of <code>while</code>.</p>\n\n<pre><code>addItem = function(id, items) {\n for (var i = 0; i < items.length; i++) {\n if (id === items[i].id) {\n items[i].quantity++;\n return;\n }\n }\n return items.push({\n id: id,\n quantity: 1\n });\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-19T18:53:39.110",
"Id": "144674",
"ParentId": "43438",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "43442",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:29:45.147",
"Id": "43438",
"Score": "14",
"Tags": [
"javascript",
"array"
],
"Title": "Writing a function to add or modify an existing object inside an array"
}
|
43438
|
<p>This is a Windows service that will run on about 600 machines. It is used to track the job server that a user is connected to (pushed through some kind of load balancer, not my area). I store this information in a SQL table and want to make sure that I don't have any SQL leaks.</p>
<p>this grabs information from the users computer (username/network name/AD Name) and requests a simple XML from the Load Balancer (which points to one of the job servers, all of which have a different value in the XML node retrieved) and then sends that information to a stored procedure which updates or inserts the information into the table, none of this happens if the application is not open.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Serialization;
using System.Data.Sql;
using System.Xml.Linq;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Data.ProviderBase;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Management;
using System.Net;
using System.Threading;
namespace AppServerTracker
{
class Tracker
{
int intConnCount;
string strServer;
string strUserName;
Process[] process = Process.GetProcessesByName("MShell");
public static string strInput = "http://Website.for.load.Balancer.com";
string strErrorMSG = "No Error"; //will show that there has been no error in the table.
private static string SQLConnectionString = Properties.Resources.ConnStage;
public SqlConnection SQLConnection = new SqlConnection(SQLConnectionString);
public Tracker()
{
}
public void Main()
{
if (process.Length > 0)
{
intConnCount = process.Length;
ManagementScope ms = new ManagementScope("\\\\.\\root\\cimv2");
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_ComputerSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, query);
foreach (ManagementObject mo in searcher.Get())
{
strUserName = mo["UserName"].ToString();
}
// Remove the domain part from the username
string[] usernameParts = strUserName.Split('\\');
// The username is contained in the last string portion.
strUserName = usernameParts[usernameParts.Length - 1];
string strComputerName = Environment.MachineName;
if (isValid(strInput))
{
try
{
XmlReader xmlReader = XmlReader.Create(strInput);
using (xmlReader)
{
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Text)
{
strServer = xmlReader.Value.ToString();
strServer = strServer.Replace("\r", "");
strServer = strServer.Replace("\n", "");
strServer = strServer.Replace(" ", "");
}
}
xmlReader.Close();
}
}
catch (Exception e)
{
strServer = "Error";
strErrorMSG = "Error with the xmlReader Exception as follows: " + e.ToString();
}
finally
{
}
}
else
{
strServer = "XML-Missing";
}
try
{
using (SQLConnection)
{
SQLConnection.Open();
using (SqlCommand TrackSproc = new SqlCommand("spServerTracking", SQLConnection))
{
TrackSproc.CommandType = System.Data.CommandType.StoredProcedure;
TrackSproc.Parameters.AddWithValue("@UserName", strUserName);
TrackSproc.Parameters.AddWithValue("@Server", strServer);
TrackSproc.Parameters.AddWithValue("@ConnCount", intConnCount);
TrackSproc.Parameters.AddWithValue("@MachineName", strComputerName);
TrackSproc.Parameters.AddWithValue("@Error", strErrorMSG);
TrackSproc.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
// E-mail Exception
}
finally
{
SQLConnection.Close();
}
}
}
public bool isValid(string url)
{
HttpWebRequest urlReq;
HttpWebResponse urlRes;
try
{
urlReq = (HttpWebRequest)WebRequest.Create(url);
urlReq.Method = "HEAD";
urlReq.Timeout = 100000;
urlRes = (HttpWebResponse)urlReq.GetResponse();
urlRes.Close();
return true;
}
catch (Exception ex)
{
//Url not valid
strErrorMSG = "Exception From isValid Method. Exception to follow: " + ex.ToString();
return false;
}
}
}
}
</code></pre>
<p>Here is the Entire code for this class.</p>
<ul>
<li><p>I am assuming that some of my Using statements are extraneous. </p></li>
<li><p>assuming from comments already made that I should move the connection to the using statement and not make it accessible anywhere else because it isn't needed</p></li>
<li><p>I removed comments that were extraneous (Mentioned in some comments listed on this post)</p></li>
<li><p>I have an annoying naming scheme going on here I know, it was a bad habit I picked up from school. I will go through when I am through with this review and correct the issue, naming is the hard part.</p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:42:49.433",
"Id": "75094",
"Score": "0",
"body": "if you are going to downvote please explain why so that I can form better questions in the future"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:50:43.353",
"Id": "75096",
"Score": "0",
"body": "I downvoted because I didn't think it was enough code to be considered \"working code\": when/how is the SQLConnection created? Does it even \"work\", given that you call a method on it (i.e. Close) after it has been Disposed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T01:36:58.773",
"Id": "75128",
"Score": "0",
"body": "it runs. it has been running on about 20 machines but they are having issues with one of the SQL Servers and I wanted to make sure that this service isn't leaving a connection open into the server."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T01:41:36.353",
"Id": "75131",
"Score": "0",
"body": "Calling a method after Dispose is IMO illegal. Would you post enough code to show how often SQLConnection is being created: is it a local variable (newly recreated each time the method is called), an instance variable, a static variable ...?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T02:20:12.597",
"Id": "75139",
"Score": "1",
"body": "I don't have the Code here to post the rest of it. The connection object still exists, so it won't throw a huge fit if you try to close and already closed connection in a finally statement, so that is inefficient use of 3 lines in my code. post that as an answer. **The code works as is though**. I also agree (after seeing it posted here) that `SQLConnection` is not a good name for that connection Variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:44:02.227",
"Id": "75236",
"Score": "0",
"body": "@ChrisW I added the rest of the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T16:56:19.770",
"Id": "75273",
"Score": "1",
"body": "Therefore I removed the downvote. Thanks."
}
] |
[
{
"body": "<p>Your code is asymmetrical....</p>\n\n<p>You open your <code>SQLConnection</code> inside the using block, but you close it outside in the final block.... anyway, <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection%28v=vs.110%29.aspx\">the Close is completely redundant</a>:</p>\n\n<blockquote>\n <p>If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent.</p>\n</blockquote>\n\n<p>You are already disposing the connection inside the try block (as part of the <code>using</code>) so it is all moot.</p>\n\n<p>The SQLConnection .... how is it created??? You have it magically appearing in the <code>using</code> preamble.... need ... more ... information.</p>\n\n<p>Why do you have commented-out old code inside the block. If you are not using the <code>sqlCommand</code> variable any more (since it moved to the outer using block), then kill it, don't comment out the line.</p>\n\n<p>Without knowing more about what the stored procedure does, it is hard to determine whether there are any other problems, but, your code could simply look like (although as the program exits the using block the SQLConnection will be disposed. This is an asymmetrical situation... the connection was open when the block started, and we are not returning it open):</p>\n\n<pre><code>try\n{\n using (SQLConnection)\n {\n SQLConnection.Open();\n using (SqlCommand TrackSproc = new SqlCommand(\"spServerTracking\", SQLConnection))\n {\n TrackSproc.CommandType = System.Data.CommandType.StoredProcedure;\n TrackSproc.Parameters.AddWithValue(\"@UserName\", strUserName);\n TrackSproc.Parameters.AddWithValue(\"@Server\", strServer);\n TrackSproc.Parameters.AddWithValue(\"@ConnCount\", intConnCount);\n TrackSproc.Parameters.AddWithValue(\"@MachineName\", strComputerName);\n TrackSproc.Parameters.AddWithValue(\"@Error\", strErrorMSG);\n TrackSproc.ExecuteNonQuery();\n }\n }\n}\ncatch (Exception e)\n{\n // E-mail Exception \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:42:10.713",
"Id": "75093",
"Score": "0",
"body": "I want to make sure that no matter what that connection is closed. but I know that the using block automatically closes the Connection. I guess you could call it overkill, I don't want it to come back and bite me that there is a SQL leak. as for the commented out code, gone now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T00:02:59.223",
"Id": "75110",
"Score": "1",
"body": "Looking at the code, it appears that you may have a static `SqlConnection` somewhere, I would avoid that practice altogether and just instantiate a new one in the `using` block any time you really need it. That way you aren't just passing things around blindly and you keep track of your objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T02:23:21.093",
"Id": "75142",
"Score": "0",
"body": "there are two things that this service does, 1. gather information 2. send the information to a Sproc, that is what this portion of the code looks like, I will post the rest of my code tomorrow because hearing what you said @EvanL made me think about where I want to create this connection. the reason is that this service runs about every 10 minutes if a certain application is open on the users machine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T08:30:31.970",
"Id": "75172",
"Score": "2",
"body": "@Malachi `using` ensures that your SQLConnection will close even if an exception occures."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:27:29.177",
"Id": "43457",
"ParentId": "43439",
"Score": "6"
}
},
{
"body": "<p>It's not clear whether your SqlConnection is reused: it would be reused, if the client code (which uses Tracker) instantiates a Tracker instance and then calls Tracker.Main more than once.</p>\n\n<p>IMO no object should be reused after it has been disposed. For example <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/b1yfkh5e%28v=vs.100%29.aspx\" rel=\"nofollow\">MSDN suggests a boolean inside the class to ensure that it's only disposed once</a>. If this (legal) pattern is implemented in the SqlConnection class, it won't properly dispose objects that are re-acquired (if you reuse it) after it as been disposed.</p>\n\n<p>It's possible that in practice SqlConnection can be reused safely after it has been disposed; however in theory that is undefined behaviour. <a href=\"http://msdn.microsoft.com/en-us/library/3cc9y48w%28v=vs.110%29.aspx\" rel=\"nofollow\">MSDN for SqlConnection.Dispose</a> says,</p>\n\n<blockquote>\n <p>Call Dispose when you are finished using the Component. The Dispose method leaves the Component in an unusable state. After calling Dispose, you must release all references to the Component so the garbage collector can reclaim the memory that the Component was occupying. For more information, see Cleaning Up Unmanaged Resources and Implementing a Dispose Method.</p>\n</blockquote>\n\n<p>It would be safer if your SQLConnection object were a local variable:</p>\n\n<pre><code>using (SqlConnection sqlConnection = new SqlConnection(SQLConnectionString)) { ... }\n</code></pre>\n\n<p>If you want to keep SQLConnection as an instance member of Tracker, it would be idiomatic for Tracker to implement IDisposable, and to call SQLConnection.Dispose from your Tracker.Dispose.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T22:47:00.503",
"Id": "75351",
"Score": "0",
"body": "I think that I want to move the connection inside the using statement. I want it created and disposed right there. so the next time the class is called it creates and destroys a new connection."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T22:44:17.040",
"Id": "43559",
"ParentId": "43439",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "43457",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:37:20.157",
"Id": "43439",
"Score": "5",
"Tags": [
"c#",
"sql-server"
],
"Title": "Do I have any SQL leaks?"
}
|
43439
|
<p>I have been trying to wrap my head around all the new options in ECMAscript 6 and to do this I tried to develop a simple setup which would allow me to place absolutely positioned <code><div></code>s on the page.</p>
<p><strong>main.js:</strong></p>
<pre><code>import {Screen} from './objects/screen';
import {Position} from './objects/position';
var welcomeScreen = new Screen("Hello World");
welcomeScreen.title = "Hello World2";
welcomeScreen.position = new Position(100,100);
//Make sure the following does work if you have any advices, because there is a simple mistake which breaks this:
console.log(welcomeScreen.position.x);
var secondScreen = new Screen("Second screen", new Position(200,200));
</code></pre>
<p><strong>objects/baseobject.js:</strong></p>
<pre><code>export class BaseObject{
on(eventname,func){
if(typeof this.listeners == "undefined"){
this.listeners = {};
}
if(typeof this.listeners[eventname] == "undefined"){
this.listeners[eventname] = [];
}
this.listeners[eventname].push(func);
return this;
}
trigger(eventname){
if(this.listeners && this.listeners[eventname]){
for(let func of this.listeners[eventname]){
func.call(this);
}
}
}
}
</code></pre>
<p><strong>objects/screen.js:</strong></p>
<pre><code>import {BaseObject} from './baseobject';
// private properties:
var pp = {
position: Symbol(),
title: Symbol()
};
export class Screen extends BaseObject{
constructor(title,position = new Position(0,0)){
this.element = document.createElement("div");
this.element.classList.add("screen");
this.title = title;
this.position = position;
document.body.appendChild(this.element);
}
reposition(){
this.element.style.left = this.position.x + "px";
this.element.style.top = this.position.y + "px";
}
set position(position){
var that = this;
this[pp.position] = position;
this[pp.position].on("positionchange",function(){
that.reposition();
}).trigger("positionchange");
}
get position(){
return this[pp.position];
}
set title(value){
this[pp.title] = value;
this.element.textContent = value;
}
get title(){
return this[pp.title];
}
}
</code></pre>
<p><strong>objects/position.js:</strong></p>
<pre><code>import {BaseObject} from './baseobject';
// private properties:
var pp = {
x: Symbol(),
y: Symbol()
};
export class Position extends BaseObject{
constructor(x,y){
this[pp.x]=x;
this[pp.y]=y;
}
set x(value){
this[pp.x]=x;
super.trigger("positionchange");
}
get x(){
return this[pp.x];
}
set y(value){
this[pp.y]=y;
super.trigger("positionchange");
}
get y(){
return this[pp.y];
}
}
</code></pre>
<p>You can transpile ES6 to ES3 (I think it is 3) using <a href="https://github.com/google/traceur-compiler" rel="nofollow">(Google) Traceur</a>.</p>
<p><strong>Points of interest:</strong></p>
<ul>
<li>Are there nice ES6 language features I am forgetting?</li>
<li>Is there a nicer way to handle the 'set triggers' (<code>-></code> private property construction)?</li>
<li>Should I be using modules? Combine classes into the same files? etc.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T16:26:39.650",
"Id": "75269",
"Score": "0",
"body": "Traceur does not support private in class bodies.. https://github.com/google/traceur-compiler/issues/57 That's a bit of a let down."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:38:47.167",
"Id": "75310",
"Score": "0",
"body": "Have been reading the spec now for the last half hour and for the life of me, I can't figure out how private properties are 'supposed' to work (regardless of Traceur)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:55:46.103",
"Id": "75313",
"Score": "0",
"body": "I looked at http://wiki.ecmascript.org/doku.php?id=harmony:classes#class_body -> check out the constructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:01:54.250",
"Id": "75316",
"Score": "0",
"body": "That one is old and superseded by http://wiki.ecmascript.org/doku.php?id=strawman:maximally_minimal_classes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:02:30.470",
"Id": "75317",
"Score": "0",
"body": "And yeah, I would have loved it if they could have agreed on that one. I thought you were talking about the `new Name()` stuff which I can't figure out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:05:36.860",
"Id": "75319",
"Score": "0",
"body": "Eh, I do not like some aspects of EC6 at all.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:07:20.363",
"Id": "75320",
"Score": "0",
"body": "You are right indeed, but on the other hand, it's quite rare for companies of that magnitude trying to work together on something they can all agree on. So if they can agree on this then hopefully step by step we will not make any stupid mistakes (like so many have been made in the past already)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-27T16:54:40.310",
"Id": "248826",
"Score": "0",
"body": "One point: now we have `const` and `let` it's easier to just ditch `var` completely. `var` behaves differently to `let` in terms of destructuring, hoisting, scoping, and redeclaration of existing variables, so it can be confusing to use both `var` and `let` at the same time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-27T16:56:09.627",
"Id": "248827",
"Score": "0",
"body": "Also `Object.assign(this, { foo, bar, baz: qux })` is shorter than `this.foo = foo; this.bar = bar; this.baz = qux`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-27T17:27:40.930",
"Id": "248831",
"Score": "0",
"body": "@gcampbell As far as `Object.assign` goes, do you actually believe it's clearer than just writing it out? I don't think programmers should ever care for the length of code, it's all about clarity (and oftenshorter code is clearer, as `Let the variable with the name x be 5` is a whole lot harder to parse visually than `let x = 5`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-28T09:53:07.547",
"Id": "248968",
"Score": "0",
"body": "@DavidMulder I think it's a matter of getting used to the pattern, so when you see `Object.assign(this, {})` you know what it means. What I do is: if you're in a `constructor`, then you can use Object.assign to set many (say, 5 or more) properties on `this`. If you only have a couple of things to assign, `this.x = x; this.y = y` is shorter and definitely easier to understand."
}
] |
[
{
"body": "<p>Most interesting,</p>\n\n<ul>\n<li>In <code>BaseObject</code>, you should really have a constructor that builds <code>this.listeners</code>, it would make your code much cleaner afterwards</li>\n<li>I am not sure why your listeners are not private in <code>BaseObject</code> ?</li>\n<li>I am not sure what is more important to you, learn EC6 or position divs efficiently, if the latter is more important, than this code is massive overkill ;)</li>\n</ul>\n\n<p>If you want to avoid having a constructor for <code>BaseObject</code>, then I would re-write <code>on</code> like this:</p>\n\n<pre><code>on(eventname,func){\n this.listeners = this.listeners || [];\n this.listeners[eventname] = this.listeners[eventname] || [];\n this.listeners[eventname].push(func);\n return this;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:29:29.253",
"Id": "75307",
"Score": "0",
"body": "To point 1 I did this because this way a user doesn't need to call the super constructor on each and every object he constructs. To point 2, you are absolutely right, I forgot entirely. And lastly to point 3: It is to learn EC6 whilst making a mobile app framework slowly (this was just me trying to figure out the setup)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:44:20.820",
"Id": "75326",
"Score": "0",
"body": "Great suggestion btw@on :D"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T15:40:01.250",
"Id": "43522",
"ParentId": "43440",
"Score": "13"
}
},
{
"body": "<p>So, going to 'answer' my own question here with a nice thing I discovered since then. Might expand my answer if I discover more stuff.</p>\n\n<p>In ECMAscript 6 rather than</p>\n\n<pre><code>var that = this;\nsomething.on(\"positionchange\",function(){\n that.reposition();\n});\n</code></pre>\n\n<p>You can do</p>\n\n<pre><code>something.on(\"positionchange\",() => {\n this.reposition();\n});\n</code></pre>\n\n<p>As the <code>this</code> scope doesn't change.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T23:15:57.643",
"Id": "75514",
"Score": "0",
"body": "It's exciting though? Already with the latest additions I have stopped using typical javascript libraries for most my projects and with ES6 I can get rid of a couple I occasionally use again :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:00:34.917",
"Id": "43638",
"ParentId": "43440",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "43522",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:38:10.723",
"Id": "43440",
"Score": "15",
"Tags": [
"javascript",
"object-oriented",
"ecmascript-6"
],
"Title": "JavaScript/ECMAscript 6 classes organization"
}
|
43440
|
<p>I need some advice to see if my simple Windows socket class is good enough to be used in a simple chat application.</p>
<pre><code>#include <iostream>
#include <string>
#include <Windows.h>
class Socket
{
private:
WSADATA wsaData;
SOCKET hSocket;
sockaddr_in service;
std::string addr;
USHORT port;
int exitCode;
bool initializeWSA();
bool initializeSocket();
bool bind();
bool listen();
bool connect();
/// Modified copy constructor for *accepted* connection sockets
Socket(Socket& socket, SOCKET hSockect) : hSocket( hSockect ),
wsaData( socket.wsaData ),
service( socket.service ),
addr( socket.addr ),
port( socket.port ){}
public:
bool close();
Socket* acceptConnection();
/// Default Constructor
Socket()
{}
/// Main Constructor
Socket(std::string addr, USHORT port, bool actAsServer = false) : addr( addr ), port( port )
{
initializeWSA();
initializeSocket();
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(addr.c_str());
service.sin_port = htons(port);
if( actAsServer )
{
bind();
listen();
}
else
connect();
}
template<class T>
int recvData(T& i) {
try
{
int ret = ::recv( hSocket, reinterpret_cast<char*>(&i), 32, 0 );
if( ret == SOCKET_ERROR )
throw WSAGetLastError();
return ret;
}
catch(std::exception& e)
{
std::cerr << "Socket//error while receiving; Error#" << WSAGetLastError() << "." << std::endl;
}
}
/// recv specialization for std::string
int recvData<std::string>(std::string& i)
{
try
{
int cread;
// receive string size
long length = 0;
cread = ::recv( hSocket, reinterpret_cast<char*>(&length), sizeof( length ), 0 );
if( cread == SOCKET_ERROR )
{
throw WSAGetLastError();
return cread;
}
length = ntohl( length );
// receive string
while( 0 < length ) {
char buffer[1024];
int cread;
cread = ::recv( hSocket, buffer, min( sizeof( buffer ), length ), 0 );
if( cread == SOCKET_ERROR )
{
throw WSAGetLastError();
return cread;
}
i.append( buffer, cread );
length -= cread;
}
return i.length();
}
catch(std::exception& e)
{
std::cerr << "Socket//error while receiving; Error#" << WSAGetLastError() << "." << std::endl;
}
}
template<class T>
int sendData(T& i) {
try
{
int ret = ::send( _hSocket, reinterpret_cast<const char*>(&i), sizeof(i), 0 );
if( ret == SOCKET_ERROR )
throw WSAGetLastError();
return ret;
}
catch(std::exception& e)
{
std::cerr << "Socket//error while receiving; Error#" << WSAGetLastError() << "." << std::endl;
}
}
/// send specialization for std::string
int sendData<std::string>(std::string& i)
{
try
{
int ret;
// send length of string
long length = htonl( i.length() );
ret = ::send( hSocket, reinterpret_cast<const char*>(&length), sizeof(length), 0 );
if( ret == SOCKET_ERROR )
{
throw WSAGetLastError();
return ret;
}
// send string
ret = ::send( hSocket, i.data(), i.length(), 0 );
if( ret == SOCKET_ERROR )
{
throw WSAGetLastError();
return ret;
}
return ret;
}
catch(std::exception& e)
{
std::cerr << "Socket//error while receiving; Error#" << WSAGetLastError() << "." << std::endl;
}
}
template<>
int sendData<char*>(char*& i)
{
std::string data;
data.append( i );
sendData( data );
}
/// Default Deconstructor, cleans up socket handle
~Socket() { close(); }
};
</code></pre>
|
[] |
[
{
"body": "<p>WSAGetLastError() returns an <code>int</code>. Throwing an int is legal but not quite usual. Your <code>catch(std::exception& e)</code> statements are fairly useless, given that Win32 APIs are unlikely to throw a std::exception object.</p>\n\n<p>Your default constructor is dangerous: you can't tell if a socket instance has been properly-constructed or default-constructed. You should probably not have a default constructor. You should also probably 'delete' the default copy constructor and assignment operator.</p>\n\n<p>You didn't post source code for your bind/listen/accept/connect methods.</p>\n\n<p>You may need two addresses: one for your address (passed to bind), and another for the remote address (passed to connect or returned from accept).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:11:51.093",
"Id": "43455",
"ParentId": "43443",
"Score": "9"
}
},
{
"body": "<ul>\n<li>I'm not excited about the structure of the code. I think you're putting more in one class than is really a good idea.</li>\n</ul>\n\n<p>Just for example, I'd start with a a tiny class that does <em>nothing</em> but handle the WSAStartup/WSACleanup sequence:</p>\n\n<pre><code>class WSAUser { \n WSADATA data;\npublic:\n WSAUser() { /* call WSAStartup() */ }\n ~WSAUser() { /* call WSACleanup() */ }\n};\n</code></pre>\n\n<p>...then any other class that's going to use winsock just includes an instance of that object to ensure the WSAStartup and WSACleanup are called appropriately.</p>\n\n<ul>\n<li>Some of your comments are utterly useless, to the point that the code would be better off without them. </li>\n</ul>\n\n<p>For one example:</p>\n\n<pre><code>/// Default Constructor\nSocket()\n{}\n</code></pre>\n\n<p>Comments should <em>not</em> just repeat what's already obvious from the code itself. They should explain things that aren't obvious. For example, if you're using an unusual or non-obvious algorithm, it's often best to explain what algorithm you're using, and possibly why (especially if there's some other algorithm that's likely to <em>seem</em> like a better choice, but for non-obvious reasons isn't).</p>\n\n<ul>\n<li>Some of your code looks broken</li>\n</ul>\n\n<p>One obvious example:</p>\n\n<pre><code>template<class T>\nint recvData(T& i) {\n\n try\n {\n int ret = ::recv( hSocket, reinterpret_cast<char*>(&i), 32, 0 );\n</code></pre>\n\n<p>This is attempting to receive and write 32 bytes of data into the destination object, regardless of that object's size. If that object is smaller than 32 bytes, it'll write past its end--a buffer overrun leading to undefined behavior (not to mention probably security problems).</p>\n\n<p>If you change <code>32</code> to <code>sizeof(i)</code>, this will at least work for primitive types, but will still produce bad results for most types that contain pointers. Given that it's a template, you're currently promising that it'll work for any possible type. Although it's somewhat more advanced, you might want to do some reading about things like <code>std::enable_if</code> and type-traits that will let you specify the types for which this code is intended to work (and prevent the code from compiling if a type that won't work is passed).</p>\n\n<ul>\n<li>Misuse of exception handling</li>\n</ul>\n\n<p>At least in my opinion, you're making poor use of exception handling. For example:</p>\n\n<pre><code>try\n{\n int ret = ::recv( hSocket, reinterpret_cast<char*>(&i), 32, 0 );\n if( ret == SOCKET_ERROR )\n throw WSAGetLastError();\n return ret;\n}\ncatch(std::exception& e)\n{\n std::cerr << \"Socket//error while receiving; Error#\" << WSAGetLastError() << \".\" << std::endl;\n}\n</code></pre>\n\n<p>First of all, <code>WSAGetLastError()</code> returns an <code>int</code>, so that's the type this will potentially throw. Since <code>int</code> isn't derived from <code>std::exception</code>, there's probably no way this exception handler can ever be invoked. Even if, however, we fix that problem, this would be a poor use of exception handling. If we really want to print out a message to <code>cerr</code> in case of a problem, that can be done a lot more directly:</p>\n\n<pre><code> int ret = ::recv( hSocket, reinterpret_cast<char*>(&i), 32, 0 );\n if( ret == SOCKET_ERROR )\n std::cerr << \"Socket//error while receiving; Error#\" << WSAGetLastError() << \".\" << std::endl;\n</code></pre>\n\n<p>The real win from exception handling stems from the fact that this part of the code doesn't really know how to react to the problem appropriately. Printing to the standard error stream makes sense for some applications, but not at all for others (e.g., in a windowed application, there might not even <em>be</em> a standard error stream).</p>\n\n<p>As such, it may well make sense for this code to throw an exception here--but <em>not</em> catch it or attempt to handle it at all:</p>\n\n<pre><code>int ret = ::recv( hSocket, reinterpret_cast<char*>(&i), 32, 0 );\nif( ret == SOCKET_ERROR ) {\n std::stringstream buf;\n buf << \"Socket//error while receiving; Error#\" << WSAGetLastError();\n throw std::runtime_error(buf.str().c_str());\n}\n</code></pre>\n\n<p>...then some code at the application level will catch the exception and display the result appropriately for the type of application in which this is being used (e.g., a server might log it, a client might display it in a message box).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:36:37.283",
"Id": "43530",
"ParentId": "43443",
"Score": "11"
}
},
{
"body": "<p>Pretty sure this is not portable.</p>\n\n<pre><code> long length = htonl( i.length() );\n ret = ::send( hSocket, reinterpret_cast<const char*>(&length), sizeof(length), 0 );\n</code></pre>\n\n<p>You are obviously trying to make it portable (good). But <code>htonl()</code> does not return a <code>long</code> which is platform/compiler dependent. What you want really want is <code>uint32_t</code> (<a href=\"http://linux.die.net/man/3/htonl\" rel=\"nofollow noreferrer\">man htonl</a>).</p>\n\n<p>Anything that has Create/Destroy cycle should be wrapped in an RAII object. That way if you create it then something else fails you don't need to remember to destroy it. That is done automatically.</p>\n\n<pre><code> initializeWSA();\n initializeSocket();\n</code></pre>\n\n<p>If <code>initializeWSA()</code> which I presume calls the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms738566%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">windows socket initialization code</a> also has a counterpart to shut it down. So if <code>initializeSocket()</code> fails the <code>WSAData</code> will be correctly re-claimed.</p>\n\n<p>I think you are trying to cram too much functionality into a single class.</p>\n\n<pre><code> if( actAsServer )\n {\n bind();\n listen();\n }\n else\n connect();\n</code></pre>\n\n<p>Why not have a class that is explicitly designed for server end and one designed for the client end. Then can share a lot of common code in a base class. But you don't need to mix them.</p>\n\n<p>This may return data but it may not be the whole message. Or it may be the combination of several messages.</p>\n\n<pre><code> long length = 0;\n cread = ::recv( hSocket, reinterpret_cast<char*>(&length), sizeof( length ), 0 );\n</code></pre>\n\n<p>But there is a distinct possibility that it could potentially return 3 bytes (not the 4 you need). If so you need to continue reading until you get the 4 bytes you need (sorry <code>sizeof(length)</code>. </p>\n\n<p>So you should wrap your <code>::recv</code> into a loop and make sure you read as much as you actually need before continuing (or specify MSG_WAITALL) in the configuration. </p>\n\n<p>Also not all errors are fatal. <code>EINTR</code> just means an interrupt was seen (so if a timer goes off or something like that). If you don't care about the interrupt you can just start the loop again.</p>\n\n<p>Conversely <code>::send()</code> may not always send all the data.</p>\n\n<pre><code> ret = ::send( hSocket, reinterpret_cast<const char*>(&length), sizeof(length), 0 );\n</code></pre>\n\n<p>You may want to keep track of how much is sent and add it up until all the data has been sent across the socket. Again not all error are fatal.</p>\n\n<p>Do you really want the copy constructor to copy WSAData?</p>\n\n<pre><code>/// Modified copy constructor for *accepted* connection sockets\nSocket(Socket& socket, SOCKET hSockect) : hSocket( hSockect ), \n wsaData( socket.wsaData ),\n service( socket.service ),\n addr( socket.addr ),\n port( socket.port ){}\n</code></pre>\n\n<p>Does the destructor not destroy something in wsaData (hard to tell and I am not a windows expert) in which case it may be done twice if you are not careful.</p>\n\n<p>Two points here: 1) Indentation. Make it obvious. 2) I prefer to wrap conditionals in curly braces. <code>{}</code>. On older compilers they implemented throw with a macro and macros are prone to errors if they were not written correctly. My point here is that you can always tells if a what you write is a single statement or multiple statements (hidden in a macro function). If its multiple statments then this type of if will break. Prefer to use '{}' to make it explicit.</p>\n\n<pre><code> if( ret == SOCKET_ERROR )\n\n throw WSAGetLastError();\n</code></pre>\n\n<p>This try block only contains a C function <code>::recv</code> so no exceptions are going to be emitted from that. So the only exception here is the one you throw (which does not match the catch).</p>\n\n<pre><code> try\n {\n int ret = ::recv( hSocket, reinterpret_cast<char*>(&i), 32, 0 );\n if( ret == SOCKET_ERROR )\n\n throw WSAGetLastError();\n\n return ret;\n }\n catch(std::exception& e)\n {\n std::cerr << \"Socket//error while receiving; Error#\" << WSAGetLastError() << \".\" << std::endl;\n }\n</code></pre>\n\n<p>Also exceptins are great for passing errors across interface boundries (ie out of public methods). But internally within your code using error codes is fine (becuase the library is self contained you can make sure you check the error codes from each method call).</p>\n\n<p>see: <a href=\"https://softwareengineering.stackexchange.com/questions/118142/what-is-a-good-number-of-exceptions-to-implement-for-my-library/118187#118187\">https://softwareengineering.stackexchange.com/questions/118142/what-is-a-good-number-of-exceptions-to-implement-for-my-library/118187#118187</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:54:44.993",
"Id": "43539",
"ParentId": "43443",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "43539",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:42:09.063",
"Id": "43443",
"Score": "11",
"Tags": [
"c++",
"windows",
"socket"
],
"Title": "Windows socket class"
}
|
43443
|
<p>I will preface by saying that this data set is much larger than what I have here. I'm having to loop through an XML file to get data and display it on a site with jQuery. I have to use jQuery because I'm working within a framework that I can't edit so I'm having to manipulate the data after the fact. This is causing the site I'm working on to slow significantly. I know that that's just the nature of what I'm doing but I'm running a loop inside a loop which I know can be pretty slow, especially when deal with 1,000 entries in an XML file. I'm curious if there's a way for me to do this in a more efficient way.</p>
<p>I'm basically looping through the data and on each iteration I'm grabbing that entries attributes and then having to loop through all the data within that iteration to compare the data with the rest of the data in the file. It seems like there's a better way to do this but I can't seem to figure it out.</p>
<p>If you need more clarification, let me know and I will provide it. I've pared the data down quite a bit so it's easier to handle and look at.</p>
<p>My XML is set up like this:</p>
<pre class="lang-xml prettyprint-override"><code><Data>
<Category>
<category_number>1</category_number>
<parent_number>4</parent_number>
<category_name>This is a test Category</category_name>
</Category>
<Category>
<category_number>2</category_number>
<parent_number>3</parent_number>
<category_name>This is another test Category</category_name>
</Category>
<Category>
<category_number>3</category_number>
<parent_number>4</parent_number>
<category_name>This is yet another test Category</category_name>
</Category>
</Data>
</code></pre>
<p>My HTML is set up like this:</p>
<pre class="lang-html prettyprint-override"><code><!--THIS WOULD BE THE UNORDERED LIST FOR CATEGORY 4; IT HAS A CLASS OF '4'-->
<ul class="4">
<li>This is a parent category. Category 4. A new list will be put in here with this categories child categories.</li>
</ul>
<ul class="2">
<li>This is a parent category. Category 2. A new list will be put in here with this categories child categories.</li>
</ul>
</code></pre>
<p>My jQuery is as follows:</p>
<pre class="lang-js prettyprint-override"><code>$.ajax({
url: "/sample_url.xml",
type: "GET",
dataType: "html",
success: function(data) {
var xml = $.parseXML(data);
$(xml).find('category_number').each(function(){
category_number = $(this).text();
var parent_number = $(this).parent().find('parent_number').text();
var category_name = $(this).parent().find('category_name').text();
var sub_array = [];
//GET CATEGORIES SUB-CATEGORIES
$(this).closest('Data').find('parent_number').each(function(){
if($(this).text()==category_number){
var category_id = $(this).parent().find('category_number').text();
sub_array.push('<li>' + $(this).parent().find('category_name').text() + '</li>');
}
});
$('ul#category_list').each(function(){
if($(this).attr('class')==parent_number){
$(this).append('<li><ul id="' + category_number + '"></ul></li>');
$('ul#' + category_number).html(sub_array.join(""));
}
});
});
}
});
</code></pre>
|
[] |
[
{
"body": "<p>Don't use selector all the time. DOM locating waste most resource and time. as less selector as possible. use variable cache the jQuery object.</p>\n\n<p>Data is look like a root: </p>\n\n<pre><code>var $data = $(\"Data\");\n</code></pre>\n\n<p>Rather than parse start with \"category_number\", why not start with \"Category\"</p>\n\n<pre><code>$(xml).find('Category').each(function(){\n //do something.\n});\n</code></pre>\n\n<p>Also, you could use <code>filter()</code> or <code>map()</code> to reduce the code:</p>\n\n<pre><code>// filter() example\nfunction getSubCategory(pid){\n $catalist = $data.find(\"Category\").filter(function(){\n return $(this).find(\"parent_number\").text()==pid;\n })\n\n return $catalist;\n\n}\n\n// map() example\nvar subCatString=$subCatList.map(function(sum,item){\n var $subCat=$(item) ;\n var vcum=$subCat.find(\"category_number\").text();\n return '<li>'+vcum+'</li>'\n}).get().join();\n</code></pre>\n\n<p>Combine them together (HTML, see this <a href=\"http://jsfiddle.net/PyLQa/3/\" rel=\"nofollow\">JSFiddle</a>, don't use AJAX): </p>\n\n<pre><code>var $xml= $(\"xml\");\nvar $data=$xml.find(\"Data\");\nvar $displayList=$(\"ul#category_list\");\n\n\n$xml.find(\"Category\").each(function(){\n var $catageory=$(this);\n var $cnum=$catageory.find(\"category_number\");\n var $pnum=$catageory.find(\"parent_number\");\n var $cname=$catageory.find(\"category_name\"); \n\n var $subCatList=getSubCategory($cnum.text());\n var subCatString=$subCatList.map(function(sum,item){\n var $subCat=$(item) ;\n var vcum=$subCat.find(\"category_number\").text();\n return '<li>'+vcum+'</li>'\n }).get().join();\n\n\n var $ul=$(\"<ul/>\",{class:$cnum.text()});\n\n $ul.append(subCatString);\n\n $displayList.append($(\"<li/>\").html($ul));\n\n\n\n});\n\n\nfunction getSubCategory(pid){\n $catalist = $data.find(\"Category\").filter(function(){\n return $(this).find(\"parent_number\").text()==pid;\n })\n\n return $catalist;\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T13:15:52.647",
"Id": "75996",
"Score": "0",
"body": "This all looks great. My biggest question though, is you say don't use AJAX. My XML is it's own file that is being referenced by the jQuery. How would I import that data into the page without using AJAX?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T00:24:29.963",
"Id": "76172",
"Score": "0",
"body": "@MxmastaMills sorry for misunderstand. it is that my example is not using Ajax, because I use jsfiddle which is no point to use ajax. To save the time, I use mix xml and html in jsfiddle as document example. you may just adopt my code into your ajax code, that all."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T04:55:46.980",
"Id": "43482",
"ParentId": "43449",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "43482",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:26:46.943",
"Id": "43449",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"parsing",
"xml",
"ajax"
],
"Title": "Parsing XML data to be put onto a site with jQuery"
}
|
43449
|
<p>I've been going through LPHW (learn Python the hard way) lessons and I am now at exercise No36 where I have to create a similar game. </p>
<p>Could you please review it and point out beginner mistakes?</p>
<pre><code>from sys import exit
inventory = []
ground = ['Bones', "Commander's Key", 'Security Code', 'Shipment Report']
turrets_active = True
rats_hungry = True
hatch_active = True
def check_inventory(inv):
print
print ">The contents of your inventory are:"
if len(inv) > 0:
for counter, content in enumerate(inv):
# This will look like " 0 . Bones " and then " 1 . Security Code " etc
print ">", counter, ".", content
else:
print
print ">Your inventory is empty"
def report_in_inventory():
if 'Shipment Report' in inventory:
print
print "You map the coordinates from the report to your PIP-BOY"
print "Fort Everlast awaits!"
print "CONGRATULATIONS! YOU COMPLETED THE GAME!"
else:
print
print "You wander the desert for the rest the day..."
exit("But deathclaws get you near Broken Hills...")
def take_item(item):
if item in ground:
inventory.append(item)
print
print ">", item, "taken."
ground.remove(item)
else:
print
print ">You check same spots all over again"
print ">but there is nothing to be found"
print
def surroundings_text():
print """
You find yourself in a valley surrounded by the mountains.
You are in a field of the old pre-war satellite dishes
that glare at you with their eyeless faces.
In front of you is an entrance to the Underground Control Complex
that was used to operate the satellite array.
By looks of it the door is guarded by automated Gatling turrets
that will tear you to shreds.
On your right you see a small passage between the mountains
On your left there is an old maintenance hatch surrounded by a fence.
"""
surroundings()
def surroundings():
print
print "1. Use Underground Control Complex entrance"
print "2. Check the old maintenance hatch"
print "3. Check the small passage"
print "4. Go back to the desert. What awaits you there?"
print "5. See if you can find something useful around..."
print "6. Check your inventory."
print
choice = raw_input(">What do you do? ")
if choice == "1" and turrets_active:
print
print "Last thing you hear is a 'swoosh' of the turrets"
exit("You are torn to shreds. Your remains later eaten by rats")
elif choice == "1" and turrets_active == False:
me_text()
elif choice == "2" and hatch_active:
if 'Bones' in inventory:
print "You hop over the fence and try the hatch."
print "It's rusted shut but you are strong enough to open it."
print
print "You get engulfed by the smell from the tunnels below"
print "but you decide to descend and check it out anyway."
mt_text()
else:
print
print "You should probably check the surroundings first"
surroundings()
elif choice == "2" and hatch_active == False:
print "The hatch is a toast after your last visit. You turn back"
surroundings()
elif choice == "3":
print "You squeeze through the narrow passage..."
ts_text()
elif choice == "4":
report_in_inventory()
elif choice == "5":
print
print "You roam around the dishes for awhile staying as far away"
print "as possible from the Gatling turrets near the Main Entrance.."
print "You think you see something behind one of the bigger rocks"
print "and you go check it out..."
take_item('Bones')
surroundings()
print
elif choice == "6":
check_inventory(inventory)
surroundings()
else:
print
print "Please use numbers 1, 2, 3, 4, 5, 6"
surroundings()
def mt_text():
print """
When you reach the bottom you see huge pack of molerats
that will surely tear you to shreds...
Not so far from the place where the pack is nested you see
a glimmering light.
But you have to deal with those molerats first, don't you?
Luckily you found those bones on the surface...
"""
maintenance_tunnels()
def maintenance_tunnels():
global rats_hungry
global hatch_active
print
print "1. Attack the molerats with largest bone you found on the surface"
print "2. Go towards the light"
print "3. Use the bones as bait."
print "4. Go back to the surface"
print "5. Check your inventory"
print
choice = raw_input(">What do you do? ")
if choice == "1" and rats_hungry:
print
print "You run towards the molerats and try to hit the largest one!"
print "You miss!"
print "Molerats jump on you and tear you to shreds"
exit("Last thing you remember is the crunch of your testicles")
elif choice == "2" and rats_hungry:
print
print "You try to sneak around the molerat pack"
print "But the largest rat spots you and attacks with whole horde."
exit("Last thing you remember is the crunch of your testicles")
elif choice == "2" and rats_hungry == False:
print
print "You silently move out of the alcove you've been hiding in"
print "and run towards the light at the end of the tunnel..."
print "While you get closer and closer you hear the molerats"
print "finishing their meal and crunching on something metallic."
print "Few seconds later the ladder that you used to get down"
print "collapses along with the ceiling of the tunnel."
hatch_active = False
print
print "You reach the door handle under the glimmering light"
print "just in time to save your life. The door has an ID on it:"
print "Array Control Center. AUTHORIZED PERSONNEL ONLY"
print "You enter the unknown..."
uc_text()
elif choice == "3" and rats_hungry:
print
print "You throw the bones behind you and hide in the nearest alcove."
inventory.remove('Bones')
rats_hungry = False
maintenance_tunnels()
elif choice == "3" and rats_hungry == False:
print
print "You don't have anything else to feed the rats."
print "You'd better hurry out of your hiding place..."
maintenance_tunnels()
elif choice == "4" and rats_hungry:
print
print "You climb back to the surface"
surroundings()
elif choice == "4" and rats_hungry == False:
print
print "Molerats now block your way back. It's too late"
maintenance_tunnels()
elif choice == "5":
check_inventory(inventory)
maintenance_tunnels()
else:
print
print "Please use numbers 1, 2, 3, 4, 5"
maintenance_tunnels()
def uc_text():
print"""
You light up your old lantern and find yourself in a catacomb of
corridors and doors. Some of the corridors are collapsed and
some doors are blocked. The overall view is very much
depressing. You roam this shallow installation until you think
that it's time to decide which one of the more or less working
doors to check...
"""
underground_complex()
def underground_complex():
print
print "1. Check the Armory door"
print "2. Check the Commander's Quarters door"
print "3. Check the TEST SITE Terrace door"
print "4. Check Main Entrance door"
print "5. See if you can find something useful around..."
print "6. Check your inventory."
print
choice = raw_input(">What do you do? ")
if choice == "1":
if 'Security Code' in inventory:
print
print "You input the security code into the slowly blinking pad."
print "The yellow light above the door starts flashing"
print "and it slowly opens with a shrieking creak."
armory_text()
else:
print
print "You see the code pad on the right from the door"
print "but there is no code scratched or written anywhere nearby."
print "You should probably check around the Complex thoroughly..."
underground_complex()
elif choice == "2":
if "Commander's Key" in inventory:
print
print "You slide the keycard into the socket. Something clicks"
print "and the door silently unlocks. Judging by the door sound"
print "there is a chance that nobody's been here after the war..."
cq_text()
else:
print
print "The door is locked but you see a keycard slot."
print "You wonder if you should check around the Complex..."
print "If this place hasn't been looted you can probably"
print "find that keycard on one of the bodies around."
underground_complex()
elif choice == "3":
print
print "The door is rusted shut and cannot be opened"
underground_complex()
elif choice == "4":
print
print "You hit the switch on a console and a large round door"
print "slowly rolls aside..."
me_text()
elif choice == "5":
print
print "As you rummage around the various rooms and cabinets you find"
print "a small piece of fragile paper with some numbers on it."
print "What would that be? A code?"
take_item('Security Code')
underground_complex()
elif choice == "6":
check_inventory(inventory)
underground_complex()
else:
print
print "Please use numbers 1, 2, 3, 4, 5, 6"
underground_complex()
def armory_text():
print """
As you enter the Armory you notice that all the weapon lockers are
(of course) already cleaned out.
In the corner you see a skeleton dressed in high-ranking uniform.
Maybe he was a commander?
"""
armory()
def armory():
print
print "1. See if you can find something useful on the skeleton..."
print "2. Go back."
print "3. Check your inventory."
print
choice = raw_input(">What do you do? ")
if choice == "1":
print
print "You approach the skeleton and notice that its skull is blown"
print "to pieces. The guy probably shot himself. Poor fella..."
print "As you rummage through his pockets you find a keycard."
print "Better check those other doors in the Complex to see"
print "where this can be applied..."
take_item("Commander's Key")
armory()
elif choice == "2":
print
print "You turn around and go back to the Underground Complex"
underground_complex()
elif choice == "3":
check_inventory(inventory)
armory()
else:
print
print "Please use numbers 1, 2, 3"
armory()
def ts_text():
print """
Far on the horizon you see a large crater formed by a nuclear blast.
It is black as night and you feel goosebumps running all over your neck.
So many lives taken during this war. War never changes...
On your left you notice a small terrace overlooking the mountains
and the valley below.
Can it be another entrance to the Complex? Better watch for turrets."
"""
test_site()
def test_site():
print
print "1. Approach the terrace."
print "2. See if you can find something useful around..."
print "3. Go back to Satellite array."
print "4. Check your inventory."
print
choice = raw_input(">What do you do? ")
if choice == "1" and turrets_active:
print
print "As you approach the terrace you see the Gatling Turrets"
print "slowly rising from the mountain slopes..."
print "The moment you understand that it is too late to run"
exit("you are torn to shreds by their fire.")
elif choice == "1" and not turrets_active:
print
print "You spent a few minutes climbing but finally reach the terrace."
print "The view to the valley is magnificent but depressing"
print "at the same time. Semi-destroyed satellite array to your right"
print "and nuclear test site that lays in front of your eyes remind"
print "of the war that destroyed us all..."
print "You try the door but its rusted shut so you climb back down."
test_site()
elif choice == "2":
take_item("None")
test_site()
elif choice == "3":
print
print "You turn around and go back to the Satellite Array"
surroundings()
elif choice == "4":
check_inventory(inventory)
test_site()
else:
print
print "Please use numbers 1, 2, 3"
test_site()
def cq_text():
print """
As you enter the room you feel a certain amount of homesickness swept
over you. Dusty but yet neatly placed furniture reminds you of your
hometown of Arroyo that you left behind so long ago.
A small green light slowly blinking on a miraculously working console
catches your attention...
"""
commander_quarters()
def commander_quarters():
print
print "1. Check the console"
print "2. Go back."
print "3. Check your inventory."
print
choice = raw_input(">What do you do? ")
if choice == "1":
print
print "You check the console and print out a single piece of"
print "information that is available. Everything else (whatever that"
print "was) is deleted wiped clean off the tape-drive."
take_item("Shipment Report")
print
print "When you look at what came out of the old matrix printer"
print "you see a shipment report of a crate of highly valuable"
print "Plasma Rifles to a place yet unknown to you - Fort Everlast."
print
commander_quarters()
elif choice == "2":
print
print "You turn around and go back to the Underground Complex"
underground_complex()
elif choice == "3":
check_inventory(inventory)
commander_quarters()
else:
print
print "Please use numbers 1, 2, 3"
commander_quarters()
def me_text():
print """
You find yourself at the main entrance to the
Underground Complex. You see a probably working terminal
behind one of the Gatling Turrets and a console
near the large round door leading inside.
"""
main_entrance()
def main_entrance():
global turrets_active
print
print "1. Check the Terminal"
print "2. Go to satellite array."
print "3. Go to Underground Complex."
print "4. Check your inventory."
print
choice = raw_input(">What do you do? ")
if choice == "1" and turrets_active:
print
print "You approach the blinking terminal and hit the red button."
print "Loud shriek fills the air but fells silent after a while."
print "The lonely message pops on the screen."
print "TURRETS DEACTIVATED. PLEASE PUT HUMAN SENTRIES ON GUARD"
turrets_active = False
main_entrance()
elif choice == "1" and not turrets_active:
print
print "The terminal seems dead. There is nothing for you here."
main_entrance()
elif choice == "2" and turrets_active:
print
print "As you move down the slope towards the satellite array"
print "you hear a smooth 'whoosh'. Before you realize it is too late"
exit("and you are torn to shreds by Gatling Turrets.")
elif choice == "2" and not turrets_active:
print
print "You slide down the slope towards the satellite array."
surroundings()
elif choice == "3":
print
print "You hit the switch on a console and a large round door"
print "slowly rolls aside..."
underground_complex()
elif choice == "4":
check_inventory(inventory)
main_entrance()
else:
print
print "Please use numbers 1, 2, 3, 4"
main_entrance()
print
surroundings_text()
</code></pre>
|
[] |
[
{
"body": "<p>I would be inclined to reduce some of the duplication using dictionaries and functions, if not classes. </p>\n\n<p>For example, you repeatedly take user input from defined choices, which could all be done by:</p>\n\n<pre><code>def get_input(choices):\n for choice in sorted(choices):\n print(\"{0}. {1}\".format(choice, choices[choice]))\n while True:\n try:\n ui = int(raw_input(\"Choose an action: \"))\n except ValueError:\n print(\"Please enter a number.\")\n else:\n if ui in choices:\n return ui\n print(\"Not a valid action.\")\n</code></pre>\n\n<p>You can then use this function as:</p>\n\n<pre><code>action = get_input({1: \"See if you can find something useful on the skeleton...\",\n 2: \"Go back.\",\n 3: \"Check your inventory.\"})\n</code></pre>\n\n<p>And guarantee a valid choice in the response. Each set of choices is now defined by a simple dictionary and the validation is handled in one place. </p>\n\n<p>You could also hold the definitions of what to do for each choice in a dictionary, rather than the <code>if: elif:</code> blocks, although you will need to think about how to represent your choices' inventory items needed or global state (e.g. turrets active).</p>\n\n<p>Similarly, you can handle moving around your world by having each choice return the next room to go to, then store all room functions in a dictionary:</p>\n\n<pre><code>rooms = {\"tower\": enter_tower, \"bunker\": enter_bunker, ...}\n</code></pre>\n\n<p>You could then finish by returning <code>None</code>, and have an overall game loop:</p>\n\n<pre><code>room = \"tower\" # first room \nwhile room is not None: # game loop\n room = rooms[room]() # call function and get next room\nprint(\"Game over.\") # end of the game\n</code></pre>\n\n<p>This avoids your current recursive calling. </p>\n\n<p>Finally, the <code>global</code> is a bad sign. Instead, you could have a <code>World</code> object or dictionary that holds this state:</p>\n\n<pre><code>world = {\"rats hungry\": True, \"turrets active\": False,\n \"ground\" [\"bones\", \"security code\", ...], \n \"inventory\": [], ...}\n</code></pre>\n\n<p>and pass it around explicitly:</p>\n\n<pre><code>room = rooms[room](world)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T08:17:51.133",
"Id": "76421",
"Score": "0",
"body": "Thank you for going through my wall of text. Im fairly new to python but what you are saying makes perfect sense. I will rework it and post an update as soon as I get to it. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T22:57:44.973",
"Id": "44111",
"ParentId": "43450",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "44111",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:34:15.980",
"Id": "43450",
"Score": "5",
"Tags": [
"python",
"beginner",
"game",
"homework",
"python-2.x"
],
"Title": "Fallout-style homework game"
}
|
43450
|
<p>I am initializing a PHP array as follows</p>
<pre><code>$newArray = array();
$newArray['2014-13-03']['SMD']['IMPR'] = 5;
$newArray['2014-13-03']['SMD']['CLICK'] = 10;
</code></pre>
<p>I just wanted to check if you think this is a wrong way to insert data into an array. It is working just fine, but I still wanted to check from an optimization standpoint.</p>
|
[] |
[
{
"body": "<p>I would do the definition inline with the declaration:</p>\n\n<pre><code>$newArray = array(\n '2014-13-03' => array(\n 'SMD' => array(\n 'IMPR' => 10,\n 'CLICK' => 10\n )\n )\n);\n</code></pre>\n\n<p>If you wanted to lean towards the more compact side, you could achieve almost the same clarity with something like:</p>\n\n<pre><code>$newArray = array('2014-13-03' => array('SMD' => array(\n 'IMPR' => 10,\n 'CLICK' => 10\n)));\n</code></pre>\n\n<p>In addition to a bit more clarity (at least in my opinion), this has the advantage of it being more difficult to accidentally mess up the data. Since the parents keys aren't repeated, the keys are either right for both leaves or wrong for both leaves. That should help prevent a rather odd potential bug.</p>\n\n<hr>\n\n<p>By the way, that's a rather odd data structure unless this is just an example. Three levels deep for such a sparse data set is kind of excessive.</p>\n\n<hr>\n\n<p>From an optimization standpoint, it's not going to matter how you do it. You're in the realm of microseconds at most. Really it's just the parser that's going to differ on it anyway since I would imagine the parser will change any reasonable incantation of this to the same instructions (I have not confirmed that though).</p>\n\n<hr>\n\n<p>By the way, <code>$newArray</code> is a terrible variable name in anything but example code. If your real code is using that, change it to a descriptive name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T23:17:47.853",
"Id": "75107",
"Score": "0",
"body": "This is just an example. What I wanted to know is is there anything wrong in setting the multi-dimensional array the way I have done?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T23:21:55.300",
"Id": "75108",
"Score": "0",
"body": "@user2884319 No, there's nothing wrong with it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:06:33.280",
"Id": "43454",
"ParentId": "43452",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "43454",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T21:47:00.403",
"Id": "43452",
"Score": "5",
"Tags": [
"php",
"array"
],
"Title": "Multidimentional array initialization"
}
|
43452
|
<p>I designed a program that calculates the square root of a number using Newton's method of approximation that consists of taking a guess (<code>g</code>) and improving it (<code>improved_guess = (x/g + g)/2</code>) until you can't improve it anymore:</p>
<pre><code>#include <iostream>
#include <iomanip>
using namespace std;
template <class Y>
Y sqrt (Y x)
{
double g (1), ng;
while (true) {
ng = (x/g + g)/2;
if (g != ng) g = ng;
else if (g == ng) break;
}
return g;
}
void menu()
{
double x, g;
string a = "";
do {
cout << "Enter a number to get the sqrt of: ";
cin >> x;
g = sqrt(x);
cout << "The result is: " << setprecision(100) << g << endl;
cout << "Result^2 = " << setprecision(100) << g*g << endl;
cout << "\nDo it again ? <y/n> ";
cin >> a;
cout << endl;
} while (a == "y");
}
int main()
{
menu();
return 0;
}
</code></pre>
<p>Can you see any way to improve this ? Like in the "do it again" part, I just couldn't use y/n...</p>
|
[] |
[
{
"body": "<p>Looks fairly good over all, but a few things jumped out at me. Please note that the stylistic ones are opinion based.</p>\n\n<hr>\n\n<p>Make sure you don't get into a habit of <code>using namespace std;</code>. It's acceptable in some places, but it can form a bad habit very easily. Your code is a perfect example of this since your sqrt will conflict with <code>std::sqrt</code> if you include <code>cmath</code> or <code>math.h</code>. A lot more discussion on the matter can be found <a href=\"https://stackoverflow.com/q/1452721/567864\">here</a>.</p>\n\n<hr>\n\n<p>If you're not going to put your function in a namespace, I would avoid calling it <code>sqrt</code>. In fact, unless you have a compelling reason, it's best to avoid names from the standard library in general.</p>\n\n<hr>\n\n<p>I would leave a blank space after your header lines. The typical format is:</p>\n\n<pre><code>#include \"local1.h\"\n#include \"local2.h\"\n\n#include <blah1>\n#include <blah2>\n\n// stuff here\n</code></pre>\n\n<p>Also, I would consider alphabetizing the headers. When there's a long list of headers, it can help make quick mental scanning easier.</p>\n\n<hr>\n\n<p>You forgot to include <code>string</code>.</p>\n\n<hr>\n\n<p>Your <code>c</code> variable in <code>sqrt</code> isn't used. </p>\n\n<hr>\n\n<p>I don't like the use of the constructor form initialization of primitives. I would stick with plain old equals.</p>\n\n<p>Also, it's fairly typical to define one variable per line when values are being assigned during declaration.</p>\n\n<pre><code>double g = 1;\ndouble ng;\n</code></pre>\n\n<hr>\n\n<p>I'm not quite sure why <code>sqrt</code> is templated. By using doubles internally, you've basically restricted it to doubles. If you're going to make it templated, use the templated type all the way through.</p>\n\n<hr>\n\n<p><code>Y</code> is a bad typename. Use something more descriptive like <code>FloatingPoint</code> or <code>Number</code>.</p>\n\n<hr>\n\n<p>Consider taking <code>x</code> by const reference in <code>sqrt</code>. If an expensive-to-copy class is used as the template parameter, you're causing an unnecessary copy since <code>x</code> is never modified.</p>\n\n<hr>\n\n<p>In menu, you should check if reading in a double was successful:</p>\n\n<pre><code>if (std::cin >> x) {\n // Use x\n} else {\n std::cerr << \"Invalid value provided\\n\";\n}\n</code></pre>\n\n<hr>\n\n<p>Try to declare variables as close to usage as possible. For example, your <code>g = sqrt(x);</code> could be <code>double g = sqrt(x);</code>. Seeing a giant list of variables declared at the top of a function is overwhelming. If they're defined where they're used, it's much simpler to see their relation to the overall code.</p>\n\n<hr>\n\n<p>If you're using C++11, avoiding naming types except where necessary. This will ease future change of type. For example, imagine that at some point you want to use some kind of Complex class instead of a built in double. If you only name the type for the input <code>x</code> and use auto else where, you'll only have to change one thing (provided the class overrode <code>operator>></code> for <code>istream</code>s). You can read more about this <a href=\"http://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<hr>\n\n<p>When it's not possible for the program to return a non-0 exit code, I like to omit it. This signifies at a simple glance that the program always exits with a success code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T11:42:00.287",
"Id": "75194",
"Score": "0",
"body": "Great ! I think the `using namespace std;` is safer to put inside the function scope right ? so that way it affects just the code inside that function (which is better than the full code) and you can manage better if you got some problem later on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T16:46:11.820",
"Id": "75271",
"Score": "0",
"body": "@matheussilvapb Correct. It's a lot easier to manage name conflicts in the relatively small scope of a function. Some people also use it in implementation files, which in a lot of cases is fine, but as shown here can still cause problems. I tend to use name-wise importing rather than entire namespaces. For example, you can do \"using std::cout;\" at the top of a function and it will be available as \"cout\". Explicit importing like that makes you much more aware of potential conflicts (and it drags way less into the global namespace)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:48:28.600",
"Id": "43459",
"ParentId": "43456",
"Score": "5"
}
},
{
"body": "<p>I'm not enthused about the your <code>sqrt</code> template.</p>\n\n<p>First of all, there may easily be inputs for which it won't terminate--once you get really close to an answer, Newton's method can sometimes \"oscillate\", switching between a couple of different values that are nearly (but not quite) equal. You rarely want to compare floating point numbers for strict equality anyway--you normally want to test whether the difference is below some delta.</p>\n\n<p>Second, I <em>prefer</em> to avoid the <code>while (true) ... if(something) break;</code> structure when at all reasonable (and I think it is here).</p>\n\n<p>Finally, <code>1</code> is rarely a good choice for your first guess at the root. You'll almost certainly gain at least a little speed by using a better initial guess.</p>\n\n<pre><code>double my_sqrt(double x) {\n static const double delta =.00001;\n double g = x / 2;\n double ng;\n while (fabs(g - (ng = (x / g + g) / 2)) > delta)\n g = ng;\n return g;\n}\n</code></pre>\n\n<p>Note that I haven't tried to use a particularly good value for <code>delta</code> here. It's adequate for numbers in the vicinity of 1, but if (for example) you were trying to find the square root of 1e-100, it would clearly be <em>seriously</em> wrong. For real use, you'd typically want to estimate the magnitude of the result, then choose delta to be small enough to give (for example) 10 decimal digits of precision.</p>\n\n<p>Two other minor points:</p>\n\n<ol>\n<li><p>asking for a precision of 100 isn't likely to accomplish much with most computers. You'd need some sort of extended precision library to get even close to that precision on most computers (around 20 digits is the limit with most typical hardware).</p></li>\n<li><p>While it's pretty common to try to stuff too much functionality into <code>main</code>, in this case I think you've gone a little too far the opposite direction. For most practical purposes, your <code>main</code> does nothing. This mostly requires the reader to chase through an extra level of function calls, without accomplishing anything really useful.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T06:25:58.420",
"Id": "43488",
"ParentId": "43456",
"Score": "3"
}
},
{
"body": "<p>Good comments have been posted already but no one explicitly pointed out that the <code>if (g == ng)</code> doesnt bring anything in the function and :</p>\n\n<pre><code>while (true) {\n double ng = (x/g + g)/2;\n if (g != ng) g = ng;\n else if (g == ng) break;\n}\nreturn g;\n</code></pre>\n\n<p>can be written :</p>\n\n<pre><code>while (true) {\n double ng = (x/g + g)/2;\n if (g != ng)\n g = ng;\n else\n break;\n}\nreturn g;\n</code></pre>\n\n<p>or even better :</p>\n\n<pre><code>double g (1);\nwhile (true) {\n double ng = (x/g + g)/2;\n if (g == ng)\n break;\n g = ng;\n}\nreturn g;\n</code></pre>\n\n<p>which can just as easily be written :</p>\n\n<pre><code>while (true) {\n double ng = (x/g + g)/2;\n if (g == ng)\n return g;\n g = ng;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T11:44:35.377",
"Id": "75195",
"Score": "0",
"body": "I'm a little methodical, and I'm just coing with c++ for a week or 2, so when I write code I like to explicit he way the program thinks, but anyway I'm sure it could be faster without the `else if (g == ng);`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T11:48:43.807",
"Id": "75197",
"Score": "2",
"body": "The program itself will probably not be faster because any decent compiler would have figured out on its own that there's no point in re-evaluating the condition. The reason to remove the test is just to make things as clear as they can be. You can have a read at http://en.wikipedia.org/wiki/Don%27t_repeat_yourself http://en.wikipedia.org/wiki/KISS_principle . Also I think the other answers are technically better than mine :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T08:36:12.553",
"Id": "43491",
"ParentId": "43456",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "43491",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T22:25:04.920",
"Id": "43456",
"Score": "8",
"Tags": [
"c++",
"mathematics"
],
"Title": "Square root approximation with Newton's method"
}
|
43456
|
<p>I've been studying C# for about 6 months and am trying to make a simple example for an n-tier application. I want to learn to do things in the most proper and professional way. This example uses a table in the database called "Settings" where various application settings can be persisted to the database. I figure once I can make a simple example, then I can have the knowledge to do something more advanced with the other tables in the database. I'm most concerned if this is a good simple example of a business logic layer.</p>
<p>There are 4 projects:</p>
<ol>
<li><p>AnimalDB.Models - POCO objects</p></li>
<li><p>AnimalDB.DataAccess - Entity Framework DBContext, Repository, Unit of Work</p></li>
<li><p>AnimalDB.Logic - Business Logic Layer</p></li>
<li><p>AnimalDB.API - Web API</p></li>
</ol>
<p>Here is my code for the project:</p>
<p><strong>AnimalDB.Models</strong></p>
<pre><code>namespace AnimalDB.Models
{
[Table("Settings")]
public class Setting
{
[Key]
public int SettingID { get; set; }
[Required]
[MaxLength(255)]
public string Name { get; set; }
[Required]
[MaxLength(255)]
public string Value { get; set; }
}
}
</code></pre>
<p><strong>AnimalDB.DataAccess</strong></p>
<pre><code>namespace AnimalDB.DataAccess
{
public class AnimalDBContext: DbContext
{
public DbSet<Setting> Settings { get; set; }
public AnimalDBContext():base("AnimalDB"){ }
}
}
namespace AnimalDB.DataAccess
{
public class GenericRepository<TEntity> where TEntity : class
{
internal AnimalDBContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(AnimalDBContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
}
namespace AnimalDB.DataAccess
{
public class UnitOfWork : IDisposable
{
private AnimalDBContext context = new AnimalDBContext();
private GenericRepository<Setting> settingRepository;
public GenericRepository<Setting> SettingRepository
{
get
{
if (this.settingRepository == null)
{
this.settingRepository = new GenericRepository<Setting>(context);
}
return settingRepository;
}
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
</code></pre>
<p><strong>AnimalDB.Logic</strong></p>
<pre><code>namespace AnimalDB.Logic
{
public class SettingManager: IDisposable
{
private UnitOfWork unitOfWork;
public SettingManager()
{
unitOfWork = new UnitOfWork();
}
public IQueryable<Setting> GetAll()
{
return unitOfWork.SettingRepository.Get(orderBy: q => q.OrderBy(d => d.Name)).AsQueryable();
}
public Setting Find(int? id)
{
return unitOfWork.SettingRepository.GetByID(id);
}
public void Insert(Setting setting)
{
unitOfWork.SettingRepository.Insert(setting);
unitOfWork.Save();
}
public void Update(Setting setting)
{
unitOfWork.SettingRepository.Update(setting);
unitOfWork.Save();
}
public void Delete(int? id)
{
Setting setting = unitOfWork.SettingRepository.GetByID(id);
unitOfWork.SettingRepository.Delete(setting);
unitOfWork.Save();
}
public void Dispose()
{
unitOfWork.Dispose();
}
}
}
</code></pre>
<p><strong>AnimalDB.API</strong></p>
<pre><code>namespace AnimalDB.API.Models
{
public class PostSettingViewModel
{
[Required]
[MaxLength(255)]
public string Name { get; set; }
[Required]
[MaxLength(255)]
public string Value { get; set; }
}
public class PutSettingViewModel
{
[Required]
public int SettingID { get; set; }
[Required]
[MaxLength(255)]
public string Name { get; set; }
[Required]
[MaxLength(255)]
public string Value { get; set; }
}
}
namespace AnimalDB.API.Controllers
{
public class SettingsController : ApiController
{
private SettingManager sm = new SettingManager();
// GET api/Settings
public IQueryable<Setting> GetSettings()
{
return sm.GetAll();
}
// GET api/Settings/5
[ResponseType(typeof(Setting))]
public IHttpActionResult GetSetting(int id)
{
Setting setting = sm.Find(id);
if (setting == null)
{
return NotFound();
}
return Ok(setting);
}
// PUT api/Settings/5
public IHttpActionResult PutSetting(int id, PutSettingViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != model.SettingID)
{
return BadRequest();
}
Setting setting = sm.Find(id);
setting.Name = model.Name;
setting.Value = model.Value;
sm.Update(setting);
return StatusCode(HttpStatusCode.NoContent);
}
// POST api/Settings
[ResponseType(typeof(Setting))]
public IHttpActionResult PostSetting(PostSettingViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Setting setting = new Setting();
setting.Name = model.Name;
setting.Value = model.Value;
sm.Insert(setting);
return CreatedAtRoute("DefaultApi", new { id = setting.SettingID }, setting);
}
// DELETE api/Settings/5
[ResponseType(typeof(Setting))]
public IHttpActionResult DeleteSetting(int id)
{
Setting setting = sm.Find(id);
if (setting == null)
{
return NotFound();
}
sm.Delete(id);
return Ok(setting);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
sm.Dispose();
}
base.Dispose(disposing);
}
}
}
</code></pre>
<p>I like to try to make a simple example for myself so I can have an understanding and then build something more complex from there. Here are some things that bother me:</p>
<ol>
<li>I'm not using Interfaces and am not sure if they are necessary.</li>
<li>I'm not sure where I would put error handling</li>
<li>The business logic layer is very simple but that is only because its doing CRUD operations</li>
<li>Why is the Unit Of Work and Repository necessary because I can just access entity framework in my business logic layer? I guess I'm not seeing the point.</li>
<li>How could I use Dependency Inject and Inversion of Control? I'm not exactly sure what both are but I've read they should be used to make your application more testable.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T10:00:50.100",
"Id": "75383",
"Score": "1",
"body": "So nobody has commented on this yet... I think it looks good from a quick glance. I haven't thoroughly went over it but from I've seen it looks good. Just thought I should say that since nobody has posted anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-03T18:47:36.717",
"Id": "201964",
"Score": "0",
"body": "Excuse my ignorance, is the `SettingManager` here considered the Service? in many N-Layer implementations they use names like `xxxService`. Correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-03T18:52:35.840",
"Id": "201965",
"Score": "1",
"body": "Yes, now that I have more experience, I would rename that as a service and use autofac for dependency injection. It's amazing what difference a year and a half of experience makes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-03T20:48:42.870",
"Id": "202000",
"Score": "0",
"body": "@David you gave me hope, i am not a programmer at all.. just a hobby, i will be there in a few months hopefully :)"
}
] |
[
{
"body": "<p>Of your questions, 1, 4, 5 all seem to hit on a common theme I think you might be missing the point of. The <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">Single Responsibility Principle</a> says that every object should have exactly one reason to change. The nuances of this become apparent if you were to try to write unit tests around your controller. </p>\n\n<p>Without making any changes, it seems impossible to write tests for your SettingsController without hitting a real database. Go ahead and try it. </p>\n\n<p>So how would you write tests for SettingsController without hitting a database? First thing you need to do is to remove the concern of persistence from the controller by inverting the control of it to something else. You are 90% of the way there already in that you have a class that handles this called the SettingsManager. What you need is an easy way of swapping out implementations of the SettingsManager without modifying the code of SettingsController. This is generally done by injecting an instance into the constructor of the SettingsController. But we aren't done yet. SettingsManager is a concrete class that cannot have its methods overridden. I would extract out an interface, maybe an ISettingsManager, and then instead of injecting an instance of SettingsManager to the SettingsController, you would instead inject an instance of ISettingsController.</p>\n\n<p>So you are probably wondering how this helps. Now you could theoretically write a new implementation of ISettingsManager that stores settings in memory, or to DynamoDB, or MongoDB, or writes to a CSV on the filesystem, it doesn't matter. In testing you might even make a MockSettingsManager using something like <a href=\"https://github.com/Moq/moq4\">Moq</a>. Now what you have is a way of testing only the logic in the SettingsController separate from everything else. </p>\n\n<p>As for validation, I sometimes struggle with that myself. I find it helpful to ask myself \"Who should be responsible for validation?\" or \"Where would I put validation so that validation is that objects only responsibility?\" or my personal favorite \"Where would I put validation if I only was going to write tests for validation and nothing else?\"</p>\n\n<p>I strongly encourage you to do two things going forward that will make a lot of these concepts clearer. </p>\n\n<ul>\n<li>Watch this talk from Uncle Bob called <a href=\"http://www.confreaks.com/videos/759-rubymidwest2011-keynote-architecture-the-lost-years\">Architecture The Lost Years</a>. Bob Martin gives some great background on where the <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\">SOLID</a> principles come from and how they benefit your applications architecture as a whole.</li>\n<li>Get in the habit of practicing <a href=\"http://en.wikipedia.org/wiki/Test-driven_development\">Test Driven Development</a>. It may feel painful and slow at first, but once you get in the habit of it you will find it does far more than reduce the bug count. It goes a long way to producing more maintainable code, code that follows better object-oriented patterns, and in the long run makes you a more productive programmer.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T19:41:29.357",
"Id": "43808",
"ParentId": "43463",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T23:03:53.587",
"Id": "43463",
"Score": "15",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Simple example of N-Tier, entity framework, unit of work, repository, business logic layer"
}
|
43463
|
<p>Here is my solution to this problem; please be brutally honest/strict, if I would have written this code, in a 45 minute interview, what would you think? (I am aiming for Google,Facebook).</p>
<p>Here is the problem I solved:</p>
<p>*Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.</p>
<blockquote>
<p><strong>For example</strong></p>
<p>Given this linked list: 1->2->3->4->5</p>
<p>For k = 2, you should return: 2->1->4->3->5</p>
<p>For k = 3, you should return: 3->2->1->4->5</p>
</blockquote>
<p>Thanks.</p>
<pre><code> public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
int count=1;
ListNode cursor = head;
ListNode current = null;
ListNode remainingHalf = null;
Queue linkQueue = new LinkedList();
if(head==null){
return null;
}
if(k<=1){
return head;
}
if(k>findSize(head)){
return head;
}
if(k==2){
return reverse(head);
}
while(cursor!=null || cursor.next!=null){
while(count!=k){
if(cursor!=null){
cursor = cursor.next;
}
count++;
}
if(cursor!=null){
remainingHalf = cursor.next;
cursor.next=null;
ListNode partial = reverse(head);
linkQueue.add(partial);
cursor = remainingHalf;
head = remainingHalf;
}
else{
linkQueue.add(remainingHalf);
break;
}
count=1;
if(cursor==null || cursor.next==null){
linkQueue.add(remainingHalf);
break;
}
}
boolean headFlag=false;
ListNode toRet=null;
while(!linkQueue.isEmpty()){
ListNode first = (ListNode)linkQueue.poll();
ListNode end=null;
if(first!=null){
end = findEnd(first);
if(headFlag==false){
toRet = first;
headFlag=true;
}
}
else{
break;
}
ListNode second = (ListNode)linkQueue.poll();
if(second==null){
ListNode temp = findEnd(toRet);
temp.next=first;
break;
}
end.next=second;
if(linkQueue.size()==1 || linkQueue.size()==0){
ListNode last = findEnd(toRet);
last.next = (ListNode)linkQueue.poll();
}
}
return toRet;
}
public int findSize(ListNode head){
int count=0;
while(head!=null){
count++; head=head.next;
}
return count;
}
public ListNode findEnd(ListNode head){
while(head.next!=null){
head = head.next;
}
return head;
}
public ListNode reverse(ListNode head){
if(head==null){
return null;
}
if(head.next==null){
return head;
}
ListNode remaining = head.next;
head.next = null;
ListNode temp = reverse(remaining);
remaining.next = head;
return temp;
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>Brutally honest?</h2>\n<p>If this is an interview, and you provide this line of code:</p>\n<blockquote>\n<pre><code>Queue linkQueue = new LinkedList();\n</code></pre>\n</blockquote>\n<p>Your resume gets put in the pile of 'ignore this person if they apply again'... ;-)</p>\n<p>Genercis have been around for a decade now (introduced in 2004). You should know them, and use them.</p>\n<h2>Class Model</h2>\n<p>The ListNode should not be a public class. The information should be encapsulated within a single class, and not exposed. There should be no need for a user to have to supply a 'head' node to the <code>public ListNode reverseKGroup(ListNode head, int k)</code>. This should be a class, say <code>ReversingList</code> which has a method <code>reverseK(int k)</code>, and then provides a way to retrieve the re-ordered data (which may be in the format of a new <code>ReversingList</code> instance.</p>\n<h2>Algorithm</h2>\n<p>Your algorithm looks really complicated. There should be no need to scan the list before processing it. That indicates some serious inefficiencies.</p>\n<p>Additionally, relying on the LinkedList class is a bit of a cheat... but, if you are going to use it, then you may as well go the whole hog, and use its reverse function... (<code>descendingIterator()</code>)</p>\n<h2>How would I do it?</h2>\n<p>This was the original title of the question... well, how about:</p>\n<pre><code>public class SolutionList {\n\n private static final class ListNode {\n private final int val;\n private ListNode next;\n\n ListNode(int x) {\n val = x;\n next = null;\n }\n\n @Override\n public String toString() {\n return "ListNode " + val;\n }\n }\n\n // use relatively common trick of having a dummy head node.\n private final ListNode head = new ListNode(0);\n\n public SolutionList() {\n // default constructor does nothing.\n }\n\n public void add(int v) {\n ListNode node = head;\n while (node.next != null) {\n node = node.next;\n }\n node.next = new ListNode(v);\n }\n\n public void addAll(SolutionList toadd) {\n ListNode tail = head;\n while (tail.next != null) {\n tail = tail.next;\n }\n ListNode their = toadd.head.next;\n while (their != null) {\n tail.next = new ListNode(their.val);\n tail = tail.next;\n their = their.next;\n }\n }\n\n public void reverseKInPlace(final int k) {\n if (k <= 1 || head.next == null) {\n return;\n }\n ListNode[] stack = new ListNode[k];\n int depth = 0;\n ListNode node = head.next;\n ListNode mark = head;\n while (node != null) {\n ListNode nxt = node.next;\n stack[depth++] = node;\n if (depth == k) {\n while (--depth >= 0) {\n mark.next = stack[depth];\n mark = mark.next;\n }\n depth = 0;\n }\n node = nxt;\n }\n if (depth > 0) {\n mark.next = stack[0];\n }\n\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder("SolutionList [");\n ListNode node = head.next;\n while (node != null) {\n sb.append(node.val).append(", ");\n node = node.next;\n }\n if (head.next != null) {\n sb.setLength(sb.length() - 2);\n }\n sb.append("]");\n return sb.toString();\n }\n\n public SolutionList reverseK(final int k) {\n SolutionList copy = new SolutionList();\n copy.addAll(this);\n copy.reverseKInPlace(k);\n return copy;\n }\n\n public static void main(String[] args) {\n int[] vals = { 1, 2, 3, 4, 5 };\n SolutionList soln = new SolutionList();\n for (int v : vals) {\n soln.add(v);\n }\n System.out.println(soln);\n System.out.println("Reverse 2 " + soln.reverseK(2));\n System.out.println("Reverse 3 " + soln.reverseK(3));\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T00:04:18.787",
"Id": "75111",
"Score": "0",
"body": "I appreciate your honesty, as it helps improve my code-writing ability. Now what do you mean by use generics, like use an ArrayList<ListNode> instead? I don't see what's wrong with using a Queue interface? Pardon my ignorance, as I have 0 industry experience."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T00:06:39.423",
"Id": "75113",
"Score": "2",
"body": "@bazang - should be `Queue<ListNode> linkQueue = new LinkedList<>();`. This has a lot of benefits for creating bug-reduced code, and it eliminates a lot of compiler warnings, etc. It is important to study up on this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T00:06:51.077",
"Id": "75114",
"Score": "4",
"body": "+1 for `... wait for it, kid's bath time... ;-)` this is the most important part of the review"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T00:07:49.057",
"Id": "75115",
"Score": "0",
"body": "@bazang - [Official Generics Tutorial](http://docs.oracle.com/javase/tutorial/java/generics/) - not necessarily the best. Google around"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T00:23:16.140",
"Id": "75118",
"Score": "0",
"body": "@bazang - updated with a code example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T01:27:31.603",
"Id": "75125",
"Score": "0",
"body": "@rolfl I usually use generics; It was a slip up in this one, I felt like it would impress the interview to show my knowledge of interfaces, along with apparent vs actual types. Thank you for your brutal honesty. I appreciate the criticism, it will help me improve. Back to the drawing board to solve another problem."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T23:58:35.353",
"Id": "43465",
"ParentId": "43464",
"Score": "13"
}
},
{
"body": "<p>I couldn't resist to disagree with <em>@rolfl</em>'s following sentence:</p>\n\n<blockquote>\n <p>Your resume gets put in the pile of 'ignore this person if they apply again'... ;-)</p>\n</blockquote>\n\n<p>As an occasional interviewer I would appreciate a solution which shows that the candidate does not reinvent the wheel and can use (and know) the existing libraries.</p>\n\n<p>Here is a solution with Guava:</p>\n\n<pre><code>import static com.google.common.collect.Lists.newArrayList;\nimport static com.google.common.collect.Lists.newLinkedList;\nimport java.util.LinkedList;\nimport java.util.List;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\n\n...\n\npublic <T> List<T> reverseFirstPart(final LinkedList<T> input, \n final int reversedElementsNumber) {\n final Iterable<T> firstPart = Iterables.limit(input, reversedElementsNumber);\n final Iterable<T> secondPart = Iterables.skip(input, reversedElementsNumber);\n final List<T> reversedFirstPart = Lists.reverse(newArrayList(firstPart));\n\n final List<T> result = newLinkedList();\n Iterables.addAll(result, reversedFirstPart);\n Iterables.addAll(result, secondPart);\n return result;\n}\n</code></pre>\n\n<p>Related: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.</p>\n\n<p>Two notes about the implementation:</p>\n\n<ol>\n<li><p>I'd use consistent indentation.</p></li>\n<li><p>Short variable names (like <code>x</code>) are not too readable:</p>\n\n<blockquote>\n<pre><code>ListNode(int x) {\n val = x;\n...\n</code></pre>\n</blockquote>\n\n<p>I suppose you have autocomplete, so using longer names does not mean more typing but it would help readers and maintainers a lot since they don't have to remember the purpose of each variable - the name should express the programmers intent. <code>val</code> also could be <code>value</code>.\n(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Avoid Mental Mapping</em>, p25)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T01:29:52.520",
"Id": "75126",
"Score": "0",
"body": "so if you were interviewing me, and I produced that working code in 45 minutes(I didn't create that ListNode class, it was a given, I only wrote the functions); you'd think I'm not Google quality? Please be honest here, and offer a bit of critique on what I'm doing wrong. I can generally solve questions quickly, but have a hard time producing the beautiful solution that you produced."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T20:45:23.310",
"Id": "75338",
"Score": "1",
"body": "@bazang: Oh dear :) What's Google quality at all? I guess the expected code quality depends on the position you applied for and code quality might not be the most important (!) factor for them. (I expect better code from a senior than a junior, therefore the junior's code could be worse.) So do your homework because code quality might not be that you should optimize for, maybe there are more important things you could learn. Anyway, you can find some good resources here: http://codereview.stackexchange.com/q/31/7076 http://workplace.stackexchange.com/ also a good place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-02T16:49:55.003",
"Id": "125284",
"Score": "0",
"body": "From the question statement: \"You may not alter the values in the nodes, only nodes itself may be changed.\" It seems they wanted you to work with actual nodes. They would probably be annoyed if you used guava in this case."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T00:46:35.300",
"Id": "43470",
"ParentId": "43464",
"Score": "11"
}
},
{
"body": "<p>Thank you for posing this delightfully tricky interview question. Before writing this review, I felt compelled to try coding it myself — on paper. It took me about an hour, and I made three mistakes.<sup>1</sup> I've posted my solution below, with comments added after the fact. (In an interview, commentary would probably have been presented verbally.)</p>\n\n<h3>Evaluation criteria</h3>\n\n<p>If I were asking this question as an interviewer, here's what I would look for in a candidate's response. Of course, these criteria reflect my own abilities and preferences.</p>\n\n<ol>\n<li><p><strong>Reasonable syntax.</strong> If writing the solution on a computer, the code must compile with no warnings and no suppressed warnings. If writing the solution on a whiteboard, it should \"visually compile\" with only minor syntax errors.</p>\n\n<p>Your code compiles with warnings about Generics.</p></li>\n<li><p><strong>One-pass O(<em>n</em>) solution.</strong> The solution, whether correct or not, must attempt to complete the task by traversing the list just once. If the candidate fails to produce code that accomplishes the task in one pass, I would be lenient if he/she spontaneously apologized for using a suboptimal algorithm. (In that case, I might ask the candidate to try again at the end of the interview, schedule permitting.)</p>\n\n<p>For an interview, I would value a slightly buggy one-pass O(<em>n</em>) algorithm over a bug-free but inefficient algorithm. I believe that the candidate should quickly recognize that a one-pass solution is possible. Minor bugs are inevitable, but picking an inefficient strategy would just be going off in the wrong direction altogether.</p>\n\n<p>In my opinion, a candidate who produces an inefficient algorithm should not be hired to develop production code: his/her work would probably require subsequent intervention by other developers to fix performance problems. However, such a programmer could still be useful for maintenance work or writing code for internal use (such as QA tests).</p>\n\n<p>Your <code>findSize()</code> and <code>findEnd()</code> helper methods both walk the list to the end. Since your <code>findEnd()</code> is called from within a loop, your algorithm must not be O(<em>n</em>), much less a one-pass O(<em>n</em>).</p></li>\n<li><p><strong>Intelligent interaction.</strong> I would like to see that the candidate asks questions to seek clarification before and during the coding process. Some of the questions I would ask are listed below.</p></li>\n<li><p><strong>General cluefulness.</strong> A solution should be reasonably concise, and each chunk of code should be purposeful. By purposeful, I mean that I should be able to point to a chunk of code, and the candidate should be able to explain, preferably using diagrams, what the data structure looks like before executing that chunk, and the result after executing that chunk.</p>\n\n<p>To be honest, your solution is too complex for me to follow in my head. If presented with your solution, I'd just challenge you with some questions instead:</p>\n\n<ul>\n<li>Is this an iterative or recursive solution? Why did you pick that over the alternative?</li>\n<li>What kind of running time would you expect?</li>\n<li>You have a <code>cursor</code> and a <code>current</code>. Isn't <code>current</code> a kind of cursor as well? Could you come up with more purposeful names?</li>\n<li>What is the <code>Queue</code> for?</li>\n<li>Before entering the first while-loop, there appear to be four base cases. Is that reasonable number of base cases? Could you get away with fewer base cases?</li>\n<li>Can you explain the loop condition <code>while (cursor != null || cursor.next != null)</code>? Would there ever be a situation where <code>cursor</code> is <code>null</code> but <code>cursor.next</code> is not?</li>\n</ul>\n\n<p>Hopefully, those questions would trigger some \"Aha!\" or \"Oops!\" moments and result in some improvements. To be frank, though, your code is way too complex and confusing to be salvageable through a Socratic dialogue.</p></li>\n</ol>\n\n<h3>Interviewee strategy</h3>\n\n<ol>\n<li><p>For this question, I would <strong>prefer recursion</strong> to iteration. Recursive solutions are often more succinct and involve fewer variables. Recursion enforces some rigour in your thinking process, by making you think about preconditions, postconditions, and invariants. Recursion works well for this linked-list question precisely because invariants exist: walk <em>k</em> nodes down the list, and the situation looks similar.</p>\n\n<p>Production Java code often avoids recursion due to practicalities such as the function-call overhead and worries about stack overflow. However, interview questions are naturally an academic exercise. Just in case the interviewer is prejudiced against recursion, ask two questions:</p>\n\n<ul>\n<li>\"Will the input be small enough such that the stack overflow is not a concern?\"</li>\n<li>\"How about a recursive solution? I can rewrite it as an iterative solution afterwards, if you prefer.\"</li>\n</ul></li>\n<li><p>Keep it simple. There are other <strong>things you can get away when coding in an interview</strong>, especially if coding on a whiteboard. Just keep talking.</p>\n\n<ul>\n<li><code>import java.util.*;</code> \"Of course, in production code, I would list individual classes.\"</li>\n<li>Naked linked list nodes. \"Normally, I'd hide the nodes within the linked list. To save time, we'll just say that a node <em>is</em> a list. OK?\"</li>\n<li>Public fields. \"Normally, there would be getters and setters. I'll take a shortcut and expose <code>.value</code> and <code>.next</code>. However, to enforce your rule that nodes should have their pointers and not values manipulated, I'll make <code>.value</code> <code>final</code>. OK?\"</li>\n</ul></li>\n<li><p>Think out loud. Draw diagrams. Ask questions, especially questions that clarify the requirements. Score some points before writing a single line of code.</p></li>\n</ol>\n\n<h3>My ideal</h3>\n\n<p>Here's my solution, for comparison. The heart of the implementation, the <code>kReverse()</code> helper, is only about a dozen lines, if you strip out assertions and comments.</p>\n\n<pre><code>// Import * not advisable in production code, but good enough for interview code\nimport java.util.*;\nimport static java.lang.System.out;\n\npublic class LinkedListNode<T> {\n public final T value;\n private LinkedListNode<T> next;\n\n public LinkedListNode(T value, LinkedListNode<T> next) {\n this.value = value;\n this.next = next;\n }\n\n public static <T> LinkedListNode<T> makeList(List<T> list) {\n LinkedListNode<T> head = null;\n for (int i = list.size() - 1; i >= 0; i--) {\n head = new LinkedListNode<T>(list.get(i), head);\n }\n return head;\n }\n\n /**\n * Stringifies entire list for diagnostics.\n */\n public String toString() {\n StringBuilder sb = new StringBuilder(this.value.toString());\n for (LinkedListNode<T> n = next; n != null; n = n.next) {\n sb.append(\" -> \").append(n.value.toString());\n }\n return sb.toString();\n }\n\n public static <T> LinkedListNode<T> kReverse(LinkedListNode<T> head, int k) {\n if (k < 1) throw new IllegalArgumentException(\"k = \" + k);\n return kReverse(head, k, head, null, k);\n }\n\n /**\n * Sets the <tt>.next</tt> pointer of the <tt>head</tt> node and all\n * of its successors to perform k-group reversal of a list.\n *\n * @param head The current node being processed\n * @param k Chunk size, as specified in the problem\n * @param group The original head of this k-group\n * @param prev The original predecessor of head\n * @param remain The number of nodes remaining to be processed in this\n * k-group, including head\n *\n * @return The new leading node of the current k-group (which could be null\n * if the current k-group is empty)\n */\n private static <T> LinkedListNode<T> kReverse(LinkedListNode<T> head, int k,\n LinkedListNode<T> group,\n LinkedListNode<T> prev,\n int remain) {\n assert remain > 0;\n if (null == head) {\n // Incomplete or empty group.\n return group;\n\n } else if (1 == remain) {\n // head is the last node of the k-group, and will become the\n // leading node of the reversed k-group.\n\n // Reverse the next k-group (and by recursion, all subsequent\n // k-groups). n is the leading node of the next k-group after\n // its reversal is complete (possibly null).\n LinkedListNode<T> n = kReverse(head.next, k, head.next, null, k);\n\n // The next two statements must be in this order, because if\n // k == 1, head and group are the same.\n head.next = prev;\n group.next = n;\n\n return head;\n\n } else {\n // head not the last node of the k-group. n is the leading node of\n // this k-group after reversal: the same as the old leading node if\n // this k-group is incomplete, or the same as the old trailing node\n // of this k-group if reversal succeeds.\n LinkedListNode<T> n = kReverse(head.next, k, group, head, remain - 1);\n\n // group != n means this k-group has k members and is being reversed.\n if (group != n && head != group) {\n // Don't set head.next, though, if head is the old leading node,\n // i.e., the new trailing node, since it was already set in\n // the (1 == remain) case above.\n head.next = prev;\n }\n return n;\n }\n }\n\n /**\n * Tests\n */\n public static void main(String[] args) {\n List<Integer> oneFive = Arrays.asList(new Integer[] {1, 2, 3, 4, 5});\n // No-op expected...\n out.println(kReverse(LinkedListNode.makeList(oneFive), 1));\n out.println(kReverse(LinkedListNode.makeList(oneFive), 2));\n out.println(kReverse(LinkedListNode.makeList(oneFive), 3));\n out.println(kReverse(LinkedListNode.makeList(oneFive), 4));\n out.println(kReverse(LinkedListNode.makeList(oneFive), 5));\n out.println(kReverse(LinkedListNode.makeList(oneFive), 6));\n // IllegalArgumentException expected...\n out.println(kReverse(LinkedListNode.makeList(oneFive), 0));\n }\n}\n</code></pre>\n\n<p>As stated above, comments and JavaDoc were added just before posting the code; I wouldn't have produced such nice comments in a time-limited situation.</p>\n\n<p>This is, of course, not the only good solution possible. However, as you can see, your implementation is quite far off.</p>\n\n<hr>\n\n<p><sup>1</sup> The three mistakes I made were:</p>\n\n<ul>\n<li>Wrote <code>static LinkedListNode<T> function(…)</code> instead of <code>static <T> LinkedListNode<T> function(…)</code></li>\n<li>Forgot the <code>head != group</code> condition near the end of <code>kReverse()</code></li>\n<li>Silly mistake when writing <code>main()</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:28:30.030",
"Id": "75321",
"Score": "0",
"body": "I know it took you a while to write that comment; and I want to mention/emphasize, that I appreciate your time. I'll be posting more of my responses to questions that I will try to answering, and will appreciate it if you may continue to be brutally honest with me about my code. I will also start posting how long it took me to solve it. I agree, that in the case of that problem, I still feel like I did a TERRIBLE job, and honestly lost sleep over the fact that I couldn't solve it in a better manner."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:51:32.017",
"Id": "75328",
"Score": "0",
"body": "Please remember to upvote all answers that you find useful. I don't usually mention how much time it took me, but did so in this case only because you mentioned it too. This was _not_ an easy challenge! Take your time to think through it. Hope to see more of your posts on Code Review! [@JavaDeveloper](http://codereview.stackexchange.com/users/28539/javadeveloper) is in a similar situation as you, and is up to 91 posts now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T20:10:50.443",
"Id": "75334",
"Score": "0",
"body": "@JavaDeveloper, I think that trying to answer some questions tagged as [tag:interview-questions] would give you some insight to help improve your interviewing skills."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T09:36:12.697",
"Id": "43494",
"ParentId": "43464",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "43465",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T23:06:14.517",
"Id": "43464",
"Score": "20",
"Tags": [
"java",
"algorithm",
"linked-list",
"interview-questions"
],
"Title": "Reversing k-sized sequences in a linked-list"
}
|
43464
|
<p>Here is my attempt at the UTTT <a href="/questions/tagged/code-challenge" class="post-tag" title="show questions tagged 'code-challenge'" rel="tag">code-challenge</a> (in response to the the <a href="https://codereview.meta.stackexchange.com/a/1472/27623">Weekend-Challenge Reboot</a>). Here is what I would like critiqued:</p>
<ul>
<li><p>I tested the code a few times for bugs, but I may have missed some.</p></li>
<li><p>I feel like I have duplicated code in some places (with only minor changes being the difference), refining them down a bit would be nice.</p></li>
<li><p>Better parsing of input</p></li>
</ul>
<p>But any and all suggestions are acceptable. If you are interesting in looking at some occasionally updated versions of this code, take a look the <a href="https://github.com/syb0rg/Ultimate-Tic-Tac-Toe" rel="noreferrer"><strong>the Github repository that houses the code</strong></a> (feel free to send fork and send pull requests).</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define ROWS 9
#define COLS 9
typedef char Board[ROWS][COLS];
typedef char MetaBoard[ROWS / 3][COLS / 3];
typedef enum {VALID, NOT_A_DIGIT, NOT_IN_BOARD, SPACE_OCCUPIED, OUT_OF_BOUNDS} MoveStatus;
void fillSubBoard(Board board, int x, int y, char c)
{
for (; (x % 3) != 0; x--); // quickly set x to left bound of sub-board
for (; (y % 3) != 0; y--); // quickly set y to upper bound of sub-board
for (int rowMax = x + 2, row = x; row <= rowMax; row++)
{
for (int columnMax = y + 2, column = y; column <= columnMax; column++)
{
board[row][column] = c;
}
}
}
int getRowBound(int row)
{
switch (row)
{
case 0 ... 2:
return 0;
case 3 ... 5:
return 1;
case 6 ... 8:
return 2;
default:
return -1;
}
}
int getColumnBound(int column)
{
switch (column)
{
case 0 ... 2:
return 0;
case 3 ... 5:
return 1;
case 6 ... 8:
return 2;
default:
return -1;
}
}
void printBoard(Board board)
{
printf("\n=============||===========||=============\n");
for (int row = 0; row < ROWS; row++)
{
printf("||");
for (int column = 0; column < COLS; column++)
{
if (board[row][column] == '-') printf("%d,%d|", row, column);
else printf(" %c |", board[row][column]);
if (0 == (column+1) % 3) printf("|");
}
if ((row+1) % 3 == 0) printf("\n=============||===========||=============\n");
else printf("\n-----|---|---||---|---|---||---|---|-----\n");
}
}
static int checkMeta(MetaBoard meta)
{
const int xStart[ROWS - 1] = {0, 0, 0, 0, 1, 2, 0, 0};
const int yStart[COLS - 1] = {0, 1, 2, 0, 0, 0, 0, 2};
const int xDelta[ROWS - 1] = {1, 1, 1, 0, 0, 0, 1, 1};
const int yDelta[COLS - 1] = {0, 0, 0, 1, 1, 1, 1, 1};
static int startx, starty, deltax, deltay;
for (int trip = 0; trip < ROWS - 1; trip++)
{
startx = xStart[trip];
starty = yStart[trip];
deltax = xDelta[trip];
deltay = yDelta[trip];
// main logic to check if a subboard has a winner
if (meta[startx][starty] != '-' &&
meta[startx][starty] == meta[startx + deltax][starty + deltay] &&
meta[startx][starty] == meta[startx + deltax + deltax][starty + deltay + deltay]) return 1;
}
return 0;
}
static int checkBoard(Board board, MetaBoard meta, int player, int row, int column)
{
const int xStart[ROWS - 1] = {0, 0, 0, 0, 1, 2, 0, 0};
const int yStart[COLS - 1] = {0, 1, 2, 0, 0, 0, 0, 2};
const int xDelta[ROWS - 1] = {1, 1, 1, 0, 0, 0, 1, 1};
const int yDelta[COLS - 1] = {0, 0, 0, 1, 1, 1, 1, 1};
static int startx, starty, deltax, deltay, status = 0;
for (; (row % 3) != 0; row--); // quickly set row to left bound of sub-board
for (; (column % 3) != 0; column--); // quickly set column to upper bound of sub-board
for (int trip = 0; trip < ROWS - 1; trip++)
{
startx = row + xStart[trip];
starty = column + yStart[trip];
deltax = xDelta[trip];
deltay = yDelta[trip];
if (board[startx][starty] != '-' &&
board[startx][starty] == board[startx + deltax][starty + deltay] &&
board[startx][starty] == board[startx + deltax + deltax][starty + deltay + deltay])
{
fillSubBoard(board, row, column, (player == 1) ? 'X' : 'O');
meta[getRowBound(row)][getColumnBound(column)] = (player == 1) ? 'X' : 'O';
status = 1;
}
}
return (status + checkMeta(meta)); // always check if the game has a winner
}
MoveStatus validCoords(Board board, int row, int column, int rowBound, int columnBound)
{
if (!isdigit((char)(((int)'0') + row)) && !isdigit((char)(((int)'0') + column))) return NOT_A_DIGIT; // supplied coordinates aren't digits 1-9
else if (row > ROWS - 1 || column > COLS - 1) return NOT_IN_BOARD; // supplied coordinates aren't within the bounds of the board
else if (board[row][column] != '-') return SPACE_OCCUPIED; // supplied coordinates are occupied by another character
else if (rowBound == -1 && columnBound == -1) return VALID; // supplied coordinates can move anywhere
else if (((row > rowBound * 3 + 2 || column > columnBound * 3 + 2) ||
(row < rowBound * 3 || column < columnBound * 3)) &&
(rowBound > 0 && columnBound > 0)) return OUT_OF_BOUNDS; // coordinates aren't within the sub-board specified by the previous move
else return VALID; // didn't fail anywhere else, so coords are valid
}
int main(void)
{
int winner = 0, row = 0, column = 0, rowBound = -1, columnBound = -1, invalid = 0;
char tempRow = '\0', tempColumn = '\0';
Board board;
MetaBoard meta;
// initialize boards and fill with '-'
memset(board, '-', ROWS * COLS * sizeof(char));
memset(meta, '-', (ROWS / 3) * (COLS / 3) * sizeof(char));
// game loop
for (int turn = 0; turn < ROWS * COLS && !winner; turn++)
{
int player = (turn % 2) + 1;
printBoard(board);
printf("Player %d, enter the coordinates (x, y) to place %c: ", player, (player==1) ? 'X' : 'O');
do
{
scanf("%c, %c", &tempRow, &tempColumn);
for(; getchar() != '\n'; getchar()); // pick up superfluous input so we don't run into problems when we scan for input again
row = abs((int) tempRow - '0');
column = abs((int) tempColumn - '0');
invalid = 0;
switch (validCoords(board, row, column, rowBound, columnBound))
{
case NOT_A_DIGIT:
printf("Invalid input. Re-enter: ");
invalid = 1;
break;
case NOT_IN_BOARD:
printf("Out of board's bounds. Re-enter: ");
invalid = 2;
break;
case SPACE_OCCUPIED:
printf("There is already an %c there. Re-enter: ", board[row][column]);
invalid = 3;
break;
case OUT_OF_BOUNDS:
printf("Your move was in the wrong sub-board. Re-enter: ");
invalid = 4;
break;
default:
break;
}
} while (invalid);
board[row][column] = (player == 1) ? 'X' : 'O';
switch(checkBoard(board, meta, player, row, column))
{
case 1:
// next move can be anywhere
rowBound = -1;
columnBound = -1;
break;
case 2:
winner = player;
break;
default:
rowBound = row % 3;
columnBound = column % 3;
break;
}
}
printBoard(board);
if(!winner) printf("The game is a draw\n");
else printf("Player %d has won\n", winner);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T00:10:33.157",
"Id": "75116",
"Score": "0",
"body": "I think if you move the game logic out the main is better. Something like while (isGameRunning ()) do game logic manage input etc. All with functions."
}
] |
[
{
"body": "<p>A few comments:</p>\n\n<p>[ ... ]</p>\n\n<pre><code>for (; (x % 3) != 0; x--); // quickly set x to left bound of sub-board\nfor (; (y % 3) != 0; y--); // quickly set y to upper bound of sub-board\n</code></pre>\n\n<p>I think I'd move the code to round to a multiple of three into a function of its own. I think I'd implement that something like this:</p>\n\n<pre><code>int round3(int in) { return (in/3)*3; }\n</code></pre>\n\n<p>[ ... ]</p>\n\n<pre><code>int getRowBound(int row)\n{\n switch (row)\n {\n case 0 ... 2:\n return 0;\n case 3 ... 5:\n return 1;\n case 6 ... 8:\n return 2;\n default:\n return -1;\n }\n}\n\nint getColumnBound(int column)\n{\n switch (column)\n {\n case 0 ... 2:\n return 0;\n case 3 ... 5:\n return 1;\n case 6 ... 8:\n return 2;\n default:\n return -1;\n }\n}\n</code></pre>\n\n<p>These two functions (<code>getRowBound</code> and <code>getColumnBound</code>) are identical--and not just by coincidence either, so I think I'd merge them into a single function:</p>\n\n<pre><code>int getBound(int in) { \n return (unsigned)in < 9 ? in / 3 : -1;\n}\n</code></pre>\n\n<p>[ ... ]</p>\n\n<pre><code>for (; (row % 3) != 0; row--); // quickly set row to left bound of sub-board\nfor (; (column % 3) != 0; column--); // quickly set column to upper bound of sub-board\n</code></pre>\n\n<p>These should be calls to the <code>round3</code> (or whatever name you prefer) mentioned previously. </p>\n\n<p>[ ... ]</p>\n\n<p>Although some disagree (vehemently in some cases) I'd personally prefer to get rid of some of the conditionals like these:</p>\n\n<pre><code> fillSubBoard(board, row, column, (player == 1) ? 'X' : 'O');\n meta[getRowBound(row)][getColumnBound(column)] = (player == 1) ? 'X' : 'O';\n</code></pre>\n\n<p>...and instead have something like:</p>\n\n<pre><code>static const char marks[] = {'X', 'O'};\n\n// ...\nfillSubBoard(board, row, column, marks[player]);\nmeta[getBound(row)][getBound(column)] = marks[player];\n</code></pre>\n\n<p>[ ... ]</p>\n\n<pre><code>MoveStatus validCoords(Board board, int row, int column, int rowBound, int columnBound)\n{\n if (!isdigit((char)(((int)'0') + row)) && !isdigit((char)(((int)'0') + column))) return NOT_A_DIGIT; // supplied coordinates aren't digits 1-9\n</code></pre>\n\n<p>Any user input that you pass to <code>isdigit</code> (or any of the other <code>isXXX</code> functions/macros from <code>ctype.h</code>) should be cast to <code>unsigned char</code> first. Passing a negative number (other than EOF) to <code>isXXX</code> gives undefined behavior. In a typical case, any character outside the basic US-ASCII set (e.g., any letter that's not used in English, plus anything with a diacritic mark) will have a negative value when stored in a <code>char</code>.</p>\n\n<p>[ ... ]</p>\n\n<pre><code>int winner = 0, row = 0, column = 0, rowBound = -1, columnBound = -1, invalid = 0;\n</code></pre>\n\n<p>Though <em>some</em> disagree, I think <em>most</em> programmers would prefer each variable in a separate definition. If (for some reason) you prefer not to do that, I'd at least format each variable onto a separate line.</p>\n\n<pre><code> for(; getchar() != '\\n'; getchar()); // pick up superfluous input so we don't run into problems when we scan for input again\n</code></pre>\n\n<p>This looks buggy. In the condition you're calling <code>getchar()</code>, and checking the return value--but then in the <code>increment</code> part of the loop, you're calling <code>getchar()</code> again without checking the return value.</p>\n\n<p>I think you probably want something more like:</p>\n\n<pre><code>while (getchar() != '\\n')\n ;\n</code></pre>\n\n<p>[ ... ]</p>\n\n<pre><code> switch (validCoords(board, row, column, rowBound, columnBound))\n {\n case NOT_A_DIGIT:\n printf(\"Invalid input. Re-enter: \");\n invalid = 1;\n break;\n case NOT_IN_BOARD:\n printf(\"Out of board's bounds. Re-enter: \");\n invalid = 2;\n break;\n case SPACE_OCCUPIED:\n printf(\"There is already an %c there. Re-enter: \", board[row][column]);\n invalid = 3;\n break;\n case OUT_OF_BOUNDS:\n printf(\"Your move was in the wrong sub-board. Re-enter: \");\n invalid = 4;\n break;\n</code></pre>\n\n<p>Here (again) I think I'd probably use the return value to index into an array:</p>\n\n<pre><code>static char const *errors[] = {\n \"Invalid Input.\",\n \"Out of board's bounds\",\n \"That space is already used\",\n \"Your move was in the wrong sub-board\"\n};\n\nint error;\nwhile (0 != (error=validCoords(...))) {\n printf(\"%s Re-enter:\", errors[error]);\n getinput();\n}\n</code></pre>\n\n<p>This does require that you keep the list of errors in synch with the error numbers, but the payoff outweighs the extra burden (IMO).</p>\n\n<p>[ ... ]</p>\n\n<pre><code> board[row][column] = (player == 1) ? 'X' : 'O';\n</code></pre>\n\n<p>Again, I'd use the <code>marks</code> mentioned earlier, so this would end up like:</p>\n\n<pre><code>board[row][column] = marks[player];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-14T12:26:09.833",
"Id": "315480",
"Score": "0",
"body": "What purpose does the cast to `unsigned` serve in function `getBound`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-14T14:09:54.413",
"Id": "315510",
"Score": "0",
"body": "It eliminates a comparison. We want to return -1 for any number <0 or >8. The cast to unsigned converts negative numbers to large positive numbers (guaranteed much greater than 8) so we only compare to 8, rather than to both 0 and 8."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-14T14:13:19.807",
"Id": "315511",
"Score": "0",
"body": "Ok, that's pretty much what I thought. I guess it at least deserves a comment; I'd probably scratch my head or accidentally remove the `unsigned` if I didn't pay attention :p"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T04:46:20.297",
"Id": "43481",
"ParentId": "43466",
"Score": "24"
}
},
{
"body": "<p>One quick observation I have is about the way you are storing the playable spaces. While a 9 by 9 grid is a simple way to do it, it isn't the most clear way to store and ends up requiring some complicated addressing logic to get each sub-board.</p>\n\n<p>Your options to deal with it are a bit limited by C, but there is support for nesting types. You can use this to define a MainBoard type that takes a 3 by 3 matrix of SubBoard types and a SubBoard type that takes a 3 by 3 grid of playable squares (characters).</p>\n\n<pre><code>typedef char SubBoard[ROWS][COLS];\ntypedef SubBoard MainBoard[ROWS][COLS];\n</code></pre>\n\n<p>I'm not 100% sure on the syntax since my C is a bit rusty, but this should allow you to use much simpler addressing. If the player uses space 1,3 on the sub-board they are playing, you can then get board 1,3 for the next play.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T05:06:35.410",
"Id": "43483",
"ParentId": "43466",
"Score": "11"
}
},
{
"body": "<pre><code>for (; (row % 3) != 0; row--); // quickly set row to left bound of sub-board\nfor (; (column % 3) != 0; column--); // quickly set column to upper bound of sub-board\n</code></pre>\n\n<p>Why not just</p>\n\n<pre><code>row -= row % 3;\ncolumn -= column % 3;\n</code></pre>\n\n<p>And it should be actually call to something like</p>\n\n<pre><code>static inline int round3(int x) {\n return x - x % 3;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T09:59:45.920",
"Id": "43497",
"ParentId": "43466",
"Score": "6"
}
},
{
"body": "<p>In this piece of code:</p>\n\n<pre><code>int getRowBound(int row)\n{\n switch (row)\n {\n case 0 ... 2:\n return 0;\n case 3 ... 5:\n return 1;\n case 6 ... 8:\n return 2;\n default:\n return -1;\n }\n}\n</code></pre>\n\n<p>The ellipsis <code>...</code> is a GCC extension to the C programming language known as <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html#Case-Ranges\" rel=\"nofollow noreferrer\">Case Ranges</a>. Using it hinders portability since not all compilers support it (as for most of the extensions). If you want to get rid of it, you should use the function <code>getBound</code> proposed by Jerry Coffin:</p>\n\n<pre><code>int getBound(int in) { \n return (unsigned)in < 9 ? in / 3 : -1;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T23:19:40.877",
"Id": "43562",
"ParentId": "43466",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "43481",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T23:59:34.227",
"Id": "43466",
"Score": "39",
"Tags": [
"performance",
"c",
"game",
"tic-tac-toe",
"community-challenge"
],
"Title": "Ultimate Tic-Tac-Toe in C"
}
|
43466
|
<p>I'm trying to do a SPOJ problem called twosquares where you check whether the current number can be obtained by adding two squares together. However, I'm getting a "time limit exceeded" message.</p>
<p>I'm creating a Sieve of Eratosthenes program. If the number <em>n</em> is prime and</p>
<blockquote>
<p><em>n</em> ≡ 1 (mod 4)</p>
</blockquote>
<p>then the number is a sum of two squares by <a href="http://en.wikipedia.org/wiki/Fermat%27s_theorem_on_sums_of_two_squares" rel="nofollow">Fermat's theorem on sums of two squares</a>. If the number is not prime then I prime factorize the number; if each prime factor <em>p</em> where <em>p</em> % 4 = 3 has an even exponent then the number is a sum of two squares.</p>
<p>How could I improve the algorithm so that it runs faster and doesn't reach the time limit?</p>
<pre><code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
class sum_of_two_squares_part2 {
static boolean array[];
static ArrayList<Pair> get_prime_factorization(long number){
int prime=2;
int number_of_times=0;
ArrayList<Pair> list=new ArrayList<Pair>();
while(number!=1){
number_of_times=0;
while(number%prime==0 && array[prime]==true){
number=number/prime;
number_of_times++;
}
if(number_of_times>0){
list.add( new sum_of_two_squares_part2().new Pair(prime,number_of_times));
}
if(prime==2){
prime++;
}else{
prime+=2;
}
}
return list;
}
public class Pair{
int number;
int times;
public Pair(int number, int times){
this.number=number;
this.times=times;
}
}
public static void main(String[] args) {
array = new boolean[10000001];
Arrays.fill(array, true);
array[0]=false;
array[1]=false;
for(int i=2;i<=Math.sqrt(10000001);i++){
if(array[i]){
for(int j=2;j*i<=10000000;j++){
array[j*i]=false;
}
}
}
Scanner input=new Scanner(System.in);
int number_of_inputs=input.nextInt();
long array_of_inputs[]=new long[number_of_inputs];
int number_of_true=0;
int number_of_even=0;
for(int i=0;i<number_of_inputs;i++){
array_of_inputs[i]=input.nextLong();
}
for(int i=0;i<array_of_inputs.length;i++){
if(array_of_inputs[i]==1||array_of_inputs[i]==2){
System.out.println("Yes");
}
else if(array.length-1<array_of_inputs[i]&&array[(int)array_of_inputs[i]]==true){
if(array_of_inputs[i]%4==1){
System.out.println("Yes");
}else{
System.out.println("No");
}
if(array_of_inputs[i]==76){
System.out.println(" yolo1");
}
}else{
number_of_true=0;
number_of_even=0;
ArrayList<Pair> list=get_prime_factorization(array_of_inputs[i]);
for(int j=0;j<list.size();j++){
//System.out.println("The value of j is: "+j+"\n and the size of arraylist is "+list.size());
if((list.get(j).number-3)%4==0){
number_of_true++;
if(list.get(j).times%2==0){
number_of_even++;
}
}
}
if(number_of_true==number_of_even){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T19:55:13.153",
"Id": "75330",
"Score": "1",
"body": "clean up your formatting a little bit please"
}
] |
[
{
"body": "<p>Your code is a mess, does not follow any standard naming conventions, and the indentation makes it really difficult.</p>\n\n<p>It is not really worth reading. You need to fix it.</p>\n\n<p>But, since you have tagged this <a href=\"/questions/tagged/algorithm\" class=\"post-tag\" title=\"show questions tagged 'algorithm'\" rel=\"tag\">algorithm</a>, let's look at that.</p>\n\n<p>A correct Sieve of Eratosthenes is an <em>O(n log log n)</em> complexity algorithm.</p>\n\n<p>Then, prime factoring is hard, and slow. It is probably at least <em>O(n)</em> plus more.</p>\n\n<p>This algorithm is just wrong....</p>\n\n<p>It is much simpler to simply calculate the squares.</p>\n\n<p>Consider this algorithm:</p>\n\n<ul>\n<li>find the integer-value of the square-root of the input.</li>\n<li>find the squares of all values up to that square-root</li>\n<li>scan that list and see if any of them can be combined to add to the desired value.\n<ul>\n<li>start at the one end of the squares</li>\n<li>search the remainder for a matching value.</li>\n</ul></li>\n</ul>\n\n<p>This will operate in <em>O(m log m)</em> where m is the square-root of the input.... which will be really fast.</p>\n\n<p>Here's some code:</p>\n\n<pre><code>private static int[] getSquareSums(int input) {\n int limit = (int)Math.sqrt(input);\n int[] squares = new int[limit];\n for (int i = 0; i < limit; i++) {\n squares[i] = (i + 1) * (i + 1);\n }\n for (int i = limit - 1; i >= 0; i--) {\n int target = input - squares[i];\n int pos = Arrays.binarySearch(squares, 0, i, target);\n if (pos >= 0) {\n return new int[]{squares[i], squares[pos]};\n }\n }\n return new int[0];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T03:32:18.390",
"Id": "75147",
"Score": "0",
"body": "Is the binary search method in java including or excluding the fromTo index- in this case the value of i? Also, in the squares array shouldn't you include the value of zero?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T03:39:03.467",
"Id": "75151",
"Score": "0",
"body": "The binary-search documentation is clear, [it is exclusive of i](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(int[],%20int,%20int,%20int)) which may be a problem. As for the square of 0, is zero square? Your call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T04:00:26.510",
"Id": "75153",
"Score": "0",
"body": "Using your method the time limit has exceeded once again"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T04:08:58.843",
"Id": "75154",
"Score": "0",
"body": "I believe there is a way to do this in sqrt(n) time, but I don't know what it is..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T04:09:54.260",
"Id": "75155",
"Score": "0",
"body": "What's the link?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T04:18:54.527",
"Id": "75156",
"Score": "0",
"body": "http://www.spoj.com/problems/TWOSQRS/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T08:55:17.133",
"Id": "75375",
"Score": "1",
"body": "I might be wrong but if you are to perform a Sieve of Eratosthenes, prime factoring can be really easy : when performing your Sieve, instead of using a array mapping numbers to a boolean (prime or not prime), use an array mapping numbers n to their smallest (prime) factor if not prime, anything else you can detect (0, -1, n, etc) if prime. Then prime factoring takes as many constant time steps as the number of prime factors."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T01:24:50.357",
"Id": "43474",
"ParentId": "43469",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T00:45:39.920",
"Id": "43469",
"Score": "3",
"Tags": [
"java",
"optimization",
"algorithm",
"primes",
"mathematics"
],
"Title": "Sum of two squares"
}
|
43469
|
<p>I've decided to implement a simple smart pointer:</p>
<pre><code>#pragma once
//simple and basic reference by Aldrigo Raffaele
#include "Common.h"
#include "Exceptions.h"
class MemWrp {
private:
uint numref;
public:
void* content;
MemWrp(void* content) {
this->content = content;
numref = 1;
}
void AddRef() { numref++; }
uint RemoveRef() { return --numref; }
destructor MemWrp() { delete content; }
};
template< class T >
class Ref {
private:
MemWrp* wrp = NULL;
public:
Ref() {}
Ref(T* ptr) {
wrp = NULL;
if (ptr != NULL) wrp = new MemWrp(ptr);
}
Ref(const Ref<T>& r) {
wrp = r.wrp;
if (wrp != NULL) wrp->AddRef();
}
Ref(MemWrp* w) {
wrp = w;
wrp->AddRef();
}
T* Get() const {
if (wrp == NULL) return NULL;
return (T*)wrp->content;
}
template<class F>
bool is() { return dynamic_cast<F*>(Get()) != NULL; }
template<class F>
Ref<F> as() {
if (!this->is<F>()) return Ref<F>::Ref();
return Ref<F>::Ref(this->wrp);
}
Ref<T>& operator=(Ref<T>& rhs) {
if (this == &rhs) return *this;
if (rhs.wrp == NULL && wrp != NULL && wrp->RemoveRef() == 0) delete wrp;
wrp = rhs.wrp;
if (wrp != NULL) wrp->AddRef();
return *this;
}
Ref<T>& operator=(T* rhs) {
if (Get() == rhs) return *this;
if (rhs == NULL && wrp != NULL && wrp->RemoveRef() == 0) delete wrp;
else if (rhs != NULL) wrp = new MemWrp(rhs);
return *this;
}
bool operator==(const Ref<T>& other) const {
return (this->Get() == other.Get());
}
bool operator==(const int other) const {
return (this->Get() == (void*)other);
}
bool operator!=(const Ref<T>& other) const {
return !(*this == other);
}
bool operator!=(const int other) const {
return !(*this == other);
}
T* operator->() {
if (this->Get() == NULL) throw NullPointerException();
return this->Get();
}
const T* operator->() const {
if (this->Get() == NULL) throw NullPointerException();
return this->Get();
}
destructor Ref() {
if (wrp != NULL && wrp->RemoveRef() == 0) delete wrp;
}
};
</code></pre>
<p>What do you think? How can I subdivide it into .h and .cpp?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:10:19.830",
"Id": "75124",
"Score": "11",
"body": "C++ includes smart pointers already, why implement another? Also, this question is probably better suited to the Code Reviews Stack Exchange."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T07:56:28.207",
"Id": "75166",
"Score": "0",
"body": "@John Gaughan: I can think of several valid reasons, though they all contain one of the words \"training\", \"study\", \"drilling\" or the like."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T07:58:38.687",
"Id": "75167",
"Score": "2",
"body": "@Raffa50: I think the first lesson you should learn this time is to not introduce new \"keywords\" using `#define` (i.e., if you example compiles for you, then only because you did `#define destructor`). #define-Macros are frowned upon in 99.9% of cases for very good reasons."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T14:59:38.493",
"Id": "75240",
"Score": "0",
"body": "@phresnel I agree, but the author was not clear on the reason for doing this. That is why I pointed out that C++ already has smart pointers, and asked \"why implement another?\" This may be a learning exercise, or it may be reinventing the wheel. One is fine, one is a bad idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T17:31:44.080",
"Id": "75280",
"Score": "0",
"body": "Well because this smart pointer have is and as that works like C#... can I do the same with std::share_ptr?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:05:28.390",
"Id": "75300",
"Score": "0",
"body": "@Raffa50: I always found C# objects more akin to C++ raw pointers, especially wrt resource management. Shared and unique pointers are safer than standard C# objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:30:53.173",
"Id": "75308",
"Score": "0",
"body": "@Raffa50: don't try and imply the idioms of the language you know onto a new language. Try and learn the idioms of the new language. Doing the former will just result in ugly code. The latter takes longer but will make you adept at using the language. C# and C++ are very different in how they are used. C++ shared_pointer is a much more sophisticated and accurate tool when compared to the C# garbage collector. The C++ automatic object is akin to the C# new combined with a using declaration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T21:51:24.187",
"Id": "75830",
"Score": "0",
"body": "However how I subdivide it into H and Cpp???\nI've tryed but VS13 gave me linking error..."
}
] |
[
{
"body": "<p>Is <code>destructor</code> a new C++ keyword?</p>\n\n<p>In the assignment operator you want to decrement the reference count even when rhs is null.</p>\n\n<p>Calling delete on a void* content in MemWrp won't call the T destructor.</p>\n\n<p>Allowing <code>Ref(int ptr)</code> construction doesn't make much sense, when you later cast ptr to void*.</p>\n\n<p>Is <code>MemWrp* wrp = NULL;</code> legal C++ syntax? I thought you needed to initialize in the constructor.</p>\n\n<p>Returning a default-constructed empty Ref in the as method is counter-intuitive.</p>\n\n<p>You should prefer to use one of the standard smart pointer classes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:14:18.077",
"Id": "75303",
"Score": "0",
"body": "Ref(int ptr) allows me to do: return NULL;"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T01:31:01.520",
"Id": "43475",
"ParentId": "43472",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>What do you think?</p>\n</blockquote>\n\n<p>For learning RAII/resource management, it's a good idea to write your own smart pointer class. For production code, use std::shared_ptr, std::unique_ptr, or boost smart pointers (if you have to).</p>\n\n<p>Here are some notes on the code itself:</p>\n\n<ul>\n<li>The code only compiles if you add:</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>#define destructor ~\n</code></pre>\n\n<p>Don't do that! It simply increases the WTFPLOC (\"what the fuck!\"s per lines of code) ratio of your code and even if it seems like a nice idea now, you will (most probably) not consider it a good idea one year from now, looking at the code.</p>\n\n<ul>\n<li><p>MemWrp should:</p>\n\n<ul>\n<li><p>store the data in a strongly-typed pointer (that means, make it a template by pointer type); Otherwise, when you delete it will not invoke the right destructor type unless you use a cast.</p></li>\n<li><p>be a private part of the Ref class; It's an implementation detail; you should not need to create instances of it outside of Ref implementation, and you should not pollute the global namespace with the class name.</p></li>\n<li><p>Use a better name; While using shortened words for names (i.e. MemWrp instead of MemoryWrapped/MemoryWrapper/MemoryWrap etc), this is only a good idea if the shortened words are traditionally used for replacement (e.g. \"ptr\" for \"pointer\" is fine, \"Mem\" for \"memory\" is fine, \"Wrp\" can be expanded into about five words easily and leads to confusion).</p></li>\n<li><p>protect it's managed resource (why is MemWrp::content public?)</p></li>\n</ul></li>\n<li><p>Ref class should:</p>\n\n<ul>\n<li><p>be renamed to _Something_Ptr or Ptr_Something_ (\"Ref\" traditionally represents a reference which has/should have reference semantics). See std::ref and std::cref for comparison. Examples: Shared_Ptr, CountedPtr, ManagedPtr, SmartPtr, etc. Just don't call it Ref.</p></li>\n<li><p>Not allow construction from a pointer converted to <code>int</code>.</p></li>\n</ul></li>\n</ul>\n\n<p>The interface of the class suggests that this code is perfectly legal:</p>\n\n<pre><code>class Qxb; // implementation is irrelevant\nRef<Qxb> ref(101); // good luck dereferencing this pointer\n</code></pre>\n\n<ul>\n<li><p>Ref class should (continued):</p>\n\n<ul>\n<li><p>Not need C-style (or any other style) casts; They are not only unnecessary, they are a symptom of bad implementation or design.</p></li>\n<li><p>Disallow construction of a Ref instance from a MemWrp instance, especially since the MemWrp class is not strongly-typed on the stored content.</p></li>\n<li><p>not implement equality comparison with ints. Your class doesn't store ints, it should not have a value equal to them. This will (probably) lead to problems in client code.</p></li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T18:14:53.800",
"Id": "75304",
"Score": "0",
"body": "Ref(int ptr) allows me to do: return NULL;"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T09:10:01.327",
"Id": "75377",
"Score": "1",
"body": "@Raffa50, it also allows you invalid examples (`return 25;` for example). If you want to simply return NULL, define `Ref::Ref(nullptr_t);` Then, use `return nullptr;` in client code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T13:19:34.027",
"Id": "43506",
"ParentId": "43472",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T20:08:54.340",
"Id": "43472",
"Score": "1",
"Tags": [
"c++",
"reinventing-the-wheel",
"smart-pointers"
],
"Title": "Smart pointer implementation"
}
|
43472
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.