How can I check if signal present in object? - c++

I can't find a way to do it with a build-in way like someObject->signalPresent(SomeSignal). Maybe I missed something. I know that I can do this in C++ using SFINAE, but there should be same ability to do that in QT.

There's QMetaObject::indexOfSignal(). Code using it could look like:
if (someQObject->metaObject()->indexOfSignal("someSignal(QString)") != -1) {
// has signal
...
} else {
// doesn't have signal
...
}
Note the requirements regarding signature normalization described in the documentation, e.g. "someSignal(const QString&)" won't work.

Related

Bukkit - Referring to a custom item in an IF statement doesn't work

Apologies for terrible use of words but I'm not into the lingo yet.
I've been creating a spell book for a simple bukkit plugin which opens into an inventory on the right click of a certain custom item that is crafted. Here is the code
#EventHandler
public void onBookInteract(PlayerInteractEvent e){
if(e.getAction() == Action.RIGHT_CLICK_AIR){
if(e.getItem() == SpellBook){
openGUI(e.getPlayer());
When I try to do this ingame nothing happens. I've removed if(e.getItem() == SpellBook){ and it works as well as if I change the statement to:
if(e.getMaterial() == Material.BLAZE_POWDER){
It works as well. Probably a simple error but I only started coding a couple of days ago. Thanks for any and all helpful feedback ^_^
There are a couple things that could be wrong.
1) Make sure that the class that this is in implements Listener, and that in your Main class, (the one that extends JavaPlugin) in the onEnable() method, you have:
this.getServer().getPluginManager().registerEvents(new <class that implements Listener>(), this);
so if the class that your code with #EventHandler is in is called Handler, then you would use:
this.getServer().getPluginManager().registerEvents(new Handler(), this);
2) Try using .equals() instead of ==:
if(e.getAction().equals(Action.RIGHT_CLICK_AIR)){
if(e.getItem().equals(SpellBook)){
3) Make sure that SpellBook is actually an ItemStack. If it is, then you may want to try doing this if it has no ItemMeta (display name, lore, etc.)
if(e.getItem().getType().equals(SpellBook.getType())){
Otherwise, if it does have ItemMeta, you could use this:
if(e.getItem().getType().equals(SpellBook.getType()) && e.getItem().hasItemMeta()){
if(e.getItem().getItemMeta().getDisplayName().equals(SpellBook.getItemMeta().getDisplayName(){
if(e.getItem().getItemMeta().getLore().equals(SpellBook.getItemMeta().getLore(){
So, your final code should probably look something like this:
#EventHandler
public void onBookInteract(PlayerInteractEvent e){
if(e.getAction().equals(Action.RIGHT_CLICK_AIR)){
if(e.getItem().getType().equals(SpellBook.getType()) && e.getItem().hasItemMeta()){
if(e.getItem().getItemMeta().getDisplayName().equals(SpellBook.getItemMeta().getDisplayName()){
if(e.getItem().getItemMeta().getLore().equals(SpellBook.getItemMeta().getLore()){
openGUI(e.getPlayer());
}
}
}
}
}
If SpellBook is a type (i.e. a Java class) then that's your problem, e.getItem() returns an instance of a class. Again, if SpellBook is a type (I can't tell with the brief code you gave), then try using e.getItem() instanceof SpellBook instead. Sorry if I'm way off.

Object oriented alternative to glob/globfree

I'm currently using glob to match UNIX pathnames against an input string containing wildcards. My dirty code looks like this:
glob_t gl;
int result = glob(inputString, GLOB_TILDE, NULL, &gl);
try {
// do whatever
} catch(...) {
globfree(&gl);
throw;
}
globfree(&gl);
I wonder if there's a smarter way to do this job in C++. I've been searching for a class that would encapsulate the call to globfree in the destructor or something similar but didn't find anything out of the box.
A smarter, entirely C++-way of doing what you want is using http://www.boost.org/doc/libs/1_54_0/libs/filesystem/doc/index.htm.
Especially directory_iterator helps you to accomplish what you want.
Please see the excellent tutorials about how to use it!

How to test asynchronuous code

I've written my own access layer to a game engine. There is a GameLoop which gets called every frame which lets me process my own code. I'm able to do specific things and to check if these things happened. In a very basic way it could look like this:
void cycle()
{
//set a specific value
Engine::setText("Hello World");
//read the value
std::string text = Engine::getText();
}
I want to test if my Engine-layer is working by writing automated tests. I have some experience in using the Boost Unittest Framework for simple comparison tests like this.
The problem is, that some things I want the engine to do are just processed after the call to cycle(). So calling Engine::getText() directly after Engine::setText(...) would return an empty string. If I would wait until the next call of cycle() the right value would be returned.
I now am wondering how I should write my tests if it is not possible to process them in the same cycle. Are there any best practices? Is it possible to use the "traditional testing" approach given by Boost Unittest Framework in such an environment? Are there perhaps other frameworks aimed at such a specialised case?
I'm using C++ for everything here, but I could imagine that there are answers unrelated to the programming language.
UPDATE:
It is not possible to access the Engine outside of cycle()
In your example above, std::string text = Engine::getText(); is the code you want to remember from one cycle but execute in the next. You can save it for later execution. For example - using C++11 you could use a lambda to wrap the test into a simple function specified inline.
There are two options with you:
If the library that you have can be used synchronously or using c++11 futures like facility (which can indicate the readyness of the result) then in your test case you can do something as below
void testcycle()
{
//set a specific value
Engine::setText("Hello World");
while (!Engine::isResultReady());
//read the value
assert(Engine::getText() == "WHATEVERVALUEYOUEXPECT");
}
If you dont have the above the best you can do have a timeout (this is not a good option though because you may have spurious failures):
void testcycle()
{
//set a specific value
Engine::setText("Hello World");
while (Engine::getText() != "WHATEVERVALUEYOUEXPECT") {
wait(1 millisec);
if (total_wait_time > 1 sec) // you can put whatever max time
assert(0);
}
}

What is Qt for boost::promise<T>?

I see that Qt has future class that is direct analog for boost::future but what is qt for boost::promise?
Constructing my own QFuture as shown in the accepted answer did not work for me. At first it seemed like it was working, but in my testing I realized it was not blocking the caller. Whoops! So I dug into the code a little further and found that QFutureInterface is what you want to use as your 'promise'. Like boost::promise, QFutureInterface is what you interact with in your worker thread, and it is a factory for QFutures.
So here's what I've been doing in Qt 4.8 (not sure if this is applicable to later versions).
QFutureInterface<QVariant> promise;
promise.reportStarted();
...
promise.reportResult(someVariant);
promise.reportFinished();
Then in the client thread, assuming you have access to the QFutureInterface 'promise'
QVariant result = promise.future().result();
The future() call is a factory method for creating a QFuture bound to your QFutureInterface. You should be able to get the QFuture and call result() on it later if you wanted.
The boost::promises are means of setting values in futures. In Qt, you can't set futures, you can only return them. That's the only way of "setting" data in a future.
So, in order to set data on a future, you have to return it from a function that was invoked by QtConcurrent::run. To do this, you'd use any of Qt's mechanisms for communicating between threads -- events, mutex-protected variables, etc. You have to tell the thread that runs the code that would return a future that given future is to be returned. That's the only way of achieving what a promise would do.
Alas, if you want to go into the undocumented territory, then the following code does what boost::promise::setValue would:
QFuture<int> f;
int i = 1;
...
f.d.reportResult(&i);
// or
f.d.reportFinished(&i);
I haven't bothered checking if it works (yet).
There is no official Qt analog but there are a few community libraries implementing promises (or similar patterns):
Ben Lau's AsyncFuture (benlau/asyncfuture)
Based on the undocumented QFutureInterface mentioned in one of the other answers.
And it's not exactly a promise pattern but rather an observer pattern.
Benoit Walter's QtPromise (bwalter/qt-promise)
Partially based on Ben Lau's AsyncFuture.
Simon Brunel's QtPromise (simonbrunel/qtpromise)
My QtPromise (julrich/QtPromise)
Disclaimer: I'm the author.
Promises for Qt are now also available with QML/JavaScript btw: https://v-play.net/updates/release-2-18-1-javascript-promises-for-rest-services-tinder-swipe-material-cards-qml-qsortfilterproxymodel-qml-youtube-player
Here is some example code:
import VPlayApps 1.0
import QtQuick 2.0
App {
Component.onCompleted: {
var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = HttpRequest
.get("http://httpbin.org/get")
.then(function(resp) {
return resp.body;
});
var p4 = Promise.all([p1, p2, p3]);
p4.then(function(values) {
console.log(values[0]); // 3
console.log(values[1]); // 1337
console.log(values[2]); // resp.body
});
}
}
I created this library that is highly integrated with Qt and implements javascript-like promises:
https://github.com/juangburgos/QDeferred
It allows to create a thread-safe async API as follows:
multiplyNumbersInThread(3, 4)
.fail([](int res) {
Q_UNUSED(res);
qDebug() << "multiplyPositiveNumbers failed!";
})
.done([](int res) {
qDebug() << "multiplyPositiveNumbers succeded! Result :" << res;
});
Hope you find it useful.

Exception handling aware of execution flow

Edit:
For personn interested in a cleaner way to implemenent that, have a look to that answer.
In my job I often need to use third-made API to access remote system.
For instance to create a request and send it to the remote system:
#include "external_lib.h"
void SendRequest(UserRequest user_request)
{
try
{
external_lib::Request my_request;
my_request.SetPrice(user_request.price);
my_request.SetVolume(user_request.quantity);
my_request.SetVisibleVolume(user_request.quantity);
my_request.SetReference(user_request.instrument);
my_request.SetUserID(user_request.user_name);
my_request.SetUserPassword(user_request.user_name);
// Meny other member affectations ...
}
catch(external_lib::out_of_range_error& e)
{
// Price , volume ????
}
catch(external_lib::error_t& e)
{
// Here I need to tell the user what was going wrong
}
}
Each lib's setter do checks the values that the end user has provided, and may thow an exception when the user does not comply with remote system needs. For instance a specific user may be disallowed to send a too big volume. That's an example, and actually many times users tries does not comply: no long valid instrument, the prices is out of the limit, etc, etc.
Conseqently, our end user need an explicit error message to tell him what to modify in its request to get a second chance to compose a valid request. I have to provide hiim such hints
Whatever , external lib's exceptions (mostly) never specifies which field is the source
of aborting the request.
What is the best way, according to you, to handle those exceptions?
My first try at handling those exceptions was to "wrap" the Request class with mine. Each setters are then wrapped in a method which does only one thing : a try/catch block. The catch block then throws a new exceptions of mine : my_out_of_range_volume, or my_out_of_range_price depending on the setter. For instance SetVolume() will be wrapped this way:
My_Request::SetVolume(const int volume)
{
try
{
m_Request.SetVolume(volume);
}
catch(external_lib::out_range_error& e)
{
throw my_out_of_range_volume(volume, e);
}
}
What do you think of it? What do you think about the exception handling overhead it implies? ... :/
Well the question is open, I need new idea to get rid of that lib constraints!
If there really are a lot of methods you need to call, you could cut down on the code using a reflection library, by creating just one method to do the calling and exception handling, and passing in the name of the method/property to call/set as an argument. You'd still have the same amount of try/catch calls, but the code would be simpler and you'd already know the name of the method that failed.
Alternatively, depending on the type of exception object that they throw back, it may contain stack information or you could use another library to walk the stack trace to get the name of the last method that it failed on. This depends on the platform you're using.
I always prefer a wrapper whenever I'm using third party library.
It allows me to define my own exception handling mechanism avoiding users of my class to know about external library.
Also, if later the third party changes the exception handling to return codes then my users need not be affected.
But rather than throwing the exception back to my users I would implement the error codes. Something like this:
class MyRequest
{
enum RequestErrorCode
{
PRICE_OUT_OF_LIMIT,
VOLUME_OUT_OF_LIMIT,
...
...
...
};
bool SetPrice(const int price , RequestErrorCode& ErrorCode_out);
...
private:
external_lib::Request mRequest;
};
bool MyRequest::SetPrice(const int price , RequestErrorCode& ErrorCode_out)
{
bool bReturn = true;
try
{
bReturn = mRequest.SetPrice(price);
}
catch(external_lib::out_of_range_error& e)
{
ErrorCode_out = PRICE_OUT_OF_LIMIT;
bReturn = false;
}
return bReturn;
}
bool SendRequest(UserRequest user_request)
{
MyRequest my_request;
MyRequest::RequestErrorCode anErrorCode;
bool bReturn = my_request.SetPrice(user_request.price, anErrorCode);
if( false == bReturn)
{
//Get the error code and process
//ex:PRICE_OUT_OF_LIMIT
}
}
I think in this case I might dare a macro. Something like (not tested, backslashes omitted):
#define SET( ins, setfun, value, msg )
try {
ins.setfun( value );
}
catch( external::error & ) {
throw my_explanation( msg, value );
}
and in use:
Instrument i;
SET( i, SetExpiry, "01-01-2010", "Invalid expiry date" );
SET( i, SetPeriod, 6, "Period out of range" );
You get the idea.
Although this is not really the answer you are looking for, but i think that your external lib, or you usage of it, somehow abuses exceptions. An exception should not be used to alter the general process flow. If it is the general case, that the input does not match the specification, than it is up to your app to valid the parameter before passing it to the external lib. Exceptions should only be thrown if an "exceptional" case occurrs, and i think whenever it comes to doing something with user input, you usually have to deal with everything and not rely on 'the user has to provide the correct data, otherwise we handle it with exceptions'.
nevertheless, an alternative to Neil's suggestions could be using boost::lambda, if you want to avoid macros.
In your first version, you could report the number of operations that succeeded provided the SetXXX functions return some value. You could also keep a counter (which increases after every SetXXX call in that try block) to note what all calls succeeded and based on that counter value, return an appropriate error message.
The major problem with validating each and every step is, in a real-time system -- you are probably introducing too much latency.
Otherwise, your second option looks like the only way. Now, if you have to write a wrapper for every library function and why not add the validation logic, if you can, instead of making the actual call to the said library? This IMO, is more efficient.