20/7/10

The Four Polymorphisms in C++

When people talk about polymorphism in C++ they usually mean the thing of using a derived class through the base class pointer or reference, which is called subtype polymorphism. But they often forget that there are all kinds of other polymorphisms in C++, such as parametric polymorphism, ad-hoc polymorphism and coercion polymorphism.

These polymorphisms also go by different names in C++,
- Subtype polymorphism is also known as runtime polymorphism.
- Parametric polymorphism is also known as compile-time polymorphism.
- Ad-hoc polymorphism is also known as overloading.
- Coercion is also known as (implicit or explicit) casting.
In this article I'll illustrate all the polymorphisms through examples in C++ language and also give insight on why they have various other names.

Subtype Polymorphism (Runtime Polymorphism)
Subtype polymorphism is what everyone understands when they say "polymorphism" in C++. It's the ability to use derived classes through base class pointers and references.

Here is an example. Suppose you have various cats like these felines,

Since they are all of Felidae biological family, and they all should be able to meow, they can be represented as classes inheriting from Felid base class and overriding the meow pure virtual function,
// file cats.h

class Felid {
public:
virtual void meow() = 0;
};

class Cat : public Felid {
public:
void meow() { std::cout << "Meowing like a regular cat! meow!\n"; }
};

class Tiger : public Felid {
public:
void meow() { std::cout << "Meowing like a tiger! MREOWWW!\n"; }
};

class Ocelot : public Felid {
public:
void meow() { std::cout << "Meowing like an ocelot! mews!\n"; }
};

Now the main program can use Cat, Tiger and Ocelot interchangeably through Felid (base class) pointer,
#include
#include "cats.h"

void do_meowing(Felid *cat) {
cat->meow();
}

int main() {
Cat cat;
Tiger tiger;
Ocelot ocelot;

do_meowing(&cat);
do_meowing(&tiger);
do_meowing(&ocelot);
}
Here the main program passes pointers to cat, tiger and ocelot to do_meowing function that expects a pointer to Felid. Since they are all Felids, the program calls the right meow function for each felid and the output is:
Meowing like a regular cat! meow!
Meowing like a tiger! MREOWWW!
Meowing like an ocelot! mews!
Subtype polymorphism is also called runtime polymorphism for a good reason. The resolution of polymorphic function calls happens at runtime through an indirection via the virtual table. Another way of explaining this is that compiler does not locate the address of the function to be called at compile-time, instead when the program is run, the function is called by dereferencing the right pointer in the virtual table.

In type theory it's also known as inclusion polymorphism.

Parametric Polymorphism (Compile-Time Polymorphism)
Parametric polymorphism provides a means to execute the same code for any type. In C++ parametric polymorphism is implemented via templates.

One of the simplest examples is a generic max function that finds maximum of two of its arguments,
#include
#include

template
T max(T a, T b) {
return a > b ? a : b;
}

int main() {
std::cout << ::max(9, 5) << std::endl; // 9

std::string foo("foo"), bar("bar");
std::cout << ::max(foo, bar) << std::endl; // "foo"
}
Here the max function is polymorphic on type T. Note, however, that it doesn't work on pointer types because comparing pointers compares the memory locations and not the contents. To get it working for pointers you'd have to specialize the template for pointer types and that would no longer be parametric polymorphism but would be ad-hoc polymorphism.

Since parametric polymorphism happens at compile time, it's also called compile-time polymorphism.

Ad-hoc Polymorphism (Overloading)
Ad-hoc polymorphism allows functions with the same name act differently for each type. For example, given two ints and the + operator, it adds them together. Given two std::strings it concatenates them together. This is called overloading.

Here is a concrete example that implements function add for ints and strings,
#include
#include

int add(int a, int b) {
return a + b;
}

std::string add(const char *a, const char *b) {
std::string result(a);
result += b;
return result;
}

int main() {
std::cout << add(5, 9) << std::endl;
std::cout << add("hello ", "world") << std::endl;
}
Ad-hoc polymorphism also appears in C++ if you specialize templates.Returning to the previous example about max function, here is how you'd write a max for two char *,
template <>
const char *max(const char *a, const char *b) {
return strcmp(a, b) > 0 ? a : b;
}
Now you can call ::max("foo", "bar") to find maximum of strings "foo" and "bar".

Coercion Polymorphism (Casting)
Coercion happens when an object or a primitive is cast into another object type or primitive type. For example,
float b = 6; // int gets promoted (cast) to float implicitly
int a = 9.99 // float gets demoted to int implicitly
Explicit casting happens when you use C's type-casting expressions, such as (unsigned int *) or (int) or C++'s static_cast, const_cast, reinterpret_cast, or dynamic_cast.

