Code Bug Fix: How to avoid VS Code warning: “[myfile].java is a non-project file, only syntax errors are reported”

Original Source Link

I am running a build task in a java project in Visual Studio Code.
The warning in the “PROBLEMS” tab:

[myfile].java is a non-project file, only syntax errors are reported

It refers to the first line where I load in the class file containing the main():

package [the project folder];
import [the project folder].[the file with other classes].*;
  • I can only avoid the warning by copying the files’ text (the code text itself) into new java files of a new project in a new unrelated folder. The code itself is correct and compiles without errors. Actually, this is the answer, but it is much manual work.
  • When I just copy the java files of the project with the warning message into a new folder, the warning still appears!!!! (!)
  • When I just copy the whole project folder to a new place, the error remains as well, of course.

I guess that copying text into new java files with the same names and the same folder structure is different from copying the files themselves because the files probably get tagged by VS Code, so that they have a project stamp even when the folder structure is destroyed. Perhaps this supports recovering the project structure from recovered raw files? Could this be the problem of this Visual Code warning?

I have already deleted the workspaceStorage incl. restart.

I had other errors before, this is just the last step.

I got the same warning as well. It was simply because I had two Java projects in the same vscode workspace. Once I’ve moved projA out of the workspace, the warning is gone for projB.

WorkspaceRoot
│   projectA
└───projectB

At this point, I think the most likely solution is to have one Java (Maven) project for one workspace. Otherwise I guess vscode will treat they all as one project and they’ll interfere with each other.

I think I found the answer. The whole problem came up from loading not the direct project folder, but the parent folder, though the projects had been developed in their direct project folders from the start.

FOLDER1 (parent) contained

  • FolderA (direct project folder of java files)
  • FolderB (direct project folder of java files)

I have written the projects separately. But one time I opened the FOLDER1 in VS Code instead. That seems to have merged the 2 projects to just one project. After this, I changed back to opening only the FolderA/B and got the warnings that are reported in the question.

Now that I have opened FOLDER1 again and made both FolderA/B projects run without warnings (perhaps you might just comment out everything without fixing anything, but that is untested), opening the isolated FolderA/B projects threw no warnings either. Seems as if VS Code makes opening the parent folder the start of a new project which interferes with the child projects.

And the reason why I had a warning was a code error inside the other project’s folder in the end (not important, but I had forgotten to load the local package needed for “FolderA” project at the start of some java file).

Whatever error I had, the warning was confusing, as I was only working on project “FolderB” which had nothing to do with “FolderA” and which had no code issue. This led to the strange effect that I got the warning of the “FolderA” project also in my “FolderB” project, because VS Code considered both as one project.

Tagged : / / / /

Code Bug Fix: Java error – bad source file: file does not contain class x . Please remove or make sure it appears

Original Source Link

Recently started studying Java for an exam.

While learning packages, tried this and got an error message. What I did was,


    //Creating class A (Within package the package: com.test.helpers)

    package com.test.helpers;
    public class A {
        public void sayHello(){
            System.out.println("Hello World");
        }
    }

    //And then the class App utilizing the class A

    import com.test.helpers.*;

    public class App{
        public static void main(String args[]){
            A a = new A();
            a.sayHello();
        }
    }

I had both of these files in a directory called ‘JavaTest’ (on Windows 7),
and first compiled the A.java using the command javac -d . A.java

And then, while attempting to compile App.java, I got the following error message:


    App.java:5: error: cannot access A
                    A a = new A();
                    ^
      bad source file: .A.java
        file does not contain class A
        Please remove or make sure it appears in the correct subdirectory of the source path.
    1 error

However, the problem seems to resolve in two ways,

  1. Deleting the Source file A.java
  2. Changing the import statement from import com.test.helpers.*; to
    import com.test.helpers.A in the file, ‘App.java’.

I’d be highly grateful if you can explain what happens here. Or I might be making a goofy human mistake or a syntax error.

Here’s the link to the source files

Thank you very much

move the A.java under folder JavaTest to com/test/helpers. the error you are seeing is for the compiler complaining that A.java is in a folder that does not match its package declaration. Remember, you cannot access A from App without A being in a package.

from under src driectory run the following command to compile your classes

