Replacing VSCode and VSCode Remote with VSCodium and Open Remote SSH

VSCode with the VSCode Remote plugin make for an awesome Windows client for connecting to a remote Linux machine to do the real development. It’s seamless, once connected to the remote it feels like you are just working on a Linux machine. In the background it connects via SSH to a Linux host, installs a server daemon, and from then on commands are handled by the VS Code Server plugin, from the client you can open files, edit them, create new terminals, navigate, install packages, build, all as if you are directly working on the remote. It’s like a hybrid of SSH and RDP.

I love this combination. It’s how I develop at work and home. But, I don’t like the telemetry that Microsoft has added. They also seem to be slowly closing up parts of VSCode in proprietary closed source extensions. Due to this worrying progression I started looking at VSCodium, but no VSCode Remote would be a deal breaker. Luckily there is the Open Remote SSH plugin.

Download and Install VSCodium and Open Remote SSH plugin

  1. Download and install VSCodium
  2. Preferences: Open User Settings
    Add this to settings.json:
    "terminal.integrated.shell.windows": "C:\windows\system32\cmd.exe"
  3. Extensions
    Search for jeanp413 and install the “Open Remote SSH” extension
  4. Preferences: Configure Runtime Arguments
    Add this at the end of the argv.json:
    "enable-proposed-api": [
    ...
    "jeanp413.open-remote-ssh",
    ]
  5. Restart VSCodium
  6. You should now be able to connect to a remote server under Remote Explorer on the left

If you were already using VSCode and VSCode Remote before this, then your remote hosts should all be listed under the new Open Remote SSH extension and they should all still work.

Logging Structured Data From an Application

What is structured data?

Structured data is data formatted in a structured manner so that the sender can clearly communicate to the receiver each field/property/part of each message without confusion or ambiguity about where the message starts/stops, and what each field represents and it’s value.

We usually represent structured data with fields or key value pairs. The data can even be represented in a tree such as in JSON or XML.

Logging Flavours

RFC 3164 doesn’t know about structured data:

<34>Oct 11 22:14:15 mymachine MyApplication: This is the message part

RFC 5424 supports structured data:

<74>1 2017-07-11T22:14:15.003Z myhostname evntslog - ID47 [exampleSDID@12345 x="y" eventSource="MyApplication" eventID="6789"] This is the message part

systemd journal supports structured data

Logging Methods

syslog(3) designed for RFC 3164, doesn’t know about structured data.
logger(1) can log with RFC 3164 or RFC 5242, and supports structured data, but just adds it as part of the message field unless you send it to a socket
liblogging mentions structured data in the readme, but it hasn’t been implemented
sd_journal_send/sd_journal_sendv logs to the systemd journal, supports structured data

…And the most common method of getting structured data into logs

Adding key/value pairs or JSON to the message part of any logging system. This works in any logging protocol, here is an example of RFC 3164 with JSON in the message part:

<34>Oct 11 22:14:15 mymachine MyApplication: This message has JSON in it { "x": "y", "age": 123, "flag": true }

This works universally for RFC 3164, RFC 5242 and the systemd journal.

With CEE:

<34>Oct 11 22:14:15 mymachine MyApplication: @cee: { "x": "y", "age": 123, "flag": true }

Adding JSON to the message part is the lingua franca of logs, it works everywhere, even with old APIs, adding the CEE signature makes the JSON payload easy to identify.

See Also

https://rsyslog.adiscon.narkive.com/rrLJiWRs/best-practice-for-an-application-to-get-structured-data-to
https://techblog.bozho.net/the-syslog-hell/
https://sematext.com/blog/what-is-syslog-daemons-message-formats-and-protocols/
https://github.com/systemd/systemd/issues/19251

Creating a Linux Container in C++

I love Linux containers. You get a degree of separation from the host and other machines without hosting a full VM and without requiring a whole second OS.

What are containers?