Coercion also happens if the constructor of a class isn't explicit, for example,
#include

class A {
int foo;
public:
A(int ffoo) : foo(ffoo) {}
void giggidy() { std::cout << foo << std::endl; }
};

void moo(A a) {
a.giggidy();
}

int main() {
moo(55); // prints 55
}
If you made the constructor of A explicit, that would no longer be possible. It's always a good idea to make your constructors explicit to avoid accidental conversions.

Also if a class defines conversion operator for type T, then it can be used anywhere where type T is expected.

For example,
class CrazyInt {
int v;
public:
CrazyInt(int i) : v(i) {}
operator int() const { return v; } // conversion from CrazyInt to int
};
The CrazyInt defines a conversion operator to type int. Now if we had a function, let's say, print_int that took int as an argument, we could also pass it an object of type CrazyInt,
#include

void print_int(int a) {
std::cout << a << std::endl;
}

int main() {
CrazyInt b = 55;
print_int(999); // prints 999
print_int(b); // prints 55
}
Subtype polymorphism that I discussed earlier is actually also coercion polymorphism because the derived class gets converted into base class type. Sphere: Related Content

11/7/10

Computer Virus News & Alerts

Computers are becoming more and more indispensable day after day. They have become primary repositories our digital photos, documents, invoices, multimedia etc. The sheer volume of computer users and the advent of cheap always-on internet connections has made computers an attractive targets to hackers distributing viruses, spyware and other malicious software.

You might have an anti-virus software installed in your computer that auto updates itself against latest threats. if you haven’t, here are MakeUseOf’s recommendations for the best free antivirus you can get your hands on. In addition to that, it is always a good idea to keep yourself on top of what exactly is happening in the computer security front. Viruses and other threats have a tendency to replicate themselves, making it tough for security software vendors to issue a patch. We have compiled a list of reliable official and independent sources that publish computer virus news and alerts as and when the outbreak happens.

Official Sources

ESET Threat Blog
ESET is a trusted name in the desktop security business. They won the hearts of both enterprise and home users alike with their rapid virus signature updates, sometimes multiple times a day, if necessary. They maintain a fantastic ESET Threat blog to keep everyone up to date on any new virus or malware threats. The blog is updated regularly and in addition to providing the latest information on viruses, they post lot of useful data walking users through tips & tricks to avoid skimming, phising etc. ESET updates the blog with content that serves everyone – from newbies to White Hat hackers.
Posts detailing as to how the malware underground works, how BlackHat hackers distribute malware via online games, how botnets manipulate the stock market are some of the interesting topics covered in the blog.
Trend Micro Threat Encyclopedia
Trend Micro is one of the pioneers in the computer security business and they have put up a threat encyclopedia to keep their users in the know of the latest computer virus news and alerts. Recent strains of malware, spyware and vulnerabilities are segregated in their respective tables, with an appropriate risk rating. Clicking on the malware name opens a pretty detailed advisory as to how this malware harms the desktop and the platforms it is active on.
McAfee Virus Information
With a global map showing virus threat levels, list of recent threats to a general purpose threat meter, McAfee’s Virus Information page is put together very well. There are free resources to teach beginners about various threats like virus, malware, spyware etc. and how to identify one from another. Free virus specific diagnostics and removal tools can also be downloaded from here.
Norton Threat Explorer

Being a name synonymous with the computer security industry, Norton maintains an exhaustive threat explorer index. You can check out all the latest computer security threats listed in a single page in alphabetical order and can even search for a particular virus if you know the name.
Securelist
Securelist is a computer virus threat information portal maintained by Kaspersky Labs. They list recent virus descriptions found, in depth reviews of Malware behaviour on test systems, news & analysis of hot security topics, Monthly malware statistics and a lot more related to information security.

Independent Sources

ComputerWeekly
ComputerWeekly, a reputed technology blog has an exclusive section dedicated to computer security alerts and analysis. In addition to covering news about computer security threats, they also publish in depth articles on vulnerabilities available in popular gadgets and smartphones. Their forward-looking coverage on future threats & impending spam campaigns and in-depth white papers on IT security alerts are thorough and written in a simple language making it easy for newbies to understand.
Virus Bulletin
True to its name, Virus Bulletin is a blog dedicated to cover virus, malware and spyware outbreaks. Virus Bulletin carries a lot of articles on malware tests & analysis complete with complex graphical interpretations. A fantastic chart showing the list of top malware and their prevalence percentage on computers adorns the homepage. There is also a calender displaying various security conferences & conventions across the globe.
Security News Portal
With hard to miss, color-coded list of recent IT security threats displayed prominently, Security News Portal makes an impression right from the first visit. The portal covers a lot of platforms but highlights vulnerabilities in Microsoft Windows, the biggest among them all.

