Default values instead error handling

Take a look at the following declaration.

Although this isn’t particularly interesting, I have come across this little thing. This declaration is from Unity’s PlayerPref’s class and is an interesting way of solving a problem. The problem is “What should this thing do, if the key doesn’t exist in the player prefs?” While attempting to write something very similar, I thought, I could return an error code, which means the output is a parameter. Bleh. I could throw an exception, which is valid too. Which is also kinda bleh. But here, even though retrieving a float is exceptional, it’s handled elegantly because you don’t need to check an error code or write exception safe boiler plate code. You’re specifying what the value should be in case it doesn’t exist. Which is a case that might be expected. In other words, you’re handling the exceptional cases by configuring it. You’re telling it what you want to do in case it fails. Since this method can only fail in one way to the user (doesn’t exist, can’t get it, etc.), one parameter suffices. If it can fail in multiple ways, this could turn into something terrible as all the parameters tell this thing what to do on failure. Perhaps something better, in that case, might be to pass in a “configure” struct. But that’s kinda bleh too.

This actually has an issue that can cause some pain though. When I was using Unity a long time ago, I remember having a bug where I thought the value was in the player prefs, but really it was just the return value. The GetFloat and SetFloat actually had a slight typo where the keys were not identical. You could imagine the frustration. Although this might be equivalent to not checking the error code return value if the declaration was specified that way.

Anyways, the point is that sometimes an elegant simple solution is also a clever one.

Website slowness

I noticed that my website was super slow and I had no idea why. I did a little research and discovered I wasn’t caching things very well and I had too many useless plugins installed into wordpress. My site load time went from 8 seconds to .8 seconds after the optimizations. I used these two sites mainly to diagnose and fix the issues:

Mac dylib rpath framework bundle explanation

The purpose of this article is to teach you how to properly configure a dylib / framework on the mac and the application linking against it. If you don’t do this properly, you could be in for a long time wasting ordeal. In this article we will describe, in enough detail, how the linking process works in order to get things working and hopefully teach you enough to configure things on your own if you decide to do something in a non-standard way. We will also give you the tools and knowledge required in order to debug issues related to library loading, particularly with rpaths.

The subject
When you load an application, the dynamic linker (it’s actually an application on the mac called dyld I believe), will look at all of the references (symbols) in the application and try to resolve them (perhaps on load, perhaps not, who knows these days). In order to do this, it needs to know what libraries this application depends upon, where the libraries are on the hard drive, and also, what libraries those libraries depend upon so it can load them too, recursively. If the dynamic linker can’t find these libraries, it can’t load them, bottom line. You’ll end up with an error such as “bundle is corrupt, invalid, or missing resources” or some error like that.

Read the rest of this entry »

Send mail to yourself

While stumbling along on the internet, I found this gem.
How to create a shortcut to send an email. Basically I use this to add a task to toodledo.com.
You just click the shortcut on the taskbar, it’s all filled out, and click send to quickly add a task to your task list. And with toodledo, you can tag things and star things via the subject line.

https://www.howtogeek.com/howto/the-geek-blog/create-shortcuts-or-hotkeys-to-quickly-send-mail-to-a-recipient/

Pure Functions – Category Theory

What is a pure function? This is more abstract and not specific to C++. I ran across this term while watching a video from Bartosz Milewski at C++ Russia, 2015 on Categories. I felt that this little bit about a pure function can help programmers and when I code, I try to use it frequently.

  1. A pure function has no side effects. Think “functional language”. Or a const function in C++. It doesn’t modify any state.
  2. When called with the same arguments, it always returns the same result. (Referential Transparency)
  3. It can be memoized. Because it doesn’t depend on shared state, you can precompute the results. The example he uses is the Fibonacci sequence. A function that compute the Fibonacci sequence can be precomputed and cached off into a table.
  4. Because there’s no side effects of a pure function and they don’t modify a shared state, it’s easier to move function calls around.

Smart pointer general guidelines

Modern pointer guidelines for C++ are confusing, so I wanted to gather a list of general guidelines for pointer use. I’m sure I’m missing some though that could be added.