A process or group of processes that are running on the same kernel as the host but in isolation via namespaces, cgroups and images

Why would you do this?

  • Share resources (3 web servers in containers on one physical server for example)
  • Less overhead and quicker to spin up than a VM
  • To experiment in Linux without modifying the host OS settings or filesystem
  • To run software or use libraries that cannot or shouldn’t be run on the host (Mismatched versions, tries to read data from your home folder, tries to mess around with other processes, spams syslog, tries to phone home or query the network, or talk to Linux kernel modules)
  • Consistent behaviour (Developers can run wildly different machines but develop within identical containers, consistent continuous integration, simulate end users’ machines for debugging)
  • Run a collection of containers that can talk to each other but can’t talk to the rest of the network (Local testing, integration testing, load testing, mess around with network configurations and firewall rules without endangering the host)
  • Run a collection of containers that can talk to each other but only one or two of them are public facing (LAMP stack, ELK stack, a cluster, etc.)
  • Set limits on memory usage and disk usage (Restrict resource heavy applications or test out of memory situations without killing the host)
  • Share folders and even whole Linux kernel modules from the host into the container.

Why wouldn’t you do this?

  • A VM or separate machine is generally a better approach if you have the resources
  • A VM can be more secure due to better isolation, not sharing a kernel for example
  • A VM can be more stable due to not sharing the kernel and kernel modules
  • Containers must be the same architecture as the host
  • Applications and libraries in a container have to be created for a version of the Linux kernel that is compatible with the host

Fair enough. How do containers work?

