The difference between a function-like macro and a function in C, C++

I’ve been working my way through some of the open courseware computer science materials that MIT hosts. The past few nights, I’ve been reviewing the “Practical Programming in C” lecture notes and assignments. For the most part, the first few assignments were really easy for me – few new concepts.

One bit that tripped me up were what looked like functions, but were actually macros (I later learned these are called macro-like functions).

Now, I know C is an ancient language and I’m sure this has been discussed thousands of times (or more) – but I still think it warrants a blog post. So here is a macro-like function:

#define squaredM(x) x*x

And here is a function:

double squaredF(double x)
{
    return x*x;
}

Here is what looks like the same code calling functions that do the same things:
double ans = 18.0 / squaredM(2+1);
double ans = 18.0 / squaredF(2+1);

You might assume that both pieces of code would be handled the same way. And you’d be wrong. I did not assume that both pieces of code would be handled the same way, but I also made an incorrect assumption how a function-like macro worked (I did not already know). The key difference is that a function-like macro is pre-processed and then compiled, while the function is compiled. In plain english, that means that when you compile the program, the preprocessor essentially creates a new piece of code, with the macro substituted in, and then compiles:

double ans = 18.0 / 2+1*2+1;

Order of operations tells us that division / multiplication, left to right, should happen first. So you actually end up with 9 + 2 + 1.

In the second example, using a function, 2+1 is already a float of 3.0 when it is received by squaredF. This may not ever be useful to you, but I thought it was cool and wanted to share it.

References:
Wikipedia (C Preprocessor)
IBM AIX Compilers Reference
MIT Open Courseware Answers

Posted in C Programming Language, C++ | 2 Comments

How Well Do You Understand “Static” Variables?

Today I realized that I did not completely understand the “static” keyword as it applies to variables, which is used in many programming languages. If you weren’t aware of the full breadth of how the static keyword alters a variable, this post should be a mind blower.

So, let’s start simple. Take the following example (it’s in PHP, but you will find EXACTLY the same behavior in ANY language that uses the static keyword on variables – the concept itself is inherited from C):

function test(){
	$test = 0;
	$test += 1;
	return $test;
}

echo test(); //1
echo test(); //1
echo test(); //1

What’s expected, right? Ok, now throw a static in front of the declaration for $test

function test(){
	static $test = 0;
	$test += 1;
	return $test;
}

echo test(); //1
echo test(); //2
echo test(); //3

Trippy, right? When a variable is declared static, it’s stored in the program’s memory for the duration of the program’s runtime (translate for web devs: from the point the static var is created till the request has finished and the page is loaded). In this case, $test is only available within the scope of the test() function, so it isn’t global, but within the scope which it was declared – it persists until the program ends.

Ok, now let’s look at how the same idea applies to classes:

class StaticTest {

	public static $test;

	public function __construct()
	{
		self::$test = 'hello';
	}

	public static function getTest()
	{
		return self::$test;
	}

	public static function setTest()
	{
		self::$test = 'test';
	}

	public function __destruct()
	{
		echo "StaticTest class is dead \n";
	}
}

class Tester {
	public function __construct()
	{
		new StaticTest();
	}

	public function __destruct()
	{
		echo "Tester class is dead \n";
	}
}

new Tester();

echo StaticTest::$test . "\n \n";

The previous example may remind you of the Singleton pattern. The important distinction to be made is that in this example, no instance of StaticTest exists when StaticTest::$test is called at the end of the program. StaticTest is instantiated by Tester, sets a static variable, and then dies. Tester is instantiated, and then dies. The static member of StaticTest itself lives on, and is still available, regardless of whether the class instance which created it is alive or not. Singletons are different because proper Singletons store their static properties privately. Thus, if the Singleton was killed (which, I’ll grant you, presents it’s own set of challenges), it’s members would no longer be accessible, even though they do still exist in memory.

To sum up, a public, static property of a class is generally equivalent to a global property, and thus violates encapsulation. Thus, their implementation within a class interface should be carefully considered. A static variable within a function persists within it’s own scope for the duration of the program’s runtime.

Posted in Abstract, PHP, Programming, Software Design | 2 Comments

Quick Introduction to the Observer Pattern

