Rectangle 27 49

First let me tell you how to find the problem. Then I'll tell you where it is:

I haven't even bothered to try to figure out your code. I just ran it and took 3 random-time stack samples. I did that by typing control-C and looking at the resulting stacktrace.

One way to look at it is: if a statement appears on X% of random stack traces, then it is on the stack for about X% of the time, so that is what it's responsible for. If you could avoid executing it, that is how much you would save.

OK, I took 3 stack samples. Here they are:

File "camels.py", line 87, in <module>
  print solve([fCamel, fCamel, fCamel, gap, bCamel, bCamel, bCamel])
File "camels.py", line 85, in solve
  return astar(formation, heuristic, solution, getneighbors)
File "camels.py", line 80, in astar
  openlist.put((current.g + heuristicf(neighbor), node(neighbor, current.g + 1, current)))

File "camels.py", line 87, in <module>
  print solve([fCamel, fCamel, fCamel, gap, bCamel, bCamel, bCamel])
File "camels.py", line 85, in solve
  return astar(formation, heuristic, solution, getneighbors)
File "camels.py", line 80, in astar
  openlist.put((current.g + heuristicf(neighbor), node(neighbor, current.g + 1, current)))

File "camels.py", line 87, in <module>
  print solve([fCamel, fCamel, fCamel, gap, bCamel, bCamel, bCamel])
File "camels.py", line 85, in solve
  return astar(formation, heuristic, solution, getneighbors)
File "camels.py", line 80, in astar
  openlist.put((current.g + heuristicf(neighbor), node(neighbor, current.g + 1, current)))

Notice, in this case the stack samples are all identical. In other words, each one of these three lines is individually responsible for nearly all of the time. So look at them:

line        87: print solve([fCamel, fCamel, fCamel, gap, bCamel, bCamel, bCamel])
line solve: 85: return astar(formation, heuristic, solution, getneighbors)
line astar: 80: openlist.put((current.g + heuristicf(neighbor), node(neighbor, current.g + 1, current)))

Clearly line 87 is not one you can avoid executing, and probably not 85 either. That leaves 80, the openlist.put call. Now, you can't tell if the problem is in the + operator, the heuristicf call, the node call, or in the put call. You could find out if you could split those out onto separate lines.

So I hope you pick up from this a quick and easy way to find out where your performance problems are.

Really interesting way of debugging a performance issue. Also highlights that sometimes separating calls onto their own line can be helpful.

well that ended up being a significant amount of time spent. Followed the link trail to 3 or so posts related to this technique. I've always found it extremely hard to find non-obvious problems with traditional profilers and I guess now I know why. It all makes sense. Now on to differential execution (wiki article was dropped by the way).

@MikeDunlavey Great approach. Consider adding descriptive title into your answer, something like "Find bottleneckes quickly by random sampling" (you know better how to name it). It would be more visually appealing and this is what your answer deserves.

Unfortunately, the way asynchronous exceptions are handled kind of ruins that nice approach.

python - How to improve performance of this code? - Stack Overflow

python performance optimization time-complexity
Rectangle 27 49

First let me tell you how to find the problem. Then I'll tell you where it is:

I haven't even bothered to try to figure out your code. I just ran it and took 3 random-time stack samples. I did that by typing control-C and looking at the resulting stacktrace.

One way to look at it is: if a statement appears on X% of random stack traces, then it is on the stack for about X% of the time, so that is what it's responsible for. If you could avoid executing it, that is how much you would save.

OK, I took 3 stack samples. Here they are:

File "camels.py", line 87, in <module>
  print solve([fCamel, fCamel, fCamel, gap, bCamel, bCamel, bCamel])
File "camels.py", line 85, in solve
  return astar(formation, heuristic, solution, getneighbors)
File "camels.py", line 80, in astar
  openlist.put((current.g + heuristicf(neighbor), node(neighbor, current.g + 1, current)))

File "camels.py", line 87, in <module>
  print solve([fCamel, fCamel, fCamel, gap, bCamel, bCamel, bCamel])
File "camels.py", line 85, in solve
  return astar(formation, heuristic, solution, getneighbors)
File "camels.py", line 80, in astar
  openlist.put((current.g + heuristicf(neighbor), node(neighbor, current.g + 1, current)))

File "camels.py", line 87, in <module>
  print solve([fCamel, fCamel, fCamel, gap, bCamel, bCamel, bCamel])
File "camels.py", line 85, in solve
  return astar(formation, heuristic, solution, getneighbors)
File "camels.py", line 80, in astar
  openlist.put((current.g + heuristicf(neighbor), node(neighbor, current.g + 1, current)))

Notice, in this case the stack samples are all identical. In other words, each one of these three lines is individually responsible for nearly all of the time. So look at them:

line        87: print solve([fCamel, fCamel, fCamel, gap, bCamel, bCamel, bCamel])
line solve: 85: return astar(formation, heuristic, solution, getneighbors)
line astar: 80: openlist.put((current.g + heuristicf(neighbor), node(neighbor, current.g + 1, current)))

Clearly line 87 is not one you can avoid executing, and probably not 85 either. That leaves 80, the openlist.put call. Now, you can't tell if the problem is in the + operator, the heuristicf call, the node call, or in the put call. You could find out if you could split those out onto separate lines.

So I hope you pick up from this a quick and easy way to find out where your performance problems are.

Really interesting way of debugging a performance issue. Also highlights that sometimes separating calls onto their own line can be helpful.

well that ended up being a significant amount of time spent. Followed the link trail to 3 or so posts related to this technique. I've always found it extremely hard to find non-obvious problems with traditional profilers and I guess now I know why. It all makes sense. Now on to differential execution (wiki article was dropped by the way).

@MikeDunlavey Great approach. Consider adding descriptive title into your answer, something like "Find bottleneckes quickly by random sampling" (you know better how to name it). It would be more visually appealing and this is what your answer deserves.

Unfortunately, the way asynchronous exceptions are handled kind of ruins that nice approach.

python - How to improve performance of this code? - Stack Overflow

python performance optimization time-complexity
Rectangle 27 47

Jquery later allowed you to to find the parents with the .parents() method.

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

The answer is not misleading, its just showcasing another alternative to .closest(), .parents() looks more readable and is another solution the the problem.

Closest is a better solution than this as closest will just find the first match, whereas parents will find ALL matches going up the DOM. Obviously more efficient to use closest, although I agree, it's not the best named function.

I guess it is better to give the choice to the user. Depending upon the situation, he can use the exact function :)

Funny enough, I ended up using this solution as .parentsUtil() wasn't working as i expected.

JQuery find first parent element with specific class prefix - Stack Ov...

jquery jquery-selectors
Rectangle 27 628

After searching a lot I find out that it is possible to create a new folder from the web interface, but it would require you to have at least one file within the folder when creating it.

When using the normal way of creating new files through the web interface, you can type in the folder into the file name to create the file within that new directory.

E.g. If I would like to create the file filename.md in a series of sub-folders, I can do this (taken from the GitHub Blog):

The requirement of having at least one file in the folder is actually a shortcoming of Git itself

It would be great if they made this more intuitive, like adding a "create folder" button to the web interface, while editing a file if not at the root. What they did is cool, but probably confusing to new/nontechnical users.

Rawr, yes, this is very not intuitive for first-timers. I like how they do it, but seriously, why could I not find it in their docs?

Nice tip! It saved me from moving away from Subclipse for now...

It probably has something to do with the fact that in under Linux/UNIX, there is no difference between folders and files. A folder, or directory, is just a file with the names of other files in it. tldp.org/LDP/intro-linux/html/sect_03_01.html I know it doesn't make sense to Windows folk, but it's true.

