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

I think we largely agree on this topic. When I look at your example C code, I see a generalized effort to keep variables as locally scoped as possible, within bounds of reason. It's style is in complete agreement with the guideline, at least, the way I see it, which I think is essentially the same as you. Code like the one you linked to (formatted I/O, parsing, etc.) does require things like tentative variables, flags, lots of switch-case style coding, etc. In this realm, the paradigm of "here are the variables I'm playing with, and here is the code" is a natural one, but even then, you still show evidence of trying to limit the scope, which just proves my point.

I don't know what you think I mean by declaring variables where they are first needed. That C code obeys that guideline, in my book. What I see are things like:

  1. Declare a few variables that will store the results of a loop.
  2. Run the loop (with locally declared variables that are needed only per-iteration).
  3. Inspect / return the result based on those variables.

So, those variables that appear at the start of the loops (which I presume is what you are pointing to, since all other variables in that code are declared directly on-site of where they are needed) are being declared and used at exactly the time and scope at which they are needed.

I'm not advocating for an obsessive compulsion to declare variables at …

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

You must move the contents of DoubleLinked.cpp into DoubleLinked.h, and move the contents of Node.cpp into Node.h. As I said, you cannot have the function definitions in a separate cpp file, they must be in the header file.

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

Are you referring to Job Scheduling or CPU Scheduling?

For the former, there isn't much to say, it's what the cron tool does, and it isn't particularly challenging or involving any special algorithm or anything.

For the latter, however, what you'd want to look at is the Completely-Fair Scheduler and the Brain F$ck Scheduler. This is much more in-depth of a topic, it's the nerve-center of Linux. I would focus on that latter scheduler, if only for the opportunity to use the f-word repeatedly in a college paper.

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

The problem here is that you cannot separate the definition and declaration of templates (class or functions). You have to understand that template code is not "real" code, it is a set of precise instructions for the compiler about what code to generate once the template argument(s) have been provided. Since source files are compiled separately (in isolation from each other), you cannot put the definitions (implementations) of the function templates in a separate cpp file, that is, one that is different from the cpp file in which the template is used (with some argument(s)). This is why you get all these errors. The cpp file in which the main() function appears, in which the class template is being used, does not contain any of the implementation code of that class template. So, the compiler cannot generate code for that specific instantiation of the class template, so it is left to assume that there was one already compiled (in another object file). At this point, the linker takes over and tries to find the definitions of those functions. However, when you compiled the other cpp file (with the definitions of the function templates), there was no instantiation of that class template, so no "real" code to compile, so, nothing to be found by the linker, and hence, the avalanche of "undefined reference" errors (which means the linker didn't find what it was looking for).

So, long story short, the definitions (implementations) of you class template's member functions must appear in …

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

declare your variables as close as possible to where you first use them

That's debatable.

Well, I don't mean that you should give the death penalty to those who don't follow that guideline. It's a very minor offense to good style. In other words, it's good to foster the habit of declaring variables as locally as possible, but I don't mean that you should go back and refactor all your code to bring it on par with that guideline.

And if you want to debate the issue, take it up with Herb Sutter, Andrei Alexandrescu and Bjarne Stroustrup. Not that I wouldn't have arguments of my own on that subject, but they've made better cases for this guideline in the past than I could.

don't create variables with uninitialized values

Also debatable.

Ditto.

"Antiquated" isn't synonymous with "bad",

Yeah, that's exactly why I used the word "antiquated" and not the word "bad". I meant antiquated in the sense that it is a relic of the past, an outdated practice. I guess you could say it's one kind of "bad", but I prefer the more precise term "antiquated" because it conveys what I mean. If you want to argue that antiquated isn't necessarily bad, well, maybe not always, but I didn't say "bad", so you're barking at the wrong tree.

It's an outdated practice because it came from the earlier days of programming when stack-growth limitations (i.e., when they can occur) …

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

Do you have a specific question?

Otherwise, here are a few remarks on your code:

  • You are using pre-standard headers like <iostream.h> and <math.h>. These shouldn't be used today (as in, not since 15 years ago). You should use <iostream> and <cmath> (all C++ standard headers don't have the .h, and all those taken from C (like math.h, stdlib.h, stdio.h, etc.) also omit the .h and are prefixed with the letter c).
  • The conio.h header is not standard and is certainly not guaranteed to be supported anywhere, although some popular C++ compilers in Windows do support it still today. There is no reason to use it here.
  • Since standardization, all standard library elements (classes, functions, objects ..) are in the std namespace. This means that accessing cout for example should be done by either writing std::cout everywhere you use it, or writing the line using std::cout; in the scope in which you are going to use it, or writing the line using namespace std; in the scope in which you are using cout and other standard library components.
  • The main() function is required to return an integer value. The two acceptable, standard forms for the main() function is either int main() { /* ..*/ }; or int main(int argc, char** argv) { /* .. */ };. The return value should be 0 if the program executed correctly, and something else otherwise.
  • Your formatting of the code is quite ugly. Indentation is important, and spacing out the code is too. In …
