File Open Dialog Box in Python

I’m putting the finishing touches on a side project at work that requires opening a file as an argument at the command line, or through a file open dialog box. Here’s a snippet that demonstrates how I implemented it.

 

import sys
import os

def choose_file():
    try:
        import Tkinter, tkFileDialog
    except ImportError:
        print "Tkinter not installed."
        exit()
    
    #Suppress the Tkinter root window
    tkroot = Tkinter.Tk()
    tkroot.withdraw()
    
    return str(tkFileDialog.askopenfilename())
    
if __name__ == "__main__":
    
    #If no file is passed at the command line, or if the file
    #passed can not be found, open a file chooser window.
    if len(sys.argv) < 2:
        filename = os.path.abspath(choose_file())
    else:
        filename = os.path.abspath(sys.argv[1])
        if not os.path.isfile(filename):
            filename = choose_file()
            
    #Now you have a valid file in filename

It’s pretty straightforward. If no file is passed at the command line, or if the file passed at the command line isn’t a legitimate file, a file chooser dialog box pops up. If Tkinter isn’t installed, it bails out with an error message.

The bit about suppressing the Tk root window prevents a small box from appearing alongside the file chooser dialog box.

 

Posted in Programming | Leave a comment

Valve Trouble

It rained real hard Tuesday night. Wednesday morning at about 5am I’m stumbling in my kitchen trying to make coffee and I hear a hissing noise outside.

“Hah”, I says to myself, “my neighbors are watering their lawn on an off day. They’ll get fined by the city if caught”.

The wife goes out to walk the dog, and when she returns she asks me why I’m watering the back yard.

Ruh roh.

One of the sprinkler zones in my back yard was running, and could have been running since we went to bed at 9:30pm the night before. They weren’t running prior to that when I let the dog out before retiring to bed, so it must have spontaneously started itself at some point in the night, meaning it could have been running for up to seven and a half hours!

The control box in the garage didn’t indicate that it was active. I did the first obvious step: I turned it off and on again. No luck. Next I cycled the system through all the zones hoping it would kick it into normal operation. No luck.

I hadn’t even had my coffee yet, so I wasn’t firing on all cylinders. I grabbed a flashlight and started popping open all the valve holes in my yard hoping to at least find the one that was stuck, not knowing what in the world I’d do if I even found it. I could only find four (of the six), and they were all in my front yard. Fortunately I came across one larger covered hole in my front yard and noticed it said “Irrigation” on the cover. Inside there was a master faucet, and closing it finally shut the water off.

This post is a bit of self-flagellation. I’ve been in this house for two years now, and there are LOTS of things (important things!) that I’m still totally unfamiliar with. I should have known about this master faucet. I knew the box was there, but I had assumed it was some electrical thing.

After a bit of Googling how sprinkler systems work, I came to the tentative conclusion that the solenoid that controls the valve for that sprinkler zone must have shorted out and got stuck on – probably due to the rain. Thinking on it more (because solenoids are very simple) this could mean that one of the lines going to the solenoid is always hot, and the control box activates that solenoid by closing the path to ground. Rainwater buildup could have provided a conductive path to ground. There’s probably a good reason that the control box provides the ground path, and not the hot path. Or I could be totally wrong how it works.

I called Collin County Sprinkler that Wednesday morning, and they had someone out this morning (Thursday). It took them 20 minutes to find the valve hole (using a fancy wire tracing tool) and fix it. They showed me a busted seal that let rainwater into the valve and up into the solenoid, and confirmed my “rainwater allowed path to ground” hypothesis (or they were just humoring me because I was asking a lot of annoying questions).

Zone Five Valve

Fortunately my back yard slopes towards the alley so the excessive water didn’t get into the garage, and it’s hot outside so it evaporated very quickly. I don’t feel dumb not knowing where that valve was because it was very well hidden under the grass. There is one last valve I need to track down (which I forgot to ask about before they left), but I think I can find it on my own.

This incident is a big wake-up call for me. There are too many critical things in this house that I take on faith that they’re functional, and will stay functional – AC, plumbing, electricity, sprinklers, garage door, appliances, etc. I need to get a handle on those things. I don’t need to know every detail, but if something goes horribly wrong I need a plan.

Posted in Uncategorized | Leave a comment

Summer Plans

My involvement with Mojo Frankenstein is taking up all my hobby energy lately. We’ve been at it for about a year now and have gigs booked on over half the weekends through the summer (and growing).

I’ve been doing just enough programming for some office skunkworks projects that I don’t feel the need to do it at home to stay sane and keep the skills up. That’s good, I think.

