Press any key to continue... (in Linux, using C)

I didn't realize this was at all difficult. I just want a program which waits for user input before terminating. Just like any old Windows console program, where there's just enough output to warrant the user looking at it, but not enough to generate a whole graphical UI or a logging interface for it.

It's Windows, so you don't expect a user to open up a console to run the program... solution?
#include <stdlib.h>
...
    system("PAUSE");
...

Yes, it's really that "complicated."

But, here I am on a Linux system, wanting to replicate it (at this point, more for curiosity's sake than anything else). How do I do it?

I tried at first making STDIN unbuffered, ie.
#include <unistd.h>
#include <fcntl.h>
...
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
...

... but that didn't quite work, because then my subsequent read() just returns right away with EAGAIN. The problem is that the terminal is buffering a line until an EOL character is found, because it wants to be clever and let you getline and all that cal.

OK then, terminal, it's on. While the manpage for tcsetattr() and tcgetattr() should in no way be considered well laid-out and readable, one coffee later, I had it.
#include <termios.h>
...
    char b;
    struct termios tcattr;

    // the spacing of the ellipsis matters if you want to look like DOS.
    printf("Press any key to continue . . . \n");
    tcgetattr(0, &tcattr);

    // disable 'Canonical mode' which assumes you want line-buffering.
    tcattr.c_lflag &= ~ICANON;

    /* Set TIME = 0, and MIN = 1, thus telling the terminal that we want to
     * send along the stdin buffer when a minimum of MIN or chars requested
     * by read() is available, ie. in our case 1 (since read() just returns
     * immediately if you want 0 chars), and to disable the timeout which
     * governs how long to wait before sending the stdin buffer along.
     */
    tcattr.c_cc[VTIME] = 0;
    tcattr.c_cc[VMIN] = 1;

    // engage - NOW!
    tcsetattr(0, TCSANOW, &tcattr);

    read(0, &b, 1);

BAM! This should be portable to any system that conforms to POSIX.1-2001, ie. SuSv3, so your favourite OS has now had almost 10 years to support my code.
  • Current Music
    The New Pornographers - The Slow Descent Into Alcoholism

xfonts-jmk under Debian

Holy mother of God.

If you want to install xfonts-jmk, notable for its wonderful Neep (and my personal preference, "Neep Alt") fonts, under Debian, and actually have these fonts available to use in your Gnome/X applications, or say, from the Preferences -> Appearance -> Fonts menu, *don't just sit there scratching your ass wondering why everything you've done seems right, but fontconfig and friends just don't recognize and pick up the fucking font*.

dpkg-reconfigure fontconfig-config
(yes, that -config at the end is intentional).

*ENABLE BITMAPPED FONTS*. Really, I can't believe they disabled this by default. Holy gods, Debian, I swear to god I'm going to kill someone.

Then, a mere:
dpkg-reconfigure fontconfig
fc-cache -fv
xset fp rehash
and you're done.

I can't believe I need to do this shit in the 21st Century.

Debugging pfSense on a Soekris net5501

So your old router died (it was a custom build box using components from LogicSupply, not known for their robustness, which died in a thunderstorm). You replaced it with a Pentium II-400 that you cobbled together from spare parts, which is now on its third CPU fan and making hideous grinding noises - and where do you find replacement fans for a Slot 1 motherboard these days?

You bit the bullet. You had your housemates partially subsidize the purchase of a Soekris Engineering net5501 along with a flash card, correct power adapter, all the works. You found a Linux box, downloaded a version of pfSense that matched your compact flash size, correctly ran
gunzip -c <path_to_pfSense_file> | dd of=/dev/<path_to_compact_flash> bs=16k
and you're ready to get your hardon for no moving parts satisfied. (running Windows like the other 95% of the desktop market? Try this)

So you plug the thing in, and nothing happens. Huh.

How anti-climactic. I guess it's time for some debugging.

The biggest impediment to my debugging was that, despite years of owning old computers and even living with Mr. Langmaid, I failed to find a null-modem cable around the house - that being the only way to stare the router in the metaphorical teeth.

Hm. Well, a quick trip to Canada Computers - which, for the record, only closes at 19:30 on weekdays, what the crap is up with that? - and I come home with $6 of null-modem cable. Time to get to work.

I stare at the asses of a bunch of my computers and note that the only (functional) one with a COM port is the old Pentium III that I took with me to University. Oh man has that thing served me well. Hook one end of the cable into the COM port (/dev/ttyS0 in the old PIII), the other into the pfSense/Soekris box, and you're good to roll.

I used minicom to connect to the Soekris, because I suck and don't really know how to use other serial communication programs. Though I had to learn. Read more. About the only trick to manipulating the net5501's BIOS is that you have to set the connection to 19200 bps 8N1, hardware flow control. This guide helps a lot with minicom stuff. I'll refer to it again when discussing BIOS updating, which it turns out you should do if your net5501 has a BIOS revision that happens not to boot your CF card. For now, the first thing you should do, if you're running pfSense, is to change the baud rate to a paltry 9600 bps, since otherwise you won't really be able to see your BSD prompt.

In the BIOS prompt (after a Ctrl + P on your keyboard), try:
set ConSpeed=9600
reboot
(as you're rebooting, remember to modify minicom to run at 9600 bps)

OK. Now even if you boot BSD, you'll actually see stuff on the screen which doesn't resemble voodoo hieroglyphs.

Next up, if you're running an old firmware version and you can't boot off of your compact flash, or just for shits, you should update your BIOS version to the latest released by Soekris. I had to use the steps outlined at the bottom of the minicom section in the link above, since minicom 2.1 (on the old Pentium III, which is still running Ubuntu 6.06) was just plain broken and didn't want to do XMODEM transfers at all. sx (of lrzsz fame) worked well.

Once you've transferred the file,
flashupdate
reboot
and you're set. You may want to set time/date in the BIOS as well if you're pedantic.

Honestly, as anti-climactic as this may sound, this *just worked* and I was able to boot my pfSense immediately (and much more speedily than I was accustomed to). I configured a few basic things, and tomorrow I'll update with my further attempts to just move (scp?) my config file from my old pfSense-enabled PII to the Soekris box, so that I don't have to suffer the indignity of setting up all the port-forwards, static IPs, etc. manually.

*UPDATE 2010/11/16 00:50* It turns out pfSense just comes with a method of storing and loading the XML configuration (OK, that's disgusting, but whatever, I don't have to parse it) it uses for the system, and then restoring it onto another system, all via the web-based GUI. This feature *almost* worked flawlessly; there were some hitches because I had a number of packages installed in my previous version which were no longer available, and they've remained as dead, hanging links in my web menu, and aren't functional. It also failed to install any packages which were available and compatible, so I had to go and do it manually myself. That said, this took 5 minutes, so let's not exaggerate.

I've now got the net5501 purring (not literally, of course, since it's all solid-state and makes no noise) and the network is running smoothly. Nothing to see here, other than a Pentium II which I can rip apart and sell for scrap metal.

Shopping for dress shoes

"So, do you think I should even look at these ones? I mean, they're $50 cheaper."
"No."
"If I looked at them, I'd only be doing it so that I could scorn them and objectively tell myself that the ones for $50 more are actually worth it."
"Yep."
"So in fact, it would be a total waste of your time and mine, and I'd only be doing it to alleviate my own consumer guilt, and so that I can pretend that I didn't just buy these out of sheer vanity and preference for their appearance."
"Yep."

...

"I'll take these ones. No, not those, these ones for $50 more."

Sigh.

In unrelated news...

It appears that if I view my own entries without signing in, there are ads in my journal.

ADS.

In my journal.

Despite years of ad-free service, it appears that Russian management is the same in this day and age as during the 18th century: expansionist, imperialistic, and willing to stamp their dominance on people.

Well, thankfully, I'm no longer physically in Poland, but in Canada, and this gives the opportunity to evade my would-be Russian dominators.

Be advised that my search is on for an alternative blogging service, where I won't be fettered with bullshit ads.

I will attempt to transport my old entries there; in the event that I'm unsuccessful in any mass import, I'll leave this journal up as an archive and merely post new entries elsewhere.

After 9 years here, this is how they treat me. Fuckers.

The B.C. HST initiative: stop believing the rhetoric and think for yourselves

That does it. Today, I received something like the 500th invite to join some dumbass Facebook group from wannabe concerned citizens attacking British Columbia's initiative to enact the HST. Instead of actually joining such a group, nor joining a group that says "stop fucking bugging me with your misspelled and ignorant pleas," I decided to take time out of my day, yes, time that could be spent doing something actually productive, to read all about the HST in BC, and actually figure out whether it's worth bitching about or not. I admit; my initial bias was in favour of the HST, if only because the documents I saw from the government had actually passed by an editor who wasn't a semi-literate tree-hugging malcontent. That said, I attempted to examine all the evidence as best I could.

If you're not from British Columbia, or Canada at all, or you are from British Columbia and are an apathetic social mooch, here's the deal, in summary.

In general, if you live somewhere in Canada, you have three government structures above you: a municipal government (your city), a provincial government (Canada is split into ten provinces and three territories), and our Federal government (one ring to bind them all...). Each of these generally has a corresponding set of taxes that are levied for various services. This debate concerns (as it pertains to the province of British Columbia, or 'BC') the merging of the BC Provincial Sales Tax (PST) with Canada's Goods and Services Tax (GST) to create a new Harmonized Sales Tax (HST).

The idea is premised on a similar transition that the Canadian provinces of Nova Scotia, New Brunswick, and Newfoundland made in 1997, an operation evidently deemed successful by the BC government. Despite the apparent success, it's impossible to simply deduce whether BC's transition will be successful, since each province administers its own version of the PST differently, and, as such, the effects of a transition will be different.

I aimed to discover whether BC's transition plan is actually solid.

I'm not going to go into my research or reading about the Atlantic provinces and their transitions, because, as I state above, it's not terribly relevant. If there's a reference which is relevant, either factually or to support a point below, I'll include a link, but for the most part, let's look just at the facts as they pertain to BC's situation.

Very basically, the current GST rate on applicable goods in Canada is 5%. In BC, the PST rate on applicable goods is 7%. Therefore, the set of goods to which both GST and PST applies in BC is taxed at 12% (each tax is applied to the retail price, and not to the retail price plus one of the taxes). The main argument which makes adopting an HST in BC 'bad', it seems, is that the HST will make the union, or entire set of items, which were previously exempt from PST but not from GST, charge 12% instead of 5% tax.

In short, this is a tax hike.

That said, this is pretty much where the average Joe's cognitive abilities have ended. Time to go out into the streets and riot, you slack-jawed yokels! This level of comprehension negates the full breadth of the situation. No government would levy new taxes at a time when they could do immense harm (has anyone heard of our economic recession? I'm sure Gordon Campbell has.) just to piss people off. Well, how are they justifying this, then?

