Archive

Archive for the ‘Tips ‘n Tricks’ Category

Early-outs for n00bs

November 26th, 2011 No comments

Sometimes I see people code something up like the following:

void AwesomeFunc( void )
{
    if( var == 3 )
    {
        if( var2 == 4 )
        {
            if( var4 == "napkin" )
            {
                if( var5 == 8495 )
                {
                    g_flag = true;
                }
                else
                {
                    Debug.Log( "var5 wasn't 8495" );
                }
            }
            else
            {
                Debug.Log( "var4 was not napkin" );
            }
        }
        else
        {
            Debug.Log( "var2 wasn't 4" );
        }
    }
    else
    {
        Debug.Log( "var wasn't 3" );
    }
}

Read more…

Categories: Blog, Tips 'n Tricks Tags: ,

Const qualifier reminder

November 7th, 2011 No comments

Just a reminder how const-ness works. If I remember correctly.

// These two lines are the same type
// const and int can be switched around and the result is the same.
const int i;
int const j;

// If the word "const" follows the "*", it affects the pointer
int* const k;

// Both the pointer and the int are const
const int* const m;

// Same as line above, it just looks weird
int const * const n;

// Does the const affect the pointer or the int? The int..
int const * p;
Categories: Blog, Miscellaneous, Tips 'n Tricks Tags: ,

Quick vim tip

July 6th, 2011 No comments

I’ve always used the “w” key to go forward a word when highlighting stuff. There’s a problem with this though when you want to just copy a single word.

Lets say you have the sentence “you are a car.” Let’s also assume you have placed your cursor on the letter “a” in “are.”

And we want to highlight the word “are.” So we press “vw”. When you press the letter “w”, it highlights the following: “are a”. Note that it includes a space and the letter a.

So the letter “w” is the wrong key to use, so what is the key to go to the end of the word instead?

It’s the letter: e

Categories: Blog, Tips 'n Tricks Tags:

What is the difference between aggregation and composition?

May 5th, 2011 No comments

This question has bothered me for some time and I always forget. So I wrote it down here and added an answer.

Composition : An object contains another object. When the container object dies, so does the composited objects.

Aggregation : An object pseudo-contains another object (contains a pointer to it). When the container object dies, the containees do not.

class Container
{
public:
    // Composition
    Containee _c[5];

    // Aggregation
    Containee* _pc[5];
}

Sometimes aggregation is called composition when the difference doesn’t matter.
Note: In UML, aggregation is an unfilled diamond, whereas composition is a filled diamond.

References:
http://en.wikipedia.org/wiki/Object_composition#Aggregation

Don’t get left behind

February 28th, 2011 No comments

Do you want to know what the latest trends are in game development? Do you have a fear of being left behind in the game dev industry because you don’t know what such n’ such a technique is? Is there something you can do to make sure you’re not left behind in the dust?  There is!

In this post, I’m mainly concerned with physics and graphics, but the same sort of techniques apply to other fields as well. The following items are what I do regularly to keep up to date in my field:

Read more…

Things you can do to make your code better

January 6th, 2011 No comments

I got most of this list from some other place on the internet, but I felt there could be more added to it.
I’ll continue to add to this list as I think of things or come across things.

  1. Test Driven Development Really Is Worth It
  2. Don’t Rely On Comments Too Much: Make Your Code Self-Explanatory
  3. Don’t Let Exceptions Disappear Into A Black Hole
  4. Don’t reinvent the wheel. Use libraries when possible because you know they work.
  5. Code like you will reuse the code for other projects.
  6. Learn what good design should look like an emulate it until you see why it is good design (and what you dislike about it).
  7. Too many newbies like to over-engineer just to pretend to be smart or having fun with resume-driven-development. In other words, implementing every pattern in the book or putting bayesian filters in every corner of the code should be avoided if they aren’t needed. Debugging, testing, maintenance will be all easier, not mentioning performance.
  8. Have your code reviewed often.
  9. Be wary of code smells (Class too big, method too big, method with too many arguments, Ask don’t Tell etc).
  10. Enforce standards by using checkstyle / PMD, cobertura / emma, findbugs, etc within maven build cycle to make sure code in repository is adhering to a certain quality standard.
  11. Make sure it meets the quality standard for the project.
  12. Just keep it simple. Functions should be short and sweet, and do just one thing. They should fit on one or two screenfuls of text (the ISO/ANSI screen size is 80×24, as we all know), and do one thing and do that well.
  13. Test, test, test.
  14. You will see how many times you will have to tradeoff between design and schedule. Forgive yourself but remember to refactor whenever possible.
  15. Use Standard Annotation Language (SAL) if you are using C or C++, to prevent bugs and make your code robust. It is found in the book “Writing Secure Code for Windows Vista.”
  16. Code with contracts (partially enforced with SAL).
  1. Avoid global mutable state, such as static variables and static singletons.
