QT - Where is config.ini - qt

I wanted to save db's conenction in Config.ini file. I created it and added to project (as "other file") - suitable record appered in .pro file.
I started in code with this:
QSettings settings(QDir::currentPath()+"/"+fileName, QSettings::IniFormat);
Then i created 2 functions
for savng settings:
settings.beginGroup("DB");
settings.setValue("HostName",_hostName);
//_hostName is attribute I can access, so that's not an issue
settings.endGroup();
for reading settings
settings.beginGroup("DBSettings");
_hostName =settings.value("HostName", "Unknown").toString();
// hostName is attribute i can access
settings.endGroup();
I initially called 1. and then 2.
It seems like that the .ini file is created and I could read from it, but it's not that I added to project and i can't find it in the folder it supposed to be.
It works, but I need to include it into the project and I need to be able to "control" it.

I resolved this problem myself. Turned out, that line :
QSettings settings(QDir::currentPath()+"/"+fileName, QSettings::IniFormat);
just has to be repalced with
settings = new QSettings(QDir::currentPath()+"/"+fileName, QSettings::IniFormat);

Related

Disable file output of hydra

I'm using hydra to log hyperparameters of experiments.
#hydra.main(config_name="config", config_path="../conf")
def evaluate_experiment(cfg: DictConfig) -> None:
print(OmegaConf.to_yaml(cfg))
...
Sometimes I want to do a dry run to check something. For this I don't need any saved parameters, so I'm wondering how I can disable the savings to the filesystem completely in this case?
The answer from Omry Yadan works well if you want to solve this using the CLI. However, you can also add these flags to your config file such that you don't have to type them every time you run your script. If you want to go this route, make sure you add the following items in your root config file:
defaults:
- _self_
- override hydra/hydra_logging: disabled
- override hydra/job_logging: disabled
hydra:
output_subdir: null
run:
dir: .
There is an enhancement request aimed at Hydra 1.1 to support disabling working directory management.
Working directory management is doing many things:
Creating a working directory for the run
Changing the working directory to the created dir.
There are other related features:
Saving log files
Saving files like config.yaml and hydra.yaml into .hydra in the working directory.
Different features has different ways to disable them:
To prevent the creation of a working directory, you can override hydra.run.dir to ..
To prevent saving the files into .hydra, override hydra.output_subdir to null.
To prevent the creation of logging files, you can disable logging output of hydra/hydra_logging and hydra/job_logging, see this.
A complete example might look like:
$ python foo.py hydra.run.dir=. hydra.output_subdir=null hydra/job_logging=disabled hydra/hydra_logging=disabled
Note that as always you can also override those config values through your config file.

Setting Jetty resourcebase to static file embedded in the same jar file

I am trying to access static resource (eg. first.html) packed inside the same .jar file (testJetty.jar), which also has a class which starts the jetty (v.8) server (MainTest.java). I am unable to set the resource base correctly.
The structure of my jar file (testJetty.jar):
testJetty.jar
first.html
MainTest.java
==
Works fine on local machine, but when I wrap it in jar file and then run it, it doesn't work, giving "404: File not found" error.
I tried to set the resourcebase with the following values, all of which failed:
a) Tried setting it to .
resource_handler.setResourceBase("."); // Results in directory containing the jar file, D:\Work\eclipseworkspace\testJettyResult
b) Tried getting it from getResource
ClassLoader loader = this.getClass().getClassLoader();
File indexLoc = new File(loader.getResource("first.html").getFile());
String htmlLoc = indexLoc.getAbsolutePath();
resource_handler.setResourceBase(htmloc); // Results in D:\Work\eclipseworkspace\testJettyResult\file:\D:\Work\eclipseworkspace\testJettyResult\testJetty1.jar!\first.html
c) Tried getting the webdir
String webDir = this.getClass().getProtectionDomain()
.getCodeSource().getLocation().toExternalForm();
resource_handler.setResourceBase(webdir); // Results in D:/Work/eclipseworkspace/testJettyResult/testJetty1.jar
None of these 3 approaches worked.
Any help or alternative would be appreciated
Thanks
abbas
The solutions provided in this thread work but I think some clarity to the solution could be useful.
If you are building a fat jar and use the ProtectionDomain way you may hit some issues because you are loading the whole jar!
class.getProtectionDomain().getCodeSource().getLocation().toExternalForm();
So the better solution is the other provided solution
contextHandler.setResourceBase(
YourClass.class
.getClassLoader()
.getResource("WEB-INF")
.toExternalForm());
The problem here is if you are building a fat jar you are not really dumping your webapp resources into WEB-INF but are probably going into the root of the jar, so a simple workaround is to create a folder XXX and use the second approach as follows:
contextHandler.setResourceBase(
YourClass.class
.getClassLoader()
.getResource("XXX")
.toExternalForm());
Or change your build tool to export the webapp files into that given directory. Maybe Maven does this on a Jar for you but gradle does not.
Not unusually, I found a solution to my problem. The 3rd approach mentioned by Stephen in Embedded Jetty : how to use a .war that is included in the .jar from which Jetty starts? worked!
So, I changed from Resource_handler to WebAppContext, where WebAppContext is pointing to the same jar (testJetty.jar) and it worked!
String webDir = MainTest.class.getProtectionDomain()
.getCodeSource().getLocation().toExternalForm(); ; // Results in D:/Work/eclipseworkspace/testJettyResult/testJetty.jar
WebAppContext webappContext = new WebAppContext(webDir, "/");
It looks like ClassLoader.getResource does not understand an empty string or . or / as an argument. In my jar file I had to move all stuf to WEB-INF(any other wrapping dir will do). So the code looks like
contextHandler.setResourceBase(EmbeddedJetty.class.getClassLoader().getResource("WEB-INF").toExternalForm());
so the context looks like this then:
ContextHandler:744 - Started o.e.j.w.WebAppContext#48b3806{/,jar:file:/Users/xxx/projects/dropbox/ui/target/ui-1.0-SNAPSHOT.jar!/WEB-INF,AVAILABLE}

