Reducing API modifications

A colleague of mind gave me a really cool idea that’s so simple I never thought about it from a design perspective. Sometimes, a function might take several arguments, where each argument represents a configuration value.

If, in the future, you need to add more settings you can add more parameters… But that causes the API to change, which is a huge hassle most of the time. Instead, it’s better to create a struct and pass that in. That way, the API is kept the same. You probably want to initialize the struct to some good defaults though.

So now, it doesn’t matter how many settings you might add in the future, the API doesn’t change. In fact, if you look at the Win32 API, you’ll see they do the same thing. The function takes a struct, and a bunch of stuff you need to set in the struct. This allows the API to be usable well after it should be be killed without the older apps crashing. 🙂

Comments – 01

I think the APIs should be most self documenting. So I prefer to not add any comments unless it somehow helps. Obviously, this doesn’t help if the user wants doxygen documentation. If you do add comments, they should be in the .cpp file only. The reason for this is because reading the .h file is nice, neat, and compact. Otherwise, your header files are massively huge and difficult to digest. But if you do need comments, make sure they’re doxygen style.

So in the cpp file, prefer to have something like this:

There’s no point in adding comments to this function because it should be obvious. But I prefer to have the divider for readability. If you need comments, add them doxygen style, like this:

This of course causes problems. If all of your function comments are in the cpp, you need the cpp to read the documentation. This is okay for me, but not okay if someone else uses the library precompiled. But then again, you’re probably going to have to compile the sources yourself anyways since there’s no guarantee the ABI won’t change between versions of the tool chain.

This is a catch 22. You must build doxygen comments in order to see the documentation. Or ship the source code. I really don’t care because I don’t intend on publishing any of my code… Right now anyways. But I’m not sure if it would make my life easier just putting them all in the .h file.

Linux Quick Reference

General Sys Admin
Misc Commands
uname -r – Displays kernel version
useful for changing between bases – calculator: bc; obase=#; ibase=#; input base # and output base #
editing the runlevel /etc/inittab
changing the runlevel on the fly: init #
Get version of ubuntu: lsb_release -a

Hardware Information
network settings: /sbin/ifconfig -a
displays cpu info: cat /proc/cpuinfo
displays devices: cat /proc/devices
list hardware: /sbin/lspci -vv
displays system status: procinfo -a
free memory: free -m
checks hard drive specs: hdparm -I /dev/device
lspci -nn – Shows hardware connected to the pci bus
lsusb – Shows USB connected hardware
lshw -C usb – Additional info on USB related hardware (good for USB dongles)
cat /proc/cpuinfo
cat /proc/meminfo
cat /proc/zoneinfo
cat /proc/mounts

File / Drive / Directory Commands
pwd – print working directory
check file or directory size: du -sh filename
get partition information: df -alh
mount a drive: mount -t dos floppy /dev/fd0
find something: apropos or whatis, which, locate (updatedb), whereis, find / -print | xargs grep
zip up a folder: tar czf filename.tar.gz folder
unzip a folder: tar -zxvf filename.tar.gz
Download a file: scp @:
Upload a file: scp @:

Process Management
ps -aux | grep program_name
list processes: ps -eflea
list processes interactively: top or htop
identify processes using files or sockets: fuser filename
run a process in the the background after logging off: nohup command & OR command &
atq : views the pending jobs
watch PROGRAM_NAME – keeps running the same program over and over
crontab -l : Displays crontab jobs
crontab -e : Edits the crontab job file
at : schedules a one time task
batch : runs a task when the system load average is low

top : interactive process management
t: Displays summary information off and on.
m : Displays memory information off and on.
A: Sorts the display by top consumers of various system resources. Useful for quick identification of performance-hungry tasks on a system.
f: Enters an interactive configuration screen for top. Helpful for setting up top for a specific task.
o: Enables you to interactively select the ordering within top.
r: Issues renice command.
k: Issues kill command.
z: Turn on or off color/mono

User Management
who – Who is connected to the machine
last – last users who’ve logged in
rwho -a

Service Management
service status | start | stop | restart
sudo /etc/init.d/service-name (start|stop|restart)
/usr/sbin/ntsysv : allows you to modify system services
/usr/sbin/chkconfig : allows you to modify system services
/sbin/chkconfig –list : lists systems services and their state
service –status-all