Most of these were taken from gotw-91.

  1. Don’t pass a smart pointer as a function parameter unless you want to use or manipulate the smart pointer itself, such as to share or transfer ownership. Only pass a smart pointer if you intend to share ownership.
  2. Prefer passing objects by value, *, or &, not by smart pointer.
  3. Pass by * or & to accept a widget independently of how the caller is managing its lifetime.
  4. Use a * if you need to express null (no widget), otherwise prefer to use a &; and if the object is input-only, write const widget* or const widget&.
  5. Put pointer in class header almost all of the time. Prefer using the pimpl idiom.
  6. You can put a reference in a class header, but it must be set at construction time, passed into the constructor. (dependency injection)
  7. Prefer unique_ptr to shared_ptr
  8. Express a “sink” function using a by-value unique_ptr parameter:
  9. Use a non-const unique_ptr& parameter only to modify the unique_ptr.
  10. Don’t use a const unique_ptr& as a parameter; use widget* instead.
  11. If it can be null, pass widget*, if it can’t be null, use &.
  12. Express that a function will store and share ownership of a heap object using a by-value shared_ptr parameter.
    1. Don’t normally use this because it restricts the lifetime of the caller.
    2. This is used to modify the shared_ptr itself.
    3. void f( shared_ptr& );
  13. Use a non-const shared_ptr& parameter only to modify the shared_ptr.
  14. Use a const shared_ptr& as a parameter only if you’re not sure whether or not you’ll take a copy and share ownership; otherwise use widget* instead (or if not nullable, a widget&).

References:
https://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters

Getting Qt + CMake to work on the mac (Sierra)

It took me forever to figure this out since the .bash_profile file doesn’t work for gui apps.

sudo vim /etc/launchd.conf
type in: setenv CMAKE_PREFIX_PATH /Users//Qt/5.7/clang_64
grep -E “^setenv” /etc/launchd.conf | xargs -t -L 1 launchctl
restart cmake
Configure
Generate

Skipping boost and stl libraries while debugging

This trick will allow you to step over boost and stl functions when debugging. It will not allow you to step into any of that stuff. Yippee.
The downside is that if you want to follow where a boost::signal ends up, you won’t be able to unless you already know where it’s going.

  1. Create a file called: boost_stl.natstepfilter
  2. Dump contents below into it.
  3. Put that file into your “C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Packages\Debugger\Visualizers” directory.

Hyperdimensional Beings

Do you believe in angels or demons, or ghosts that are destined to wander the earth for who knows how long? I love looking for connections between what we know scientifically (or what we’ve theorized) and what religions have taught and passed down. For example, I am Catholic, so I believe in angels, demons, souls in purgatory, God, Jesus, Holy Spirit, saints, hell, among other things.

I’m not too good at math stuff or the physics stuff, but I like to theorize in my spare time because I think it’s fun and to me it makes sense. For example, one of my theories is about angels and demons.

I believe angels and demons exist, but we can’t see them. Why? It’s obvious from a physics perspective. Maybe this isn’t physically accurate, but it’s just a thought. For example, let’s assume that we live in a 2D world, similar to a painting. We can only look forward and backward and that’s all we can see. We can only see things on our flat piece of art work. It’s impossible to look perpendicular outside of our picture because that’s a higher dimension. Even if we could see it, we wouldn’t be able to comprehend it. It might be like looking into the future or the past.

I think that maybe demons, angels, people in purgatory all live in a higher dimension. Where they can see us (on a painting), but we can’t see them. They can interact with us if they want as well. If we raise the concept to a 3D level, they live in the fourth dimension or 5th, but we can’t see them. But they can see us quite easily, like looking at a painting.

But sometimes angels and demons interact with us, which is quite possible. We have demons that possess people and we have angels that appear to people. This is about the same as flattening yourself and injecting yourself into a 2D painting. Not something they probably want to do too often. Sometimes people report shadows that move, or foot prints in carpet, but they see nothing. This should make sense because I can take my finger and scratch off a piece of the painting, but light only interacts in our 3D space with materials in 3D, not 4th or 5th dimension. Or does it? Sometimes people see things, but it’s faint. Maybe a stupid orb or a weird floaty thing. Their cameras do weird things too.

Electromagnetic interference is frequently reported when “ghost hunters” go into haunted houses and the lights do strange things, and the devices go crazy. Lights flicker and sometimes you hear sounds. We know that light is just another electromagnetic frequency, so it might bounce off of something if they are only a little bit in our dimension. But to us, it looks like weird floaty things.

For example, me putting my finger on the piece of art work. The majority of my finger is not on or in the painting, just a tiny bit touches the surface. But what the 2D person sees is this weird line that is suspended in mid air. It appears and disappears when I want it to. Light even bounces off of it. It can even cast a shadow or push things over, since I’m directly touching the stuff in the painting. (if the stuff in the painting actually contained movable objects).

I think sometimes we assume that electromagnetism only happens in our 3D world. If we don’t know there are other dimensions, and things in those dimensions we can’t see (so we assume nothing is there), we will be unable to describe weird electromagnetic happenings. It will be impossible. For example, today physicists talk about “dark energy” and/or “dark matter” that they throw into their simulations to get things to simulate properly. Come on, we know what that crap is. It’s stuff in a higher dimensions that warp spacetime. It has mass, it has energy, we just can’t see it but yet we know it’s there because our simulations fall apart without these “fudge factors”.