The government, in the usual manner governments tend to do, put out a very consistent but enthusiastic website on this issue. You can find it here. To prevent you from needing to wade through propaganda, I summarize the main motivations they state for the HST (colour commentary provided later):
- the HST will be a value-added tax (VAT), rather than the PST, which was a sales tax. More on this distinction later.
- the government ministry responsible for handling PST collection will be downsized and folded into the Canada Revenue Agency (CRA), reducing the 'heavy foot of government', as it were.
- the above bullet means that businesses will only need to remit and keep track of one set of taxes and remittance dates for collected taxes.
- as a result of the transition to a VAT and simplified administration, they expect a lot of savings for businesses, which will translate into job growth.
- in addition to job growth this way, they expect VAT to cut effective marginal tax rates on capital, which should stimulate monetary investment, particularly into industries with high capital purchase requirements.
- as a result of sales tax transitioning to VAT, they expect consumer item prices to go down over time (explained a bit later).
- ... if all that wasn't enough, to offset the increased taxes from formerly PST-exempt items, and riding the lowered administrative cost for the provincial government, there are planned tax cuts, in the form of lowered income tax and tax rebates.

OK, that's the summary. How do they envision this is going to work? First, let's explain the big difference between sales taxes and VAT. A sales tax is one that's applied at the point of sale on an item that's not being resold. What does that mean? It means that if I'm running a hardware store, a hammer, a tool which I purchase and resell to you (the consumer), I can buy without paying a sales tax. Paper on which I print my receipts, however, I have to pay taxes on, since I am the end user of the paper. When I sell you the hammer, I charge you sales tax on it, and remit that to the government. Effectively, this means that I, as a business have to cover the cost of my inputs (in my example, the receipt paper and the hammer) as well as the sales tax paid on my inputs (the sales tax on receipt paper).