Package Management
apt-get install : Installs package
apt-get remove : Removes package
apt-get –purge remove : Removes package & configuration files
apt-get update : Updates the the package listings from the mirrors on the servers
apt-get upgrade : Displays list of upgrades for package
apt-get dist-upgrade : Similar to apt-get upgrade, except will install or remove packages to satisfy dependencies
apt-cache search “TextToSearch” : Searches description and package names for a keyword
Ex: apt-cache search “Intrusion Detection”
Ex2: apt-cache search sniffer
apt-cache depends : Lists package dependencies
apt-cache showpkg : Shows more details about the package
apt-cache show : Same as dpkg -s

dpkg -l : Lists all installed packages
dpkg -l : Lists individual package
dpkg -l ‘**’ : Lists packages related to dpkg -L : Lists files owned by the installed package
dpkg — contents sudo_1.6.7p5-2_i386.deb : Lists files owned by not installed package
dpkg -S /bin/netstat : Finds what package owns the /bin/netstat file
dpkg -s | grep Status : Checks if package is installed or not
dpkg -s : Lists lots of info about the package installed

Networking Commands
ifconfig – lists IP address (similar to ipconfig in Windows)
/etc/rc.d/init.d/network start – start the network service
sudo ifconfig up/down – Brings up/down the interface for the specified interface
/etc/init.d/network restart – restarts the interfaces
activating your NIC: /sbin/ifup eth0 or ifconfig eth0 up
deactivating your NIC: /sbin/ifdown eth0 or ifconfig eth0 down

sudo dhclient – Request IP address from DNS server for specified interface
sudo dhclient -r – Release IP address associated with specified interface
sudo iptables -L – Lists firewall rules
/etc/iftab (Feisty and pre-releases (Edgy, etc)) – /etc/udev/rules.d/70-persistent-net.rules (Gutsy) – File which assigns logical names (eth0, wlan0, etc) to MAC addresses
cat /etc/resolv.conf – Lists DNS servers associated with network connections (Network Manager)
/etc/dhcp3/dhclient.conf – File which sets or modifies dns (domain name servers) settings

Lists open ports:
lsof -Pnl +M -i4 : Lists open ports
lsof -Pnl +M -i6 : Lists open ports
-P : This option inhibits the conversion of port numbers to port names for network files. Inhibiting the conver-
sion may make lsof run a little faster. It is also useful when port name lookup is not working properly.
-n : This option inhibits the conversion of network numbers to host names for network files. Inhibiting conversion may make lsof run faster. It is also useful when host name lookup is not working properly.
-l : This option inhibits the conversion of user ID numbers to login names. It is also useful when login name lookup is working improperly or slowly.
+M : Enables the reporting of portmapper registrations for local TCP and UDP ports.
-i4 : IPv4 listing only
-i6 : IPv6 listing only

cat /proc/net/tcp |perl -lane ‘(undef,$p)=split “:”,$F[1]; print hex($p).”\t”.getpwuid($F[7]) if $p’|sort -n|uniq -c
netstat -tulpn
netstat -npl
-t : TCP port
-u : UDP port
-l : Show only listening sockets.
-p : Show the PID and name of the program to which each socket / port belongs
-n : No DNS lookup (speed up operation)

Shows service listening on port 8080:
cat /etc/services | grep 8080

route -n OR netstat -rn : Shows current gateway
Check routing cache: /sbin/route -Cn
route : shows/modifies current routing table
nslookup or dig – shows info about the server’s ip
iwlist scan – shows wireless networks that are available in the area along with basic encryption information
lshw -C network – Shows interface and driver associated with each networking device
sudo route add default gw – Example of how to set the default gateway to
sudo route del default gw – Example of how to delete the default gateway setting
mtr – my traceroute
change finger information: chfn
talk username [terminal-name]
write username [terminal-name] – must be using the same computer
arp -e : shows other systems’ MAC addresses
cat /proc/net/arp : shows current arp table
iptables, ipchains(old)
socklist : lists open sockets,type,port, process id and name, use fuser or kill
host : same as nslookup but will use both hosts file as well as DNS
nslookup : returns an ip address give a hostname
netstat – displays connections, routing tables, stats, etc.
netstat -punta : list externally connected processes
netstat -nap : list all connected processes
netstat -s : show network stastics
netstat -a -i eth0 :kernel interface table info
iptraf – program for monitoring lan traffic
tcpdump – allows you to analyze certain packets based on a criteria
nmap -sP : scans network for pingable ip addresses
Wireshark – network protocol analyzer

important files:
Environment Variables
To make environment variables set themselves at every login
place them in .bash_profile in the user’s home directory

– To add to an already existing one
export PATH

– To Create a new one
export PATH
check environment variables: set, env

– To reload the .bash_profile type:
source ~/.bash_profile