http://misko.hevery.com/2008/11/11/clean-code-talks-dependency-injection/
http://misko.hevery.com/2008/11/21/clean-code-talks-global-state-and-singletons/
  1. Make your methods small and well named.
http://c2.com/ppr/wiki/WikiPagesAboutRefactoring/ComposedMethod.html
http://tottinge.blogsome.com/meaningfulnames/
  1. Simple Design
http://jamesshore.com/Agile-Book/simple_design.html
  1. Adhere to SOLID Principles
http://en.wikipedia.org/wiki/Solid_(object-oriented_design)
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod

Simple coding tips 01

November 24th, 2010 No comments

Simple tip: Naming functions

Examples:
GetName()
SetName()
DoAreaTransition()
CreateBird()
DestroyBird()

Note how each function name begins with a verb and usually, each function ends with a noun. Naming your functions this way helps you think more clearly about what you’re doing and helps other people understand your code more thoroughly.

Categories: Blog, Tips 'n Tricks Tags: ,

Two dropbox instances for one Win7 user

November 7th, 2010 No comments

I’m always afraid of websites randomly disappearing, especially when they have useful information on them. I happened to stumble across a website that explains how to set up multiple dropbox instances on a windows 7 or vista machine. I’m going to briefly just copy that info here for my own reference ( and yours :-) )

  1. Setup dropbox like normal with an account.
  2. Create a second user on your windows machine with a password.
  3. Login as that second user.
  4. Install dropbox again for that user and set it to synchronize a folder that both windows accounts can access.
  5. Log back into the original windows account.
  6. Find the dropbox.exe in the other user’s folder that you just created: c:\users\<username>appdata\roaming\dropbox\bin\dropbox.exe
  7. Make a shortcut to that .exe file somewhere.
  8. In the shortcut’s properties, change the “Target” field to something like this: runas /user:<username> /savecred C:\Users\<username>\AppData\Roaming\D ropbox\bin\Dropbox.exe
  9. Double click the shortcut, type in the password, and it should be working.
Categories: Blog, Tips 'n Tricks Tags: , ,

How not to suck at interviews

November 5th, 2010 No comments

I have been on multiple in-person interviews and, although I still don’t do very well at interviewing, I have picked up quite a few interview tips along the way. The main idea is: Interviewers are looking for any reason to reject you. Don’t give them that reason. This list will help you avoid common reasons for rejection. Some of these items might be completely wrong and may screw up your chances. If you think so, let me know and we can discuss it. After all, I said I wasn’t very good at interviewing. I will add more to this list when I think of them though too.

I have labeled each item as E – “Easy”, M – “Medium”, D – “Difficult”. Most of the difficult/medium entries are labeled as such because you have to remember to do them during the interview and you may be required to train yourself to stop doing bad things, which will require days, weeks, or months to get right. These difficult items are indeed difficult because there is already a lot going on during the interview.

Read more…

Adding “edit with” to context sensitive menu

September 18th, 2010 No comments

I manually installed notepad++ into my dropbox folder so I could use it anywhere. Unfortunately, it didn’t add the “Edit with Notepad++” entry for the context sensitive right-click menu. This trick works for almost any application that accepts a file name on the command line as the first argument.

To see if your application has this ability, open up a command prompt (start->run->cmd). For example, lets see if notepad has this ability. In the command prompt, type “notepad.exe file.txt” without the quotes and where file.txt is some text file in the directory the command prompt is currently in. Notepad will launch with file.txt loaded and showing. If you can do this with other apps (such as Notepad++), then you are good to go.

So to add the “edit with” menu option manually, you have to create a text file and add this to it:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\shell\Edit with Notepad++]

[HKEY_CLASSES_ROOT\*\shell\Edit with Notepad++\command]
@="\"E:\\DropBox\\toddseiler\\My Dropbox\\Apps\\Notepad++\\notepad++.exe\" \"%1\""

Replace the path with wherever you installed the application you want to launch (in this case, it was notepad++.exe).

Two things of note: Make sure the path has double back slashes between each directory “\\” and make sure that after the “file.exe” file name, there is a trailing “\”. In this example it says “…\notepad++.exe\” This must be there.

