mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

And, if you want the numbers to be aligned to the right, you have to put the setw immediately before you print the number and you can also use setprecision to have only two numbers after the dot (for floating-point numbers), as in:

cout << setprecision(2);
cout << setw(23) << left << "Loan amount:" << "\t$" << setw(5) << principle << endl;
cout << setw(23) << left << "Monthly Interest Rate:" << "\t" << setw(6) << monthlyIntRate << "%" << endl;
cout << setw(23) << left << "Number of Payments:" << "\t" << setw(6) << numPayments << endl;
cout << setw(23) << left << "Monthly Payment:" << "\t$" << setw(5) << monthlyPayment << endl;
cout << setw(23) << left << "Total Amount Paid:" << "\t$" << setw(5) <<totalAmt << endl;
cout << setw(23) << left << "Interest Paid:" << "\t$" << setw(5) << intPaid << endl;

That should be pretty nice looking!

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, first of all, there's a typo in what you have posted. In the source path, developer@192.168.1.9:/home/develope/fromlaptopsaveDeveloper.tar.gz, you are missing the R in developer folder name. It could very well be just that.

Otherwise, your destination is weird. You send the file to the desktop under username garrett, but the destination folder is in /home/developer. That doesn't make sense. Usually, a normal (non-root) user account does not have write permission to a home folder of another user account. In this case, I don't think that user "garrett" has write permissions on user "developer"'s home folder. And hence the permission denied.

Thirdly, if you are already on the laptop (garrett-laptop) under the home folder of user "developer", you should be able to simply write:

developer@garrett-laptop:~$ scp fromlaptopsaveDeveloper.tar.gz garrett@192.168.1.5:/home/garrett/Desktop/