Common process kill signals:
SIGHUP – the modem connection has been broken
SIGQUIT – the process should stop and produce a coredump file as a debugging aid
SIGINT – the user has struck the interrupt key (^C)
SIGKILL – signal 9
SIGTERM – the default termination signal sent by kill

Octal Permissions
read: 4
write: 2

Sections of the Manual
man pages sections: man # command
1) Commands
2) System Calls
3) Library Functions
4) Special Files
5) File Formats
6) Games
7) Miscellaneous Information
8) Maintenance Commands

SVN Client Commands
checkout: svn co svn://hostname/myproject myproject
update: svn update
svnserve -d –foreground -r /home/svn

Module and kernel manipulation
1) list loaded modules: /sbin/lsmod
2) Determines if the module is compatable with the kernel
High level handling of loadable modules
Loads module and dependencies : modprobe module
3) Remove a loaded module: /sbin/rmmod modulename
4) Inserts a module into the active kernel: /sbin/insmod modulename
5) Creates dependencies file for a module (used by modprobe): depmod
6) Display information about a kernel module: modinfo
cat /etc/modprobe.d/blacklist – List modules that will not be loaded by the Operating System at boot time
lsmod – lists currently loaded kernel modules. (Example usage – lsmod | grep ndiswrapper)
sudo modprobe ***** – Loads the kernel module **** . (Example usage – sudo modprobe ndiswrapper, sudo modprobe r818x, sudo modprobe ath_pci)
sudo modprobe -r **** – Unloades the kernel module ****. (Example usage – sudo modprobe -r ndiswrapper)
dmesg | more – Lists boot log \u2014 good for troubleshooting problems with modules/drivers not being loaded

XWindow Commands
xorgcfg – Graphical configuration tool for XFree86 4.0
X -configure – generate an XF86Config file
glxgears – displays an openGL demo app
xvidtune – allows you to adjust monitor and graphics properties
how to restart xfree86 server and client:
shut down X11: sudo killall gdm or init 3
start with: init 5
Important XWindow Files:
Specifies which window manager to use and what
applications to start: $HOME/.xinitrc
Same as above: $HOME/.xsession
X Window Display Manager, automatically starts the xserver: xdm
$HOME/.Xdefaults: resources are stored here

logging into an ssh server: ssh username@ipaddress
starting a vncserver: vncserver
killing a vncserver: vncserver -k :# (where # is the display number created when you started the server)
getting regular desktop: modify the $HOME/.vnc/xstartup file
Download a file: scp @:

Printer Management
http://localhost:631 – used to manage cups – use root as the login
Current Printer Description from CUPS management webpage:
hppsc1510 (Default Printer)
Description: HP PSC 1510 All-In-One
Location: HP PSC 1510 All-In-One
Make and Model: HP PSC 1510 Foomatic/hpijs (recommended)
Printer State: idle, accepting jobs, published.
Device URI: hp:/usb/PSC_1500_series?serial=MY62ND30C90498

Open ports 50000 and 50002 in the firewall. Check /var/log/messages to verify.
Getting network printing to work from windows
Make sure the “hplip” service is running to take advantage of all the features
1) Install HP Printer on windows machine using normal USB cable
2) Install HP Printer on linux machine using normal USB cable using the hplip driver and CUPS
3) Set up samba and CUPS together.
4) Browse to My Network Places and make sure the printer is in there.
Double click it (connect to it) and install the HP PSC 950 ( or something ) driver.
5) After the driver is installed, go into “Printers and Faxes” and make sure it is
in there.
6) Right click on it and go to properties->advanced and select the correct driver (HP PSC 1510 driver)
7) Click on “Color Management” and add all the HP_PSC_1600…. files. Also add the “sRGB Color Space Profile”

Other common ops:
Send a file to the printer: lpr or lp
Shows print jobs in queue: lpq or lpstat
Cancel print job: lprm or cancel
Installing sun Java on ubuntu 11.04
sudo add-apt-repository ppa:ferramroberto/java OR sudo add-apt-repository “deb lucid partner”
sudo apt-get update
sudo apt-get install sun-java6-bin sun-java6-jre sun-java6-jdk
sudo update-java-alternatives -s java-6-sun
ls /usr/lib/jvm -> To find out which one you need (just use the generic link)
sudo bash -c “echo JAVA_HOME=/usr/lib/jvm/java-6-sun/ >> /etc/environment”
Add : $JAVA_HOME/bin to the /etc/environment file under the path file.
java -version

Logging into mysql: mysql -u root -p
Restart mysql: “mysqld restart”

mysql commands:
show tables;
show databases;

Set up so you don’t have to type in password