Conclusion

Among the official sources, ESET’s blog is an enjoyable read and is extremely qualified to become a full-fledged computer security blog. Kaspersky Securelist comes in as a close second with its computer virus alerts and analysis. The rest of the official sources are updated regularly with mostly basic computer threat description for a quick glance. ComputerWeekly and Virus Bulletin both do an excellent job in reporting and covering threat alerts in a language that even newbies can comprehend.

Now that you know where to read about computer virus alerts, you might want to check out our coverage of the best websites to find fixes for virus & malware.

Do you follow a great blog or portal for computer virus news and alerts that we have missed? Please do share it with us in the comments section. Sphere: Related Content

2/7/10

10 Useful WordPress Security Tweaks

Security has always been a hot topic. Offline, people buy wired homes, car alarms and gadgets to bring their security to the max. Online, security is important, too, especially for people who make a living from websites and blogs. In this article, we’ll show you some useful tweaks to protect your WordPress-powered blog.

1. Prevent Unnecessary Info From Being Displayed

The problem
When you fail to log into a WordPress blog, the CMS displays some info telling you what went wrong. This is good if you’ve forgotten your password, but it might also be good for people who want to hack your blog. So, why not prevent WordPress from displaying error messages on failed log-ins?

The solution
To remove log-in error messages, simply open your theme’s functions.php file, and paste the following code:

1add_filter('login_errors',create_function('$a', "return null;"));

Save the file, and see for yourself: no more messages are displayed if you fail to log in.

Please note that there are several functions.php files. Be sure to change the one in your wp-content directory.

Code explanation
With this code, we’ve added a simple hook to overwrite the login_errors() function. Because the custom function that we created returns only null, the message displayed will be a blank string.

Source

2. Force SSL Usage

The problem
If you worry about your data being intercepted, then you could definitely use SSL. In case you don’t know what it is, SSL is a cryptographic protocol that secures communications over networks such as the Internet.

Did you know that forcing WordPress to use SSL is possible? Not all hosting services allow you to use SSL, but if you’re hosted on Wp WebHost or HostGator, then SSL is enabled.

The solution
Once you’ve checked that your Web server can handle SSL, simply open your wp-config.php file (located at the root of your WordPress installation), and paste the following:

1define('FORCE_SSL_ADMIN', true);

Save the file, and you’re done!

Code explanation
Nothing hard here. WordPress uses a lot of constants to configure the software. In this case, we have simply defined the FORCE_SSL_ADMIN constant and set its value to true. This results in WordPress using SSL.

Source

3. Use .htaccess To Protect The wp-config File

The problem
As a WordPress user, you probably know how important the wp-config.php file is. This file contains all of the information required to access your precious database: username, password, server name and so on. Protecting the wp-config.php file is critical, so how about exploiting the power of Apache to this end?

The solution
The .htaccess file is located at the root your WordPress installation. After creating a back-up of it (it’s such a critical file that we should always have a safe copy), open it up, and paste the following code:

1
2order allow,deny
3deny from all
4

Code explanation
.htaccess files are powerful and one of the best tools to prevent unwanted access to your files. In this code, we have simply created a rule that prevents any access to the wp-admin.php file, thus ensuring that no evil bots can access it.

Source

4. Blacklist Undesired Users And Bots

Sm4 in 10 Useful WordPress Security Tweaks

The problem
This is as true online as it is in real life: someone who pesters you today will probably pester you again tomorrow. Have you noticed how many spam bots return to your blog 10 times a day to post their annoying comments? The solution to this problem is quite simple: forbid them access to your blog.

The solution
Paste the following code in your .htaccess file, located at the root of your WordPress installation. As I said, always back up the .htaccess file before editing it. Also, don’t forget to change 123.456.789 to the IP address you want to ban.

1
2order allow,deny
3allow from all
4deny from 123.456.789
5

Code explanation
Apache is powerful and can easily be used to ban undesirable people and bots from your website. With this code, we’re telling Apache that everyone is allowed to visit our blog except the person with the IP address 123.456.789.

To ban more people, simply repeat line 4 of this code on a new line, using another IP address, as shown below:

1
2order allow,deny
3allow from all
4deny from 123.456.789
5deny from 93.121.788
6deny from 223.956.789
7deny from 128.456.780
8

Source

5. Protect Your WordPress Blog From Script Injections