That being said, here are some projects I’d like to tackle this summer.

  • Raspberry Pi security camera: I’m borrowing an RPi and I’d like to get some kind of minimal framework for a wireless network security camera happening. If OpenCV works on an RPi then I’m 80% there – the rest is figuring out where to dump images periodically (FTP?). There’s a great example of what I’m trying to accomplish here.
  • Re-write the Arduino Serial Communications tutorials: They still get ~40-60 page views daily, and I’ve learned so much in the past few years that I could easily make them better. I started writing a small e-book on the subject (using LeanPub) but couldn’t make enough material to justify going through the hassle. I would have had to include 5-10 example projects to demonstrate the material and I’m just not that creative.
  • Write about my ray-caster experiment: I’m bad at math, so I tackled a math-heavy(ish) project. I got results (rays were cast, walls were detected) but I was only able to figure out the naive way of doing it. There is a fancy way to do the ray casting using something called DDA, and I want to wait until I figure it out before writing it up. Every time I think I’ve worked it out with pencil and paper, I run into a massive wall (pun intended). It might be better to instead write about the process of learning this algorithm while I’m trying to learn it. That’s worked wonders for me before.
  • Write about problems I’ve having with Python package/module organization: I’ve been writing a semi-complicated Python package for work stuff. In an effort to be good I’ve tried to not just make it one monolithic .py file and split up the major classes into their own Python modules. For the life of me I can’t figure out any rhyme or reason to how the packages refer to each other, and what role __init__.py has in it. Again, I want to be good and not just have “from foo import *” in every module since it’s considered bad form. I don’t want to put work stuff on this page, so I’d have to write a contrived example that demonstrates my point (and hope that someone on StackOverflow or /r/python can help me out). I’ve found legit issues with the documentation before, and I’m hoping that this is simply a matter of documentation being incomplete as opposed to me being dense.

I think that’s a pretty ambitious set of goals.

Posted in Hobbies, Programming, Technology | Leave a comment

Removing zeros from a Python tuple

I’ve been working with Python’s ctypes module to shuttle data back and forth with a Windows .dll. One of the arrays the .dll fills is pre-allocated, but not necessarily all used. So I’ll wind up with a tuple like this:

>>>some_data

(42, 33, 89, 0, 0, 0, 0, 0, 0)

It’s harmless to have the trailing 0’s, but for the sake of tidiness I want to remove them. Python tuples are immutable, so there aren’t any methods for just chopping them out. What you can do is fill a new tuple with just the non-0 values. Here’s a fancy way of doing this using list comprehensions.

>>>some_data_fixed = tuple([x for x in some_data if x])

>>>some_data_fixed

(42, 33, 89)

Which basically says to fill a list with x for every element x in some_data if it evaluates as true (meaning non-0), and then cast it to a tuple.

This example is in the official documentation for list comprehensions.

Posted in Programming | Leave a comment

Win32 and SFML noodling

I ran into a problem that I thought would be best solved by combining a prior UI framework and SFML. There are a zillion reasons you’d want to do this – if you need any kind of UI element (button, menu, text entry, etc) with an SFML project you quickly run into this crossroad.

GTK+, the only UI framework I’m familiar with, has a C API with its own wacky OOP implementation. There is a C++ binding called GTKMM, but some of the tutorials and code samples I’ve seen are bit off-putting.

I researched Qt and didn’t find a lot of hope there. Any framework that seems to insist on using its own development environment sounds like a bad time. There are Visual Studio plugins, but I didn’t see any clear indication that they would work with Visual Studio Express 2013.

Visual Studio Express 2013 obviously has Win32 support and project wizards built in, so what about that?

win32SFML

This seems to work. I referenced the Win32 sample on the SFML creator’s Github repository, as well as this outdated tutorial on the SFML site itself.

A few years back I ran through a few Win32 tutorials in order to understand some demo code at work, but the stuff that gets generated with VSE2013 looks nothing like it. I’m going to have to do a lot of research if I want to keep going forward with this.

There are lots of big questions, like how do I intercept SFML events? Does the Win32-generated window get them first, and I have to intercept/interpret those and then pass them to SFML? What about timing loops (a big deal in some of the game programming I’ve been doing)? Why does the window go white when I resize it?

Posted in Programming | Leave a comment

Initializing a C++ class with a reference to another class

I’ve been working on a small game that has a Player class and a Render class. The Render class needs to know about the Player class so that it can draw the player in the right spot. My first pass at this had a method in the Render class called UpdatePlayerLocation where I passed it the Player’s location.

This seemed a bit inefficient. I figured it would be better if my Render class was initialized with a reference to my (existing) Player class, so that any time the Player location was updated my Render class would already know about it.

All of my attempts to get this to work resulted in a compiler error, or the Render class only creating a local copy of the Player class, meaning my updates to the Player outside of Render were ignored by Render.

I decided to create a small program to test my methods and figured it out. It’s extremely troubling how I got it to work. Let me demonstrate the wrong way (only a local copy created), the error way, and the right way.

The general idea is that I have a class called SomeNumber that is initialized with a number, and has methods for getting and setting this number after initialization. I have another class called NumberPrinter that is initialized with knowledge of an instance of the SomeNumber class. NumberPrinter prints the number stored in the instance of SomeNumber class that it’s passed. The program(s) below show the definitions of the SomeNumber and NumberPrinter classes, and the main() function initializes the classes, lets them print their number values, changes the SomeNumber number, and prints again. Ideally the number change in SomeNumber will propagate to NumberPrinter (propagate is the wrong word since it’s just a reference, but you know what I mean).

