• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

So I have an interesting career choice right now. I have the option to go into a media player route (dealing with Android and iOS development, video transcoders, etc) or jump into big data. I am leaning towards player since I find that to be incredibly fascinating but there might be more money and opportunity in big data. I can't decide and I feel like that whatever I chose will be the wrong one lol.
 

Kalnos

Banned
Choose the one that's more interesting. Don't do anything just for the money (assuming they're identical otherwise: travel time, company size/feel, etc).
 
Hey working on a project in Java that will require a graph data structure. I don't have tons of experience with graphs in programming, so I was wondering what would be the best way to implement this? Is there a good standard Java API? Because I've had trouble finding one, if there is. Should I just make my own?

It's for a map based games where nodes have varying degrees from 2 to 5.

Sounds like you probably want an adjacency list. An adjacency matrix is also an option, but seems inefficient for your particular case, since it sounds like the graph is pretty sparse. As for how to represent it, I had a project recently where I used a List<List<Edge>> to store my graph. The indices in the outer list corresponded to the node IDs and for each node, it stores a list of adjacent edges. The edge representation was advantageous in my case but it might not be necessary for you. A simpler List<List<Integer>> might also work for you.
 

mooooose

Member
Sounds like you probably want an adjacency list. An adjacency matrix is also an option, but seems inefficient for your particular case, since it sounds like the graph is pretty sparse. As for how to represent it, I had a project recently where I used a List<List<Edge>> to store my graph. The indices in the outer list corresponded to the node IDs and for each node, it stores a list of adjacent edges. The edge representation was advantageous in my case but it might not be necessary for you. A simpler List<List<Integer>> might also work for you.
Thank you! I did some research and came to a similar conclusion but it's cool to see it validated by someone else. Thanks again.

I just wanted to say how great this thread is. Everyone is super helpful and its a really friendly and approachable atmosphere. So thanks to anyone who has ever helped me, and will ever help again.
 

squidyj

Member
Alright so using C++ I want to write a flexible loader for 3d models and Im trying to minimize coupling between the loader and whatever model specification winds up being used.

Its not terribly complicated to read in from file to some sort of standardized format internal to the loader but trying to reorganize for some arbitrary definition of a model without a massive amount of reimplementation per model definition is proving troublesome.
 

injurai

Banned
Haven't found much time recently, but Rust has opened my eyes.

I understand it's not yet ready to take over, and maybe something even better will come along. But my god it feels like what language should be.
 
Alright so using C++ I want to write a flexible loader for 3d models and Im trying to minimize coupling between the loader and whatever model specification winds up being used.

Its not terribly complicated to read in from file to some sort of standardized format internal to the loader but trying to reorganize for some arbitrary definition of a model without a massive amount of reimplementation per model definition is proving troublesome.

If by reimplementation you mean writing a parser for each model format I don't really see how you can avoid that. Is there some other functionality that you find overlapping frequently?

Haven't found much time recently, but Rust has opened my eyes.

I understand it's not yet ready to take over, and maybe something even better will come along. But my god it feels like what language should be.

Yeah Rust is sort of glorious. I've been playing with it a bit and it's very very nice to use. I fully intend to use it for the next project I do that would have been C++ based.
 
Haven't found much time recently, but Rust has opened my eyes.

I understand it's not yet ready to take over, and maybe something even better will come along. But my god it feels like what language should be.

Yeah, it really is something. I love that they (basically) have type classes, probably my favorite feature from Haskell. It's super cool that you can do something like this: (a generic 3D vector class that can contain any type that you can do +, -, *, / and % with and has a 0 and 1 value)

Code:
#[deriving(Show, PartialEq)]
pub struct Vec3<A: Num> {
	pub x: A,
	pub y: A,
	pub z: A
}

and then provide implementations for Add, Sub, Mul and so on (Rust's version of operator overloading). I was actually able to implement Num for Vec3 as well, so I can now put a Vec3 inside of another Vec3 (because Vec3 implements Num). This actually lets you put three vectors inside of a vector, which turns out to be a 3x3 matrix.

Code:
fn matrix_add() {
	let v = Vec3::new(
	 	Vec3::new(2i, 4i, 9i), 
	 	Vec3::new(1i, 1i, 1i), 
	 	Vec3::new(2i, 4i, -2i)
 	);

 	let w = Vec3::new(
 		Vec3::<int>::one(),
 		Vec3::<int>::one(),
 		Vec3::<int>::one()
 	);

 	assert!(v * w == v);
}
It's not terribly useful but it's really cool that the type system lets you express things like this. Also, the syntax is very clean and readable unlike e.g. Scala.
 

Quasar

Member
So I continue to struggle with adapting SQL queries to LINQ ones for a C# project. I'm current struggles involve sibqueries and the use of NOT IN.

I have a SQL query like this:

Code:
SELECT * from patient where patient.patientID not in 

(SELECT admission.admissionPatient
     FROM Admission
LEFT JOIN operation ON admission.admissionID = operation.operationAdmission
    where operation.operationID is null);

Anyway I have the subquery part in LINQ like this:

Code:
(from a in Admissions
from o in Operations.DefaultIfEmpty()
select new {patient = a.AdmissionPatient}
).Distinct()

That returns rows with just patient IDs where are the primary key for the patient table. From that I just want to do a simply query of the patient table where the primary key does not match any of the numbers returned from the existing query.

I even thought about doing two separate queries, it would be like:

Code:
var query1 = (from a in Admissions
                     from o in Operations.DefaultIfEmpty()
                     select new {patient = a.AdmissionPatient}
                     ).Distinct();

var query2 = (from p in db.Patients
                         from a in query1
                         select p);

But I'm not sure how to return the rows that DON'T match rather than the rows that DO match.
 

Mr.Mike

Member
I have the exact same C code for a quick sort working perfectly on my computer, but not working on my schools servers. Why would something like this happen and what can I do to fix it?

My computer outputs:
Code:
Please enter the length of the list
?10
28 20 4 76 45 42 34 47 74 66 
Running time of quick sort is 0.000000 seconds

4 20 28 34 42 45 47 66 74 76

On my school's servers, through SSH:
Code:
Please enter the length of the list
?10
84 25 15 0 83 19 24 22 79 50 
Running time of quick sort is 0.000000 seconds

-1075197240 0 15 19 22 24 25 50 79 83

But it's not just weird large negative values. For some numbers it's a 0 instead, and for others it works perfectly fine on my schools computer. For example, a list of length 1 returns a 0 as the first digit no matter what, 2 returns a large negative value as the first value, and 3 works perfectly fine.

It always seems to work on my own computer. Here's the code. https://www.dropbox.com/s/l6yed0nn9sm74t0/qtest.c?dl=0
 

squidyj

Member
it looks like you're running outside of the array bounds. An array A of size n runs from A[0] to A[n-1].

you go

quicksort(array, 0, size)
-> partition(array, 0, size)
-> rp = size + 1;
-> rp = rp - 1 = size;
-> array[rp] = array[size] //out of bounds
 

Mr.Mike

Member
it looks like you're running outside of the array bounds. An array A of size n runs from A[0] to A[n-1].

you go

quicksort(array, 0, size)
-> partition(array, 0, size)
-> rp = size + 1;
-> rp = rp - 1 = size;
-> array[rp] = array[size] //out of bounds

Thank you! I've changed the third argument to quicksort in main to be size-1, which has fixed the issue.

I'm still not sure why the incorrect code would seemingly work on Windows but not on Linux?
 

Mr.Mike

Member
Accessing an array index out of bounds is undefined behaviour. Essentially it means anything at all could happen depending on the implementation.

I can see why accessing an array out of bounds would be problematic, as you'd essential be accesing whatever piece of memory is next to your array, IIRC.

From a quick Google search I understand that Windows uses some sort of virtualization to run all apps, and as such there wouldn't been anything outside of the array anyway. This I'd imagine, is what causes the program to either work in Windows, or at least be broken in a different way than it would be if it had been run with Linux. Please correct me if I'm wrong.
 

Slavik81

Member
I can see why accessing an array out of bounds would be problematic, as you'd essential be accesing whatever piece of memory is next to your array, IIRC.

From a quick Google search I understand that Windows uses some sort of virtualization to run all apps, and as such there wouldn't been anything outside of the array anyway. This I'd imagine, is what causes the program to either work in Windows, or at least be broken in a different way than it would be if it had been run with Linux. Please correct me if I'm wrong.
All modern operating systems use virtual memory. Each application gets to run more or less as if they're the only program on the machine. Their 'virtual' addresses are translated by the operating system into real, physical addresses.

Even on the same platform, the result of accessing out-of-bounds memory can vary. Since the operating system needs to keep track of what virtual addresses correspond to what physical addresses, it can tell if you try using a virtual address which it never set up with a physical address. That will typically cause a segmentation fault (a crash).

However, memory gets assigned to a program in big chunks. Making up numbers for the sake of example, if you ask for 235 bytes of memory, the C language runtime might ask the operating system for something like 256 bytes. You're not allowed to reach into those remaining 21 bytes, but if you do, the mistake probably won't cause a crash. Which is bad, because now it's a lot harder to track down the mistake... especially if those 21 bytes were legitimately being used by something else in your program.

Valgrind, by the way, is a wonderful Linux tool for finding these sorts of issues.

Alright so using C++ I want to write a flexible loader for 3d models and Im trying to minimize coupling between the loader and whatever model specification winds up being used.

Its not terribly complicated to read in from file to some sort of standardized format internal to the loader but trying to reorganize for some arbitrary definition of a model without a massive amount of reimplementation per model definition is proving troublesome.
I'm not really a modelling expert, but from my introductory understanding, the in-memory format you want depends on what you plan to do with it. Half-edge models, for instance, are pretty good for traversing the mesh, and for storing data about faces, edges and vertexes. They are great for editing, but overcomplicated if you're just trying to display something.

It's extremely difficult to create a good, flexible solution to a problem when you aren't actually facing that problem. Or even to build it on your first try if you are. There is something to be said for hacking it together with lots of duplication, and then looking at how you can clean it up afterwards.
 

squidyj

Member
All modern operating systems use virtual memory. Each application gets to run more or less as if they're the only program on the machine. Their 'virtual' addresses are translated by the operating system into real, physical addresses.

Even on the same platform, the result of accessing out-of-bounds memory can vary. Since the operating system needs to keep track of what virtual addresses correspond to what physical addresses, it can tell if you try using a virtual address which it never set up with a physical address. That will typically cause a segmentation fault (a crash).

However, memory gets assigned to a program in big chunks. Making up numbers for the sake of example, if you ask for 235 bytes of memory, the C language runtime might ask the operating system for something like 256 bytes. You're not allowed to reach into those remaining 21 bytes, but if you do, the mistake probably won't cause a crash. Which is bad, because now it's a lot harder to track down the mistake... especially if those 21 bytes were legitimately being used by something else in your program.

Valgrind, by the way, is a wonderful Linux tool for finding these sorts of issues.


I'm not really a modelling expert, but from my introductory understanding, the in-memory format you want depends on what you plan to do with it. Half-edge models, for instance, are pretty good for traversing the mesh, and for storing data about faces, edges and vertexes. They are great for editing, but overcomplicated if you're just trying to display something.

It's extremely difficult to create a good, flexible solution to a problem when you aren't actually facing that problem. Or even to build it on your first try if you are. There is something to be said for hacking it together with lots of duplication, and then looking at how you can clean it up afterwards.

half-edges are also only valid over manifolds but that's neither here nor there. Although I remember being upset when my professor complained about me using a more memory wasteful adjacency list for a mesh simplification technique that was designed to work over non-manifold meshes :l

I think that I am not going to see it until I write it :L
 

tokkun

Member
I can see why accessing an array out of bounds would be problematic, as you'd essential be accesing whatever piece of memory is next to your array, IIRC.

From a quick Google search I understand that Windows uses some sort of virtualization to run all apps, and as such there wouldn't been anything outside of the array anyway. This I'd imagine, is what causes the program to either work in Windows, or at least be broken in a different way than it would be if it had been run with Linux. Please correct me if I'm wrong.

The difference you are seeing is based on what data is in the uninitialized memory just beyond your array. If that data is initially larger than any element in the array you are trying to sort, your algorithm will appear to function properly. If it is less, you will see the bug. So whether you detect the bug or not depends entirely on where that array was allocated in memory and what happened in the past to that memory. It may be that a certain compiler or certain kernel memory allocator consistently hides the bug, but if so, it's by chance, not design.
 
Choose the one that's more interesting. Don't do anything just for the money (assuming they're identical otherwise: travel time, company size/feel, etc).

To follow up a bit about this, they are both positions within the company. My current project is wrapping up and my manager just wanted to let me decide. He suggests Big Data due to the fact that it is a hot commodity and that there would be more career choices but I really can't go wrong with either.

Decisions, decisions...
 

jokkir

Member
I need help understanding this

Use vectors to solve the following problem. A company pays its salespeople on a commission basis.
The salespeople each receive $200 per week plus 9 percent of their gross sales for that week. The vector should contain Employee object that contain:

2 string members for First and Last name
1 double to record Gross Sales for the current week
1 double for the weekly income initialized to 200
1 double for the bonus received based on the Gross Sales

For example, a salesperson who grosses $5000 in sales in a week receives $200 plus 9 percent of $5000, or a total of $650.
Write a program (using a stl::vector) that determines how many of the salespeople earned salaries in each of the following ranges (assume that each salesperson&#8217;s salary is truncated to an integer amount). Your main program should create a test case including at least 15 employee (the 15 Employee structures can be hard coded inside the main). The main program should then display the range and the number of employee within that range.

What exactly is the last double for? The "1 double for the bonus received based on the Gross Sales". This is an assignment and seems really easy and I'm thinking it shouldn't be :S . What I did was just created vectors of classes then initialized them with whatever values I made then calculated the salary using that formula mentioned in the instructions.
 

Tater Tot

"My God... it's full of Starch!"
Java newbie here: Can someone please explain this to me?

What will be outputted by the following program code?


int g = 9;
int k = 3;

for (int x=10 ; k<g; g--)
{
k=k+2
System.out.println(x);
x++
g = g+1;
}

I am lost I dont know how to read this or understand it.
 

Ortix

Banned
Java newbie here: Can someone please explain this to me?

What will be outputted by the following program code?


int g = 9;
int k = 3;

for (int x=10 ; k<g; g--)
{
k=k+2
System.out.println(x);
x++
g = g+1;
}

I am lost I dont know how to read this or understand it.

Your for loop will continue running until your condition"k<g" is not longer true. The starting values of k and g are respectively 3 and 9, which is true, so the statements in your loop will all be executed. You are increasing the value of k by 2 and the value of g by 1 BUT also decreasing the g by 1 after the loop ("g--").
So after the first time the value of k is 5 and g is still 9. g is still smaller than k, so the loop will be executed again. After the second time, k is 7 and g is still 9. The condition is still true, so again the loop will be executed. After that third time k will be 9, and g will still be 9. 9 is not smaller than 9, so your for loop will be stopped.
While all this was going on, every time you went through your loop yoou've printed out "x" and increased it's value by 1 after. The first time x was 10, the second time it was 11, the third time it was 12, and there's no fourth since your loop stopped by then.
Your output will be:

To paraphrase:
You have 3 statements between your ():
- the first one is for declaring variables you want to use in your loop. These variables are not known outside the loop, so if you try to print "x" in your example outside the brackets, it would not be recognized.
- the second one is the condition. It checks at the start if it's true. If it is, it'll run the loop, if not it won't. After the loop has been executed, it'll check again if the condition is true. Same as before, if it's true it'll run it again, if not you'll go on to the next code block, and so on. It'll keep checking if the condition is still true after every time.
- the third one is to change the value(s) of the variable(s). If the variables in your condition don't change, the condition will always be true and the loop will go on forever, which is of course not a good idea.

the actual loop, inside the {} brackets, is what will be executed as long as the condition is true.

This probably doesn't make much sense, I'm sure there's several tutorials that can explain it better than I did.
 

Apoc29

Member
I need help understanding this



What exactly is the last double for? The "1 double for the bonus received based on the Gross Sales". This is an assignment and seems really easy and I'm thinking it shouldn't be :S . What I did was just created vectors of classes then initialized them with whatever values I made then calculated the salary using that formula mentioned in the instructions.

Based the example:
For example, a salesperson who grosses $5000 in sales in a week receives $200 plus 9 percent of $5000, or a total of $650.

1 double to record Gross Sales for the current week: 5000
1 double for the weekly income initialized to 200: 200
1 double for the bonus received based on the Gross Sales: 0.09 * 5000 = 450
 

Slavik81

Member
I know this is only semi-relevant to this topic, but I thought it still important enough to mention: Windows 10 will come with a command line package manager built in.
Which is a godsend. I worked on configuration management and version control for a while because the problem bugged me at work. The lack of real Windows package support was a big issue. I ended up using Chocolatey, which is basically what this new Windows package manager (OneGet) is based on.

There was a GAF thread, actually. I posted a bit more about it there.

What's kinda cool is that it's fairly easy to build your own packages. The packages mostly just say where to download an installer from, what flags to pass to the installer when it's run, and maybe include a little scripting to change a few settings files. Most official installers already have a silent install flag of some sort, so basically all existing software can easily be packaged by a thirdparty without any help from anyone else.

It's doublely cool that this came out of the Microsoft open-source group.
 

Exuro

Member
I need some help with GLSL.

I'm trying to set up my projection and modelview matrices and as far as I know they are correct and are being multiplied correctly so the only thing I can think of being the issue is when I move the Matrix to the shader. I'm a complete beginner(as in this is my 3rd day learning it) at this so I'm not 100% whats going on with unifroms. So I have Matrix MVPM which is the modelviewprojection matrix that I got from calculating projection * modelview. I double checked the orientation (row vs column) so I'm sure this is being calculated correctly(and I've tried both anyways). Anyways, after getting this value I pass the matrix as a uniform to the shader.

Code:
GLint loc = glGetUniformLocation(shader.id(),"MVPM");
	glUniform4fv(loc, 4, *MVPM.m);

Then in the vertex shader

Code:
uniform mat4 MVPM;

void main()
{
	
	//gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
	gl_Position = MVPM * gl_Vertex;
}

Is anything above incorrect? I'm getting a black screen, which when I comment out my line and comment in the deprecated line it works perfectly. I'm pretty much stuck on just figuring this out. Seems like something simple I'm missing. In this MVPM is a object of class Matrix that I've defined. The data is stored in a 2d array m. shader.id() returns the shader's id. If only there was a way to debug the shader with print statements.

EDIT: Just found out about this function to check the value of the uniforms. Used this code

Code:
glGetUniformfv(shader.id(), loc, ptr); 
	
	
	printf("UNIFORM\n");
	printf("%f %f %f %f\n",ptr[0], ptr[1], ptr[2], ptr[3]);
	printf("%f %f %f %f\n",ptr[4], ptr[5], ptr[6], ptr[7]);
	printf("%f %f %f %f\n",ptr[8], ptr[9], ptr[10], ptr[11]);
	printf("%f %f %f %f\n",ptr[12], ptr[13], ptr[14], ptr[15]);

And it's spitting out zeros so I'm assigning this incorrectly. Can someone clarify how I need to do this?
 

Slavik81

Member
It's way past my bedtime, but I found apitrace to be invaluable for catching OpenGL errors when porting from fixed function to shader-based code. If you're on Linux, it's fairly easy to build from source. Very useful for debugging.
 

jokkir

Member
Based the example:


1 double to record Gross Sales for the current week: 5000
1 double for the weekly income initialized to 200: 200
1 double for the bonus received based on the Gross Sales: 0.09 * 5000 = 450

Huzzah thanks.

I finished it but I can't help but feel that I did it completely wrong. It seemed a bit too easy :\
 

nan0

Member
Can someone recommend a book or resources on Unit-testing (preferably C#/.Net), that have relevant real-world examples? Most of the stuff I find is more like "how to test if your {return x*x;} function works properly", but I'd need stuff like mocking registry access, xml serialization etc. and generally testing non-primitive data types.
 
I am doing a server-client program in C++ and am having trouble figuring out how to do a couple of things. I already have the server and client up and running and they are able to exchange simple messages. What I need to do is have the client send the name of a file to the server and have the server run a function of that file name and return the output to the client.

I am lost on
1) How to pass the file name when the server receives it (in main) to the appropriate function outside of main.
2) How to return the output from the function (about 250 lines) to the client

Any help/tips on how to do this would be greatly appreciated.
 

poweld

Member
I am doing a server-client program in C++ and am having trouble figuring out how to do a couple of things. I already have the server and client up and running and they are able to exchange simple messages. What I need to do is have the client send the name of a file to the server and have the server run a function of that file name and return the output to the client.

I am lost on
1) How to pass the file name when the server receives it (in main) to the appropriate function outside of main.
2) How to return the output from the function (about 250 lines) to the client

Any help/tips on how to do this would be greatly appreciated.

Show us what you've got in a pastebin or something and we'll be able to give you a hand.
 

Exuro

Member
It's way past my bedtime, but I found apitrace to be invaluable for catching OpenGL errors when porting from fixed function to shader-based code. If you're on Linux, it's fairly easy to build from source. Very useful for debugging.
Thanks. I was able to determine that I needed to use this code...

Code:
GLint loc2 = glGetUniformLocation(shader.id(),"modelviewprojection");
	glUniformMatrix4fv(loc2, 1, false, *modelviewprojection.m);

since I'm putting my uniform into a mat4 type. That fixed that and the matrix is now being moved over correctly. However now I'm stuck on my screen not looking like it should be. Listed below is my programs output of my matrices along with gluperspective's projection matrix and gluLookAt's modelview matrix.

Code:
PM:
2.414214, 0.000000, 0.000000, 0.000000
0.000000, 2.414214, 0.000000, 0.000000
0.000000, 0.000000, -1.222222, -2.222222
0.000000, 0.000000, -1.000000, 0.000000
MVM:
1.000000, -0.000000, 0.000000, -0.000000
0.000000, 1.000000, 0.000000, -0.000000
-0.000000, -0.000000, 1.000000, -5.000000
0.000000, 0.000000, 0.000000, 1.000000
MVPM being sent:
2.414214, 0.000000, 0.000000, 0.000000
0.000000, 2.414214, 0.000000, 0.000000
0.000000, 0.000000, -1.222222, 3.888889
0.000000, 0.000000, -1.000000, 5.000000
glLookatModelview Matrix
1.000000 0.000000 0.000000 0.000000
0.000000 1.000000 0.000000 0.000000
0.000000 0.000000 1.000000 0.000000
0.000000 0.000000 -5.000000 1.000000
gluPerspective Matrix
2.414214 0.000000 0.000000 0.000000
0.000000 2.414214 0.000000 0.000000
0.000000 0.000000 -1.222222 -1.000000
0.000000 0.000000 -2.222222 0.000000
UNIFORM
2.414214 0.000000 0.000000 0.000000
0.000000 2.414214 0.000000 0.000000
0.000000 0.000000 -1.222222 3.888889
0.000000 0.000000 -1.000000 5.000000

PM is the projection matrix.
MVM is the modelview matrix.
MVPM is the modelview projection matrix, or P * M.
glulookat and perspective are the fixed pipelines matrices. I can see their orientation is column major, but if I try this I get a black screen.
The UNIFORM is the MVPM that is sent to my shader. I'm using it to make sure the matrix went through properly to the shader.

So the main difference is my matrices are row major. When I run this as is with the above PM and MVM matrices I get the brick object that I'm hoping for.

2wSGENe.png

Now if I move along with z or n axis, the object moves correctly, as if its moving closer or farther. The problem I'm having is when I rotate or translate on the y or x axis. When I tried to translate right in relation to the window this happens.


I've been looking over my matrices when I translate and rotate and they're matching up perfectly with the gluperspective/gluLookat counterparts(other than the row vs column major). Any idea why this could be occuring?

EDIT: Wow I found a strange issue. So my near and far clipping plane values don't seem to be working. Like the projection matrix is correct but I guess that part of the pipeline is being disabled? When I decrease the far plane I expect the box to vanish, but instead it gets larger and larger...

So I guess that means I can't simple use this as my vertex shader? Doesn't make a lot of sense as gl_modelviewmatrix seems to work fine.

Code:
uniform mat4 modelviewprojection;

void main()
{
	//gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
	gl_Position = modelviewprojection * gl_Vertex;
}
 
Just to be clear, you're asking how to send `filename` as an argument to another function, and have that function write something back to the client?

Yes, I need the 'filename' to be able to be read by the ProcessNumbers function which will do the stuff it has do with the numbers in the file and then have the output of the ProcessNumbers function be sent to the client. If the ProcessNumbers function can send the output directly back to the client instead of having to go back to main that would probably be better.

Flow chart would be:
1) Client sends filename
2) Server receives filename
3) Server passes filename to ProcessNumbers that work can be done
4) ProcessNumbers functions does it thing
5) Server sends output of ProcessNumbers to client
 

