Converting littleEndian via QDataStream - c++

i want to send some integers (int32_t) via network.
For this I convert the integers first and send them.
p.x = 129;
p.y = 42;
p.d = counter++;
converted[0] = htonl(p.x);
converted[1] = htonl(p.y);
converted[2] = htonl(p.d);
if ( (bytes = send(socket, (char *)converted, pointSize, 0)) < 0)
{
std::cerr << "bytes = " << bytes << std::endl;
}
Then Qt should do the work, so I tried a QDataStream conversion but that failed, values > 128 got negative. So currently I do a conversion like this:
while ( socket->bytesAvailable() > 0 )
{
//qDebug() << "Data received" << socket->bytesAvailable();
m_data.append(socket->readAll());
//qDebug() << "Buffer " << m_data.size();
if (m_data.size() >= sizeOfPoint)
{
Point x;
QByteArray b = m_data.left(sizeOfPoint);
for (int i = 0; i < 4; i++)
{
x.x += (u_int8_t) b[i] << 8*(3-i);
}
for (int i = 4; i < 8; i++)
{
x.y += (u_int8_t) b[i] << 8*(7-i);
}
for (int i = 8; i < 12; i++)
{
x.d += (u_int8_t) b[i] << 8*(11-i);
}
//x.x = (u_int8_t) (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | (b[3]);
//x.y = (b[4] << 24) | (b[5] << 16) | (b[6] << 8) | (b[7]);
//x.d = (b[8] << 24) | (b[9] << 16) | (b[10] << 8) | b[11];
//x.d = b[10] << 8;
//x.d = (b[11]);
//QDataStream in(buffer.data());
//in.setByteOrder(QDataStream::LittleEndian);
//in >> conv[1];
//in >> conv[2];
qDebug() << "Data provided " << x.x << " " << x.y << " "<< x.d;
m_data.remove(0, sizeOfPoint);
}
}
What is the best way to convert these integers, the for loop seems not optimal for me.
Thank you

Related

How to format output like this

My code is like this so far :
void matrix::print(int colWidth) const
{
cout << getRows() << " x " << getCols() << endl;
cout << "-";
for (unsigned int d = 0; d < getCols(); d++) {
cout << "--------";
}
cout << endl;
for (unsigned x = 0; x < getRows(); x++) {
cout << "|";
for (unsigned y = 0; y < getCols(); y++) {
cout << setw(colWidth) << at(x, y) << " |";
}
cout << endl;
}
cout << "-";
for (unsigned int d = 0; d < getCols(); d++) {
cout << "--------";
}
cout << endl;
}
But the output depends on the colWidth which will be the space between each number printed. So how can I adjust my dashes to be printed like the following no matter the colWidth it should align.
One output should look like this:
Second output is like this:
If the column width is a parameter, you're almost done with your code. Just turn the cout<<"--------" into:
std::cout << std::string(getCols()*(colWidth + 2) + 1, '-');
That code prints a string of dashes, which width is: number of matrix columns, times column width plus 2, plus 1:
Plus 2 because you are appending a " |" to each column.
Plus 1 because you are adding a '|' at the beginning of each row.
You may want to check for empty matrices at the beginning of your print method.
[Demo]
#include <initializer_list>
#include <iomanip> // setw
#include <iostream> // cout
#include <vector>
class matrix
{
public:
matrix(std::initializer_list<std::vector<int>> l) : v{l} {}
size_t getRows() const { return v.size(); }
size_t getCols() const { if (v.size()) { return v[0].size(); } return 0; }
int at(size_t x, size_t y) const { return v.at(x).at(y); }
void print(int colWidth) const
{
std::cout << "Matrix: " << getRows() << " x " << getCols() << "\n";
// +2 due to " |", +1 due to initial '|'
std::cout << std::string(getCols()*(colWidth + 2) + 1, '-') << "\n";
for (unsigned x = 0; x < getRows(); x++) {
std::cout << "|";
for (unsigned y = 0; y < getCols(); y++) {
std::cout << std::setw(colWidth) << at(x, y) << " |";
}
std::cout << "\n";
}
std::cout << std::string(getCols()*(colWidth + 2) + 1, '-') << "\n";
}
private:
std::vector<std::vector<int>> v{};
};
int main()
{
matrix m{{1, 2}, {-8'000, 100'000}, {400, 500}};
m.print(10);
}
// Outputs
//
// Matrix: 3 x 2
// -------------------------
// | 1 | 2 |
// | -8000 | 100000 |
// | 400 | 500 |
// -------------------------

Parsing HHMMSS come from NMEA