A continuation in my self-assigned crash course in design patterns, I’ve been learning more about the observer pattern recently. It’s a cool pattern, and I’m hoping I can convince some of you that it’s worth learning more about. I only have time for a quick post, and hopefully I can get in the major points – but I WILL follow up on this with some example implementations.

High Level Overview

The observer pattern does exactly what it sounds like it should do – it allows one class to observe the changes made in another. Essentially, you have a class or set of classes (the subject), that inherit an abstract interface which will dictate the methods that they must implement in order to provide updates to their observer(s). The subjects don’t actually do the talking to their observers directly; there is always a layer of abstraction to ensure the subjects and observers are decoupled.

Coming from a web programming background, it may not be immediately apparent why the observer pattern is especially useful. This is because (in my opinion) web programs (with some exceptions) tend to have a very short runtime (meaning their execution starts when you load a page and concludes when the page finishes loading). So, even though we use the observer pattern in web programming (MVC springs to mind), I don’t think it’s usefulness and role are as readily apparent as in other contexts. In programs which are “on” until they are intentionally shut down (ie programs that run on an event loop, main loop, etc.), the importance of this pattern is much more obvious.

Here are some real world examples:

- The observer pattern forms the basis for how many GUI frameworks operate. It was first introduced in the SmallTalk language, which had an extremely strong influence on Apple and the evolution of their Objective C language. Many of the programs you use every day implement the observer pattern. Qt framework (c++), a GUI framework developed by Nokia, implements the observer pattern for Signal and Slot events – ie so your program knows when a button is pushed and can hook that update to the appropriate class / method. Java likewise implements a very similar signals / slots mechanism.
- Your web browser implements the observer pattern. You know that thing the DOM? Event listeners? onSomething(doThis)? Yea.
- Your cell phone implements the observer pattern. Your phone is always sitting there…waiting…just waiting for the network to tell it there is an inbound call.

…There are tons of other real world examples. At it’s core, the observer pattern is just a standardized way of separating cause and effect to reduce dependencies within a system. I hope this has been a decent beginner’s introduction!

Resources (best I’ve found)

Source Making: http://sourcemaking.com/design_patterns/observer
IBM Research: http://www.research.ibm.com/designpatterns/example.htm

Posted in Programming, Software Design | Leave a comment

Understanding Singletons

Why ANOTHER article about Singletons?

If you search for ‘Singleton’ in Google or StackOverflow you get a bajillion and a half results.  That makes sense, because it’s one of the most commonly implemented design patterns in the history of software.  Some reasons for the popularity of the Singleton are:

A.  It makes more intuitive sense to store things you want global access to in well-defined groupings, instead of having a bunch of globally namespaced functions, constants and variables you need to keep track of (read more about namespacing here).

B.  They are incredibly easy to implement.

Stick with me, by the end of this post you’ll have a much better understanding of the Singleton, and links to some other great reference materials.

So what are Singletons, exactly?

As you may know, computer science inherits a great many ideas from mathematics, and if you want to become a better programmer – and hope to someday call yourself a computer scientist, you must understand the mathematical foundations on which computer science has been built.  Fortunately, most of the concepts are pretty easy, including the Singleton.

A Singleton, as defined mathematically, is a set (a set could be similarly described as an array, linked list, vector, etc.) which has a cardinality of 1, meaning it only contains a single tuple, and that it cannot be subject to injective functions.  In plain English, this means that a set is only a Singleton if it:

A.  Only has one root level element.

B.  Has no siblings.

C.  Can not be cloned.

If it does not meet these requirements, it is not a Singleton.

As programmers, we commonly associate Singletons with single class instances (single objects), but they could also be other data types as well.  For example, some languages, such as Delphi, C# and Charm++, allow for read-only arrays, while C++ allows you to declare arrays and vectors as constant.  I’m sure there are many other examples.  I believe (though someone may correct me on this) – that those would also qualify as Singletons using the mathematical definition – provided they meet the aforementioned requirements.

Common uses of Singletons

Singletons are usually used by programmers when they want a class instance that is truly global – meaning that various classes and functions can perform operations on the instance, and see the changes the others make, without the need to pass a reference to that class around.

A. Logging: As opposed to procedural functions in the global namespace, “Logger” classes are commonly implemented as Singletons.

B.  Truly global classes: For example, keeping state.  Session and authentication management come to mind.

