davidpritchard.org

A Year of Apple Watch

· Computers

Last January, I bought an Apple Watch series 3. A week later, I bought a second watch.

In between, I’d learned a lesson about trying to buy used goods on Kijiji. I learned from Apple staff that the first one was stolen from an Apple Store… and Apple decides to put the watches that failed waterproofing tests in the store. I wore the watch for a swim within a few hours of buying it… and poof, it was gone.

But I’m quite pleased with the watch. I got it for three reasons: to track/improve my exercise, to reliably receive phone/text notifications, and to keep up with current technology / user interface trends. All of these have proven useful.

Let me talk about the last two first: I appreciate that the watch is less addictive than a phone, and helps you reduce phone use. I’ll go a step further: the watch’s best feature is that the screen is too small. It’s so small that I don’t want to use it for an extended period of time… so I don’t. No facebook, no twitter, no instagram, no addictions. I will happily pay extra to have a device that I don’t want to use much… which I guess is “win-win” for Apple, isn’t it?

I appreciate that it’s better adapted to human social interactions: you can turn your phone ringer off and just rely on vibrations, you can keep your phone in a bag and still get all notifications, and it’s much easier to quickly glance at a text during a meeting without looking like a jerk.

On exercise: I’m primarily a commuter cyclist and swimmer, and to a lesser extent a bit of an omnivore. Tracking all of the types of sports I do was very appealing. I was also attracted by a company that uses the addictive “gamification” approach that usually keeps us glued to our smartphones for good - to actually keep me healthier and happier.

And it’s worked: my calorie goal has risen from 400 active calories per day to 650 over the course of the year, despite a change in work situation removing my reliable cycle commute. The data’s also fascinating; while what’s captured by “Workouts” is only part of my total exercise, it’s neat to see:

Random trivia in these charts:

  • My worst month (March 2017) was the one where I spent two weeks on an urban Mexico vacation. With high heat, no bike, and two kids to manage, I got very, very little exercise. This is one reason why I like camping vacations!
  • The “seasonal” category is mostly skating and cross-country skiing, plus a little snowboarding and canoeing. Now that I live in Ottawa, I even skate to work regularly. I’m a little annoyed that Apple doesn’t track distance or provide maps for skating and skiing, though. And the icon for “skating” is a skateboard, so I’ve started classifying it as “hockey”.
  • In October, a new WatchOS version started autodetecting “walking” workouts for me.
  • The comparison of February 2018 (Toronto) and 2019 (Ottawa) is pretty striking. Winter cycling just wasn’t feasible. (And yes, I did cycle 155km in February in Toronto.) Even walking quickly enough to be classified as “exercise” was tricky on the icy sidewalks.

Adventures in Vintage Emme

· modelling & sci/tech

Imagine there are no variable names. Imagine working - in 2016 - with registers. Imagine one minute file load times. Imagine that all commands are just numbers. Imagine there’s no usable string processing.

Welcome to Emme 3. During the years that I worked in travel demand forecasting, this was the main tool available to me.

Emme was undoubtedly a trailblazing innovator when it first came out in 1982 and remained a power user’s dream through to the early 90s. But it clearly missed the Windows boat; the software seems to have stagnated until beginning a revival in the late 00s.

Emme 2’s graphical capabilities

Continue reading

Working with XAML Designer 2 (UwpSurface)

· User Interface, windows · 1 comment

In September 2017, Microsoft released a rewritten XAML Designer program within Visual Studio. It’s only enabled for a tiny fraction of apps and got a very quiet launch, so almost no one knows about it. The new version runs as UwpSurface.exe instead of XDesProc.exe and is only enabled for UWP apps targetting Fall Creators Update SDK or newer.
For my app, the new Designer simply broke everything initially. Why? Presumably for technical reasons, it only works with {Binding} and not {x:Bind} - but this was not made at all clear in the launch announcements. UWP developers have been encouraged to use {x:Bind}: it’s compiled, type-safe and faster, and x:Bind functions are the only way to do multibinding. For my 64-bit app, I never got design data or design instances working under XAML Designer (xdesproc), so I relied entirely upon {x:Bind}’s FallbackValue parameter to preview different modes of my UI - but {Binding} has no equivalent mechanism.
After a lot of tinkering, I’ve finally learned a few important things about the new XAML Designer, and got a usable workflow.

