mardi 4 août 2015

Using SDL2 for software development

I was surfing the internet this morning and I came upon reading about SDL2 game programing library for c++. Looking at how SDL2 works, I wonder if actual software applications can be developed with game programing libraries like SDL2. Why or why not would be really helpful for me to understand the reasons why you would ever do this. Thanks!!



via Chebli Mohamed

How can a bitwise operator be used to read a file?

I'm trying to read from a .dat file using the following code:

ifstream input_file; 
double x;
while (input_file >> x) {...}

I don't understand how this actually works though - input_file >> x seems like it's using the right bit-shift operator. In what way does that actually read the file?



via Chebli Mohamed

How to call a value template inside a type template [duplicate]

This question already has an answer here:

The idea is to provide a compile time integer element to a specific function of type S, for different types such as S.

G++ does not allow code below. Who can help me to fix this?

template <class T, int s>
void fn1(T &t)
{
    t.fn2<s>();
}

struct S
{
    template <int s> void fn2 ()
    {
    }
};

void test()
{
    S s;

    fn1<S,3>(s);
}

which leads to:

$ g++ -c t.cpp
t.cpp: In function ‘void fn1(T&)’:
t.cpp:4:11: error: expected primary-expression before ‘)’ token
  t.fn2<s>();
           ^
t.cpp: In instantiation of ‘void fn1(T&) [with T = S; int s = 3]’:
t.cpp:18:12:   required from here
t.cpp:4:7: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binary ‘operator<’
  t.fn2<s>();



via Chebli Mohamed

How to return the derived type from a template class

I want to be able to call makeAnother() this without providing a template argument. I've tried using different forms of decltype(this) both in and outside of the function body with no success.

#include <vector>

template <class T>
class A {
    template <class Derived>
    Derived makeAnother() {
        Derived result;
        /* do stuff */
        return result;
    }
    std::vector<T> v;
};

class B : A<int>
{
    /* stuff */
};

int main() {
    B foo;
    B result = foo.makeAnother(); // this doesn't work
}



via Chebli Mohamed

googletest SetUp Method not called

I'm using Google Test to unit test my C++ project. The getting started guide says:

If necessary, write a default constructor or SetUp() function to prepare the objects for each test. A common mistake is to spell SetUp() as Setup() with a small u - don't let that happen to you.

SetUp() is spelled correctly, but I still can't get SetUp to work. Any ideas?

#include "gtest/gtest.h"

class SampleTest : public testing::Test {
 protected:
  virtual void SetUp() { std::cout << "SetUp called." << std::endl; }
};