poweld

Member
Yes, I need the 'filename' to be able to be read by the ProcessNumbers function which will do the stuff it has do with the numbers in the file and then have the output of the ProcessNumbers function be sent to the client. If the ProcessNumbers function can send the output directly back to the client instead of having to go back to main that would probably be better.

Flow chart would be:
1) Client sends filename
2) Server receives filename
3) Server passes filename to ProcessNumbers that work can be done
4) ProcessNumbers functions does it thing
5) Server sends output of ProcessNumbers to client

Your code is a little tough to follow, but if you want to have the ProcessNumbers function take in an additional string argument (filename), and return a string which you wish to send to the client, you should change the function signature to something like this:

Code:
string ProcessNumbers( void *threadarg, string filename )

The two changes I've made are to change the return type to string as well as adding an argument for the filename. The function can now be called like this:

Code:
string responseString = ProcessNumbers(threadarg, filename)

...and return the string you'd like to send to the client at the end of the function.

As for sending this string back to the client, you can do something like this:

Code:
n = write(newsockfd, responseString.c_str(), responseString.length())

Note that I have not run your code nor tested mine, but I believe it is the direction you want to go in.

As a side note, if you don't know how to change the signature of the function, it makes me think that you may need to study more of the fundamentals of the language. There are a lot of great resources out there. It's been a while since I've worked in c/c++, but I'm sure that I can find some resources, and other here may be able to offer suggestions as well.