In VAT, what I remit to the government is the difference between my input taxes and my output taxes. In the example above, I pay VAT on both, the hammer and the receipt paper. I also charge you, the consumer, VAT on the hammer when you purchase it from my store. However, what I remit to the government is the difference between what I charged you in tax, and what I paid. This means that, assuming that my taxes collected outweigh the taxes I paid, I only have to cover the untaxed cost of my input items as a business expense.

This has very interesting consequences down a long supply chain. Let's look at a very, very fictional example involving 3 companies:
- a company which sells paper (for receipts, work, etc.)
- a lollipop maker
- a pen manufacturer where the employees eat lollipops

First, a sales tax example. The paper manufacturer sells you paper. Let's assume that $1 of paper is required (for whatever administrative reasons) for the lollipop maker to create a lollipop. Assuming a sales tax rate of 10%, the paper manufacturer will sell it to the lollipop manufacturer for $1.10 ($1 + 10% of $1). Let's assume, for simplicity, that this was the only input cost on lollipops (impossible, I know, but just bear with me). The lollipop manufacturer wants to make a profit of 50% on his lollipops. He paid $1.10 for the raw material for his lollipop, so 50% is $0.55. He thus sells lollipops to the pen manufacturer for $1.82 (($1.10 + $0.55) * 1.1). The pen manufacturer marks up and sells pens to make $0.30 profit per pen. In order for this profit to be there, all of the input costs need to be covered. Suppose that the workers work for free, and one worker makes one pen, and for every pen, he eats one lollipop. Then, the cost of the lollipop is the input cost to make the pen. The pen maker paid $1.82 for the lollipop, so he charges you (the consumer) $2.33 (($1.82 + $0.30) * 1.1) for your pen. At the end of the day, the government gets $0.10 from the paper manufacturer, $0.17 from the lollipop manufacturer, and $0.21 from the pen maker in remitted taxes, for a grand total of $0.48, and you're out $2.33 for your pen. The paper maker made $1, the lollipop manufacturer $0.55, and the pen maker made $0.30.