Namespaces, cgroups and images are set up to provide an environment for the container’s processes to run in.

  • Namespaces – Isolate the processes from the host, giving it it’s own filesystem, process tree, network, IPC, hostname, and users
  • Cgroups – Set limits for CPU usage, memory, disk and more for the container
  • Images – An image or folder containing the applications, libraries, and data that a container needs to run, for example cut down all the way up to fully featured distros: busybox, alpine, centos, ubuntu, etc. (Docker and LXC allow combining images via an overlay so you can get alpine + java + nifi for example which a smushed together into a single filesystem

Great. Now what?

What does this look like in code?
Here is my C++ rewrite of Lizzie Dixon’s excellent C container. It demonstrates setting the cgroups, creating the namespaces, mounting the busybox filesystem, and launching the child process.


NOTE: This is just a proof of concept, it doesn’t have basic, nice things like networking, package management, file system overlays, any sort of Dockerfile/makefile/recipe support, code reviews, testing, battle hardened development history, etc. It’s not Docker, it’s a proof of concept of the basics of how containers work that doesn’t hide everything away in the Go language and libraries or a “docker run” command.

Here is an example of it running:

root@laptop:~/cpp-container# BUSYBOX_VERSION=1.33.0
root@laptop:~/cpp-container# ./cpp-container -h myhostname -m $(realpath ./busybox-${BUSYBOX_VERSION}/) -u 0 -c /bin/sh
=> validating Linux version…4.3.0-36-generic on x86_64.
Starting container myhostname
=> setting cgroups…
memory…
cpu…
pids…
done.
=> setting rlimit…done.
=> remounting everything with MS_PRIVATE…remounted.
=> making a temp directory and a bind mount there…done.
=> pivoting root…done.
=> unmounting /oldroot.kCeIkg…done.
=> trying a user namespace…writing /proc/3856/uid_map…writing /proc/3856/gid_map…done.
=> switching to uid 0 / gid 0…done.
=> dropping capabilities…bounding…inheritable…done.
=> filtering syscalls…done.
/ # echo "Look ma, no docker"
Look ma, no docker
/ # whoami
root
/ # exit
Container myhostname has exited with return code 0
=> cleaning cgroups…done.
root@laptop:~/cpp-container#

Minecraft Server Cross Platform Compatibility

Minecraft cross platform compatibility chart

Note: The legacy consoles essentially cannot connect outside their own platform

References

With GeyserMC and the Java and Bedrock editions there seems to be quite good cross platform compatibility, but alas, I was hoping to connect Xbox 360 to a Java or Bedrock server which I do not think is possible.

Protocol
“The programming language and game engine have little to do with incompatibilities; rather, it is because of differences in various data formats like IDs; for example, in the PC edition each type of wooden fence uses its own block ID*, while in PE they use data values so only one ID is used (the same as oak fences in PC). More significant differences may lie in things like mob AI and mechanics like combat and items that are missing (e.g. PE does not have shields and swords presumably still block).

*FWIW, these were added by Jeb, not Notch – they are still making poor design decisions to this day, including things like using 16 block IDs for Shulker boxes instead of just 1 (they are already tile entities so they could have just added a color tag, as with beds), or using excessive encapsulation like using an object for x,y,z coordinates.”
Pocket Edition Protocol

MCPE uses Raknet protocol

I’ve seen a string like this in tcpdumps of packets between an Android tablet and a Linux Bedrock server:
MCPE;Dedicated Server;390;1.14.60;0;10;13253860892328930865;Bedrock level;Survival;1;19132;19133;
Xbox 360 Version

Version: TU74

“The gameplay was first released largely intact from Java Edition Beta 1.6.6”
I did some TCP dumps to see if the Xbox 360 was advertising its Minecraft server to the local network but didn’t notice anything.

Basic HTML5 Soundboard

readme-image.png

I made a thing. It has other people’s giant images and audio that I haven’t bothered resizing or compressing so it can take maybe 20 seconds to load as you click through the sounds. I made it as something my kids can play with on a tablet and because I’ve always thought it would be a great use for the new audio APIs in HTML5. The source code is here. Enjoy.

Stop Watch and Time Out Classes

I have a passing interest in stop watch and time out type classes. Keeping track of elapsed time, remaining time. They are very basic classes, but I find them interesting.

GetTimeMS function

The stop watch and timer classes use this function to get the system time, we actually return the system time minus the application start time to get a time relative to the application start time, starting at 0. This is not necessary, return the system time is fine, returning the time the application is running is usually just easier to think about than the time since 1970, which is kind of arbitrary.
This function uses milliseconds, if this is not enough, we can easily switch to nanoseconds.

typedef uint64_t durationms_t;
 
// Get the time since epoch in milliseconds
durationms_t GetTimeMS()
{
  static const std::chrono::system_clock::time_point start = std::chrono::system_clock::now();
 
  const std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
  return std::chrono::duration_cast<std::chrono::milliseconds>(now - start).count();
}

Stop watch class

Provides start, stop, reset and we can get the total duration.

class cStopWatch
{
public:
  cStopWatch();
 
  void Start();
  void Stop();
  void Reset();
 
  durationms_t GetTotalDurationMS() const;
 
private:
  bool running;
  durationms_t started;
  durationms_t totalDuration;
};
 
cStopWatch::cStopWatch() :
  running(false),
  started(0),
  totalDuration(0)
{
}
 
void cStopWatch::Start()
{
  assert(!running);
 
  // Started our stop watch
  started = GetTimeMS();
 
  running = true;
}
 
void cStopWatch::Stop()
{
  assert(running);
 
  // Get the time now
  const durationms_t now = GetTimeMS();
 
  // Add the duration for this period
  totalDuration += now - started;
 
  // Reset our start time
  started = 0;
 
  running = false;
}
 
void cStopWatch::Reset()
{
  started = 0;
  totalDuration = 0;
 
  running = false;
}
 
durationms_t cStopWatch::GetTotalDurationMS() const
{
  if (running) {
    // Get the time now
    const durationms_t now = GetTimeMS();
 
    // Return the previous duration plus the duration of the current period
    return totalDuration + (now - started);
  }
 
  return totalDuration;
}

Example usage

cStopWatch stopWatch;
 
// Start the stop watch
stopWatch.Start();
 
// Sleep for 1 second
const uint64_t timeout_ms = 1000;
::usleep(1000 * timeout_ms);
 
// Stop the stop watch
stopWatch.Stop();
 
// We have now waited for at least 1 second
std::cout<<"Stop watch time: "<<stopWatch.GetTotalDurationMS()<<" ms"<<std::endl;

Time out class

Allows us to get the time remaining, check if the time out has expired and reset the time out.

class cTimeOut {
public:
  explicit cTimeOut(durationms_t timeout);
 
  void Reset();
 
  bool IsExpired() const;
 
  durationms_t GetRemainingMS() const;
 
private:
  const durationms_t timeout;
  durationms_t startTime;
};
 
cTimeOut::cTimeOut(durationms_t _timeout) :
  timeout(_timeout),
  startTime(GetTimeMS())
{
}
 
void cTimeOut::Reset()
{
  startTime = GetTimeMS();
}
 
bool cTimeOut::IsExpired() const
{
  return ((GetTimeMS() - startTime) > timeout);
}
 
durationms_t cTimeOut::GetRemainingMS() const
{
  // Get the total time this timeout uhas been running for so far
  const int64_t duration = int64_t(GetTimeMS()) - int64_t(startTime);
 
  // Calculate the remaining time
  const int64_t remaining = (int64_t(timeout) - duration);
 
  // Return the remaining time if there is any left
  return (remaining >= 0) ? remaining : 0;
}

Example usage

// Create a 5 second time out
cTimeOut timeout(5000);
 
// Wait until the time out is expired
while (!timeout.IsExpired()) {
  std::cout<<"Waiting..."<<std::endl;
 
  // Sleep for 1 second
  const uint64_t timeout_ms = 1000;
  ::usleep(1000 * timeout_ms);
}
 
std::cout<<"Time out reached"<<std::endl;

Colour Picker Added Hex and Float Conversions

Colour picker hex and float entry.
Colour picker hex and float entry.

The colour pickers I see never have conversions from RGB uint8_t 255, 255, 255 to RGB float (1.0f, 1.0f, 1.0f), so I added it to mine.
HSL, HSV and YUV are also shown.
There is one bug when typing in a text colour if no single RGB component dominates then the colour palette look up fails, picking full white.
It’s in JavaScript, so as usual I am surprised by how quickly and relatively easy this was to implement. The biggest issues I had were not knowing how JavaScript converts strings to and from numbers.

Try It
Source

Some Simple Regexes for Finding If Statements

I know almost nothing about regexes, these are just some useful ones I created for checking code style, if statements specifically.

Find single line if statements (Useful when your coding style requires adding curly braces to everything):

/^ *if \(.+\).*(;)/igm

regex101

Find multiple line if statements (Useful when your coding style favours less lines):

/^ *if \(.+\).*({)/igm

regex101

Regex101 is really impressive.  You can paste a regex and check it against some test inputs.  The best part is the description of what each symbol in your regex does and even what some of the combined parts do, such as various brackets around groups of expressions.

openglmm_shaders Test 20150817

Here is a video demo of my OpenGL 3.3 library libopenglmm.
Source

YouTube Video

Materials:
Lambert shading (Mirror’s Edge style)
Fog
Cube mapping
Multitexturing
Normal mapping
Car paint (Slighty broken, I think a texture look up is incorrect)
Glass mixed with dirty metal texture (Similar to an old rusty/broken mirror)
Cel shading
Smoke particle system with lambert lighting with 4 normals that very roughly approximate a sphere (I think something is wrong with the depth texture look up)

Post render effects:
Sepia
Teal and orange
Noir
Matrix
HDR (It is cheesy and over done, but you get the idea, it would normally be a lot more tame, either brought back or blending less of the HDR textures in at the end)
Colour blind simulation (3 modes are possible, only one is shown)

Colour Picker Released

Colour Picker in action

I created a colour picker in JavaScript, then I created 3 variations that simulate the common colour blindnesses. They are all linked so that when you select a colour in one it picks the “same” colour in the others. I mainly just created it out of interest. I realise there are similar colour blind simulator tools, but I hadn’t seen any that used linked colour pickers like this.

I don’t normally use JavaScript, but I had fun doing this. The syntax is easy to read and relatively sane. The rapid development is great and the HTML5 features such as canvas are easy to use and quite powerful.

Try it
Source

Diesel Photo Manager 0.1 Released

I couldn’t find a photo browser for Linux that also imported my photos in the folder format I wanted so I created my own.

This is the first release and it has these features:

  • Simple interface
  • Thumbnail grid mode
  • Single photo mode
  • Import and sort photos into folders based on the date
  • Convert files to dng
  • Show the background thread progress on the statusbar
  • Check for updates via version.xml
  • Default to dark theme (Can be overridden with the –light command line parameter)

Still to come:

  • Fixes to the single photo viewing mode
  • Popup notifications when a new track is played
  • Work out what I want to do with the photo browser

Thumbnail browsing mode
Thumbnail browsing mode

Download
Source

Medusa Music Player 0.9 Released

I’ve release a new version of Medusa music player with these features:

  • Simple interface
  • Last.fm support
  • Date added and a full file path column
  • Drag and drop from the file manager
  • Moving files to the trash folder
  • Move files to a particular folder and remember the last 5 folders
  • Extra columns
  • Show the background thread progress on the statusbar
  • Import playlist from Rhythmbox and Banshee
  • Autoplay at last track at startup
  • Web server for controlling playback, volume and deleting tracks remotely
  • Check for updates via version.xml
  • Popup notifications when a new track is played

New:

  • Various bug fixes
  • Web server bug fixes
  • Default to dark theme (Can be overridden with the –light command line parameter)

Still to come:

  • Easy tag editing for multiple files at once

Dark Theme
Dark theme

Download
Source

Medusa Music Player 0.8 Released

I’ve release a new version of Medusa music player with these features:

  • Simple interface
  • Last.fm support
  • Date added and a full file path column
  • Drag and drop from the file manager
  • Moving files to the trash folder
  • Move files to a particular folder and remember the last 5 folders
  • Extra columns
  • Show the background thread progress on the statusbar
  • Import playlist from Rhythmbox and Banshee
  • Autoplay at last track at startup

New:

  • Web server for controlling playback, volume and deleting tracks remotely
  • Check for updates via version.xml
  • Popup notifications when a new track is played

Still to come:

  • Easy tag editing for multiple files at once

Medusa Main Window
Medusa Main Window
Download
Source

Medusa Music Player 0.7 Released

I’ve release a new version of Medusa music player with these features:

  • Simple interface
  • Last.fm support
  • Date added and a full file path column
  • Drag and drop from the file manager
  • Auto play last track at startup
  • Moving files to the trash folder
  • Move files to a particular folder and remember the last 5 folders

New:

  • Extra columns
  • Show the background thread progress on the statusbar
  • Import playlist from Rhythmbox and Banshee
  • Add autoplay at last track at startup

Still to come:

  • Easy tag editing for multiple files at once

Medusa Main Window
Download for Linux
Source

Medusa Music Player 0.6 Released

I’ve release a new version of Medusa music player with these features:

  • Simple interface
  • Last.fm support
  • Date added and a full file path column

New:

  • Drag and drop from the file manager
  • Auto play last track at startup
  • Moving files to the trash folder
  • Move files to a particular folder and remember the last 5 folders

Still to come:

  • Easy tag editing for multiple files at once

Medusa Main Window
Download for Linux
Source

Java Gotchas

Java

  • Everything is a pointer that initially points to null. Every non-POD type must be newed (I forget this one a lot)
  • The POD types (int, float, enum, etc.) behave just like their C++ counter parts.
    The boxed versions (Integer, Float) and String in Java are more like a pointer to the POD value.
    For example:

    String a = "chris";
    String b = "chris";
    if (a == b) System.out.println("The strings are the same");

    This test will always fail because operator== for pointers (Instances of anything derived from java.lang.Object) will test if the pointers point to the same memory.
    To compare boxed types:

    if (a.equals(b)) System.out.println("The strings are the same");
  • Strings are immutable in Java, this doesn’t work as expected:
    String a = "a";
    a.replace('a', 'b');
    System.out.print(a); // Prints "a" instead of "b"

    A copy must be made:

    String a = "a";
    String b = a.replace('a', 'b');
    System.out.print(a); // Prints "b"

    String toUpperCase and toLowerCase have the same problem.

  • Java finalize() is not a C++ destructor.  It is not guaranteed to be called.  If a finalize() function is called it is up to the child class to call super.finalize().
  • If you specify no access modifier in C++ the default behaviour is private to the class, in Java it is private to the package. If you are bitten by this bug it kind of serves you right because you should always specify an access modifier anyway, but it may bite you when porting old code from C++.
  • There is no way to choose what lives on the stack and what lives on the heap. It doesn’t really matter most of the time, but it would be nice to have the option.
  • There is no passing by reference, everything is passes as a pointer.
  • There are no function pointers, anonymous interfaces are probably the closest thing to it.
  • Copy vs Reference Confusion
    Car a = new Car();
    a.SetColour("red");
    Car b = a; // Takes a reference to a, does not create a copy
    b.SetColour("blue");
    System.out.print(a.GetColour()); // Prints "blue"
  • Java final is not the same as C++ const
    class PaintShop {
      public void PaintCarBlue(final Car car) {
        car.SetColour("blue"); // Changes the colour of the original car
      }
    }
     
    PaintShop paintShop = new PaintShop();
    Car a = new Car();
    a.SetColour("red");
    paintShop.PaintCarBlue(a);
    System.out.print(a.GetColour()); // Prints "blue"

Medusa Music Player 0.5 Released

I’ve been working on a music player for Linux. What I really wanted was foobar2000 for Linux but nothing on Linux is quite like it. There are lot of iTunes clones (Amarok, Banshee, Songbird, Rhythmbox, etc) but they are all too complicated or make copies of your music or show you lyrics and Wikipedia articles and include a web browser. I just want a simple music player. I can list the features I want one hand (I’ve only implemented the struck through items so far):

  • Simple interface (Most are not simple but can be configured to be simple)
  • Last.fm support (They all do this)
  • Date added and a full file path column (You would be surprised at just how many music players do not have these columns but they are so useful for sorting by)
  • Moving files to the trash folder (Most can do this)
  • Easy tag editing for multiple files at once (Most are ok at this)
  • Move files to a particular folder and remember the last 5 folders (Useful for remembering which songs I like by putting them in a “Collection” folder. I haven’t seen any other players do this)

This is a very early version, I’ve only implemented 3 out of 6 of the proposed features. By the time I release a 1.0 version I hope to have all of these features implemented.
Medusa Main Window
Download
Source

Debugging 101

Tips to help you find bugs.

Turn the warning level up and turn on warnings as errors
I know, it can be a pain, but it works. It helps you produce more rhobust, forward compatible, portable code that is syntactically correct on more compilers.
Use assert …
Assert will help you find errors before you even knew there was a problem. It is 100x better if your application tells you exactly where problems are and breaks into the debugger than for your application to crash for the customer. It goes hand in hand with compile time type safety, compiler warnings and static_assert.
… and use if () return
Think of assert as flagging the problem for you to fix and if () return as guarding the application from crashing for the customer.
Print to your errors/trace file
It can be easier to read what the application did rather than stepping through it, in some cases it is not possible to step through the code at all; full screen games, embedded devices and drivers for example. Print out variables, function entrance/exit and “I am here” lines.
Simplify
Comment out or remove as much code as possible. Slowly remove lines until you find the offending line. Try different ways of doing the same thing. Read your errors/trace file. If I had a dollar for every time a coworker tells me there is a bug in the library/standard library/compiler/Operating System and it is actually an error in their code and they have ignored a printed error, I would buy a Ferrari, and then I would buy them a pair of spectacles and I would say, “Use these to read these”, and point at the error message.
Write data to files and validate your files
For example XML, HTML, JSON, RSS, KML, PNG, WAV and MP3, can all be written to files and run through third party validation software. You can even setup a unit test to write these to a file and run the validator for you.
Use your debugger
Put break points on suspect lines, step through functions, find out the value of variables, look at what each thread is doing, look at the call stack.
Read the documentation for the library you are using
You may be using a library incorrectly, it may have conditions or prerequisites you didn’t know about. If it is too complex wrap it into something easier to digest. If its usage is error prone wrap it into something simpler and type safe, that only uses what you need. An optimising compiler will factor out your wrapper and it will have no run time impact.
Use STL
It is there for a reason. Millions of developers have used it for almost two decades, hundreds of thousands of eyes have pored over the source code to it. Chances are that it is more capable, less bug ridden and more portable than your hodge podge collection of classes. A large percentage of bugs I have seen are in classes that could be replaced by the STL. Plus developers will “just know” what your code does because they already have experience with STL. Just use it.

Pimp My Code Part 2

Xhibit

char szPassword[255];
GenerateRandomPassword(szPassword, 8);
char szText[255];
sprintf(szText, "User: %s, ID: %d, Password: %s", szUser, int(userid++), szPassword);

Don’t increment and use a variable on the same line. We know, you’re very tricky, you saved a line. You also made sure that beginners to C++ don’t know what the result will be. Keep it simple stupid. Create the simplest most readable code possible, it makes skimming over code and debugging code much easier. Fixed length arrays are very prone to buffer overruns, in this example szPassword is probably only 8 characters long after calling GenerateRandomPassword, but szUser could be any length and could definitely overrun 255 characters. The best way to mitigate this problem is to use a real string class such as std::string. We can also avoid using sprintf by using a type safe string writing class, std::ostringstream. Code using std::ostringstream is also slightly more human readable.

userid++;
const std::string sPassword = GenerateRandomPassword(8);
std::ostringstream oText;
oText<<"User: "<<sUser<<", ID: "<<userid<<", Password: "<<sPassword;
std::string sText = oText.str();

There, type safe, buffer overflow safe, future proof and slightly more readable, what’s not to like?

Pimp My Code Part 1 Redux

Xhibit

Not exactly a redux, but very similar to last time:

bIsNotEmpty = false;
if (vNests.GetSize() != 0) {
  if (vNests[0]->vEggs.GetSize() != 0) bIsNotEmpty = true;
}

First of all we don’t actually care about the size, we just care that we have (Or don’t have) a nest with eggs in it. Depending on the container GetSize may or may not be a variable look up. IsEmpty is always a variable lookup:

bIsNotEmpty = false;
if (!vNests.IsEmpty()) {
  if (!vNests[0]->vEggs.IsEmpty()) bIsNotEmpty = true;
}

We can combine this into a single line:

bIsNotEmpty = (!vNests.IsEmpty() && !vNests[0]->vEggs.IsEmpty());

I would use more descriptive variable naming change my logic to use bIsEmpty/!bIsEmpty. Using bIsNot variables is often confusing and leads to harder to read code:

bIsNestWithEggs = (!vNests.IsEmpty() && !vNests[0]->vEggs.IsEmpty());
bIsEmpty = !bIsNestWithEggs;
// Use bIsEmpty and !bIsEmpty from now on