TEST(SampleTest, OneEqualsOne) {
  int one = 1;
  ASSERT_EQ(1, one);
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

g++ -g -Wno-deprecated -I gtest/include SampleTest.cpp gtest/libgtest.a -o SampleTest

Output:

[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from SampleTest
[ RUN      ] SampleTest.OneEqualsOne
[       OK ] SampleTest.OneEqualsOne (1 ms)
[----------] 1 test from SampleTest (1 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[  PASSED  ] 1 test.



via Chebli Mohamed

Bridging objective-c library in swift project does not work

In my swift project in need to use snmp++ project ( http://ift.tt/1fyN2Ff ). The snmp++ project is written in c++ and then objective-c wrapper is created for functions.

The project generates libMobileSNMP_PP.a file which i include in my swift project and then create a bridging header and in the bridging header inport "XISMobile_SNMP_PP.h".

Also included .mm and .h files in the swift project as shown in the attached image example1

enter image description here

at compile it gives "could not reference bridging file in the app".

I refered link Can I mix Swift with C++? Like the Objective - C .mm files but still issue exist.

I even tried steps as given in example as shown http://ift.tt/1P42pSz but no success.

Please tell where i'm doing or missing any step.



via Chebli Mohamed

OpenMP Single Producer Multiple Consumer

I am trying to achieve something contrived using OpenMP.

I have a multi-core system with N available processors. I want to have a vector of objects of length k*P to be populated in batches of P by a single thread (by reading a file), i.e. a single thread reads this file and writes in vecObj[0 to P-1] then vecObj[p to 2P-1] etc. To make things simple, this vector is pre-resized (i.e. inserting using = operator, no pushbacks, constant length as far as we are concerned).

After a batch is written into the vector, I want the remaining N-1 threads to work on the available data. Since every object can take different time to be worked upon, it would be good to have dynamic scheduling for the remaining threads. The below snippet works really well when all the threads are working on the data.

#pragma omp parallel for schedule(dynamic, per_thread)
    for(size_t i = 0; i < dataLength(); ++i) {
        threadWorkOnElement(vecObj, i);
    }

Now, according to me, the the main issue I am facing in thinking up of a solution is the question as to how can I have N-1 threads dynamically scheduled over the range of available data, while another thread just keeps on reading and populating the vector with data?

I am guessing that the issue of writing new data and messaging the remaining threads can be achieved using std atomic.

I think that what I am trying to achieve is along the lines of the following pseudo code

std::atomic<size_t> freshDataEnd;
size_t dataWorkStart = 0;
size_t dataWorkEnd;
#pragma omp parallel
{
    #pragma omp task
    {
        //increment freshDataEnd atomically upon reading every P objects
        //return when end of file is reached
        readData(vecObj, freshDataEnd);
    }
    #pragma omp task
    {
        omp_set_num_threads(N-1);           
        while(freshDataEnd <= MAX_VEC_LEN) {
            if (dataWorkStart < freshDataEnd) {
                dataWorkEnd = freshDataEnd;
                #pragma omp parallel for schedule(dynamic, per_thread)
                for(size_t i = dataWorkStart; i < dataWorkEnd; ++i) {
                    threadWorkOnElement(vecObj, i);
                }
                dataWorkStart = dataWorkEnd;
            }
        }
    }
}

Is this the correct approach to achieve what I am trying to do? How can I handle this sort of nested parallelism? Not so important : I would have preferred to stick with openmp directives and not use std atomics, is that possible? How?



via Chebli Mohamed

VLC and MPlayer doesn't play video stream with ortp library

I need example of rtp video streaming with ortp library. My implementation of video streaming doesn't work with VLC and MPlayer.



via Chebli Mohamed

Invalid conversion from void * when using ibpp in c++

One of my class members has void * type:

void * conn;

In Connection method I set connection to Firebird database and set conn member like this:

IBPP::Database conn = IBPP::DatabaseFactory(host, dbname, user, pass);
conn->Connect();
this->conn = static_cast<void *>(conn);

This way of doing things works well for other multiple databases, but breaks when I try to use it with Firebird. So, this is what happens. In another method I use conn member to fetch data from a particular database. When it comes to Firebird, I do it like this:

IBPP::Transaction tr = IBPP::TransactionFactory(static_cast<IBPP::Database>(this->conn));

However, this line of code results in an error message:

error: invalid conversion from 'void *' to 'IBPP::IDatabase *'

I do not know what I'm doing wrong.



via Chebli Mohamed

Qt TableView: How to get rid of the extended grey rectangle from the row headers

How do I get rid of grey area as seen in the image below. It seems like if the table does not fill the entire space, the grey color just extends until the end.

I coded something similar to this image in C++.

enter image description here



via Chebli Mohamed

c++ writing and reading text file is very slow, any alternatives?

I am currently writing code for a game and I'm a little bit stuck on saving and loading the level. For writing I use this piece of code:

    bool WorldGen::GenerateNewWorld(unsigned int seed, int width)
{
    std::cout << "World generating..." << std::endl;
    int heigth = 1; //2D perlin noise instead of 3D
    m_WorldSizeX = width;
    m_WorldSizeY = 1800; //add a int height if implementing different world sizes

    // Create a PerlinNoise object with a random permutation vector generated with seed
    PerlinNoise(seed);

    std::vector<byte> arrMaxHeight;

    // looping through all the x locations and deciding the y value
    for (unsigned int i = 0; i < heigth; ++i) {     // y
        for(unsigned int j = 0; j < width; ++j) {  // x
            double x = (double)j / ((double)width);
            double y = (double)i / ((double)heigth);

            // Typical Perlin noise
            double n = noise(10 * x, 10 * y, 0.8);

            //n is the ground added on top of the base layer (n = highest peak at point j)
            arrMaxHeight.push_back((int)(n * 255));
        }
    }

    std::wofstream fileStream;
    fileStream.open(L"GameSave/world/World.txt");

    if (fileStream.fail())
    {
        return false;
    }

    //fileStream << L"[I could put something up here but that's still in development!]" << std::endl;

    byte blockType = 0;
    std::vector<byte> arrBlockType;

    for (int i = 0; i < m_WorldSizeX; i++)
    {
        for (int j = 0; j < m_WorldSizeY; j++)
        {
            if (j > arrMaxHeight.at(i))
            {
                //block is not air
                blockType = 1;
            }
            else
            {
                //block is air
                blockType = 0;
            }

            arrBlockType.push_back(blockType);
            fileStream << blockType << "/n";
        }
    }

    fileStream.close();

    return true;
}

Now this not too bad, generates the world in around 5 minutes and sends it to world.txt without any issues, my loading(reading world.txt line per line) however takes ages. Around 30+ minutes to fully read all the lines from the text file using std::wifstream and its getline() function. It reads all the lines and adds them to a std::vector and later creates "blocks" from this vector. The creation of the blocks is done in a few seconds but the wifstream is really slow.

Any idea on how to optimise this? I was thinking about only reading blockTypes around the player but that would still require me putting all the blocks into a vector before being able to operate on them.

Kind regards, Jannes

PS: if you need the loading snippet as well I will edit it in later.



via Chebli Mohamed

cutting first string from second string and show remaining characters

i want to code a program in which we take two strings separated by space as an input from user. then first string will be cut from second one, if resultant again have first string then again cut it from that string until there is no first string in second string as a result. output will b the remaining characters in separated line. and at the end a number that shows the quantity of those characters.

#include<iostream>
using namespace std;


int main(){
    string ch1,ch2,ch3;
    cout<<" Enter  two strings values...separated by space..."<<endl;
    cin>>ch1>>ch2;
    //cout<<aa<<" 2nd  "<<bb<<endl;
    // ch1[]={"ab"},ch2[]={"caabbefcdeab"},ch3[50];
    int a=0 ,b=0 ,c;
    string s,t,r;
   int check = true;

    for(int i=0 ; ch2[i]!='\0' ; i++)
    {
         int w=i;
            check=1;
            b=0;
            if(ch1[0]==ch2[i])
            {
                for(int p=0 ; ch1[p]!='\0' && check==1 ; p++)
                   {
                 if(ch1[p]==ch2[w])
                      {
                      check=1;
                       w=w+1;
                      }


                    }

                   if(check==1)
                   {

                                  for(int e=i;e<w;e++)
                                  {
                                   ch2[e]='\0';       
                                   ch2[e]='~';

                                  }
                       i=-1;
                         for(int l=0;ch2[l]!='\0';l++)
                            {
                                  ch3[l]='\0';

                                  if (ch2[l]!='~')
                                  { 
                                // cout<<" ch2 "<<ch2[l]<<endl;
                                   ch3[b]=ch2[l];

                                  // cout<<" ch3 "<<b<<" contains.."<<ch3[b]<<endl;
                                   b=b+1;
                                   }



                            }
                             for(int l=0;ch2[l]!='\0';l++)
                            {
                                  ch2[l]='\0';
                                  ch2[l]=ch3[l];




                            }  

                   }

            }      

    }
    for(int u=0;ch2[u]!='\0';u++)
    {
   cout<<ch2[u]<<endl;
     a=a+1;
   //  cout<<" ch3 "<<u<<" contains "<<ch3[u]<<endl;
    }
   cout<<a<<endl;

    system("pause");
    return 0 ;
    }

sample input ::: cde ccdedefcde

sample output ::: f 1

but my output is :::

d e f 3



via Chebli Mohamed

Set cipher suites used by WinHTTP

I would like to use WinHTTP to verify the correctness of some cipher suites which are a modified version of OpenSSL ciphers.

However, I am not able to set what cipher WinHTTP uses when contacting a TLS/SSL server. I tried a couple of things, but none worked.

Here is what I tried:

  1. Using the CryptoAPI to remove cipher suites: I basically removed all cipher suites and added the one I wanted to test using the API functions: BCryptAddContextFunction() and BCryptRemoveContextFunction(). Here is a link.
  2. Followed instructions here to in the section "To configure the SSL Cipher Suite Order group policy setting".

But none of these worked. Is there any clue how to do this?

btw, I am using Windows 7 Enterprise. And I am verifying what ciphers are being used using Wireshark.

Thank you in advance.



via Chebli Mohamed

STD Set Unique Pointer

struct departure_compare {
    bool operator() (const Leg* lhs, const Leg* rhs) const
    {
        return lhs->CurrentDepartureTime() < rhs->CurrentDepartureTime();
    }
};

class Station
{
    uint station_number_;
    std::set<Leg *, departure_compare> departure_legs_in_order_; // legs that depart from this station in order of departure time
public:
    Station(uint station_number) : station_number_(station_number) {};
    void addDepartureLeg(Leg *leg) { departure_legs_in_order_.insert(leg); };
    const std::set<Leg *, departure_compare>& DepartureLegs() const { return departure_legs_in_order_; };
    uint StationNumber() { return station_number_; };
};

I call this in a loop

Leg *new_leg = new Leg();
start_station->addDepartureLeg(new_leg); // start_station of type station

Now i recognized that some times, it doesn't insert the new_leg into this structure. Now i looked at the documentation which says that if it is already in the set structure that it doesn't insert new_leg. But how is this possible, if i always create a new Pointer (Shouldn't the address be unique)?



via Chebli Mohamed

What is the syntax for parameter pack expansion with alignas?

I'm trying to expand a parameter pack in an alignment specifier. I can't get the syntax right. Here's a simple example:

#include <cstdint>
#include <tuple>

template <typename... Ts>
struct C
{
    using Tuple_Type = std::tuple <Ts...>;

    void f()
    {
        uint8_t i1;
        uint8_t i2 alignas (2);
        uint8_t i3 alignas (typename std::tuple_element<0, Tuple_Type>::type);
        uint8_t i4 alignas (Ts...);
    }
};

//template class C <>;  // not compatible with i3 declaration above
template class C <uint64_t>;

This fails to compile with gcc 4.8.3:

foo.cpp: In member function 'void C<Ts>::f()':
foo.cpp:14:31: error: expected ')' before '...' token
         uint8_t i4 alignas (Ts...);
                               ^
foo.cpp:14:31: error: expected ')' before '...' token
foo.cpp:14:31: error: expected initializer before '...' token

The C++ standard ([dcl.align]) says "An alignment-specifier with an ellipsis is a pack expansion", so it seems like it should be possible to do what I want.

I've been unable to find an example of this kind of parameter pack expansion, and my search for a possible bug in gcc didn't find anything.



via Chebli Mohamed

Using GL_TEXTURE_2D_ARRAY as a draw target

I've created an array of 2D textures and initialized it with glTexImage3D. Then I attached separate textures to color attachments with glFramebufferTextureLayer, Framebuffer creation doesn't throw an error and everything seems fine until the draw call happens.

When shader tries to access color attachment the following message appears:

OpenGL Debug Output message : Source : API; Type : ERROR; Severity : HIGH;
GL_INVALID_OPERATION error generated. <location> is invalid.

Shaders are accessing layers of an array with location qualifier:

layout (location = 0) out vec3 WorldPosOut; 
layout (location = 1) out vec3 DiffuseOut; 
layout (location = 2) out vec3 NormalOut; 
layout (location = 3) out vec3 TexCoordOut; 

Documentation says that glFramebufferTextureLayer works just like glFramebufferTexture2D, except the layer parameter, so can I use location qualifiers with texture array, or some other way exsists?



via Chebli Mohamed

Iterating a vector from end to somewhere (not begin)

I'm trying to iterate over a std::vector using rbegin() and an iterator coming from a std::find_if(). Of course iterator and reverse_iterator are not compatible. How can I do it ?

auto my_it = std::find_if(vec.begin(), vec.end(), 
    // irrelevant lambda
});

for (auto rit = vec.rbegin(); rit != my_it; ++rit)   // doesn't compile, iterators not compatible
{
    // do something
}

There are plenty of question on how to iterate from rbegin() to rend(), but I can't find anything for when I want to stop before rend().



via Chebli Mohamed

Strange behavior of bit-shift [duplicate]

Can't understand behavior of this bit shift:

int container = 1;

cout<<(container>>32)<<endl;

If it's logical shift the output should be 0, but it's 1 instead, as if it was cyclic shift. When looking at disassembly I see that command used is SAR. Please explain this behavior to me.



via Chebli Mohamed

Is there a data structure that works like a map but also allows the sequence of values to be used independently of the keys?

Often I have a map for which the keys are only used for importing, exporting and setup. During the performance critical stage, the values are of importance, not the keys.

I would like to use a data structure that acts like a map but gives me the option to just use a simple vector of mapped values when the keys are irrelevant.

The implementation seems reasonably simple. Just use a pair of equally sized vectors in which to store the key and value respectively, sorted with respect to the key vector. Insertions and deletions will be less efficient than in boost::flat_map, but that is a compromise I'm willing to make in order to get instant access to the vector of key unencumbered values.

Is this a terrible idea? If not, is there an existing implementation I can use?



via Chebli Mohamed

Taking camera photos in Cocos2d-x?

I saw Fennex attempt to access the camera api of Android within Cocos2dx. But on the project listed, I am not sure how I am going to access the camera and the photogallery. Is there a way to do this in Cocos2dx just as you do with Cocos2d?

Thank you!



via Chebli Mohamed

Is function defined in class always inline?

As per some of the books, function defined(along with definition in header) in class are always inline. Is that true?

How we can create such scenario using test app?



via Chebli Mohamed

Delegated constructors

I have two questions. Consider this code:

#include <iostream>

struct A {
    A(int n, char c, bool b) 
        /* : some complex initialization list that you don't want to repeat. */
        {initialize();}
    A(int n) : A(n, default_char, default_bool) {}
    A(char c) : A(default_int, c, default_bool) {}  // Do not want initialize() called!
    A(bool b) : A(default_int, default_char, b) {}
    A(int n, char c) : A(n, c, default_bool) {}
    A(int n, bool b) : A(n, default_char, b) {}  // Do not want initialize() called!
    A(char c, bool b) : A(default_int, c, b) {}
private:
    static const int default_int = 3;
    static const char default_char = 't';
    static const bool default_bool = true;
    void initialize() {std::cout << "A ctor.\n";}
};

int main() {
    A a(5,'a',false);
    A b(5);
    A c('a');
    A (5,'a');
    A (5,false);
    A ('a',false);
}

First of all, assuming I want initialize(); to be called for all the constructors of A, is there a way to avoid explicitly repeating the use of default_int, default_char, default_bool, and have them called automatically somehow? Something like

template <typename... Args> A(Args...args) : A(???) {}

Second of all, assume I do NOT want initialize(); to be called for some of the constructors (e.g. stated in the code). How to avoid that without repeating the "complex initialization list" of A(int,char,bool) 's constructor (so as to avoid future maintenance issues)?



via Chebli Mohamed

Creating compiler independent shared objects (C++ with C interface)

On Windows DLLs with C interfaces can be used to call C++ code compiled with one compiler (e.g., GCC) from an executable compiled with another one (e.g., MSVC). However, trying to do the same on Linux using SOs has proven to be less easy.

For example, I have the following code:

#include <vector>
#include <string>

extern "C" void __attribute__ ((visibility ("default"))) foo()
{
    [&] () noexcept { std::vector<std::string> bar; bar.emplace_back("foo"); }();
}

And create a shared object as follows:

g++ -std=c++14 -shared -fvisibility=hidden -fPIC -o libso_test.so so_test.cpp

Where g++ is G++ 5.2.0.

And another file for the main executable:

extern "C" void foo();

int main(int, char**)
{
    foo();
    return 0;
}

When trying to compile it with the following command:

g++-4.8 -L. -o so_test_main so_test_main.cpp -lso_test

Where g++-4.8 is G++ 4.8.1 I get a number of errors (using g++ instead of g++-4.8 works fine but defeats the purpose):

./libso_test.so: undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)@GLIBCXX_3.4.21'
./libso_test.so: undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&)@GLIBCXX_3.4.21'
./libso_test.so: undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()@GLIBCXX_3.4.21'
collect2: error: ld returned 1 exit status

According to the output of nm -g -D --defined-only libso_test.so, aside from the expected symbols _init _fini and foo (marked T) a large number of other symbols are exported marked W.

How can I hide these symbols properly?



via Chebli Mohamed

Using right and left justification on the same line and replacing that line in the console

This is my first question on here, so I hope I'm being clear enough. I'm finishing up a little programming project for a class at the moment. I'm done with all of the actual requirements for the project, but I'd really like to make it look nicely formatted now.

How can I send two separate statements of output, from say, two different classes, to the same line on the console with one being left justified and one being right justified. At the moment when I attempt to do this it smushes the two together with both being on the left side. I also need to delete and update the same line of code during this process as well if it is to end up looking how I want it.

Here is as far as I got fiddling around with some test code:

for (int x = 0; x < 10; ++x)
{
    cout << '\r' << left << "stuff on the left" << right << "stuff on the right" << flush;
    this_thread::sleep_for(chrono::seconds(1));
}

Any help or suggestions would be greatly appreciated!



via Chebli Mohamed

Save generated code in a special folder in "rtwbuild"

I am using rtwbuild to generated C++ code from a Simulation diagrams and would like to save generated code to an arbitrary directory. Is there any way to do so?



via Chebli Mohamed

Adding Event Handler for Windows Application Dialog box

I would like to an add event handler to my simple GUI application made with a windows application in Visual Studio 2013. I have seen that you can use the Resource View to create windows, buttons, etc. However, whenever I right-click and see the option to "Add Event Handler..." it is always grayed out. I saw in this post Visual Studio 2013 and C# - Unable to add event handler to try creating a new project and/or restart VS, both of which I tried. Am I making some newbie mistake?? Why can't I add an event handler? Any suggestions would be great. Thanks.



via Chebli Mohamed

Changing type for each variadic template argument [on hold]

I have some class:

template<typename... Args>
class X
{
    using F = void(*)(Args...);
};

Now I want variadic parameters in F definition become converted with a specific condition:

template<typename T>
using custom_t = typename std::conditional<std::is_fundamental<Args>::value, T, T&&>::type;

using F = void(*)(custom_t<Args>...);

So, for example, for class X<int, MyCustomT> definition X::F should become void(*)(int, MyCustomT&&)



via Chebli Mohamed

Concatenating string to char*

I am a C# developer and I find strange that when I run the following code in C++:

std::string original = "Hello";

std::string st = original + "World";
const char *c = st.c_str();

const char *c2 = (original + "World").c_str();

std::cout << "c  = '" << c << "'" << std::endl;
std::cout << "c2 = '" << c2 << "'" << std::endl;

I get the following output:

c  = 'HelloWorld'
c2 = ''

In C# a similar construct will result in c and c2 having the same value ("Hello World"). My guess would be that the scope of the result of (original + "World") ends on the right ), so c_str() is called on an invalid input. Is that correct? Is there a better way of achieving this other than creating variables to hold temporary results?

Thanks!



via Chebli Mohamed

CUDA detecting busy waiting / conflicts via tool

Is there any possibility (some tool) to check if my code does busy waiting (has some conflicts) in CUDA? I've checked nvprof but haven't seen such option (just general information about kernel's execution time, not from kernel itself).

I have some code that works about 2,5sec sequential and about 4,5sec asynchronus and I don't know which part of code can be improved.



via Chebli Mohamed

how to familiarise oneself with C++ libraries [on hold]

from: http://ift.tt/OCf0lV, c++ has a lot of libraries for accomplishing many different tasks-this i appreciate,however i'm not sure how to go about being familiar with all these libraries.Should I look for books on most of the libraries and go through them chapter after chapter or should i just get a tutorial on each and get an overview of them? what is the best way for me to familiarise myself with all these libraries?



via Chebli Mohamed

error message : no match for call to ‘(cv::Rect) (cv::Mat&, cv::Point_

I have looked quite a bit everywhere and cannot find an answer to my problem. I tried to replicate a text detection software form this thread (Extracting text OpenCV) but at the end of the code there is a message error saying there is no match for the rectangle even though i have drawn one just above and we enter the loop. I have tested all the values i could think of and everything seems correct.

here is the complete code ;

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>


using namespace cv;
using namespace std;





int main( int argc, char** argv )
{

namedWindow("source_window2",WINDOW_AUTOSIZE);
namedWindow("source_window3",WINDOW_AUTOSIZE);
Mat input = imread(argv[1], CV_LOAD_IMAGE_COLOR);
Mat in_gray = imread(argv[1],CV_LOAD_IMAGE_GRAYSCALE);
Mat gradient;

Mat Kernelellipse = getStructuringElement(MORPH_ELLIPSE, Size(3,3));
morphologyEx(in_gray, gradient, MORPH_GRADIENT, Kernelellipse);
Mat thresh;
//on convertit en binaire
threshold(gradient, thresh, 0.0, 255.0, THRESH_BINARY | THRESH_OTSU);
rectangle(input,Point(0,0),Point(50,50),Scalar(255,255,255),2);
Mat Kernelrectangle = getStructuringElement(MORPH_RECT, Size(9,1));
Mat fermee;
morphologyEx(thresh, fermee, MORPH_CLOSE, Kernelrectangle);
imshow("source_window3", fermee);

Mat noire = Mat::zeros(thresh.size(), CV_8UC1);
//on cheche les contours
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(fermee, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
for (int i = 0; i < contours.size(); ++i)
{
    Rect rectangle = boundingRect(contours[i]);
    Mat noirerectangle(noire, rectangle);
    noirerectangle = Scalar(0, 0, 0);
    //on les dessine
    drawContours(noire, contours, i, Scalar(255, 255, 255), CV_FILLED);
    double proportion_de_blanc = (double)countNonZero(noirerectangle)/(rectangle.width*rectangle.height);

    if (proportion_de_blanc > 0.45 && (rectangle.height > 8 && rectangle.width > 8))
    {
        rectangle(input,rectangle.tl(),rectangle.br(),Scalar(0,255,0),2);
    }


}
imshow("source_window2",input);





waitKey(0);
return(0);

}

My issue is within the last loop :

    if (proportion_de_blanc > 0.45 && (rectangle.height > 8 && rectangle.width > 8))
    {
        rectangle(input,rectangle.tl(),rectangle.br(),Scalar(0,255,0),2);
    }



via Chebli Mohamed

Using temporary objects to do some tasks like log writing a good idea?

So I was searching for a good way to make a log manager to use in my programs, and I found an article, with a class similar to this(I simplified it to a few lines of code just to show it here) :

class Log
{
public:
   Log();
   virtual ~Log();
   std::ostringstream& Get();
protected:
   std::ostringstream os;
};
std::ostringstream& Log::Get()
{
      return os;
}
Log::~Log()
{
   //  Write the data from ostringstream;
}

The log record is written in the destructor, so to write a log record, you do this:

Log().Get() << "Log record";

It's a temporary object, so the log record would be written when this object is destroyed. Is it ok to do it like this ? Is this a better way than using a singleton ? Article with the class can be found here



via Chebli Mohamed

Create Pango Layout Before Cairo Surface

In my application, I am using Pango and Cairo to create text textures. These textures have their width fixed, but should scale their height to fit text contents. The parent objects involved in this situation will then scale their heights to match the text.

The problem is, the way I have been initializing Pango and Cairo does not allow for this. Currently, the system is set up by:

cairo_surface_t* cairoSurface = cairo_image_surface_create( CAIRO_FORMAT_ARGB32, sizeX, sizeY );
cairo_t* cairoContext = cairo_create( cairoSurface );
PangoLayout* pangoLayout = pango_cairo_create_layout( cairoContext );

Which fixes the height, at least of the surface - something I do not want to do, at least not all the time.

My understanding is that if the layout height is not specified, it will automatically scale the height, which can then be found via pango_layout_get_size(). I would like to create the layout first and then use the output of this function to create the surface.

However, pango_cairo_create_layout() requires the surface to already be created, and I have been unable to find a way to render a layout from pango_layout_new() via Cairo. The API docs one of the render functions, pango_cairo_update_layout(), specify that pango_cairo_create_layout() had to be used to create the layout; however, the more important function, pango_cairo_show_layout(), notes no such requirement, and I am not sure if that means that any Pango layout is allowed or not. While I could test if it works, I'm afraid that trial and error could lead me to undefined behavior.

I feel like I'm stuck in a chicken and egg situation, and the documentation for Pango is mostly an API reference with little explanation of how the library is intended to be used. Is there a way to do this properly?



via Chebli Mohamed

Using GCC Undefined Behavior Sanitizer

Today I have read an article about GCC Undefined Behavior Sanitizer (ubsan). However, when I follow steps there (add -fsanitize=undefined to my code), the compiler (GCC 4.9.2 on Ubuntu 15.04) says that some references are not defined:

||=== Build: Debug in Entangle (compiler: GNU GCC Compiler) ===|
obj/Debug/EntangleApp.o||In function `EntangleApp::OnInit()':|
/home/ilya/Projects/Entangle/EntangleApp.cpp|31|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|31|undefined reference to `__ubsan_handle_load_invalid_value'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|32|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|34|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|34|undefined reference to `__ubsan_handle_load_invalid_value'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|34|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|34|undefined reference to `__ubsan_handle_load_invalid_value'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|35|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|37|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|37|undefined reference to `__ubsan_handle_load_invalid_value'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|43|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|43|undefined reference to `__ubsan_handle_load_invalid_value'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|52|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|52|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `EntangleApp::OnCmdLineParsed(wxCmdLineParser&)':|
/home/ilya/Projects/Entangle/EntangleApp.cpp|75|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `EntangleApp::OnRun()':|
/home/ilya/Projects/Entangle/EntangleApp.cpp|128|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.cpp|128|undefined reference to `__ubsan_handle_load_invalid_value'|
obj/Debug/EntangleApp.o||In function `wxPrivate::UntypedBufferData::~UntypedBufferData()':|
/usr/include/wx-3.0/wx/buffer.h|43|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/wx-3.0/wx/buffer.h|43|undefined reference to `__ubsan_handle_load_invalid_value'|
/usr/include/wx-3.0/wx/buffer.h|44|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `std::exception::exception()':|
/usr/include/c++/4.9/exception|63|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `wxCriticalSectionLocker::wxCriticalSectionLocker(wxCriticalSection&)':|
/usr/include/wx-3.0/wx/thread.h|305|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/wx-3.0/wx/thread.h|307|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `wxCriticalSectionLocker::~wxCriticalSectionLocker()':|
/usr/include/wx-3.0/wx/thread.h|312|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o:/usr/include/wx-3.0/wx/thread.h|767|more undefined references to `__ubsan_handle_type_mismatch' follow|
obj/Debug/EntangleApp.o||In function `wxThreadHelperThread::Entry()':|
/usr/include/wx-3.0/wx/thread.h|775|undefined reference to `__ubsan_handle_load_invalid_value'|
/usr/include/wx-3.0/wx/thread.h|776|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/wx-3.0/wx/thread.h|776|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `std::type_info::name() const':|
/usr/include/c++/4.9/typeinfo|100|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/c++/4.9/typeinfo|100|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/c++/4.9/typeinfo|100|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o:/usr/include/c++/4.9/typeinfo|100|more undefined references to `__ubsan_handle_type_mismatch' follow|
obj/Debug/EntangleApp.o||In function `wxObjectEventFunctor::operator()(wxEvtHandler*, wxEvent&)':|
/usr/include/wx-3.0/wx/event.h|3757|undefined reference to `__ubsan_handle_add_overflow'|
/usr/include/wx-3.0/wx/event.h|3757|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/wx-3.0/wx/event.h|3757|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `wxLocale::wxLocale()':|
/usr/include/wx-3.0/wx/intl.h|154|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `wxAppConsoleBase::CallOnInit()':|
/usr/include/wx-3.0/wx/app.h|93|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/wx-3.0/wx/app.h|93|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o:/usr/include/wx-3.0/wx/app.h|592|more undefined references to `__ubsan_handle_type_mismatch' follow|
obj/Debug/EntangleApp.o||In function `wxAppBase::IsActive() const':|
/usr/include/wx-3.0/wx/app.h|592|undefined reference to `__ubsan_handle_load_invalid_value'|
obj/Debug/EntangleApp.o||In function `wxAppBase::SetTopWindow(wxWindow*)':|
/usr/include/wx-3.0/wx/app.h|595|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `EntangleApp::EntangleApp()':|
/home/ilya/Projects/Entangle/EntangleApp.h|19|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.h|19|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.h|19|undefined reference to `__ubsan_handle_type_mismatch'|
/home/ilya/Projects/Entangle/EntangleApp.h|19|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o:/home/ilya/Projects/Entangle/EntangleFrame.h|32|more undefined references to `__ubsan_handle_type_mismatch' follow|
obj/Debug/EntangleApp.o||In function `std::_Vector_base<unsigned long long, std::allocator<unsigned long long> >::~_Vector_base()':|
/usr/include/c++/4.9/bits/stl_vector.h|161|undefined reference to `__ubsan_handle_sub_overflow'|
/usr/include/c++/4.9/bits/stl_vector.h|161|undefined reference to `__ubsan_handle_type_mismatch'|
obj/Debug/EntangleApp.o||In function `std::_Vector_base<unsigned long long, std::allocator<unsigned long long> >::_Vector_impl::_Vector_impl()':|
/usr/include/c++/4.9/bits/stl_vector.h|87|undefined reference to `__ubsan_handle_type_mismatch'|
/usr/include/c++/4.9/bits/stl_vector.h|87|undefined reference to `__ubsan_handle_type_mismatch'|
||More errors follow but not being shown.|
||Edit the max errors limit in compiler options...|
||=== Build failed: 50 error(s), 0 warning(s) (0 minute(s), 23 second(s)) ===|

How can I fix this?



via Chebli Mohamed

displaying 16bit unsigned integers in opengl

I would like a simple way of achieving this, but seem to be bjorking the parameters to glTexImage2D. I have an std::vector<uint16_t> depth_buffer that, on a frame-by-frame basis has depth measurements coming from a kinect. There are exactly 640 x 480 of them, one depth measurement per pixel. If the world went my way, the call should be

glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, 640, 480, 0, GL_LUMINANCE16, GL_UNSIGNED_SHORT, depth_buffer.data());

Where internalFormat (third parameter) is GL_LUMINANCE16 because they are 16 bit unsigned integers, and format is the same because that is exactly how the data is coming in. The type parameter should be GL_UNSIGNED_SHORT...because these are shorts and not bytes.

Surprisingly, if I change it to be

glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, 640, 480, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, depth_buffer.data());

where internalFormat is still GL_LUMINANCE16, format is just GL_LUMINANCE without the 16, and type is GL_UNSIGNED_BYTE, then I get something. Things are clearly being skipped, but just changing to GL_UNSIGNED_SHORT doesn't cut it.

Depending on which documentation you read, format (the second GL_LUMINANCE) may or may not allow the 16 after it (anybody know why? experimentation seems to confirm this). But my chief concern here is why GL_UNSIGNED_**SHORT** seems to be invalid (either all black or all white) depending on the internalFormat -- format combination.

I've tried an obscene amount of combinations here, and am looking for the right approach. Anybody have some advice for achieving this? I'm not opposed to using fbo's, but would really like to avoid it if possible...since it definitely should be doable.



via Chebli Mohamed

How to build BOOST 64bit under Windows with libiconv?

I built libiconv as a 64bit DLL for Windows.

I have,

I:\libiconv\src

  • iconv.c
  • libiconv.rc
  • localcharset.c
  • localcharset.h
  • relocatable.c
  • relocatable.h

and

I:\include

  • config.h
  • iconv.h
  • other files

and

I:\libiconv\x64\Release

  • libiconv.lib
  • libiconv.dll
  • Other files

I tried running:

b2 address-model=64 --with-locale -sICONV_PATH=I:\libiconv\

Performing configuration checks

- 32-bit                   : yes (cached)
- arm                      : no  (cached)
- mips1                    : no  (cached)
- power                    : no  (cached)
- sparc                    : no  (cached)
- x86                      : yes (cached)

Building the Boost C++ Libraries.

- iconv (libc)             : no  (cached)
- iconv (separate)         : no  (cached)
- icu                      : no  (cached)
- icu (lib64)              : no  (cached)

Yet, every time iconv is listed as no, so what other magic do I need in this build process?



via Chebli Mohamed

How To Start another app while running a program in Turbo C++

I was making a program that would help me keep track of all the other programs I was making.In the program I would hit the key corresponding to a particular app and the the app should open up.

But I am not able to find a way to do that.{ system(D:\\APPS\\calc.exe) is not working}. I Need Help for this :) Both are Dos Apps and are running on DosBox Emulator. (Drive D: is Mounted-No problem about that)



via Chebli Mohamed

Visual C++ 2015 redistribution DLLs?

Up to Visual Studio 2013 all you needed was msvcr[version].dll and msvcp[version].dll. Now they changed the DLLs with 2015. What do I need to include in order to avoid a redist installer?



via Chebli Mohamed

Invalid read of size 8, but no memory leaks

I am doing C++ Kafka Client http://ift.tt/1SI5yNs.

In my KafkaProducer class, there are several pointers.

RdKafka::Conf* m_conf;
RdKafka::Conf* m_tconf;
RdKafka::Producer* m_producer;
RdKafka::Topic* m_topic;

m_conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
m_producer = RdKafka::Producer::create(m_conf, m_errstr);
m_tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);
m_topic = RdKafka::Topic::create(m_producer, m_topic_str, m_tconf, m_errstr);

In the destructor, I did the following:

if(m_producer)
    delete m_producer;

if(m_topic)
    delete m_topic;

if(m_tconf)
    delete m_tconf;

if(m_conf)
    delete m_conf;

I used valgrind to check my program, there is no leaks. But there are some problems of "Invalid read". Some memory are freed twice. But I have do idea which memory. The following are part of the valgrind output.

==4627== 2 errors in context 10 of 12:
==4627== Invalid read of size 8
==4627==    at 0x52887A7: RdKafka::log_cb_trampoline(rd_kafka_s const*, int, char const*, char const*) (in /usr/lib/x86_64-linux-gnu/librdkafka++.so.1)
==4627==    by 0x5493C8F: ??? (in /usr/lib/x86_64-linux-gnu/librdkafka.so.1)
==4627==    by 0x549A531: ??? (in /usr/lib/x86_64-linux-gnu/librdkafka.so.1)
==4627==    by 0x54A0219: ??? (in /usr/lib/x86_64-linux-gnu/librdkafka.so.1)
==4627==    by 0x54A1A13: ??? (in /usr/lib/x86_64-linux-gnu/librdkafka.so.1)
==4627==    by 0x506C181: start_thread (pthread_create.c:312)
==4627==    by 0x5EE747C: clone (clone.S:111)
==4627==  Address 0x68df7f8 is 24 bytes inside a block of size 64 free'd
==4627==    at 0x4C2C2BC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4627==    by 0x407E90: KafkaProducer::disconnect() (kafkaproducer.cpp:57)
==4627==    by 0x407D29: KafkaProducer::~KafkaProducer() (kafkaproducer.cpp:32)
==4627==    by 0x407DF1: KafkaProducer::~KafkaProducer() (kafkaproducer.cpp:38)
==4627==    by 0x409DC0: KafkaProducerFactory::~KafkaProducerFactory() (kafkaproducerfactory.cpp:22)
==4627==    by 0x4045A8: main (test_kafkaproducerfactory.cpp:14)

kafkaproducer.cpp lines 56-67 (double-spacing preserved):

 if(m_producer)           // line 56
     delete m_producer;

 if(m_topic)
     delete m_topic;


 if(m_tconf)
     delete m_tconf;

 if(m_conf)
     delete m_conf;       // line 67

Any help is welcome.

UPDATE

I already found the following codes caused this problem. If I commented the following part (If I did not set the event call back function.), the problem would disappear. But I have no idea why it caused the problem. I used the same way to set delivery call back function, which did not cause any problem. It is wired.

//defination
    class MyEventCb : public RdKafka::EventCb
    {
    public:
        void event_cb (RdKafka::Event &event)
        {
        }
    private:

    };

//set the callback function
    if( m_conf->set("event_cb", &m_event_cb, m_errstr) != RdKafka::Conf::CONF_OK)
    {
        DBG_PRINT( 1, "Kafka::Failed to set event callback : %s\n", m_errstr.c_str() );
        return false;
    }
    // Class member
MyEventCb m_event_cb; // event callback



via Chebli Mohamed

How to make a program in c++ that monitors news from RSS feeds

I am trying to create a program in c++ that will monitor news feeds from different RSS feeds and then sort it and display news according to the user's interests. How do i get Started? Is there any Library which already does this? Im an Intermediate c++ Programmer and i would really appreciate it if someone could guide me on the difficulty, depth and perhaps, the way i can implement this.



via Chebli Mohamed

Starting problems with OTL 4.0 MS SQL, ODBC and Code:Blocks

I have to insert some values into a MS SQL-Database on a Windows Machine, but also have to insert some values in a MySQL-Database on Linux soon. So I looked around and found SOCI and OTL 4.0.

I decided to use OTL 4.0 because it looked more easy for one, who haven't worked with C++ and databases before.

I tried to compile a modification of an example ( made it easier) and stumbled serveral times.

My Code so far:

    #include "db.h"
#include <iostream>
#include <fstream>
#include <stdio.h>

#include "plc.h"

#include <sqlncli.h>
#include <oledbdm.h>

using namespace std;


#define OTL_ODBC_MSSQL_2008 // Compile OTL 4/ODBC, MS SQL 2008
//#define OTL_ODBC // Compile OTL 4/ODBC. Uncomment this when used with MS SQL 7.0/ 2000
#include "otlv4.h" // include the OTL 4.0 header file

otl_connect db; // connect object

void insert(TIMESTAMP_STRUCT tm, string table)
{

 string sql_statement;
 //sql_statement = "insert into " << table << " values (:"
 otl_stream o(50, // buffer size
              "insert into test_tab2 values(:f1<float>,:f2<timestamp>)",
                 // SQL statement
              db // connect object
             );

 for(int i=1;i<=10;++i){
  tm.year=1998;
  tm.month=10;
  tm.day=19;
  tm.hour=23;
  tm.minute=12;
  tm.second=12;
  tm.fraction=0;
  o<<(float)i<<tm;
 }
}



void getDataIntoDB(plcdata &data)
{
    otl_connect::otl_initialize(); // initialize ODBC environment
    try{

        db.rlogon("UID=scott;PWD=tiger;DSN=mssql2008"); // connect to ODBC

        }

 catch(otl_exception& p){ // intercept OTL exceptions
  cerr<<p.msg<<endl; // print out error message
  cerr<<p.stm_text<<endl; // print out SQL that caused the error
  cerr<<p.sqlstate<<endl; // print out SQLSTATE message
  cerr<<p.var_info<<endl; // print out the variable that caused the error
 }

 db.logoff(); // disconnect from Oracle


}

Build log:

-------------- Build: Debug in TimeLogger (compiler: GNU GCC Compiler)---------------

mingw32-g++.exe -Wall -fexceptions -g -DOTL_ODBC -IC:\Users\bauermar\GTK -IC:\Users\bauermar\Documents\Sources\EN3 -I"C:\Program Files\Microsoft SQL Server\90\SDK\Include" -c C:\Users\bauermar\Documents\Sources\TimeLogger\db.cpp -o obj\Debug\db.o In file included from C:\Users\bauermar\Documents\Sources\TimeLogger\db.cpp:8:0: C:\Program Files\Microsoft SQL Server\90\SDK\Include/sqlncli.h:17:0: warning: ignoring #pragma warning [-Wunknown-pragmas] In file included from C:\Users\bauermar\Documents\Sources\TimeLogger\db.cpp:8:0: C:\Program Files\Microsoft SQL Server\90\SDK\Include/sqlncli.h:133:19: fatal error: oledb.h: No such file or directory compilation terminated. Process terminated with status 1 (0 minute(s), 0 second(s)) 1 error(s), 1 warning(s) (0 minute(s), 0 second(s))

I installed the Microsoft SQL Native Client with SDK, I included all libs and headers in the IDE of Code::Blocks I also included the sqlncli.h like it is said here

But I have no idea how to continue

I'm using Windows 7, Code::Blocks and MinGW32

Does anybody knows a good tutorial for working on DBs with C++ on several OS? Had someone the same problem? Is there a easier way to handle that with C++?

Thanks in advice!



via Chebli Mohamed

Should a theoretically, but not practically, throwing function be declared noexcept?

Is it safe to declare the following function noexcept even though v.at(idx) could theoretically throw a out_of_range exception, but practically not due to the bounds check?

int get_value_or_default(const std::vector<int>& v, size_t idx) noexcept {
    if (idx >= v.size()) {
        return -1;
    }
    return v.at(idx);
}



via Chebli Mohamed

Calling C from C#

I am from electric engineer background, therefore my knownledge is small about C#,DLL,etc.... I want to use c function into a C#. I know there is a couple post about that but I didn't find one that is enough simple.

Currently, I got C function call windows API to read/write on the USB port. First to create a .dll do I need a header file? Because I got the following function decleration function into a header. The examples that I saw on stack overflow and Internet only use a simple .c file, Can I get rid of the header files?

__declspec(dllexport) LMUSB_HANDLE  __stdcall InitializeDevice(unsigned short usVID,
                                    unsigned short usPID,
                                    LPGUID lpGUID,
                                    BOOL *pbDriverInstalled);
__declspec(dllexport) LMUSB_HANDLE  __stdcall InitializeDeviceByIndex(unsigned short usVID,
                                           unsigned short usPID,
                                           LPGUID lpGUID,
                                           DWORD dwIndex,
                                           BOOL bOpenDataEndpoints,
                                           BOOL *pbDriverInstalled);
__declspec(dllexport) BOOL  __stdcall TerminateDevice(LMUSB_HANDLE hHandle);
__declspec(dllexport) BOOL  __stdcall WriteUSBPacket(LMUSB_HANDLE hHandle,
                          unsigned char *pcBuffer,
                          unsigned long ulSize,
                          unsigned long *pulWritten);
__declspec(dllexport) DWORD  __stdcall ReadUSBPacket(LMUSB_HANDLE hHandle,
                         unsigned char *pcBuffer,
                         unsigned long ulSize,
                         unsigned long *pulRead,
                         unsigned long ulTimeoutMs,
                         HANDLE hBreak);
 __declspec(dllexport) BOOL  __stdcall Endpoint0Transfer(LMUSB_HANDLE hHandle, UCHAR ucRequestType,
                             UCHAR ucRequest, USHORT usValue,
                             USHORT usIndex, USHORT usLength,
                             PUCHAR pucBuffer, PUSHORT pusCount);

Second point, do I need to write __declspec(dllexport) in the cpp file? Here an function from the cpp:

extern "C" __declspec(dllexport) BOOL PASCAL EXPORT TerminateDevice(LMUSB_HANDLE hUSB)

I got no idea what "BOOL PASCAL EXPORT" does, this code is recycled from a furnisher project.

Finaly, when the DLL is properly build. How I import it in the C# project? I tried the following but without success :

[DllImport("lmusbdll.dll")]

I see that you could use right click on the project and add reference but Visual Studio pop-up an error message:

A reference to "DLL path" could not be added. Please make sure that the file is accessible, and that it is a valid assembly or COM component.

[EDIT]

I tried the following solution , but when I tried to reference the header file in my c# project. I still get the message that I cannot reference the file.



via Chebli Mohamed

Get user who initiates Windows Portable Device (MTP) event

I am detecting files being copied to a mobile phone, and I have IPortableDeviceValues available so I can get the file name (WPD_OBJECT_ORIGINAL_FILE_NAME) and device name (WPD_EVENT_PARAMETER_PNP_DEVICE_ID), but I'm not able to get a PSID or anything else that I can use to identify the person who performed the action.

Any ideas how I can get the user?



via Chebli Mohamed

OpenGL "glGenBuffers' cause segmentation fault

I am not sure what's going on, this was working before and all of a sudden it's just acting really crazy on me.

this is a cmake and sdl project. cmakelists.txt

PROJECT(ren_opengl)

SET(SRC_FILES ren_opengl.c)
set(CMAKE_MACOSX_RPATH 1)

FIND_PACKAGE(SDL2 REQUIRED)
INCLUDE_DIRECTORIES(${SDL2_INCLUDE_DIR})

FIND_PACKAGE(OPENGL REQUIRED)
INCLUDE_DIRECTORIES( ${OPENGL_INCLUDE_DIR})

ADD_EXECUTABLE(ren_opengl ${SRC_FILES})
TARGET_LINK_LIBRARIES(ren_opengl ${SDL2_LIBRARY} ${OPENGL_LIBRARIES})

included headers

#include <SDL2/SDL.h>
#include <OpenGL/gl3.h>
#include <SDL2/SDL_opengl.h>

Init SDL in ren_opengl.c

int init_sdl(int width, int height, char* title, double fps)
{

if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
  {
    SDL_Log("sdl failed to init");
    SDL_Quit();
    return -1;
  }

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);


  window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
  if(window == NULL)
  {
    SDL_Log("sdl failed to create window");
    SDL_Quit();
    return -1;
  }

  maincontext = SDL_GL_CreateContext(window);
  if(maincontext == NULL)
  {
    SDL_Log("sdl failed to create opengl context");
    SDL_Quit();
    return -1;
  }
    SDL_GL_SetSwapInterval(1);


  return 1;

}