Now let's look to see if VAT was in place, and the stores had the same motivations. Again, assume a VAT of 10%. The paper manufacturer is still selling his wares for $1 + 10%, or $1.10. The lollipop manufacturer wants to make a 50% profit. He knows that, since he's going to mark up his item, ie. 10% of his cost of sale will be greater than 10% of the cost of his inputs, he can disregard the tax he paid from his 50% profit calculation. Thus, he sells a lollipop for $1.65 (($1 + 50% of $1) * 1.1). The pen maker, wanting to make $0.30 on the sale of their pen to you, knows the same thing, so they charge $1.98 (($1.50 + $0.30) * 1.1), assuming a similar situation as above regarding total input cost of the pen. The end result? You're only out $1.98, saving yourself some money from the previous example. The government gets $0.10 from the paper manufacturer, $0.05 (= $0.15 charged - $0.10 paid) from the lollipop manufacturer, and $0.03 from the pen maker (= $0.18 charged - $0.15 paid), for a total of $0.18. The paper manufacturer made $1 in profit, the lollipop maker made $0.50 (= 50% of his costs, his goal), and the pen maker made $0.30, as they desired. Everybody won, except the government, which got less money than the previous example.

Most importantly, the example above illustrates that you the whiny consumer claiming they get taxed too much, actually saved money with VAT in place, because manufacturers were able to offer lower prices throughout the supply chain and still meet their profit goals. Let's say that each of our manufacturers wants to make an extra $0.02 in profit. That translates to roughly $0.07 in cost passed on to you, for a grand total of $2.05, which is still cheaper than the sales tax example. However, these companies each now have an extra $0.02 to invest into expanding their operations, and new hires.

