lundi 30 mars 2015

OpenGl viewport zooming


I'm a bit new in opengl so please bear with me. I have a viewport window like this


http://ift.tt/1GFZsoQ


I have implemented a zoom in and zoom out using the arrow keys now the problem is it zooms in and out with the whole image. Can anyone put me in the right direction as to how i can make the gui on the sides stay in place while making my viewport the white background zoom in and out.


Any tips or suggestions on how i would accomplish this would be greatly appreciated!




Creating a NTP client with no prior network programming experience. Where do I start?


I have a task to implement a NTP client in C/C++. I have not done much programming in the networking area before and i'm not really sure where to start. Eventually this NTP client needs to be implemented in an embedded system, but I figured it would be wise to start out easy and implement it in a pc program first and then continue from there.


I've read through this: http://ift.tt/1GFYnxp, but I didn't get much wiser as to where to start. Any help to get me started would be greatly appreciated




Find the number of steps required to reach at the top of ladder


I have one question, where i have to climb a ladder of N steps. I have to follow this rule to reach at the top of ladder 1. Take one step 2. Skip one 3. Take another step 4. Skip two steps.


and so on..till i reaches at top.


Algorithm to find the required number of steps i have to take to reach at the top of ladder.


Thanks




Voronoi diagram of point clusters?


Is there a way to compute the voronoi diagram of groups of points?


I.e. all points with the same label/value should be entirely contained by one voronoi segment. Computing the centroid of each group and using that for a regular voronoi diagram will not guarantee that points of the same group are contained within the same segment.


Calculating the convex hull of each group is also not satisfactory as it does not guarantee that either all segments are joined, or that segments do not overlap.


I am trying to derive approximate postal-code boundaries based on lat/long information for individual addresses.


The data itself is in postgis, but any language is suitable (extra points for solutions using sql, python or C++)...




Passing reference of packed struct member to template. gcc bug?


I encountered a problem, passing struct member to a template function. The function's goal is to take the address and size of the member. Here is simple example:


This is the struct. It has packed attribute.



struct TestStruct {
unsigned char elem1;
unsigned char elem2;
uint64_t elem3;
char buf[10000];
int elem4;
unsigned char elem5;
}
__attribute__ ((packed));


this is the template function, which should get a member's address



template<typename T>
void addData(const T &val)
{
printf ("address inside func: %p \n",&val);
}

int main(int argc, char *argv[])
{
TestStruct testdata;
testdata.elem4 = 0;
printf ("struct address is: %p \n",&testdata);
printf ("elem4 address is: %p \n",&testdata.elem4);
addData(testdata.elem4);
return 0;
}


The problem: When attribute ((packed)); is set (like in the example) the template function receives wrong address of the member:


Output:



struct address is: 0x7fff735bb4e0
elem4 address is: 0x7fff735bdbfa
address inside func: 0x7fff735bb4dc


If I remove the "packed" attribute, everything is OK. There is no error and no warning (even with -Wall -Wextra), but not the right address is passed to the function.


I read this:


http://ift.tt/1xO5ke8


and found that there is an issue, getting references to packed-struct members. Interesting enough, replacing const T& with T& in my template function, produces the error message:



error: cannot bind packed field ‘testdata.TestStruct::elem4’ to ‘int&’


So, I have 2 questions:




  1. Why cannot packed-struct members be passed as const references, when their address can be passed as pointer




  2. What happens in the const T& case? There is no error, no warning, but the incorrect address is passed to the function. As we know, the address of reference is the address of the variable, the reference points to.






C++ template function specialization as an argument of template function


Consider a c++ template function specialization :