C.  Database instances: Singletons can in some cases reduce memory usage in your application because a single connection point to the database is established; a new instance is not created each time a query is made.

I’d love to hear some of the ways which you have implemented Singletons with satisfaction.

Criticisms

But what is a pattern if not also a suspected anti-pattern?  Singletons, despite their heavy usage, certainly have a fair amount of haters out there.  Some of these criticisms are simply FUD (fear, uncertainty and doubt) being passed from programmer to programmer like gonnorhea in a co-ed dorm; however, some are valid, and certainly need to be factored into design decisions.

A.  It’s hard to destroy a Singleton, and mishandling can cause very subtle and perhaps disastrous results.  Say, for example, that you want your program to destruct (shut down) in a very specific way.  You can’t really have a class destruct the Singleton, because hey, if the only class that can MAKE a Singleton is the Singleton itself, why should another class be able to destroy it?  And what happens if the class that destroys it kills it before another class, also dependent on the Singleton, can use data it depends on?  This rules out having other classes destroy Singletons.  So how about self destruction?  Well, depending on the language, compiler, and other variables, you may not have any control over what order objects are destroyed in.  When you only have one Singleton, this probably won’t cause an issue, but if you have many Singletons, each of which may depend on the data of the other, you may create the same problem faced in the previous example – you have dangling references to things that don’t exist anymore.  Not good!

This barely scratches the surface of this topic, for more I’d check out this article by John Vlissides, one of the original “Gang of Four” members, who spent most of his career as a researcher at IBM.

B.  Singletons can make testing, reuse and debugging painful.  Remember, since there is only one instance of a Singleton, if one class makes a change to a Singleton member – all other classes that use that data are now using that updated value.  Misko Hevery has written an amusing post on this topic here titled “Singletons are Pathological Liars.”