That should work to transfer the file. If you want it on the home folder of the "developer" user on the desktop, then you should use the "developer" username in the scp command (or give write permissions to garrett over the developer home folder, or transfer the file into garrett's home folder and then copy it locally with a sudo cp or sudo mv command).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Your operator overload is for Element + Element not for int + Element or Element + int.

You can fix the problem by defining those operator overloads, as free-functions:

Element operator+(const Element& lhs, int rhs);
Element operator+(int lhs, const Element& rhs);

and implementing them as you see fit.

BTW, it is also preferred to implement all operators as free-functions (or friend-functions), not as member functions. There are technical reasons for that.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Consistent indentation is really important. I tend to prefer 2 spaces, I don't mind 4 spaces, more is too much IMO. Too much indentation breaks readability of the flow of the code. I tend to use K&R style for braces.

I like line lengths to be limited to about 80 characters (a typical text-area width).

Names of variables, functions and classes should be descriptive, even if it means that they are longer (code-completion solves the problem of additional typing). As for actual conventions (e.g., CamelCase, camelCase, underscore-separated, etc.), I hardly care about it, as long as it is consistent.

The general idea is that when names are descriptive, the code should read like prose, in which case, the need for comments is much less. So, I don't tend to put too much comments inside the body of functions. But, sometimes, when writing a harder algorithm, I write out the steps as comments, which I often leave there after I finished coding it.

However, comments on the interface are hugely important. Documenting what functions do, as in, what are the parameters, what it returns, what exceptions it could throw, and, for mutating member functions, of course, what are the pre-conditions and post-conditions. This is harder to do because it takes time (often longer than writing the code), but I try to do this as much as possible (unless it is really obvious). And, of course, you might as well do it using tags for the relevant document generation system (doxygen (C/C++, …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I would recommend that moderators get more involved with their members, not only in answering questions, but also in the voting and commenting process.

I totally agree. I think, also, that it's important to be on the look-out for fairly new members that give good answers and encourage that with up-vote-comments.

Also, sometimes, like others I'm sure, I tend to forget to give encouragements in addition to answers. Many newbies are young / learning, and in that spirit, it's important not to forget the little encouraging words, like saying: "This code looks good! Keep it up! But if you want to improve it you can ..." as opposed to just "You need to do this ..". Personally, I think I did a bit too much of that in the beginning and got PMed all the time for private help. But now my posts have swong a bit the other way lately. I'll definitely try to bring back some of that "uber-optimistic teacher" attitude.

I also think there isn't enough up-voting on the OP, when it is a good question.

But I guess my question is, as administrators, members, and advocates, what specifically can we physically do to to foster such a great sense to community?

What do you mean by "physically do"? I mean, this is a discussion forum, the principal activity is discussion. So far, people suggested solutions / improvements on the way to discuss, what to discuss, what attitude to have, and how to …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

To help with the problem of getting votes on less visited forums, I would suggest that, at least, all snippets should have a link posted on this thread, and ask that moderators try to take the time to check out each submission, even if it is in a foreign programming language (as in, not the mod's preferred language). I don't know about you, but I can appreciate a nice piece of code regardless of the programming language (as long as I understand it, which I do for most languages). But beyond that, as Dani said, it's part of the game, if you choose a narrow language to code a piece of code with a narrow application area, then you can't expect as much of a wide-spread appreciation of it.

Also, I'm starting to think of ideas and I'd like to get a feel for the expected extent of the snippet. So here are two ideas I have, tell me if they are too much or too little.
(1) A logging system for exceptions in C++, with some predefined logging and handling behaviors. With configurable sinks, strong safety guarantees, and so on.
(2) An adjacency-list graph overlaid on a breadth-first tree layout to allow for efficient, cache-aware (or cache-oblivious) binary-search tree implementations over nodes of a general graph (adj-list).

The first is pretty simple (~200 lines or so). The second is pretty hefty (~1000 lines or so) with loads of advanced C++ techniques. So, are code snippets expected to …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Anyone who doesn't have a broken link as profile picture!

What does a deer think when it is caught in the headlights?

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Git is built like most other Unix/Linux tools, as a set of command-line tools (programs) with options. The best library for the purpose of creating an option-rich command-line program is the Boost.Program-Options.

If what you want to do is create a shell program (like bash), then it's a whole other ball-park. Probably not worth the effort just for one project. I believe that the windows version of Git, called "Git Bash" is simply the Unix/Linux Git tool wrapped inside a cygwin bash application. So, this is probably the route you should take too.

I suggest you develop your application as a Unix/Linux tool (which relies on a powerful shell). Either use cygwin on Windows, or use a Linux distro installation of some kind.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Why does the compilation of "main.cpp" trigger error reports coming from "player.cpp"? You are not #includeing "player.cpp" from your "main.cpp" file, are you?

This has to be coming from an undeclared type or variable. The real error is at "player.cpp" at line 43, the rest is just noise from the compiler.

Please post the relevant code for us to help you further.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I am more interested in knowing if a certain distribution of Linux is better supported for Hadoop and why?

Don't know about Hadoop specifically, but I would imagine that Red Hat Enterprise Linux (Server) is one of the best OS for this application (and by "best OS", I don't mean just the best Linux distro). Linux is used in the majority of servers ( > 60%) up to supercomputers ( > 90%), and RHEL is the prominent distro. If it's good enough for Google, Amazon, CERN, the US DoD, and most "cloud" providers, it's good enough for you. Another alternative is Fedora, which is based on Red Hat, but is free, you get the same extremely robust OS, but you'll have to do a bit more work to set things up correctly (and get good performance out of your server applications). By buying RHEL, you buy the support and assistance of the experienced professionals at Red Hat.

Novell's SUSE Linux Enterprise Server is also an obvious candidate. But I haven't heard as much good about it, and certainly, these days it seems they are having trouble keeping up. I'm no expert in this at all, and don't work in this business either, but, nevertheless, I just keep hearing great things about RHEL's stability, up-time, speed and low TCO. And Red Hat seem more proactive in the emerging cloud solutions.

I would guess that OpenSolaris or Oracle Linux wouldn't be bad choices either.

I'm sure you'll find more expert …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I believe you need a parent QWidget for your new window. And, I also think that your window should be persistent, if you are going to just show() it (as opposed to exec() it). So, I think that the following should work better:

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private:
    Ui::MainWindow ui;
    AuthorsWindow authors;  // NOTICE HERE.
private slots:
    void DisplayAuthors();
};

// ...

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), 
                                          ui(), authors(this)   // NOTICE HERE.
{
    ui.setupUi(this);
    connect(ui.actionAutorzy, SIGNAL(triggered()), this, SLOT(DisplayAuthors()));
}
MainWindow::~MainWindow() { }
void MainWindow::DisplayAuthors()
{
    authors.show();
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The guidelines for the two algorithms are basically the same as for their respective mother-algorithms, i.e., the sorting algorithms.

The counting-selection algorithm is only applicable to a very tightly packed integer-valued array. What I mean by that is that the bound (cap in your function) has to be very small, underwise the memory consumption of the algorithm is really unacceptable. You see, the theoretical best algorithm for such a selection problem requires O(n) time and O(1) memory. The counting selection requires O(n + m) time and O(m) memory, where m is the maximum possible value in the array, this is significantly worse than the theoretically achievable performance. So, unless m is really small compared to n, it makes no sense to use this algorithm. And because you should be able to get O(n) time and O(1) memory for this problem, there is no reason to use this algorithm in any case, at least, from a theoretical point-of-view. If you do some comparative performance tests to show that for certain small array sizes and small bound on the values, that the counting-selection algorithm has sufficiently small constant-factor to make it faster than others in that regime, than that is your guideline.

As for the quick-selection algorithm, it is quite a bit better, with O(n) best-case time and O(1) memory, but it does have O(n^2) worse-case time. This algorithm applies in the general case (values don't have to be integers either) but it is not guaranteed to be fast in all cases, …

Sasstraliss commented: Very good explanation +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you mean the problem about your process remaining active after your program ended, then I have no idea where that comes from. You should maybe post some code (please reduce it to the essential, in which the error still appears).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, maybe you should start by trying to locate the declarations of HT and pos, because, as the compiler says, they are not declared in that scope. For your function prototype to be valid, HT should be a type and pos should be a #define. I see no such thing anywhere. I believe you simply made a mistake declaring that function. Care to explain what you think that function-declaration means?

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The integer 0 is always recognized as a null pointer when in pointer context. I'd be very very surprised if any modern compiler didn't allow that conversion. However, the OP could be using something ancient. The code looks fine even for older compilers, but I don't have any of them handy to test with, so I can't say for certain.
..
So in general, NULL and 0 are synonymous, where NULL would be used to make it clear you intended a pointer context. Ideally, with the advent of C++11, nullptr would be used instead, and the whole issue becomes moot. :D

Points taken. However, the definition of NULL and integral-pointer conversions have been the subject of variations between compilers, even with fairly recent ones. I can't pin-point exactly which compilers are the problem, and no longer have easy access to them, but I definitely remember having problems related to that with BCB and some older MSVC compilers. And certainly, today, one would be better off using nullptr in any case.

Have you found that an implicit conversion to bool is generally safe from unexpected conversions?

I do share your concerns about implicit conversions, and that is why I mostly try to remember to make my single-argument constructors explicit. In general, the more dangerous implicit conversions are those that are between somewhat similar types (like different representations of the same thing, like std::string and C-style strings), and I have had problems related to that in …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Would anyone know what is meant by dynamically linking to qt libraries??

Well, this is just a matter of knowing what dynamic linking means. Take wiki for a start. As a quick explanation, let me start from the basics. You have some code. In a usual project, you'll have a bunch of cpp files and their corresponding header files (declaring what is in the cpp files). Normally, on a small project, you compile all the cpp files together into an executable. In reality, the compiler compiles each cpp file separately into object files (.o or .obj) which contain the compiled code for the code in each cpp file, then, after the compiler is done, the linker puts all the object files together and links all the function calls to their corresponding binary code. Well, on a bigger project, or when using external libraries, you often won't do that. Instead, you can compile a bunch of cpp files and put all the resulting binary code into a library, which is like a repository of precompiled code (functions, classes, etc.). You can use that code in any program if you have all the header files for that library, but you don't need the cpp files (where all the real source code is), you only need to tell the compiler to link the library into your project. Now, there are two kinds of libraries, static and dynamic. A static library is merely a bundle of object files, and when …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The compilation success is contigent on the fact that the compiler allows 0 to be implicitly converted to the pointer type DOMNode*. I'm not sure what is the standard behavior required here. In general, if you replace 0 with NULL, it should work, because NULL must be convertible to any pointer type, and for compilers that don't automatically convert 0 to pointer types, they define NULL as ((void*)0) which solves that problem.

In any case, you probably don't really want to allow implicit conversions of numbers into MyDOMNode objects. And since the only time you really want to compare a MyDOMNode object to a number is when you do either (node == 0) or (node != 0), in any other case, you would compare two nodes. A common trick to solve this problem is to create an implicit conversion to a bool as so:

class MyDOMNode {
  public:
    // ..

    operator bool() const {
      return mDomNode;
    };

  private:
    DOMNode* mDomNode;
};

Then, you can test your nodes with these expressions:

(node == 0)   becomes   (!node)
(node != 0)   becomes   (node)

That's a lot more convenient, isn't it?

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Here are some initial comments:

Style
Overall the coding style is OK, but a bit unusual. Naming functions like Pull_randWord is a bit unusual, but more importantly, it is not consistent with the rest of the code, you should pick one style and make it consistent. Then, using all upper-case letters for class names is a big no no. If there is one convention that you should obey to is that of reserving upper-case names for MACROs and #defines, every programmer will expect all upper-case names to mean that (like HANDLE, which is a #define).

Practical coding issues
The header-guard on a single line is weird, better make it like this:

#ifndef HANGMAN_H
#define HANGMAN_H

You use some non-standard headers, like <conio.h> and <time.h>, you should avoid conio completely and replace <time.h> with the standard header <ctime>

#include <iostream>
#include <fstream>
#include <windows.h>
#include <string>
#include <ctime>

Also, in your header file, you should avoid including headers that you don't need in order to complete the class declaration. The headers that you only need to implement the class functions should be included in the cpp file. As I see it now, the only headers that you need to complete the class declaration are <string> and <windows.h>. All the other headers, you should include them in the cpp file only, after the inclusion of your header file. This is a practical thing, it helps to avoid dependencies between header files and reduces compilation times, it's …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

starting names of all classes and variables of composit data types with capital and of base types with a small letter.

That is very odd indeed. The most important thing about coding conventions, is that they should be conventional. It's like with a standard, it doesn't matter as much how good the standard is, only that everyone adopts it. When it comes to coding style (indentation, CamelCase vs. camelCase vs underscore_separation, brace placements, line lengths, etc. etc.), most books on coding guidelines don't spend much time discussing this, for one good reason: it doesn't matter nearly as much as any of all the other things that you need to agree upon in a team project. As Sutter and Alexandrescu (two giants in C++) would say, "don't sweat the small stuff".

In any case, you do need to agree to a convention. And, in general, it is a good idea to conform to an already existing convention. There is absolutely no point in trying to come up with your own "best" convention, that's just a waste of time. A good convention is just one that everyone is used to and fairly comfortable with, and it also helps if it's simple (no rules like "if a data member is also mutable and a pointer to a const, then it should be prefixed with mpc" or something stupid like that).

In C++, there are a number of different conventions, partly because it is a multi-paradigm language and often, the programming paradigm …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The demand for good programmers is high, and is not likely to diminish anytime soon. The saying goes: "Good programmers don't starve." For example, I'm subscribed to some C++ developer groups on LinkedIn, and there are between 10-20 new job postings everyday, just for C++ programmers. Overall, salaries seem comparable to mid-range engineering jobs (around 50 k$ to 80 k$ per year).

Let me talk a bit about what I know.

Artificial Intelligence / Robotics
No idea about companies. The only thing that comes to my mind is Honda's ASIMO and Research.

The Asimo doesn't have much A.I. at all, most of its motions are scripted and/or remote controlled, and most of the intelligence in it (and there is a lot of it) is in the hardware design (mechanical and electronics) and in control software.

For the moment, there is much more job prospects in research (with AI, you could call it "intelligent robotics"). There are many companies that develop hardware and software for robotics directed towards university research. And then there is defense research (DARPA and the like in other countries). Currently, most private companies in this field are young start-ups, but there are a few bigger ones like Boston Dynamics (Big Dog, and Rumba), Quanser (mostly research-grade software tools), and Willow Garage (PR-2, X-8, and the ROS platform). But most of these companies look for people that have experience in AI and robotics, and that have an engineering background in addition to programming skills (because …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

It's a trade-off between speed and safety. Generally, in many places, C++ standard libraries and their implementations put the emphasis on speed. This is why many STL container functions do not have bounds checking (or they have it only as an assert condition), although there are bound-checked alternatives like the at() function in the std::vector. A good programmer, like myself, is generally able to program in such a way that out-of-bound conditions (e.g., accessing an element beyond the length of an array, or calling front() / back() on an empty queue) happen extremely rare, almost never (except for the occasional typo). This means that I would get almost no benefit from bound-checking, but I would have to suffer a strong performance penalty for it. The C++ standard committee decided that this was unacceptable, so they required that there be no bound-checking on most of the container functions (but allowing bound-checks as assert() conditions). But they could have decided otherwise (e.g., in Java and .NET frameworks you do get bound-checking on everything, but you also pay a hefty price in performance for that extra safety, but that is the design choice in these frameworks, and it does have its merits too, because safety is important).

This means, of course, that if you want bound-checking, you have to implement it yourself (or I'm sure there are libraries out there that can "replace" the STL containers with safer versions). BTW, if you want to just add bound-checks to the standard queue implementation, why …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If the program finishes and there is still memory that wasn't deleted, it won't matter. The memory gets allocated by a thing called the "heap", which is a part of the program (something the compiler generates for you). This heap is like a manager of memory, it allows you to allocate and deallocate memory (via new and delete). This heap gets its memory by asking the OS for it. When your program ends, the heap is destroyed along with all the memory that it is managing, so it doesn't matter if there is still some memory that wasn't deallocated (by deleting it in your program). As a double safety, if the heap is also corrupted (which can happen, depending on the system, if you ask it to delete memory twice or if you ask it to delete memory that it doesn't own or that wasn't allocated before), then destroying the heap at the end of the program might not be able to release all the memory that it requested from the OS, if that is the case, it won't matter either because the OS also keeps track of what memory was given to which program, and if your program ends (end of the process), the OS will reclaim all the memory that was allocated to it.

What you do have to worry about, however, is having memory leaks (memory that you forgot to delete) within a running loop. The effect of this is that the memory consumption will grow incrementally …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You need to delete every thing that has been allocated with new. It's as simple as that.

In practice, however, it can be complicate to ensure that nothing is left behind (undeleted). There are many techniques and guidelines to follow in order to help you with that. I wrote two lenghty tutorials on two aspects (or set of guidelines) that can help you, the first is on RAII and the second is on ownership relationships. They may be a bit advanced, but if you can ignore the more complicated things, and stick to the essentials, that is, make sure to use RAII classes as much as possible and use smart-pointers in a smart way. Also, by and large, you should prefer local variables (on the stack) as opposed to variables allocated with new.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, obviously, you can't hard-code the vertices into your program (your post almost made it sound like that is what you are trying to do). You must store the mesh (list of vertices and polygons) into a file that you can load and display. Or, you should generate simple geometric shapes, such as cylinders, spheres, cubes, etc. which is just a matter of computing vertices from a math formula.

You should look into Vertex Buffer Objects, this is the preferred way to render objects in OpenGL. Usually, for building a 3D model, you either load the vertex buffer from a file (of a standard format), or you generate the vertex buffer for simple geometric shapes, and then, you hand over that vertex buffer to OpenGL (via VBOs) and then you can render the model anytime with a simple OpenGL function call. The main problem here is that saving and loading 3D model formats (especially the more feature-rich and complex formats like 3ds) will require a significant amount of work by itself, so you should look for libraries that can do that for you, and at that point, you might as well use a library for all the rendering too.

Ogre3D is a pretty nice game engine that can load all sorts of 3D model formats and do nice rendering effects. Coin3D is another very good option (and implements to OpenInventor interface) which is easier and faster if you don't need fancy visual effects (it …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Congrats on your fourth grand-kid!

I'm really sorry to hear about your eye affliction.. I wish you the best of luck and success in treatments.

Being the robotic geek that I am, I have to mention this. Coincidently, a couple of weeks ago, I just attended this plenary talk (which you can watch on video) on intra-ocular micro-robotics to perform exactly the kind of interventions that you would need to treat Wet Macular Degeneration, in a way that is much less invasive and much more precise. I doubt that this technology would be ready within 5 years, but they are already doing eye surgery on rabbits and pigs with this.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Analogy: You are a thread. You're looking for a room in a hotel, which is the resource. Because you are not alone, there can be several people coming in and out of the hotel at unpredictable times. So, the question is, how do you make sure not to over-book the hotel? The answer is, you need a guy at the front desk keeping count of the number of people who checked in (and didn't check out yet), that's a semaphore. Of course, this requires that everyone is diligent enough not to go into a room without having checked in, and that no one forgets to check out, that's also true of threads when using semaphores.

A binary semaphore just means that the hotel has a total of 1 room. While a counting semaphore means the hotel has N rooms.

The problem is, if you only keep count of the number of people currently checked in, but you don't keep a record of who is assigned to which room, you get the problem that everytime someone checks in, you can't direct them to any particular room that is available. This is why the counting semaphore is not as useful, at least, by itself. There are some cases where it can be sufficient to just keep count (for example, when limiting the load on a system), but in many cases you need more than that (e.g., managing a resource pool), in which case you might use a counting semaphore as part of …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The errors are due to the fact that this assembly code is not real assembly code. This is just a simplified syntax to teach the logic of it. The actual syntax is quite a bit more complicated.

Here is the AT&T syntax that is equivalent to your program ("AT&T" syntax is preferred in GCC (used by Dev-CPP), the "Intel" syntax is the alternative often used by other compilers):

int main ()
{
    int a = 10, b = 50, res;
    asm(
      "movl %1, %%eax; \
       cmp %2, %%eax; \
       jb etq1; \
       jmp etq2; \
       etq1: \
       movl %2, %%eax; \
       etq2: \
       movl %%eax, %0"
      : "=r"(res)
      : "r"(a), "r"(b)
    );
    printf(" %d %d %d\n",a,b,res);
    return 0;
}

If you want to do assembly, you should read this tutorial, you will find the explanations of the code I just posted on that page.

I tested the above code (I use Linux), and it works and behaves as expected, so I guess you should be able to compile and run it too.

BTW, here is a shorter version that does the same thing:

asm(
  "cmp %%ebx, %%eax; \
   ja etq1; \
   movl %%ebx, %%eax; \
   etq1:"
  : "=a"(res)
  : "a"(a), "b"(b)
);
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

That program is equivalent to this:

if(A + B < 20)
  A = A + 5;
else
  A = A - 1;

Line-by-line, you have:

LOAD  A
ADD   B

Puts the variable A on the register, and then adds the value of B to that. So, it computes A + B.

CMP   20
JB    etq1

Compares the result of the previous lines (i.e., A + B) to the value 20, and jumps if the comparison results in a less-than case, that is, if A + B < 20. If not (e.g. "else") it computes this:

LOAD  A
SUB   1
JMP   etq2.

Which puts A on the register and subtracts one to that. Then, it jumps to label 2 (I assume that etq2 is an abbreviation for "étiquette 2").

If the comparison did yield a less-than case, then it executes this (at label 1) instead:

LOAD A
ADD  5

Which is obviously A + 5. And finally, in any case, at label 2, it executes this:

STORE A

which means that the current value of the register (either A + 5 or A - 1) is saved into the variable A.

En passant, deceptikon a raison, il vaut utiliser l'anglais, pour le bénéfice de tous.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There are a few issues with your code.

First, your ImplementCalculations function doesn't need to take those three parameters because they are already part of the class (and object). Also, you should probably name the function a bit better, like "ComputeOvertime" or something like that.

Second, you probably shouldn't call the display function from within the ImplementCalculations function. Keep things simple and separate. Call the ImplementCalculations function from the main function to compute those overtime hours and pay, and then, call the display function from the main function to list the employee information.

Third, to the main problem that you have. Summary information like Total_salaries, Total_hours, and Total_OvertimeHours should not be part of your EmployeeClass because they don't pertain to one individual employee. My recommendation is that you create a second class to store that information and implement the computation of those summaries in that class and also a display function for it. In other words, remove the three aforementioned data members from your EmployeeClass class and also, remove the Addsomethingup function. Then, create a class like this:

class WorkForceSummary {
  public:
    WorkForceSummary(EmployeeClass* employees, int employee_count);

    void Display();

    double total_salaries;
    int total_hours;
    int total_overtime_hours;
};

// ...

WorkForceSummary::WorkForceSummary(EmployeeClass* employees, int employee_count) {

  total_salaries = 0;
  total_hours = 0;
  total_overtime_hours = 0;

  for(int i = 0; i < employee_count; ++i) {
    // insert code here to sum up to employees[i].something
    //  and store those sums in total_salaries, total_hours and total_overtime_hours
  };

};

void WorkForceSummary::Display() {

  cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" << endl; …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you look at these two lines:

for (int j = 1; j <= i * i; j++) 
  if (j % i == 0)
    //..

The if-statement means that the iteration will only execute if j is a multiple of i. So, in combination with the for-statement before it, how many multiples of i do you have between 1 and i * i? Obviously, there are only i multiples of i between 1 and i * i. So, the two lines are actually equivalent to this:

for (int j = i;   // the first multiple of i is i. 
     j <= i * i;  // the last multiple of i is i * i.
     j += i)      // the next multiple of i is j + i.
  //..

Or, you could also write it as:

for (int l = 1; l <= i; l++) {
  int j = l * i;
  //..
};

which actually executes on i times, obviously. And because i is bounded by n, the complexity of that loop (merging the original for-loop and if-statement) is O(n).

So, using the above, we can reduce the for-loops to this:

for (int i = 1; i <= n; i *= 2)           // O( log2(n) )
  for (int j = 1; j <= i; j++)            // less-than O(n)
    for (int k = 1; k <= j * i * i; k++)  // less-than O(n^3)
      f=x*f;

From this, it is pretty trivial to …

thedarklord commented: Thank you very much, you helped me a lot +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Ok, so let's recapitulate what the program does. The program generates random numbers between 0-9 and records the number of times each specific number was obtained. To record the hit-count for each specific number, it uses an array called hits. The main loop generates N random numbers, each temporarily stored in the variable called r. For each sample, it increments the hit-count for the specific number obtained. Doing hits[r] accesses the hit-count associated to the specific number r. Doing hits[r]++ increments that hit-count. The variable r is only a temporary variable used within an iteration of the main loop.

At the end, the program outputs the number of hits for each specific number, and also the corresponding probability (normalized).

The point of the program is just to verify that the random-number generator is indeed uniform (there is equal probability for any number to come up).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yes. But there's a trap in the question. Pay attention to the if-statement:

if (j % i == 0)
thedarklord commented: I figured out that i is of base 2 like 2^l for example and th if statment is true when j is also of base 2 but in the inner is j*i so i don't know how to continue please help me +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The function rand_0toN1 returns rand() % n, in this case I believe that it's returning a random number from 1-10 because 10 was passed as an argument through n, which is not the same n that was declared at the beggining of the program but local to the function only. DId I get that part right.

Yes.

Secondly what's going on with these two lines?

The line hits[r]++; increments the hit-count for the value r.

The expression static_cast<double>(hits[i]) / (n / 10) simply computes the probability of getting the number i times the range, and from the number of trials that you did. If the random number generator is perfectly uniform, then this number should be very close to 1. Also, the cast in the expression is there to force the expression to be evaluated as a floating-point division, as opposed to an integer division (which would discard the remainder).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

but cstring can be used by all libraries?

C-strings are a built-in type. In other words, they are part of the programming language. C++ string is a library feature, defined in the header <string>. Built-in types can be used everywhere, without the need to include a library for them.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Calculating the complexity of an algorithm is really just a matter of figuring out how many times an operation will be done.

If you take the outer loop, for(int i = 1; i <= n; i *= 2), you can ask yourself how many iterations will be executed. If n = 8, then you'll iterations i = (1,2,4,8). If n = 5, then i = (1,2,4). If n = 13, then i = (1,2,4,8). You get the idea? The number of iterations will be the log in base 2 of n, or just log(n).

You can proceed like this for the inner loops, each time you must multiply the results.

For loops that have inter-dependent bounds, like for(int j = 1; j <= i * i; j++), where the bound of the inner-loop is dependent on the value of the outer-loop, you can simply take the upper bound of the outer loop and assume some constant factor. That is, in that loop, the upper-bound is i * i where i is at most n, so you can consider the upper-bound of that inner-loop to be a constant factor times n squared, as in C * n * n, and since we don't care about the constant factor, you can just say that it is O(n^2).

I'll let you figure out the rest, since I get the feeling this might be a homework question.

thedarklord commented: Ok thanks for you help +0
Sky Diploma commented: :) +8
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

but there's no further explanation why i must convert the it to cstring, anyone knows?

Yeah, I know. The reason is because of the original design of the libraries, in particular the iostream and the string library. Basically, they were developed more or less in isolation, and iostream came first. You will notice that the iostream library does not make use of C++ strings anywhere. The operations that you can do between iostreams and C++ strings are limited to functions that are defined by the string library (like std::getline() or the operator << and >> for strings). In other words, none of the iostream libraries include the string header. It was simply designed like that. And, obviously, if that is the case, the file-streams cannot take a C++ string as the file-name, and thus the conversion to a C-string.

why do i should use reference variable to pass a fstream object?

Such that the function parameter becomes an alias for the fstream object that was passed to the function. In other words, if you want the changes made to the fstream object within the function to affect the dataFile object in the main() function, then it must be passed by reference. Otherwise, if you don't pass-by-reference, the fstream object will be copied into the function, and when the function returns, the file will be closed as that local variable gets destroyed, and as for the dataFile object, it will remain completely unaffected (still empty).

i …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, you need to have a matrix that you need to invert. For a simple test program:

#include <iostream>

void printMatrix(double** M, int dim) {
  for(int i = 0; i < dim; ++i) {
    for(int j = 0; j < dim; ++j)
      std::cout << M[i][j] << " ";
    std::cout << std::endl;
  };
};

int main() {
  double** A = new double*[3];
  for(int i = 0; i < 3; ++i)
    A[i] = new double[3];
  // fill the matrix with values:
  A[0][0] = 3; A[0][1] = 4;  A[0][2] = 5;
  A[1][0] = 6; A[1][1] = 7;  A[1][2] = 8;
  A[2][0] = 9; A[2][1] = 10; A[2][2] = 11;

  std::cout << " A = " << std::endl;
  printMatrix(A,3);

  double** A_inv = gauss(A,3);

  // now, A_inv points to the inverse of A!
  std::cout << " A_inv = " << std::endl;
  printMatrix(A_inv,3);

  // never forget to clean up when you are done:
  for(int i = 0; i < 3; ++i)
    delete[] A[i];
  delete[] A;
  for(int i = 0; i < 3; ++i)
    free(A_inv[i]);
  free(A_inv);
  return 0;
};

Just a remark, if you didn't know how to call a function, or how to create such a matrix representation, then what are you doing searching to web for matrix inversion code? The learning process is a sequential process, you must get the basics first and build up from there.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You must transfer the data into an array (or vector) that you can use to manipulate the data. Then, you save the data back to the file, overwriting it. The rdbuf is really not meant for you to tamper with, and you certainly cannot use it to modify the content of the file. Not to mention that manipulating rdbuf would be very hard since it has basically not useful interface for that, e.g., you won't be able to insert, overwrite, or delete data at random places.

You can use the seekg / tellg facilities to move to certain reading position with the fstream which will allow you to read only the part of the file that is interesting, instead of loading the entire thing in memory. But that is about as far as it goes with manipulating the data using the fstream object. To be able to do more useful (and non-sequential) manipulations, you will need a more powerful random-access container, like std::vector or std::deque.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

please note that i am reading a file that consits of all characters (ascii 0-255) therefore i must use wstring instead of string..

I doubt that this is true. A normal character (char) is one byte in size, and it can represent 256 characters (many of which don't actually result in any printed character). To read the bytes correctly (and in order) from the file, you should not use the wide-char versions of fstream, stringstream and string.

the file reading is stopped upon the occurence of first null character. how can i stop this from happening?

You read the values using the rdbuf which is a raw reading method. So, I doubt that the actual reading of the file stops at the first null-character (or zero byte). My best guess is that the content of the stringstream get cut-off either during the conversion to a string or during the printing of the string to cout. In any case, you shouldn't use a string to store and manipulate an array of binary data (non-characters). Try to use a vector of chars instead:

#include <sstream>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<char> readfile(const char* filename)
{
    ifstream infile(filename,ios::binary);
    vector<char> result;
    copy(istream_iterator<char>(infile), 
         istream_iterator<char>(), 
         back_inserter(result));
    return result;
}

int main()
{
    vector<char> data = readfile("hello.exe");
    cout << data.size() << endl;
    return 0;
}

BTW, the main function must return an integer (zero if all went well), this is required by the standard.

Humayoon Khan commented: very well explained =) thanks +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This is not a program, it is a function. What it does is to compute the inverse of a matrix through a Gaussian elimination. The implementation itself is very naive, meaning that it is inefficient, numerically unstable, and also programmed in bad style, not to mention that this is basically in C.

The function first allocates the memory for the resulting matrix. Then, it initializes the resulting matrix to the identity matrix (as the right-hand-side of the linear system of equations). Then, it does a number of row reductions in order to end up with an upper-triangular matrix. And finally, it performs a back-substitution to obtain the inverse matrix.

I suggest you read up on Gaussian elimination algorithm, because this function is a pretty straight-forward implementation of it. If you understand Gaussian elimination, you should have no problems understanding that function.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Basically, the difference between a mutex and a binary semaphore is that the semaphore is a more general mechanism which makes it somewhat less appropriate to do the same job as a mutex (although I guess it might be faster on some implementations).

Because you can have semaphores that carry any integer count (not just 0 or 1), it is intended for managing a resource pool with limited capacity. The general scenario is that multiple threads can increase (lock) the semaphore when they need to, and decrease (unlock) it when they are done, and if the semaphore reached its max-count when a thread attempts to lock it, that thread will have to wait. To keep things simple, the OS doesn't keep track of which threads currently have a lock on the semaphore and which don't, because if it did, it would be just like having a number of mutexes instead of one semaphore count. It's just a simpler (but sufficient and efficient) mechanism under-the-hood.

The (unfortunate) consequence of this simplicity is that the OS cannot guarantee that if a thread unlocks a semaphore, that that thread actually had locked it before, and vice versa. It is up to the programmer not to make such a mistake.

So, if you use a binary semaphore, you basically get a mutex, without the guarantee that only the thread that locked the mutex will be the one unlocking it. But, generally, if you code things correctly, it isn't hard to make sure that you …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You have a massive memory-leaking loop. No surprise that it crashes your system. In the loop inside main, you allocate B objects and never delete them. This is a more correct loop:

for(int i = 0; i < 1000000; i++)
{
    A* obj = new B();
    obj->foo();
    delete obj;  // this line is very important!
}

Also, when you need a temporary object only for the span of an iteration, you should just use a local variable, that is the favored mechanism in C++:

for(int i = 0; i < 1000000; i++)
{
    B obj;
    obj.foo();
}

Finally, DO NOT forget to make your base-class destructor virtual!!! This is very important to make sure that the most derived class destructor is called when you delete the object via a base-class pointer.

virtual ~A()
{
    cout << "ADest\n";
    delete b;
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, strictly speaking, from the OP's question, there is not implication that the value-type of the array is an integer, only that it is constructible or assignable with an integer value. So, there is a slight chance that the non-POD case is relevant. Also, to me, it seemed like the relevant part of the question was on how to assign an entire sub-array (or sub-array-of-array) without having to do two nested loops to assign each individual element, so I thought it would be salient to include a general solution to that problem.

And, of course, for a POD type (like int) the memcpy solution is totally fine, given that you are aware that it does not apply to non-POD types, a fact that is relevant to point out. When applying such a method, there is a fine line between doing so because you know that it is OK in this particular case, and doing so because you think it is the general way to do it. I, like deceptikon, don't want the OP to be mislead into the latter category.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The library to do this is called winsock. This is a standard Windows library and it is usually installed with any compiler you have and is also pretty simple to use. You can following this msdn guide to get acquainted with the library.

If you have any more specific questions about it, you're welcome to ask!

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yes, definitely, for ease of use in the future, the OP should not rely on a static array, but create, instead, a vector/matrix/tensor class for his particular purpose. Or, at the very least, rely on a more practical static-size array representation, like std::array, if available to him.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

That's a good point deceptikon, do you have a solution? I do, of course, but it gets tricky.

Of course, you can't use memcpy and expect well-defined behaviour for any non-POD type. You can manage to force an element-wise copy-construction into the destination array by the following trick:

template <typename T>
void initializeArray(T (&arr)[5][4][3]) {      
  for(int i = 0; i < 5; ++i) {
    // create a local aggregate struct that you use to represent sub-arrays:
    struct local_sub_array {
      T data[4][3];
    };
    // create your static const sub-array:
    static const local_sub_array rhs = {{{4,2,6},{4,5,2},{5,3,6},{3,1,5}}};
    // use the placement-new and the copy-constructor of the local class to force
    //  the use of element-wise copy-constructors if they are needed (non-POD):
    new( (local_fixed_array*) &arr[i] ) local_sub_array(rhs);
  };
};

The placement-new operator is very often used as a "constructor-calling memcpy replacement", but that is usually a bad idea. There is a big flaw in the above solution because the array is already constructed when you attempt to overwrite it with copy-constructed elements. You can't overwrite a constructed object, you need to destroy it first. In other words, you'll need to add this part:

template <typename T>
void initializeArray(T (&arr)[5][4][3]) {

  for(int i = 0; i < 5; ++i)
    for(int j = 0; j < 4; ++j)
      for(int k = 0; k < 3; ++k)
        arr[i][j][k].~T();       // call destructor on each element.
                                 // NOTE: Don't attempt to reproduce this at home.
                                 // This was done by a trained professional (me!).

  for(int i …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

A) Does it already exists?

No. Unless you are working on a very unusual platform that has a native word size of 3 bytes (most systems have a native word size of 4 or 8 bytes, and some really small embedded systems might use 2 bytes natively).

B) If not, am I kinda on the right track for writing a class to fill the sweet spot between short int and int?

No. The processor will not be able to deal with a 3 byte integer value, you will have to put it into a 4 byte integer variable if you want to do anything with it. Also, even if you make a class that stores the 3 bytes individually, there is little chance that size of the object will actually be 3 bytes, because most compilers will add padding in order to align the size of the object to the native word size of the system (this is a fundamental optimization that all compilers will do).

but for a large data set this wastes a lot of space

Sure. If you store many numbers using 4 bytes when 3 bytes would do just fine, then you get a 33% increase in the memory used. But, if you try to pack all the numbers such that they each use only 3 bytes, I can't even imagine how horribly slow your program will become. The additional memory expense is worth the performance gain from using native …

Jsplinter commented: Solid explanations! +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If I was able to travel back in time, I would probably also be able to travel very large distances instantly. I think I would travel back to a long time ago in a galaxy far, far away....

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Just an update on this.

This program by Dell didn't last very long. Word has it that MS came down hard on them. Considering that the profit margin of Dell is directly tied to how good a deal they can make with MS to buy the Windows installations for their PCs, this is not surprising at all. Clearly, at some point, some Dell people thought it would be a good idea to offer Ubuntu, because I can imagine they got many consumer requests to do so, so, naturally, they did as any sane company would, they tried to offer what their customers wanted.

Today, I checked around the Dell website a bit. They do not offer any Ubuntu pre-loads on the "customize it!" processes for any computer they sell. However, they do mention, for some models, that you can get the computer with Ubuntu pre-load (or none at all, I would imagine too), if you call them and make a special order for it (I don't know if it actually comes to be cheaper at the end). Btw, they only mention the Linux availability for a few models, mostly the high-reliability models like Precision, Vostro, OptiFlex, etc. (small-server, business or scientific computer models). I don't know if it is available for any laptop models.

Furthermore, since Windows 7, Microsoft has changed their refund policy. Before, you could by a new computer (with Windows pre-installed), then boot it up to the Windows installation screen and decline the license agreement (i.e., "I …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

you know something like a warning after your trial version of some thing has expired...?

This can simply be done by recording the installation date somewhere (in the registry, install directory, or somewhere else), preferrably encrypted, and checking that date against today's date everytime the user runs the application (and regularly while it is running, if you expect them to run your application continuously for days). But that will only allow you to warn the user as he starts the app, and block the app if the period has expired. If you want a "reminder" to pop-up on its own (independent of the application being used) when the expiration date comes close, then you should use the task scheduler of Windows (something like checking daily for a comparison between the recorded installation date and today's date, and warn the user if he is within 5-10 days of the expiration date).