Top Takeaways

  • UwpSurface is much faster and stabler than XDesProc. The dialog above (“Click here to reload the designer”) is largely history.

  • It works for both 32-bit and 64-bit apps (x86 or x64), which is a big step forward

  • Only {Binding} is evaluated; {x:Bind} is completely ignored.

  • DesignInstances (a live ViewModel) can be attached via DataContext or d:DataContext, although the DesignInstance parameter doesn’t seem to work

  • ViewModel code executes, but I don’t see any indication that View code executes, despite discussion to the contrary in Microsoft’s launch blog post

  • For C++/CX apps: due to a bug, only single-class ViewModels (without any C++/CX base classes) work as of Visual Studio 15.8.x. They’re fine in C#.
    (Update Jan. 2019: Visual Studio 15.9 fixed this bug, but ViewModels that implement property change notifications still do not work.)

  • You can attach a debugger and see debug output from your ViewModel, or any exceptions. I haven’t been able to set breakpoints.

  • Update Jan. 2019: Visual Studio 15.9 added support for something I requested in mid-2018: the FallbackValue parameter was added to {Binding}, which makes that an equally viable way to work with XAML Designer. FallbackValue doesn’t work for {x:Bind} in the new Designer.

My strategy for a C++/CX app

  • Stick with {x:Bind} and its functions in most of my code

  • For the few properties that are central to a clean layout (usually about 2-5), use {Binding} and type converters

  • For those properties, build a duplicate “DesignTimeMock” ViewModel class - with no C++/CX base classes - and return the design-time property values there. Most properties can be safely omitted.

  • In the XAML code, define two different DataContexts like this:

    <UserControl.DataContext>    <local:MyViewModel /></UserControl.DataContext><d:UserControl.DataContext>    <local:MyViewModel_DesignTimeMock/></d:UserControl.DataContext>
    

    This attaches one ViewModel for runtime, and the mock for design time.

  • Update Jan. 2019: Visual Studio 15.9 now allows a different approach: instead of a DesignTimeMock, you can just have a single DataContext using the “real” view model, but instead change {x:Bind} to {Binding} in the few places where it matters, and then add a FallbackValue parameter to choose the desired value in XAML Designer. The biggest advantage of FallbackValue: you can edit it in place and see it immediately update, without recompiling and relinking the DesignTimeMock view model.

It’s not ideal. But… it’s better than nothing.

Closing Thoughts

Despite the difficulties, I do look forward to further improvements in the XAML Designer. The old version was dated and crash-prone, and a clean slate rewrite was the only reasonable path forward. It’s just going to take some time to reach feature parity with the old version, which will mean some teething pain for “guinea pig” developers like myself.

Asynchronous Best Practices in C++/CX (Part 2)

· C++, windows · 1 comment

This is part two in a series of articles on asynchronous coding in C++/CX. See the introduction here.

  1. Prefer a task chain to nested tasks

  2. Be aware of thread scheduling rules

  3. Be aware of object and parameter lifetimes

  4. Consider the effect of OS suspend/resume

  5. Style: never put a try/catch block around a task chain.

  6. References