C.  Inheritance.  By definition, singletons cannot be used as base classes (ie child Extends Singleton).  However, some languages (such as C#) which support nested types.  Check out this post by John Skeet, a prominent C# developer and the author of “C# In Depth”, for more info on that.

Singletons and multithreading

Threads are spawned within the process created when a programming runs.  Multithreading allows a program to essentially “splinter off” and go in multiple directions simultaneously.   Concurrency problems occur when these threads are accessing shared resources and happen to collide.  One of the most intriguing bits I’ve read about Singletons was written by Vishal Kochhar.  He explains why the standard approach to Singletons is not threadsafe, and how mutual exclusion (a concept introduced by the late Edsger Djikstra, the Dutch computer scientist  who also gave us the modern pathfinding algorithm) can be implemented in C++ classes to ensure thread safety.  The article delves into many cool things – and I highly suggest you check it out.

Most scripting languages tell you that you need not worry about thread safety – that the language designers have ensured it – but if I was working on code that depended on thread safety, and was using Singletons, I’d probably double check. You need not worry about this in languages that do not use threads (such as JavaScript, unless you are using Web Workers – which DO in fact spawn threads).

Implementation in three languages

I implemented a Singleton class in 3 languages for fun and learning.

C++

#include <iostream>
#include <thread.h>

using namespace std;

class Singleton
{
	public:
		static int val_;
		static Singleton* instance() {
			if( val_ == 0 ) {
				//lock_mutex();
				if(p_instance == 0)
					new Singleton;
				//unlock_mutex();
				//MEMORY_BARRIER();
				val_ = 1;
				return p_instance;
			}
			else {
				return p_instance;
			}
		}

		void setMember(string& newState) {
			m_member = newState;
		}

		string getMember() {
			return m_member;
		}

	private:
		Singleton(){}

		static Singleton* p_instance;

		string m_member;
};

Singleton* Singleton::p_instance = 0;

int main()
{
	string newState = "active";
	Singleton::instance()->setMember(newState);
	cout << "Member has been set to:" << Singleton::instance()->getMember() << "\n";
	return 0;
}

Please note that the ideas for mutual exclusion were taken from the article written by Vishal Kochhar, which I have referenced.

JavaScript

var Singleton = (function()
{
	var instance = false;

	/*
	* Because this is in a closure, it cannot be accessed
	*/
	var member = 'test';

	function Constructor(){

		this.getMember = function(){
			return member;
		}

		this.setMember = function(v){
			member = v;
		}

	}

	/*
	* This is what's actually returned by the closure
	*/
	return new function(){

		this.getInstance = function() {	

			/*
			* Private member functions are accessible once the constructor has been called
			*/
			if(instance == false){
				instance = new Constructor();
				instance.constructor = null;
			}

			return instance;
		}

	}

}
)();

//print(Singleton.getInstance().getRand());
Singleton.getInstance().setMember('whatuppppp');

print(Singleton.getInstance().getMember());

Please note that this JavaScript implementation is almost certainly not a "real" singleton - it can be copied and passed around.

PHP


//Shows how a singleton can be used to keep state for the duration of a request
class Singleton
{
	private static $instance = 0;

	private static $member = null;

	/*
	 * Private constructor prevents object initialization ith new keyword
	*/
	private function __construct(){}

	/*
	 * Creates an instance - accesed statically since constructor is private
	*/
	public static function instance(){
		if(self::$instance)
		{
			return self::$instance;
		}

		//Return a new instance if one does not exist
		return new Singleton;
	}

	public function setMember($v){
		self::$member = $v;
	}

	public function getMember(){
		return self::$member;
	}

	/*
	 * Prevents cloning (ie copying the instance or using the clone keyword)
	*/
	public function __clone(){
		trigger_error('Singleton instance cannot be cloned.', E_USER_ERROR);
	}

	/*
	 * Prevents Unserializing of Object
	*/
	public function __wakeup(){
		trigger_error('Singleton instance cannot be unserialized.', E_USER_ERROR);
	}
}

class A
{
	public function __construct(){
		Singleton::instance()->setMember('active');
	}

	public function __toString(){
		return Singleton::instance()->getMember();
	}
}

class B
{
	public function __construct(){
	}

	public function __toString(){
		return Singleton::instance()->getMember();
	}
}

//Class A sets the member's value to 'active'
$a = new A;
echo "Member after being set by class A: $a \n \n";

//Class B simply returns the member value set by class A
$b = new B;
echo "Member after being returned by class B: $b \n \n";

Conclusion

Singletons are a popular pattern with both benefits and challenges associated with them. If you want to make use of this powerful pattern, ignore anyone who treats them as artifacts in a religious war and focus on understanding what they are, why and how they can be used.

Disclaimer

This post is essentially self-assigned homework.  I've written it to increase my own understanding of Singletons, their uses, limitations and theoretical underpinnings.  I hope this has helped you, but also hope you verify any assumptions I may have made, and point out any mistakes.

Posted in C++, JavaScript, PHP, Programming | Leave a comment

Add support for dbase in php 5.3.8

PHP’s dbase extension allows you to work with .dbf files in PHP. After php 5.2, you can no longer compile php with dbase support, so here’s how you can add it to your php installation:

1. Download dbase: http://pecl.php.net/get/dbase

2. Extract and cd into.

3. sudo phpize

4. sudo ./configure && sudo make && sudo make install

5. Add extension=dbase.so to your php config and restart apache.

Done!

Posted in PHP, Programming | Leave a comment

Tackling the Linux Network for Small Business – Part 2 – Hardware and Topology

Believe it or not, this is the easy part. There aren’t that many physical components that make up a small business network, and acquiring all of them should be both easy and fast. First, let’s start with a diagram (click to enlarge), and we’ll drill into each piece in more detail.

small business linux network

So, basically your internet service provider (ISP) is going to give you a public IP address so that you can connect to the internet. Typically, an ISP will only assign you one IP. The internet is essentially just one huge network, and having an IP allows you to be in that network.

Yea, dude, you’re gonna need a firewall

Go to whatismyip.com and get your IP address. Copy and paste that IP address into your browser and see what you get. If you’re using a standard router, or are directly connected to the internet and are running a web host on your computer, you’ll see either your router’s login page or whatever content your computer publishes on port 80. The ramifications of your computer / server having an IP on the internet are that other computers can see you, just like you can see them. All those websites out there are just other computers (or clusters of computers).

A firewall is a device (either physical or virtual) that protects your computer / server from outside intrusion by filtering out what connections can be established. At the simplest level, this is done by opening and closing ports, and by deciding which IP ranges you will allow connections from. A good firewall setup will typically only allow connections on the ports that seem to have a good reason for being open. Some examples:

  • Port 80 allows HTTP connections. This is how you browse the web
  • Port 443 allows HTTPS connections. This is how you checkout securely in a website payment process
  • Ports 22 and 21 allow for SSH and FTP, respectively, two ways of interacting with other computers (the former being total access, the second being file server access)

There are thousands of ports on a computer, many of them for unique processes you’ve never even heard of, some of them ready for you to assign a purpose to them. All of these ports give attackers MANY doorways to enter your network. Best practice is to only allow connection on the ports you need. Ports 80, 443, 22 and 21 would be pretty standard.

If you aren’t running a firewall – you are wide open. Once I get your IP address (and I could do that by scraping IPs from forums, or hell, even using nmap to try certain ranges and see who I can ping), if you aren’t running SOME type of firewall, I can own your bases. So make sure you include one in your network.

What your server does

Your server is probably the most important piece of your network. Beside the fact that it will be running all kind of software that your users need, it performs some very important functions just in keeping the network online. For example, your server can:

  • Assign IP addresses to other machines on the network
  • Share an internet connection and speed up your internet by circumventing your ISP’s DNS
  • Provide an authentication mechanism for other machines on the network to use
  • Facilitate cross-platform file and printer sharing
  • Provide shared software to use across the network

Building your server

The great thing about Linux, derived from UNIX, is that it can run and perform fairly well on just about any hardware (you can even run UNIX on a gameboy, though I don’t recommend it here = )). You’ll be building what essentially boils down to a computer. Here’s what you’ll need:

  • A motherboard
  • A processor, heatsink and fan (the heatsink and fan that come with processors usually suck)
  • RAM
  • A hard drive
  • A motherboard
  • At least 2 ethernet devices
  • A case (housing) for all of this to sit in)