deceptikon commented: Nice. +12
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The viewport is the rectangular area on which pixels can be drawn. This is usually defined as a corner offset (position of the lower-left corner, i.e., the origin) and a width and height (watch out: some GUI systems or libraries will use the upper-left corner as the origin instead, meaning the y-axis is pointing downwards). GUI systems are all about embedding things into others, and thus, viewports are always relative to a specific context which has limits of its own. In Windows, these contexts are called Device Contexts (or DC) and things like a window can provide a DC (or multiple partitioned DCs) on which other things can be drawn (buttons, menus, etc.). When you have something like a QPainter, it resides on a DC given from its parent window / widget and that bounds its area on which things can be drawn, it then uses part of it (maybe) to draw some borders or whatever and exposes whatever is left as a canvas (or a surface on which to draw things). Then, there are usually good reasons to want to create different rectangles to draw on, at least temporarily, and these are viewports. Normally, you set the viewport to one place (and size), draw some stuff, then move the viewport elsewhere (with new size) and draw some more stuff. So, the viewport is usually this area of the device context (or rendering context) in which you are currently drawing things (and clipping things).

Clipping is the act of removing …

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

Because they're not wearing a parachute.

Can a whale drown?

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

Well, there is a typo on this line:

vidfeat: libopensift.a videofeatures.cpp
    $(CCP) $(CFLAGS) $(INCL) videofeatures.cpp -o $(BIN_DIR)/$@ $(LIBS)

where it should read as:

vidfeat: libopensift.a videofeatures.cpp
    $(CPP) $(CFLAGS) $(INCL) videofeatures.cpp -o $(BIN_DIR)/$@ $(LIBS)

i.e., $(CPP), not $(CCP).

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

There is also an implementation of the filtered_iterator as part of the Boost.Iterator library. This one is generic to any predicate (a function object that determines whether an element is valid) and skips any element that doesn't satisfy the predicate. This might be an easier off-the-shelf thing to use if you don't want to implement this yourself.

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

Because he's a jolly old man.

Why does a dragon wear a yellow shirt?

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

Because you know how to extrapolate.

Why do birds have feathers?

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

Because the bird stole his fish.

Why do auctioneers speak so fast?

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

What about a filtered iterator?

Here is what I mean:

template <typename BaseIterator, typename OutputType>
struct ActorIteratorImpl {
  public:
    // the set of required typedefs:
    typedef ActorIteratorImpl<BaseIterator,OutputType> self;
    typedef OutputType* value_type;
    typedef OutputType* const & reference;
    typedef typename std::iterator_traits<BaseIterator>::difference_type difference_type;
    typedef OutputType* const * pointer;
    typedef input_iterator_tag iterator_category;

  private:
    ActorFlag required_flag; 

    BaseIterator cur_it;
    BaseIterator end_it;

    // this function seeks the next valid base-iterator
    void seekValidIterator() {
      while(cur_it != end_it) {
        OutputType* tmp_ptr = dynamic_cast<OutputType*>( *cur_it );
        if((tmp_ptr) && (tmp_ptr->hasFlag( required_flag )))
          break;
        ++cur_it;
      };
    };

  public:

    // constructor (not to be called directly by user).
    ActorIteratorImpl(ActorFlag aRequiredFlag, BaseIterator aCurrentIter, BaseIterator aEndIter) :
                      required_flag(aRequiredFlag), cur_it(aCurrentIter), end_it(aEndIter) {
      seekValidIterator();
    };
    ActorIteratorImpl() : required_flag(), cur_it(), end_it() { };

    // define an equal operator for the base-iterator:
    friend bool operator==(const self& lhs, BaseIterator rhs) { return (lhs.cur_it == rhs); };
    friend bool operator==(BaseIterator lhs, const self& rhs) { return (lhs == lhs.cur_it); };
    friend bool operator!=(const self& lhs, BaseIterator rhs) { return (lhs.cur_it != rhs); };
    friend bool operator!=(BaseIterator lhs, const self& rhs) { return (lhs != lhs.cur_it); };

    // then, the standard iterator operations:
    self& operator++() {
      ++cur_it;
      seekValidIterator();
      return *this;
    };
    self operator++(int) {
      self result(*this);
      ++(*this);
      return result;
    };

    friend bool operator==(const self& lhs, const self& rhs) { return (lhs.cur_it == rhs.cur_it); };
    friend bool operator!=(const self& lhs, const self& rhs) { return (lhs.cur_it != rhs.cur_it); };

    value_type operator*() const {
      return dynamic_cast<value_type>(*cur_it);
    };
    value_type operator->() const {
      return dynamic_cast<value_type>(*cur_it);
    };

};