Let me know if you have any questions and I'll try to get back to you in a timely manner.
 
Your code is a little tough to follow, but if you want to have the ProcessNumbers function take in an additional string argument (filename), and return a string which you wish to send to the client, you should change the function signature to something like this:

Code:
string ProcessNumbers( void *threadarg, string filename )

The two changes I've made are to change the return type to string as well as adding an argument for the filename. The function can now be called like this:

Code:
string responseString = ProcessNumbers(threadarg, filename)

...and return the string you'd like to send to the client at the end of the function.

As for sending this string back to the client, you can do something like this:

Code:
n = write(newsockfd, responseString.c_str(), responseString.length())

Note that I have not run your code nor tested mine, but I believe it is the direction you want to go in.

As a side note, if you don't know how to change the signature of the function, it makes me think that you may need to study more of the fundamentals of the language. There are a lot of great resources out there. It's been a while since I've worked in c/c++, but I'm sure that I can find some resources, and other here may be able to offer suggestions as well.

Let me know if you have any questions and I'll try to get back to you in a timely manner.

Thanks, I was able to get the ProcessNumbers function to take the name of the file. Problem was actually on the client side because I was using fgets and apparently that added the newline character to the end of the string and so when it was passed to the server it was passing it incorrectly. I fixed it by checking for and removing the newline character before the client sent the filename to the server. Still having problems sending the output to the client though.
 