Once you get all the gear, assembly is pretty easy, and is well documented elsewhere. The main thing to ensure is that everything is compatible with everything else. For example, your motherboard will support a specific chipset, so you need to choose either a motherboard or a processor and then getting a matching component. RAM types supported and the size of your hard drive (the physical dimensions, ie 3.5 inch or 2.5 inch) can vary too, so just make sure everything matches up.

Don’t feel like you need a CD drive to install the OS. You can easily load your OS from a USB drive or from the network.

Keep a backup!

Obviously, your server is your network’s lynchpin – and if it goes down it is really bad news…so make sure you have a backup. Lightning, hacking, or random hardware failure – you have to be prepared for it all.

I recommend building a secondary, much cheaper machine that you can quickly replace the more powerful version with if you absolutely have to. You’ll want to keep a daily backup of your main server so you can easily load the image onto your backup system.

The 802.1x switch

I didn’t know about this either, and when I asked about RADIUS server on ServerFault, I got flogged by experienced server admins for not knowing. 802.1x is a protocol developed specifically for handling network authentication. You can read a really good 802.1x overview here.

Unfortunately, not all networking devices support 802.1x, so you need to get one that does support it. Managed 802.1x switches start at a few hundred dollars and can get really expensive. I bought a ZyXel GS2200-24 and am really happy with it so far.

You’ll need to read your switch’s manual as it relates to creating LANs, enabling AAA / radius (802.1x), and port authentication just to get a basic setup rolling, but it should be too tough.

The patch panel

This is just a way to keep from looking at a nasty nest of jumbled wires going into your switch. Basically, you wire cables directly to the back of your patch panel (instead of using an RJ45 and plugging them in). Then, you run a short cable (under 6 inches) from the patch panel to the switch, and you label each port on the patch panel. This makes it really easy to keep track of where each wire goes, and to enable easier termination and troubleshooting.

This does mean a lot of extra wiring work, but it should be worth it.

802.1x Wi-Fi

With 802.1x enabled Wi-Fi, you’ll be super secure as long as you don’t transmit passwords in clear text. Get a wireless router which supports 802.1x and deploy where you need a signal.

The LAN

All the other machines that will connect to your networked components. Depending on the size and complexity of your network, you could have other servers, patch panels and switches at other points in your network. Imagine that this part can be very simple (just a few computers) or very complex (many switches, many wireless access points, and other servers which perform various functions).

Summary

I hope this gives you a good introduction to the physical components of the small business network I’ll be walking you through. Please feel free to ask me any questions you might have!