That was the long example. Further ones should be shorter. Regarding the folding of the body administering PST into the CRA, well, once you get rid of some office assistants and redundancy in personnel between the CRA and the BC tax collectors, you save salary money. The important part for businesses here is that rather than keeping track of two filing deadlines, and hiring accountants to remit and calculate two sets of figures (GST and PST), only one set needs to be calculated, saving the expense and overhead of administrative calculation. Personally, as part of the management team at EQL Data, I can tell you that government remittances are no fun, and keeping track of them is a pain. Less time wasted on this overhead means more money which can be spent on hiring people and invested back into the company.

Regarding the argument for HST implying increased investment, in a very long-winded report the government commissioned on economic growth, the main argument is that the tax cut will help lower the marginal effective tax of capital, which will promote investment. What does this mean? Suppose that I'm a mining company, and I'm thinking of getting investment for a new drill. The investment only makes sense to me if my return on the drill (after I pay the government) is equal to my cost of funds for the drill. Let's suppose here that someone is willing to loan me money at 5% interest. The drill only makes sense if my return on it is 5% of the purchase price. Amongst other things, the report goes on to say, sales tax means that my return must be higher than the VAT case for me to be able to justify the expense. In my example, if my sales tax is 10% (and say this is the only government cost), then my drill actually has to make me a 5.56% return such that I can justify taking the loan (since 5.56 - (10% of 5.56) = 5). In the case with VAT, assuming that my sales are good, I may be able to completely write off the government cost, so that it makes sense for me to buy the drill even if it only makes me a paltry 5% return on its cost. Modern economics seem to generally agree that the marginal effective tax of capital is a significant factor for companies when looking to make investments.

Why would anyone think any of this is bad, then?