poweld

Member
Thanks, I was able to get the ProcessNumbers function to take the name of the file. Problem was actually on the client side because I was using fgets and apparently that added the newline character to the end of the string and so when it was passed to the server it was passing it incorrectly. I fixed it by checking for and removing the newline character before the client sent the filename to the server. Still having problems sending the output to the client though.

Did you check `n` after the write? It indicates the number of bytes written. If it is -1, it indicates there was an error, in which case you should check what happened by doing something like this:

Code:
printf ("Error writing to socket: %s\n", strerror(errno));
 

Anustart

Member
So I've been given an assignment and I don't even know where to start.

We have to take in an integer as an argument then determine if that integer can be expressed in the form: 3^n2^k + 3^n+1(2^k+-I)

The 3 always starts at ^0 and goes up 1, 2 can be any number as long as powers either always ascend or descend. Anyone got any hints?
 
Alright so using C++ I want to write a flexible loader for 3d models and Im trying to minimize coupling between the loader and whatever model specification winds up being used.

Its not terribly complicated to read in from file to some sort of standardized format internal to the loader but trying to reorganize for some arbitrary definition of a model without a massive amount of reimplementation per model definition is proving troublesome.

I'm not sure I follow, but can't you just use templates?
 

sdijoseph

Member
I have a bit of a complicated question. I am designing a simple drawing program in NetBeans using JFrame. I have an abstract class called Shape, with subclasses Oval, Rectangle, RoundRect, and Line. Everytime the user draws a shape on the canvas, it gets stored in an array list. Then, whenever the paint() method is called it iterates through the array list to redraw all of the shapes. My problem is that it works correctly if you switch the type of shape each time you draw a new one (For example, I draw an oval, then a rectangle, then an oval, then a line), but if you draw the same type of shape multiple times it will only display the last shape drawn. I checked the size of the array and the Shape objects are still stored in there, they just aren't being drawn.