Posted in Internet, Networking | Leave a comment

Tackling the Linux Network for Small Business – Part 1 – Goals & Overview

I’ve been working on a Linux driven network for my family’s small business, Froedge Machine. It’s been an awesome, engrossing experience so far working on this – and the farther I delve the more I realize just how approachable this type of project is. I’m far along enough in the project now that I can see the light at the end of the tunnel and am confident enough to start teaching others how to do this – because it’s really, really, insanely cool. So without further delay, here were my goals in approaching the project:

- User authentication required across the network
- Proxy / captive portal
- Varying permissions / workgroups
- Software running in an intranet – not on the cloud (everything from accounting to project management, to timecard entry, to security systems), and accessible via VPN and in some cases web services
- Automated backups, storage and system updates

The first thing I did was hire another network admin to just come in and talk to me for a few hours. He was more of a hardware focused guy, which was fine, because I had no idea on even basic things – like the difference between a switch and a hub (basically that a hub “floods” traffic while a switch routes it intelligently more detail), or how to put an RJ45 on a Cat5e cable. I spent some time checking out Rate My Network Diagram to see some examples of large and small networks, and the physical and virtual components that compose them.

On the software side, I knew I wanted to run Ubuntu Server as our central server, despite the advice of many seasoned network admins on ServerFault who advised “Just use windows server, man, it’s a rock, and everything will just work (as a disclaimer, my experience with Microsoft products is it usually does just work, however klunkily).”

My rational for going with Ubuntu was:

  • I already knew Ubuntu fairly well, as I’d been running it for web servers (and doing all the configuration myself) for a couple of years.
  • Open source means I can make it do whatever I want
  • In the future, clients will be increasingly cross platform (ie I don’t think we’ll be running all PCs in 10 years – several people are using Ipads at work, a few run Linux at home, I use a macbook, and a lot of machines and devices that we could plug into the network run on Unix)
  • Ubuntu is crazily well supported.
  • Did I say I can make it do whatever I want it to?
  • The internet (the biggest network I know of) runs on UNIX

Since choosing a platform and defining some goals, I’ve accomplished quite a bit. So far I:
1. Ordered / assembled of my hardware
2. Got Ubuntu Server running on the machine
3. Configured my managed switch
4. Set up a DHCP server
5. Configured 802.1x authentication via RADIUS and got it working on Mac, Linux & Windows clients
6. Got internet connection sharing working
7. Set up a DNS cache / server

I’ve got a lot left to tackle, but I’m encouraged by the progress I’ve made so far. One of the toughest parts about this project has been the lack of information that brings all of the pieces together in context, yet also drills into detail on the implementation. I’d like to dedicate some time to writing a series of posts which drill into each piece of this project – hardware, networking and software. Hopefully, it will save some time for someone else out there who wants to tackle this kind of project.

The first post will be about hardware – illustrating the physical pieces that go into a computing network and the pieces that they play, and providing some recommendations on what you can get started with. Stay tuned!

Posted in Networking, Programming | Leave a comment

PCI Compliance Step 5 – Adding Automated Virus Scanning to Your Ubuntu Server

Number 5 of the 12 PCI compliance steps in the SAQ D is to “Use and regularly update anti-virus software or programs.” We all know that this *really* isn’t needed – but it’s in the PCI compliance requirements – so here’s an easy way to do it.

Install ClamAV:

sudo apt-get install clamav

And then create a simple bash script that will run clam and send you an email with a summary of the scan:

#! /bin/bash
sudo clamscan -i -r / | sendmail calvinfroedge@gmail.com

The -i flag tells clam you only want to know which files are infected (if any), the -r is to recurse into directories. The pipe then sendmail is to put the output from the clamscan into an email and send it to you.

I’m using SendGrid as my email provider, and it’s easy as hell to integrate with Postfix. Here’s how:

http://docs.sendgrid.com/documentation/get-started/integrate/examples/postfix/

Finally, schedule this to happen each day (or whatever). Put this in your contab (sudo crontab -e):

01 04 * * * /bin/viruscheck

And that’s it! You’ve just fulfilled step 5 of PCI compliance = )

Posted in PCI Compliance, Programming | 2 Comments

Getting HMVC to play nicely with deeply nested config files in Sparks