To that, we turn to the most organized contra-HST site I could find, and the main one pushed by counter-HST "proponents," if I can call you drooling apes that. For the purposes of objectivity, I will ignore the fact that a video starring Mr. Bill Vander Zalm adorns the front page of this site, and try to skip to the main arguments the site pushes against HST. Please feel free to email me more (lkosewsk małpa gmail.com). The arguments are:
- a number of goods which were formerly PST-exempt will now incorporate full HST, including (prominently) funeral home services and restaurant meals.
- marginal effective tax on capital is not an effective measure of corporate desire to invest, thus HST will not make a difference in actual business capital investment.
- the HST structure shifts tax burden from businesses (which, as in our example above, don't pay as much tax) to consumers (due to the non-PST exempt items costing extra).
- similar effects to the HST on business could be had by just eliminating the PST on capital investments.
- no public consultation before deciding to implement HST.
- even if the HST helps some businesses, does the help offset the damage done to the restaurant industry as a result of higher food prices?
- HST will cost an 'average' BC household an extra $2100/year.
- the HST removes BC's constitutional right to set and collect provincial sales taxes.
- the Liberal government (in power in BC) promised not to implement the HST.
- BC's economy is struggling, and the extra tax will hurt the economy further.

Hm. That seems like a pretty significant list of complaints. Let's attempt to discuss them all to see their validity.

Of course some services are going up 7% in tax. That was openly admitted. Unless these businesses are already earning less in revenue than they pay in input costs, though, the math we did above demonstrates that, in fact, their prices can be lowered, and their profit margin remain the same. It's difficult to calculate whether or not their prices can be lowered to offset a 7% tax increase right away, because that depends heavily on their supply chain, however, so we can't draw many conclusions there.

One thing we can attempt to work out is whether, assuming no change in consumer habits (which is unreasonable, because you can, in fact, assume consumers won't eat at restaurants so much if the prices are higher - mind you, in Canada, the taxes are not included in the prices listed on a menu, so the effect of the migration away from restaurants is also rather hard to flat-out predict due to human psychology), if the 7% tax increase in certain goods will actually hurt the BC consumer.

Here are some of the offsetting rebate initiatives planned by the government to counter the increased tax:
- No effective tax increase for hospitals or schools (link).
- Gasoline, books, diapers, and residential energy consumption are amongst the new items designated as exempt from the 7% portion of HST (link).
- Something I personally find very interesting: under PST, the private resale of used goods was subject to PST (mentioned here). Despite the fact that this was often overlooked by the government, reselling items (ie. homes) and not paying the government PST was actually tax evasion. For the purposes of more realistic laws, and fairness, HST is not being applied to the sale of used items (link, with regards to home buying. The link also discusses rebates on purchases of new homes - which are subject to HST)
- Despite the fact that this is probably backpedaling on their part to retroactively justify some tax cuts, they claim that tax credits for low income families (link) following general income tax reductions and increases in the basic personal amount for BC residents (link) are related to HST.

Alright, so some of this sounds like retroactive justification and flailing. But certainly, measures like the recently-introduced no HST on residential electricity sound good to me. I guess what I want to say with the above is that the figure of "$2100 increased cost for the average home" is probably just as made-up as the claim that BC's capital stock will somehow jump by $14.4 billion by 2020 because of this initiative. It's hard to say, without accurate income figures and other expenses, whether the raise in tax, balanced by cuts and rebates, will actually impact a person's real salary, particularly if the prices for products go down (and, in a properly fostered competitive environment, it's not impossible for them to do so).

There is more to explore. On the topic of public consultation regarding taxes: I'm glad the government didn't, frankly. Though I am very anti-totalitarian (unless I'm the tyrant in power), the amount of idiot opinions about the economy I hear every day from you flaks leads me to believe that it's very good none of you were consulted about tax structures. Nor do I care about the Liberals' promises not to invoke the HST... if I promised to never drive a car, but then broke my promise one day because you needed a lift to the hospital, you probably wouldn't be bitching much. There are valid reasons to break promises. As John Maynard Keynes put it: "when the facts change I change my mind. What do you do, sir?"

Where was I... marginal effective tax on capital. I personally don't buy the argument that it doesn't help with capital investments, if only because the one author who makes the claim also makes the claim that PST reduction could have been explored. That's terribly fishy to me, since PST reduction on capital also equals a reduction of marginal effective tax on capital. Are you for or against, friend? I don't know, but your argument here is on very slippery ground. This concept might actually be the very undoing of the whole "restaurants will go out of business if they have to charge 7% extra for food" argument. Consider; all restaurant expenses, from noodles to new chopsticks, fridges, tables, etc., can be written off of their HST in a way that PST never could be. While I don't own a restaurant, and am hard pressed to give you accurate figures into the running of restaurants, my hunch is that this 7% raise could be forgotten if food prices on menus start dropping (again, because tax prices are not included in menus on BC). The psychological effects alone could *increase* restaurant business.

This covers almost all the points I've seen against HST, with the exception of sales tax as a BC constitutional right (which you either care about or you don't, and I happen to sit in the latter camp). It's now 3:48 AM, which means I've spent far too much time sitting around writing this, and it's so long I doubt you'll get to the bottom of it. It has a bottom line though, which is really my plea.

Stop joining stupid anti-tax rhetoric without understanding the full ramifications of what's happening first. Governments don't take the decision to change tax structures lightly. Perhaps there is benefit in this for you after all.

Waking up on March 1, 2010

I don't actually recall the amount of time I slept the night prior, but it couldn't have been more than 7 hours, and was probably objectively less. John called me at 3:06 AM to ask if I had seen Victoria's cell phone anywhere, and I snoozed through the call and passed out contentedly.

Wait a second. I don't have any friends who spell their name "John." And the only Victoria I know is Julian's cousin. What just happened, and why were these people at my house? Why am I referring to them on a first-name basis?

This spontaneous meetup, my friends, was the result of Canada's gold-medal-winning performance on the ice at the culmination of the Vancouver 2010 Olympic Games. The bars poured out, including the one I was at with my Waterloo crowd (the name of this bar was Lou Dawgs, and if you're a fan of Louisiana-style cuisine and reasonably inexpensive beer, it's not a half-bad place). Where were we headed? Who knew!

What mattered was that we had done it, our national identity boosted by winning at the sport that forms the basis for over 50% of Canadian stereotypes. By winning more gold medals at a Winter Olympics than any other nation in history. It was us, we pulled as a team, we willed Crosby to score, and he did not disappoint us. Now the wait was over, we had every right to celebrate, and celebrate we did. We danced, we yelled, we sang. As traffic in downtown Toronto ground to a complete halt we kissed, shook hands with, and celebrated with the drivers, we conglomerated in the (commercial) heart of our fair city, Dundas Square, wherein we, as Canadians, celebrated our identity and cheered like it was nobody's business.

We waved flags. We waved clothes. The party lasted for a long time. Consider that, in Eastern Time, the game began at 3:15 PM, and that we had hit bars at 2:00 PM just to get a seat... give the game 3 hours, and you've got about 12 hours of drinking intermingled with 9 hours of uproarious cheer and love.

This morning when I woke up, I could hardly believe it had even happened. A Service Canada representative was at my door at 10:00 AM to verify my identity and get EQL Data signed up for filing Record of Employment forms online rather than using paper filings. He was crisp, professional, and when I asked him if he had celebrated last night, he shrugged his shoulders and mentioned that no, he hadn't really been out very late. He looked a little put-off by the state of my living room, what with several bottles of vodka scattered precariously over the foosball table, the whole house smelling of hops and lees, and jackets and blankets draped over every piece of furniture. Courteously, he mentioned that his other colleagues might not consider this a very professional meeting.

Throughout the day, this bizarre obliviousness to the happenings of February 28 only deepened. Kat said it best in a text message: "Vancouver was a gong show! Love it. Back to reality today, fuck." As I took a subway later that evening to visit Liz, reality really depressed me. Older women who smiled happily and whose cheeks I would jubilantly kiss last night leered at me from beyond raised copies of Metro, disapproving of my tattered jeans and unkempt haircut. Professionals in suits sat quietly playing with their BlackBerry phones, when only yesterday they would high-five and whoop. Girls who flung their arms around you and danced to the tune of being Canadian stood bundled up in their coats, nodding along silently to their headphones. The train was quiet and demure. We were no longer Canadian, all sharing in the full joys of this word, we were girls and boys, we were white, black, Asian and brown, we were rich, poor, we were professionals or plebeians.

The jubilation, the love, the exuberant joy was gone, we were back at work contributing to our GDP or lost in our own problems.

After a quiet dinner spent enjoying shawarma sandwiches and x-rays of Liz's new hand-bone fractures (acquired in an inebriated game of soccer during the post-Olympic gold celebration), I went home, demure and introverted, reluctant to leave the emotion of yesterday behind, but not wanting to immerse myself in what was only a dream.

As I walked up the stairs from St. Patrick station towards University and Dundas, I was quietly whistling O Canada to myself. As I passed a boy and a girl going in the opposite direction, the boy suddenly excuses himself, turns towards me, and begins to match my tune, our whistling finding a common octave. I turned around and, for what was probably the first time today, smiled broadly. Ironically, this ended our duet, but just for a moment, we had both connected, and our eyes relived the magic.

Maybe it wasn't all a dream.

I'm even better-looking without the Canada flag painted on my face


Olympic gold medal hockey game, Vancouver 2010 Winter Olympics. Canada 3, USA 2 in OT. Thanks for the memories.

(The photograph is courtesy of Steve Gircys, whom I bumped into late into the evening. You can also see that even our hockey game can't get in the way of my mildly leftist agenda.)

Allowing users to delete Windows files when they're open (in C)

Another day, another update. This is almost too frequent for me. Where do I find all this time? After a few presentations and such, things have quieted down a bit over at EQL Data, so I'm back to my "usual" (ie. maniacal) rate of development.

Every once in a while though, a person must reflect and write an entry about something nifty and new that they come across in the course of their work. Today, that new knowledge manifests itself in being able to delete open files in Windows.

First, a quick recap. Why would you want to do this? Let's look at a piece of code to find out:
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC);
unlink(filename);
// do stuff with fd, because the file still exists
Why on earth is this useful? Well, let's say 'filename' is a temporary file. It's going to get removed at some point in our computation, and, unless we have debugging code, chances are we have no need of this file even if our computation produces some kind of exception condition.

The method above is a very simple way of doing this without keeping 'filename' around for removal at the conclusion of the temporary file's use, or within an atexit() or signal handler. Moreover, it ensures that we won't have any issues with name clashes if we use functions like tempnam() or tmpnam() to create our temporary filenames for us.

Of course, it works because every modern operating system only actually removes a file when all open file handles to it are closed... until then, it simply removes it from its parent directory listing, thus preventing any other attempts to open the file.

Conclusion: you can see a use for this procedure. And, until recently, I thought it was impossible in Windows. Windows disallows removal of files if there are any open filehandles to said file, which sounds discouraging.

... that is, until I decided to port bsdsort to Windows.

Bsdsort happens to use the above algorithm in the creation of their temporary files (for intermediate radix sort stages and such), and, rather than decipher the logic of the program and figure out where to insert a manager for removing temporary files (not to mention handling their removal on all the testing errors I stumbled upon during porting), I took it upon myself to discover how to do this.

The key, it appears, is to use the Win32 API, since the POSIX layer for Windows happens to be missing these (new?) features. Let's see what the code ends up looking like:
int fd;
HANDLE h = CreateFile(	filename,
			GENERIC_READ | GENERIC_WRITE,
			FILE_SHARE_DELETE,
			NULL,
			OPEN_ALWAYS,
			FILE_ATTRIBUTE_NORMAL,
			NULL);
if (h == INVALID_HANDLE_VALUE)
    // handle error
if ((fd = _open_osfhandle((long)h, 0)) == -1)
    // handle another possible error
unlink(filename);
// Go ahead and use fd, and check your filesystem:  no 'filename'!
... ta da! What have we here? We've opened 'filename', and removed it... but our filehandle is still open! What have we done?

The key, of course, is the call to CreateFile. You'll note, upon examining the MSDN documentation for CreateFile, that the third parameter is dwShareMode, ie. all the permissions you wish to grant other processes (and your own process) on this filehandle while you have it open. FILE_SHARE_DELETE is the crucial part of this equation... it indicates the obvious: this file can be deleted while you have it open. I won't go into the other parameters to this call: I suggest reading the MSDN documentation to match this function to your needs.

In order to obtain a POSIX filehandle for the corresponding HANDLE returned by CreateFile, we call the less-known _open_osfhandle, which gives us exactly what we want.

A bit of error handling later, and we've accomplished our goal: we have an open POSIX file, and 'filename' is gone.

Another win for team EQL. The next challenge was to port bsdsort to C++ (mostly to allow interoperation with the excellent WvStreams library)... but that's a story for another day!
  • Current Music
    Anaheim Ducks @ Vancouver Canucks, 2-2 @ 9:30 in the 3rd period.
  • Tags

EQL presentations

Hey team. Team here is of course figurative, unless you consider "the set of people who might read this posting" to be a team.

It's getting quite later than I'd hoped, and I was still going to send out more emails. There are exciting things in the works, and, as most of this past year has gone, they deal with EQL Data, aka the company which continues to increase in awesome every day.

The newest... news... I suppose, on the EQL front, is that we're been invited to another conference to do a presentation. Unlike the last one, where we ran a booth displaying both our wares, and our business model, as inspiration to young entrepreneurs at the Impact National Conference, I'm going to announce this one, so that you can come out and see what EQL is all about. Thank you to those who bumped into me at Impact and suggested being more vocal about this, you found us despite the complete lack of any announcement!

Back to current events. I've been invited to present our feature product, OnWeb at the Connecticut Access User Group (CTAUG), to a room-full of curious Microsoft Access professionals on Wednesday, December 9, at the Microsoft corporate centre in Farmington, CT.

The focus? How to use OnWeb to deploy fully internet-friendly Access applications on the Web with no dedicated effort, redevelopment, and no need for migration. Yes. We do suggest you keep using Access!

My passport has been verified, and my presentation is progressing nicely. Since CTAUG generously gave me up to an hour of presentation and question time, I figure this is the first time to really discuss some of the nitty gritty of OnWeb. How does it put Access on a webserver? Why does it export Access databases to our proprietary format before synchronizing? What are deferred updates, and why are they safe? What interfaces are supported? How did we manage to get printing to work? How has the architecture of Access stomped and tried to block us at every turn? Is it scriptable? What is the roadmap going forward?

If you can be in Connecticut on Wednesday, you too could be asking these questions and more.

I'll also be unveiling a look at one model of the planned EQL in-house appliance... whoops! Did I just preannounce that? I think so. I'll be writing about that in the days to come.
  • Current Music
    System of a Down - Prison Song
  • Tags