Note that you could fairly easily make …

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

Because you're humble, and would never brag about how awesome you are...

Why do cars have four wheels?

TnTinMN commented: mine has 5 wheels +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Because coffee (also made from beans) is not a vegetable.

Why are flamingos pink?

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

"I always wanted to kick a duck up the arse." -- Karl Pilkington

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

Because he's not TheTinMaN.

Why do none of the flightless birds whistle?

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

I guess it could make sense. I would certainly like that, as I can provide some help in that domain, and am interested in that in general. I don't have the patience to watch the C forum anymore, just on the off chance that an interesting embedded systems question comes up. I think what would make most sense is a topic under "Hardware & Software" and call it "Embedded Systems" or "Embedded Development" or something like that. The point is to not make the title too Arduino-focused or too programming-focused, or even too uC-focused. Embedded system development is really the intersection of micro-controller programming, low-level hardware issues (setting registers, interrupts, GPIOs, etc.), and electronics. They all go hand in hand. For programming that is more removed from hardware, but still constrained, the C / Assembly / Legacy forums are good. For micro-Linux configuration stuff (like setting up or troubleshooting a Raspberry Pi), the Linux / Unix forum is good. But there are things that don't fit anywhere, like this recent thread on the C++ forum.

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

If the interviewee chose to be offended and filed a lawsuit, I can all but guarantee that they'd win on grounds of sexual harrassment and/or discrimination.