You can make it say whatever you want in the menu by editing the words “Edit with Notepad++” to whatever you want.

Save the file with a .reg extension. After you do this, the file should have have an icon with little blue building blocks on it. Double click it, windows will ask if you really want to enter this into the registry, click ok/yes.

You now should be able to right click on any file and have the menu option come up. Clicking it will result it the application launching with the “clicked on” file loaded (if the application developer implemented this.)

Categories: Blog, Tips 'n Tricks Tags:

Linking libraries in code with MSVS

September 15th, 2010 No comments

If you use visual studio, you can use a #pragma to tell the linker to link in a library. This way, you don’t have to screw with project settings if you just want to quickly test something.  For example, if you wanted to link in the winmm.lib import library, it is done like so:

#pragma comment (lib, "winmm")

Header Guards

September 15th, 2010 No comments

A lot of people don’t know this, but #pragma once is actually an optimization. It is faster than using the #ifndef blocks.

But you’re in luck because you can safely write portable code with it, in case the compiler doesn’t recognize #pragma once by doing this:

#pragma once
#ifndef HEADERFILE_H
#define HEADERFILE_H
class Classname
{
    int member;
};
#endif /* HEADERFILE_H */
Categories: Tips 'n Tricks Tags:

Getting access to hidden windows 7 settings

June 26th, 2010 No comments

There are a couple of things I recently stumbled across that gives Windows 7 users access to a ton of useful settings.

1) Make a folder on your desktop and name it: Everything.{ED7BA470-8E54-465E-825C-99712043E01C}

2) Click run and type in: gpedit.msc

If I come across any others, I’ll post it here.

Categories: Blog, Tips 'n Tricks Tags:

Midnight Commander trick

March 12th, 2010 No comments

After using midnight commander for a while, I realized I couldn’t open any other file except for .h and .cpp files. Finding this odd, I realized that it wasn’t gvim’s fault, but instead midnight commander’s fault. By default, pressing <ENTER> on the keyboard results in executing the file (or attempting to if it is a script). I found this bothersome as I hardly ever execute scripts through mc. So I changed the default action from “execute” to “edit.” This is done by editing the “/usr/share/mc/mc.ext” file. At the very bottom, make sure the lines read something like this:

Open=%var{EDITOR:vi} %f
View=%var{EDITOR:vi} %f
Categories: Blog, Tips 'n Tricks Tags:

Missing iPhone icons

February 19th, 2010 No comments

If you are missing icons on your springboard, using ssh, navigate yourself over to /var/mobile/Library/Preferences and delete com.apple.springboard.plist. Respring your iPhone by typing killall SpringBoard into SSH. Problem solved.

Categories: Blog, Tips 'n Tricks Tags: ,

Beginning win32 multithreading

February 19th, 2010 No comments

In an attempt to understand windows multithreading a little more thoroughly, I’ve decided to write about the simple concepts associated with multithreading. This is mainly to clarify it in my own head but maybe it will help someone else out too. If any of this information is wrong, don’t yell at me.:-)Please just post a comment and I’ll look into it and/or fix it. So here we go.

Thread: I’m not going to define a thread. Just know that a thread is a kernel object, which means that when a thread finishes executing, it gets signaled. If you use “WaitForSingleObject();” for example to wait for it to finish executing, it is safer and doesn’t eat up CPU time like a spin lock would.

Signaled: Kernel objects get signaled (threads, mutexes, etc.). When a kernel object gets signaled, “WaitForSingleObject()” wakes up. The same goes for other “Wait*()” functions. In the case of threads: running = nonsignaled, when a thread terminates = signaled.

Atomic Operation: A single operation that the processor can not perform a context switch in between.

Context Switch: When the processor halts execution of a thread, and then continues executing another thread from where it left off previously. The cause of race conditions when multithreading, but a necessary feature on processors.

Spin Lock: Eats CPU time, not atomic. Basically the predecessor to critical sections. Basically a “for” loop that waits around until a thread returns. This is the worst way to do multithreading, don’t use spin locks at all.

Race Condition: The easiest way to conceptualize a race condition is to think of it this way: A thread writes data and soon after, another thread blindly overwrites the data that was just written by the first thread. Critical Sections resolve this.

Critical Section: If you only have one resource that needs sharing between multiple threads, you use a “Critical Section.” Critical sections are not kernel objects and prevent race conditions between multiple threads. The reason you use critical sections is to make certain areas of your code / data atomic so that a context switch doesn’t fowl up your data. Note: You can specify different areas of your code as the same critical section.