trying to use log4j.xml file within WinRun4j

has anyone tried to use a log4j.xml reference within a WinRun4j service configuration. here is a copy of my service.ini file. I have tried many configuration combinations. this is just my latest attempt
service.class=org.boris.winrun4j.MainService
service.id=SimpleBacnetIpDataTransfer
service.name=Simple Backnet IP DataTransfer Service
service.description=This is the service for the Simple Backnet IP DataTransfer.
service.startup=auto
classpath.1=C:\Inbox\DataTransferClient-1.0-SNAPSHOT-jar-with-dependencies.jar
classpath.2=WinRun4J.jar
classpath.3=C:\Inbox\log4j-1.2.16.jar
arg.1=C:\Inbox\DataTransferClient.xml
log=C:\WinRun4J-Service\SimpleBacnetIpDataTransfer\NBP-DT-service.log
log.overwrite=true
log.roll.size=10MB
[MainService]
class=com.shiftenergy.ws.App
vmarg.1=-Xdebug
vmarg.2=-Xnoagent
vmarg.3=-Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n
vmarg.4=-Dlog4j.configuration=file:C:\Inbox\log4j.xml
within the log4j.xml file, there is reference to a log file for when the application runs. if I run the java -jar -Dlog4j.configuration=file:C:\Inbox\log4j.xml ...., the log file is created accordingly. if I register my service and start the service, the log file does not get created.
has anyone had success using the -D log4j configuration, using winrun4j?
thanks
I think that you provided the vmarg.4 parameter incorrectly. In your case it has to be like:
vmarg.4=-Dlog4j.configurationFile=[Path for log4j.xml]
I am also using the same and in my case, it is working perfectly fine. Please see below example:
vmarg.1=-Dlog4j.configurationFile=.\log4j2.xml
Have you tried setting the path in your code instead:
System.setProperty("log4j.configurationFile", "config/log4j.xml");
I'm using a relative path to a folder named config that contains log4j.xml. An absolute path is not recommended, but may work as well.
Just be sure to set this before making any calls to log4j, including any log4j config settings or static method calls!
System.setProperty("log4j.configurationFile", "config/log4j.xml");
final Logger log = Logger.getLogger(Main.class);
log.info("Starting up");
I didn't specify the log4j path in the ini file, only placed log4j.xml file at the same place the jar was placed.
Also without specify the
System.setProperty("log4j.configurationFile", "config/log4j.xml");
In the Java project it was stored in (src/main/resources) and will be included in the jar, but it will not be that one used if placed outside the jar.

QSettings - where is the location of the ini file?