I have a trouble with NMEA data(gpzda). The problem is explained below.
NMEA Data : $GPZDA,011856.00,17,03,2018,,*61
My Parsing Code.
char hour[2] = { 0 };
for (int i=0; i < 2; i++) hour[i] = utctime[i];
info.tm_hour = atoi(hour);
char min[2] = { 0 };
for (int i=0; i < 2; i++) min[i] = utctime[i + 2];
info.tm_min = atoi(min);
char sec[2] = { 0 };
for (int i=0; i < 2; i++) sec[i] = utctime[i + 4];
info.tm_sec = atoi(sec);
cout << info.tm_year << " | " << info.tm_mon << " | " << info.tm_mday << " | " << info.tm_hour << " | " << info.tm_min << " | " << info.tm_sec << endl;
The code is well working, but some time the hour value is strange like a "126". I thought that "6" is add from another memory. How to parse this data to well work?
You should zero terminate your strings, so declare each one to be of size 3.
char hour[3] = { 0 };
and so on

all the pos3d values are zero while posUVZ values are not zero

In the following snippet, when I print the posUVZ values, they are non-zero but after I pass them to ProjectDepthToCamera(wxhDepth, posUVZ, pos3D) all the pos3D values happen to be zero. Any though on why is this happening and how to fix it?
/***
Reads the depth data from the sensor and fills in the matrix
***/
void SR300Camera::fillInZCoords()
{
PXCImage::ImageData depthImage;
PXCImage *depthMap = sample->depth;
depthMap->AcquireAccess(PXCImage::ACCESS_READ, &depthImage);
PXCImage::ImageInfo imgInfo = depthMap->QueryInfo();
int depth_stride = depthImage.pitches[0] / sizeof(pxcU16);
Projection * projection = device->CreateProjection();
unsigned int wxhDepth = depth_width * depth_height;
// create the array of depth coordinates + depth value (posUVZ) within the defined ROI
PXCPoint3DF32* posUVZ = new PXCPoint3DF32[wxhDepth];
pxcU16 *dpixels = (pxcU16*)depthImage.planes[0];
unsigned int dpitch = depthImage.pitches[0] / sizeof(pxcU16); /* aligned width */
for (unsigned int yy = 0, k = 0; yy < depth_height; yy++)
{
for (unsigned int xx = 0; xx < depth_width; xx++, k++)
{
posUVZ[k].x = (pxcF32)xx;
posUVZ[k].y = (pxcF32)yy;
posUVZ[k].z = (pxcF32)dpixels[yy * dpitch + xx];
// cout << "xx is " << posUVZ[k].x << endl;
// cout << "yy is " << posUVZ[k].y << endl;
// cout << "zz is " << posUVZ[k].z<< endl;
}
}
// convert the array of depth coordinates + depth value (posUVZ) into the world coordinates (pos3D) in mm
PXCPoint3DF32* pos3D = new PXCPoint3DF32[wxhDepth];
projection->ProjectDepthToCamera(wxhDepth, posUVZ, pos3D);
/*
if (projection->ProjectDepthToCamera(wxhDepth, posUVZ, pos3D) < PXC_STATUS_NO_ERROR)
{
delete[] posUVZ;
delete[] pos3D;
cout << "projection unsucessful";
return;
}
*/
for (unsigned int yy = 0, k = 0; yy < depth_height; yy++)
{
for (unsigned int xx = 0; xx < depth_width; xx++, k++)
{
cout << "xx is " << pos3D[k].x*1000.0 << endl;
cout << "yy is " << pos3D[k].y*1000.0 << endl;
cout << "zz is " << pos3D[k].z*1000.0 << endl;
xyzBuffer.push_back(cv::Point3f(pos3D[k].x, pos3D[k].y, pos3D[k].z));
}
}
/*
for (int idx = 0; idx < wxhDepth; idx++) {
cout << "x is " << pos3D[idx].x*1000.0 << endl;
cout << "y is " << pos3D[idx].y*1000.0 << endl;
cout << "z is " << pos3D[idx].z*1000.0 << endl;
xyzBuffer.push_back(cv::Point3f(pos3D[idx].x, pos3D[idx].y, pos3D[idx].z));
}
*/
//xyzMap = cv::Mat(xyzMap.size(), xyzMap.type, &pos3D);
xyzMap = cv::Mat(xyzBuffer);
cout << "xyzMap = " << endl << " " << xyzMap << endl << endl;
projection->Release();
delete[] posUVZ;
delete[] pos3D;
};
Here's the correct answer to get the xyzMap from the Depth image UVmap:
PXCImage::ImageData depthImage;
depthMap->AcquireAccess(PXCImage::ACCESS_READ, &depthImage);
PXCImage::ImageInfo imgInfo = depthMap->QueryInfo();
depth_width = imgInfo.width;
depth_height = imgInfo.height;
num_pixels = depth_width * depth_height;
PXCProjection * projection = device->CreateProjection();
PXCPoint3DF32 *pos3D = new PXCPoint3DF32[num_pixels];
sts = projection->QueryVertices(depthMap, &pos3D[0]);
if (sts < Status::STATUS_NO_ERROR) {
wprintf_s(L"Projection was unsuccessful! \n");
sm->Close();
}