I was recently debugging an issue with Codeigniter Payments and HMVC. The issue was that config files were not being loaded if they were deeply nested – for example:

config/payments/my_gateway.php

The MX_Config path explodes the filepath provided on forward slashes, so if you do anything other than this->load->config(‘whatever’), the file you want won’t get loaded, since only the last segment will be sent to the CI_Config class.

I was able to implement a workaround by modifying the MX_Config class, and by passing TRUE as the third param when I loaded a config file in a spark (this asks the config loader to fail gracefully, returning FALSE when a config file isn’t found instead of using the show_error helper).

Updated load function in MX_Config:

        public function load($file = 'config', $use_sections = FALSE, $fail_gracefully = FALSE, $_module = '') {
        		$original_file = $file;
                if (in_array($file, $this->is_loaded, TRUE)) return $this->item($file);

                $_module OR $_module = CI::$APP->router->fetch_module();
                list($path, $file) = Modules::find($file, $_module, 'config/');

                if ($path === FALSE) {
                        $try1 = parent::load($file, $use_sections, $fail_gracefully);
                        if($try1) return $this->item($file);

                        $try2 = parent::load($original_file, $use_sections, $fail_gracefully);
                        if($try2) return $this->item($original_file);
                }  

                if ($config = Modules::load_file($file, $path, 'config')) {
                        /* reference to the config array */
                        $current_config =& $this->config;

                        if ($use_sections === TRUE)     {

                                if (isset($current_config[$file])) {
                                        $current_config[$file] = array_merge($current_config[$file], $config);
                                } else {
                                        $current_config[$file] = $config;
                                }

                        } else {
                                $current_config = array_merge($current_config, $config);
                        }
                        $this->is_loaded[] = $file;
                        unset($config);
                        return $this->item($file);
                }
        }

This tries the original path if the config file isn’t found at the reformatted path. Kind of a hack, I know – but I couldn’t find a more elegant way around this. Any suggestions are appreciated – but if you just need it to work – I hope this helps.

Posted in CodeIgniter, PHP, Programming | 2 Comments

Дом Водка – My Last Night on the Black Sea

I lived in a little village on the black sea for about 3 months in 2010, staying with a wonderful couple whom I had the great fortune of befriending. The village was at one time an old Soviet military base that while still somewhat active (though controlled by the Ukranian government now), is now pretty relaxed. The village used to be available to only Soviet soldiers, but after the Cold War ended was opened up to the general public. Now, it is a sleepy resort town, mostly full of good hearted people who generally spend their time preparing for the coming tourist season when the nightclubs on the pier open and the hotels and vacation rentals fill up. Most seemed to spend their spare time catching fish, meeting friends at the local pub and relaxing. Living in this village was like stepping back in time – a place where 70s model Ladas (a polish made, box-like car) line the streets and where one can find everything he needs from the small shopkeeper and the weathered farmer at the market. In this village, there were no chain stores, statues of Soviet war heroes lining the streets, and kindly Babushkas who created every delectable piece of Ukranian and Russian foodstuffs one could ever hope to chance upon. Needless to say, despite the long commute to the city, I grew quite fond of this place, and quite enjoyed my time there.

I was certainly an oddity in this little seaside village. Several times a week I would run 5-10 miles and sometimes more – through the village and up the beach, down the unpaved, criss-crossing backstreets, through the forest and the park. There were few runners here, and on top of the fact that I spoke really horrible Russian – I soon developed quite a reputation. As my friend would tell me – “You are famous here, Calvin.” At first, people just stared, but over time – and as my Russian improved – the village folk began to take a more direct interest in me. The good people I bought my food from (and oh, what wonderful food it was) slowly began to initiate conversations with me, the girls on the bus began to to ask me what I was doing here, and the “gangs” of teenage boys began to corner me and ask me to drink a beer with them, take a photo, say something in English, or all three at once.

In the middle of this village, and across from the Lenin statue, was a lone supermarket – and certainly not your average supermarket. This supermarket consisted of 4 rows of Vodka, 2 of beer, and 4 of canned foods, rice, buckwheat, and other staples – and of course – a bit of produce, meat and dairy. This layout was pretty typical for a small Ukranian supermarket. What was not typical was the night club and “hotel” upstairs.