On the client machine that gets prompted for the password when you attempt to scp, do the following:

cd ssh-keygen -t rsa
scp /root/.ssh/ ::/home//id_rsa.pub2 (otherwise rename it to pub2 so it doesn’t overwrite the one on the server)
ssh @
cd /root/.ssh
cat /root/.ssh/id_rsa.pub2 >> authorized_keys
Delete the id_rsa.pub2 file when you are done.

Ubuntu Firewall
ufw enable
ufw disable

Plugins for XCode

I’m very happy that there’s a good way to use all the vim stuff within XCode. I’ve been using it for quite a while, and there was nothing I couldn’t do, but I’m also not a super advanced user.

XVim for XCode

I recommend building it from the github repo. As of right now, the current version has a crash bug in it.

Since this post is really about plugins / extensions, I recommend downloading Alcatraz. Alcatraz has quite a few extensions including VVDocumenter, which helps to produce doxygen and appledoc compliant comments. You can change themes, and other useful stuff to make working with XCode suck less.

Intro to boost::signal

boost::signal is the C++ equivalent to a C# delegate. Actually, make sure you’re using boost::signal2, boost::signal is deprecated.

It’s a little confusing at first, but I use the following “template” code below whenever I need to use them. Using a signal requires you have a few things set up. 1) A function that is called by the signal. 2) The signal to call the function. 3) Registering the function with the signal (the slot). 4) Firing the signal. I will show you this through the interaction between two classes.

Register the callback signal handler function.

You can, of course, change the parameters and types to your liking. But you’ll have to figure out how to use boost::bind to do so. See below for the definition of “RegisterSignalHandler”.

Creating the signal.

SignalType is just something to make the code easier to read. We really need two functions, one to fire the signal (if we want to do it this way) and one to register the signal handler. “RegisterSignalHandler” is merely called when you want to register a signal handler to be called when the signal is fired.

Creating the function to fire the signal.

Really any function that has access to “signal_” can fire the signal. In this case, I fire the signal passing in true the first call, and false the second. This calls all functions that have been “registered” (in the order in which they were registered).

Creating the registration function.

Coding Standards

One thing that you can do to help you code better is to see how other people code. In particular, companies. Just reading their coding standards gives you an idea about why they code that way. It may be a little boring, but sometimes it helps and it keeps the code clean. Other times, it’s just style consistency.

For example, I like to write my function methods like this:

The .h file:

The .cpp file:

The reason I like to have my parameters, one on each line is because, if you need to remove or add a parameter, it makes it a little bit easier to identify where in the list it needs to go, or be removed.

Anyways, here are some coding standards you may want to browse:

Insomniac Games coding standards
Google style guide
CoreLinux++ Coding Standards
General Linux C++ Coding Standards

Learning vim

I found a pretty good tutorial on how to use vim.
It walks through some basics and some other useful stuff.

WebGL Test

I wanted to see if I could embed a webgl demo in wordpress. After much frustration, I was able to get it to work.

Your browser does not support the canvas tag. This is a static example of what would be seen.

Visual Studio find window formatting

1. Go to HKCU\Software\Microsoft\VisualStudio\8.0\Find
2. Add a new string value called “Find result format” with a value of $f$e($l,$c):$t\r\n where

$f is the filename
$e is the extension
$l is the line
$c is the column
$t is the text on the line

Note:  You don’t have to restart Visual Studio to pick up on your registry changes.

$p      path
$f      filename
$v      drive/unc share
$d      dir
$n      name
$e      .ext

$l      line
$c      col
$x      end col if on first line, else end of first line
$L      span end line
$C      span end col

$0      matched text
$t      text of first line
$s      summary of hit
$T      text of spanned lines

\n      newline
\s      space
\t      tab
\\      slash
\$      $

The one I personally use is this: “$f$e($l,$c)\s-$s\n”

Super Simple Singleton

Here’s a singleton that is pretty clean. No references lying around in the class. There’s nothing special about it, but it’s simple and clutter free, but it’s not templated or anything like that.

Mathematica applet test

This is just a Mathematica test. If you don’t see it, you should probably download the CDF plugin from Mathematica. I haven’t figured out how to make the little applet thingy NOT resize. I feel it’s annoying that it resizes automatically when you rotate the object. There are a lot of reasons I decided to buy Mathematica:

  1. You can quickly prototype ideas. Or I think so anyways. That’s the impression I got.
  2. Physicists model data with it for visualization, so I figured it would be handy for a variety of things I wanted to model too. I’ll probably never reach that level of sophistication, so I think I’m good along that aspect.
  3. The programming language is functional, which is something I wanted to learn anyways to improve myself. It’s still hanging around on my todo list.
  4. I’m hoping to put more math related things on my blog. This way I can demonstrate, visually, what I’m talking about with examples.
  5. I only learned up to Calculus II in college, which kind of sucks because I keep seeing things in the graphics field that requires much more Calculus than that, such as accurately describing the curvature or other features of surfaces. So, as I study higher level mathematics, I should be able to use this tool to visualize and comprehend what I’m learning better. That’s the thought anyways.