src> javac ./*.java ./com/test/helpers/*.java

then from under src folder

src>java App

that should run your program.

Hi the problem here is that the JVM confuses the class file due to the ambiguous class file name in both the directory (the JavaTest as well as the com.test.helpers directory).

when you do javac -d . A.java the compiler makes a class file in the directory com.test.helpers and now it confuses it with the sourcefile there in JavaTest

  1. Deleting the Source file A.java

When you delete the source file A.java from JavaTest, JVM knows now that the class file in com.test.... is to be used, ambiguity goes away.

  1. Changing the import statement from 'import com.test.helpers.*;' to 'import com.test.helpers.A' in the file, 'App.java'.

Here you are specifying which particular file to use in your class implementation that is you are telling the compiler to use the file A.java from com.test... and not from JavaTest package

Now, the solution for this ambiguity to not ever be a problem for you, you must import the specific files with import statement i.e. import com.test.helpers.A; or if you want to do import com.test.helpers.*; then you must specifically use com.test.helpers.A in place of A everywhere in your current class implementation to tell the compiler not to confuse it with the source at JavaTest

I know it’s a lot late for this particular answer, but I wanted to share my views for the upcoming readers, if it could help them in any way, it would be great.
Thanks!

the file A.java should be in the path JavaTestcomtesthelpersA.java

and don’t forget to compile it like this:
javac -d . comtesthelpersA.java

I have the same problem finally,

I was solved.

//Use like this
import com.test.helpers.A;

If u have a more than class in com.test.helpers then u can use import com.test.helpers.*;

every thing is in right place, java does not ask to put your A.java file, in the helpers folder

the whole reason why your code ran with the A.java file removed and not otherwise is:
when your app.java (or the main java file which is importing other classes in it, –>) is in a default package then while importing the classes it gives priority to the same directory and not to the package directory(if there exist any file that has the same name as the class file -> and thats why it gives error bad source file A.java -> as it wanted A.class)

And because of that there is a rule in java : That never place a .java file (of the same name)in parallel to the packages

so to solve this problem you have to either remove the file, A.java
or rename it (to any other name that does not present in the package)
or you can use fully qualified import statement

Tagged : / /

Code Bug Fix: R How to check if some of the loaded packages are not used at all through a script

Original Source Link

I have an 600 line script in R which I’ve been editing many times by cutting and adding entire chunks.
The script loads ~20 packages at the beginning and now I don’t know if all of them end up being used.
Therefore I have the following practical questions:

  • Will removing unnecessary packages improve performance/memory usage?
  • If yes, how can I check and remove packages that are loaded but not end up being used
Tagged : /

Code Bug Fix: Monkey patch pandas: modify value_counts function at import

Original Source Link

I want to change the value_counts function in pandas, and I try to figure out why it is not working.

If I do

>>> import pandas as pd
>>> pd.core.algorithms.value_counts = None

>>> pd.Series([1,2,3]).value_counts()

3    1
2    1
1    1
dtype: int64

I would expect to have a TypeError

However if I do

>>> import pandas as pd
>>> pd.core.base.value_counts = None #or a modified function

>>> pd.Series([1,2,3]).value_counts()

TypeError: 'NoneType' object is not callable

I get the TypeError .

What is the reason of this difference of behavior?
How I can modify the pd.core.algorithms.value_counts function such that it changes the behavior of all classes that use it to construct value_counts methods?

Can you try using pd.core.base.IndexOpsMixin.value_counts = None ?

This makes both pd.Series.value_counts and pd.Index.value_counts as None. Anything else you are looking at?

Explanation:

In pd.core.base there is an import from pandas.core.algorithms import duplicated, unique1d, value_counts

So, pd.core.base.value_counts = pd.core.algorithms.value_counts

Now, even if you make pd.core.algorithms.value_counts as None, the value_counts object in base still contains the old value_counts function. So, that doesn’t work!

Obviously, if you make pd.core.base.value_counts directly None – that works out.

Which is the same as my solution really, as pd.core.base.IndexOpsMixin.value_counts just returns the pd.core.base.value_counts.

Tagged : / / / /

Code Bug Fix: Python: application with submodules – import doesn’t work (NameError: name ‘time’ is not defined)

Original Source Link

Im building a small application. In my main.py I have:

from lib.save_decoded_json import saveJsonToFile
# some code
saveJsonToFile("get_info", outStr)
# some code

in lib folder I have 2 files:

__init__.py
save_decoded_json.py

the last one looks like this:

import time

def saveJsonToFile(folderName, packerJsonData):
    timestr = time.strftime("%Y%m%d-%H%M%S")
    with open(folderName + "/" + timestr + ".json","w") as file:
        for result in extract_json_objects(packerJsonData):
            file.write(json.dumps(result, indent=4, sort_keys=True))
    print('-------------------')
    print(folderName + ' SAVED')
    print('-------------------')

call to saveJsonToFile throws this error:

File "lib/save_decoded_json.py", line 2, in saveJsonToFile
NameError: name 'time' is not defined

Why submodule doesn’t import time properly”

You are only importing the function saveJsonToFile not the whole script so you never imported time.

However, you can import time inside your function. This will work:

def saveJsonToFile(folderName, packerJsonData):
    import time
    timestr = time.strftime("%Y%m%d-%H%M%S")
    with open(folderName + "/" + timestr + ".json","w") as file:
        for result in extract_json_objects(packerJsonData):
            file.write(json.dumps(result, indent=4, sort_keys=True))
    print('-------------------')
    print(folderName + ' SAVED')
    print('-------------------')

Tagged : / /

Code Bug Fix: No module named astropy found when trying to import

Original Source Link

I’m having issues when trying to use the astropy package in python3. I’ve found a few people having similar issues but haven’t found a solution. I understand it’s hard to help with a problem such as this but still.

When I’ve installed other packages such as numpy it works fine, it seems to be just astropy which is not working. The only difference between when I installed numpy and other packages as far as I can tell is time. I have used pip for installing, the installing gave no issue, it is just when trying to execute that the error: "Importerror: No module named astropy".

So far I have checked that the versions of pip and python coincide, and I believe it is installed in the correct directory. I’ll link some information I think might be helpful below, I am running on mac and I read in a similar thread that the recent “macOS Catalina” update might interfere when installing packages somehow.

When trying to install astropy again:

pip3 install astropy
Requirement already satisfied: astropy in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (4.0.1.post1)
Requirement already satisfied: numpy>=1.16 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from astropy) (1.18.4)

And when I check with pip3 list it states astropy is installed.

I suspect it happens because you have installed updates for macOS Catalina, which changes the location of some files from the root.
This link may be helpful, as I had the same problem:
https://medium.com/analytics-vidhya/configuring-anaconda-environment-on-macos-catalina-26e1cb02f5ab

Tagged : /

Code Bug Fix: How to write postgresql function in package

Original Source Link

CREATE OR REPLACE FUNCTION get_ehr_inv(inv character varying,bme character varying,epi character varying)
RETURNS TABLE(
                    v_invjson text             
)
AS $$
BEGIN
  RETURN QUERY
    select REPLACE(array_to_string(array_agg(finaldata), ','),'"]','')::text v_invjson from (
select rownum||') '||split_part(invsplitdata,'^',6) as finaldata  from (
select regexp_split_to_table(invdata,'",') as invsplitdata from (
select json_data::json ->> 'InvTestCodeToPrint'  as invdata
from num_json where  hrgnum_puk = inv and hrgnum_visit_no =  bme and hrgnum_episode_code = epi ORDER BY gdt_entry_date desc limit 1)));
END;
$$ LANGUAGE 'plpgsql'

Instead of writing function like this, I want to write function in package and call the package for result.

Tagged : /

Code Bug Fix: javascript Library/Package implementing the ARIMA model for training and prediction

Original Source Link

We have some python code where we train an ARIMA model on some data (for example a time trace of the mean weekly sales of tools from a DIY shop for each year) to build a model of how the sales of these tools change and then apply it to predict/forecast on a subset of that data (for example mean weekly sales of just hammers and wrenches). This works pretty well. We now want to reimplement this code in JavaScript on the client side, so a user could select a subset of the available tools and predict their sales. In the python code we have used the statsmodels package’s implementation of the ARIMA model. Is there a mature standard stats package implementing the ARIMA method in javascript that we could use to do this, similar to how we have done in python?

Tagged : / / / /