The problem
Protecting dynamic websites is especially important. Most developers always protect their GET and POST requests, but sometimes this is not enough. We should also protect our blog against script injections and any attempt to modify the PHP GLOBALS and _REQUEST variables.

The solution
The following code blocks script injections and any attempts to modify the PHP GLOBALS and _REQUEST variables. Paste it in your .htaccess file (located in the root of your WordPress installation). Make sure to always back up the .htaccess file before modifying it.

1Options +FollowSymLinks
2RewriteEngine On
3RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
4RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
5RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
6RewriteRule ^(.*)$ index.php [F,L]

Code explanation
Using the power of the .htaccess file, we can check requests. What we’ve done here is ch

eck whether the request contains a

Sphere: Related Content

7 Personality Types of Developers Today

Developers and programmers are meticulous individuals, and developers sometimes stand out even among themselves.

We introduced you to 7 types of designers in our article 7 Personality Types of Designers Today. Developers have peculiar traits and habits of their own. This article looks at 7 types of developers today and their defining characteristics.

“The best programmers are not marginally better than merely good ones. They are an order of magnitude better, measured by whatever standard: conceptual creativity, speed, ingenuity of design or problem-solving ability.”
—Randall E. Stross

Stereotyping is generally not good practice. But we’re not trying to squeeze individuals into categories. Rather, delineating these types can help you figure out where you stand and help you understand others.

1. The Self-Help Constructor
The self-help constructor does whatever it takes to get the job done with his experience and skill, no matter how limited.

For example, he may accomplish the job by finding open-source software and other free applications and tools. His best assets are his willingness to learn what he needs to complete the job and his ability to absorb the information like a sponge. He is resourceful, working with whatever is available to him.

Not every client will be impressed. Those who don’t know any better will praise his work, but the self-help constructor does not develop applications or plug-ins himself.

He merely exploits existing tools to construct something seemingly new for clients. With the wide range of sophisticated tools available today, this is becoming easier, but much less impressive.

2. The Experienced Old Man
He may not be the hippest guy in this energetic and creative field, but the experienced old man brings something valuable to the table: a wealth of knowledge and experience.

He may appear outdated, unable to keep up with the latest tools and technology, but he is wise and knows the basics like the back of his hand.

His battle stories of bygone days will fascinate and thrill. He may not be the fastest or most technologically savvy, but slow and steady wins the race, and he delivers the goods as he always has.

He proves that the old-school style of coding may be antique but isn’t extinct. He may not be your heaviest hitter, but in times of great need, you know you can count on the experienced old man to deliver.

3. The Hardcore Geek
Workaholic doesn’t begin to describe the hardcore geek, this martyr of developers. He goes beyond the call of duty to deliver the product and takes great pride in his work.

He spends his lunch hour at his desk working frantically to finish the project ahead of time. When he allows himself a little free time, he reads books, journal articles and the like to improve himself. Very much an introvert, he feels most comfortable in the world of code and programming jargon.

The more code the hardcore geek writes, the more content he feels. As great as he is with code, he makes for a much better worker bee than a leader.

4. The Scholarly Know-It-All
The scholarly know-it-all is a walking encyclopedia on programming. He can spend hours passionately discussing the history of a programming language or dissecting imperfect code.

He is the poet of the programming world, whose code is a work of art that can be appreciated and analyzed. Recursion is his middle name, and he tweaks every block of code to perfection, regardless of timelines or readability.

He sets high standards for himself, and his work sometimes complicates matters: a task that should take only an hour to complete takes him a few months. Mind you, he’s not incompetent. On the contrary, he is highly capable; but he makes work for himself by creating new tools and libraries and even reconstructing entirely new systems, all to meet his own standards.

He feels obliged to impart his knowledge to others and share his passion for the theory and technical intricacies of coding and programming. He tries his best to explain to clients why using state-of-the-art technology is so important. Every project is his precious child.

The scholarly know-it-all is great to have on your team, but be sure you can get him to spend his energy on the important details, rather than waste time satisfying his urge to delve into every nook and cranny.

5. The Ninja
The ninja is a man of few words and keeps to himself. While similar to the hardcore geek, he has more in his life than code and work.

He is an enigma: not outright friendly or forthcoming, but he works surprisingly well on a team. Everyone notices his tireless nature but can’t figure out how he does everything so well and so quickly. There is much evidence of his work but little evidence that he did it. “Show don’t tell” describes his modus operandi best.

Never outwardly frazzled (try as you might to throw him off), he resolves problems quickly and efficiently, regardless of time or place. The ninja’s stealth sends chills down your spine, and he leaves you wondering how he managed to accomplish his feat.