Here is the paint() method:

Code:
    @Override
    public void paint(Graphics g){
        super.paint(g);
        jPanel4.setBackground(c);
        Graphics pg = jPanel1.getGraphics();
        
        for (int i = 0; i < v.size(); i++) {
            Shape s = v.get(i);
            s.drawShape(pg);
        }
    }

Also, the shapes are being initialized and then added as

Code:
Shape newShape = new Oval(); // or new Rect(), etc.
v.add(newShape); // v is the Array List of type Shape

If you need to see more of my code just ask, thanks.
 

poweld

Member
I have a bit of a complicated question. I am designing a simple drawing program in NetBeans using JFrame. I have an abstract class called Shape, with subclasses Oval, Rectangle, RoundRect, and Line. Everytime the user draws a shape on the canvas, it gets stored in an array list. Then, whenever the paint() method is called it iterates through the array list to redraw all of the shapes. My problem is that it works correctly if you switch the type of shape each time you draw a new one (For example, I draw an oval, then a rectangle, then an oval, then a line), but if you draw the same type of shape multiple times it will only display the last shape drawn. I checked the size of the array and the Shape objects are still stored in there, they just aren't being drawn.

Here is the paint() method:

Code:
    @Override
    public void paint(Graphics g){
        super.paint(g);
        jPanel4.setBackground(c);
        Graphics pg = jPanel1.getGraphics();
        
        for (int i = 0; i < v.size(); i++) {
            Shape s = v.get(i);
            s.drawShape(pg);
        }
    }

