I think that the default overload of ==
for valarray
is not very convenient. By default x==y
(for two valarrays x and y) returns a valarray<bool>
, with true
on the i
th entry if x[i]==y[i]
. Rather, I need a single bool
, which tells me if both valarray<double>
contain the same elements or not. I know I can do this with a cycle, but having to do the cycle every time is not convenient. What's the best workaround here? Is there a way for me to define my own overload of ==
(and also !=
, <
, and so on)?
lundi 29 juin 2015
C++ fstream is writing hex instead of string?
I'm trying to download a file using URLDownloadToFile()
which is working so far, however I'm having trouble with the callback function and writing the callback output wszStatusText to a file.
Here is the function that's giving the problem:
HRESULT DownloadStatus::OnProgress(ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR wszStatusText)
{
fstream myfile;
myfile.open("file.txt", ios::app);
// this prints hex e.g. StatusText: 00435F78
myfile << " StatusText: " << wszStatusText;
myfile.close();
// this prints the string properly e.g. text/plain
MessageBox(NULL, wszStatusText, L"test", MB_OK);
return S_OK;
}
The thing is that MessageBox()
is showing the data properly...
How to declare unique_ptr of vector?
I am trying to declare a global vector of MyClass
using unique_ptr
. My compiler is 4.8.4.
glo.h
extern std::unique_ptr<std::vector<MyClass>> gl_vec;
glo.cpp
std::unique_ptr<std::vector<MyClass>> gl_vec;
And in the file where I initialize and use it for the first time in a different *.cpp file:
#include "glo.h"
// within function
{
gl_vec = std::unique_ptr<std::vector<MyClass>> ();
cout << "gl_vec size = " << (*gl_vec).size() << endl; // crashes here
}
Things keep crashing when I use the pointer. Anyone see what I'm doing wrong?
Qt QDir::current()
I had some code like this:
void MainWindow::saveData()
{
QDir oldDir=QDir::current();//this should return the main executable directory.Since there is no other place in my hole code where i temper with QDir.
QDir sess("Sessions");
if(!oldDir.exists("Sessions"))//if "Sessions" Dir doesn't exist
oldDir.mkdir("Sessions");//create it.
QDir::setCurrent(sess.absolutePath());
//some virtual code inside current Dir, which i didn't implement yet.
QDir::setCurrent(oldDir.absolutePath());//restore old dir
}
When i run my app firstly the code works perfectly.but in the second run, the first call to "QDir::current();" returns the "Sessions" Dir and not the main executable Dir as it should be restored in the first run.actually i did manage to overcome this by adding one line at the biginning of the code, the following :
QDir::setCurrent(QCoreApplication::applicationDirPath());
Still i want to know why the first code didn't work.already checked for the documentation of the functions and found nothing.
gmtime_r((time_t*)&title->start_time, &start_time);
I'm trying to compile on Microsoft visual studio 2013 on C++ a program written for linux ( is a mix of C and C++ (#include .h) and I'm going to convert all in C++ to not be more confused !)
the statement:
gmtime_r((time_t*)&title->start_time, &start_time);
return errors: Error 11 error C3861: 'gmtime_r': identifier not found IntelliSense: identifier "gmtime_r" is undefined
please help
Passing a reference-to-function as a universal reference
I'm struggling to understand what exactly happens when passing a reference-to-function to a function as a universal reference (what type is being deduced). Let's suppose we have a function foo that takes a param as a universal reference:
template<typename T>
void foo(T&& param)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
And then let's do the following:
void(&f)(int) = someFunction;
foo(f);
The result will be:
void foo(T&&) [with T = void (&)int]
This is perfectly understandable: we are passing lvalue to our function foo, so the deduced type is void(&)int, and the type of the param will be "void(&& &)int" which under reference collapsing rules becomes void(&)int. Param will be just an lvalue reference to a function.
But when I do the following:
void(&f)(int) = someFunction;
foo(std::move(f));
foo will print:
void foo(T&&) [with T = void (&)int]
which is exactly the same as before! What is happening here? Why the result is the same as when passing lvalue? I would expect that since we are passing rvalue to foo, the deduced type should be T = void(int), and param should become void(&&)int. This always happen with all other "normal" types (like classes, primitive types, etc.) Why is it different when dealing with function references?
Refresh a Combobox in C++?
I have a function that detects camera ports in 3D slicer, however it seems to only run once. When I unplug/plug in a camera, the number of ports should update in a combobox (designed in Qt), but nothing changes.
The function I'm using detects when the camera port is clicked:
void qSlicerTrackingModuleWidget::onCameraPortClicked(){
Q_D(qSlicerTrackingModuleWidget);
// Clear current entries
d->CameraPortComboBox->clear();
int n = 0;
// Loop over camera ports until last one is found. Add all available ports to combo box and exit.
while(1){
cv::VideoCapture cap = cv::VideoCapture(n);
if(!cap.isOpened()){
return;
}
QString portNum = QString::fromStdString(std::to_string(n++));
d->CameraPortComboBox->addItem(portNum);
qSlicerCoreApplication::processEvents();
}
}
The setup function runs last and assigns the GUI to the actual function.
connect( d->CameraPortComboBox, SIGNAL(clicked()), this, SLOT(onCameraPortClicked()));
I need it to refresh and try to detect the cameras every time the combobox is clicked on, but because of the interface setup I am not sure if it is possible. I don't think constantly refreshing the program is a good option, so I'm out of ideas. Is there any way to do this?
What is the use for buckets interface in std::unordered_map?
I've been watching this video from CppCon 2014 and discovered that there is an interface to access buckets underneath std::unordered_map
. Now I have a couple of questions:
- Are there any reasonable examples of the usage of this interface?
- Why did the committee decide to define this interface, why typical STL container interface wasn't enough?
What reasons are there for having comparisons be only of the form <= and >= (and not including =< and =>)?
In many languages, such as Java and C/C++, comparisons are always done of the form <=
and >=
. For example, here is a working sample program:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Get inputs
int input1 = s.nextInt();
int input2 = s.nextInt();
// compare them
if (input1 >= input2) {
System.out.println("Input 1 is greater than or equal to input 2");
} else {
System.out.println("Input 1 is less than input 2");
}
}
}
And this compiles and runs correctly. However, if I change the one comparison line to be:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Get inputs
int input1 = s.nextInt();
int input2 = s.nextInt();
// compare them
if (input1 => input2) { // ------Changed this line------
System.out.println("Input 1 is greater than or equal to input 2");
} else {
System.out.println("Input 1 is less than input 2");
}
}
}
It produces a compiler error here, as it does in many other languages.
This is most certainly an error generated from the language's grammar. But why would the grammar forbid such a comparison? From a programmer's perspective, it should not matter on which side of the equal sign the comparison operator is used.
Because both of the comparisons that have the operator on the left side of the equals, it makes sense that the syntax parsing is done linearly (either left-to-right, or vice versa). But why would the order matter?
boost.asio: Accept IPv4 and IPv6 together
Short and simple question: I am new to boost.asio
and I was wondering if it is possible to create a tcp::acceptor
listening for both, IPv4 and IPv6 connections together. The tutorials on boost's homepage show something like this:
_acceptor = new tcp::acceptor(_ioService, tcp::endpoint(tcp::v4(), 3456));
where the endpoint is always specified with a specific protocol. Is it not possible to listen for IPv4 and IPv6 on the same port at the same time?
Is it possible to set a class object reference as a default parameter in c++ without const?
For example, this:
Class Point{
double x, y;
public:
Point();
bool testequal(const Point& p1, Point& p2 = Point()) const;
}
doesn't work. It gives me an error:
error: could not convert 'Point()' from Point to Point&
This works if I use it as,
bool testequal(const Point& p1, const Point& p2 = Point()) const;
or
bool testequal(const Point& p1, Point p2 = Point()) const;
But instead I want to use object p2
as a reference value whose data can be changed inside the implementation.
Edit:
Here is the complete program. Yes, it's trivial - I'd prefer it if you wouldn't assess the need for this code, but instead comment on whether it's possible to implement.
If not, could you please state why, and tell me what the right way to do it is. Is overloading the only option?
#ifndef __POINT_H__
#define __POINT_H__
Class Point{
double x, y;
public:
Point();
Point(double xx, double yy);
bool testequal(const Point& p1, Point& p2 = Point()) const;
// this declaration fails. alternative is to use const Point& p2 or Point p2.
// but it is vital that the default parameter should store some value in
// it which can be accessed at the function call location without returning it.
}
#include "Point.h"
Point::Point(): x(0), y(0) {}
Point::Point(double xx, double yy): x(xx), y(yy) {}
bool Point::testequal(const Point& p1, Point& p2){
if (this->x == p1.x && this->y == p1.y){
p2.x = this->x;
p2.y = this->y;
return true;
}
else
return false;
}
WIN32 Garbage from Reading COM Port
I am attempting to read a message that was sent on one COM port and received on another. The two ports are connected via two USB to Serial converters. When I attempt to read the transmitted message I get this:
Tx Baud rate: 9600 Rx Baud rate: 9600 Attempting to read... Hello, is ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠á☼ Done...
Press any key to continue . . .
The message should read "Hello, is there anybody out there!?"
we is the code I have written:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <Windows.h>
typedef struct COMDevice {
HANDLE deviceHandle;
DWORD actualBytesReadOrWritten;
int deviceStatus;
std::string message;
DCB controlSettings;
} COMDevice;
int main(int argc, char *argv[]) {
// create new device
COMDevice *comWriter = new COMDevice;
COMDevice *comReader = new COMDevice;
// setup
comWriter->deviceHandle = NULL;
comWriter->actualBytesReadOrWritten = 0;
comWriter->deviceStatus = 0;
comWriter->message = "Hello, is there anybody out there!?";
comReader->deviceHandle = NULL;
comReader->actualBytesReadOrWritten = 0;
comReader->deviceStatus = 0;
comReader->message = "";
// open COM1 for writing
comWriter->deviceHandle = CreateFile(TEXT("COM5"), GENERIC_WRITE, 0, 0, OPEN_ALWAYS, 0, 0);
if(comWriter->deviceHandle == INVALID_HANDLE_VALUE) {
std::cout << "Error occurred opening port for writing...\n";
return (int)GetLastError();
}
// open COM4 for reading
comReader->deviceHandle = CreateFile(TEXT("COM4"), GENERIC_READ, 0, 0, OPEN_ALWAYS, 0, 0);
if(comReader->deviceHandle == INVALID_HANDLE_VALUE) {
std::cout << "Error occurred opening port for reading...\n";
return (int)GetLastError();
}
// check baud rates
if(GetCommState(comWriter->deviceHandle, &comWriter->controlSettings) == 0 ||
GetCommState(comReader->deviceHandle, &comReader->controlSettings) == 0) {
std::cout << "Error occurred getting the comm state...\n";
return (int)GetLastError();
}
else {
std::cout << "Tx Baud rate: " << comWriter->controlSettings.BaudRate << std::endl;
std::cout << "Rx Baud rate: " << comReader->controlSettings.BaudRate << std::endl;
}
// write message to serial port
comWriter->deviceStatus = WriteFile(comWriter->deviceHandle, comWriter->message.c_str(),
comWriter->message.length(), &comWriter->actualBytesReadOrWritten, NULL);
if(comWriter->deviceStatus == FALSE) {
std::cout << "Error occurred writing to port..\n";
return (int)GetLastError();
}
// wait a few
int i = 0, count = 4000;
while(i < count) { i++; }
// read
std::cout << "Attempting to read...\n";
char buffer[1024];
comReader->deviceStatus = ReadFile(comReader->deviceHandle, buffer, 1023,
&comReader->actualBytesReadOrWritten, NULL);
if(comReader->deviceStatus == FALSE) {
return (int)GetLastError();
}
std::cout << buffer << std::endl;
// close handles
(void)FlushFileBuffers(comReader->deviceHandle);
(void)CloseHandle(comWriter->deviceHandle);
(void)CloseHandle(comReader->deviceHandle);
// clean up...
delete comWriter;
delete comReader;
std::cout << "Done...\n";
return 0;
}
I also use the DCB structure to check the baud rates at both ends...they match. Is there something else I may be missing?
Too many libboost_*.lib
I have downloaded boost 1.58.0 (precompiled, x86, VC 12.0) from http://ift.tt/1eGdNQa and installed to C:\local\boost_1_58_0 (I also tried compiled the source code using msvc-12.0 by myself and get the same result.
The problem: I see too many libboost*.lib of the same library, for example
ls -l libboost_math_*
returns:
libboost_math_c99f-vc120-mt-1_58.lib
libboost_math_c99f-vc120-mt-gd-1_58.lib
libboost_math_c99f-vc120-mt-s-1_58.lib
libboost_math_c99f-vc120-mt-sgd-1_58.lib
libboost_math_c99f-vc120-s-1_58.lib
libboost_math_c99f-vc120-sgd-1_58.lib
libboost_math_c99l-vc120-mt-1_58.lib
libboost_math_c99l-vc120-mt-gd-1_58.lib
libboost_math_c99l-vc120-mt-s-1_58.lib
libboost_math_c99l-vc120-mt-sgd-1_58.lib
libboost_math_c99l-vc120-s-1_58.lib
libboost_math_c99l-vc120-sgd-1_58.lib
libboost_math_c99-vc120-mt-1_58.lib
libboost_math_c99-vc120-mt-gd-1_58.lib
libboost_math_c99-vc120-mt-s-1_58.lib
libboost_math_c99-vc120-mt-sgd-1_58.lib
libboost_math_c99-vc120-s-1_58.lib
libboost_math_c99-vc120-sgd-1_58.lib
libboost_math_tr1f-vc120-mt-1_58.lib
libboost_math_tr1f-vc120-mt-gd-1_58.lib
libboost_math_tr1f-vc120-mt-s-1_58.lib
libboost_math_tr1f-vc120-mt-sgd-1_58.lib
libboost_math_tr1f-vc120-s-1_58.lib
libboost_math_tr1f-vc120-sgd-1_58.lib
libboost_math_tr1l-vc120-mt-1_58.lib
libboost_math_tr1l-vc120-mt-gd-1_58.lib
libboost_math_tr1l-vc120-mt-s-1_58.lib
libboost_math_tr1l-vc120-mt-sgd-1_58.lib
libboost_math_tr1l-vc120-s-1_58.lib
libboost_math_tr1l-vc120-sgd-1_58.lib
libboost_math_tr1-vc120-mt-1_58.lib
libboost_math_tr1-vc120-mt-gd-1_58.lib
libboost_math_tr1-vc120-mt-s-1_58.lib
libboost_math_tr1-vc120-mt-sgd-1_58.lib
libboost_math_tr1-vc120-s-1_58.lib
libboost_math_tr1-vc120-sgd-1_58.lib
My questions: 1. Why are there so many lib files for one library? (36 files for libboost_math, 4 libboost_atomic, 6 libboost_iostreams and so on) 2. Why are there no single libboost_math.lib, libboost_atomic, ... files? 3. If I want to use boost_math, which library should I choose?
Storing large data arrays on the stack
I was watching a video that said: on Windows the size of the stack allocated in virtual memory, per process, is 1mb. I wasn't sure if it was correct, but anyway ...
So I was thinking; What happens if you declare a local variable within a function with a size that exceeds 1MB? Let's say and array of 1 byte char's whos size is around 2MB:
char oops[2000000];
There isn't enough space on the stack (if only 1mb is allocated for the stack) to reserve the required memory for the char array. What happens? Would this raise some memory exception?
And if infact an exception would be raised, the way around this would to be to declare the variable on the heap with malloc
(deleting it at the end of the function)?
I would test, except I'm not at a computer.
SDL textures no longer rendering after restructuring code
I have been following the tutorials found here and I decided to deviate a bit before moving on.
I made a basic texture wrapper with which rendering textures worked fine. I then made a GameObject Class that stores a texture, a SDL_rect and, a dimension/location for the SDL_rect. I also tried to implement the standard update/draw loop with function pointers. So after setting all of this up, the textures that previously rendered perfectly fine (which I am testing with again) no longer work under this extra wrapper
From my main.cpp:
//the Texture that we will be applying an image on
Texture TextureOne("PNGTest.png");
Texture TextureTwo("Test2.png");
Texture TextureThree("Test3.png");
GameObject Background(TextureTwo);
GameObject Viewport(TextureOne);
GameObject TextBoxBackground(TextureThree);
first I declare my objects:
Background.Dimensions.x = SCREEN_WIDITH / 2;
Background.Dimensions.y = SCREEN_HEIGHT / 2;
Background.Location.x = SCREEN_WIDITH / 2;
Viewport.Dimensions.x = SCREEN_WIDITH / 2;
Viewport.Dimensions.y = SCREEN_HEIGHT / 2;
TextBoxBackground.Dimensions.x = SCREEN_WIDITH;
TextBoxBackground.Dimensions.y = SCREEN_HEIGHT / 2;
TextBoxBackground.Location.y = SCREEN_HEIGHT / 2;
//clear screen
SDL_RenderClear(Renderer);
//for all objects in the object list
for(unsigned i = 0; i < ObjectList.size(); i++)
{
//update the object
ObjectList[i]->Update(*ObjectList[i]);
//then draw the updated object
ObjectList[i]->Draw(*ObjectList[i]);
}
//upadte screen
SDL_RenderPresent(Renderer);
Then I set up the various dimensions and locations and finally call the objects update and draw
Here is the game object constructor being used:
GameObject::GameObject(Texture TargetTexture)
{
Dimensions.x = 1;
Dimensions.y = 1;
ObjectStorage.x = Location.x;
ObjectStorage.y = Location.y;
ObjectStorage.w = Dimensions.x;
ObjectStorage.h = Dimensions.y;
Update = DefaultUpdate;
Draw = DefaultDraw;
ObjectTexture = TargetTexture;
ObjectList.push_back(this);
}
here is the update function:
float DefaultUpdate(GameObject& Self)
{
float CurrentTime = SDL_GetTicks();
Self.ObjectStorage.w = Self.Dimensions.x;
Self.ObjectStorage.h = Self.Dimensions.y;
Self.ObjectStorage.x = Self.Location.x;
Self.ObjectStorage.y = Self.Location.y;
if(CurrentTime > LastTime)
{
DeltaTime = (CurrentTime - LastTime) / 1000;
LastTime = CurrentTime;
}
return DeltaTime;
}
and lastly the draw function:
void DefaultDraw(GameObject& Self)
{
SDL_RenderSetViewport(Renderer, &Self.ObjectStorage);
SDL_RenderCopy(Renderer, Self.ObjectTexture.GetCurrentTexture(),
NULL, NULL);
}
I have a sneaking suspicion that the issue is in the draw function, in that the SDL_Viewport/SDL_RenderCopy lose meaning after going out of scope, or that I should be updating the renderer with in the draw function, but I cannot seem to get those to work, are there any suggestions or should I just give up on this architecture entirely?
I dont understand how this array of pointers is working
I dont understand why I have to increment de variable contador
before I do this
palabras[contador]=auxiliar;
palabras
is an array of char
pointers that I declared like this:
char *palabras[13];
Which I think is the proper way to do it. This array of pointers would store words that have a max size of 12
. I created contador
as a global variable and initialized to 0
. But if I don't put contador++;
before using palabras[contador]=auxiliar
the program will crash, for some reason I can't write in the palabras[0]
array.
void leerArchivo()
{
ifstream archivo("palabras.txt", ios::in);
char linea[13];
char *auxiliar;
if(archivo.fail())
{
cerr<<"Error al abrir el archivo palabras.txt"<<endl;
getch();
}else
{
while(!archivo.eof())
{
archivo.getline(linea, sizeof(linea));
contador++; //???
auxiliar=linea; //copy the first address of the array linea
palabras[contador]=auxiliar;
cout<<" "<<palabraSize(palabras[contador])<<" "; //????
cout<<palabras[contador]<<endl;
}
archivo.close();
}
}
Parsing hex values with Boost Spirit
I have been playing around with parsing with Boost Spirit and was wondering if anyone could help me get this to work. I have a simple parser that takes a file containing a pair of entries on each line. Something similar to the following:
Foo 04B
Bar 1CE
Bam 456
My code below currently parses this out and places each pair into a std::map and it seems to work correctly. What I really want to do is parse out the second string on each line and convert it to an integer. I have looked at int_parser and how you can specify the base but have been unable to get a similar setup to compile.
namespace qi = boost::spirit::qi;
std::map results;
void insert(std::pair p) {
results[p.first] = p.second;
}
template
bool parse_numbers(Iterator first, Iterator last) {
using qi::char_;
using qi::parse;
qi::rule<Iterator, std::pair<std::string, std::string>()> assignment;
assignment = +(~char_(' ')) >> +(char_);
bool r = parse(
first,
last,
assignment[&insert]);
if (first != last)
return false;
return r;
}
int main(int argc, char* argv[]) { std::ifstream ifs; std::string str; ifs.open (argv[1], std::ifstream::in);
while (getline(ifs, str)) {
if (!parse_numbers(str.begin(), str.end())) {
std::cout << "Parsing failed\n";
}
}
return 0;
}
What I would really like if to parse it out directly as a std::pair<std::string, int
>. Any help is appreciated.
wstring to wchar_t conversion
I am using Namedpipes communication(C++) to transfer data between two processes. For the sake of comfort, I am using wstring to transfer the data and everything is fine at the transfer end. I am not able to receive the total data on the receiving end. The following is the transfer end code.
wstringstream send_data;
send_data << "10" << " " << "20" << " " << "30" << " " << "40" << " " << "50" << " " << "60" << "\0" ;
DWORD numBytesWritten = 0;
result = WriteFile(
pipe, // handle to our outbound pipe
send_data.str().c_str(), // data to send
send_data.str().size(), // length of data to send (bytes)
&numBytesWritten, // will store actual amount of data sent
NULL // not using overlapped IO
);
The following is the receiving end code.
wchar_t buffer[128];
DWORD numBytesRead = 0;
BOOL result = ReadFile(
pipe,
buffer, // the data from the pipe will be put here
127 * sizeof(wchar_t), // number of bytes allocated
&numBytesRead, // this will store number of bytes actually read
NULL // not using overlapped IO
);
if (result) {
buffer[numBytesRead / sizeof(wchar_t)] = '\0'; // null terminate the string
wcout << "Number of bytes read: " << numBytesRead << endl;
wcout << "Message: " << buffer << endl;
}
The result in buffer contains only 10 20 30 Can someone please explain me why the data is truncated.
VTK: Rotate actor programmatically while vtkRenderWindowInteractor is active
I'm trying to rotate a vtkActor
using vtkActor::RotateZ
and then calling vtkRenderWindow::Render
. It works fine (it rotates the actor) but I can't move, resize, or even focus the window.
I suspected this was caused due to something not catching operating system events, so I added a vtkRenderWindowInteractor
to the mix. Now I can move, resize and focus the window, but the actor is not rotating anymore.
I've isolated the code in the snippet below, comment line 43 to see both effects:
renderWindowInteractor->Start();
I'm compiling VTK 6.2 with mingw-w64 (GCC 4.9.1), running in Windows 8.1. I've uploaded the code in this repo with a small CMake setup so you can test it easily.
Thanks for your help!
constexpr float planeWidth = 200.0f;
constexpr float planeHeight = 100.0f;
int main()
{
auto renderer = vtkRenderer::New();
// Create render window
auto renWin = vtkRenderWindow::New();
renWin->AddRenderer(renderer);
renWin->SetSize(600,600);
// Create a plane
auto texturedPlane = vtkActor::New();
auto plane = vtkPlaneSource::New();
plane->SetOrigin(0, planeHeight, 0);
plane->SetPoint1(planeWidth, planeHeight, 0);
plane->SetPoint2(0, 0, 0);
auto planeMapper = vtkPolyDataMapper::New();
planeMapper->SetInputConnection(plane->GetOutputPort());
texturedPlane->SetMapper(planeMapper);
texturedPlane->SetOrigin(planeWidth / 2, planeHeight, 0);
renderer->AddActor(texturedPlane);
renderer->ResetCamera();
// Create a RenderWindowInteractor
auto renderWindowInteractor = vtkRenderWindowInteractor::New();
renderWindowInteractor->SetRenderWindow(renWin);
renderWindowInteractor->Start(); // <-- Comment this line!
// Render
float rot = 0.0f;
while(true)
{
texturedPlane->SetOrientation(0,0,0);
texturedPlane->RotateZ(rot++);
renWin->Render();
}
}
inserting elements with duplicate keys gives same result std::map and std::multimap
I am writing a program that implements a uni-directional graph using std::map or std::multimap. I have to search for the key and then copy the vector values corresponding to that key into a new location in the map. Specifically, I am copying elements corresponding to 'find_key' into location pointed by 'mykey'. I find that both map and multimap give me the same result (no duplicate keys). How can I fix this using multimap? mymap is a map, mymultimap is a multimap. mymap[find_key] contains the vector values that I am trying to copy. I expected to be able to copy them (while retaining the original values in the multimap) using multimap. But it does not work. This is what I have so far:
for (vector<string>::const_iterator itr =mymap.find(mykey)->second.begin(); itr!=mymap.find(mykey)->second.end();++itr){
string find_key;
stringstream sso(*itr);
if (! (sso >> find_key))
{
cout<< "ERROR failed to convert value"<<endl;
}
auto& mapit= mymap.find(find_key);
if (mapit == mymap.end()) {
std::cout << "key not found" << std::endl;
} else {
mymap.insert(pair<string, vector<string>>(mykey,mymap[find_key]));
mymultimap.insert(pair<string, vector<string>>(mykey,mymap [find_key]));
}}}
native C++ use C# DLL via CLR wrapper
Trying to make a minimal code sample of calling a C# DLL from Native C++. The most straightforward method seems to be via CLR DLL wrapper.
C# DLL file (want to call this from native C++):
namespace CSharpDLL
{
public static class CSharpFunctions
{
static bool myBool = false;
public static bool GetBool() { return myBool; }
public static void SetBool(bool b) { myBool = b; }
}
}
CLR DLL header file (wraps the C#):
#pragma once
using namespace System;
namespace ClrDLL
{
public ref class ClrFunctions
{
public:
bool GetBool();
void SetBool(bool b);
};
}
CLR DLL class file (wraps the C#):
#include "stdafx.h"
#include "ClrDLL.h"
#using <CSharpDLL.dll> // C# DLL
using namespace CSharpDLL; // C# DLL namespace
using namespace ClrDLL;
using namespace System;
bool ClrFunctions::GetBool()
{
return CSharpFunctions::GetBool();
}
void ClrFunctions::SetBool(bool b)
{
CSharpFunctions::SetBool(b);
}
And finally a Win32 Console Project test file (attempts to call C# from native C++):
#include "stdafx.h"
#include <iostream>
#include "..\ClrDll\ClrDll.h"
using namespace std;
using namespace ClrDLL;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "This program demonstrates using a C# DLL in C++" << endl;
cout << endl;
// instance of clr dll class
ClrFunctions clrFunctions;
// get bool example
cout << "Get bool from C# DLL: ";
bool b = clrFunctions.GetBool();
cout << boolalpha << b << endl;
// done!
cout << "Hit any key to exit!";
getchar();
return 0;
}
Having two specific problems:
- The CLR Wrapper compiles but does not output a DLL or LIB file
- The test program fails to compile because the DLL Wrapper Header has "using namespace System;" and that requires CLR flag (which I cannot use)
Placing a "!" before a condition statement
For example:
while (! ( (planet == "Mercury") || (planet == "Pluto") ) )
{
<body>;
}
Would the above be the same as saying:
while ( (planet != "Mercury") || (planet != "Pluto") )
{
<body>;
}
If not, what would it mean to place the NOT operation before the condition statement as shown in the first block of code?
C++ immutable string container
Is there amy standard immutable string container that encapsulate char* and nothing else? Usage will be for storing strings into vectors and using char arrays as objects.
The reason I do not want to use std::string is their overhead.
Change variable type
I'm new in C++ and I'm from Ruby where I can declare a variable and set what I want, for example a class
@variable=MyClass.new
Can do something like that in C++? I have two classes and a global variable declared with the first one set and I want to modify it and set it to the second class, in Ruby I can do something like
@variable=MyClass2.new
My c++ code is like this:
TestClass1 *scene = NULL;
*scene=TestClass1();
And now I try to set it to the second class like I do in Ruby: TestClass2 *newScene=NULL
*newScene=TestClass2()
*scene=*newScene();
error: cannot convert 'TestClass1*' to 'TestClass2*' in assignment
I've search here a lot and in Google but I don't find anything, can someone help me? Thanks you so much
Having an issue reading from a text file for a Population Bar Chart program
From instructor: "Complete programming problem #18 on page 296 of the textbook. The text file People.txt to use for your program is attached to this assignment. I will use this same text file to test your program after it is submitted so do not make any changes to the text file contents. Submit the .cpp file for your program to this assignment."
Book: "Write a program that produces a bar chart showing the population growth of Prairieville, a small town in the Midwest, at 20 year intervals during the past 100 years. The program should read in the population figures (rounded to the nearest 1,000 people) for 1900, 1920, 1940, 1960, 1980, and 2000 from a file. For each year it should display a date and a bar consisting of one asterisk for each 1,000 people. The data can be found in the People.txt file.
People.txt: 2000 4000 5000 9000 14000 18000 18000
When written as below, with error checking integrated within my if statements, it doesn't give me any values, but instead immediately skips to the else statement. I have output that now reads from the file but lists 2000 then 1900 - 2000 with the asterisk population values not properly reflecting the population values within the txt file.
#include <iostream> //for cout statement
#include <fstream> //for file access
using namespace std;
int main()
{
int year, population;
//defines filestream object and opens file
ifstream inFile;
inFile.open("People.txt");
//Standard output statements providing framework for chart
cout << "Population Growth of Prairieville\n";
cout << "\n[Each asterisk (*) represents 1,000 people]\n";
cout << "\nYear \t\t Population\n";
cout << "___________________________________________\n";
//if file opens process
if (inFile)
{
//Reads to "population" variable
inFile >> population;
cout << population << endl;
for (year = 1900; year <= 2000; year += 20)
{
cout << year;
inFile >> population;
for (int star = 1; star < population; star += 1000)
{
cout << "*";
}
cout << "\n" << endl;
}
//close file
inFile.close();
}
else
{
//Display error message
cout << "Error opening file. Shutting down. \n";
}
system("PAUSE");
return 0;
}
I am trying to sequentially access the information within the text file so that it reads from the text file for all values. I don't know if it has anything to do with the extra 18000 the professor added in the text file but I feel that shouldn't have anything to do with that if I'm giving the program exactly what to look for in my for loop. I have seen this problem elsewhere but everyone seems to give very complicated solutions to what seems to me like it should be a simple answer.
Please note: My apologies for not being able to include a screenshot of my ouput in the console. I also do not intend to keep system "PAUSE"; as I know it's considered "sloppy", but I need it as of right now for eval purposes.
Thank you!!!
Whole-word matching with regex.h
I want a C++ regex that matches "bananas" or "pajamas" but not "bananas2" or "bananaspajamas" or "banana" or basically anything besides those exact two words. So I did this:
#include <regex.h>
#include <stdio.h>
int main()
{
regex_t rexp;
int rv = regcomp(&rexp, "\\bbananas\\b|\\bpajamas\\b", REG_EXTENDED | REG_NOSUB);
if (rv != 0) {
printf("Abandon hope, all ye who enter here\n");
}
regmatch_t match;
int diditmatch = regexec(&rexp, "bananas", 1, &match, 0);
printf("%d %d\n", diditmatch, REG_NOMATCH);
}
and it printed 1 1
as if there wasn't a match. What happened? I also tried \bbananas\b|\bpajamas\b
for my regex and that failed too.
I asked Whole-word matching regex in C++ about std::regex, but std::regex is awful and slow so I'm trying regex.h.
How to include enums in another enum?
I have multiple related enums like this:
enum solidmaterial { MARBLE, RUBY, ICE, … };
enum organicmaterial { BANANA, BREAD, BONE, … };
enum gasmaterial { AIR, SMOKE, GHOST, … };
…
I can define a function to take a solidmaterial
, e.g. void Foo(solidmaterial M);
, and I can also define a function to take an int
and pass any one of these enums to it.
But can I somehow define a function that could take any one of these enums but not anything else? Maybe a parent enum material
that includes all these more specific enums. Is this possible?
Turbo C++ system function running an executable
How to run any exe file from turbo c++? I know that I should stop using turbo c++ and move one to Dev or Code::Blocks, but my school doesn't agree so I gotta wing it.
I just want to know how to run a file with or without the system() function. Any kind of advice is welcome
C++ (VC) Text output breaks lines with 0d 0d 0a instead of 0d 0a - how to fix?
With the help of the experts here, I managed to put together a program that writes the contents of the Windows clipboard to a text file in a specified code page. It now seems to work perfectly, except that the line breaks in the text file are three bytes - 0d 0d 0a - instead of 0d 0a - and this causes problems (additional lines) when I import the text into a word processor.
Is there an easy way to replace 0d 0d 0a with 0d 0a in the text stream, or is there something I should be doing differently in my code? I haven't found anything like this elsewhere. Here is the code:
#include <stdafx.h>
#include <windows.h>
#include <iostream>
#include <fstream>
#include <codecvt> // for wstring_convert
#include <locale> // for codecvt_byname
using namespace std;
void BailOut(char *msg)
{
fprintf(stderr, "Exiting: %s\n", msg);
exit(1);
}
string ExePath()
{
char buffer[MAX_PATH];
GetModuleFileNameA(NULL, buffer, MAX_PATH);
string::size_type pos = string(buffer).find_last_of("\\/");
return string(buffer).substr(0, pos);
}
// get output code page from command-line argument; use 1252 by default
int main(int argc, char *argv[])
{
string codepage = ".1252";
if (argc > 1) {
string cpnum = argv[1];
codepage = "." + cpnum;
}
// HANDLE clip;
string clip_text = "";
// exit if clipboard not available
if (!OpenClipboard(NULL))
{ BailOut("Can't open clipboard"); }
if (IsClipboardFormatAvailable(CF_TEXT)) {
HGLOBAL hglb = GetClipboardData(CF_TEXT);
if (hglb != NULL) {
LPSTR lptstr = (LPSTR)GlobalLock(hglb);
if (lptstr != NULL) {
// read the contents of lptstr which just a pointer to the string:
clip_text = (char *)hglb;
// release the lock after you're done:
GlobalUnlock(hglb);
}
}
}
CloseClipboard();
// create conversion routines
typedef std::codecvt_byname<wchar_t, char, std::mbstate_t> codecvt;
std::wstring_convert<codecvt> cp1252(new codecvt(".1252"));
std::wstring_convert<codecvt> outpage(new codecvt(codepage));
std::string OutFile = ExePath() + "\\#clip.txt"; // output file name
ofstream OutStream; // open an output stream
OutStream.open(OutFile, ios::out | ios::trunc);
// make sure file is successfully opened
if (!OutStream) {
cout << "Error opening file " << OutFile << " for writing.\n";
return 1;
}
// convert to DOS/Win codepage number in "outpage"
OutStream << outpage.to_bytes(cp1252.from_bytes(clip_text)).c_str();
//OutStream << endl;
OutStream.close(); // close output stream
return 0;
}
Making a debugging helper for Qt Creator for the QUuid class
I'm using the QUuid
class in my project and for testing and debugging purposes it would be very nice to see the QUuid objects in human readable form instead of their low-level form.
For some reason, the people at Qt have not included a dump method for this type so I attempted to create one on my own, following this documentation and this guide.
I'm not familiar with Python so unfortunately, I could not get something running. Could someone help me create such a function that does nothing more than display the output of QUuid::toString() in the value column of Qt Creator?
Effect of std::memory_order_acq_rel on non-atomic variable read in other thread
I think I mostly understand the semantics of the various memory_order
flags in the C++ atomic library.
However, I'm confused about the following situation:
Suppose we have two threads - Thread A, which is a "main execution" thread, and Thread B, which is some arbitrary thread that is part of a thread pool where tasks can be scheduled and run.
If I perform a "read-write-update" atomic operation using std::memory_order_acq_rel
, then perform a non-atomic write on a boolean variable, is the non-atomic write immediately visible to other threads? I would think the answer is no, unless the other threads also access the atomic variable that did the "read-write-update" operation.
So, for example, given a global std::atomic_flag
variable X
, a global bool
value B, and a thread pool object THREADPOOL
that has a member function dispatch
, which will execute arbitrary function handlers in another thread:
if (!X.test_and_set(std::memory_order_acq_rel)
{
if (SOME_CONDITION) B = true;
THREADPOOL.dispatch([]() {
// This executes in Thread B
if (B) { /* do something */ } // are we guaranteed to see changes to B?
});
}
So in this example, the code inside the lambda function will be executed in a different thread. Is that thread necessarily going to see the (non-atomic) update to B
made in the first thread? Note that the second thread does not access the atomic_flag, so my understanding is that changes to B
will not necessarily be seen in the second thread.
Is my understanding correct here? And if so, would using std::memory_order_seq_cst
change that?
linear distribution in c++ using rand()
I am writing a function that generates n random points (x, y) such that xmin < x < xmax and ymin < y < ymax. This is easy to do with uniform distribution using rand().
int points[n][2];
for (int i = 0; i < n; i++) {
points[i][0] = rand() % (xmax - xmin) + xmin;
points[i][1] = rand() % (ymax - ymin) + ymin;
}
However, I would like to control the distribution so that the probability of each point having a given x or y value is px = (px2 * (x - xmin) + px1 * (xmax - x)) / (xmax - xmin)
or py = (py2 * (y - ymin) + py1 * (ymax - y)) / (xmax - xmin)
, respectively. In other words, a linear distribution across the rectangle in each dimension.
I can fake this by partitioning the rectangle into sufficiently small discrete rectangles and using the algorithm above for each one, with n proportional to the average probability across that smaller rectangle. However, I would prefer to apply a continuous distribution across the entire rectangle. Can this be done, either using rand() or with another approach?
trouble with C++ program [on hold]
hi guys i have this assignment, and am totally confused am new to c++ and the book doesnt explain much ive written codes for part a,b but something felt off with the number and on part c i just have no idea what to do, can you guys help me?
i need the simplest codes for it. the program is :
reads integers from a file called "datafile2.txt" ,it has 20 integers in it and need to output to a file "answers.txt.
A.read the file and write all integers to the output file in one line
B.reread the file and compute the average of all integers
C.reread the file and compute the average of the first 12 integers
D.reread the file and compute the sum of every third integers
E.reread the file and determine the range of the integers in the file.
G.read the file and find the integers that is closest to 200
G.reared the file and compute the average of all integers on the first two line in the input file.
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
ifstream infile;
ofstream outfile;
int main()
{
int num;
ifstream infile;
ofstream outfile;
outfile.open("Answer.txt");
infile.open("DataFile2.txt");
infile >> num;
while (infile)
{
outfile << num << " ";
infile >> num;
}
infile.close();
infile.open("DataFile2.txt");
int sum = 0;
double avg;
while (infile)
{
infile >> num;
sum += num;
}
infile.close();
avg = sum / 20.00;
outfile << fixed << setprecision(3) << endl << "The average of all the numbers is : " << avg;
infile.open("DataFile2.txt");
int count = 1;
sum = 0;
while (count <= 12)
{
sum += num;
count++;
}
infile.close();
avg = sum / 12.00;
outfile << fixed << setprecision(3) << endl << "The average of the first 12 numbers is : " << avg;
}
Pushing element to dynamically allocated pointer array int C++
[EDIT 1] I'll preface by saying that for this project, I am required to "Create a container class" where I can push, pop, and retrieve elements from a list. I am supposed to use pointers, and must write the functions for pushing, popping, etc. [/EDIT 1]
I am having difficulty pushing an element to a dynamically allocated pointer array. I am able to initially create an array just fine. You can see from my comments my thought process for how I think I should be able to add to the array:
1) create new array with room for the one new element;
2) add the new element to index 0;
3) copy the old array into the rest of the new array;
4) delete old array;
5) set the new array as the value of the pointer
I have the following three files:
IntegerList.h:
/**
*IntegerList.h
*/
#ifndef IntegerList_H
#define IntegerList_H
class IntegerList
{
private:
int * pArray;
int length;
public:
IntegerList(); // default constructor
void createArray(int howlong);
int getValue(int index);
void deleteArray();
void pushFront(int element);
};
#endif
IntegerList.cpp:
/**
* IntegerList.cpp
*/
#include "IntegerList.h"
#include <iostream>
using namespace std;
// IntegerList constructor:
IntegerList::IntegerList()
{
pArray = 0;
length = 0;
}
// creates an array of length howlong (determined by main.cpp); sets the values
// to equal ten times the index number. For example, if an array of size 4 is
// to be created, then an array with the following values will be created by
// this method: 0, 10, 20, 30. Sets length equal to howlong.
void IntegerList::createArray(int howlong)
{
length = howlong;
pArray = new int[length];
for (int i = 0; i < length; i ++)
pArray[i] = (i*10);
}
int IntegerList::getValue(int index)
{
return pArray[index];
}
void IntegerList::deleteArray()
{
delete[] pArray;
}
// places element at front of array
void IntegerList::pushFront(int element)
{
// create new array with room for the one new element
int newArray[length+1]; // nope
// start by adding the new element
newArray[0] = element;
// copy the old array, put it into the new array starting at index 1 (since
// index 0 is the new element)
for(int i = 0; i < length; i ++)
{
newArray[i+1] = pArray[i];
}
// delete old array
deleteArray();
// set pArray equal to the new array;
pArray = newArray;
// update the value of length
length += 1;
}
And my main file, main.cpp:
#include "IntegerList.h"
#include <iostream>
using namespace std;
int main()
{
// create object
IntegerList myArray;
// create array of length 5
myArray.createArray(5);
// print array
for (int i = 0; i < 5; i ++)
cout << "Element " << i << ". " << myArray.getValue(i) << endl;
// everything works ok so far
// push the number 99 to front
myArray.pushFront(99);
// print array
for (int i = 0; i < 6; i ++)
cout << "Element " << i << ". " << myArray.getValue(i) << endl;
myArray.deleteArray();
}
The first printArray() shows that everything is going as planned. However, after I try to push 99 to the front, things get screwed up :(
Here is the output I'm getting:
Element 0. 0
Element 1. 10
Element 2. 20
Element 3. 30
Element 4. 40
Element 0. 99
Element 1. 0
Element 2. 2130567168
Element 3. 4486648
Element 4. 2686508
Element 5. 4201772
Note that in the second printout, the first two elements appear to have the value that I intended for them to have.
Any suggestions?
More heaps found in each dump, where do they come from?
I am investigating a native memory leak through WinDbg.
With consecutive dumps, !heap -s
returns more heaps every dump. Number of heaps returned in the first dump: 1170, second dump: 1208.
There are three sizes of heaps that are returning a lot:
0:000> !heap -stat -h 2ba60000
heap @ 2ba60000
group-by: TOTSIZE max-display: 20
size #blocks total ( %) (percent of total busy bytes)
1ffa 1 - 1ffa (35.44)
1000 1 - 1000 (17.73)
a52 1 - a52 (11.44)
82a 1 - 82a (9.05)
714 1 - 714 (7.84)
64c 1 - 64c (6.98)
Most blocks refer to the same callstack:
777a5887 ntdll!RtlAllocateHeap
73f9f1de sqlsrv32!SQLAllocateMemory
73fc0370 sqlsrv32!SQLAllocConnect
73fc025d sqlsrv32!SQLAllocHandle
74c6a146 odbc32!GetInfoForConnection
74c6969d odbc32!SQLInternalDriverConnectW
74c6bc24 odbc32!SQLDriverConnectW
74c63141 odbc32!SQLDriverConnect
When will a new heap will be created, and how you would dive deeper into this to find the root cause?
AURemoteIO EXC_BAD_ACCESS
In my iOS app I use open-source code (a mix of C++ and Objective-C) in a .mm file to find the max frequency of sound recorded by the mic. However, I'm getting a bad access error about 10% of the time and have no idea how to deal with it, as I'm using a language I'm not familiar with.
The NSLog output is as follows:
ERROR: [0x19932f310] >aurioc> 806: failed: -50 (enable 3, outf< 2 ch, 44100 Hz, Int8.24, non-inter> inf< 2 ch, 44100 Hz, Int8.24, non-inter>)
2015-06-29 12:31:15.396 XXX[547:138175] error = couldn't setup remote i/o unit
Here is where the error occurs:
AudioToolbox`AUInputElement::PullInput:
0x182a821ec <+0>: stp x24, x23, [sp, #-64]!
0x182a821f0 <+4>: stp x22, x21, [sp, #16]
0x182a821f4 <+8>: stp x20, x19, [sp, #32]
0x182a821f8 <+12>: stp x29, x30, [sp, #48]
0x182a821fc <+16>: add x29, sp, #48
0x182a82200 <+20>: mov x20, x4
0x182a82204 <+24>: mov x23, x3
0x182a82208 <+28>: mov x21, x2
0x182a8220c <+32>: mov x22, x1
0x182a82210 <+36>: mov x19, x0
0x182a82214 <+40>: ldr w8, [x19, #164]
0x182a82218 <+44>: cbnz w8, 0x182a82224 ; <+56>
0x182a8221c <+48>: movn w0, #0x2a7b
0x182a82220 <+52>: b 0x182a822ac ; <+192>
0x182a82224 <+56>: cmp w8, #1
0x182a82228 <+60>: b.eq 0x182a82248 ; <+92>
0x182a8222c <+64>: ldrb w8, [x19, #160]
0x182a82230 <+68>: cbz w8, 0x182a82248 ; <+92>
0x182a82234 <+72>: add x0, x19, #120
0x182a82238 <+76>: add x1, x19, #80
0x182a8223c <+80>: mov x2, x20
0x182a82240 <+84>: bl 0x182a810e4 ; AUBufferList::PrepareBuffer(CAStreamBasicDescription const&, unsigned int)
0x182a82244 <+88>: b 0x182a82258 ; <+108>
0x182a82248 <+92>: add x0, x19, #120
0x182a8224c <+96>: add x1, x19, #80
0x182a82250 <+100>: mov x2, x20
0x182a82254 <+104>: bl 0x182a811e4 ; AUBufferList::PrepareNullBuffer(CAStreamBasicDescription const&, unsigned int)
0x182a82258 <+108>: mov x5, x0
0x182a8225c <+112>: ldr w8, [x19, #164]
0x182a82260 <+116>: cmp w8, #1
0x182a82264 <+120>: b.ne 0x182a82284 ; <+152>
0x182a82268 <+124>: ldr x0, [x19, #184]
0x182a8226c <+128>: ldr w3, [x19, #192]
0x182a82270 <+132>: mov x1, x22
0x182a82274 <+136>: mov x2, x21
0x182a82278 <+140>: mov x4, x20
0x182a8227c <+144>: bl 0x18298f0ec ; AudioUnitRender
0x182a82280 <+148>: b 0x182a8229c ; <+176>
0x182a82284 <+152>: ldp x8, x0, [x19, #168]
0x182a82288 <+156>: mov x1, x22
0x182a8228c <+160>: mov x2, x21
0x182a82290 <+164>: mov x3, x23
0x182a82294 <+168>: mov x4, x20
0x182a82298 <+172>: blr x8
0x182a8229c <+176>: ldr w8, [x19, #164] // EXC_BAD_ACCESS HERE
0x182a822a0 <+180>: cmp w8, #0
0x182a822a4 <+184>: movn w8, #0x2a7b
0x182a822a8 <+188>: csel w0, w8, w0, eq
0x182a822ac <+192>: ldp x29, x30, [sp, #48]
0x182a822b0 <+196>: ldp x20, x19, [sp, #32]
0x182a822b4 <+200>: ldp x22, x21, [sp, #16]
0x182a822b8 <+204>: ldp x24, x23, [sp], #64
0x182a822bc <+208>: ret
The thing is, this error does not happen in the demo app using the open-source code, so I figure it must be something I added. The only code I added was to the view controller, the code between the three asterisks (***) in here:
#import "LightsViewController.h"
#import "mo_audio.h" //stuff that helps set up low-level audio
#import "FFTHelper.h"
#define SAMPLE_RATE 44100 //22050 //44100
#define FRAMESIZE 512
#define NUMCHANNELS 2
#define kOutputBus 0
#define kInputBus 1
/// Nyquist Maximum Frequency
const Float32 NyquistMaxFreq = SAMPLE_RATE/2.0;
/// caculates HZ value for specified index from a FFT bins vector
Float32 frequencyHerzValue(long frequencyIndex, long fftVectorSize, Float32 nyquistFrequency ) {
return ((Float32)frequencyIndex/(Float32)fftVectorSize) * nyquistFrequency;
}
// The Main FFT Helper
FFTHelperRef *fftConverter = NULL;
//Accumulator Buffer=====================
// CHANGE "SAMPLE RATE" (?) HERE, I.E., HOW OFTEN THE METHOD IS RUN THAT SAMPLES THE MAX HZ
const UInt32 accumulatorDataLenght = 2048; //16384; //32768; 65536; 131072;
UInt32 accumulatorFillIndex = 0;
Float32 *dataAccumulator = nil;
static void initializeAccumulator() {
dataAccumulator = (Float32*) malloc(sizeof(Float32)*accumulatorDataLenght);
accumulatorFillIndex = 0;
}
static void destroyAccumulator() {
if (dataAccumulator!=NULL) {
free(dataAccumulator);
dataAccumulator = NULL;
}
accumulatorFillIndex = 0;
}
static BOOL accumulateFrames(Float32 *frames, UInt32 lenght) { //returned YES if full, NO otherwise.
// float zero = 0.0;
// vDSP_vsmul(frames, 1, &zero, frames, 1, lenght);
if (accumulatorFillIndex>=accumulatorDataLenght) { return YES; } else {
memmove(dataAccumulator+accumulatorFillIndex, frames, sizeof(Float32)*lenght);
accumulatorFillIndex = accumulatorFillIndex+lenght;
if (accumulatorFillIndex>=accumulatorDataLenght) { return YES; }
}
return NO;
}
static void emptyAccumulator() {
accumulatorFillIndex = 0;
memset(dataAccumulator, 0, sizeof(Float32)*accumulatorDataLenght);
}
//=======================================
//==========================Window Buffer
const UInt32 windowLength = accumulatorDataLenght;
Float32 *windowBuffer= NULL;
//=======================================
/// max value from vector with value index (using Accelerate Framework)
static Float32 vectorMaxValueACC32_index(Float32 *vector, unsigned long size, long step, unsigned long *outIndex) {
Float32 maxVal;
vDSP_maxvi(vector, step, &maxVal, outIndex, size);
return maxVal;
}
///returns HZ of the strongest frequency.
static Float32 strongestFrequencyHZ(Float32 *buffer, FFTHelperRef *fftHelper, UInt32 frameSize, Float32 *freqValue) {
Float32 *fftData = computeFFT(fftHelper, buffer, frameSize);
fftData[0] = 0.0;
unsigned long length = frameSize/2.0;
Float32 max = 0;
unsigned long maxIndex = 0;
max = vectorMaxValueACC32_index(fftData, length, 1, &maxIndex);
if (freqValue!=NULL) { *freqValue = max; }
Float32 HZ = frequencyHerzValue(maxIndex, length, NyquistMaxFreq);
return HZ;
}
__weak UILabel *labelToUpdate = nil;
int value;
#pragma mark MAIN CALLBACK
void AudioCallback( Float32 * buffer, UInt32 frameSize, void * userData )
{
//take only data from 1 channel
Float32 zero = 0.0;
vDSP_vsadd(buffer, 2, &zero, buffer, 1, frameSize*NUMCHANNELS);
if (accumulateFrames(buffer, frameSize)==YES) { //if full
//windowing the time domain data before FFT (using Blackman Window)
if (windowBuffer==NULL) { windowBuffer = (Float32*) malloc(sizeof(Float32)*windowLength); }
vDSP_blkman_window(windowBuffer, windowLength, 0);
vDSP_vmul(dataAccumulator, 1, windowBuffer, 1, dataAccumulator, 1, accumulatorDataLenght);
//=========================================
Float32 maxHZValue = 0;
Float32 maxHZ = strongestFrequencyHZ(dataAccumulator, fftConverter, accumulatorDataLenght, &maxHZValue);
//NSLog(@" max HZ = %0.3f ", maxHZ);
dispatch_async(dispatch_get_main_queue(), ^{ //update UI only on main thread
***//labelToUpdate.text = [NSString stringWithFormat:@"%0.3f HZ",maxHZ];
if (maxHZ > 18950.0f) {
if (maxHZ < 19050.0f) {
value = 0;
} else if (maxHZ < 19150.0f) {
value = 1;
} else if (maxHZ < 19450.0f) {
value = 2;
}
}
});***
emptyAccumulator(); //empty the accumulator when finished
}
memset(buffer, 0, sizeof(Float32)*frameSize*NUMCHANNELS);
}
@interface LightsViewController ()
@property int hzValue;
@property NSTimer *timerWhiteAndOrage;
@property NSTimer *timerRedAndBlue;
@property NSTimer *methodTimer;
@end
@implementation LightsViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
//labelToUpdate = HZValueLabel;
_hzValue = value;
//initialize stuff
fftConverter = FFTHelperCreate(accumulatorDataLenght);
initializeAccumulator();
[self initMomuAudio];
NSTimer *timer = [NSTimer
scheduledTimerWithTimeInterval:(NSTimeInterval)(0.05f)
target:self
selector:@selector(didReceiveNewMaxHz)
userInfo:nil
repeats:TRUE];
timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:(NSTimeInterval) 0.1f];
_methodTimer = timer;
}
-(void) initMomuAudio {
bool result = false;
result = MoAudio::init( SAMPLE_RATE, FRAMESIZE, NUMCHANNELS, false);
if (!result) { NSLog(@" MoAudio init ERROR"); }
result = MoAudio::start( AudioCallback, NULL );
if (!result) { NSLog(@" MoAudio start ERROR"); }
}
-(void) dealloc {
destroyAccumulator();
FFTHelperRelease(fftConverter);
}
@end
How to compile C code that #includes C++ code?
I have to compile generated C code that #include
s C++ headers and it get it to work on Linux, OS X and Windows. I put the #include
s myself to be able to interact with C++ code from it.
The C code however is such that a strict compiler would catch errors that could be treated as warnings. I want to pass these off as warnings as most of this is generated code which I don't have control over.
Here are my attempts to compile it (I use CMake
, btw):
(I use these flags: -Wno-write-strings -Wno-error -fpermissive
)
- Treat the entire project as C++ code: works on Linux (with
g++
) but on OS X I get:
With Clang
:
error: assigning to 'char *' from incompatible type 'const char *'
With g++
:
/var/folders/hf/5dbkbqrx5p3bmnpdqqy4wgpr0000gn/T//ccvMHo2S.s:18:no such instruction: `vmovdqa LC0(%rip), %xmm3'
/var/folders/hf/5dbkbqrx5p3bmnpdqqy4wgpr0000gn/T//ccvMHo2S.s:19:no such instruction: `vmovdqa LC1(%rip), %xmm2'
/var/folders/hf/5dbkbqrx5p3bmnpdqqy4wgpr0000gn/T//ccvMHo2S.s:20:no such instruction: `vmovdqu (%rsi), %xmm7'
/var/folders/hf/5dbkbqrx5p3bmnpdqqy4wgpr0000gn/T//ccvMHo2S.s:21:no such instruction: `vmovdqu 16(%rsi), %xmm8'
/var/folders/hf/5dbkbqrx5p3bmnpdqqy4wgpr0000gn/T//ccvMHo2S.s:22:no such instruction: `vmovdqa LC2(%rip), %xmm1'
/var/folders/hf/5dbkbqrx5p3bmnpdqqy4wgpr0000gn/T//ccvMHo2S.s:23:no such instruction: `vpshufb %xmm3, %xmm7,%xmm6'
- Treat C code as C code:
Doesn't find <atomic>
fatal error: atomic: No such file or directory
#include <atomic>
- Use
-Wa -q
flags as per this answer: http://ift.tt/1BRtFBu
Flag becomes invalid.
clang: error: unknown argument: '-q'
clang: warning: treating 'c' input as 'c++' when in C++ mode, this behavior is deprecated
How do I go about building this?
Does the draw order affects objects position in depth? (images included)
I have a few objects on the scene and even if I specify that the object A have y= 10 (the highest object), from the TOP camera I can see the bottom objects through the object A. Here is an image from my scene.
And only today I found an interesting property that draw order of models matters, I may be wrong. Here is another image where I change the draw order of "ship1", attention: "ship1" is way bellow my scene, if I do ship1.draw();
first, the ship disappears (correct), but if I do ship1.draw();
in last, he appears on top (incorrect).
Video: Opengl Depth Problem video
- Q1) Does the draw order always matter?
- Q2) How do I fix this, should I change draw order every time I change camera position?
Edit: I also compared my class of Perspective Projection with the glm library, just to be sure that it´s not the problem with my projection Matrix. Everything is correct.
Edit1: I have my project on git: Arkanoid git repository (windows, project is ready to run at any computer with VS installed)
Edit2: I don´t use normals or texture. Just vertices and indices.
Edit3: Is there are a problem, if every object on the scene uses(share) vertices from the same file ?
Edit4: I also changed my Perspective Projection values. I had near plane at 0.0f, now I have near=20.0f and far=500.0f, angle=60º. But nothing changes, view dose but the depth not. =/
Edit5: Here is my Vertex and Fragment shaders.
Edit6: contact me any time, I am here all day, so ask me anything. At the moment I am rewriting all project from zero. I have two cubes which renders well, one in front of another. Already added mine class for: camera, projections, handler for shaders. Moving to class which create and draw objects.
// Vertex shader
in vec4 in_Position;
out vec4 color;
uniform mat4 Model;
uniform mat4 View;
uniform mat4 Projection;
void main(void)
{
color = in_Position;
gl_Position = Projection * View * Model * in_Position;
}
// Fragment shader
#version 330 core
in vec4 color;
out vec4 out_Color;
void main(void)
{
out_Color = color;
}
Some code:
void setupOpenGL() {
std::cerr << "CONTEXT: OpenGL v" << glGetString(GL_VERSION) << std::endl;
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glDepthMask(GL_TRUE);
glDepthRange(0.0, 1.0);
glClearDepth(1.0);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
}
void display()
{
++FrameCount;
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderScene();
glutSwapBuffers();
}
void renderScene()
{
wallNorth.draw(shader);
obstacle1.draw(shader);
wallEast.draw(shader);
wallWest.draw(shader);
ship1.draw(shader);
plane.draw(shader);
}
How do I get started with a GPU voxelizer?
I've been reading various articles about how to write a GPU voxelizer. From my understanding the process goes like this:
- Inspect the triangles individually and decide the axis that displays the triangle in the largest way. Call this the dominant axis.
- Render the triangle on its dominant axis and sample the texels that come out.
- Write that texel data onto a 3D texture and then do what you will with the data
Disregarding conservative rasterization, I have a lot of questions regarding this process.
I've gotten as far as rendering each triangle, choosing a dominant axis and orthogonally projecting it. What should the values of the orthogonal projection be? Should it be some value based around the size of the voxels or how large of an area the map should cover?
What am I supposed to do in the fragment shader? How do I write to my 3D texture such that it stores the voxel data? From my understanding, due to choosing the dominant axis we can't have more than a depth of 1 voxel for each fragment. However, since we projected orthogonally I don't see how that would reflect onto the 3D texture.
Finally, I am wondering on where to store the texture data. I know it's a bad idea to store data CPU side since you have to pass it all in to use it on the GPU, however the sourcecode I am kind of following chooses to store all its texture on the CPU side, such as those for a light map. My assumption is that data that will only be used on the GPU should be stored there and data used on both should be stored on the CPU side of things. So, from this I store my data on the CPU side. Is that correct?
My main sources have been: http://ift.tt/1NuxKwa OpenGL Insights http://ift.tt/1NuxKwc A SVO using a voxelizer. The issue is that the shader code is not in the github.
"RpcAsync.h" header file not being read, in which I have put in order for recognizing AnsiString in Microsoft Visual Studio
This is my first time working with header files, and I have a source code and I'm trying to include RpcAsync.h file and written in the beginning of my source file however visual studio is not recognizing the header file for AnsiString. I am able to see AnsiString definitions in RpcASync.h .
It throws an error saying : 1 IntelliSense: identifier "AnsiString" is undefined.
Thank you
count the frequency of groups in vector using rtree ( or any other algorithm ) [on hold]
given following set of points in a vector {( 100, 150 ), ( 101, 152 ), ( 102, 151 ), ( 105, 155 ), ( 50, 50 ), ( 51, 55 ), ( 55, 55 ), ( 150, 250 ), ( 190, 260 ) }
I need to identify neighboring points and their count. Let us say the acceptable distance has been set as 5. Now I need following output: frequency of point ( 100, 150 ) with in 5 units is 4. frequency of point ( 50, 50 ) with in 5 units is 3 frequency of point ( 150, 250 ) within 5 units is 1 frequency of point ( 190, 260 ) within 5 units is 1
I have tried a RTree solution to this problem but couldn't determine the logic to exclude all neighboring points as candidates. Means Once I have identified there are four neighbors of ( 100, 150 ), I don't want to identify the neighbors of those neighbors. I would like to move on to next value. Here are the presumptions: 1. efficiency is the topmost concern 2. The vector is unsorted 3. the vector may contain thousands of points. I am using C++ and boost implementation of RTree. Please guide me how can I achieve the solution
EDIT
I can't post an answer because the question has been erroneously put on hold. The code to solve this the way you want is here. If the question reopens I could elaborate on it, for now try to read it and be patient
How to properly use IOpenServiceManager::InstallService
Im trying to define a new IE search engine, but getting into trouble whenever i try to install the service.
I walked through the following example and only changed the name of the files
upload.xml:
<OpenSearchDescription xmlns="http://ift.tt/LMPdQR">
<ShortName>Web Search</ShortName>
<Description>Use Example.com to search the Web.</Description>
<Tags>example web</Tags>
<Contact>admin@example.com</Contact>
<Url type="application/rss+xml"
template="http://ift.tt/1Io4vf8"/>
</OpenSearchDescription>
home.html
<html>
<header>
<link rel="search"
type="application/opensearchdescription+xml"
href="http://ift.tt/1eeKknz"
title="Content search" />
</header>
</html>
Links are valid and work.
c++:
ATL::CComPtr<IOpenServiceManager> spManager;
if (FAILED(hr = spManager.CoCreateInstance(CLSID_OpenServiceManager)))
return false;
//URL-OF-SERVICE: See http://ift.tt/1A8nEgo
ATL::CComPtr<IOpenService> spService;
if (FAILED(hr = spManager->InstallService(L"http://ift.tt/1Io4vfe", &spService)))
return 0;
if (FAILED(hr = spService->SetDefault(TRUE, nullptr)))
return 0;
return 1;
Everytime i try to install the service i get (hr = 0xc00ce556 / E_INVALIDARG)
Correct way to predict the required number of nodes in a kD-Tree
I'm implementing a dynamic kD-Tree storing the nodes in an std::vector in the breadth-first manner. It would support incremental insertion of points and collection of points. However I'm facing problem determining the required number of possible nodes to incrementally preallocate space.
I've found a formula on the web, which seems to be wrong:
N = min(m − 1, 2n − ½m − 1),
where m is the smallest power of 2 greater than or equal to n, the number of points.
My implementation of the formula is the following:
size_t required(size_t n)
{
size_t m = nextPowerOf2(n);
return min(m - 1, (n<<1) - (m>>1) - 1);
}
function nextPowerOf2 returns a power of 2 largest or equal to n
Any help would be appreciated.
Using TZipFile to create a new archive
I am attempting to use the TZipFile class to create a new zip file and add some files to it. I am able to add files to an existing archive using this code:
TZipFile * zip = new TZipFile();
zip->Open(fileName, zmReadWrite);
zip->Add("C:\\0\\t.txt");
zip->Close();
However, I am not sure how I can create a new archive in code, and then add files to it. I tried calling zip->Open
on a non-existent file thinking that maybe that would create the archive, however that just caused an access violation.
SFML leaves part of texture blank, if I create it from PixelPtr
I have a code, which converts plain BGR data to sf::Texture. "ifs" is opened ifstream to file which contains byte triplets of BGR colors (header of source file is omitted). And Width & Height 100% valid. In my example image is 800x600.
struct h3pcx_color_bgr { uint8_t b, uint8_t g, uint8_t r };
sf::Uint8* pixels = new sf::Uint8[width * height * 4];
h3pcx_color_bgr* fileData = new h3pcx_color_bgr[width*height];
ifs.read((char*)fileData, width * height * sizeof(h3pcx_color_bgr));
for (uint32_t i = 0; i < width*height; ++i) {
pixels[i * 4] = fileData[i].r;
pixels[i * 4 + 1] = fileData[i].g;
pixels[i * 4 + 2] = fileData[i].b;
pixels[i * 4 + 3] = 255;
}
This code works good, problem comes after. Once I draw my texture:
m_tex.update(pixels); //sf::Texture
m_sprite.setTexture(m_tex); //sf::Sprite
m_window->draw(m_sprite); // m_window is sf::RenderWindow
I have this annoying grey line in image below: What I did:
- Verified, that pixels contains valid value
Code snippet below (700 * 595 is inside "grey area") shows, that both pixels and fileData contains valid data (not grey color, which is appears just uninitialized memory).
auto f = fileData[700 * 595]; // 32, 31, 38
auto r = pixels[700 * 595 * 4]; // 38
auto g = pixels[700 * 595 * 4 + 1]; // 31
auto b = pixels[700 * 595 * 4 + 2]; // 32
"Grey" color is 204, 204, 204.
- Tried to use sf::Image
If we do something like this:
img.create(width, height, pixels); // img is sf::Image
img.setPixel(700, 595, sf::Color::Blue);
And then convert it to sf::Texture, and draw. Result will be same image with grey area, but pixel 700, 585 will be blue!
If I get color value from "grey area":
auto clr = img.getPixel(700,600); //sf::Color(204,204,204)
So, it looks like, there are some hard-limit(???) on quantity of pixels (but I doubt it, since I've looked on actual SFML code, and did not found anything suspicious) or my stupid mistake. I would be very grateful, if someone can point out - why this grey line appears.
Amibiguous operator in reference class?
I am attempting to create a class that mimics a reference to some value. To do that I want to define operator overloads so that it behaves appropriately. When I do that, operator+
resolves correctly, but operator*
complains with error: use of overloaded operator '*' is ambiguous (with operand types 'ref<int>' and 'int')
(at least in Clang 3.4).
Here's what I've done (with most things made explicit and removing all of the extra stuff):
template <typename T> class ref {
private:
T &val;
public:
ref(T &r) : val(r) {}
template <typename R> ref<T> &operator=(R const &rhs) {
val = rhs;
return *this;
}
// BINOP_TY(+);
template <typename L, typename R>
friend auto operator+(L lhs, ref<R> rhs) -> decltype((lhs) + (rhs.val));
template <typename L, typename R>
friend auto operator+(ref<L> lhs, R rhs) -> decltype((lhs.val) + (rhs));
template <typename L, typename R>
friend auto operator+(ref<L> lhs, ref<R> rhs)
-> decltype((lhs.val) + (rhs.val));
// BINOP_TY(*);
template <typename L, typename R>
friend auto operator*(L lhs, ref<R> rhs) -> decltype((lhs) * (rhs.val));
template <typename L, typename R>
friend auto operator*(ref<L> lhs, R rhs) -> decltype((lhs.val) * (rhs));
template <typename L, typename R>
friend auto operator*(ref<L> lhs, ref<R> rhs)
-> decltype((lhs.val) * (rhs.val));
};
// BINOP(+);
template <typename L, typename R>
auto operator+(L lhs, ref<R> rhs) -> decltype((lhs) + (rhs.val)) {
return lhs + rhs.val;
}
template <typename L, typename R>
auto operator+(ref<L> lhs, R rhs) -> decltype((lhs.val) + (rhs)) {
return lhs.val + rhs;
}
template <typename L, typename R>
auto operator+(ref<L> lhs, ref<R> rhs) -> decltype((lhs.val) + (rhs.val)) {
return lhs.val + rhs.val;
}
// BINOP(*);
template <typename L, typename R>
auto operator*(L lhs, ref<R> rhs) -> decltype((lhs) * (rhs.val)) {
return lhs * rhs.val;
}
template <typename L, typename R>
auto operator*(ref<L> lhs, R rhs) -> decltype((lhs.val) * (rhs)) {
return lhs.val * rhs;
}
template <typename L, typename R>
auto operator*(ref<L> lhs, ref<R> rhs) -> decltype((lhs.val) * (rhs.val)) {
return lhs.val * rhs.val;
}
// Works.
void plus(ref<int> r, int i) {
r = r + i;
}
// Fails.
void mult(ref<int> r, int i) {
r = r * i;
}
Full output:
$ clang++ -std=c++11 ref2.cpp
ref2.cpp:75:13: error: use of overloaded operator '*' is ambiguous (with operand types 'ref<int>' and 'int')
r = r * i;
~ ^ ~
ref2.cpp:29:19: note: candidate function [with L = int, R = int]
friend auto operator*(ref<L> lhs, R rhs) -> decltype((lhs.val) * (rhs));
^
ref2.cpp:59:10: note: candidate function [with L = int, R = int]
auto operator*(ref<L> lhs, R rhs) -> decltype((lhs.val) * (rhs)) {
^
1 error generated.
What am I missing?
how to i parallelise this in CUDA? [on hold]
I want to parallelize the following code in CUDA, but I don't know how to port it on kernel and convert its return value from bool to void for use it into global memory.
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <malloc.h>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <map>
#include <algorithm>
#define WEIGHTED 0
#define UNWEIGHTED 1
using namespace std;
class Graph {
public:
unsigned int nb_nodes;
unsigned long nb_links;
double total_weight;
vector<unsigned long> degrees;
vector<unsigned int> links;
vector<float> weights;
Graph();
Graph(char *filename, char *filename_w, int type);
Graph(int nb_nodes, int nb_links, double total_weight, int *degrees, int *links, float *weights);
void display(void);
void display_reverse(void);
void display_binary(char *outfile);
bool check_symmetry();
// return the number of neighbors (degree) of the node
inline unsigned int nb_neighbors(unsigned int node);
// return the number of self loops of the node
inline double nb_selfloops(unsigned int node);
// return the weighted degree of the node
inline double weighted_degree(unsigned int node);
// return pointers to the first neighbor and first weight of the node
inline pair<vector<unsigned int>::iterator, vector<float>::iterator > neighbors(unsigned int node);
};
inline unsigned int
Graph::nb_neighbors(unsigned int node) {
assert(node>=0 && node<nb_nodes);
if (node==0)
return degrees[0];
else
return degrees[node]-degrees[node-1];
}
inline double
Graph::nb_selfloops(unsigned int node) {
assert(node>=0 && node<nb_nodes);
pair<vector<unsigned int>::iterator, vector<float>::iterator > p = neighbors(node);
for (unsigned int i=0 ; i<nb_neighbors(node) ; i++) {
if (*(p.first+i)==node) {
if (weights.size()!=0)
return (double)*(p.second+i);
else
return 1.;
}
}
return 0.;
}
inline double
Graph::weighted_degree(unsigned int node) {
assert(node>=0 && node<nb_nodes);
if (weights.size()==0)
return (double)nb_neighbors(node);
else {
pair<vector<unsigned int>::iterator, vector<float>::iterator > p = neighbors(node);
double res = 0;
for (unsigned int i=0 ; i<nb_neighbors(node) ; i++) {
res += (double)*(p.second+i);
}
return res;
}
}
inline pair<vector<unsigned int>::iterator, vector<float>::iterator >
Graph::neighbors(unsigned int node) {
assert(node>=0 && node<nb_nodes);
if (node==0)
return make_pair(links.begin(), weights.begin());
else if (weights.size()!=0)
return make_pair(links.begin()+degrees[node-1], weights.begin()+degrees[node-1]);
else
return make_pair(links.begin()+degrees[node-1], weights.begin());
}
Graph::Graph() {
nb_nodes = 0;
nb_links = 0;
total_weight = 0;
}
Graph::Graph(char *filename, char *filename_w, int type) {
ifstream finput;
finput.open(filename,fstream::in | fstream::binary);
// Read number of nodes on 4 bytes
finput.read((char *)&nb_nodes, 4);
assert(finput.rdstate() == ios::goodbit);
// Read cumulative degree sequence: 8 bytes for each node
// cum_degree[0]=degree(0); cum_degree[1]=degree(0)+degree(1), etc.
degrees.resize(nb_nodes);
finput.read((char *)°rees[0], nb_nodes*8);
// Read links: 4 bytes for each link (each link is counted twice)
nb_links=degrees[nb_nodes-1];
links.resize(nb_links);
finput.read((char *)(&links[0]), (long)nb_links*8);
// IF WEIGHTED : read weights: 4 bytes for each link (each link is counted twice)
weights.resize(0);
total_weight=0;
if (type==WEIGHTED) {
ifstream finput_w;
finput_w.open(filename_w,fstream::in | fstream::binary);
weights.resize(nb_links);
finput_w.read((char *)&weights[0], (long)nb_links*4);
}
// Compute total weight
for (unsigned int i=0 ; i<nb_nodes ; i++) {
total_weight += (double)weighted_degree(i);
}
}
Graph::Graph(int n, int m, double t, int *d, int *l, float *w) {
/* nb_nodes = n;
nb_links = m;
total_weight = t;
degrees = d;
links = l;
weights = w;*/
}
void
Graph::display() {
/* for (unsigned int node=0 ; node<nb_nodes ; node++) {
pair<vector<unsigned int>::iterator, vector<float>::iterator > p = neighbors(node);
for (unsigned int i=0 ; i<nb_neighbors(node) ; i++) {
if (node<=*(p.first+i)) {
if (weights.size()!=0)
cout << node << " " << *(p.first+i) << " " << *(p.second+i) << endl;
else
cout << node << " " << *(p.first+i) << endl;
}
}
}*/
for (unsigned int node=0 ; node<nb_nodes ; node++) {
pair<vector<unsigned int>::iterator, vector<float>::iterator > p = neighbors(node);
cout << node << ":" ;
for (unsigned int i=0 ; i<nb_neighbors(node) ; i++) {
if (true) {
if (weights.size()!=0)
cout << " (" << *(p.first+i) << " " << *(p.second+i) << ")";
else
cout << " " << *(p.first+i);
}
}
cout << endl;
}
}
void
Graph::display_reverse() {
for (unsigned int node=0 ; node<nb_nodes ; node++) {
pair<vector<unsigned int>::iterator, vector<float>::iterator > p = neighbors(node);
for (unsigned int i=0 ; i<nb_neighbors(node) ; i++) {
if (node>*(p.first+i)) {
if (weights.size()!=0)
cout << *(p.first+i) << " " << node << " " << *(p.second+i) << endl;
else
cout << *(p.first+i) << " " << node << endl;
}
}
}
}
bool
Graph::check_symmetry() {
int error=0;
for (unsigned int node=0 ; node<nb_nodes ; node++) {
pair<vector<unsigned int>::iterator, vector<float>::iterator > p = neighbors(node);
for (unsigned int i=0 ; i<nb_neighbors(node) ; i++) {
unsigned int neigh = *(p.first+i);
float weight = *(p.second+i);
pair<vector<unsigned int>::iterator, vector<float>::iterator > p_neigh = neighbors(neigh);
for (unsigned int j=0 ; j<nb_neighbors(neigh) ; j++) {
unsigned int neigh_neigh = *(p_neigh.first+j);
float neigh_weight = *(p_neigh.second+j);
if (node==neigh_neigh && weight!=neigh_weight) {
cout << node << " " << neigh << " " << weight << " " << neigh_weight << endl;
if (error++==10)
exit(0);
}
}
}
}
return (error==0);
}
void
Graph::display_binary(char *outfile) {
ofstream foutput;
foutput.open(outfile ,fstream::out | fstream::binary);
foutput.write((char *)(&nb_nodes),4);
foutput.write((char *)(°rees[0]),4*nb_nodes);
foutput.write((char *)(&links[0]),8*nb_links);
}
This code contains vector, iterator, pair. Hence I don't know how to mapping it on the device, already I didn't use thrust for vector, etc.
C++ abstract or interface classes?
I found this question: When to use abstract class or interface?. But it was asked for Java
and C++
is different. There is multiple inheritence so maybe the answers are different too.
When shall I use an interface class ?
If I use the PIMPL
idiom then there will be only one member which I only need to forward declare. And if I move the private functions into the PIMPL
class then there will be only public
and protected
functions in a abstract
class. So the difference between an abstract
class like this and an ˙interface
class is that in the interface
class there shall be only pure virtual functions. Does it have any advantages over the previously mentioned one ?
SIGSEGV in CallVoidMethod jni
I have a java appliction with some jni native methods. One of them is readFile, and it is called like this:
OutputStream outStream = null;
File file = new File("Alf.txt");
try {
outStream = new FileOutputStream(file);
myObject.readFile("TestFile.txt",outStream);
...
in my jni implementation I do :
JNIEXPORT jint JNICALL Java_com_example_mylib_SomeClass_readFile
(JNIEnv *env, jclass, jstring java_string, jobject stream) {
jclass classOutputStream = env->FindClass("java/io/OutputStream");
if (classOutputStream == NULL)
{
Log::err("classOutputStream == NULL;");
return -1;
}
jmethodID OutputStream_write_ID = env->GetMethodID(classOutputStream, "write", "([BII)V");
if (OutputStream_write_ID == NULL)
{
return -1;
}
char* buf = "hello";
env->CallVoidMethod((jobject)stream, OutputStream_write_ID,buf,0,5);
and when I call CallVoidMethod I get
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007f4a85a5e1e1, pid=25597, tid=139958068348672
#
# JRE version: Java(TM) SE Runtime Environment (8.0_25-b17) (build 1.8.0_25-b17)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.25-b02 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# V [libjvm.so+0x6ad1e1] jni_GetArrayLength+0xb1
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /.../hs_err_pid25597.log
I checked - no variables are == NULL, what do I do wrong?
gmtime_r((time_t*)&title->start_time, &start_time);
I'm trying to compile on Microsoft visual studio 2013 on C++ a program written for linux ( is a mix of C and C++ (#include .h) and I'm going to convert all in C++ to not be more confused !)
the statement:
gmtime_r((time_t*)&title->start_time, &start_time);
return errors: Error 11 error C3861: 'gmtime_r': identifier not found IntelliSense: identifier "gmtime_r" is undefined
please help
lundi 27 avril 2015
regular expressions with word boundaries fail in .NET Regex
I have a problem with regular expressions in .NET. We are trying to match special tokens in a text surrounded by the paragraph sign (§). For completeness those the corresponding regular expressions are surrounded by word boundaries (\b). The problem is that the regular expression surrounded by \b does not match words:
static void Main(string[] args)
{
string data = "I would like to replace this §pattern§ with something interesting";
string requiredResult = "I would like to replace this serious text with something interesting";
Regex regSuccess = new Regex("§pattern§");
Regex regFail = new Regex(@"\b§pattern§\b");
var dataSuccess = regSuccess.Replace(data, "serious text");
var dataFail = regFail.Replace(data, "serious text");
Console.WriteLine("regSuccess match: {0}", dataSuccess == requiredResult);
Console.WriteLine("regFail match: {0}", dataFail == requiredResult);
Console.WriteLine("Press enter to continue");
var line = Console.ReadLine();
}
As you can see, dataFail == requiredResult
returns false.
Power shell: create alias for path
Is it possible in Power Shell to create alias for path?
For example: I have to write all time
PS PS C:\Users\Jacek>cd C:\windows\microsoft.net\framework\v4.0.30319
I will happy if I could write
PS PS C:\Users\Jacek>cd dotNet4path
How do I fade a picturebox image to another on mousehover event?
How do I animate a picturebox to change from one image to another on a mouse hover event as a fade-in effect?
I would also like to create the animated picturebox as a class that would show up under my toolbox for ease-of-use.
Example of a button with what I want to make a picturebox do. Animated Button Example-MSDN
I wanted to understand the purpose of this code snippet
Can someone please explain the purpose of this C# code. It's a code snippet in a Windows based application. Is it counting the number of keypress? What is the purpose of 13 here?
Any help would be much appreciated
private void num2_KeyPress(object sender, KeyPressEventArgs e)
{
if ((int) e.KeyChar != 13)
return;
this.Calculate();
}
c# powerpoint interop how do I print horizontally?
The MSDN is making me crazy. I succeeded on printing four pages at a single page, but can't find the option to change it print horizontally. By default, it is printed vertically, not that good looking.
public void test6()
{
try
{
Microsoft.Office.Interop.PowerPoint.Application varPPT = new Microsoft.Office.Interop.PowerPoint.Application();
Microsoft.Office.Interop.PowerPoint.Presentation varPre = varPPT.Presentations.Open(filePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
varPre.PrintOptions.OutputType = Microsoft.Office.Interop.PowerPoint.PpPrintOutputType.ppPrintOutputFourSlideHandouts;
varPre.PrintOut();
}
catch (Exception varE)
{
MessageBox.Show("Error:\n" + varE.Message, "Error message");
}
}
Well, this is my code. It prints well vertically, but that's not good looking at all.
I thought
varPre.PrintOptions.HandoutOrder = Microsoft.Office.Interop.PowerPoint.PpPrintHandoutOrder.ppPrintHandoutHorizontalFirst;
might do the job, but it doesn't seem to fit at all.
Does anyone knows the method or property for this?
Using DTO in Azure Mobile Service .NET throws target invocation exception
I use Azure Mobile Services .NET backend and we all know we have to use Entity Framework classes to map to the database creation/migration. So I need to use DTOs to serialize only the properties I want, computed properties etc. I'm following the Field Engineer example. But Automapper gave me so much pain although I did everything as supposed to.
I have checked couple of others blog and site, some use Automapper, others not, for example this one. I feel more comfortable not using Automapper and create DTOs on the fly with Select() as I was doing it before when implementing Web API.
I reverted TableController class to Post, use the EntityDomainManager and I left the GetAllPosts method to the following.
public class PostController : TableController<Post>
{
private MobileServiceContext _context;
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
_context = new MobileServiceContext();
DomainManager = new EntityDomainManager<Post>(_context, Request, Services);
}
//[ExpandProperty("User")]
// GET tables/Post
public IQueryable<PostDto> GetAllPost()
{
return Query().Include("User").Select(x => new PostDto());
}
}
I get the following error.
{"message":"An error has occurred.","exceptionMessage":"Exception has been thrown by the target of an invocation.","exceptionType":"System.Reflection.TargetInvocationException","stackTrace":" at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)\r\n at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)\r\n at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)\r\n at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)\r\n at System.Web.Http.OData.Query.ODataQueryOptions.LimitResults(IQueryable queryable, Int32 limit, Boolean& resultsLimited)\r\n at System.Web.Http.OData.Query.ODataQueryOptions.ApplyTo(IQueryable query, ODataQuerySettings querySettings)\r\n at System.Web.Http.OData.EnableQueryAttribute.ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions)\r\n at System.Web.Http.OData.EnableQueryAttribute.ExecuteQuery(Object response, HttpRequestMessage request, HttpActionDescriptor actionDescriptor)\r\n at System.Web.Http.OData.EnableQueryAttribute.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)\r\n at System.Web.Http.Filters.ActionFilterAttribute.OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()","innerException":{"message":"An error has occurred.","exceptionMessage":"The specified type member 'DatePosted' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.","exceptionType":"System.NotSupportedException","stackTrace":" at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MemberAccessTranslator.TypedTranslate(ExpressionConverter parent, MemberExpression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input, DbExpressionBinding& binding)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression& source, DbExpressionBinding& sourceBinding, DbExpression& lambda)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateSet(Expression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.ThenByTranslatorBase.Translate(ExpressionConverter parent, MethodCallExpression call)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateSet(Expression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.ThenByTranslatorBase.Translate(ExpressionConverter parent, MethodCallExpression call)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateSet(Expression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.UnarySequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)\r\n at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.Convert()\r\n at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()\r\n at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()\r\n at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()\r\n at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()\r\n at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\r\n at System.Web.Http.OData.Query.TruncatedCollection`1..ctor(IQueryable`1 source, Int32 pageSize)\r\n at System.Web.Http.OData.Query.ODataQueryOptions.LimitResults[T](IQueryable`1 queryable, Int32 limit, Boolean& resultsLimited)"}}
If I just convert it to the Entity Framework class it works. You will notice that I don't fill any property, just for testing purposes.
I test locally with IIS Express.
Data objects and models.
public class Post : EntityData
{
public DateTimeOffset DatePosted { get; set; }
public string StatusText { get; set; }
public PostType TypeOfPost { get; set; }
[ForeignKey("Id")]
public virtual User User { get; set; }
[ForeignKey("Id")]
public virtual ICollection<PostPhotoUrl> PhotoUrls { get; set; }
}
public class PostDto
{
public PostDto()
{
PhotoUrls = new HashSet<PostPhotoUrlDto>();
}
public DateTimeOffset DatePosted { get; set; }
public string StatusText { get; set; }
public int TypeOfPost { get; set; }
public UserDto User { get; set; }
public ICollection<PostPhotoUrlDto> PhotoUrls { get; set; }
}
Searching the internet couldn't find any other more clear tutorial how to use Azure Mobile Services and DTOs, though it shouldn't introduce such difficulty. If you have any resources are welcome.
I should mention that if I don't do the following the test website raises error when trying to test the endpoints.
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
The exception snapshot:
I don't REALLY need to have DTOs for this project, but if I don't resolve what I don't understand right now it will come back and hunt me in the long run of this service.