at the end of init sdl everything is working, I ca

void render()
{
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    SDL_GL_SwapWindow(window);
}

if I create a GLuint vao; that causes no problems, as soon as I try to do glGenBuffers(1, &vao); That line above keeps giving segmentation fault.

I even just updated to sdl 2.0.4 but i am really not sure what's going on now.



via Chebli Mohamed

Launch application inside app container

I'm currently looking for a way to programmatically launch a modern (uwp) application inside an app container using the available Win32 APIs.

I don't want to launch the app through a protocol '://app', Instead I want to create the app container myself and then load the UWP app inside that to have access to all memory etc.

Is this possible, and if so how?



via Chebli Mohamed

implement factory pattern for products with conditional compiling

I'd like to implement factory (or some other pattern) in a way that will allow me to compile the code without introducing type dependency.

enum CarType
{
 BMW,
 PORSCHE,
 MERC
};

class CarFactory
{
  public:
 static Car* create(CarType type)
 {
  switch(type)
  {
    case BMW : return new BMWCar();
    case PORSCHE : return new PorscheCar();
    default : return new MercCar();
  }
 }
};

When I compile CarFactory, I need to include BMWCar, PorscheCar and MercCar as a part of my compilation/linking unit.

The way my codebase is setup, we may want to ship BMWCar only, or two or all three of them. So, I cannot make the create() dependent on the type.