The Wrong Way

#include "stdafx.h"

class SomeNumber
{
public:
	SomeNumber(){};
	SomeNumber(int number)
	{
		mNumber = number;
	}

	void SetNumber(int number)
	{
		mNumber = number;
	}

	int GetNumber()
	{
		return mNumber;
	}
	void PrintNumber()
	{
		printf("In SomeNumber: %i\n", mNumber);
	}

private:
	int mNumber;
};

class NumberPrinter
{
public:
	NumberPrinter(SomeNumber& somenumber)
	{
		mSomeNumber = somenumber;
	}

	void PrintNumber()
	{
		printf("In NumberPrinter: %i\n", mSomeNumber.GetNumber());
	}

private:
	SomeNumber mSomeNumber;
};

int _tmain(int argc, _TCHAR* argv[])
{
	SomeNumber somenumber(42);
	NumberPrinter numberprinter(somenumber);

	somenumber.PrintNumber();
	numberprinter.PrintNumber();

	printf("\nSetting SomeNumber to 27\n\n");
	somenumber.SetNumber(27);

	somenumber.PrintNumber();
	numberprinter.PrintNumber();

	getchar();
	return 0;
}

This was the wrong way. The output is:

wrongway

The second printout of SomeNumber and NumberPrinter doesn’t match. This is because the class definition of NumberPrinter is wrong. It looks like it’s being initialized with a reference to a SomeNumber class instance, but it seems that setting a local (non-reference type) instance of SomeNumber to this passed reference only creates a class-local copy. mSomeNumber becomes a brand new instance (copy?), and isn’t affected by anything done outside of NumberPrinter. This seems obvious in hindsight.

So I figured that I should simply not declare my private mSomeNumber variable to be a SomeNumber class, but a reference to a SomeNumber class. This leads me to the error way.

The Error Way

I won’t copy/paste the entire program. Only the NumberPrinter class changed.

class NumberPrinter
{
public:
	NumberPrinter(SomeNumber& somenumber)
	{
		mSomeNumber = somenumber;
	}

	void PrintNumber()
	{
		printf("In NumberPrinter: %i\n", mSomeNumber.GetNumber());
	}

private:
	SomeNumber& mSomeNumber;
};

This results in a compiler error. “a member of reference type must be initialized”. I Googled the error, then refined my search to be more about how to pass a class a class reference in the constructor and came across this StackOverflow post: http://stackoverflow.com/questions/11117347/passing-references-to-a-c-constructor-and-saving-them-to-reference-or-non-refe

The guy in the post wasn’t getting the same error (he was asking a different question entirely) but I noticed his code worked and he was doing pretty much the same thing I was doing. The only difference was how he was doing the initializing. This leads me to the right way.

The Right Way

class NumberPrinter
{
public:
	NumberPrinter(SomeNumber& somenumber)
		:mSomeNumber(somenumber)
	{

	}

	void PrintNumber()
	{
		printf("In NumberPrinter: %i\n", mSomeNumber.GetNumber());
	}

private:
	SomeNumber& mSomeNumber;
};

Instead of putting mSomeNumber = somenumber in the constructor function body, I used the other way if initializing class variables with :mSomeNumber(somenumber). Here’s the results:

therightway

 

Yes, this is what I wanted!

I sincerely thought that initializing class variables like that was a style choice, but it seems to be a rule for some cases.

I’m pretty new to C++, and stuff like this eats up entire evenings. Thankfully I live in a time when StackOverflow exists. I’d have been super stuck not realizing that the word “initialized” can have different contextual meanings! I think that the colon marks the start of an “initializer list”.

I read a few more posts on the subject. I can kind of see why this is. You don’t want to pass a reference that could potentially get freed outside of the class it’s passed to. I wonder if there is a graceful “smart pointer” way of handling it, or maybe I could just use raw pointers. More experimenting is needed. Here is another SO post that I found interesting: http://stackoverflow.com/questions/17992121/must-a-reference-type-be-initialized-in-constructor-initialization-list

 

 

Posted in Programming | Leave a comment

Rotation!

I was so surprised that this worked that I actually jumped out of my chair. When I hold down the “A” key the line rotates counter-clockwise around the blue circle (like a clock hand).

rotation

I spent ages working this out on graph paper. I’ve been working on the next iteration of Chocolate Quest. It’s going to be a top-down game controlled by the arrow keys. I’ve been trying to implement as much of the movement code on my own, instead of using SFML functions. Rotation is weird, and I didn’t feel right implementing it before I really understood it. I think I have it all worked out, but it’s going to take time to clean up my notes and make a coherent post out of it.

Next is making the little circle move in the direction the line is pointing. After I know I understand how to do movement, I’ll feel comfortable using the built-in SFML functions. It would feel like cheating otherwise.

Posted in Programming | Leave a comment