Wow, good to know, I'll watch my back more carefully next time I'm in the US (not that I don't already). In most places, such a lawsuit would be labeled as frivolous and be dismissed with prejudice (or worse). You can't just point your finger at someone and expect the courts to indulge you, nor can you conflate a subjectively inappropriate question into an accusation of sexual harassment or discrimination. I guess the US courts have a much lower threshold on that, I guess that's why Americans are so quick to sue. Also, there is a big difference between winning a case in court for damages / trauma (which requires the establishment of a civil tort), and something being illegal (i.e., a crime), e.g., having to pay damages for a car crash that you caused doesn't mean that having a car accident is illegal (it means you are responsibly for the wrong-doing, but the wrong-doing is not illegal).

I doubt very much that a US criminal court would convict a person of sexual harassment (an illegal act) for asking this question. Sexual harassment has to be either a coersive request for sexual favor (coersion by force, power, favor, etc.) or relentless and repeated innuendos or inappropriate comments, this case doesn't even come anywhere close to that, and generally a one-time incident (a …

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

describe algorithm how can you do so, while ensuring that no STD is passed around?

The more appropriate version of the exact same question is this:

You have three very dirty surfaces to clean but only two handkerchiefs. Assuming you cannot fold the handkerchiefs, how would you go about cleaning all the surfaces without getting your own hand dirty?

The answer is that you stack the two clean handkerchiefs for the first surface, then remove the dirty one and set it aside for the second surface, and then you take it again, flip it and stack the two handkerchiefs with the dirty sides facing each other, and clean the last surface. Then, you end up with three clean surfaces, three dirty sides of a handkerchief, while your hand remained on the same (still clean) side of one of the handerchiefs.

(I'll let you figure out how this solution translates to the original question, not particularly nice to describe in words)

This certainly requires some algorithmic thinking, and in that sense, is a reasonable interview question, however, the context chosen for the question is quite inappropriate. Possibly making the interviewee uncomfortable is not a good way to conduct an interview, you want the interviewee to get uncomfortable only if his lack of competence is exposed, not his personal reservations at discussing sensitive topics.

Clearly not an interview question as such a question would be illegal (in both your country and mine).

Illegal? Really? It's a stupid context …

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

i've been looking more into kd-trees and they all use pointers to parent nodes which is what i thought a linked list was...

Well, Kd-trees are, first and foremost, trees. So, yes, they are naturally expressed as linked-list-style structure: each node has a parent pointer and a few (2 or more) pointers to children nodes (with the exception of the root (no parent) and the leafs (no children)). But take this with a grain of salt. When you read descriptions of the structure or the algorithms (insertion / deletion, etc.), they will often assume this kind of linked-structure, and you will probably also see that in example implementations (or pseudo-code). That doesn't mean that it should be implemented exactly in that way. There are many ways to actually implement a tree structure (especially with fixed branching factors), and a linked-structure (i.e. pointers to parent-children) is usually the worst way to do it, but it is also the easiest to use in pseudo-code / examples. Unfortunately, some (or many) are misled into thinking that the pseudo-code or the explanation of the algorithm / data-structure actually corresponds directly to how it is implemented in real life. In this domain, these types of explanation must be regarded more as if someone told you "it has a metal frame, two wheels, a set of pedals, and a handle bar" as a way to instruct you on how to build a bicycle. In other words, there are lots of additional implementation details and …

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

the linked list would point to what's above, below, left, right, previous and next, with this it would be i think fairly easy to move objects around inside the map by jumping from node to node.

Linked-lists perform extremely bad for any kind of traversals. It might seem "easy" to move from node to node, but easy doesn't mean efficient. There are ways to implement a linked-list for efficient traversals, but that's also really hard and rarely worth the trouble.

for computer and player controlled objects i was thinking of just dividing there location by the size of each block globally and locally to get the position though i'm not sure of the computation overhead from a lot of division operations.

This is basically what a Kd-tree is, or similarly, an Octree / Quadtree. A simple solution that could be a good start would be to do a coarse Kd-tree partitioning, i.e., recursively divide the space only up to some coarse resolution, and store an array of objects inside each area. That would make the array of object in local areas quite small, meaning that dealing with them is easy and quick. And because the final division is coarse (not too small in volume), objects won't tend to transfer from one area to another too often, reducing the amount of maintenance to do (remove an object from one area and insert it in another). This certainly won't be optimal or anything like that, but it will …

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

This sounds like a space partitioning tree. I'm guessing it has something to do with collision detection. In any case, as rubberman said, this is far from being a trivial problem in which picking an STL container is not sufficient (you need something much more elaborate than what the STL can provide off-the-shelf), and, in addition, picking a correct storage strategy (within a more elaborate space partitioning tree) will not be a trivial task either.

The main concept that you must get acquainted with is the concept of "locality of reference" (aka "memory locality"). This is what can make or break a space partitioning structure (and, more generally, any search tree structure). The idea is as follows: the memory accessing patterns that characterize your main tasks (e.g., look-up, nearest-neighbor, etc.) must map well to your underlying storage such that traversals are reasonably sequential and operations are reasonably localized in physical memory. The point is that if you randomly jump back and forth in memory, you are maximizing the amount of cache misses, which, in turn, completely dominates the performance (or lack thereof) because one cache miss is roughly equivalent to a couple of hundred clock cycles (instructions). For example, if every distance computation (between a query point and a node of the search tree) takes about 20 instructions to compute, then having a cache miss at every new node visited is going to make the performance about 10 to 20 times worse than what you could get with …

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

However, I'm wondering if this type of response is actually counter productive with regard to the ultimate goal of this site which is to generate revenue.

It definitely is counter productive. I don't know much about search engine algorithms but I would certainly imagine that they try very actively to filter out any sites that are just link relays. At least, some years ago I remember it was much worse when you did a search and half of the pages coming up were other search-like sites or phony forums with links (or not) to other sites, often not any better, and so on, until you eventually found some original content. Now, this is a thing of the past. I imagine there are strong rejection criteria for sites that seem to act only as a hopp to other links, given traffic analysis of those sites. That's why the market of such sites (attract traffic with links, make money with adds) seem to be disappearing (no longer attract traffic due to SE filtering them out), which is a very good thing and promotes original content.

The problem with questions that could simply be googled is that there is no good way to answer them. If you leave it unanswered or simply say "just google it", then that will be frustrating to anyone finding this discussion from google, they will come and go really quickly and that will work against search-ranking of Daniweb. If you give some short answer with some …

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

From what I understand, making an SDR out of a TV tuner relies on two things. First, the electronics on the TV tuner chip must be wide enough (in bandwidth) to be interesting, meaning that its RF filtering front-end must be reasonably wide, and the DSP chip must be fairly fast. This is kind of guaranteed by virtue of the fact that a TV tuner needs this kind of speed and front-end filtering to be able to tune to a wide array of TV signals. Second, the DSP chip on the TV tuner must be hackable, and reasonably rich in functionality too. I believe that the RealTek chipsets are more popular for that exact reason, although I'm no expert in this. These are things that can vary a lot between manufacturers:

  • The operating system running on the DSP chip, if any at all. This is usually a micro-Linux system, with varying degrees of usability (i.e., how "reduced" the environment is, as it can often reside somewhere between micro-Debian release and a barebone custom Linux build of a few MB in size). But it might very well be that there is no operating system at all, just a flashed program, in which case the protocol to communicate to it will usually be proprietary and would need to be reversed engineered by lots of poking and probing on xterm.
  • The availability of options in the DSP filtering implementations. Some manufacturers might just flash a fixed simple DSP program with virtually no options …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I notice that add() got broken in your changes. It just traverses the (probably nonexistent) path rather than adding keys where they don't exist. You'd end up dereferencing null pointers unless new nodes are added at the right places:

Yes you're right. I originally re-wrote the code with a by-value storage of the nodes, in a std::map<T,node>. Until I realized that it wasn't standard-compliant to assume that an incomplete type could be stored in an STL container, although many implementation allow it (because it is certainly possible to implement STL containers that allow incomplete types, but the standard doesn't require it). So, I went back and changed it to unique_ptr, with rather ugly effects, including that bug, which wouldn't have been one if the nodes were stored by value. I guess this is a legitimate case for wanting containers to contain incomplete types, it would save one level of indirection and one level of new-allocated memory, both of which are a big deal in a tight loop.

Btw, you, again, introduced three map lookups where only one is needed:

template <typename String>
void add(const String& s) {
    auto it = &root;
    // Traverse the path and extend it as necessary
    for (auto c : s) {
        // lookup / create the node for the character c:
        it = &( (*it)->link[c] );
        if (!(*it)) {
            // it didn't exist yet, so, create it:
            (*it) = std::unique_ptr(new node());
        }
    }
    (*it)->terminal = true;
}

For this class, …

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

Is there any reason at all for using a shared_ptr<node> for your links? Why not use a unique_ptr<node>? Why incur the extra memory payload and overhead. It seems to me that the following would be a bit simpler (and smaller, and faster):

#include <map>
#include <memory>
#include <stack>
#include <limits>
#include <iterator>

template <typename T>
class trie {
    struct node {
        std::map<T, std::unique_ptr<node> > link;
        bool terminal;
    public:
        node(): terminal(false) { }
    };

    std::unique_ptr<node> root;
public:
    trie(): root(new node()) {}

    typedef std::size_t size_type;

    template <typename String>
    size_type match(const String& s, bool require_terminal = true) const
    {
        // Follow the path until the end of the string or a mismatch
        auto it = &root;
        for(auto sit = s.begin(); sit != s.end(); ++sit) {
            auto lit = (*it)->link.find(*sit);
            if(lit == (*it)->link.end())
                return std::distance(s.begin(), sit); // Return the index of the mismatch
            it = &( lit->second );
        }

        if (!require_terminal || (*it)->terminal)
            return std::numeric_limits<size_type>::max(); // The path was matched completely

        return s.size(); // Return the index of the mismatch
    }

    template <typename String>
    void add(const String& s) {
        auto it = &root;
        // Traverse the path and extend it as necessary
        for (auto c : s)
            it = &( (*it)->link[c] );
        (*it)->terminal = true;
    }

    template <typename String>
    void remove(const String& s) {
        auto it = &root;

        // Store the reversed path
        std::stack< decltype(it) > bak;
        auto sit = s.begin();
        for (; sit != s.end(); ++sit) {
            bak.push(it);
            auto lit = (*it)->link.find(*sit);
            if(lit == (*it)->link.end())
                return; // no match! nothing to remove! …
deceptikon commented: Thanks for the feedback! +12
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Definitely, I have to say it was an internship some years back. I worked in a lab (at Uni Duisburg-Essen) where they had a roller-coaster seat mounted to the end of a Kuka KR560 industrial robotic manipulator (about 600kg payload capacity), similar to the robocoaster systems. My job was to do some testing and fine-tuning of the control software for that robot and model its dynamics, but at one point, my supervisor just asked me to imagine the craziest rides possible as demos to impress visitors to the lab. I spent a two weeks doing that, and it was really cool.

I wish I had an actual video of this, but this one should give you a good idea of what I'm talking about (although they used an ABB one) (N.B.: we weren't as crazy reckless as the people in that video, we actually cared for safety regulations, not like these idiots).

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

(try and find a company that starts with !) :) ha ha

I found one (providing learning material for the !Xhosa language). Not an exclamation mark, but an alveolar click. (At least, I don't cheat!):

!Xhosa Fundis

TnTinMN commented: good job, I searched for 1/2 hour to no avaiil +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Unfortunately, byte alignment is an issue here. This means you cannot just send the structure, you have to fill in the individual members into a buffer. Byte alignment means that if, for example, you have a 64bit system with a native word size of 64bit (8 bytes), then the compiler might arrange you structure as so:

|     64bit     |     64bit     |     64bit     |     64bit     |
| 32bit | 32bit | 32bit | 32bit | 32bit | 32bit | 32bit | 32bit |
| time  |  pad  |      LAT      |      LONG     | ALT   |  pad  |

Where "pad" is for "padding", which are basically holes in the memory (with garbage data), which are there in order to keep data such as those double variables in proper alignment (not split up across two 64bit sections). On a 32bit architecture, you would probably not have this padding. And even on 64bit architectures, it might not even have the padding either (still have native 32bit word sizes). And, at the end of the day, it is also up to the compiler to decide what's the best alignment to use. In other words, you cannot really be sure of it. And code that tries to override the compiler's or platform's wishes in terms of alignment is going to be tedious to write and probably worse in performance.

So, I find that the easiest method to create a buffer for the data is to just use an std::string, like I showed in my previous …

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

For a very technical answer:

which one should be preferable from the following two nested for loops:

The one that results in the most predictable and contiguous memory accessing pattern, to minimize cache misses and maximize pre-fetching.

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

but I have little experience with bigger projects so I'd probably run into a few problems with maintenance. Considering that I'm interested in programming as a career, I have to get started somewhere. Regrettably it seems the majority of tutorials are not about honing skills. Most of them give basic theory and leave me without the experience necessary to accomplish larger projects.

It's a good thing to think ahead and anticipate what problems you might have and what things you will need to have / to learn. But don't be overly cautious either. What doesn't kill you makes you stronger. Like many programmers, my formative years in programming were a long sequence of failures. I did some cool things that were fun and with some success, but most of my projects ended up at a dead-end because my code was getting unmaintainable, or because of architectural flaws that just couldn't be resolved without a full re-write. But every new project was a huge improvement over the previous one. For some things, there just aren't any good substitutes for learning by trial-and-error. You can read books or attend lectures on software engineering, coding practices, software development methodology, and such, but without experience (and failures) they will, at best, get you to think about it a little bit, but you're unlikely to remember much of it when you're coding. But with experience, those same lectures / books will make you jump from your seat going "Ahh! That's why I had …

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

Actually, the words that finish with "ally" are basically all essentially and factually annoying. Basically, I am trying to gradually stop using them practically, but actually, it's hard. Essentially, speaking adverbially might sound fancy, but actually, it's annoyingly crappy, really.

TnTinMN commented: Actually, you have essentially made a factually good point! :> +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

In C++, every cpp file is compiled separately, and then linked together. When the functions appear in the same cpp file as the main() function, then it is compiled together and doesn't need linking. When the functions appear in a different cpp file, then all the compiled cpp files (compiles to .o or .obj files), including the one with the main() function, must be linked together. In order to be able to use the functions from any cpp file, a function needs to be declared in the cpp file in which it is used, usually through the inclusion of a header file that declares a set of functions.

Here is a simple example (hello world):

In hello.h:

#ifndef HELLO_H
#define HELLO_H

// This is a declaration of the function:
void printHelloWorld();

#endif

In hello.cpp:

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

// This is the definition of the function:
void printHelloWorld() {
  std::cout << "Hello World!" << std::endl;
};

In main.cpp:

// include the header file for the function:
#include "hello.h"

int main() {

  // call the function:
  printHelloWorld();

  return 0;
};

Then, you must compile both cpp files and put them together. In an IDE (like Visual Studio or CodeBlocks), you need to add both cpp files to the "project" and build it. If using a compiler like GCC using the command-line, you need to do:

$ gcc -Wall -o main main.cpp hello.cpp

which has the effect of doing the following steps:
compile …

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

Let me get this straight. You want to demodulate IF signals digitally from a Windows PC? Isn't this sort of insane? IF signals are usually around 20 to 100 MHz in frequency, depending on application, meaning that your analog-digital converter would have to run at about an order of magnitude faster (0.1 to 1 GHz). Such an ADC unit, as a raw chip (SMD), would probably retail for about 300$, and as a proper PCIe board (and well insulated for EMI), would be a few thousands. Your typical TV Tuner will have a clock in the 16 to 32 MHz range, and does most of its filtering and demodulation before ADC occurs. What you can do, is adjust the TV tuner's filtering and demod (that's called "tuning"), and stream the data directly from the ADC sampling to your PC for further processing (e.g., AM, FM, PM, CDMA, etc.). I imagine this is what you want to do. And this is called a Software Defined Radio.

Then, you should look at the GNU Radio which is a C++/Python library and front-end program to create SDRs and play around with that, and it can do lots of DSP. Also, look at this work on rooting TV tuners and re-purposing them as cheap SDR RF-hardware and having fun montoring all sorts of signals (as long as you go the right antenna and LNB module), like aircraft signals and satellite downlinks.

Personally, I'd use C/C++ as appropriate …

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

Try to install build-essential (at least, in Ubuntu repos, I don't know if other debian distros have it too), it will install everything you need.

$ sudo apt-get install build-essential

Also, if you get the message "unable to locate package ..", then you should try to do a search for it:

$ sudo aptitude search gcc

It should list all packages that contain that word (like grep). It's possible that the package is named something else, like gcc-4.7 or something like that.

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

What I hate are all those French words or expressions that English-speakers use and speak with a stupidly exagerated and totally wrong pronounciation. Like "rendezvous" or "laissez-faire", even the online dictionaries have a ridiculous pronounciation, listen here or here.

Why don't people just call it the stomach or abdomen, tummy seems too childish if you ask me.

But then we wouldn't have great rhymes like "yummy yummy yummy, I've got love in my tummy".

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

sir, please tell me that can i say both map and set as associative arrays ? i have read this and seen that associative arrays have key,value pairs (like map). but set don't have value , then why are they called associtiave array ?

Yes, they are both types of associative containers, at least, in the world of C++ (it might not be universal among computer scientists, I would presume some would only consider things like std::map or std::unordered_map as associative containers). Here is the definition of "associative containers" from the C++ standard (section 23.2.4/1-2):

  1. Associative containers provide fast retrieval of data based on keys. The library provides four basic kinds of associative containers: set, multiset, map and multimap.
  2. Each associative container is parameterized on Key and an ordering relation Compare that induces a strict weak ordering (25.4) on elements of Key. In addition, map and multimap associate an arbitrary type T with the Key. The object of type Compare is called the comparison object of a container.

The defining characteristic of associative containers is the "fast retrieval of data based on keys", whether the "data" is the key itself (e.g., std::set) or another value (e.g., std::map) doesn't change that, it's still called an associative container. The second clause also is the defining characteristic of ordered containers (set or map), that is, they are organized by a method of strict weak ordering (e.g., less-than, greater-than, etc.).

By contrast, unordered_set or unordered_map are "unordered associative containers", as in …

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

could I do something like this

Yes. The mechanism to do this is called "templates". Your function would look like this:

template <typename T>
T* createEmployee() {
  return new T();
};

And it would be called as so:

Employee* p = createEmployee< Manager >();

For a more complete tutorial on this, refer to this, or this, or any good book on C++.

Also, I must remark on the fact that you should not return a new-allocated object by pointer from a function. This is bad style because it obscurs the method of allocation, and thus, creates confusion as to the method of destruction (with delete in this case). One option is to always provide a pair of functions, one for creation one for destruction:

template <typename T>
T* createEmployee() {
  return new T();
};

template <typename T>
void destroyEmployee(T* p) {
  delete p;
};

And make it clear in the documentation that anything created with the one function must be destroyed with its corresponding function.

Another option is to use a smart-pointer to (implicitly) bundle the pointer with a deallocation method. One such smart-pointer is std::shared_ptr (from <memory>):

template <typename T>
std::shared_ptr<T> createEmployee() {
  return std::shared_ptr<T>(new T());
};

This smart-pointer is reference-counted and will automatically destroy the object when there are no more shared_ptr to that object in existence (i.e., the object is no longer needed). In other words, you don't need to explicitly delete that …

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

Nissan

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

we can say that set (ordered or unordered) are MAINLY used for look-ups ? and i have a big advantage with set(ordered) that they are arranged in sorted order when i will traverse it. am i roght ?

Yes that's right.

secondly, if can i have a set of structre ? if yes, then how will it check for uniqueness ? thanks.

If you want to use unordered_set with a custom class (or structure), you have to define a hash function as well as an equality comparison function, as you see from the signature of the class template:

template < class Key,                        // unordered_set::key_type/value_type
           class Hash = hash<Key>,           // unordered_set::hasher
           class Pred = equal_to<Key>,       // unordered_set::key_equal
           class Alloc = allocator<Key>      // unordered_set::allocator_type
           > class unordered_set;

The default equality comparison is the == operator for the class (which you can define).

For a std::set, it is similar, you have to define your own comparator (analogous to less-than), or simply overload the less-than operator.

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

Can we install .deb format on ubuntu 11.10 or 12.10 using sudo apt-get install???

In Linux, most software is installed through the package manager. This is an application that connects to a bunch of software repositories on the internet that host databases of .deb files (or .rpm in Red Hat variants). In the terminal (command-line window), you can install packages from the repositories via the command apt-get (or yum in Red Hat variants), which needs to be run as superuser. So, if you want to install GIMP (GNU Image Manipulation Program, i.e., a kind of open-source version of Photoshop), then you would open the terminal and write:

$ sudo apt-get install gimp

(note: the $ sign represents the prompt, you don't type that)

The sudo command means "superuser do". It allows you to execute one command (whatever follows it) with superuser privileges. It will ask you for your user password (same as when loging in).

The apt-get command is the program that can connect and fetch packages from the repositories. The option install speaks for itself. And the rest is a space-separated list of packages you wish to install (e.g., "gimp"). If you wish to remove a specific package (e.g., "gimp"), you would do:

$ sudo apt-get remove gimp

If you don't know the name of a package, you can always do a search that will return a list of suggestions:

$ sudo aptitude search gim    (note: missing 'p', 'gimp' will be suggested)

For .deb …

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

OHB

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

the words will be stored in the order they are added to the unordered set unlike a set where they are put in order of thier key value.

That's not true. Not at all. The values stored in an unordered_set will appear in whatever order they map to through the hashing function and the bucketing (to resolve collisions). This is why it is specified as "store elements in no particular order". If an implementation was required to preserve the order of insertion (as you suggest), there would be no way to implement this without doing an indirect indexing, and that is an unacceptable compromise for most purposes (if you want indirect indexing, just do it yourself through a vector and an unordered_set working together).

if i iterate it, then will they be in any specific order ?

No. The elements appear in "no particular order", which means neither sorted nor in their original insertion order.

what can be the use of it ?

If you don't need the data to be sorted (as in a std::set), then you can use an std::unordered_set for the same purposes you would use an std::set. Then, lookups, insertions, removals, and just about any operation that requires finding a particular value in the set can be done in constant time O(1) (amortized) as opposed to logarithmic time O(logN). For large numbers of elements, this can be a huge performance benefit. For smaller sets, you get less of a performance …

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

AFAIK both [UK] and France have similar governments as the USA.

Not true at all, there are significant differences that greatly change the political climate.

In the UK, like in Canada BTW, the House of Old Farts, which is officially called the House of Lords in the UK and called the Senate in Canada, is virtually powerless. Bills get passed on to that House, but they can merely do some tiny corrections to the bill and voice an opinion about it, that the real representatives (e.g., House of Commons in UK, or Members of Parliament in Canada) are free to ignore. In other words, their role is merely ceremonial. Nothing like what the Senate is in the US (with veto power, filibusters, grossly un-proportional and un-representative of the people, etc.).

Secondly, both in Canada and UK (and I would imagine all Commonwealth nations), the executive branch is merged with the legislative branch, i.e., the executives (e.g., the minister of agriculture) is also an elected member of parliament. And, of course, the big boss (President / Prime Minister, whatever you call it) is also a member of parliament + the leader of the majority party / coalition. In other words, whatever the party wants to do (under the lead of its leader), they can do it without endless backdoor negociations and bargains at the different levels of government, as is the case in the US, which, at the very least, greatly delays everything, and at worst, locks up the …

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

The default package manager for the 12.04 version of Ubuntu is called "Software Center". You should be able to find it in the main menu (with all the other apps). In the software center, you can search for anything that you want to install (games, applications, libraries, etc.) and install it. That's the purpose of a package manager like Software Center or Synaptic.

For mp4 codecs, you need to install the package called ubuntu-restricted-extras (you can search for it in the software center). You can also install it by running the following command in the terminal:

$ sudo apt-get install ubuntu-restricted-extras

If you want to have Synaptic Package Manager, which is what Ubuntu used to have as its default package manager (before Software Center), you can also install it:

$ sudo apt-get install synaptic

And you should then be able to find it in the main menu along with the other apps.
The same goes for Software Center, in case it didn't install it by default (it should have):

$ sudo apt-get install software-center

For playing videos, it might be hard to make sure you have all the codecs for all the formats, what I find easiest is to just install VLC, because it will pull, along with it, pretty much all codecs (except those in ubuntu-restricted-extras), so you can install VLC:

$ sudo apt-get install vlc

As you can see from the above, the apt-get install command is a very quick and easy way …

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

Election of the President by popular vote only. Whoever gets the most popular votes nationwide gets elected.

This seems fair, but I think that making the electoral votes proportional to the state's popular vote is actually do-able within the bounds of the constitution and would have the same effect (a few rounding-off errors aside). In fact, the Founding Fathers never intended for a winner-take-all electoral college system and attempted to ban it, as the travesty that it is. Here's an interesting article on those tribulations. The current winner-take-all system was essentially the result of a cascade of gerrymandering. It is also interesting to note that the original non-proportionality of the system was in large part motivated by a large population of slaves that didn't count, and thus, southern states would be under-represented by a proportional system (because they couldn't count their slaves as part of their voting population).

Personally, I'm a big fan of instant-runoff voting systems. Because I think that beyond the problem of non-proportionality (i.e., popular votes not necessarily agreeing with the presidential election), there is a huge problem of locking up the electoral system into strict two-party races, which inevitably leads to two parties that are barely distinguishable (e.g., Democrats and Republicans) and only catering to their donors, who usually give almost equally to both sides. And you end up with rather trivial issues being central to elections.

HoR: Rep Majority, Senate: Dem Majority

If Obama wants to introduce a …

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

IMO the EC should just be abolished and get rid of that headache.

OK, we're getting somewhere now. So, let's imagine that things could change. What would be the ideal system? But still, a functional system.

I would go for a proportional allocation of electoral votes, as so:

  • Each state gets a number of electoral votes in proportion to its population (updated every 4 years).
  • The number of electoral votes awarded to each party within a state is chosen as the best approximation of the popular vote obtained by each party (e.g., if there are 24 electoral votes in a state and the popular vote ended up at 60% / 40%, you end up with 15 / 9 electoral votes).

I think that would be fair, and wouldn't be subject to gerrymandering, as long as all states functioned this way. It would also give better chance to third parties (I know, that's dreaming... only in real democracies do third parties get a say, the US is a long way from there). In any case, it would be a first baby-step towards getting democratic elections in the US.

The next thing on the agenda (while we are re-engineering the system, in our imagination) would be, IMHO, an instant-runoff voting system.

I know that it is a wacky idea to think that things could change and a system could be fashioned by the people, of the people and for the people. But wasn't that the main achievement of the …

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

Samsung