How can I adapt the factory pattern for this ? Also, I'd like to avoid doing ifdefs since this is just a sample of my problem. The real codebase is huge and is not a practical solution to ifdef the code.

Update: Also, I am not allowed to use:

  • templates
  • has to conform to c++ 98 standard
  • cannot use boost

These are mostly due to customer build toolchain restrictions. I don't have a choice in changing these.



via Chebli Mohamed

CMake on windows cannot link to executable with exposed symbols

I have a main executable that dynamically loads a shared library, both are compiled in the same CMake file. The library calls a function defined in the main executable, in Linux this is done successfully and the program works as expected, however in Windows the library fails to link the executable and the program crashes during compilation.

I am using this cmake file to construct an executable and a library that I modified from the Unix version I found here.

CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR)
PROJECT(EXPORTS C)
SET(CMAKE_VERBOSE_MAKEFILE ON)
SET(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "")
FILE(WRITE ${CMAKE_BINARY_DIR}/main.c
"#include <windows.h>
#include <stdio.h>
void internal(void){printf(\"internal()\\n\");}
int main(void)
{
    HMODULE plugin_library = LoadLibrary (\"./plugin.dll\");
    FARPROC initizer = GetProcAddress(plugin_library, \"external\");
    initizer();
}\n")
ADD_EXECUTABLE(main main.c)
target_link_libraries(main ${CMAKE_DL_LIBS})
SET_TARGET_PROPERTIES(main PROPERTIES
    ENABLE_EXPORTS TRUE)
FILE(WRITE ${CMAKE_BINARY_DIR}/plugin.c
"void external(void){internal();}\n")
ADD_LIBRARY(plugin MODULE plugin.c)
TARGET_LINK_LIBRARIES(plugin main)

When I try to build the program I get this output which throws the error fatal error U1073: don't know how to make 'main.lib'.

C:\Users\User\Desktop\linkingdemo\build>cmake -G "NMake Makefiles" ..
-- The C compiler identification is MSVC 19.0.23026.0
-- Check for working C compiler: C:/Program Files/Microsoft Visual Studio 14.0/VC/bin/cl.exe
-- Check for working C compiler: C:/Program Files/Microsoft Visual Studio 14.0/VC/bin/cl.exe -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/User/Desktop/linkingdemo/build

C:\Users\User\Desktop\linkingdemo\build>nmake

Microsoft (R) Program Maintenance Utility Version 14.00.23026.0
Copyright (C) Microsoft Corporation.  All rights reserved.

        "C:\Program Files\CMake\bin\cmake.exe" -HC:\Users\User\Desktop\linkingdemo -BC:\Users\User\Desktop\linkingdemo\build --check-build-system CMakeFiles\Makefile.cmake 0
        "C:\Program Files\CMake\bin\cmake.exe" -E cmake_progress_start C:\Users\User\Desktop\linkingdemo\build\CMakeFiles C:\Users\User\Desktop\linkingdemo\build\CMakeFiles\progress.marks
        "C:\Program Files\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe" -f CMakeFiles\Makefile2 /nologo -                   all
        "C:\Program Files\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe" -f CMakeFiles\main.dir\build.make /nologo -L                  CMakeFiles\main.dir\depend
        "C:\Program Files\CMake\bin\cmake.exe" -E cmake_depends "NMake Makefiles" C:\Users\User\Desktop\linkingdemo C:\Users\User\Desktop\linkingdemo C:\Users\User\Desktop\linkingdemo\build C:\Users\User\Desktop\linkingdemo\build C:\Users\User\Desktop\linkingdemo\build\CMakeFiles\main.dir\DependInfo.cmake --color=
Scanning dependencies of target main
        "C:\Program Files\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe" -f CMakeFiles\main.dir\build.make /nologo -L                  CMakeFiles\main.dir\build
        "C:\Program Files\CMake\bin\cmake.exe" -E cmake_progress_report C:\Users\User\Desktop\linkingdemo\build\CMakeFiles 1
[ 50%] Building C object CMakeFiles/main.dir/main.c.obj
        C:\PROGRA~1\MICROS~1.0\VC\bin\cl.exe  @C:\Users\User\AppData\Local\Temp\nm3E0E.tmp
main.c
Linking C executable main.exe
        "C:\Program Files\CMake\bin\cmake.exe" -E vs_link_exe C:\PROGRA~1\MICROS~1.0\VC\bin\link.exe /nologo @CMakeFiles\main.dir\objects1.rsp @C:\Users\User\AppData\Local\Temp\nm3FE4.tmp
        "C:\Program Files\CMake\bin\cmake.exe" -E cmake_progress_report C:\Users\User\Desktop\linkingdemo\build\CMakeFiles  1
[ 50%] Built target main
        "C:\Program Files\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe" -f CMakeFiles\plugin.dir\build.make /nologo -L                  CMakeFiles\plugin.dir\depend
        "C:\Program Files\CMake\bin\cmake.exe" -E cmake_depends "NMake Makefiles" C:\Users\User\Desktop\linkingdemo C:\Users\User\Desktop\linkingdemo C:\Users\User\Desktop\linkingdemo\build C:\Users\User\Desktop\linkingdemo\build C:\Users\User\Desktop\linkingdemo\build\CMakeFiles\plugin.dir\DependInfo.cmake --color=
Scanning dependencies of target plugin
        "C:\Program Files\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe" -f CMakeFiles\plugin.dir\build.make /nologo -L                  CMakeFiles\plugin.dir\build
        "C:\Program Files\CMake\bin\cmake.exe" -E cmake_progress_report C:\Users\User\Desktop\linkingdemo\build\CMakeFiles 2
[100%] Building C object CMakeFiles/http://ift.tt/1N7p27p
        C:\PROGRA~1\MICROS~1.0\VC\bin\cl.exe  @C:\Users\User\AppData\Local\Temp\nm43BB.tmp
plugin.c
C:\Users\User\Desktop\linkingdemo\build\plugin.c(1): warning C4013: 'internal' undefined; assuming extern returning int
NMAKE : fatal error U1073: don't know how to make 'main.lib'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe"' : return code '0x2'
Stop.NMAKE : fatal error U1077: '"C:\Program Files\Microsoft Visual Studio 14.0\VC\BIN\nmake.exe"' : return code '0x2'
Stop.

C:\Users\User\Desktop\linkingdemo\build>

What do I need to do on Windows to get this program to work correctly across multiple platforms?



via Chebli Mohamed

When can return type affect function arguments in C?

I noticed a function in an Arduino example that goes like this:

uint8_t getPrint(int id){
    ......
    p = finger.storeModel(id);
    Serial.println();
    if (p == FINGERPRINT_OK) {
        Serial.println("Stored!");
    } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
    } else if (p == FINGERPRINT_BADLOCATION) {
        Serial.println("Could not store in that location");
        return p;
    } else if (p == FINGERPRINT_FLASHERR) {
        Serial.println("Error writing to flash");
        return p;
    } else {
        Serial.println("Unknown error");
        return p;
    }
}

I didn't include the rest of the function because the argument was used only once as above. Whenever i pass a value greater that 255 to the function, the serial monitor prints id % 256 e.g. 300 changes to 44. As soon as i changed the return type to int, it began to behave normally. Is this possible? What can make a return type affect the arguments? I also noticed that the function does not return a value when it completes successfully (the if statement). Can this be the cause? The return value of the getPrint() function is used in this way by the loop() function:

void loop(){
    //code that obtains an id (declared int) from the user
    .......
    while (!  getPrint(id) );
}

I also need to ask: what value is returned to the while statement? When i run the code, the loop() function seems to restart each time the getPrint() function either returns or reaches the end, regardless of the success or failure of the function; i cant see the effect of the while statement. Thoughts? **All the constants are non-zero 8-bit values except FINGERPRINT_OK



via Chebli Mohamed

How to create a console application in Code::Blocks?

I need to create a console application in Code::Blocks using some of wxWidgets classes (such as wxThread, wxHTTP, ...).

There are no "wxWidgets console application" wizard in Code::Blocks, so I choose just a "Console application", getting main.cpp created with the following code:

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    return 0;
}

It compiles and runs Ok. When I replace it with a contents of examples/samples/console/console.cpp from wxWidgets's examples (skipped some text to be shorter):

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
    #include "wx/wx.h"
#endif
#include <wx/app.h>
#include <wx/cmdline.h>

// implementation
static const wxCmdLineEntryDesc cmdLineDesc[] =
{
    ...
};

int main(int argc, char **argv)
{
    wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, "program");
    //!: **ERROR HERE:^**

    wxInitializer initializer;
    if ( !initializer )
    {
        fprintf(stderr, "Failed to initialize the wxWidgets library, aborting.");
        return -1;
    }
    ...
    // do something useful here
    return 0;
}

I got "undefined reference to wxAppConsoleBase::CheckBuildOptions(char const*, char const*)" error (gcc) at specified line.

What am I doing wrong?

How to fix this?

I can compile my GUI projects with wxWidgets (version 3.0) with no problem, so it looks like I need to specify some defines, includes or any other magic to make it work. I tried to understand example's makefile, but with no luck.



via Chebli Mohamed