2. Be Aware of Thread Scheduling Rules

  • When working with non-threadsafe code, you will usually prefer to continue on the same thread and not have to deal with multiple threads contending for the same data.

  • Helpfully, Universal Windows Platform (UWP) apps have a user interface thread inside a Single Threaded Apartment. On that thread, continuations (either a task .then() statement or code after a co_await statement) will almost always be scheduled to continue on the same thread.

    • Exception #1: if the initial task in a chain is not an IAsyncAction or IAsyncOperation (or their WithProgress variants), then the continuation may “break out” of the apartment to a different thread.

    • Exception #2: in my tests, I found that mixing coroutines and task-based continuations could still break out of the apartment. Calling a coroutine and then following it with a .then() task-based continuation seemed to cause it, although I haven’t dug very deep into the exact conditions.

  • If a continuation is not on the UI thread, then the guarantees go out the window. For threadpool threads, a continuation can be scheduled on any thread.

    • So, partway through a coroutine, you may find yourself on an entirely different thread.

    • I imagine this is to prevent “starvation” of asynchronous chains when running on a compute-intensive thread, for example. But it can be quite a gotcha.

    • The concurrency::create_task() method can take a task_continuation_context::use_current() parameter to (try) to force execution to stay on the same thread, but there’s no equivalent for coroutines. It’s not clear to me that this always works, however; I need to test further and explore.

  • When in doubt: use std::this_thread::get_id() to check the thread id over the course of an asynchronous chain of operation.

  • When on a threadpool thread, my preference is to write a standalone coroutine in a functional style rather than as a traditional method within a class. I avoid using the this pointer, pass inputs to the coroutine by value and return a result from the asynchronous chain. If I want to modify an object, I’ll write an accompanying method that calls the coroutine, then schedules a final task on the original thread to mutate the object. Here’s an example:

    class MyClass {private:  static concurrency::task<std::wstring> Coroutine(wstring filename) {    // ... do some stuff, open file with co_await, read data, etc...    co_return result;  }public:  void MemberFnAsync() {    concurrency::create_task(Coroutine(m_filename),      task_continuation_context::use_current())    .then([this](wstring result) {      this->SetTextFromFile(result);    });  }};
    

3. Be Aware of Object and Parameter Lifetimes

  • When passing data into asynchronous code, you want to pass by value. That applies to both lambda captures (for continuation tasks) and to coroutine parameters.

  • Why? If you pass do a traditional C++ calling convention like this:

    concurrency::task<void> MyCoroutineAsync (const wstring &str) {// do some stuff.co_await OtherFn();AnotherFn(str);}
    

    … the str parameter will typically be valid until the first co_await statement, but at that point execution will return to the caller until OtherFn() completes. The str parameter may well then be destroyed—especially if it was an rvalue or a stack variable. By the time the coroutine resumes and AnotherFn() is called, str will be a dangling pointer.

  • The underlying issue is that the coroutine task chain outlives its caller and therefore can’t count on references to data from its caller.

  • This applies to reference and pointer data. Pass-by-value is usually preferred, but of course smart pointer types are also valid.

    • Just be sure to pass smart pointers in a manner that creates a separate reference count: std::shared_ptr, not const std::shared_ptr&

Asynchronous Best Practices in C++/CX (Part 1)

· C++, windows · 1 comment

For me, the steepest learning curves with the Universal Windows Platform (UWP) was the use of asynchronous APIs and the various libraries for dealing with them. Any operation that may take more than 50ms is now asynchronous, and in many cases you can’t even call the synchronous equivalent from Win32 or C. This includes networking operations, file I/O, picker dialogs, hardware device enumeration and more. While these APIs are pretty natural when writing C# code, in C++/CX it tends to be a pretty ugly affair. After two years of use, I now have a few “best practices” to share.
C++/CX offers two different approaches for dealing with asynchronous operations:

  1. task continuations using the Parallel Patterns Library (PPL)

  2. coroutines (as of early 2016)

Personally, I vastly prefer coroutines; having co_await gives C++/CX a distinctly C# flavour, and the entire API starts to feel “natural.” However, at my current job we have not yet standardized on coroutines, and have a mix of both approaches instead. And to be fair - despite Microsoft’s assurances that they are “production ready”, I’ve personally hit a few coroutine bugs and they do occasionally completely break with compiler updates.
I’m going to write up my advice in a series of posts, as the examples can be pretty lengthy.

  1. Prefer a task chain to nested tasks

  2. Be aware of thread scheduling rules

  3. Stay aware of object and parameter lifetimes

  4. Consider the effect of OS suspend/resume

  5. Style: never put a try/catch block around a task chain.

  6. References

1. Prefer a Task Chain to Nested Tasks

When writing a series of API calls that need local variables, conditional logic, or loops, it’s tempting to write it as a nest of tasks. But a nest will:

  • hurts legibility: an extra indent level for every sequential API call, and very wordy

  • painful/missing exception handling: every level of the nest needs its own exception handler. Exceptions will not propagate automatically from an inner task to the outer exception handler, but will instead raise an unobserved exception error.

  • makes it hard to return a waitable/gettable task that can track when the entire chain completes.

Consider this example nested code:

concurrency::create_task(folder->GetFileAsync())
.then([](StorageFile ^file) {
  if(file != nullptr) {
    concurrency::create_task(file->ReadAsync())
    .then([](IRandomAccessStream ^stream) {
      /* do something with stream */
    })
    .then([](concurrency::task<void> t) {
      try { t.get(); }
      catch (COMException ^) { /* do something */}
      catch (...) { /* do something */ }
    });
  }
})
.then([](concurrency::task<void> t) {
  try { t.get(); }
  catch (COMException ^) { /* do something */}
  catch (...) { /* do something */ }
});

Here’s the equivalent implemented as a task chain:

concurrency::create_task(folder->GetFileAsync())
.then([](StorageFile ^file) {
   if(file == nullptr)
     concurrency::cancel_current_task();
   return file->ReadAsync();
}).then([](IRandomAccessStream ^stream) {
   /* do something with stream */
}).then([](concurrency::task<void> t) {
   try { t.get(); }
   catch (std::task_cancelled ) { }
   catch (COMException ^) { /* do something */}
   catch (...) { /* do something */ }
});

Let’s look at a few other situations and the best way to make a chain:

  • Need access to local variable in earlier stage of chain: the best solution is to define a custom struct with the local variables that are needed throughout the chain, heap-allocate it with a std::sharedptr, and pass it in via lambda-capture:

    struct StackFrame { String ^filename; }auto stack = std::make_shared<StackFrame>();concurrency::create_task(folder->GetFileAsync()).then([stack](StorageFile ^file) {   stack->filename = file->Name;   return file->ReadAsync();}).then([stack](IRandomAccessStream ^stream) {   /* do something with stream and stack->filename */})
    
  • Need a loop with asynchronous calls on each item: collect the tasks for each item in the loop into a std::vector and return when_all on that vector.

    concurrency::create_task(folder->GetFilesAsync()).then([stack](IVector<StorageFile> ^files) {   std::vector<concurrency::task<void> > tasks;   for (auto file : files) {     tasks.push_back(concurrency::create_task(file->DeleteAsync()));   return concurrency::when_all(tasks.begin(), tasks.end());});
    

Of course—just in case you’re curious—as a coroutine this is all trivial and highly readable.

try {
  StorageFile ^file = co_await folder->GetFileAsync();
  if (file != nullptr) {
    IRandomAccessStream ^stream = co_await file->ReadAsync();
    /* do something with stream and file->Name */
  }
}
catch (COMException ^) { /* do something */}
catch (...) { /* do something */ }

Continues in Part 2

This One Weird Grid Trick in XAML

· User Interface, windows

I recently found a neat XAML user interface trick that I hadn’t seen in my usual resources. Suppose you have:

  • a grid-based responsive user interface that you want to grow/shrink to fit the window

  • suppose it has a fixed width, and each row has a “core” minimum height it needs.

  • then there’s some extra vertical space that you want to sprinkle around

  • you have some priorities - first give row #1 extra space, then row #2 any extra.

XAML makes it easy to do proportional space allocation - e.g., give row #1 two-thirds and row #2 one-third by giving them “2*” and “*” height respectively. But it doesn’t do priorities.
The trick: combine a massive star size with a MaxHeight. That looks like this:

<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="1000*" MaxHeight="200" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>
</Grid>

Essentially, row #1 gets “first claim” on any extra space, up to a limit of 200 pixels. Any extra space beyond 200 pixels falls over to row #2.

Return of the Mix

· Music

It’s been a while. My daytimes were 80% meetings until last September, when I returned to the coding world. At that point, my job is compatible with listening to (lyrically simple) music… but I’m basically 10 years out-of-date with the scene.

So I’m slowly trying out “music discovery” in the modern age. If you’ve got any good tricks, pass ’em on! Meanwhile, here’s an extended mix — 40 mins. longer than usual — of some of the best stuff I’ve dug up.

As you can see, I’ve made more headway in electronic genres than the others. Lyricless music is definitely the best for my line of work. The slowest tune of the bunch (Loscil) is not a “listen at work” artist, but a different place: we have a sauna in our basement now, and I find slow ambient music is amazing there. Albums I’d had for a while — like Loscil’s Endless Falls disc — suddenly clicked, with the slow drone fitting perfectly with calm breathing rhythms. That said, I can’t yet justify dropping such an introspective track into a mix… so the Loscil track here has a little more tension in it.

Download here, for a few weeks only, or stream from Mixcloud.

David Pritchard - Mix 2017.11 by Drpritch on Mixcloud

In this era of easy streaming music… I feel pretty bad for the artists. If you like these tracks, please buy them individually, or buy a few of the albums. Think of it like a tip jar. The Mixcloud widget will let you buy many tracks from Juno with very little effort, and iTunes or Bandcamp searches can find the rest for you.

  1. eight and a half. go ego. rock, from eight and a half, 2012.
  2. the weeknd. rolling stone. r&b, from thursday, 2011.
  3. robin thicke. everything i can’t have. r&b, from the evolution of robin thicke, 2006.
  4. hypnolove. midnight cruising [mickey moonlight dub]. acid jazz, from future sounds of jazz 12 compilation, 2010.
  5. the cinematic orchestra. everyday. acid jazz, from every day, 2002.
  6. baden powell & vinicius de moraes. canto de ossanha [m.rux edit]. acid jazz, from m.rux - edits & cuts, 2014.
  7. radiohead. identikit. rock, from a moon shaped pool, 2016.
  8. sufjan stevens. drawn to the blood. folk, from carrie & lowell, 2015.
  9. dope lemon. neon lights. rock, from houndstooth ep, 2017.
  10. caribou. your love will set you free. techno, from our love, 2014.
  11. headshotboyz. calypso. dubstep, from project mooncircle 10th anniversary compilation, 2012.
  12. com truise feat. joel ford. declination. synthwave, from wave 1, 2014.
  13. jamie xx. girl. electronic, from in colour, 2015.
  14. daft punk. contact. house, from random access memories, 2013.
  15. emperors new clothes. darklight [underdog version]. downtempo, from kid loco: dj-kicks, 1999.
  16. loscil. drained lake. ambient, from monument builders, 2016.
  17. lapalux. rotted arp. experimental, from ruinism, 2017.
  18. gorillaz. el mañana. downtempo, from demon days, 2005.
  19. yppah. never mess with sunday. downtempo, from ninja tunes xx compilation, 2010.
  20. plaid. scoobs. techno, from peel session ep, 1999.
  21. isolée. floripa. techno, from floripa ep, 2015.
  22. diplo. into the sun. downtempo, from florida, 2000.
  23. afrolicious. a dub for mali. downtempo, from st. germaine-des-prés café 15 compilation, 2013.
  24. the xx. on hold. rock, from i see you, 2017.

A few tips outwards: thanks to Hendrik for reminding that Radiohead is amazing, to Tyson for helping me notice that Sufjan Steven’s new one was back to his old form, to Dave B for an immersion in synthwave, to the Aussie staff at the Only Cafe for playing that Dope Lemon track, to Paul for getting me on to the XX, to Matt T’s friends for pointing me at M.Rux, to Eddy for putting Loscil more firmly on my radar, to Soundcloud for actually making a good “you might like” recommendation, and to David T for giving me a streaming membership.

My First XAML Tips for the Universal Windows Platform

· User Interface, windows

I’m a latecomer to Microsoft’s user interface technologies. I never used Windows Framework (WPF) on top of .net and I never used Silverlight on the web. The last year was my first taste of these tools through the XAML framework that is part of the “Universal Windows Platform” (UWP) - that is, the Windows 10 user interface layer (and Win8).
XAML has steadily evolved since the WPF days, and it took a little while to really understand the different major eras of the technology, especially since the UWP flavour of XAML strips out some of the older syntaxes in the name of efficiency on mobile platforms, better error checking at compile-time and code readability and ease-of-use. The technology’s old enough that much of the Google search hits and StackOverflow results are not applicable on the modern UWP platform.

My Tips

So what were a few of my first lessons when using XAML on UWP?

Continue reading

Passive Portfolio 2016

· Finance

I haven’t updated in a while; the story gets a little boring after a while. But, as I was asked for advice a few times this year, I think it’s finally time to do another update.

Past editions: 2009, 2010, 2011, 2012, 2013

The last few years have been a little slower: +11% in 2014, +9.6% in 2015 and +6.3% in 2016. The difference is largely due to bonds: 2014 was a boom year and 2016 was a slow year. For me personally, the performance over this period was not a big deal; I bought a house in 2014 and now have a real estate-heavy portfolio.

Performance

Here’s the performance of my portfolio over the past several years, using the latest 2016 country weights. The table below shows the annual returns of each component of the portfolio, giving the “sequence of returns” for each piece.

weight2007- 2011 annual average20122013201420152016
Equities
   U.S.A.VTI33.6%-2%16%43%23%19%9%
   Europe / PacificVEA21.1%-7%18%30%3%19%-1%
   EmergingVWO5.3%0%19%2%9%0%9%
   CanadaXIC15.0%1%7%12%11%-8%20%
Subtotal75%-2.3%15.2%28.5%12.4%11.8%8.1%
Fixed income
   Mixed bondsVAB20%6%3%-2%9%4%1%
Subtotal20%5.8%3.0%-1.8%8.6%3.6%1.2%
Cash5%0%0%0%0%0%0%
Total100%-0.3%12.0%21.1%11.0%9.6%6.3%

Same assumptions as usual:

  • Expressed in Canadian dollar terms (i.e., including all currency shift effects and using no currency hedging)
  • Includes all distributions/dividends
  • Rebalanced annually

Cumulative returns:

  • From Jan. 2007 to Dec. 2016: 76.9% (5.9% annually over 10 years)
  • From Jan. 2008 to Dec. 2016: 75.0% (6.4% annually over 9 years)
  • From Jan. 2009 to Dec. 2016: 117.9% (10.2% annually over 8 years)
  • From Jan. 2012 to Dec. 2016: 75.4% (11.9% annually over 5 years)

It’s always good to look at the longer term. While the 5-year performance looks quite good at 11.9% growth per year, as soon as the time window includes a major negative event — like the 2008 crash — the 10-year performance shows a more modest 5.9% growth per year: a more realistic expectation for the long run. It’s also interesting to see the benefits of a mix of stocks and bonds: during the first five years, bonds outperformed stocks and delivered a +6% annual return (+30% over 5 years) while stocks lost value. It’s a little hard to remember now, when bonds have ben so underwhelming recently, but great to see a reminder why a mixed stocks/bonds portfolio is worth while.  (As it happens, I started investing in Jan. 2009, just after the crash, so I haven’t actually yet been through a period where bonds seriously paid off.)

Other Notes

  • Currency exchange: I’m earning income in US dollars this year, and no have a sudden interest in better ways to exchange money. I did my first few Norbert’s gambit recently, and was pleased by the results. I’ll be doing that going forward. For those not willing to make the jump, I did also learn that TD Waterhouse offers a significantly better exchange rate (~1%) when swapping US$25,000 in a single transaction; but that’s still a $250 charge while Norbert’s gambit is closer to $20.
  • I’m still curious to know better strategies for managing a portfolio that includes real estate. I feel vastly overexposed to interest rate risk, not to mention the vagaries of the real estate market these days, and it feels to me that bonds may be a bit redundant when holding real estate. Oddly, I haven’t found anything that treats real estate as part of a normal portfolio.

From Data Science & Transportation to Software

· modelling & sci/tech, Transportation

mds

As of early September, I’ve shifted to a new job in software development / 3D graphics with Mental Canvas. This comes after eight years as a data scientist / transport modeller at Metrolinx. I’m very excited to take on this new position, and I’m particularly keen to shift to a job where the product is working software instead of analysis and advice.
While the transportation modellers I’ve talked understand the close relationship between software and modelling, for others in transportation this seems like a drastic shift in direction. It’s not; the two jobs have quite a bit in common, and I’d like to explain the shared ground. To me, there are three basic stories here:

  • Similar Data: both transportation and graphics have a lot of similarly structured data. Both jobs involve a lot of time organizing, structuring and automating the flow of data.

  • Data Science & Software: a software person would use the term “data science” to describe transport modelling; it’s a hybrid of software and statistics, applied to the problems in the transportation field. Data Science and Software Development are closely related career paths.

  • Software and Transportation are Converging: or perhaps more boldly, software is in the early stages of disrupting the transportation sector.

Continue reading