I'm using QSettings to store some data as ini file in Windows.
I want to see the ini file, but I don't know what is the location of the ini file.
This is my code:
QSettings *set = new QSettings(QSettings::IniFormat, QSettings::UserScope, "bbb", "aaa");
set->setValue("size", size());
set->setValue("pos", pos());
Where do I have to look? Or may be I miss the code which write it to the file?
When does the QSettings write its values?
To print out the exact location of your settings file use method fileName method of QSettings class.
QSettings settings("folderName", "fileName");
qDebug() << settings.fileName();
Console output looks then like:
/home/user/.config/folderName/fileName.conf
I think you'll find everything you're looking for here : http://doc.qt.io/archives/qt-4.7/qsettings.html
It's plateform specific, see under :
Platform-Specific Notes
Locations Where Application Settings Are Stored
You can store Settings in files as well :
QSettings settings("/home/petra/misc/myapp.ini",
QSettings::IniFormat);
QSettings save location changes to the QSettings.Scope enum. QSettings save to the Local scope by default. On Linux, I found my local settings in:
~/.config/CompanyName/ApplicationName.conf
If you create a QSettings without giving any specific path, the ini file will be located in the application path.
QSettings Settings("myapp.ini", QSettings::IniFormat);
Settings.setValue("Test", "data");
//...
qDebug() << QApplication::applicationDirPath();
Be careful though : the application path might change : for instance, if you are developping your app with Qt Creator, in debug mode, the application path is in the /debug subfolder.
If you are running it in release mode, the application path is in the /release subfolder.
And when your application is deployed, by default, the application path is in the same folder as the executable (at least for Windows).
Check out the QStandardPaths class, it links to multiple standard paths including configuration on all supported platforms. https://doc.qt.io/qt-5/qstandardpaths.html
QT >= 5.5:
QString path = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
QT < 5.5:
QString path = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
There are paths for config files in shared config directories, application data directories, and more.
In linux you can use this snippet or insert this lines into your main code for find location of your file with python.
from PyQt5.QtCore import QSettings
settings = QSettings("Organization Name", "App name")
print(QSettings.fileName(settings))
It should return an output like this.
/$HOME/.config/Organization Name/App name.conf
Source
in windows path is like below:
C:\Users\user_name\AppData\Roaming\bbb
On Mac OSX, I found the file under at ~/Library/Preferences
The QSettings class provides persistent platform-independent application settings.
Users normally expect an application to remember its settings (window sizes and positions, options, etc.) across sessions. This information is often stored in the system registry on Windows, and in XML preferences files on Mac OS X. On Unix systems, in the absence of a standard, many applications (including the KDE applications) use INI text files
http://doc.qt.io/archives/qt-4.7/qsettings.html
On Windows without providing an ini filename, you'll find the data in the registry.
Using this code snippet:
int red = color.red();
int green = color.green();
int blue = color.blue();
QSettings settings("Joe", "SettingsDemo");
qDebug() << settings.fileName();
settings.beginGroup("ButtonColor");
settings.setValue("button1r", red);
settings.setValue("button1g", green);
settings.setValue("button1b", blue);
settings.endGroup();
After running this code, you'll see the output:
"\\HKEY_CURRENT_USER\\Software\\Joe\\SettingsDemo"
Now, opening the regedit tool and following the path list you got: 1

How to create a new File with full path in Qt?

I am a Qt beginner and just got stuck with the problem. I am looking for a file SomePath/NewDirectoryA/NewFile.kml (NewFile.kml will be the only file in NewDirectoryA, having this directory just to maintain semantics in the project).
If SomePath/NewDirectoryA/NewFile.kml exists then I will use it in my code and if it doesn't exist then I have to create it. If this File doesn't exist then this directory also doesn't exist in SomePath. So If only I have to create a file I can use QFile and open it in ReadWrite or WriteOnly mode.
But the problem is I have to create the file with the directory itself.
I tried with QFile with file name SomePath/NewDirectoryA/NewFile.kml but it didn't worked.
Please suggest me a way in which I can create a new file (NewFile.kml) in a new directory (NewDirectorA) at a given location (SomePath).
bool QFile::open ( OpenMode mode ) [virtual]
[...]
Note: In WriteOnly or ReadWrite mode,
if the relevant file does not already
exist, this function will try to
create a new file before opening it.
Qt's caveat for file creation
Platform Specific Issues
File permissions are handled differently on Unix-like systems and
Windows. In a non writable directory on Unix-like systems, files
cannot be created. This is not always the case on Windows, where, for
instance, the 'My Documents' directory usually is not writable, but it
is still possible to create files in it.
Directories are created with
bool
QDir::mkdir
( const QString & dirName ) const
Creates a sub-directory called
dirName.
and
bool QDir::mkpath
( const QString & dirPath ) const
Creates the directory path dirPath.
The function will create all parent
directories necessary to create the
directory.
AFAIK it is not possible to create the file and the directory directly with QFile. You have to first create the directory (QDir::mkpath will create the full path) and then the file (QFile::open).
QString path("SomePath/NewDirectoryA/");
QDir dir; // Initialize to the desired dir if 'path' is relative
// By default the program's working directory "." is used.
// We create the directory if needed
if (!dir.exists(path))
dir.mkpath(path); // You can check the success if needed
QFile file(path + "NewFile.kml");
file.open(QIODevice::WriteOnly); // Or QIODevice::ReadWrite

Resources