Very nice. Yes not very intuitive!

Creating folders inside github.com repo without using Git - Stack Over...

git github github-services
Rectangle 27 24

how do I find out what is referencing System.Web.WebPages.Razor v2.0.0.0?

Calling assembly : Microsoft.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
Microsoft.Web.Helpers
System.Web.WebPages.Razor, Version=2.0.0.0

As a matter of fact, it relies on System.Web.WebPages.Razor v2.0.0.0 which is only at the Release Candidate stage, and if I install it, it is breaking my application. So the solution for me now will be to revert to the previous version of Microsoft.Web.Helpers.

I still can't get this to work. I've searched the entire solution for ANY instance of 2.0.0.0 and found NOTHING! There's not one single reference to ANY assembly with a 2 in it anywhere in my solution let alone System.Web.WebPages.Razor. I've also checked the actual version number of all the assemblies from the System.Web.WebPages namespace and they're all 3.0. 1. Uninstalled the MVC package from Nuget and reinstalled it. 2. Removed the assemblyBinding elements from Web.config. 3. Cleaned/rebuilt the solution. 4. Unloaded the solution and looked through the .proj file for any references.

Ami, did you check the web.config? I was quite frustrated recently and then found it in the web.config.

asp.net mvc 3 - Could not load file or assembly 'System.Web.WebPages.R...

asp.net-mvc-3 razor dependencies asp.net-4.0
Rectangle 27 613

After searching a lot I find out that it is possible to create a new folder from the web interface, but it would require you to have at least one file within the folder when creating it.

When using the normal way of creating new files through the web interface, you can type in the folder into the file name to create the file within that new directory.

E.g. If I would like to create the file filename.md in a series of sub-folders, I can do this (taken from the GitHub Blog):

The requirement of having at least one file in the folder is actually a shortcoming of Git itself

It would be great if they made this more intuitive, like adding a "create folder" button to the web interface, while editing a file if not at the root. What they did is cool, but probably confusing to new/nontechnical users.

Rawr, yes, this is very not intuitive for first-timers. I like how they do it, but seriously, why could I not find it in their docs?

It probably has something to do with the fact that in under Linux/UNIX, there is no difference between folders and files. A folder, or directory, is just a file with the names of other files in it. tldp.org/LDP/intro-linux/html/sect_03_01.html I know it doesn't make sense to Windows folk, but it's true.

Very nice. Yes not very intuitive!

Creating folders inside github.com repo without using Git - Stack Over...

git github github-services
Rectangle 27 245

1. What does a "Cannot find symbol" error mean?

Firstly, it is a compilation error1. It means that either there is a problem in your Java source code, or there is a problem in the way that you are compiling it.

Your Java source code consists of the following things:

true
false
class
while
  • Literals: like 42 and 'X' and "Hi mum!".
  • Operators and other non-alphanumeric tokens: like +, =, {, and so on.
Reader
toString
processEquibalancedElephants
  • Comments and whitespace.

A "Cannot find symbol" error is about the identifiers. When your code is compiled, the compiler needs to work out what each and every identifier in your code means.

A "Cannot find symbol" error means that the compiler cannot do this. Your code appears to be referring to something that the compiler doesn't understand.

As a first order, there is only one cause. The compiler looked in all of the places where the identifier should be defined, and it couldn't find the definition. This could be caused by a number of things. The common ones are as follows:

  • Perhaps you spelled the name incorrectly; i.e. StringBiulder instead of StringBuilder. Java cannot and will not attempt to compensate for bad spelling or typing errors.
  • Perhaps you got the case wrong; i.e. stringBuilder instead of StringBuilder. All Java identifiers are case sensitive.
  • Perhaps you used underscores inappropriately; i.e. mystring and my_string are different. (If you stick to the Java style rules, you will be largely protected from this mistake ...)
  • Perhaps the variable declaration is out of scope at the point you tried to use it. (See example below)
  • Perhaps you are trying to refer to an inherited method or field that wasn't declared in the parent / ancestor classes or interfaces.
  • Perhaps you are trying to use a method as a field, or vice versa; e.g. "someString".length or someArray.length().
  • Perhaps you used "star" imports, but the class isn't defined in any of the packages that you imported.
  • Perhaps you forgot a new as in: String s = String(); // should be 'new String()'
  • Perhaps you have declared a nested class or a generic parameter that shadows the type you were meaning to use.
  • Perhaps you are shadowing a static or instance variable.
  • Perhaps you imported the wrong type; e.g. due to IDE completion or auto-correction.
  • Perhaps you are using (compiling against) the wrong version of an API.

The problem is often a combination of the above. For example, maybe you "star" imported java.io.* and then tried to use the Files class ... which is in java.nio not java.io. Or maybe you meant to write File ... which is a class in java.io.

Here is an example of how incorrect variable scoping can lead to a "Cannot find symbol" error:

for (int i = 0; i < strings.size(); i++) {
    if (strings.get(i).equalsIgnoreCase("fnoord")) {
        break;
    }
}
if (i < strings.size()) {
    ...
}

This will give a "Cannot find symbol" error for i in the if statement. Though we previously declared i, that declaration is only in scope for the for statement and its body. The reference to i in the if statement cannot see that declaration of i. It is out of scope.

(An appropriate correction here might be to move the if statement inside the loop, or to declare i before the start of the loop.)

Here is an example that causes puzzlement where a typo leads to a seemingly inexplicable "Cannot find symbol" error:

This will give you a compilation error in the println call saying that i cannot be found. But (I hear you say) I did declare it!

The problem is the sneaky semicolon before the {. The Java language defines that to be an empty statement. So that code actually means this:

for (int i = 0; i < 100; i++); 

{
    System.out.println("i is " + i);
}

The { ... } block is NOT the body of the for loop, so the declaration of i is not in scope in the the block.

Here is another example of "Cannot find symbol" error that is caused by a typo.

int tmp = ...
int res = tmp(a + b);

Despite the previous declaration, the tmp in the tmp(...) expression is erroneous. The compiler will look for a method called tmp, and won't find one. The previously declared tmp is in the namespace for variables, not the namespace for methods.

In the example I came across, the programmer had actually left out an operator. What he meant to write was this:

int res = tmp * (a + b);

There is another reason why the compiler might not find a symbol if you are compiling from the command line. You might simply have forgotten to compile or recompile some other class. For example, if you have classes Foo and Bar where Foo uses Bar. If you have never compiled Bar and you run javac Foo.java, you are liable to find that the compiler can't find the symbol Bar. The simple answer is to Foo and Bar together; e.g. javac Foo.java Bar.java or javac *.java. Or better still use a Java build tool; e.g. Ant, Maven, Gradle and so on.

Generally speaking, you start out by figuring out what caused the compilation error.

  • Look at the line in the file indicated by the compilation error message.
  • Identify which symbol that the error message is talking about.
  • Figure out why the compiler is saying that it cannot find the symbol; see above!

Then you think about what your code is supposed to be saying. Then finally you work out what correction you need to make to your source code to do what you want.

Note that not every "correction" is correct. Consider this:

for (int i = 1; i < 10; i++) {
    for (j = 1; j < 10; j++) {
        ...
    }
}

Suppose that the compiler says "Cannot find symbol" for j. There are many ways I could "fix" that:

for
for (int j = 1; j < 10; j++)
  • I could add a declaration for j before the inner for loop, or the outer for loop - possibly correct.
  • I could change j to i in the inner for loop - probably wrong!

The point is that you need to understand what your code is trying to do in order to find the right fix.

Here are a couple of cases where the "Cannot find symbol" is seemingly inexplicable ... until you look closer.

You are looking at the wrong source code: It often happens that a new Java programmers don't understand how the Java tool chain works, or haven't implemented a repeatable "build process"; e.g. using an IDE, Ant, Maven, Gradle and so on. In such a situation, the programmer can end up chasing his tail looking for an illusory error that is actually caused by not recompiling the code properly, and the like ...

IDE issues: People have reported cases where their IDE gets confused and the compiler in the IDE cannot find a class that exists ... or the reverse situation.

Redefining system classes: I've seen cases where the compiler complains that substring is an unknown symbol in something like the following

String s = ...
String s1 = s.substring(1);

It turned out that the programmer had created their own version of String and that his version of the class didn't define a substring methods.

Lesson: Don't define your own classes with the same names as common library classes!

Homoglyphs: If you use UTF-8 encoding for your source files, it is possible to have identifiers that look the same, but are in fact different because they contain homoglyphs. See this page for more information.

You can avoid this by restricting yourself to ASCII or Latin-1 as the source file encoding, and using Java \uxxxx escapes for other characters.

I had another situation where this compilation error occured while eclipse didn't see the problem: Two classes with dependencies defined in the respectively other class. In my case I had an enum, implementing an interface, defined in a class where I foolishly already used the enum.

Somewhat similarly to the comment above, when I compile and run my program from Eclipse it works no problem. Compiling it from the console raises a bunch of these "Cannot find symbol" errors often related to last element in an import. I have no idea what is causing this as there is nothing wrong in the code really.

Another common one I don't see listed (maybe I'm just missing it in the list) is a method named without () after it like String s = ""; int len = s.length;

java - What does a "Cannot find symbol" compilation error mean? - Stac...

java compiler-errors cannot-find-symbol
Rectangle 27 235

1. What does a "Cannot find symbol" error mean?

Firstly, it is a compilation error1. It means that either there is a problem in your Java source code, or there is a problem in the way that you are compiling it.

Your Java source code consists of the following things:

true
false
class
while
  • Literals: like 42 and 'X' and "Hi mum!".
  • Operators and other non-alphanumeric tokens: like +, =, {, and so on.
Reader
toString
processEquibalancedElephants
  • Comments and whitespace.

A "Cannot find symbol" error is about the identifiers. When your code is compiled, the compiler needs to work out what each and every identifier in your code means.

A "Cannot find symbol" error means that the compiler cannot do this. Your code appears to be referring to something that the compiler doesn't understand.

As a first order, there is only one cause. The compiler looked in all of the places where the identifier should be defined, and it couldn't find the definition. This could be caused by a number of things. The common ones are as follows:

  • Perhaps you spelled the name incorrectly; i.e. StringBiulder instead of StringBuilder. Java cannot and will not attempt to compensate for bad spelling or typing errors.
  • Perhaps you got the case wrong; i.e. stringBuilder instead of StringBuilder. All Java identifiers are case sensitive.
  • Perhaps you used underscores inappropriately; i.e. mystring and my_string are different. (If you stick to the Java style rules, you will be largely protected from this mistake ...)
  • Perhaps the variable declaration is out of scope at the point you tried to use it. (See example below)
  • Perhaps you are trying to refer to an inherited method or field that wasn't declared in the parent / ancestor classes or interfaces.
  • Perhaps you are trying to use a method as a field, or vice versa; e.g. "someString".length or someArray.length().
  • Perhaps you used "star" imports, but the class isn't defined in any of the packages that you imported.
  • Perhaps you forgot a new as in: String s = String(); // should be 'new String()'
  • Perhaps you have declared a nested class or a generic parameter that shadows the type you were meaning to use.
  • Perhaps you are shadowing a static or instance variable.
  • Perhaps you imported the wrong type; e.g. due to IDE completion or auto-correction.
  • Perhaps you are using (compiling against) the wrong version of an API.

The problem is often a combination of the above. For example, maybe you "star" imported java.io.* and then tried to use the Files class ... which is in java.nio not java.io. Or maybe you meant to write File ... which is a class in java.io.

Here is an example of how incorrect variable scoping can lead to a "Cannot find symbol" error:

for (int i = 0; i < strings.size(); i++) {
    if (strings.get(i).equalsIgnoreCase("fnoord")) {
        break;
    }
}
if (i < strings.size()) {
    ...
}

This will give a "Cannot find symbol" error for i in the if statement. Though we previously declared i, that declaration is only in scope for the for statement and its body. The reference to i in the if statement cannot see that declaration of i. It is out of scope.

(An appropriate correction here might be to move the if statement inside the loop, or to declare i before the start of the loop.)

Here is an example that causes puzzlement where a typo leads to a seemingly inexplicable "Cannot find symbol" error:

This will give you a compilation error in the println call saying that i cannot be found. But (I hear you say) I did declare it!

The problem is the sneaky semicolon before the {. The Java language defines that to be an empty statement. So that code actually means this:

for (int i = 0; i < 100; i++); 

{
    System.out.println("i is " + i);
}

The { ... } block is NOT the body of the for loop, so the declaration of i is not in scope in the the block.

Here is another example of "Cannot find symbol" error that is caused by a typo.

int tmp = ...
int res = tmp(a + b);

Despite the previous declaration, the tmp in the tmp(...) expression is erroneous. The compiler will look for a method called tmp, and won't find one. The previously declared tmp is in the namespace for variables, not the namespace for methods.

In the example I came across, the programmer had actually left out an operator. What he meant to write was this:

int res = tmp * (a + b);

There is another reason why the compiler might not find a symbol if you are compiling from the command line. You might simply have forgotten to compile or recompile some other class. For example, if you have classes Foo and Bar where Foo uses Bar. If you have never compiled Bar and you run javac Foo.java, you are liable to find that the compiler can't find the symbol Bar. The simple answer is to Foo and Bar together; e.g. javac Foo.java Bar.java or javac *.java. Or better still use a Java build tool; e.g. Ant, Maven, Gradle and so on.

Generally speaking, you start out by figuring out what caused the compilation error.

  • Look at the line in the file indicated by the compilation error message.
  • Identify which symbol that the error message is talking about.
  • Figure out why the compiler is saying that it cannot find the symbol; see above!

Then you think about what your code is supposed to be saying. Then finally you work out what correction you need to make to your source code to do what you want.

Note that not every "correction" is correct. Consider this:

for (int i = 1; i < 10; i++) {
    for (j = 1; j < 10; j++) {
        ...
    }
}

Suppose that the compiler says "Cannot find symbol" for j. There are many ways I could "fix" that:

for
for (int j = 1; j < 10; j++)
  • I could add a declaration for j before the inner for loop, or the outer for loop - possibly correct.
  • I could change j to i in the inner for loop - probably wrong!

The point is that you need to understand what your code is trying to do in order to find the right fix.

Here are a couple of cases where the "Cannot find symbol" is seemingly inexplicable ... until you look closer.

You are looking at the wrong source code: It often happens that a new Java programmers don't understand how the Java tool chain works, or haven't implemented a repeatable "build process"; e.g. using an IDE, Ant, Maven, Gradle and so on. In such a situation, the programmer can end up chasing his tail looking for an illusory error that is actually caused by not recompiling the code properly, and the like ...

IDE issues: People have reported cases where their IDE gets confused and the compiler in the IDE cannot find a class that exists ... or the reverse situation.

Redefining system classes: I've seen cases where the compiler complains that substring is an unknown symbol in something like the following

String s = ...
String s1 = s.substring(1);

It turned out that the programmer had created their own version of String and that his version of the class didn't define a substring methods.

Lesson: Don't define your own classes with the same names as common library classes!

Homoglyphs: If you use UTF-8 encoding for your source files, it is possible to have identifiers that look the same, but are in fact different because they contain homoglyphs. See this page for more information.

You can avoid this by restricting yourself to ASCII or Latin-1 as the source file encoding, and using Java \uxxxx escapes for other characters.

I had another situation where this compilation error occured while eclipse didn't see the problem: Two classes with dependencies defined in the respectively other class. In my case I had an enum, implementing an interface, defined in a class where I foolishly already used the enum.

Somewhat similarly to the comment above, when I compile and run my program from Eclipse it works no problem. Compiling it from the console raises a bunch of these "Cannot find symbol" errors often related to last element in an import. I have no idea what is causing this as there is nothing wrong in the code really.

@AndresStadelmann - Without seeing the code, I can't comment. If you want help from someone ask a Question.

@StephenC Hello! So here's the thing. The program that I wrote is a huge 13 week work in progress that I've only ever launched and compiled in eclipse. I'm working on implementing server functionalities and for that I would rather launch the program from a console with the required variables. The only feedback I've been getting from this is are these errors, so I casually came looking for answers online. Once I get really desperate I'll probably ask a more detailed question, but thanks for your concern. (Sorry for my ramble)

Also, for identifiers that are in a different class.

java - What does a "Cannot find symbol" compilation error mean? - Stac...

java compiler-errors cannot-find-symbol
Rectangle 27 235

1. What does a "Cannot find symbol" error mean?

Firstly, it is a compilation error1. It means that either there is a problem in your Java source code, or there is a problem in the way that you are compiling it.

Your Java source code consists of the following things:

true
false
class
while
  • Literals: like 42 and 'X' and "Hi mum!".
  • Operators and other non-alphanumeric tokens: like +, =, {, and so on.
Reader
toString
processEquibalancedElephants
  • Comments and whitespace.

A "Cannot find symbol" error is about the identifiers. When your code is compiled, the compiler needs to work out what each and every identifier in your code means.

A "Cannot find symbol" error means that the compiler cannot do this. Your code appears to be referring to something that the compiler doesn't understand.

As a first order, there is only one cause. The compiler looked in all of the places where the identifier should be defined, and it couldn't find the definition. This could be caused by a number of things. The common ones are as follows:

  • Perhaps you spelled the name incorrectly; i.e. StringBiulder instead of StringBuilder. Java cannot and will not attempt to compensate for bad spelling or typing errors.
  • Perhaps you got the case wrong; i.e. stringBuilder instead of StringBuilder. All Java identifiers are case sensitive.
  • Perhaps you used underscores inappropriately; i.e. mystring and my_string are different. (If you stick to the Java style rules, you will be largely protected from this mistake ...)
  • Perhaps the variable declaration is out of scope at the point you tried to use it. (See example below)
  • Perhaps you are trying to refer to an inherited method or field that wasn't declared in the parent / ancestor classes or interfaces.
  • Perhaps you are trying to use a method as a field, or vice versa; e.g. "someString".length or someArray.length().
  • Perhaps you used "star" imports, but the class isn't defined in any of the packages that you imported.
  • Perhaps you forgot a new as in: String s = String(); // should be 'new String()'
  • Perhaps you have declared a nested class or a generic parameter that shadows the type you were meaning to use.
  • Perhaps you are shadowing a static or instance variable.
  • Perhaps you imported the wrong type; e.g. due to IDE completion or auto-correction.
  • Perhaps you are using (compiling against) the wrong version of an API.

The problem is often a combination of the above. For example, maybe you "star" imported java.io.* and then tried to use the Files class ... which is in java.nio not java.io. Or maybe you meant to write File ... which is a class in java.io.

Here is an example of how incorrect variable scoping can lead to a "Cannot find symbol" error:

for (int i = 0; i < strings.size(); i++) {
    if (strings.get(i).equalsIgnoreCase("fnoord")) {
        break;
    }
}
if (i < strings.size()) {
    ...
}

This will give a "Cannot find symbol" error for i in the if statement. Though we previously declared i, that declaration is only in scope for the for statement and its body. The reference to i in the if statement cannot see that declaration of i. It is out of scope.

(An appropriate correction here might be to move the if statement inside the loop, or to declare i before the start of the loop.)

Here is an example that causes puzzlement where a typo leads to a seemingly inexplicable "Cannot find symbol" error:

This will give you a compilation error in the println call saying that i cannot be found. But (I hear you say) I did declare it!

The problem is the sneaky semicolon before the {. The Java language defines that to be an empty statement. So that code actually means this:

for (int i = 0; i < 100; i++); 

{
    System.out.println("i is " + i);
}

The { ... } block is NOT the body of the for loop, so the declaration of i is not in scope in the the block.

Here is another example of "Cannot find symbol" error that is caused by a typo.

int tmp = ...
int res = tmp(a + b);

Despite the previous declaration, the tmp in the tmp(...) expression is erroneous. The compiler will look for a method called tmp, and won't find one. The previously declared tmp is in the namespace for variables, not the namespace for methods.

In the example I came across, the programmer had actually left out an operator. What he meant to write was this:

int res = tmp * (a + b);

There is another reason why the compiler might not find a symbol if you are compiling from the command line. You might simply have forgotten to compile or recompile some other class. For example, if you have classes Foo and Bar where Foo uses Bar. If you have never compiled Bar and you run javac Foo.java, you are liable to find that the compiler can't find the symbol Bar. The simple answer is to Foo and Bar together; e.g. javac Foo.java Bar.java or javac *.java. Or better still use a Java build tool; e.g. Ant, Maven, Gradle and so on.

Generally speaking, you start out by figuring out what caused the compilation error.

  • Look at the line in the file indicated by the compilation error message.
  • Identify which symbol that the error message is talking about.
  • Figure out why the compiler is saying that it cannot find the symbol; see above!

Then you think about what your code is supposed to be saying. Then finally you work out what correction you need to make to your source code to do what you want.

Note that not every "correction" is correct. Consider this:

for (int i = 1; i < 10; i++) {
    for (j = 1; j < 10; j++) {
        ...
    }
}

Suppose that the compiler says "Cannot find symbol" for j. There are many ways I could "fix" that:

for
for (int j = 1; j < 10; j++)
  • I could add a declaration for j before the inner for loop, or the outer for loop - possibly correct.
  • I could change j to i in the inner for loop - probably wrong!

The point is that you need to understand what your code is trying to do in order to find the right fix.

Here are a couple of cases where the "Cannot find symbol" is seemingly inexplicable ... until you look closer.

You are looking at the wrong source code: It often happens that a new Java programmers don't understand how the Java tool chain works, or haven't implemented a repeatable "build process"; e.g. using an IDE, Ant, Maven, Gradle and so on. In such a situation, the programmer can end up chasing his tail looking for an illusory error that is actually caused by not recompiling the code properly, and the like ...

IDE issues: People have reported cases where their IDE gets confused and the compiler in the IDE cannot find a class that exists ... or the reverse situation.

Redefining system classes: I've seen cases where the compiler complains that substring is an unknown symbol in something like the following

String s = ...
String s1 = s.substring(1);

It turned out that the programmer had created their own version of String and that his version of the class didn't define a substring methods.

Lesson: Don't define your own classes with the same names as common library classes!

Homoglyphs: If you use UTF-8 encoding for your source files, it is possible to have identifiers that look the same, but are in fact different because they contain homoglyphs. See this page for more information.

You can avoid this by restricting yourself to ASCII or Latin-1 as the source file encoding, and using Java \uxxxx escapes for other characters.

I had another situation where this compilation error occured while eclipse didn't see the problem: Two classes with dependencies defined in the respectively other class. In my case I had an enum, implementing an interface, defined in a class where I foolishly already used the enum.

Somewhat similarly to the comment above, when I compile and run my program from Eclipse it works no problem. Compiling it from the console raises a bunch of these "Cannot find symbol" errors often related to last element in an import. I have no idea what is causing this as there is nothing wrong in the code really.

@AndresStadelmann - Without seeing the code, I can't comment. If you want help from someone ask a Question.

@StephenC Hello! So here's the thing. The program that I wrote is a huge 13 week work in progress that I've only ever launched and compiled in eclipse. I'm working on implementing server functionalities and for that I would rather launch the program from a console with the required variables. The only feedback I've been getting from this is are these errors, so I casually came looking for answers online. Once I get really desperate I'll probably ask a more detailed question, but thanks for your concern. (Sorry for my ramble)

Also, for identifiers that are in a different class.

java - What does a "Cannot find symbol" compilation error mean? - Stac...

java compiler-errors cannot-find-symbol
Rectangle 27 235

1. What does a "Cannot find symbol" error mean?

Firstly, it is a compilation error1. It means that either there is a problem in your Java source code, or there is a problem in the way that you are compiling it.

Your Java source code consists of the following things:

true
false
class
while
  • Literals: like 42 and 'X' and "Hi mum!".
  • Operators and other non-alphanumeric tokens: like +, =, {, and so on.
Reader
toString
processEquibalancedElephants
  • Comments and whitespace.

A "Cannot find symbol" error is about the identifiers. When your code is compiled, the compiler needs to work out what each and every identifier in your code means.

A "Cannot find symbol" error means that the compiler cannot do this. Your code appears to be referring to something that the compiler doesn't understand.

As a first order, there is only one cause. The compiler looked in all of the places where the identifier should be defined, and it couldn't find the definition. This could be caused by a number of things. The common ones are as follows:

  • Perhaps you spelled the name incorrectly; i.e. StringBiulder instead of StringBuilder. Java cannot and will not attempt to compensate for bad spelling or typing errors.
  • Perhaps you got the case wrong; i.e. stringBuilder instead of StringBuilder. All Java identifiers are case sensitive.
  • Perhaps you used underscores inappropriately; i.e. mystring and my_string are different. (If you stick to the Java style rules, you will be largely protected from this mistake ...)
  • Perhaps the variable declaration is out of scope at the point you tried to use it. (See example below)
  • Perhaps you are trying to refer to an inherited method or field that wasn't declared in the parent / ancestor classes or interfaces.
  • Perhaps you are trying to use a method as a field, or vice versa; e.g. "someString".length or someArray.length().
  • Perhaps you used "star" imports, but the class isn't defined in any of the packages that you imported.
  • Perhaps you forgot a new as in: String s = String(); // should be 'new String()'
  • Perhaps you have declared a nested class or a generic parameter that shadows the type you were meaning to use.
  • Perhaps you are shadowing a static or instance variable.
  • Perhaps you imported the wrong type; e.g. due to IDE completion or auto-correction.
  • Perhaps you are using (compiling against) the wrong version of an API.

The problem is often a combination of the above. For example, maybe you "star" imported java.io.* and then tried to use the Files class ... which is in java.nio not java.io. Or maybe you meant to write File ... which is a class in java.io.

Here is an example of how incorrect variable scoping can lead to a "Cannot find symbol" error:

for (int i = 0; i < strings.size(); i++) {
    if (strings.get(i).equalsIgnoreCase("fnoord")) {
        break;
    }
}
if (i < strings.size()) {
    ...
}

This will give a "Cannot find symbol" error for i in the if statement. Though we previously declared i, that declaration is only in scope for the for statement and its body. The reference to i in the if statement cannot see that declaration of i. It is out of scope.

(An appropriate correction here might be to move the if statement inside the loop, or to declare i before the start of the loop.)

Here is an example that causes puzzlement where a typo leads to a seemingly inexplicable "Cannot find symbol" error:

This will give you a compilation error in the println call saying that i cannot be found. But (I hear you say) I did declare it!

The problem is the sneaky semicolon before the {. The Java language defines that to be an empty statement. So that code actually means this:

for (int i = 0; i < 100; i++); 

{
    System.out.println("i is " + i);
}

The { ... } block is NOT the body of the for loop, so the declaration of i is not in scope in the the block.

Here is another example of "Cannot find symbol" error that is caused by a typo.

int tmp = ...
int res = tmp(a + b);

Despite the previous declaration, the tmp in the tmp(...) expression is erroneous. The compiler will look for a method called tmp, and won't find one. The previously declared tmp is in the namespace for variables, not the namespace for methods.

In the example I came across, the programmer had actually left out an operator. What he meant to write was this:

int res = tmp * (a + b);

There is another reason why the compiler might not find a symbol if you are compiling from the command line. You might simply have forgotten to compile or recompile some other class. For example, if you have classes Foo and Bar where Foo uses Bar. If you have never compiled Bar and you run javac Foo.java, you are liable to find that the compiler can't find the symbol Bar. The simple answer is to Foo and Bar together; e.g. javac Foo.java Bar.java or javac *.java. Or better still use a Java build tool; e.g. Ant, Maven, Gradle and so on.

Generally speaking, you start out by figuring out what caused the compilation error.

  • Look at the line in the file indicated by the compilation error message.
  • Identify which symbol that the error message is talking about.
  • Figure out why the compiler is saying that it cannot find the symbol; see above!

Then you think about what your code is supposed to be saying. Then finally you work out what correction you need to make to your source code to do what you want.

Note that not every "correction" is correct. Consider this:

for (int i = 1; i < 10; i++) {
    for (j = 1; j < 10; j++) {
        ...
    }
}

Suppose that the compiler says "Cannot find symbol" for j. There are many ways I could "fix" that:

for
for (int j = 1; j < 10; j++)
  • I could add a declaration for j before the inner for loop, or the outer for loop - possibly correct.
  • I could change j to i in the inner for loop - probably wrong!

The point is that you need to understand what your code is trying to do in order to find the right fix.

Here are a couple of cases where the "Cannot find symbol" is seemingly inexplicable ... until you look closer.

You are looking at the wrong source code: It often happens that a new Java programmers don't understand how the Java tool chain works, or haven't implemented a repeatable "build process"; e.g. using an IDE, Ant, Maven, Gradle and so on. In such a situation, the programmer can end up chasing his tail looking for an illusory error that is actually caused by not recompiling the code properly, and the like ...

IDE issues: People have reported cases where their IDE gets confused and the compiler in the IDE cannot find a class that exists ... or the reverse situation.

Redefining system classes: I've seen cases where the compiler complains that substring is an unknown symbol in something like the following

String s = ...
String s1 = s.substring(1);

It turned out that the programmer had created their own version of String and that his version of the class didn't define a substring methods.

Lesson: Don't define your own classes with the same names as common library classes!

Homoglyphs: If you use UTF-8 encoding for your source files, it is possible to have identifiers that look the same, but are in fact different because they contain homoglyphs. See this page for more information.

You can avoid this by restricting yourself to ASCII or Latin-1 as the source file encoding, and using Java \uxxxx escapes for other characters.

I had another situation where this compilation error occured while eclipse didn't see the problem: Two classes with dependencies defined in the respectively other class. In my case I had an enum, implementing an interface, defined in a class where I foolishly already used the enum.

Somewhat similarly to the comment above, when I compile and run my program from Eclipse it works no problem. Compiling it from the console raises a bunch of these "Cannot find symbol" errors often related to last element in an import. I have no idea what is causing this as there is nothing wrong in the code really.

@AndresStadelmann - Without seeing the code, I can't comment. If you want help from someone ask a Question.

@StephenC Hello! So here's the thing. The program that I wrote is a huge 13 week work in progress that I've only ever launched and compiled in eclipse. I'm working on implementing server functionalities and for that I would rather launch the program from a console with the required variables. The only feedback I've been getting from this is are these errors, so I casually came looking for answers online. Once I get really desperate I'll probably ask a more detailed question, but thanks for your concern. (Sorry for my ramble)

Also, for identifiers that are in a different class.

java - What does a "Cannot find symbol" compilation error mean? - Stac...

java compiler-errors cannot-find-symbol
Rectangle 27 227

1. What does a "Cannot find symbol" error mean?

Firstly, it is a compilation error1. It means that either there is a problem in your Java source code, or there is a problem in the way that you are compiling it.

Your Java source code consists of the following things:

true
false
class
while
  • Literals: like 42 and 'X' and "Hi mum!".
  • Operators and other non-alphanumeric tokens: like +, =, {, and so on.
Reader
toString
processEquibalancedElephants
  • Comments and whitespace.

A "Cannot find symbol" error is about the identifiers. When your code is compiled, the compiler needs to work out what each and every identifier in your code means.

A "Cannot find symbol" error means that the compiler cannot do this. Your code appears to be referring to something that the compiler doesn't understand.

As a first order, there is only one cause. The compiler looked in all of the places where the identifier should be defined, and it couldn't find the definition. This could be caused by a number of things. The common ones are as follows:

  • Perhaps you spelled the name incorrectly; i.e. StringBiulder instead of StringBuilder. Java cannot and will not attempt to compensate for bad spelling or typing errors.
  • Perhaps you got the case wrong; i.e. stringBuilder instead of StringBuilder. All Java identifiers are case sensitive.
  • Perhaps you used underscores inappropriately; i.e. mystring and my_string are different. (If you stick to the Java style rules, you will be largely protected from this mistake ...)
  • Perhaps the variable declaration is out of scope at the point you tried to use it. (See example below)
  • Perhaps you are trying to refer to an inherited method or field that wasn't declared in the parent / ancestor classes or interfaces.
  • Perhaps you are trying to use a method as a field, or vice versa; e.g. "someString".length or someArray.length().
  • Perhaps you used "star" imports, but the class isn't defined in any of the packages that you imported.
  • Perhaps you forgot a new as in: String s = String(); // should be 'new String()'
  • Perhaps you have declared a nested class or a generic parameter that shadows the type you were meaning to use.
  • Perhaps you are shadowing a static or instance variable.
  • Perhaps you imported the wrong type; e.g. due to IDE completion or auto-correction.
  • Perhaps you are using (compiling against) the wrong version of an API.

The problem is often a combination of the above. For example, maybe you "star" imported java.io.* and then tried to use the Files class ... which is in java.nio not java.io. Or maybe you meant to write File ... which is a class in java.io.

Here is an example of how incorrect variable scoping can lead to a "Cannot find symbol" error:

for (int i = 0; i < strings.size(); i++) {
    if (strings.get(i).equalsIgnoreCase("fnoord")) {
        break;
    }
}
if (i < strings.size()) {
    ...
}

This will give a "Cannot find symbol" error for i in the if statement. Though we previously declared i, that declaration is only in scope for the for statement and its body. The reference to i in the if statement cannot see that declaration of i. It is out of scope.

(An appropriate correction here might be to move the if statement inside the loop, or to declare i before the start of the loop.)

Here is an example that causes puzzlement where a typo leads to a seemingly inexplicable "Cannot find symbol" error:

This will give you a compilation error in the println call saying that i cannot be found. But (I hear you say) I did declare it!

The problem is the sneaky semicolon before the {. The Java language defines that to be an empty statement. So that code actually means this:

for (int i = 0; i < 100; i++); 

{
    System.out.println("i is " + i);
}

The { ... } block is NOT the body of the for loop, so the declaration of i is not in scope in the the block.

Here is another example of "Cannot find symbol" error that is caused by a typo.

int tmp = ...
int res = tmp(a + b);

Despite the previous declaration, the tmp in the tmp(...) expression is erroneous. The compiler will look for a method called tmp, and won't find one. The previously declared tmp is in the namespace for variables, not the namespace for methods.

In the example I came across, the programmer had actually left out an operator. What he meant to write was this:

int res = tmp * (a + b);

There is another reason why the compiler might not find a symbol if you are compiling from the command line. You might simply have forgotten to compile or recompile some other class. For example, if you have classes Foo and Bar where Foo uses Bar. If you have never compiled Bar and you run javac Foo.java, you are liable to find that the compiler can't find the symbol Bar. The simple answer is to Foo and Bar together; e.g. javac Foo.java Bar.java or javac *.java. Or better still use a Java build tool; e.g. Ant, Maven, Gradle and so on.

Generally speaking, you start out by figuring out what caused the compilation error.

  • Look at the line in the file indicated by the compilation error message.
  • Identify which symbol that the error message is talking about.
  • Figure out why the compiler is saying that it cannot find the symbol; see above!

Then you think about what your code is supposed to be saying. Then finally you work out what correction you need to make to your source code to do what you want.

Note that not every "correction" is correct. Consider this:

for (int i = 1; i < 10; i++) {
    for (j = 1; j < 10; j++) {
        ...
    }
}

Suppose that the compiler says "Cannot find symbol" for j. There are many ways I could "fix" that:

for
for (int j = 1; j < 10; j++)
  • I could add a declaration for j before the inner for loop, or the outer for loop - possibly correct.
  • I could change j to i in the inner for loop - probably wrong!

The point is that you need to understand what your code is trying to do in order to find the right fix.

Here are a couple of cases where the "Cannot find symbol" is seemingly inexplicable ... until you look closer.

You are looking at the wrong source code: It often happens that a new Java programmers don't understand how the Java tool chain works, or haven't implemented a repeatable "build process"; e.g. using an IDE, Ant, Maven, Gradle and so on. In such a situation, the programmer can end up chasing his tail looking for an illusory error that is actually caused by not recompiling the code properly, and the like ...

IDE issues: People have reported cases where their IDE gets confused and the compiler in the IDE cannot find a class that exists ... or the reverse situation.

Redefining system classes: I've seen cases where the compiler complains that substring is an unknown symbol in something like the following

String s = ...
String s1 = s.substring(1);

It turned out that the programmer had created their own version of String and that his version of the class didn't define a substring methods.

Lesson: Don't define your own classes with the same names as common library classes!

Homoglyphs: If you use UTF-8 encoding for your source files, it is possible to have identifiers that look the same, but are in fact different because they contain homoglyphs. See this page for more information.

You can avoid this by restricting yourself to ASCII or Latin-1 as the source file encoding, and using Java \uxxxx escapes for other characters.

I had another situation where this compilation error occured while eclipse didn't see the problem: Two classes with dependencies defined in the respectively other class. In my case I had an enum, implementing an interface, defined in a class where I foolishly already used the enum.

Somewhat similarly to the comment above, when I compile and run my program from Eclipse it works no problem. Compiling it from the console raises a bunch of these "Cannot find symbol" errors often related to last element in an import. I have no idea what is causing this as there is nothing wrong in the code really.

@AndresStadelmann - Without seeing the code, I can't comment. If you want help from someone ask a Question.

@StephenC Hello! So here's the thing. The program that I wrote is a huge 13 week work in progress that I've only ever launched and compiled in eclipse. I'm working on implementing server functionalities and for that I would rather launch the program from a console with the required variables. The only feedback I've been getting from this is are these errors, so I casually came looking for answers online. Once I get really desperate I'll probably ask a more detailed question, but thanks for your concern. (Sorry for my ramble)

Also, for identifiers that are in a different class.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - What does a "Cannot find symbol" compilation error mean? - Stac...

java compiler-errors cannot-find-symbol
Rectangle 27 100

P7 and P8 are the important ones to find out where the P9 exception was raised. Use P4 to know what assembly to look for. Run ildasm.exe and open that assembly. File + Dump, tick the "Token values" checkbox, OK and save the .il file somewhere.

Open the file in a text editor. P7 gives you the method token, it starts with 0x06, producing token value "06000129". Search for:

.method /*06000129*/

Which gives you the method name, look up from there to find the .class, that gives you the class name.

P8 gives you the IL offset. From the found .method, look for IL_0050 for the instruction that raised the exception. Mapping it back to your source code is a bit tricky but you'll probably figure it out. Use Reflector if necessary.

In general, write an event handler for AppDomain.UnhandledException to avoid the pain of reverse-engineering these Watson crash buckets. Log the value of e.ExceptionObject.ToString() to get both the exception message and a stack trace.

If the exception occurs in library code, you are likely to need the stack trace anyways to figure out which of your code was on the stack. (Would be nice if Microsoft would modify that dialog to be nicer to .NET.)

In addition to handling UnhandledException, it also helps to try/catch right inside Main, since sometimes the problem happens before the UnhandledException handler is installed.

I think this is going to save me my friend. I've got an ASP.NET application that's fallen in my lap that keeps crashing the application pool - and an error listing CLR20R3 with a bunch of those P values is getting logged right around the crash time. It may be messy, but it will probably lead me to a solution, but in the end I'm going to have to modify this code and get some real logging going on.

Very useful +10 if I could - in my case it was a StackOverFlow exception and my catch blog didn't execute.

In following this, I have found the function our code is crashing on is an abstract virtual function.. method /*06003452*/ public hidebysig newslot abstract virtual instance int32 Read([in][out] uint8[] buffer, int32 offset, int32 count) cil managed { } // end of method Stream::Read

Deciphering the .NET clr20r3 exception parameters P1..P10 - Stack Over...

.net exception clr
Rectangle 27 6

for others that find this in the search:

I often get this one when I accidentally call a function using the class name rather than the object name. This typically happens because i give them too similar names : P

MyClass myclass = new MyClass();

// then later

MyClass.someFunction();
myclass.someFunction();

It's such a silly mistake, but every couple of months, i waste about 30 mins messing with vars in the "MyClass" definitions to work out what im doing wrong when really, its just a typo.

Funny note: stack overflow highlights the syntax to make the mistake really obvious here.

java - Cannot make a static reference to the non-static method - Stack...

java compiler-errors static-methods
Rectangle 27 168

It would be a lot nicer if javascript had namespaces built in, but I find that organizing things like Dustin Diaz describes here helps me a lot.

var DED = (function() {

    var private_var;

    function private_method()
    {
        // do stuff here
    }

    return {
        method_1 : function()
            {
                // do stuff here
            },
        method_2 : function()
            {
                // do stuff here
            }
    };
})();

I put different "namespaces" and sometimes individual classes in separate files. Usually I start with one file and as a class or namespace gets big enough to warrant it, I separate it out into its own file. Using a tool to combine all you files for production is an excellent idea as well.

I usually refer to that as "the crockford way". +1 from me

@MattBriggs otherwise called the module pattern and it is based on the IIFE pattern.

Don't you need to export classes somehow? How does an object get created from the outside of such a module? Or should there be a method createNewSomething() in the return object, so object creation happens solely within the module? Hm... I would expect that classes (constructors) are visisble from the outside.

jquery - Commonly accepted best practices around code organization in ...

javascript jquery design-patterns architecture formatting
Rectangle 27 168

It would be a lot nicer if javascript had namespaces built in, but I find that organizing things like Dustin Diaz describes here helps me a lot.

var DED = (function() {

    var private_var;

    function private_method()
    {
        // do stuff here
    }

    return {
        method_1 : function()
            {
                // do stuff here
            },
        method_2 : function()
            {
                // do stuff here
            }
    };
})();

I put different "namespaces" and sometimes individual classes in separate files. Usually I start with one file and as a class or namespace gets big enough to warrant it, I separate it out into its own file. Using a tool to combine all you files for production is an excellent idea as well.

I usually refer to that as "the crockford way". +1 from me

@MattBriggs otherwise called the module pattern and it is based on the IIFE pattern.

Don't you need to export classes somehow? How does an object get created from the outside of such a module? Or should there be a method createNewSomething() in the return object, so object creation happens solely within the module? Hm... I would expect that classes (constructors) are visisble from the outside.

jquery - Commonly accepted best practices around code organization in ...

javascript jquery design-patterns architecture formatting
Rectangle 27 168

It would be a lot nicer if javascript had namespaces built in, but I find that organizing things like Dustin Diaz describes here helps me a lot.

var DED = (function() {

    var private_var;

    function private_method()
    {
        // do stuff here
    }

    return {
        method_1 : function()
            {
                // do stuff here
            },
        method_2 : function()
            {
                // do stuff here
            }
    };
})();

I put different "namespaces" and sometimes individual classes in separate files. Usually I start with one file and as a class or namespace gets big enough to warrant it, I separate it out into its own file. Using a tool to combine all you files for production is an excellent idea as well.

I usually refer to that as "the crockford way". +1 from me

@MattBriggs otherwise called the module pattern and it is based on the IIFE pattern.

Don't you need to export classes somehow? How does an object get created from the outside of such a module? Or should there be a method createNewSomething() in the return object, so object creation happens solely within the module? Hm... I would expect that classes (constructors) are visisble from the outside.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

jquery - Commonly accepted best practices around code organization in ...

javascript jquery design-patterns architecture formatting
Rectangle 27 50

In short: Yes. Go with the first example... The hash function can lose entropy if feed back to itself without adding the original data (I can't seem to find a reference now, I'll keep looking).

And for the record, I am in support of hashing multiple times.

A hash that takes 500 ms to generate is not too slow for your server (considering that generating hashes are typically not done the vast majority of requests). However a hash that takes that long will significantly increase the time it will take to generate a rainbow table...

Yes, it does expose a DOS vulnerability, but it also prevents brute force attacks (or at least makes them prohibitively slow). There is absolutely a tradeoff, but to some the benefits exceed the risks...

A reference (more like an overview) to the entire process: Key Strengthening

As for the degenerating collisions, the only source I could find so far is this discussion...

And a few more links:

There are tons of results. If you want more, Google hash stretching... There's tons of good information out there...

+1 Don't get why this got a downvote. I would really appreciate if you could find that reference ;)

+1 for the DoS vulnerability I still think you are recommending a mistake.

@The Rook: Considering that the vast majority of security papers that I've read from reputable researchers all suggest stretching keys prior to using them (Whether for storage or for encryption). And considering that you need to stretch for PCI compliance, I'm not sure how this is bad advice...

Good information, still think its a terrible trade off. If you look at systems like pbkdf2 you'll see they are only used in cases where the hash is freely given to the attacker like in the case of WinZIP. No one can use this for a web application with more than a handfull of users. Its just a waste of resources.

@nikic: That's talking about from a brute force perspective (slowing down the attacker). I was talking about from a collision perspective. MD5(MD5(data)) will be a superset of all of the collisions of MD5(data). The degradation is linear, so it's not a significant concern, but it was enough to cause PBKDF2 to be introduced to combat the concern (considering that's the main difference between PBKDF1 and PBKDF2)...

php - Many hash iterations: append salt every time? - Stack Overflow

php security passwords cryptography
Rectangle 27 50

In short: Yes. Go with the first example... The hash function can lose entropy if feed back to itself without adding the original data (I can't seem to find a reference now, I'll keep looking).

And for the record, I am in support of hashing multiple times.

A hash that takes 500 ms to generate is not too slow for your server (considering that generating hashes are typically not done the vast majority of requests). However a hash that takes that long will significantly increase the time it will take to generate a rainbow table...

Yes, it does expose a DOS vulnerability, but it also prevents brute force attacks (or at least makes them prohibitively slow). There is absolutely a tradeoff, but to some the benefits exceed the risks...

A reference (more like an overview) to the entire process: Key Strengthening

As for the degenerating collisions, the only source I could find so far is this discussion...

And a few more links:

There are tons of results. If you want more, Google hash stretching... There's tons of good information out there...

+1 Don't get why this got a downvote. I would really appreciate if you could find that reference ;)

+1 for the DoS vulnerability I still think you are recommending a mistake.

@The Rook: Considering that the vast majority of security papers that I've read from reputable researchers all suggest stretching keys prior to using them (Whether for storage or for encryption). And considering that you need to stretch for PCI compliance, I'm not sure how this is bad advice...

Good information, still think its a terrible trade off. If you look at systems like pbkdf2 you'll see they are only used in cases where the hash is freely given to the attacker like in the case of WinZIP. No one can use this for a web application with more than a handfull of users. Its just a waste of resources.

@nikic: That's talking about from a brute force perspective (slowing down the attacker). I was talking about from a collision perspective. MD5(MD5(data)) will be a superset of all of the collisions of MD5(data). The degradation is linear, so it's not a significant concern, but it was enough to cause PBKDF2 to be introduced to combat the concern (considering that's the main difference between PBKDF1 and PBKDF2)...

php - Many hash iterations: append salt every time? - Stack Overflow

php security passwords cryptography
Rectangle 27 126

You should be able to do it with something like this, where you query for the Snapin but tell PowerShell not to error out if it cannot find it:

if ( (Get-PSSnapin -Name MySnapin -ErrorAction SilentlyContinue) -eq $null )
{
    Add-PsSnapin MySnapin
}

Ah-hah! This is exactly what I needed, thank you! I had tried something similar to this in my experimenting but I didn't know about the -ErrorAction SilentlyContinue.

The SilentlyContinue is because Get-PSSnapin doesn't quietly return null when if doesn't find the snap in by default. It errors out.

For the lazy: This article provides a full code example how to also check if a snap-in is registered before loading it.

How to check if PowerShell snap-in is already loaded before calling Ad...

powershell
Rectangle 27 554

There are many ways to import a python file, all with their pros and c...

Don't just hastily pick the first import strategy that works for you or else you'll have to rewrite the codebase later on when you find it doesn't meet your needs.

I'll start out explaining the easiest example #1, then I'll move toward the most professional and robust example #7

Example 1, Import a python module with python interpreter:

Put this in /home/el/foo/fox.py:

def what_does_the_fox_say():
  print("vixens cry")

Get into the python interpreter:

el@apollo:/home/el/foo$ python
Python 2.7.3 (default, Sep 26 2013, 20:03:06) 
>>> import fox
>>> fox.what_does_the_fox_say()
vixens cry
>>>

You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within fox.py.

Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place:

Put this in /home/el/foo2/mylib.py:

def moobar():
  print("hi")

Put this in /home/el/foo2/main.py:

execfile("/home/el/foo2/mylib.py")
moobar()

run the file:

el@apollo:/home/el/foo$ python main.py
hi

The function moobar was imported from mylib.py and made available in main.py

Put this in /home/el/foo3/chekov.py:

def question():
  print "where are the nuclear wessels?"

Put this in /home/el/foo3/main.py:

from chekov import question
question()
el@apollo:/home/el/foo3$ python main.py 
where are the nuclear wessels?

If you defined other functions in chekov.py, they would not be available unless you import *

Example 4, Import riaa.py if it's in a different file location from where it is imported

  • Put this in /home/el/foo4/stuff/riaa.py: def watchout(): print "computers are transforming into a noose and a yoke for humans"
  • Put this in /home/el/foo4/main.py: import sys import os sys.path.append(os.path.abspath("/home/el/foo4/stuff")) from riaa import * watchout()
el@apollo:/home/el/foo4$ python main.py 
computers are transforming into a noose and a yoke for humans

That imports everything in the foreign file from a different directory.

os.system("python yourfile.py")
import os
os.system("python yourfile.py")

Example 6, import your file via piggybacking the python startuphook:

~/.pythonrc.py
class secretclass:
    def secretmessage(cls, myarg):
        return myarg + " is if.. up in the sky, the sky"
    secretmessage = classmethod( secretmessage )

    def skycake(cls):
        return "cookie and sky pie people can't go up and "
    skycake = classmethod( skycake )
import user
msg = "The only way skycake tates good" 
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")
$ python main.py
The only way skycake tates good is if.. up in the sky, 
the skycookie and sky pie people can't go up and  have the sky pie! 
SKYCAKE!

Example 7, Most Robust: Import files in python with the bare import command:

/home/el/foo5/
/home/el/foo5/herp
el@apollo:/home/el/foo5/herp$ touch __init__.py
el@apollo:/home/el/foo5/herp$ ls
__init__.py

Make a new directory /home/el/foo5/herp/derp

__init__.py
el@apollo:/home/el/foo5/herp/derp$ touch __init__.py
el@apollo:/home/el/foo5/herp/derp$ ls
__init__.py

Under /home/el/foo5/herp/derp make a new file called yolo.py Put this in there:

def skycake():
  print "SkyCake evolves to stay just beyond the cognitive reach of " +
  "the bulk of men. SKYCAKE!!"

The moment of truth, Make the new file /home/el/foo5/main.py, put this in there;

from herp.derp.yolo import skycake
skycake()
el@apollo:/home/el/foo5$ python main.py
SkyCake evolves to stay just beyond the cognitive reach of the bulk 
of men. SKYCAKE!!

The empty __init__.py file communicates to the python interpreter that the developer intends this directory to be an importable package.

If you want to see my post on how to include ALL .py files under a directory see here: https://stackoverflow.com/a/20753073/445131

whether you are using Mac, Linux or Windows, you need to be using python's idle editor as described here. It will unlock your python world. http://www.youtube.com/watch?v=DkW5CSZ_VII

You should also add Example 6: using __import__(py_file_name). Amazing guide anyway

What's the big difference between all of these, and why is one better than any other? For example 5, you write "Import files in python with the bare import command," but you also use the (bare?) import command in examples 1, 3 and 4, don't you?

Hey Eric! I think you got me wrong.. I just wanted to answer HelloGoodbyes question "what's the big difference between all of these" because I too was curious and found the blog entry (which is NOT mine btw) which I thought was helpful for him too...

Good answer but the fact that you use a different import file as example all the times makes it cumbersome to read.

Python: How to import other Python files - Stack Overflow

python python-import