A lone ranger, he gets the job done regardless of his status on the team or his relationship with other members. His motto? Don’t have doubts; just resolve the problem quickly and efficiently. This no-nonsense attitude makes him an absolute joy to work with.

6. The Clever Ambassador
The clever ambassador is the face of the team. He is outspoken and the unofficial project manager. His knowledge of software development, project workflows and code theory is adequate, but he does very little of the actual programming or work.

He is quick to pick up leads and great at communicating with clients. He is the consummate ring-master, able to please both clients (the ferocious lions) and team members (the elephants that could easily trample him if they wanted).

In his supervisory role, the clever ambassador ensures that every project meets the requirements and satisfies the client. He is the go-between, representing the development team for the client and balancing client satisfaction with practicality.

Having to walk this tight rope, he often feels that he should be better compensated, despite never doing any heavy lifting (i.e. coding). He is the model who sits pretty in front of the camera selling the product, while the rest of the team (make-up artists, hair stylists, etc.) works behind the scenes, receiving lower payment for what amounts to the same work.

7. The Half-Cup Speedster
The half-cup speedster takes on multiple projects at once. He works much faster than most, but his amazing quantity is tarnished by its quality: his speed results from cutting corners and hacking core.

He feels that optimizing and checking code takes too long. His code is messy because he does not follow best practices and never makes use of object-oriented programming (OOP).

Amazingly, despite his code looking like a minefield, the product works just as intended. Cutting corners is generally not good practice, but in an impossible crunch, the half-cup speedster might be the person for the job.

Unfortunately, much like the handwriting of physicians, his code is practically indecipherable. Should someone need to fix a problem that surfaces later, they will surely encounter difficulties. You can’t fix what you can’t read or understand.


Written exclusively for Webdesigner Depot by Aidan Huang, a freelance front-end developer and designer. He is also an editor at Onextrapixel.

As we’ve seen, there are many types of developers in the field. Which do you most closely resemble? Have you met anyone who fits any of the categories mentioned here? Share your thoughts with us in the comments below… Sphere: Related Content

How to Rescue Files from Dying External Hard Drive

Ram asks:
My WD external USB self-powered 500 GB hard drive just kicked the bucket. The drive is recognized after I plug it in, but the files are inaccessible and Explorer (or any other process) that tries to access it hangs. Disk scan with HDDTune shows bad sectors across the board.

Is there any way to salvage the files? I have tried to copy through Windows Explorer and a raw copy, but like I said above, all software hangs.

Thanks!

John said:
Get a copy of spinrite from http://www.grc.com It will likely restore the drive so you can copy the files. It is an amazing product it may work at it for hours but in most cases it will restore the drive but be ready to copy the files don't be fooled that it is fixed because if it rashes again its likely gone for good. If spinrite can't fix it nothing can.

Jessica said:
Perhaps you could try an Ubuntu Live CD?

1. Just download and put the .iso file to a USB flash drive using UNetbootin (which makes it really easy but just make sure to select your USB flash drive and not your current or external hard drive) or burn the .iso file on a CD.

2. Once you've done either, now plug in the USB flash drive w/Ubuntu or the CD you burned.

3. Reboot and assuming your computer can boot from USB or CD, choose "Try Ubuntu without any changes to your computer" when you eventually get to the screen with the orange Ubuntu logo.

If your computer doesn't boot from USB or CD, which means you go straight to Windows, follow the directions here to change the boot order in your BIOS (but first, just try to note the default boot order so you can revert this later on.)

4. When you get to the desktop in Ubuntu, plug your dying 500GB hard drive in.

5. You should now see your hard drive appear on the desktop as a mounted drive. Double-click on it to see if you can access your files and copy them to another place like your USB flash drive. Hope you can!

Even if this doesn't work, you might want to change your BIOS boot order back to the default settings.

Did this help?


Artur said:

If step 5 of Jessicas' walkthrough won't help with recovering data your next best bet is byte-by-byte copy of affected disk or partition.

Make sure that you have enough free space on target drive, login as root and type in:

# download ddrescue
wget http://download.savannah.gnu.org/releases/ddres...
# extract the source code
tar xjf ddrescue-1.8.tar.bz2
# compile ddrescue
cd ddrescue-1.8
./configure && make
# first, grab most of the error-free areas in a hurry:
./ddrescue -n /dev/old_disk /dev/new_disk rescued.log
# then try to recover as much of the dicy areas as possible:
./ddrescue -r 1 /dev/old_disk /dev/new_disk rescued.log

You can write to file if that's what you desire:

./ddrescue -r 1 /dev/old_disk imagefile.hdd rescued.log

Good luck with your data recovery. Sphere: Related Content