Just because we can’t see heaven or hell, or demons angels or God, that doesn’t mean it doesn’t exist. Prove those things exist? It’s in another dimension perpendicular to ours. It’s not possible for us to do so. If you’re in an elevator rapidly accelerating up, can you prove the elevator is rapidly accelerating up? Or are you being pulled downward? It’s not possible for you to know. Similarly, proving that God, satan, demons, or angels exist or don’t exist is a stupid request. Physically. Really it is. We need a different reference frame. It’s the same as asking me to prove there are more than 4 dimensions. How does someone that lives in a 2D plane prove there’s a third dimension to someone else who also lives in a 2D plane?

Singletons with controlled destruction

I’m not going to debate about why one should or should not use singletons. I’m only going to provide an improvement for the singleton. One of the problems with singletons is that they use a static member. The problem with static members is that they can be destroyed in any order on application exit. If you have more than one singleton, and have dependencies between them, you want to control destruction of the singleton on application exit.

The differences between this and the Super Simple Singleton I previously posted about a couple of years ago are:

  1. The instance is a member of the class, not a function.
  2. There is a destroy() function

The destroy function allows for controlled destruction of the singleton, which is a million times better. When your application exists, and you have more than one singleton and they are dependent upon each other, who knows which one will get destroyed first. This gives you a lot more control over it.

Todd’s Practical GTD Agile Method

I love GTD, but it definitely has some issues that I don’t like. Here are some good links to learn GTD. I also recommend reading his book, or not. It’s long and boring actually. What I ended up doing is merging a few things between GTD and Agile. I’m definitely not any sort of Scrum Master or Agile guru by any means, but I do find some things useful about it when it comes to project management.

I use Toodledo.com to implement my GTD / Agile Methodology, but my method is a little different and I will explain why. Come back here after you’ve read at least the first link above.

I organize Toodledo.com by doing the following:

I use the tag system heavily. The folder system is too limited. If I want to categorize one item into two boxes I should be able to do so. They work exactly like the folders but it’s substantially more flexible. The folders just aren’t necessary.

Read the rest of this entry »

C++ Best Practices

I love best practices. It’s like a jump start or a synopsis of all the things you should do without reading through all the heavy books.

In and out params

For functions, it’s handy to be able to identify what’s an “in” parameter, versus what’s an “out” parameter. I just got done reading an article about the Doom3 engine source code and there was something that I liked.

  1. From this signature you can identify what is an “in” and what is an “out”.
  2. The return type is obviously an “out”.
  3. The “const int val” identifies this as an “in”, even though it’s just an int.
  4. const Data& d1 is an “in”.
  5. For d2, it’s an out, and this is obvious because it takes a double pointer.
  6. For d3, this is also obviously an out. You want the function to fill something out.
  7. All out parameters use pointers, all in parameters use const or const refs.
  8. Never use a parameter as both an “in” and an “out”.

For #6, when you call this function look at what it looks like.

You can tell by looking at how it’s called what is an input and what is an output. If it has an &, you know it’s an out. Except for the return value obviously. You also have a guarantee that counter or data won’t be modified, and it won’t be modified inside the function. The function could copy the value and change it there as a separate variable on the stack, but that requires extra work. This is all about simple guarantees. I really like this approach, and I think I will adopt it for my standards.

Tools I use

Some of the tools I use to manage my tasks (life) are the following:

Toodledo

The toodledo.com website is a task management system based around the GTD technique. It’s great because you don’t have to use a particular technique if you don’t want to. For example, I use the “tags” feature to assign tags to all of my tasks for organization. It also have a handy feature where you can create tasks by sending an email to a special email address. This is handy when used in combination with a “send email widget” you can install on your phone to quickly send an email. Whenever I send an email, it’s automatically “starred” so during my weekly review, I know what to turn into actionable tasks. You can assign due dates, priorities, contexts, etc. The only thing I feel it doesn’t or can’t capture very well are files and research. You can upload files, but it requires a more expensive plan to store data. I just use evernote for this, but evernote also has limits. It has a calendar, which I use heavily and I can sort things any way I want. I currently use onenote and also Instapaper. I looked around at a lot of different task management systems (including stuff like Jira), but I have found nothing better. It can create goals, store outlines and notes among other things as well, but I find the notes are better captured in the tasks themselves or with Evernote.

Pomodoro