Also, the shapes are being initialized and then added as

Code:
Shape newShape = new Oval(); // or new Rect(), etc.
v.add(newShape); // v is the Array List of type Shape

If you need to see more of my code just ask, thanks.

Have you checked whether the shapes stored in the array of the same class are in fact different? e.g. print out their dimensions? Also, can I see your `add` method?
 

sdijoseph

Member
Have you checked whether the shapes stored in the array of the same class are in fact different? e.g. print out their dimensions? Also, can I see your `add` method?

Actually never mind, apparently it didn't matter for this problem. Thanks anyway though.
 

poweld

Member
So I've been given an assignment and I don't even know where to start.

We have to take in an integer as an argument then determine if that integer can be expressed in the form: 3^n2^k + 3^n+1(2^k+-I)

The 3 always starts at ^0 and goes up 1, 2 can be any number as long as powers either always ascend or descend. Anyone got any hints?

I'm having a hard time understanding the problem. Can you try and explain it a bit more clearly? What are the parameters? Provide the function signature, if you can.
 

Kansoku

Member
Quick question. I'm working with a database on android, and I need to populate a ListFragment, but the info I want is on different tables. The thing is, there's this main table and it has ids for the other tables, for example, a row on the main one might be:
_id, object_id, attribute_one_id, attribute_two_id,
and I want to exchange the attribute id from a table with the names of the attribute, and change the object id to it's name from another table. Would I use a CursorJoiner?
 
C++ w/ clang pro-tip, since I just ran into this:

Not remembering to give your function a return value (say if it's a bool that you only check in unit tests) will generate SIGILL when you call it! At least on x64.

or: if it's going to produce such nasty code it should probably be a build error, not a warning...
 
Top Bottom