namespace test {

template < const int L, typename InputIt >
typename std::iterator_traits<InputIt>::value_type
Sum_L( InputIt beg, InputIt end)
{
typedef typename std::iterator_traits<InputIt>::value_type real_t;

for( int i=0 ; i<L; ++i)
call_rearrange_sum( beg, end);

real_t sum( 0 );
for( ; beg != end; ++beg)
sum += *beg;

return sum;
}

template < const int L, typename Real >
Real
Sum_L( const std::size_t len, Real * x)
{
for( int i=0 ; i<L; ++i)
call_rearrange_sum( x, x+len);

Real sum( 0 );
for( std::size_t i=0; i< len; ++i)
sum += x[i];

return sum;
}

template < typename Real, typename Func >
Real
special_sum( std::size_t len, const Real * const x, const Real * y, Func f)
{
std::vector<Real> res( 2*len );

for( std::size_t i=0; i<len; ++i) {
Real tmp;
res.push_back( call_operator( x[i], y[i], &tmp);
res.push_back( tmp );
}

return f( res.begin(), res.end(), f);
}
}


Now I want to use the above functions as :



double my_test( const std::size_t len, double * x, double * y)
{
return test::special_sum( len, x,y,
test::Sum_L< 4, typename std::vector<double>::iterator> );
}


The gcc 4.9.2 it is not able to find the correct template specialization function. The error is "no matching function for call to 'special_sum(std::size_t&, const double*&, const double*&, < unresolved overloaded function type > )'.


Ι know that it is difficult to resolve by the compiler. From whatever I tried, it is one of the two template function 'Sum_L' to get an extra dummy-template argument. Is there any other way?


Thanks.




How to allocate memory for object of the derived class by pointer of the base class using malloc?


For example there is a chain



class A
{
int a;
int b;
public:
A();
};

class B: public A
{
int c;
char b;
public:
B()
};


In ordinary way to to create an object of the derived class we can use this form



A* ptr = new B()


How to do the same using malloc ?




Error : a 'for each' statement cannot operate on an expression of type "MyKinect::ActionKeys []"


im very new in c# and c++. i wana convert C# codes into c++ but i got this error on "for each (auto key in keys)"line. do u mind tell me wat i did wrong. Many Thanx.


C# code :



Public InputResule GetKey(ActionKeys[] keys)
{
InputResule ir = new InputResule();

foreach (var key in keys)
{
var data = mActionList.FirstOrDefault(p => p.Key == key);
if (data.Value != MovementType.None)
{
ir = CheckMovement(data.Value);
}
}
return ir;
}


C++ Code :



InputResule KinectInput::GetKey(ActionKeys keys[])
{
InputResule ir = InputResule();

for each (auto key in keys)
{
auto data = mActionList.find(key->first);
{
return p->Key == key;
};
if (data->Value != MovementType::None)
{
ir = CheckMovement(data->Value);
}
}
return ir;
}



Parse .ini file from resource during runtime using C++/boost


I have an .ini file which is located inside the resource as an RCDATA. I load it from the resource during runtime, and I am able to get it as a very long string.


I am interested of loading the .ini file (from the resource at runtime) and parse it as an .ini file using Boost or Win32 API but the question is how do I do it ?


It seems that it is possible of doing such thing using QT.


I have tried loading the resource file and assigning read_ini() the binary data/string file but it doesn't iterate over it afterwards.


Is it possible of doing such thing ?




Making expression a binary tree?


if we have an expression like a[b(c(-1,e),d),f(g,-1)], here a is root node and in brackets there are child nodes, and -1 is a sentinal. How can we can represent this in a binary tree in c++.




dimanche 29 mars 2015

error: cannot increment value of type 'char [6]'


I am trying to learn pointers and string literals in C/C++. As per my understanding, string literals are char arrays with a null \0 at the end. Also we can basically do all the pointer arithmetic operations on array like increment and decrement.


But when I am trying to run the following code:



#include <iostream>
using namespace std;

int main (){
char *c ="Hello";
char d[6];

while(*d++ = *c++);

cout<<c<<endl<<d;
}


I am getting the following error,



error: cannot increment value of type 'char [6]'
while(*d++ = *c++);


My assumption for this code was, that the values of string literal c will be copied to char array d.




convert mat to ipl image in opencv 3.0


I tried to convert mat image to IplImage but i could not able to convert it , i tried like this





Mat frame=imread("image path");
IplImage* image=IplImage(frame);



I got the error like cannot convert 'IplImage {aka _IplImage}' to 'IplImage* {aka _IplImage*}' in initialization...please any one tell how to convert in opencv 3.0




implementing matlab hist() in c++


here is the line of code I want to implement



kb = [];
for k = 1:length(nRef)
for n=1:length(dCmpInd{k})
x = [centroid(nRef{k}, 1), centroid(dCmpInd{k}(n),1)];
y = [centroid(nRef{k}, 2), centroid(dCmpInd{k}(n),2)];

[x,ind] = sort(x);
y = y(ind);
kb = [kb diff(y) / diff(x)];
end
end

theta = (atan(kb));

[N, X] = hist(abs(theta),2);


here is my c++ code:



std::vector<double> kb;
std::vector<double> theta;
for (int k = 0; k < nRef.size(); k++)
{
for (int n = 0; n < dCmpInd[k].size(); n++)
{
double x1 = centroids[nRef[k]].m_X; double x2 = centroids[dCmpInd[k][n]].m_X;
double y1 = centroids[nRef[k]].m_Y; double y2 = centroids[dCmpInd[k][n]].m_Y;
if (x1 <x2)
{
double tempdiff = (y2-y1)/(x2-x1);
kb.push_back(tempdiff);
theta.push_back(abs(atan(tempdiff)));
}
else
{
double tempdiff = (y1-y2)/(x1-x2);
kb.push_back(tempdiff);
theta.push_back(abs(atan(tempdiff)));
}
}
}


is there a quick way to implement :



[N,X] = hist(theta,2);


I can use openCV 2.4.10 as well but calcHist() isn't really the same, I need to create 2 bins.


my input is 1D array:



0.00598881028540019 1.56120677124307 0.00598881028540019 0.00669537049433832 1.37723800334516 1.37723800334516 1.36424594043624 1.56120677124307 0.0152220988707370


the output is:



X= 0.394793300524817 1.17240228100365
N = 4 5



C++ this pointer equivalent in Python ctypes


I'm calling a C dll from Python using ctypes and having some trouble passing the correct parameters to the IBSU_RegisterCallbacks function, defined below.



int WINAPI IBSU_RegisterCallbacks
(const int handle,
const IBSU_Events event,
void *pCallbackFunction,
void *pContext);


It describes the final parameter as:



/* pContext Pointer to user context that will be passed to callback function.*/


A working C++ example calls the function like this:



RegisterCallbacks(0, 1, OnCallback, this);


So far in Python I have the below code (relevant section shown only), which crashes Python (no traceback) shortly after the event is triggered and callback run! is printed.



from ctypes import *

class IBSU(object):
_dll = WinDLL('ibsu.dll')

_C_CALLBACK = CFUNCTYPE(
None,
c_int, # device handle
c_void_p) # user context

_register_callbacks = _dll.IBSU_RegisterCallbacks
_register_callbacks.restype = c_int
_register_callbacks.argtypes = (c_int, # device handle
c_int, # event type
c_void_p, # callback function
c_void_p) # user context

def _get_c_callback(self):
def callback(handle, # device handle
p_context): # user context
print 'callback run!'
return self._C_CALLBACK(callback)

def register_callbacks(self):
# keep ref to prevent garbage collection
self._c_callback = self._get_c_callback()

self._register_callbacks(0, # device handle
1, # event type
self._c_callback, # callback function
c_void_p()) # user context


What is the equivalent to this in my Python class that I can send instead of just c_void_p()?




does the value of pointers change if exception occurs during assignment?


Consider the following code where pb is a member of class myclass:



myclass& operator=(const myclass& rhs){
myclass *pOrig = pb;
pb = new myclass(*rhs.pb); //exception occurs here .
delete pOrig;
return *this;
}


Will the value of pb remain the same or will it change ? Explain.




What is the difference between the address stored and displayed in C and C++?


In C, if I make a variable and print its address like this:



int a;
int main (void) {
printf ("%p", &a);
return 0;
}


The output was: 00AA


The same program in C++ using the line:



cout << &a << endl;


The output was: 0x8f970aa


What is the difference between these two?


I compiled both the programs using Turbo C.




Face alignment and Fisher face recognition


I am trying out face recognition with LDA Fisher faces. Since Fisher faces are not rotation invariant, is it a good method to do face alignment before face recognition? Please provide a theoretical/math explanation.


Thanks in advance




How the compiler does create an object of derived class using the pointer of the base class?


For example we have the following hierarchy.



class A
{
int a;
char* b;
public a() {}
};

class B
{
int c;
chard;
public:
}


Now, lets allocate memory for derivet class B, using the pointer type of the base class (let's using malloc, because this way is more understandable)



void* a = malloc(sizeof(A)); // we use the size of the class A, which is equal 8 byte in x32 machine
A* obj = new(a) B(); // placement new syntax runs the constructor of B()


The same we can write by following way



A* obj = new B()


In this case we allocate 8 byte of memory for class B and call the B's constructor, but B need to have 12 byte of size, what happens in this case ?




the source code of AODV algorithm


i have searched too much the source code of AODV algorithm but i have not found the source code of it , because i want to work on the AODV algorithm. so any body who has this source code of AODV algorithm please share with me.





This is a link to my previous question with some code that I have.


Thanks.


Here is the code I have so far.



#include <fstream>
#include <iostream>
#include <cstdlib>

using namespace std;

void clean_file(ifstream& fin, ofstream& fout);

int main()
{
ifstream fin;
ofstream fout;
clean_file(fin, fout);
}

void clean_file(ifstream& fin, ofstream& fout)
{
fin.open("string.txt");
if (fin.fail())
{
cout << "File could not open.";
exit(1);
}
fout.open("cleanString.txt");
if (fout.fail())
{
cout << "File could not open.";
exit(1);
}
char line;
while (fin.get(line))
{
fout << line;
}


fin.close();
fout.close();
}


The input file I currently have has extra spaces between some of the words and I want to figure out how to check if the string has more than one space and if it does, to replace it with one space. I am thinking I have to check each character by itself and if the consecutive characters are both spaces then I need to replace it with only one. I have searched my question online but I can't find out how to do it by only using the libraries I mentioned before.




Can we use boost::multi_index::multi_index_container as a multiindex map?


I'm using boost::multi_index::multi_index_container<> of boost library.


I want to store the values related to each element present in this container.


Can we modify this container to use a multimap as well as it will be used as multi index container?




Send and Return 2D dynamic struct from a function in C++


I want to send and retrieve an 2D dynamic struct from a function in C++. I already search in some sites, but the is no one can works. Can anybody help me?


This is my function:





122 void initializePopulation(Body* bodies, int nBodies, Body** kromosom_awal, int nKromosom)
123 {
124 time_t t;
125 time(&t);
126 typedef boost::mt19937 RNGType;
127 RNGType rng((unsigned int) t);
128 boost::uniform_int<> awal_dan_akhir(1, 10);
129 boost::variate_generator< RNGType, boost::uniform_int<> >
130 acak(rng, awal_dan_akhir);
131 cout << "fungsi inisialisasi" << endl;
132 for(int i=0; i<nKromosom; i++)
133 {
134 for(int j=0; j<nBodies; j++)
135 {
136 cout << "nBodies: " << nBodies << " " << i << j << " " << kromosom_awal[i][j].x << " " << bodies[i].x << endl;
137 kromosom_awal[i][j].x = bodies[j].x;
138 kromosom_awal[i][j].y = bodies[j].y;
139 kromosom_awal[i][j].z = bodies[j].z;
140 kromosom_awal[i][j].dx = bodies[j].dx;
141 kromosom_awal[i][j].dy = bodies[j].dy;
142 kromosom_awal[i][j].dz = bodies[j].dz;
143 kromosom_awal[i][j].rho = (acak()/(double) 10);
144 }
145 cout << "nKromosom : " << i << " " << nKromosom << endl;
146 }
147 }



Here is how I call that function:





160 void goGA(XYZ* stasiun, int nStasiun, Body* bodies, int nBodies)
161 {
162 //initialize population
163 int nKromosom = 10;
164 Body *kromosom_awal[nKromosom];
165 initializePopulation(bodies, nBodies, kromosom_awal, nKromosom);
166 }



but it gets me an error:





Segmentation fault: 11


Where is my mistakes?


Oh, btw this is my struct declaration:





17 typedef struct Body
18 {
19 double x;
20 double y;
21 double z;
22 double dx;
23 double dy;
24 double dz;
25 double rho;
26 }Body;
27
28 typedef struct Response
29 {
30 double x;
31 double y;
32 double z;
33 double grav;
34 }Response;
35
36 typedef struct gen
37 {
38 double x;
39 double y;
40 double z;
41 double rho;
42 }gen;
43
44 typedef struct XYZ
45 {
46 double x;
47 double y;
48 double z;
49 }XYZ;





Compiling CLD2 in Visual Studio


I am trying to compile the chromium compact language detector in Visual Studio 2013. I am actually trying to create a .NET Wrapper for the library so I have added all the source files inside my CLR project.


Now whenever I compile I get these linking errors.



error LNK2005: "struct CLD2::CLD2TableSummary const CLD2::kCjkDeltaBi_obj" (?kCjkDeltaBi_obj@CLD2@@3UCLD2TableSummary@1@B) already defined in cld_generated_cjk_delta_bi_32.obj


These all seems to be related as I can see a relation between the 'generated' files.


Problem is I have a lot of these and I am not sure which ones I should exclude and which I should keep and use in my code.


Here is a list all the generated files that came with the CLD2 code.



cld_generated_cjk_uni_prop_80.cc
cld_generated_score_quad_octa_2.cc
cld_generated_score_quad_octa_0122.cc
cld_generated_score_quad_octa_0122_2.cc
cld_generated_score_quad_octa_1024_256.cc
cld_generated_cjk_delta_bi_4.cc
cld_generated_cjk_delta_bi_32.cc
cld2_generated_octa2_dummy.cc
cld2_generated_quad0122.cc
cld2_generated_quad0720.cc
cld2_generated_quadchrome_2.cc
cld2_generated_quadchrome_16.cc
cld2_generated_cjk_compatible.cc
cld2_generated_deltaocta0122.cc
cld2_generated_deltaocta0527.cc
cld2_generated_deltaoctachrome.cc
cld2_generated_distinctocta0122.cc
cld2_generated_distinctocta0527.cc
cld2_generated_distinctoctachrome.cc


The naming convention of these suggests that I should only be using one of each group. At least that how I think I should use it as I am not really an expert in encoding nor in how CLD2 works. And I could not find any references online explaining how to configure it.


I tried eliminating the linking errors by keeping only one of each generated group:


for example: from cld_generated_cjk_delta_bi_4 and cld_generated_cjk_delta_bi_32 I kept the 32 version. And so on for the rest of the files.


Now this made CLD compile yet when I tried testing it with languages I noticed that the scores were way way off and it was behaving inexplicably bad.


I am not trying to support all languages I only need to support latin languages along with hebrew, arabic, japanese and chinese.


Can someone please explain how to configure CLD2 to compile and work correctly.




How to inherit a SimpleRefCount subclass for a class in ns3 (Network Simulator 3)


In network simulator 3, I want to create a Ptr< RoutingTable > object. However, the compiler returns as such:



./ns3/ptr.h:457:7: error: 'class ns3::dsdv::RoutingTable' has no member named 'Unref'
m_ptr->Unref();


I've searched through ns3's doxygen, and I now understand that I should inherit SimpleRefCount which provides Ref and Unref methods for the class. To help me, I've reviewed the class OutputStreamWrapper which inherits from a SimpleRefCount< OutputStreamWrapper >. I have some understanding of generic types. However, I cannot for the life of me see where the actual inheritance takes place. I cannot find the link between OutputStreamWrapper and its SimpleRefCount parent.


Your help would be greatly appreciated.




Build errors while attempting to build synergy


I am having an issue while building synergy. I have followed the steps on http://ift.tt/1xNYaXk however it is saying it is missing a variety of files. Has anyone had luck getting synergy to compile using the Windows instructions? Any help would be greatly appreciated.


As reference I am building with the -g3 flag instead of the default in the instructions. Then just using the hm build command to attempt to build it.


I am also using the 1.7.0 release found on the github for synergy.


Relevant log file is below.


Also pastebin mirror for the log file: http://ift.tt/1IdrKW7



Build started: Project: net, Configuration: Release|Win32
net - up-to-date
Build started: Project: server, Configuration: Release|Win32
server - up-to-date
Build started: Project: synergy, Configuration: Release|Win32
synergy - up-to-date
Build started: Project: synwinhk, Configuration: Release|Win32
synwinhk - up-to-date
Build started: Project: winmmjoy, Configuration: Release|Win32
winmmjoy - up-to-date
Build started: Project: platform, Configuration: Release|Win32
platform - up-to-date
Build started: Project: usynergy, Configuration: Release|Win32
Compiling...
uSynergyWin32.c
C:\Users\steven new\Desktop\synergy\synergy-1.7.0\src\cmd\usynergy\..\..\micro\uSynergy.h(27) : fatal error C1083: Cannot open inc
lude file: 'stdint.h': No such file or directory
Build log was saved at "http://filec:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\src\cmd\usynergy\usynergy.dir\Release\Build
Log.htm"
usynergy - 1 error(s), 0 warning(s)
Build started: Project: integtests, Configuration: Release|Win32
integtests - up-to-date
Build started: Project: ns, Configuration: Release|Win32
Compiling...
SecureSocket.cpp
..\..\..\..\..\src\lib\plugin\ns\SecureSocket.cpp(26) : fatal error C1083: Cannot open include file: 'openssl/ssl.h': No such file
or directory
Build log was saved at "http://filec:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\src\lib\plugin\ns\ns.dir\Release\BuildLog.h
tm"
ns - 1 error(s), 0 warning(s)
Build started: Project: synergyc, Configuration: Release|Win32
synergyc - up-to-date
Build started: Project: synergyd, Configuration: Release|Win32
synergyd - up-to-date
Build started: Project: synergyp, Configuration: Release|Win32
synergyp - up-to-date
Build started: Project: synergys, Configuration: Release|Win32
synergys - up-to-date
Build started: Project: syntool, Configuration: Release|Win32
syntool - up-to-date
Build started: Project: unittests, Configuration: Release|Win32
unittests - up-to-date
Skipped building project C:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\ALL_BUILD.vcproj for solution configuration RELEA
SE|WIN32. This project is excluded from build for this solution configuration.

Build complete: 23 Projects succeeded, 3 Projects failed, 1 Projects skipped
Error: Microsoft compiler failed with error code: 1

C:\Users\steven new\Desktop\synergy\synergy-1.7.0>\
'\' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\steven new\Desktop\synergy\synergy-1.7.0>\
'\' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\steven new\Desktop\synergy\synergy-1.7.0>\
'\' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\steven new\Desktop\synergy\synergy-1.7.0>\
'\' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\steven new\Desktop\synergy\synergy-1.7.0>
C:\Users\steven new\Desktop\synergy\synergy-1.7.0>hm build
Setting environment for using Microsoft Visual Studio 2008 x86 tools.
C:\Users\steven new\Desktop\synergy\synergy-1.7.0
Build started: Project: ZERO_CHECK, Configuration: Release|Win32
ZERO_CHECK - up-to-date
Build started: Project: arch, Configuration: Release|Win32
arch - up-to-date
Build started: Project: base, Configuration: Release|Win32
base - up-to-date
Build started: Project: client, Configuration: Release|Win32
client - up-to-date
Build started: Project: common, Configuration: Release|Win32
common - up-to-date
Build started: Project: gmock, Configuration: Release|Win32
gmock - up-to-date
Build started: Project: gtest, Configuration: Release|Win32
gtest - up-to-date
Build started: Project: io, Configuration: Release|Win32
io - up-to-date
Build started: Project: ipc, Configuration: Release|Win32
ipc - up-to-date
Build started: Project: micro, Configuration: Release|Win32
Compiling...
uSynergy.c
c:\users\steven new\desktop\synergy\synergy-1.7.0\src\micro\uSynergy.h(27) : fatal error C1083: Cannot open include file: 'stdint.
h': No such file or directory
Build log was saved at "http://filec:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\src\micro\micro.dir\Release\BuildLog.htm"
micro - 1 error(s), 0 warning(s)
Build started: Project: mt, Configuration: Release|Win32
mt - up-to-date
Build started: Project: net, Configuration: Release|Win32
net - up-to-date
Build started: Project: server, Configuration: Release|Win32
server - up-to-date
Build started: Project: synergy, Configuration: Release|Win32
synergy - up-to-date
Build started: Project: synwinhk, Configuration: Release|Win32
synwinhk - up-to-date
Build started: Project: winmmjoy, Configuration: Release|Win32
winmmjoy - up-to-date
Build started: Project: platform, Configuration: Release|Win32
platform - up-to-date
Build started: Project: usynergy, Configuration: Release|Win32
Compiling...
uSynergyWin32.c
C:\Users\steven new\Desktop\synergy\synergy-1.7.0\src\cmd\usynergy\..\..\micro\uSynergy.h(27) : fatal error C1083: Cannot open inc
lude file: 'stdint.h': No such file or directory
Build log was saved at "http://filec:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\src\cmd\usynergy\usynergy.dir\Release\Build
Log.htm"
usynergy - 1 error(s), 0 warning(s)
Build started: Project: integtests, Configuration: Release|Win32
integtests - up-to-date
Build started: Project: ns, Configuration: Release|Win32
Compiling...
SecureSocket.cpp
..\..\..\..\..\src\lib\plugin\ns\SecureSocket.cpp(26) : fatal error C1083: Cannot open include file: 'openssl/ssl.h': No such file
or directory
Build log was saved at "http://filec:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\src\lib\plugin\ns\ns.dir\Release\BuildLog.h
tm"
ns - 1 error(s), 0 warning(s)
Build started: Project: synergyc, Configuration: Release|Win32
synergyc - up-to-date
Build started: Project: synergyd, Configuration: Release|Win32
synergyd - up-to-date
Build started: Project: synergyp, Configuration: Release|Win32
synergyp - up-to-date
Build started: Project: synergys, Configuration: Release|Win32
synergys - up-to-date
Build started: Project: syntool, Configuration: Release|Win32
syntool - up-to-date
Build started: Project: unittests, Configuration: Release|Win32
unittests - up-to-date
Skipped building project C:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\ALL_BUILD.vcproj for solution configuration RELEA
SE|WIN32. This project is excluded from build for this solution configuration.

Build complete: 23 Projects succeeded, 3 Projects failed, 1 Projects skipped
Error: Microsoft compiler failed with error code: 1

C:\Users\steven new\Desktop\synergy\synergy-1.7.0>hm build
Setting environment for using Microsoft Visual Studio 2008 x86 tools.
C:\Users\steven new\Desktop\synergy\synergy-1.7.0
Build started: Project: ZERO_CHECK, Configuration: Release|Win32
ZERO_CHECK - up-to-date
Build started: Project: arch, Configuration: Release|Win32
arch - up-to-date
Build started: Project: base, Configuration: Release|Win32
base - up-to-date
Build started: Project: client, Configuration: Release|Win32
client - up-to-date
Build started: Project: common, Configuration: Release|Win32
common - up-to-date
Build started: Project: gmock, Configuration: Release|Win32
gmock - up-to-date
Build started: Project: gtest, Configuration: Release|Win32
gtest - up-to-date
Build started: Project: io, Configuration: Release|Win32
io - up-to-date
Build started: Project: ipc, Configuration: Release|Win32
ipc - up-to-date
Build started: Project: micro, Configuration: Release|Win32
Compiling...
uSynergy.c
c:\users\steven new\desktop\synergy\synergy-1.7.0\src\micro\uSynergy.h(27) : fatal error C1083: Cannot open include file: 'stdint.
h': No such file or directory
Build log was saved at "http://filec:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\src\micro\micro.dir\Release\BuildLog.htm"
micro - 1 error(s), 0 warning(s)
Build started: Project: mt, Configuration: Release|Win32
mt - up-to-date
Build started: Project: net, Configuration: Release|Win32
net - up-to-date
Build started: Project: server, Configuration: Release|Win32
server - up-to-date
Build started: Project: synergy, Configuration: Release|Win32
synergy - up-to-date
Build started: Project: synwinhk, Configuration: Release|Win32
synwinhk - up-to-date
Build started: Project: winmmjoy, Configuration: Release|Win32
winmmjoy - up-to-date
Build started: Project: platform, Configuration: Release|Win32
platform - up-to-date
Build started: Project: usynergy, Configuration: Release|Win32
Compiling...
uSynergyWin32.c
C:\Users\steven new\Desktop\synergy\synergy-1.7.0\src\cmd\usynergy\..\..\micro\uSynergy.h(27) : fatal error C1083: Cannot open inc
lude file: 'stdint.h': No such file or directory
Build log was saved at "http://filec:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\src\cmd\usynergy\usynergy.dir\Release\Build
Log.htm"
usynergy - 1 error(s), 0 warning(s)
Build started: Project: integtests, Configuration: Release|Win32
integtests - up-to-date
Build started: Project: ns, Configuration: Release|Win32
Compiling...
SecureSocket.cpp
..\..\..\..\..\src\lib\plugin\ns\SecureSocket.cpp(26) : fatal error C1083: Cannot open include file: 'openssl/ssl.h': No such file
or directory
Build log was saved at "http://filec:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\src\lib\plugin\ns\ns.dir\Release\BuildLog.h
tm"
ns - 1 error(s), 0 warning(s)
Build started: Project: synergyc, Configuration: Release|Win32
synergyc - up-to-date
Build started: Project: synergyd, Configuration: Release|Win32
synergyd - up-to-date
Build started: Project: synergyp, Configuration: Release|Win32
synergyp - up-to-date
Build started: Project: synergys, Configuration: Release|Win32
synergys - up-to-date
Build started: Project: syntool, Configuration: Release|Win32
syntool - up-to-date
Build started: Project: unittests, Configuration: Release|Win32
unittests - up-to-date
Skipped building project C:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\ALL_BUILD.vcproj for solution configuration RELEA
SE|WIN32. This project is excluded from build for this solution configuration.

Build complete: 23 Projects succeeded, 3 Projects failed, 1 Projects skipped
Error: Microsoft compiler failed with error code: 1

C:\Users\steven new\Desktop\synergy\synergy-1.7.0>hm build
Setting environment for using Microsoft Visual Studio 2008 x86 tools.
C:\Users\steven new\Desktop\synergy\synergy-1.7.0
Build started: Project: ZERO_CHECK, Configuration: Release|Win32
ZERO_CHECK - up-to-date
Build started: Project: arch, Configuration: Release|Win32
arch - up-to-date
Build started: Project: base, Configuration: Release|Win32
base - up-to-date
Build started: Project: client, Configuration: Release|Win32
client - up-to-date
Build started: Project: common, Configuration: Release|Win32
common - up-to-date
Build started: Project: gmock, Configuration: Release|Win32
gmock - up-to-date
Build started: Project: gtest, Configuration: Release|Win32
gtest - up-to-date
Build started: Project: io, Configuration: Release|Win32
io - up-to-date
Build started: Project: ipc, Configuration: Release|Win32
ipc - up-to-date
Build started: Project: micro, Configuration: Release|Win32
Compiling...
uSynergy.c
c:\users\steven new\desktop\synergy\synergy-1.7.0\src\micro\uSynergy.h(27) : fatal error C1083: Cannot open include file: 'stdint.
h': No such file or directory
Build log was saved at "http://filec:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\src\micro\micro.dir\Release\BuildLog.htm"
micro - 1 error(s), 0 warning(s)
Build started: Project: mt, Configuration: Release|Win32
mt - up-to-date
Build started: Project: net, Configuration: Release|Win32
net - up-to-date
Build started: Project: server, Configuration: Release|Win32
server - up-to-date
Build started: Project: synergy, Configuration: Release|Win32
synergy - up-to-date
Build started: Project: synwinhk, Configuration: Release|Win32
synwinhk - up-to-date
Build started: Project: winmmjoy, Configuration: Release|Win32
winmmjoy - up-to-date
Build started: Project: platform, Configuration: Release|Win32
platform - up-to-date
Build started: Project: usynergy, Configuration: Release|Win32
Compiling...
uSynergyWin32.c
C:\Users\steven new\Desktop\synergy\synergy-1.7.0\src\cmd\usynergy\..\..\micro\uSynergy.h(27) : fatal error C1083: Cannot open inc
lude file: 'stdint.h': No such file or directory
Build log was saved at "http://filec:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\src\cmd\usynergy\usynergy.dir\Release\Build
Log.htm"
usynergy - 1 error(s), 0 warning(s)
Build started: Project: integtests, Configuration: Release|Win32
integtests - up-to-date
Build started: Project: ns, Configuration: Release|Win32
Compiling...
SecureSocket.cpp
..\..\..\..\..\src\lib\plugin\ns\SecureSocket.cpp(26) : fatal error C1083: Cannot open include file: 'openssl/ssl.h': No such file
or directory
Build log was saved at "http://filec:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\src\lib\plugin\ns\ns.dir\Release\BuildLog.h
tm"
ns - 1 error(s), 0 warning(s)
Build started: Project: synergyc, Configuration: Release|Win32
synergyc - up-to-date
Build started: Project: synergyd, Configuration: Release|Win32
synergyd - up-to-date
Build started: Project: synergyp, Configuration: Release|Win32
synergyp - up-to-date
Build started: Project: synergys, Configuration: Release|Win32
synergys - up-to-date
Build started: Project: syntool, Configuration: Release|Win32
syntool - up-to-date
Build started: Project: unittests, Configuration: Release|Win32
unittests - up-to-date
Skipped building project C:\Users\steven new\Desktop\synergy\synergy-1.7.0\build\ALL_BUILD.vcproj for solution configuration RELEA
SE|WIN32. This project is excluded from build for this solution configuration.

Build complete: 23 Projects succeeded, 3 Projects failed, 1 Projects skipped
Error: Microsoft compiler failed with error code: 1

C:\Users\steven new\Desktop\synergy\synergy-1.7.0>



C++ Function Return/Input Reference Type


I'm way too confused of reference return/input types. I think I can best ask my question by explaining my understanding.


When a reference is input to a function as an argument as below...



void squareByReference( int & );

int main ()
{
int z = 4;
sequareByReferece( z );

return 0;
}

int squareByReference( int &numberRef )
{
numberRef *= numberRef;
}


I understand it as in the 'squareByReference,' &numberRef is received by the function as an address to an int variable, but 'somehow' can be recognized and treated just like a normal int variable. Therefore, the line 'numberRef *= numberRef; can treat numberRef as a normal int even though it's actually an address.


I'm okay with this. I get it and no problem interpreting/coding programs.


However, when it comes down to reference return, it makes me confused too much.



int g_test = 0;

int& getNumberReference()
{
return g_test;
}

int main()
{
int& n = getNumberReference();

n = 10;
std::cout << g_test << std::endl; // prints 10
std::cout << getNumberReference() + 5 << std::endl; // prints 15

return 0;
}


My confusion is this: Why is 'n' defined as a reference int variable?! Following my previous logic, the getNumberReference() returned a reference variable, and even though it is actually an address to an int, it should be 'somehow' treated as equal to normal int variable. Therefore, it should be defined in int variable not reference to int variable! This logic works perfectly fine when it comes to the line 'std::cout << getNumberReference() + 5 << std::endl;.' It is 'somehow' treated as a normal int variable and prints 15.


Could you please correct my understanding to resolve my question on int& definition???





In Multidimensional arrays as class member with arbitrary bounds I was advised I should use a vector of vectors of ints to represent a dynamic 2D array in my array-backed graph object. However, I'm getting segmentation faults whenever I try to run my code. GDB points to the line where a variable is defined as the arraygraph type; I presume that means I did something wrong specifying the type of edges. Here is the class definition:



class arraygraph {
private:

public:
void open(char *filename);
bool exists(int nodeid);
int node_count(void);
int weight(int nodea, int nodeb);
void print();
private:
int count;
vector <vector <int> > edges; //A vector of vectors! [Inception Noise]
};


All the methods of this object are defined (funny how you can compile with prototypes that haven't been filled out...). The code compiles without errors or warnings. Why's it segfaulting?


EDIT:


Here's some disassembler output:



163 int main(int argc, char *argv[]) {
main(int, char**):
00401c86: lea 0x4(%esp),%ecx
00401c8a: and $0xfffffff0,%esp
00401c8d: pushl -0x4(%ecx)
00401c90: push %ebp
00401c91: mov %esp,%ebp
00401c93: push %ebx
00401c94: push %ecx
00401c95: sub $0x20,%esp
00401c98: mov %ecx,%ebx
00401c9a: call 0x402350 <__main>
164 arraygraph thegraph;
00401c9f: lea -0x18(%ebp),%eax (this is where the problem occured according to GDB)
00401ca2: mov %eax,%ecx
00401ca4: call 0x403e90 <arraygraph::arraygraph()>


So apparently the segfault happened before the arraygraph was constructed? I don't know what to make of this.


EDIT:


The entirety of main() is as such:



int main(int argc, char *argv[]) {
arraygraph thegraph;
thegraph.open(argv[1]);
return 0; //Added this after I noticed I'd omitted it - didn't fix anything
}


And here's arraygraph::open():



//Only call .open() once. A second call will leave the old graph's dessicated corpse around the edges of the new one.
void arraygraph::open(char *filename){
int count;
int x, y;
tomgraph loader;

loader.open(filename);

count=loader.node_count();

//delete edges;
//edges = new vector <vector <int> >;

for (x=1; x <= count; x++) {
for (y=1; y <= count; y++) {
int weight;
if (loader.is_connected(x,y,&weight) || loader.is_connected(y,x,&weight)) {
edges[x-1][y-1]=weight;
} else {
edges[x-1][y-1]=0; //0 represents "no edge"
}
}
}
}


But according to the disassembler this never gets called anyway.


EDIT:


Full code here. Umm... I think it's saying it worked? Lemme try a different machine...


EDIT:


Nope. Similar segfault after compiling on a completely separate Linux machine.


EDIT:


Just to confirm, I commented out the call to thegraph.open(). Didn't fix it.




When Iterator invalidation is occurred in observer pattern with single process single thread environment


I'm implementing an observer pattern that the subject notifies observers and I knew it has a issue as bellow.



  • Issue : iterator for notify() can be invalid, when container for observers like std::vector, std::list is modified on being notified.


But as I think, in single thread single process environment, invalid iterator issue never be happen except in as bellow situation.



  • situation 1 : some observers modify observer container when it notified.

  • situation 2: loop for notify() modify observer container on being notified.


I know, situation 1,2 make iterator invalid, but I want to know concrete case.


Hope some advice. Thanks.




How can I get GPU information?


I have a task to collect information about GPU in Windows with C++ and I don't know where to start! Any idea?


Update: I want name, vram, dac, manufacturer, version, clock.


update2: If I use win32_videocontroller class, I just got the currently used video card's properties, but I need all video card's properties if there are more.




matlab mex cannot find vcomp.lib when openmp is used


I am trying to mex a c++ source file containing openmp usages. In the mex command, i have added COMPFLAGS="/openmp $COMPFLAGS" but it says cannot find vcomp.lib. My matlab mex have been setup to use the compiler of Windows SDK 7.1 located in C:\Program Files. I checked the lib files inside this SDK and didn't find vcomp.lib. Anyone knows how can I install openmp to Windows SDK 7.1? Thanks a lot!




My output file does not read the spaces from my input file.


I am having trouble getting my program to read the spaces in my input file, I am new to and objects in general so any help would be appreciated.


My input file is: Hello my name is Pierre. I like to code .

My output file is: HellomynameisPierre.Iliketocode.


Another question I have is how can I check if my string has more than one space, and if it does, replace it with only one space.



#include <fstream>
#include <iostream>
#include <cstdlib>

using namespace std;

void clean_file(ifstream& fin, ofstream& fout);

int main()
{
ifstream fin;
ofstream fout;
clean_file(fin, fout);
}

void clean_file(ifstream& fin, ofstream& fout)
{
fin.open("string.txt");
if (fin.fail())
{
cout << "File could not open.";
exit(1);
}
fout.open("cleanString.txt");
if (fout.fail())
{
cout << "File could not open.";
exit(1);
}
char line;
while (fin >> line)
{
fout << line;
}


fin.close();
fout.close();
}



Incremental parse with POCO JSON


I am using POCO 1.6.0. I am trying to write a service that receives a JSON message on a raw socket and parses it.


However, the only way that POCO's parser seems to work is to take an entire string as input, and either return the parsed result, or throw a "Syntax error" exception.


So this means I have to re-parse the whole message each time a new byte arrives on the socket; and also there is no way of distinguishing between an actual syntax error versus it just being an incomplete message so far.


The parseChar function looks nice but it is private. Is there any way to have the parser parse some of a message and remain in that state so that I can resume parsing by passing more data?


Also, is there any way to distinguish actual syntax errors from incomplete messages (and preferably get feedback about the exact nature of the syntax error).


Pseudocode:



Poco::JSON::Parser parser;
std::string input_buffer;

for(;;)
{
// (append byte(s) from socket into input_buffer)
// (return failure if this read times out after 5 seconds)

parser.reset();
try
{
parser.parse(input_buffer);
break;
}
catch(Poco::Exception &e)
{
// (abort, but we don't know if data incomplete or data malformed
}
}




Note: I realize that this problem could be mooted by having the client frame the entire message as described in this thread, however I was hoping to make things as simple as possible for the client by just having a correctly-formed packet be sufficient to define a frame (method 5 of that question).




How can I get motherboard information in C++? (Windows)


I know about WMI , but are there any other possibilities? I mean like at CPU -> CPUID




Setting data of one class from within another class


I am trying to set the attendance of students based on user input. Where I run it to the problem is trying to take that input and assign it to my data on each student.


All the data I have is read from a file in to a singly linked list. The struct for this data type is declared in my node.h.


So what I'm asking is how would I modify the values that originate from the Node class, within my menu class?


Menu.cpp



void Menu::chooseMenu(ifstream *input, List L1)
{
data temp;
//data plswork[12];
char holder[30];
char junk[30];
int i=1,j=1;

do{
system("cls");
cout<<"1. Import"<<endl;
cout<<"2. Load Master"<<endl;
cout<<"3. Store Master"<<endl;
cout<<"4. Mark Absence"<<endl;
cout<<"5. Generate Report"<<endl;
cout<<"6. Exit"<<endl;
cout<<""<<endl;
cin>>selection;

if(selection == 1)//import
{
while(!input->eof())
{
memset(holder,0,30);

if(i==3 && j != 1)
{
input->getline(holder,30,'"');
input->getline(holder,30,'"');
input->getline(junk,30,',');
}
else
{
input->getline(holder,30,',');
}

if(i==1)
{
strcpy(temp.record, holder);
//cout<<temp.record<<endl;
i++;
}
else if(i==2)
{
strcpy(temp.ID, holder);
//cout<<temp.ID<<endl;
i++;
}
else if(i==3)
{
strcpy(temp.name, holder);//read between quotes
//cout<<temp.name<<endl;
i++;
j=2;
}
else if(i==4)
{
strcpy(temp.email, holder);
//cout<<temp.email<<endl;
i++;
}
else if(i==5)
{
strcpy(temp.units, holder);
//cout<<temp.units<<endl;
i++;
}
else if(i==6)
{
strcpy(temp.major, holder);
//cout<<temp.major<<endl;
i++;
}
else if(i==7)
{
strcpy(temp.grade, holder);

//cout<<temp.grade<<endl;
L1.insertOrder(temp);
i=1;
}

}
}

else if(selection == 2)//load master
{

}

else if(selection == 3)//store master
{

}

else if(selection == 4)//mark absence
{
while(L1.nextPtr() != NULL)
{
char name;
cout<<"Bruce :"<<L1.getDataL().absent<<endl;
cout<<"Is "<<L1.getDataL().name<<" present? (Y/N)"<<endl;
cin>>name;
if(name == 'y' || name == 'Y')
{
L1.setAtt(L1.getDataL(),1); // This is where I try to set attendance to 0 or 1.
cout<<L1.getDataL().absent<<endl;
}
else
{
L1.setAtt(L1.getDataL(),0);
}

L1.nextPtr();
system("pause");
}
}

else if(selection == 5)//gen report
{

}

}while(selection != 6);

}


Node.cpp



#include "Node.h"

ListNode::ListNode (ListNode &copyObject)
{
this->mData = copyObject.mData;
this->mpNext = copyObject.mpNext;
}

ListNode::~ListNode ()
{
// does nothing
cout << "exiting listnode object - going out of scope" << endl;
}

ListNode * ListNode::getNextPtr () const
{
return mpNext;
}

data ListNode::getData() const
{
return mData;
}

ListNode::ListNode(data newData)
{
mData = newData;
this->mpNext = NULL;
}



My while loop goes into it's second iteration before my switch statement executes completely, I'm coding in c++



#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

void ReadFile()
{

string fileName;
ifstream inFile;

cout << "Please enter the password for the external file: ";
getline(cin, fileName);

inFile.open(fileName);

}//End of ReadFile() function


int main()
{
vector<string> studentName, studentNumber, studentClass;
char option;

while (option != 'g' && option != 'G')
{

cout << "\t\t\t" << "Student List Menu\n\n";
cout << "A. Reading the Student List from a file\n";
cout << "B. Adding Student's Informations into the Student List\n";
cout << "C. Displaying the content of the Student List\n";
cout << "D. Sorting and Displaying the content of the Student List\n";
cout << "E. Writing the Student List to a file\n";
cout << "F. Searching for a Student's Information from the Student List\n";
cout << "G. Ending the program\n\n";
cout << "Please enter an option: ";
cin >> option;
cout << endl;

switch (option)
{

case 'A':
case 'a':
ReadFile();
break;

case 'B':
case 'b':
break;

case 'C':
case 'c':
break;

case 'D':
case 'd':
break;

case 'E':
case 'e':
break;

case 'F':
case 'f':
break;

case 'G':
case 'g':
cout << "Thank you for using the program!";
break;

default: cout << "Invalid option choice\n\n";

}

}

return 0;
}//End of main function


When I select option 'A', the switch statement calls the ReadFile() function, but when it asks for the "password" (the file name) to be entered, "Student List Menu" is read, which I think means the do-while loop continued to run while executing the ReadFile function, so it read the input until the newline character. What can I do to get it to run the option first, then continue through the do-while loop?




What's the type of "precision" specifier for printf()


Suppose I use the following printf() specifier string:



printf("%.*s", length, str);


which asks printf() to print the first length characters in str . The question is which type length has? I only see brief mentions of integer number in the documentation.


So it looks like it is int. Then it looks like I cannot use the following code when a string is very long:



const char* startOfString = ...
const char* middleOfString = ...
printf("%.*s", (int)( middleOfString - startOfString ), startOfString);


It looks like I cannot output more than INT_MAX characters this way.


So which type is precision? Is it int or is it size_t or anything else?




Segmentation Fault in Function Call


So I've got my program to the point where it compiles, but upon calling up the other functions the program drops with a Segmentation Fault(core dumped) error. Everything works until then. I'll add the entire code in case the setup is wrong (possible as I don't particularly understand pointers or passing values and such)



#include <cmath>
#include <iostream>
using namespace std;

void discrim0(float a, float b, float c, float * root1, float * root2);
void discrimmore(float a, float b, float c, float * root1, float * root2);
void discrimless(float a, float b, float c, float * real, float * sqrtim);

int main()
{

float discrim;
float a;
float b;
float c;
float * root1=0;
float * root2=0;
float * real=0;
float * sqrtim=0;
char cAgain;

cout << "Welcome to the quadratic roots calculator." <<endl;

do
{
do
{

cout << "Please enter the three coefficient values of the" <<endl;
cout << "quadratic equation. The coefficient of x^2 must not"<<endl;
cout << "be 0." <<endl;

cin >> a >> b >> c;

if(a==0)
{
cout << "The value you entered for the coefficient of x^2"<<endl;
cout << "is not valid(0). Please enter a proper value."<<endl;
}
}while(a==0);


discrim=(b*b)-4*a*c;

if(discrim<0)
{
cout << "Your equation has two imaginary roots."<<endl;
//error occurs here
discrimless(a,b,c, real, sqrtim);
cout << *real << " + " << *sqrtim << "i" << endl;
cout << "and" << endl;
cout << *real << " - " << *sqrtim << "i" << endl;
}

if(discrim==0)
{
cout << "Your equation two roots of the same value."<<endl;
//error occurs here
discrim0(a,b,c, root1, root2);
cout << *root1 << " and " << *root2 << endl;
}

if(discrim>=0)
{
cout << "Your equation has two real roots, which are: "<<endl;
//error occurs here
discrimmore(a,b,c, root1, root2);
cout << *root1 << " and " << *root2;
}

cout << "Would you like to run another calculation? Y/y/N/n"<<endl;
cin >> cAgain;

}while(cAgain=='Y'||cAgain=='y');

return 0;
}

void discrim0(float a, float b, float c, float * root1, float * root2)
{
*root1= ((-b + sqrt((b*b)-4*a*c))/2*a);

*root2= ((-b - sqrt((b*b)-4*a*c))/2*a);
}

void discrimless(float a, float b, float c, float * real, float * sqrtim)
{
*real= (-b)/(2*a);
*sqrtim= (sqrt(-(b*b-4*a*c)))/(2*a);

}

void discrimmore(float a, float b, float c, float * root1, float * root2)
{
*root1= ((-b + sqrt((b*b)-4*a*c))/2*a);

*root2=((-b - sqrt((b*b)-4*a*c))/2*a);
}


I marked in the code where it happens. Essentially it will tell you the number of roots and then crash. I understand the general idea of seg fault that I am trying to access memory I don't have or something to that effect, but I don't really know why it is occurring. Also please keep in mind that I don't really understand technical speak too well. Thanks.




C++ : Disabling a device driver in Windows


Can anybody help me to tell why this code is not disabling the cdrom driver?It builds correctly.I debugged each line everything works perfectly. I have removed the error handling code and the cleanup code.



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

IWbemServices *pSvc = NULL;
HRESULT hres = CoInitializeEx(0, COINIT_MULTITHREADED);

hres = CoInitializeSecurity(NULL,-1,NULL,NULL,RPC_C_AUTHN_LEVEL_DEFAULT,RPC_C_IMP_LEVEL_IMPERSONATE,NULL,EOAC_NONE,NULL);
IWbemLocator *pLoc = NULL;
hres = CoCreateInstance(CLSID_WbemLocator,0,CLSCTX_INPROC_SERVER,IID_IWbemLocator,LPVOID *)&pLoc);

hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"),NULL,NULL,0,NULL,0,0,&pSvc);

BSTR MethodName = SysAllocString(L"StopService");
BSTR ClassName = SysAllocString(L"Win32_SystemDriver");

IWbemClassObject* pClass = NULL;
hres = pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL);
IWbemClassObject* pInParamsDefinition = NULL;
hres = pClass->GetMethod(MethodName, 0, &pInParamsDefinition, NULL);

VARIANT varCommand;

IWbemClassObject* pOutParams = NULL;
hres = pSvc->ExecMethod(L"Win32_SystemDriver.Name=\"cdrom\"", MethodName, 0,
NULL,NULL, &pOutParams, NULL);

VARIANT varReturnValue;
hres = pOutParams->Get(L"ReturnValue", 0, &varReturnValue, NULL, 0);
if (!FAILED(hres))
wcout << "ReturnValue " << varReturnValue.intVal << endl;
VariantClear(&varReturnValue);

// Clean up
SysFreeString(ClassName);
SysFreeString(MethodName);
return 0;
}


Please help..




Saving string to class attribute using character pointer in C++


I'm having difficulty trying to take in inputs using cin, saving them to a few variables, and then constructing a class. When I put in the first input, instead of waiting for the next input, the program loop infinitely and keeps displaying the prompt over and over.


The class is:



class person {
public:
char *name;
char *email;
int phone;
// constructor that uses the parameters to initialize the class properties
person(char *cName, char *cEmail, int iPhone) {
name = new (char[32]); // acquiring memory for storing name
email = new (char[32]); // acquiring memory for storing email
strcpy(name, cName); // initialize name
strcpy(email, cEmail); // initialize email
phone = iPhone; // initialize phone
}
virtual ~person() {
delete[] name;
delete[] email;
}
};


And the input and constructor call is as follows:



char* nameIn = new (char[32]); // acquiring memory for storing name
char* emailIn = new (char[32]);
int iPhoneIn;

cout << "Enter name, email, and phone:\n";

cin >> *nameIn;
cin >> *emailIn;
cin >> iPhoneIn;

person* newPerson = new person(nameIn, emailIn, iPhoneIn); //create node



Undefined Reference to [duplicate]



This is the input to g++ and the resulting error messages.



$ g++ main.cpp -o keyLogger
/tmp/ccvwRl3A.o:main.cpp:(.text+0x93): undefined reference to `SaveFeatures::SaveFeatures(std::string)'
/tmp/ccvwRl3A.o:main.cpp:(.text+0x93): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `SaveFeatures::SaveFeatures(std::string)'
/tmp/ccvwRl3A.o:main.cpp:(.text+0xbf): undefined reference to `SaveFeatures::save(std::string)'
/tmp/ccvwRl3A.o:main.cpp:(.text+0xbf): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `SaveFeatures::save(std::string)'
collect2: error: ld returned 1 exit status


I've checked and rechecked my syntax for the .h and .cpp for SaveFeatures class but havent been able to find an error. Any help would be welcome.


Main.cpp



#include <string>
#include "SaveFeatures.h"

using namespace std;

int main(){
string fileName="saveTest.text";
string saveContent="this is a test";
SaveFeatures saveFeatures(fileName);
saveFeatures.save(saveContent);
}


SaveFeature.cpp



#include "SaveFeatures.h"
#include <string>
using namespace std;

SaveFeatures::SaveFeatures(string fileName){
setFileName(fileName);
}

void SaveFeatures::setFileName(string fileName){
if(fileName!=NULL){
this.fileName=fileName;
}
}
bool SaveFeatures::save(string content){
if(fileName==NULL)return false;
if (content==NULL)return false;
FILE *file;
file=fopen(fileName,"a");
if(file!=NULL){
fputs(content,file);
}
return true;
}

string SaveFeatures::getFileName(){
return fileName;
}


SaveFeatures.h



#ifndef SAVEFEATURES_H
#define SAVEFEATURES_H
#include <string>
using namespace std;

class SaveFeatures{
public:
SaveFeatures(string fileName);
void setFileName(string fileName);
string getFileName();
bool save(string content);
private:
string fileName;
//need to make a method to determine if the fileName has file extension
};
#endif


Thank you for your help ladies and gents




Compile and Run Cocos2D-x


Hi guys n00b developer here, just asking if i can build a cocos2d-x c++ project for a html5? can someone guide me please? thank you so much in advance.




Inheritance with Nodes in C++


I'm writing a doubly linked list in C++ and have a class Node which I'm using for a singly linked list. Below shows the definition of the class.



Node.h




#ifndef NODE_H
#define NODE_H

template <class T>
class Node {
public:
Node<T>() { this = nullptr; }
Node<T>(T init) { data = init; next = nullptr; }

void setData(T newData) { data = newData; }
void setNext(Node<T> *nextNode) { next = nextNode; }

const T getData() { return data; }
Node<T> *getNext() { return next; }
private:
T data;
Node<T> *next;
};

#endif


Obviously the main difference between a singly linked list and doubly linked list is a pointer to the previous Node, so I'm trying to inherit everything from the Node class in a new class and simply add a prev attribute:



DoublyLinkedList.h




#ifndef DOUBLY_LINKEDLIST_H
#define DOUBLY_LINKEDLIST_H

#include "Node.h"

template <class T>
class DLLNode : public Node {
public:
// Inherit default constructor from Node and set prev to nullptr;
DLLNode<T>() : Node<T>(), prev() {}
// Inherit constructor from Node and set prev to nullptr;
DLLNode<T>(T init) : Node<T>(init), prev() {}

Node<T> *getPrev() { return prev; }
private:
Node<T> *prev;
};

/*
TODO: Implement doubly linked list class
*/

#endif


My driver is, simply, the following:



driver.cc




#include <iostream>
#include "DoublyLinkedList.h"

int main()
{
DLLNode<int> test;

return 0;
}


When I compile, I get the following errors:



./DoublyLinkedList.h:7:24: error: expected class name
class DLLNode : public Node {
^
./DoublyLinkedList.h:9:18: error: type 'Node<int>' is not a direct or virtual base of 'DLLNode<int>'
DLLNode<T>() : Node<T>(), prev() {}
^~~~~~~
driver.cc:6:15: note: in instantiation of member function 'DLLNode<int>::DLLNode' requested here
DLLNode<int> test;


I don't understand why the class Node isn't being recognized as a class as my compiler has claimed by the first error. Any tips would be greatly appreciated.


My compiler is Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)




project.exe has triggered a breakpoint after system("pause")


I've created my own vector, and when I try to close the console in my driver, I hit enter and get the breakpoint.



#include "MyVector.h"
#include <vector>

// Default constructor
MyVector::MyVector()
{
theData = nullptr;
vecSize = 0;
vecCap = 0;
}

// Parameterized constructor
MyVector::MyVector(int vecCap)
{
// Set vecSize to 0 and vecCap to user input (driver) plus 1 to account
// for null terminator
vecSize = 0;
this->vecCap = vecCap;
theData = new int[vecCap];
}

// Destructor
MyVector::~MyVector()
{
// Run the clear() function
clear();
}

// Copies the vector
void MyVector::copy(const MyVector& toCopy)
{
// Set size and capacity to toCopy's
this->vecCap = toCopy.vecCap;
this->vecSize = toCopy.vecSize;

// Create a temporary pointer array of ints
int* tempArray = new int[];

// Copy data from toCopy to new array
for (int i = 0; i < toCopy.size(); i++)
{
tempArray[i] = toCopy.theData[i];
}

// Point theData to the tempArray
theData = tempArray;
}

// Clears theData and resets vecCap and vecSize to 0
void MyVector::clear()
{
// Check if theData is null
if (theData != nullptr)
{
// Delete theData from heap and set to nullptr
delete[] theData;
theData = nullptr;

// Set vecSize and vecCap to 0
vecSize = 0;
vecCap = 0;
}
}

// Returns size of the vector
int MyVector::size() const
{
return vecSize;
}

// Returns capacity of the vector
int MyVector::capacity() const
{
return vecCap;
}

// Push input values into vector
void MyVector::push_back(int n)
{
// Check if vecSize is too big for vecCap
if (vecSize >= vecCap)
{
// Double vecCap through grow() function
grow(vecCap);
}

// Set theData at element vecSize to user input n, increment vecSize
theData[vecSize] = n;
vecSize++;
}

// Returns index value of vector
int MyVector::at(int vecIdx) const
{
// Check if vecIdx is within bounds
if (vecIdx >= 0 && vecIdx <= vecSize)
{
// Return vector index
return theData[vecIdx];
}
else
{
// Display out of bounds index
throw vecIdx;
}
}

// Doubles the size of the vector capacity
void MyVector::grow(int curCap)
{
// Check if curCap is 0 ro less
if (curCap <= 0)
{
// Set vecCap to CAP_GROWTH -1
vecCap = CAP_GROWTH - 1;
}
else
{
// Increase curCap by CAP_GROWTH (doubled)
vecCap = CAP_GROWTH * curCap;
}

// Create new array
int* newArray = new int[vecCap];

// Copy data to new array
for (int idx = 0; idx < vecSize; idx++)
{
newArray[idx] = theData[idx];
}

// Delete theData
delete[] theData;

// Point theData to new array
theData = newArray;
}

//
MyVector& MyVector::operator=(const MyVector& rho)
{
// Check if the implicit object's address is the same as rho
if (this != &rho)
{
// Clear the implicit object
this->clear();
// Copy the
this->copy(rho);
}
return *this;
}

//
ostream& operator<<(ostream& out, const MyVector& rho)
{
for (int idx = 0; idx < rho.size(); idx++)
{
// Output index of rho, separated by a space
out << rho.at(idx) << " ";
}
return out;
}


I've checked for somewhere I may have tried to re-delete a pointer, but I can't find anything, any it doesn't say why the exception was thrown. Any tips?




how initialize char* const argv [] in c++


An API function takes an argument of type 'char *const argv[]' I am initializing this type of arguments in my c++ application like:



char* const argv[] = {"--timeout=0", NULL};


and passing the arguments to API function like:



Spawner spawner;
spawner.execute (argv, true);


using g++ compiler, I am getting following Error:



error: deprecated conversion from string constant to 'char*' [-Werror=write-strings]


how can I get rid of above error?


Below is the declaration of execute function in API:



void Spawner::execute (char *const argv[], bool bShowChildWindow)



FBX Scene causing vs2013 to crash with exception to NTDLL.DLL


I am Loading An FBX Scene and when all dependency are set it run OK from a simple main(), but when I integrate it back into my D3D Application which uses Concurrency it seems to conflict with NTDLL.DLL, the debugger displays an apparent exception that is not caught, see below



Unhandled exception at 0x77EEE052 (ntdll.dll) in App7.exe: 0xC0000135: Unable to Locate DLL.


The code is simple:



#include "pch.h"
#include "SceneFBX.h"
#include <fbxsdk.h>
#include <fbxsdk/fileio/fbxiosettings.h>

using namespace App7;
//using namespace DirectX;
//using namespace Windows::Foundation;
SceneFBX::SceneFBX():
failed(NULL)
{
failed=LoadFBX();
}
bool SceneFBX::LoadFBX()
{
FbxManager* g_pFbxSdkManager = nullptr;

if (g_pFbxSdkManager == nullptr) {
g_pFbxSdkManager = FbxManager::Create();
FbxIOSettings* pIOsettings = FbxIOSettings::Create(g_pFbxSdkManager, IOSROOT);
g_pFbxSdkManager->SetIOSettings(pIOsettings); }

FbxImporter* lImporter = FbxImporter::Create(g_pFbxSdkManager, "");
const char* lFilename = "FILE.fbx";

bool lImportStatus = lImporter->Initialize(lFilename, -1,g_pFbxSdkManager->GetIOSettings());

if (!lImportStatus) { printf("Call to FbxImporter::Initialize() failed.\n");
printf("Error returned: %s\n\n", lImporter->GetStatus().GetErrorString()); exit(-1);
}
FbxScene* lScene = FbxScene::Create(g_pFbxSdkManager, "myScene");
lImporter->Import(lScene);
lImporter->Destroy();

return true;
}


so why does ntdll.dll load normally then crash?



'App7.exe' (Win32): Loaded 'Projects\App7\Debug\App7\AppX\App7.exe'. Symbols loaded.
'App7.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'. Symbols loaded.
'App7.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'. Symbols loaded.
'App7.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'. Symbols loaded.
'App7.exe' (Win32): Loaded 'C:\Windows\SysWOW64\d2d1.dll'. Symbols loaded.
'App7.exe' (Win32): Loaded 'C:\Windows\SysWOW64\d3d11.dll'. Symbols loaded.
'App7.exe' (Win32): Loaded 'C:\Windows\SysWOW64\dxgi.dll'. Symbols loaded.
'App7.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ole32.dll'. Symbols loaded.
'App7.exe' (Win32): Loaded 'C:\Windows\SysWOW64\DWrite.dll'. Symbols loaded.
First-chance exception at 0x77EEE052 (ntdll.dll) in App7.exe: 0xC0000135: Unable to Locate DLL.
Unhandled exception at 0x77EEE052 (ntdll.dll) in App7.exe: 0xC0000135: Unable to Locate DLL.


Does this help?? Threads View




C++ iostream operator overladed function return type


I'm still in learning phase of basic formats and commands of C++. I'm now at class operator function overloading and came to << and >>. My question is: when they are defined in friend functions such as below:



ostream &operator << ( ostream &output, const PhoneNumber &number )


and are called with PhoneNumber class phone like this:



cout << phone << endl;


Why is the friend function returning ostream&? I mean when a function returns a value of a particular type, it is generally received by a fundamental type variable such as bool, int, char, string, and etc. However, for ostream and istream, the returned type of ostream& is not being saved. Then, in this case, shouldn't it be void (carry out the task and terminate without returning any values)?




precompile v8 screipt for use in multiple isolate


I have implemented a 'require'-like function using embedded v8 that loads a javascript file and executes it, but because my program has multiple threads, and as such each thread has its own isolate, I am having to load and compile the file separately in each thread that specifies the same source. I am wanting to, if possible, somehow cache any compiled script so that if another thread (using another isolate) happens to want the same file, I can utilize some sort of precocmpiled format, and just give it the script to run, instead of having to separately compile it inside of each isolate that needs the same file.




How to create the makefiles for a c project comprised of several folders with code?


Here is the deal. I have a folder structure with several building blocks of code and I can't figure out how to create the necessary makefiles to compile the project.


I tried to make the following but it didn't work:


I created the project with the wizard in order to let eclipse to create the makefiles automatically and it compiled correctly.


I observed that the makefiles automatically created by eclipse are created in the workspace folder but I want them in my project folders.


What I did as a test was basically to replicate all the .mk files and the main makefile in my folder structure exactly as eclipse did in the workspace and create a new project with the create empty makefile option from the wizard but but it doesn't compile.


I don't know what else should I do or configure to make it work.


Thanks for helping.




Confusing sizeof(char) by ISO/IEC in different character set encoding like UTF-16


Assuming that a program is running on a system with UTF-16 encoding character set.


So according to The C++ Programming Language - 4th, page 150: "A char can hold a character of the machine’s character set." → I think that a char variable will have the size is 2-bytes.


But according to ISO/IEC 14882:2014: "sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1". or The C++ Programming Language - 4th, page 149: "[...], so by definition the size of a char is 1" → It is fixed with size is 1.


Question: Is there a conflict between these statements above or is the "sizeof(char) = 1" just a default (definition) value and will be implementation-defined depends on each system?




Function to delete node with given value from a binary search tree


I have a struct called TreeNode with an int key, and left right and parent. I am trying to delete a node from a tree with my DeleteNode function and it is not working. I am supposed to replace the deleted node in my DeleteNode function with the max value from the left subtree. My transplant and max functions are helper functions for DeleteNode. My issue is I'm not sure where in my DeleteNode function I should be comparing the node value I am at to the value I am passing in through the function. I have a comment in my code with astericks where I'm confused what to do. Any help would be greatly appreciated!



void transplant(TreeNode* u, TreeNode* v) //swaps u with v
{

if (u->parent == NULL) //if u was root, make v new root
u->parent = v;
else if (u == u->parent->left) //if u is smaller than it's parent
u->parent->left = v; //set v to the left child of parent of u. Swap them at left, really
else
u->parent->right = v; //otherwise swap them at right

if (v != NULL) //reassign parents to double link
v->parent = u->parent;
}

TreeNode* maximum(TreeNode* n)
{

while (n->left != NULL)
n = n->left;
return n;
}

void deleteNode(TreeNode *node, int key)
{

if (node->left == NULL) //if there is no left child
transplant(node, node->right); //swap
else if (node->right == NULL) //if there is no right child
transplant(node, node->left); //swap
else
{
if(node->key == key){ //****This if comparison must be wrong***
TreeNode* temp = maximum(node->right); //make temp the max on right
if (temp->parent != node ) //if it is more than one chain down
{
transplant(temp, temp->right); //swap temp and it's right branch
temp->right = node->right; //set right branch to nodes right
temp->parent->right = temp; //set temp to the right child
}
transplant(node, temp); // transplant
temp->left = node->left; //get nodes left branch
temp->left->parent = temp; //replace
}
}
}



Trouble calling an object's method using a pointer to that object


So I normally wouldn't bother posting about such a simple thing but I can't for the life of me figure out what I'm doing wrong and it's probably something very simple that i'm over looking.


Getting straight to the point, I'm making an object pointer and then using that pointer to call a method of that particular object.


But for some reason whenever I cout the function as follows:



Entry FirstEntry = Entry(J1,H1);
cout << FirstEntry.getItem() << endl;
cout << FirstEntry.getKey() << endl;


Entry *siz = new Entry();

cout << siz->getItem() << endl;


It gives me a blank line being output. Whereas it should be giving me my item value. The Object itself looks like such:


Entry::Entry() {



}

Entry::Entry(KeyType & Key, ItemType & newItem)
{
setKey(Key);
setItem(newItem);
}

Entry::~Entry()
{

}

ItemType Entry::getItem() const
{
return item;
}

KeyType Entry::getKey() const
{
return searchKey;
}
void Entry::setItem(const ItemType & newItem)
{
item = newItem;
}

void Entry::setKey(const KeyType & Key)
{
searchKey = Key;
}


I've been staring at this code for awhile and I can't quite figure out what's causing it to output just a blank line.


Thank you very much for your patience,




C/C++ dynamic memory allocation using realloc() and free()


In the code below, I have made a function for finding the prime numbers between two given number. What I am trying to do is, from the given list of initial numbers remove all the numbers divisible by the first prime number, i.e. 2, then from the new list of the remaining elements, remove those divisible by 3, and continue so on till number<=square root(maximum given number).


How I have implemented this is create a pointer of integers storing the initial list. Check for divisibility and store the indivisible elements in a new pointer of integers. Once that is done, I want to free the initial pointer, in my case "inp_storage", reallocate it memory of the size of the second list, which is "storage", and make it point to what "storage points to". Then I want to free "storage" so that it can store a new list, maybe of different size.


x,y are the given two numbers between which I have to find the prime numbers.


However, on building and debugging in visual studio 10, I get this error during runtime:


HEAP[primenumgen.exe]: Invalid address specified to RtlValidateHeap( 007E0000, 007E57B4 ) Windows has triggered a breakpoint in primenumgen.exe.


This may be due to a corruption of the heap, which indicates a bug in primenumgen.exe or any of the DLLs it has loaded.



int num_begin=2, num_n=x;

int storage_count =0;

float sqrt_num=sqrt(float(y));

int *inp_storage=(int*)malloc(sizeof(int)*(y-x));

int *storage=(int*)malloc(sizeof(int)*(y-x));

int *inp_head=inp_storage;
int *storage_head=storage;

for(int i=x; i<=y; i++)
{
*inp_storage=i;
inp_storage++;
}
inp_storage=inp_head;

while(num_begin<=(int)sqrt_num)
{
storage_count=0;
while(*inp_storage >0)//!=NULL)
{
if(*inp_storage%num_begin >=1)
{
cout<<"Inside if "<<*inp_storage<<"\n";

*storage=*inp_storage;
storage++;
storage_count++;
}
inp_storage++;
}
free(inp_storage);
inp_storage=(int *)realloc(inp_storage, sizeof(int)*storage_count);
storage=storage_head;
inp_storage=storage;

if(num_begin==2)
{
num_begin=num_begin+1;
}
else
{
num_begin=next_num_gen();
cout<<"next number is "<<num_begin <<"\n";
}
}



investigating visual studio assembly output


While using /FA option for compiling code that uses this dummy class



class A {
public:
A() {}
int Initialize() {
return 0;
}
};


I looked over the generated asm file where this was defined and also used and saw this in the asm file



PUBLIC ?Initialize@A@@QEAAHXZ ; A::Initialize
PUBLIC ??0A@@QEAA@H@Z ; A::A

??0A@@QEAA@H@Z PROC ; A::A, COMDAT
; File d:\dev\temp\consoleapplication1\consoleapplication1\consoleapp2.cpp
; Line 7
mov rax, rcx
ret 0
??0A@@QEAA@H@Z ENDP ; A::A
_TEXT ENDS
; Function compile flags: /Ogtpy
; COMDAT ?Initialize@A@@QEAAHXZ
_TEXT SEGMENT
this$dead$ = 8
?Initialize@A@@QEAAHXZ PROC ; A::Initialize, COMDAT
; File d:\dev\temp\consoleapplication1\consoleapplication1\consoleapp2.cpp
; Line 9
xor eax, eax
; Line 10
ret 0
?Initialize@A@@QEAAHXZ ENDP ; A::Initialize


As you can see there is generated "trivial" implementation functions for both constructor and Initialize function.


At first I thought that this non inline implementation was going to be used where class A is used but debugging showed that this was not the case (code seemed to be inlined). Class A is not used anywhere else except this asm file so why are those functions generated if not used ?


Whole program optimization was in place.




Magick++ Error when reading BLOB into Image


I'm trying to export an image from raw pixel data into a RGBA PNG using the Magick++ library.


However, I'm getting a strange error when I'm attempting to run it:



terminate called after throwing an instance of 'Magick::ErrorCorruptImage'
what(): test: unexpected end-of-file `': No such file or directory @ error/rgb.c/ReadRGBImage/229
Aborted


This is the relevant code part (I omitted filling the pixel vector, but that doesn't change anything):



#include <iostream>
#include <vector>
#include <ImageMagick/Magick++.h>

using namespace std;

int main(int argc, char *argv[]) {
Magick::InitializeMagick(*argv);
int rres, ires;
cin >> rres >> ires;
//RGBA
//rres: horiz. resolution, ires: vert. resolution
vector<unsigned char> image(rres * ires * 4);
Magick::Blob blob(&image[0], rres*ires*4);
Magick::Image img;
img.size(to_string(rres) + "x" + to_string(ires));
img.magick("RGBA");
img.read(blob);
img.write("out.png");
}


Compilation with:



g++ --std=c++11 -O0 -g3 -ggdb3 -D_GLIBCXX_DEBUG -Wall test.cpp -o test `Magick++-config --cppflags --cxxflags --ldflags --libs`