What is wrong with my function for Lagrange?

GsVec curve_eval::eval_lagrange(float t, float numberofsegmentsn, const GsArray<GsVec>& ctrlpnts) //f(t) = sum of p.i * B.i(t)
{
//float interval = 1 / numberofsegmentsn; //so if 4, then 0.25
float interval = 1 / ctrlpnts.size();
//remember that for interval that is put in above, it's based on numbers of ctrlpnts
//for lagrange, let t
GsVec ft(0.0f, 0.0f, 0.0f);
int sizeofctrlpnts = ctrlpnts.size();
float result = 0;
std::cout << "interval = " << interval << " \\ number of segments = " << numberofsegmentsn << " \\ ctrlpnts.size() = " << ctrlpnts.size() << "\n";
float tt = 0;
float ti[50] = { 0 };
float tj[50] = { 0 }; //only this might be used
for (int x = 0; x < ctrlpnts.size(); x++) //changed from 'numberofsegmentsn'
{
tj[x] = tt;//
std::cout << "tt in tj[" << x << "]= " << tt << "\n";
tt = tt + interval;
}
float tb = 1;
tt = 1;
int i = 0;
for (int i = 0; i < ctrlpnts.size(); i ++)
{
tt = 1;
tb = 1;
for (int j = 0; j < ctrlpnts.size(); j++) //
{
if (i != j)
{
std::cout << "Before cal: i = " << i << " :: j = " << j << " :: tt = " << tt << " :: tb = " << tb << " :: t = " << t << " :: tj[i" << j << "] = " << tj[j] << " :: tj[j" << i << "] = " << tj[i] << "\n";
tt = (t - tj[j]) * tt;
tb = (tj[i] - tj[j])* tb;
std::cout << "After cal: tt = " << tt << " :: tb = " << tb << "\n";
}
//t gotta change
}
result = tt / tb;
ft = ft+(ctrlpnts[i]*result);
}
return ft;
Above is my written algorithm for Lagrange function for opengl.
Following link is the screenshot of the formula that i had to impliment, http://imgur.com/gkuaxVm.
I have been tweaking it for awhile, and i can't seem to find what is wrong with it.

segmentation fault for string function argument

I have a simple main code that gives me segmentation fault when calling a function. In the following code, I have two functions, the first one works correctly but the program doesn't enter the second one and gives me segmentation fault error. Is there any reason for that? I have made sure about the following:
The variables o and c are not out of bound.
cn is initialized correctly.
I have a read-only access to cm and argv. Plus it does not even enter the function evaluate
Here is the code:
void print_cm(vector<vector<int> > *cm, char* gtf);
void evaluate(vector<vector<int> > *cm, char* gtf);
int main(int argc, char** argv)
{
int o = 2; // It is initialized
int c = 4; // It is initialized
vector<vector<int> > cm; // It is initialized
if (argc>4)
print_cm(&cm, argv[o]);
if (argc>4)
{
cout << argv[c] << endl; // Works
// The following also works
for (int i=0; i<cm.size(); i++)
for (int j=0; j<cm[i].size(); j++)
cout << cm[i][j] << " ";
// The following causes segmentation fault;
evaluate(&cm, argv[c]);
}
return 0;
}
void evaluate(vector<vector<int> > *cm, char* gtf)
{
// Read-only access to cm and gtf
}
void print_cm(vector<vector<int> > *cm, char* gtf)
{
// Read-only access to cm and gtf
}
Here is the complete code:
#include "includes/Utility.h"
#include "includes/Graph.h"
void print_cm(vector<vector<int> > *cores, char* output);
void evaluate(vector<vector<int> > const *cm, char* gtf);
int main(int argc, char** argv)
{
int g = -1, c = -1, o = -1;
for (int i=1; i<argc-1; i++)
if (argv[i][0]=='-')
{
if (argv[i][1]=='g')
g = i + 1;
else if (argv[i][1]=='c')
c = i + 1;
else if (argv[i][1]=='k')
ki = i + 1;
else if (argv[i][1]=='s')
si = i + 1;
else if (argv[i][1]=='o')
o = i + 1;
}
Graph G;
if (c>0) G.read_input(argv[g], argv[c]);
else G.read_input(argv[g]);
if (ki > 0)
{
int k = atoi(argv[ki]);
cout << k << endl;
}
if (si > 0)
{
int s = atoi(argv[si]);
cout << s << endl;
}
// Find communities
vector<vector<int> > cores;
G.partitioning(&cores);
if (o>0)
print_cm(&cores, argv[o]);
if (c>0)
{
cout << "here" << endl;
for (size_t i=0; i<cores.size(); i++)
for (size_t j=0; j<cores[i].size(); j++)
if (cores.at(i).at(j)<0) cout << "here";
cout << "here" << endl;
evaluate(&cores, argv[c]);
}
}
return 0;
}
void print_cm(vector<vector<int> > *cores, char* output)
{
ofstream out;
out.open(output);
for(size_t i=0; i<(*cores).size(); i++)
{
for(size_t j=0; j<(*cores)[i].size(); j++)
out << (*cores)[i][j] << " ";
out << endl;
}
out.close();
return ;
}
void evaluate(vector<vector<int> > const *cm, char* gtf)
{
// we evaluate precision, recall, F1 and F2
vector<vector<int> > gt;
ifstream in;
char str[100000000];
in.open(gtf);
while(in.getline(str, 100000000))
{
stringstream s;
s << str;
int a;
gt.resize(gt.size()+1);
while (s >> a) gt[gt.size()-1].push_back(a);
}
in.close();
cout << "==================== Evaluation Results ====================" << endl;
int imax = 0;
for(size_t i=0; i<(*cm).size(); i++)
imax = max(imax, *max_element((*cm)[i].begin(), (*cm)[i].end()));
for(size_t i=0; i<gt.size(); i++)
imax = max(imax, *max_element(gt[i].begin(), gt[i].end()));
vector<bool> flag(imax, false);
vector<double> recall((*cm).size(), 0), precision((*cm).size(), 0), f1((*cm).size(), 0), f2((*cm).size(), 0);
int overlap;
double size = 0;
for(size_t i=0; i<(*cm).size(); i++)
{
// evaluate
size += (double) (*cm)[i].size();
for(size_t j=0; j<(*cm)[i].size(); j++)
flag[(*cm)[i][j]] = true;
double p, r, ff1, ff2;
for(size_t j=0; j<gt.size(); j++)
{
overlap = 0;
for(size_t k=0; k<gt[j].size(); k++)
if (flag[gt[j][k]]) overlap++;
p = (double) overlap / (double) (*cm)[i].size();
if (p > precision[i])
precision[i] = p;
r = (double) overlap / (double) gt[j].size();
if (r > recall[i])
recall[i] = r;
ff1 = (double) 2*(p*r)/(p+r);
if (ff1 > f1[i])
f1[i] = ff1;
ff2 = (double) 5*(p*r)/(4*p + r);
if (ff2 > f2[i])
f2[i] = ff2;
}
for(size_t j=0; j<(*cm)[i].size(); j++)
flag[(*cm)[i][j]] = false;
}
double Recall = 0, Precision = 0, F1 = 0, F2 = 0;
for(size_t i=0; i<(*cm).size(); i++)
{
Recall += recall[i];
Precision += precision[i];
F1 += f1[i];
F2 += f2[i];
}
cout << "+--------------+--------------+--------------+--------------+" << endl;
cout << "| " << setiosflags( ios::left ) << setw(10) << "Precision";
cout << " | " << setiosflags( ios::left ) << setw(10) << "Recall";
cout << " | " << setiosflags( ios::left ) << setw(10) << "F1-measure";
cout << " | " << setiosflags( ios::left ) << setw(10) << "F2-measure";
cout << " |" << endl;
cout << "| " << setiosflags( ios::left ) << setw(10) << Precision/(*cm).size() ;
cout << " | " << setiosflags( ios::left ) << setw(10) << Recall/(*cm).size();
cout << " | " << setiosflags( ios::left ) << setw(10) << F1/(*cm).size();
cout << " | " << setiosflags( ios::left ) << setw(10) << F2/(*cm).size();
cout << " |" << endl;
cout << "+--------------+--------------+--------------+--------------+" << endl;
cout << "Number of communities: " << (*cm).size() << endl;
cout << "Average community size: " << size/(*cm).size() << endl;
return ;
}
char str[100000000];
This is in your evaluate function. This are 100 million bytes, or about 95 MB that you're allocating on the stack.
Typical stack sizes are far less than that, around 1 MB.
So apart from possible other problems this is most likely causing a stack overflow.
When entering the function, the stack frame gets extended to be large enough to hold the local variables. As soon as the stack is used then (to write a default value) you're accessing invalid (non stack, thankfully protected) memory.