Mutex: If you have multiple resources that need to be shared among threads, you do NOT use a critical section. This can result in a dead lock where one thread waits for the other thread to release a resource, but that thread is waiting on the first thread to release a resource it needs, so both end up waiting forever. So instead you use a mutex. A mutex is a kernel object and can be shared among threads as well as processes. Basically, a mutex says: “Execute this code if both (or however many the mutex was defined with) resources are available.” If that requirement isn’t satisfied, then the code isn’t run. For example: If only one resource was available but the mutex was defined for two resources, then the code would not run.

Note: Mutexes introduce race conditions now, the very thing that critical sections fixed. Also, it’s worth noting that you can still get a dead lock with mutexes if you use “WaitForSingleObject().” Instead, you must use “WaitForMultipleObjects()” to avoid dead locks.

Win32 functions associated with multithreading
General Win32 Thread Functions: You can look up the parameters yourself on msdn.
CreateThread();
GetExitCodeThread();
ExitThread();
WaitForSingleObject();
WaitForMultipleObjects();
MsgWaitForMultipleObjects();

Critical Section: Sharing one resource
InitializeCriticalSection();
DeleteCriticalSection();
EnterCriticalSection();
LeaveCriticalSection();

Mutex: Sharing multiple resources
CreateMutex();
OpenMutex();
WaitForSingleObject();
WaitForMultipleObjects();
MsgWaitForMultipleObjects();
ReleaseMutex();
CloseHandle();

Notes on library files

February 19th, 2010 No comments

A few notes regarding library files.

Shared library: Not the same as a dynamic library. Only used in linux. A .so file extension. Can be shared across processes, not loaded into a process’s address space, loaded globally. (i believe) Note: It is loaded at application startup.

Static library: Also known as an object library, contains a collection of .obj files, extension .lib

Dynamic library: .dll extension or .so. Dynamically loaded by the OS’s loader. Loaded into a process’s address space. (i think) Note: Loaded whenever you use a “load library()” call, not on application startup.

Import library: Allows your program to call entry points in the DLL, .lib file, linux does not require these as it directly links to the .so file

Sometimes a shared library and a dynamic library are said to be the same thing, but they aren’t. If there are any mistakes or I have my facts mixed up, please let me know.

In fact, if you want, there is an entire book dedicated to linkers and loaders online. And it’s free: Linkers and Loaders

Categories: Blog, Tips 'n Tricks Tags: , , ,

The hidden default constructor in C++

February 19th, 2010 No comments

I think I’m going to start posting about general C++ stuff too and since C++ is my favorite language (aside from assembly) I thought it would be interesting to post obscure C++ things that I find. Today I’m going to talk about a blog post that I found a while ago regarding constructors.

The fellow (I forgot where I saw it) mentioned that there was a significant difference the two lines of code.

Class *pClass = new Class;
Class *pClass = new Class();

The first line will NOT initialize intrinsic data types. So they will be filled with whatever when the object is instantiated.
The second line, on the other hand, WILL initialize all intrinsic data types to zero.
There are a couple of issues to be aware of though:

1) There must NOT be a default constructor available.
2) This is very well compiler/implementation dependent. I haven’t actually checked the standard though but I don’t see why the standard would define such a thing since it could (theoretically) impose a performance risk.

Looking back at point 1, lets use an example:

Class{
int foo;
};

Note: No default constructor or destructor. In this case, the compiler will provide them for your automatically. At least Microsoft’s compiler will. In that case, it will be kind enough to also initialize foo to zero if you specify

new Class();

as opposed to

new Class;


Categories: Blog, Tips 'n Tricks Tags: ,

A Few Code Snippets

February 19th, 2010 No comments

Periodically I’ll stumble across a small but useful piece of code. I have a small list right now, but as I stumble across them, I’ll post them here. Note: I do not take credit for any of this code.

Pausing your application

__asm int 3;

or

__debugbreak();

Convert any data type to a std::string object

#include <sstream>
template <typename T>
std::string toString( const T &arg )
{
    std::stringstream ss;
    ss << arg;
    return ss.str();
}

Test if a float is zero or near zero

inline bool IsZero( float val )
{
    return( fabs( val ) < EPSILON);
}

EPSILON is a #define that is something small, like 0.002f
Note, I will repost, I just realized that serendipity can’t handle angle brackets…

Categories: Blog, Tips 'n Tricks Tags: , ,