One day, luckily my last day there, I was buying Hurman (hoor-man) at the supermarket – which is basically a persimmon twice the size of your fist (looks like a persimmon, tastes like a persimmon – but freaking huge). While I was checking out, a man walks up to me and says in very broken English, “Boss want meet you.”

“Ok?”

In Russian… “Please, follow me.”

Half from curiosity, and half from not feeling this was an offer I should refuse, I followed the man to the back of the supermarket and into a room filled with computers. The man who occupied the room wore Italian shoes, tight jeans, and a black leather jacket. He was smoking a cigarette and looked to be about 40.

In Russian…

“Hello, I am boss. My name is (we’ll call him Vladimir). I have hear of you – they say you computer guy. This is good, because I am need server administrator. Do you want job?”

Surprised and certainly amused, I kindly declined, introduced myself, and told him how much I enjoyed the Hurman. Assuming I must have misunderstood him, he responds,

“Ok, see man, my wife teacher English. You talk her – you understand she say. Please, one moment.”

He frantically dials a number, briefly explains the situation to his wife, and hands me the cell phone. A woman speaking in understandable English asks me “Do you want job as server administrator? My husband want hire you. He pay 400 hryvna per week (about $50).”

“No, no. Thank you, I have job.” I kindly thank her for her help and hand the phone back to Vladimir, who is still slightly bewildered but now seems to understand that I don’t see this as a stellar, upward trending career move.

In Russian… “Ok, ok,” he rationalizes. “You not want job. I am see. We be friends then, is good?”

“Sure!” I shrugged.

“Ok, please, follow me, friends drink together.”

“No, no, I don’t drink” I explained.

“Oh, please, just a taste, I want show you something. This good Vodka, DOME VODKA (House Vodka). Germans leave in WW2. This Vodka not for customer – only friend drink.”

I told him, “Ok, please, show me what you wish.”

The man leads me upstairs to a small “hotel” and proudly shows me his 8 or so rooms.

“You see? This is hotel.” ..and opening the door to the night club… “And this is club!”

Still gleaming, by this time I’ve noticed that he’s already been sipping the Dome Vodka a bit. He disappears behind the bar for a moment, and returns with a huge, clear jar of Vodka. When he opened it, it was obvious that this was indeed very good Vodka.

You should know that when Ukranians / Russians drink Vodka, they don’t drink from those pesky things we Westerners call shot glasses. They pound mason jars (exaggerating just a bit, but not much) full of the stuff – one after another – and usually eat dried fish or raw pork fat (called Sala). He set my own mason jar in front of me and proclaimed generously “Ok, now we are drink.”

As I pretended to sip my Vodka, Vladimir proceeded to slowly recount the executive summary of pretty much his entire life. He spoke in Russian, so I only caught half of it, but I caught enough to get a good feel for who the guy was. He explained how he had come to the village after an exciting career as a captain in the KGB, and had settled into the quiet life of a local mafia boss. I just kept nodding my head, seeming interested, and assuring him that Americans did not feel animosity towards ex-KGB officers. After half an hour or so of this he was nearing a table-checking state (when you’re drunk enough that your head sways back and forth with your speech and you near headbutting the table), and seemed to have built up quite a liking for me. He said:

“Ah, you are good American. I am like you. Listen, I make you an offer, friend. First, if you need ride, or to be ride to airport, I arrange a Porsche to get you. And if you need girl – just ask me. Also, I am man who solve problem. If you have problem here, you let me know, and mans with machine gun come in car and solve problem.”

In one slurred sentence, he had just crossed the threshold from amicable ex-Soviet Agent with interesting stories to “guy who solve problem with machine gun.” It was time to go. After spending a few minutes looking at the various photos hanging on the wall of the club and complimenting Vladimir on his fine work putting all of this together, I explained that it was now very late, and I must get up very early to catch the bus. After insisting that he arrange a car for me, and me very politely refusing, he finally agrees to having 2 of the supermarket employees escort me across the parking lot. The supermarket employees walked with me across the parking lot, explained that boss is very drunk tonight, and wished me a pleasant evening.

I haven’t been back that supermarket since, but if I ever do find myself there again, I’ll probably avoid speaking and count myself lucky for having a somewhat impressive beard on my last visit. ..and hey, it could have just been the House Vodka talking.

Posted in Adventure, Travel | Leave a comment