I still love my TI-89 though. *sniffles* We’ve been through a lot together. Mathematica isn’t exactly portable though, unless I get a laptop, but that’ll never be as portable as my TI-89. Unfortunately, they haven’t released Mathematica on iPad yet, so that’s out of the question. It would be a little difficult to program or model on the iPad anyways. It was kind of expensive. But the upgrades are cheaper, if I wanted to upgrade every year or so, but I probably won’t.

[WolframCDF source=”” width=”450″ height=”450″ altimage=”” altimagewidth=”” altimageheight=””]

Only check parameters on public interface methods

This was not obvious but should make some sense. Of course, it can break if you have “friends” or some other weirdness going on in your code. Let’s say that you have a class like this:

If I create an instance of this class, I have a little nice and neat package. The only way to access the data or modify the data in the class is through the public interface, like such:

As long as you verify the data coming into these public function methods that are exposed, the state of the object should be valid. You don’t need to do parameter checking on the internal function methods.

Of course, you may want to do checking on the internal methods simply because you don’t trust your calculations, but in general, the state of the object should always be sane. But you don’t know what’s going to enter the public interface, so you should always check that. Alternatively, you can use “if” statements and “throw” while validating the contract on the public interfaces, but maybe just use “assert”s on the private methods to make sure your code is internally stable while developing. When unit testing, of course, you probably only test the interface.

VsVim for Visual Studio 2012

Since I started using visual studio 2012 in April, I have discovered that the vsVim plugin extension is very very good. I highly recommend it if you want to swing that way. It’s not perfect, but it’s much more functional than it used to be and it’s frequently updated, which is great. I use it at work and I find that using vsVim, and visual studio hotkeys allows me to work without ever having to touch the mouse. These are the commonly used hotkeys that I use to navigate around:

Ctrl+S (I installed the “switch” extension) – navigates between .h and .cpp files
Ctrl+Tab – Navigates between sources files. Just pressing once goes to the last file used. Pressing multiple times allows you to navigate.
Ctrl+; – Searches for the name of a file in the project.
Ctrl+Alt+F – standard file search.
F5, Ctrl+F5, F7, Ctrl+F7 – Build commands.
F12, Ctrl+F12 (go to definition/declaration)

Header file neatness

One thing that I like to do in a class, is to break up the function methods and the data. Like this:

I separate the private data section from the private function method section. This groups all of the data together. I think it looks much cleaner this way personally.

Updating repository while fixing a bug

It may be helpful to never update your local stuff if you have files checked out and you are working on something. If you do, it may further introduce bugs into your work, which may cause frustration. This is particularly important if you are in the middle of fixing a troublesome bug. By updating, it would change the bug hunting environment, which could cause you to lose all currently gathered information.


This is a really good site if you want to get into demoscenes. You can see the source for their pixel shaders and things. It looks very simple to use.

Staying up to date
This site has a wide variety of lecture notes, papers, and conference presentations. – There is a ton of training vids on here from intel, google, random people, etc.

Classes and Lectures

There are so many sites out that can teach you things. I love it! Here are some of my favorites. Some of them are free and some aren’t.
iTunesU – on the left side of the iTunes application, it should have an entry. There’s also an iTunesU app available.

Using namespace

When learning C++, frequently people will tell you to use “using namespace std” or some other namespace like “boost”. What they don’t tell you is that you’re never supposed to use it in a header file. You’re only supposed to use it in cpp files. If you use it in a header file, every included after that directive will be using that directive. It could lead to name clashes and other issues. Also, if you put it in a header, you may unintentionally be using that directive without even knowing it, which can cause serious headaches.

Try not to use getters and setters

Avoid getters and setters. Why? Because they break encapsulation. If you need them, it’s usually a sign of bad code, “code smell”. In some cases, they can be useful, but in general, avoid them. If you think you need them, think about how else you can avoid them. Perhaps using “friend” as long as they’re behind the same architectural boundary interface. Or perhaps the class itself could do the work instead of exposing it’s privates to the world. Using getters and setters is almost equivalent to just making the members “public”.