Using a pomodoro app is useful to doing 30 minute or 50 minute sprints. You can use an ordinary timer, but there are other apps you can use on your phone, which is easier to use if you’re at a coffee shop or something. These are very helpful so you can timebox your tasks so you don’t go overboard. It has many benefits, such as forcing you to get as much done as you can in 30 minutes, so you concentrate more. It prevents you from working too much on one task so you don’t waste time and you don’t get get burnt out on that one task.

Read the rest of this entry »

Vim – Jumping around the page

These are my favorite shortcuts for jumping around the page.

z+t = Scroll the current line to the top of the screen

z+b = Scroll the current line to the bottom of the screen

z+z = Scroll the current line to the center of the screen

H = Move the cursor to the top (high) of the screen.

L = Move the cursor to the bottom (low) of the screen.

M = Move the cursor to the center (middle) of the screen.

Task Management – 01

I’ve been learning a lot about how to manage my time (or tasks rather) more effectively. How do you get more done in a day without causing more stress and still have time for leisure. There are a few things that I personally do and I’ll just be keeping a log here on this site of some of the helpful tips and things I’ve been doing.

  1. Timebox your tasks. Use the pomodoro technique.
    1. Do 50/10 for things like projects, if you can. But sometimes this can be difficult.
    2. Do 25/5 for smaller things like homework or habits that don’t end.
    3. Alternate between difficult and easy pomodoros. For example in order “write book”, “clean out email inbox”, “do homework”, “lift weights”. Hard easy hard easy.
    4. There are many pomodoro timers for your phone. Get one.
  2. Do the most important things in the morning. After you get home from work, you won’t want to do them because you’ll be worn out.
  3. Change your environment. Coffee shop, library, or some other place to keep you away from distractions.
  4. Listen to ambient sound or noise. I listen to thunderstorms or rain + trains. It drowns out the chatter and noise from Starbucks and lets me focus a lot easier.
  5. Mix in easy very short healthy habits between pomodoros such as “drink full glass of water”. Or you can set them up to start the pomodoro instead of using your break time.
  6. Use the S.M.A.R.T. system for goals. More on this in a later post.

Next time, I’ll discuss GTD and the tools I use.

Clang omp XCode

How to switch from clang to clang-omp. I am using Yosemite and XCode 6.2.
Some of this was taken from Stack Overflow.

brew install clang-omp
cd /usr/bin
sudo mv clang clang-apple
sudo mv clang++ clang++-apple
sudo ln -s /usr/local/Cellar/clang-omp/2015-04-01/bin/clang-omp++ ./clang++
sudo ln -s /usr/local/Cellar/clang-omp/2015-04-01/bin/clang-omp ./clang
cd /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
sudo mv clang clang-apple
sudo mv clang++ clang++-apple
sudo ln -s /usr/local/Cellar/clang-omp/2015-04-01/bin/clang-omp++ ./clang++
sudo ln -s /usr/local/Cellar/clang-omp/2015-04-01/bin/clang-omp ./clang
cd /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1
sudo mv -f * ../../

Create a project in Xcode, using the Hello World code on clang-openmp website for test.
Add “-fopenmp” to Custom Compiler Flags -> Other C Flags in project settings.
Add /usr/lib/libiomp5.dylib to the build phases of project (project settings -> Build Phases -> drag /usr/lib/libiomp5.dylib into Link Binary with Libraries)
Set Header search path: /usr/local/include/libiomp

Don’t forget to add #include

boost::algorithm::ends_with

One of the biggest hassles with strings is doing what you want quickly with a one-liner. I recently stumbled across this little gem in boost. boost::algorithm::ends_with(). Basically, it’s a quick check to see if a string ends with another string. No messing around with indices and decrementing iterators, etc.

operator= for a derived class

It didn’t occur to me until now that I have never actually written an operator= for a derived class until now. Or maybe I wasn’t doing it right, or maybe I completely forgot… Here is how you’re supposed to do it:

I don’t ever recall invoking operator=() manually this way. It looks odd, but it should make sense because if you don’t, the base class will never be copied and that’s what you’re explicitly doing.

boost::uuid for unique identifiers

Frequently when I need a unique identifier I might do something silly, like create a static variable and every time an instance of that object is created, I would increment the counter. There are concerns of overflow and other weird things, such as saving and loading these identifiers and syncing the counter back up…

Instead, I would highly recommend using boost::uuid to create a unique identifier. It’s basically a GUID or a UUID. The best part is that it’s cross platform, so it works on mac/linux/windows. It goes something like this:

The syntax is a bit weird for generating a uuid, but that’s how it’s done.

You can use boost::lexical_cast to convert between the uuid and a string. As of right now, boost::serialization can not serialize boost::uuids::uuid objects, for some reason, so the best thing to do is to lexical cast to a string, serialize it, then lexical cast back into a boost::uuids::uuid data type.