C. Keith Ray

C. Keith Ray is developing software for Sizeography and Upstart Technology. He writes code for multiple platforms and languages, including iOS® and Macintosh®.
Go to Sizeography and Upstart Technology to join our mailing lists and see more about our products. Keith's Résumé (pdf)

Thursday, January 15, 2015

Swift - initializing CGFloat values

import UIKit

var red: Int = 12

var newRed1 = red/255
// newRed1 is Int with value 0

// var newRed2 = red/255.0
// Error: Cannot invoke '/' with an argument list of type '(@lvalue Int,FloatLiteralConvertible)'

var newRed3 = CGFloat(red)/255.0
// newRed3 is CGFloat with value 0.0470588235294118

var newRed4 = CGFloat(red)/255
// newRed4 is CGFloat with value 0.0470588235294118

var newRed5 = CGFloat(red/255)
// newRed5 is CGFloat with value 0.0
// This one is surprising:
// var newRed6 = CGFloat(red/255.0)
// Error: "Could not find an overload for 'init' that accepts the supplied arguments"

Tuesday, December 23, 2014

myGraph is free for Christmas

myGraph by Sizeography, the app that prints graph paper, is free for Christmas and from now (Dec 23, 2014) until the end of the year. Free!

Besides printing standard kinds of grids and graph paper, you can customize the colors, spacing, and line-width. Do you want green and red? You can have it.

Check it out!

Monday, December 8, 2014

Readable Code

Recently, I needed to change a scalar variable into a stack, as I modified my code to handle a new feature. Here's what I did.

First, I looked to see if the libraries I had access to contained a Stack class. (Apple's Foundation framework, etc.) I didn't find one. Nor did I find 'push' and 'pop' methods.

I could have changed the variable to an NSMutableArray and used these two methods instead of 'push' and 'pop':

- (void)addObject:(id)anObject;  // adds to the end of the array
- (void)removeLastObject;  // removes from the end of the array

Functionally, those two method would serve as 'push' and 'pop', but it would be easy for future-me, or another member of the developer team, to forget that the object is supposed to be used like a stack.

One option would be to add methods to the NSMutableArray class via a class category. That would allow my code to call 'push' or 'pop' but still doesn't clearly express my intent for this variable (which would still be declared as an NSMutableArray.

Since a basic stack is very easy to construct, I built one very quickly with just the API that I wanted. This is a common enough "demo" of Test-Driven-Development that I'm not going to reproduce it hear.

One thing did come up: I will sometimes want to display the contents of the entire stack, and I don't want to push/pop everything to do so. So I added another stack test and another method to my stack class.  Since I know the stack will be small (less than 30 objects), I return a copy the internal array storage, rather than returning an enumerator for the caller to access elements one-at-a-time.

-(void) testContents
    [stack push: @"a"];
    [stack push: @"b"];
    [stack push: @"c"];
    AssertEqual(3, [stack count]);
    NSArray *arr = [stack contents];
    AssertEqual(3, [arr count]); // calling contents doesn't pop.
    AssertObjectsEqual(@"a", arr[0]); // oldest
    AssertObjectsEqual(@"b", arr[1]);
    AssertObjectsEqual(@"c", arr[2]); // newest - top of stack


-(NSArray *) contents
    return [_storage copy];


Getting the data in this order (from the bottom of stack to the top of stack, is precisely what I want, since I be displaying the contents horizontally in the UI. 

But... I think 'contents' isn't clear enough. So I renamed the method:

-(NSArray *) contentsBottomUp
    return [_storage copy];


And, for symmetry, I added another method (and test) to return stack contents top-down instead of bottom-up. While not strictly needed for the current UI. I might want to display the stack contents vertically, and then I'd want the display the top first, and the bottom last.

-(NSArray *) contentsTopDown;

Since I didn't find a 'reverse' method in the Foundation framework either, I needed to implement a way to reverse the contents being returned from 'contentsTopDown'. While looking for examples of code using Apple's 'Fast Enumeration' implementation, I found this one-liner in NSHipster's blog:

-(NSArray *) contentsTopDown;
    return _storage.reverseObjectEnumerator.allObjects;

The end.

Monday, November 17, 2014


The question: "I encountered an issue when I try to mock 3rd-party library functions.  The MOCK_METHOD_i macro supports i = 1 to 10 arguments, but 3rd-party library has functions with 11 arguments. Should I alter the scripts that build the MOCK_METHOD_i macros?"

My answer:

Yes and no.

Yes: so go ahead and rebuild the mocking framework by setting "n = 12 or so" in the script the generates the MOCK_METHOD_i macros. Make the tools do the work you want them to do.

No: it's often better to only mock code that you own. If you make that a rule, then what you have to mock is code that you wrote, code which hides and (hopefully) simplifies access to the external code. Your own code will likely NOT need 11 arguments, since you can hide unnecessary parts of the external code. 

There's a nice wrap-up of this concept here: http://www.davesquared.net/2011/04/dont-mock-types-you-dont-own.html

Using test doubles for types we don’t own can end up with fragile tests that don’t actually test much of value, or can even compromise our design and the effectiveness of the abstractions we use. Even when mocking a library we know really well we can end up with compromised abstractions and fragile tests due to relying on implementation details or assumptions based on previous versions of the library.

Friday, October 3, 2014

iPhone and iPad Models and Screen Resolutions

iPhone and iPad models and screen resolutions in the context of Apple's Xcode launch image xcassets view.

Tuesday, August 26, 2014

I and Me

If you're wondering whether to say "Bob and I" or "Bob and me," here's the trick: Take "Bob and" out of the sentence, correct the number implied by other words, if necessary, and judge whether the sentence sounds right.

Example 1: "Bob and I just want the best for you."

Drop Bob: "I just want the best for you."

The rewritten sentence sounds right, so "Bob and I" is correct in this example. The sentence should be, "Bob and I just want the best for you."

Example 2: "That award belongs to Bob and I."

Drop Bob: "That award belongs to I."

That doesn't sound right. So this example should be "That award belongs to Bob and me."

And you can test that again by changing "I" to "me" and leaving out Bob. "That award belongs to me." (But don't say that to Bob!)

Example 3: "We want to create the same experience you would have if you had called both Bob and I into your office for a meeting."

Drop Bob: "I want to create the same experience you would have if you had called I into your office  for a meeting."

That doesn't sound right. Let's try "me."  "I want to create the same experience you would have if you called me to your office  for a meeting." Better.

So, the better sentence is: "We want to create the same experience you would have if you had called both Bob and me into your office for a meeting."

That's it. Those of us who speak English as a native tongue, already know the unspoken rules of grammar; we just get confused when we try to follow the artificial rules we were taught in schools or by well-meaning friends.

Wednesday, August 13, 2014

Two Weird 'Tricks' For Testing Graphical Code

Before I do a bunch of "Extract Method" refactorings, I looked over the code and wrote this comment:

    // creates pdf context.
    // computes rowCount and columnCount from paper_size
    //    and major_grid_distance.
    // computes margin sizes (and thus origin.)
    // draws graph paper into context.
    // close context.
    -(void) drawMajorMinorGridAt: (CGPoint) origin
                     andRowCount: (int32_t) numberOfRows
                  andColumnCount: (int32_t) numberOfColumns

                       inContext: (CGContextRef) context;

What the extract methods will do, is let me draw while not in a pdf context. Code-reuse: yay!

Another way to achieve the same goal: copy & paste. While copy & paste may be quicker,  it bulks up the code and potentially doubles the number of defects that may "bug" us in the future. Technical debt.

One could argue that planning ahead would have created a better design. But... I didn't need to draw while not in a pdf context, a half-year ago.

One reason this code is so bad, is that I didn't exactly test-drive it. I ran some calculations, wrote the code, and looked at the output. In some early iterations, it produced grids with lines poking too far through other lines: I had to reduce the length of some lines, by the thickness of other lines. Similar glitches provoked a few other changes. And then it was done. I haven't touched the code in quite a while. 

Could I write some automated tests for this code? Yes. 

I could save some manually-verified pdf output as "Golden Data" and do file comparison in tests that are supposed to produce the same output. I have done something like this before. The only time the test failed in my project (without my changing code to cause the failure) was when a graphics library that my code depended on changed. 

So... few "false" failures. Drawbacks: slow tests, manual verification needed if the test fails. And manual intervention to re-create the "Golden Data" when the code is fixed or the failure is identified as not a bug. I also had to write a custom file-comparison routine in order to ignore parts of the file that change all the time (a time-stamp in the file itself.)

You do not want to do "Golden Data" test data when false failures are frequent. (Or any kind of manual intervention is frequent.)

Mocking. Yes, I could mock out the drawing code. It's a bit difficult because the drawing code below this Objective-C class consists of C functions. I would have to create a "seam" to allow compile-time, link-time, or run-time switching out of the drawing library. 

Mocking can create fragile tests. Since mocking works by verifying that the code-under-test executes an expected sequence of function-calls, and checks that the parameters passed into those functions have expected values, any change to the order of calls or the parameters passed in will cause the test to fail. This depends on how picky you configure the mock objects to be.

With some work, depending on the mocking framework, you could ignore the exact sequence of function calls, but still check that all of the calls have been made. Make the mocks too "loose" and then you're not testing anything. Make the mocks too strict, and you not only open yourself up to the possibility of frequent false failures, you also inhibit refactoring the drawing code.

There is also the danger that the functions you're avoiding calling will someday change their behavior, but the mock functions don't reflect that change. Instead of false test failures, you get false test successes. Some redundancy in testing helps avoid this problem: have some tests using mocks, have other tests using the real functions and some other form of verification, like Golden Data.)

Learn about Golden Data, mocks, and other xUnit Test Patterns here: xUnit Test Patterns: Refactoring Test Code

Test-drive safely, everyone!

Tuesday, August 12, 2014

When Your Brain Freezes Up

Some time ago, I was part of team for a trivia contest. There was no internet or computer access at that location, so no chance of cheating. I took the lead on some of the questions and got them wrong!

Why did that happen? I expected the questions to be hard. I expected the trivia questions to have non-obvious answers. It turned out that the obvious answers were the correct ones.

Go to this you-tube "video" (it's audio only) where a radio disk-jockey is posing a question to someone they randomly called. If the person they called gets the question right, they could win a motorcycle worth around $8,000 (US).

DJ: We've got to ask you a question before we put your name in the barrel. Spell AC/DC.
Mark: AD AC
DJ: I'm going to ask you again.
Mark: Hang on.
DJ: How do you spell AC/DC?
Mark: A… D… A… C
There's some overlapping dialog, and we hear Mark say "ACDC" in that noise. But his answer when asked a third time is still ADAC, until they call him an idiot and tell him it's AC/DC!

It could be this guy had other issues, but under stress, our body is preparing for flight or fight. The neocortex is only a recent invention. "Flight or fight" has been around for billions of years.

Friday, July 18, 2014

Function Pointer Syntax Cheat-Sheet-By-Example

#include <stdio.h>

// Using * to indicate the parameter is a pointer to a function.

void functionTakingFunctionPointerOldStyle(int (*pf)(int))
    printf("\nold style pf = %p\n", pf);
    if (pf != NULL)
        int x = (*pf)(12); // Using * to deref function pointer.
        printf("pf(12) = %d\n", x);

// We don't need * to indicate that a parameter is a function pointer.

void functionTakingFunctionPointerNewStyle(int pf(int))
    printf("\nnew style pf = %p\n", pf);
    if (pf != NULL)
        int x = pf(12); // Don't need * to deref function pointer, either.
        printf("pf(12) = %d\n", x);

// Blocks. Like old-style function pointer, using ^ instead of *.

void functionTakingBlock(int (^pf)(int)) // like old-style function pointer.
    printf("\nblock pf = %p\n", pf);
    if (pf != NULL)
        int x = pf(12); // Same syntax as calling function or function-pointer.
        printf("pf(12) = %d\n", x);


If we use a typedef, then the syntax for parameter declaration is simple:

     typedef int (*funcPtr)(int);

     void functionTakingFunctionPointer(funcPtr fp);

 But now we need to remember how to declare the function-pointer typedef!

 This is how I create a typedef for a function pointer type:

 1. Start with the function declaration itself.

     int functionTakingIntReturningInt(int i);

 2. Remove parameter names.

     int functionTakingIntReturningInt(int);

 3. Change the function name to a name appropriate for this function-pointer type, maybe suffixed with "FuncPtr" if you can't think of something more meaningful. Don't suffix "Type" to the name—like "FuncPtrType"—it makes you look like a newby. (I stopped doing that last week.)

     int funcPtr(int);

 4. Wrap name with (* and )

     int (*funcPtr)(int);

 5. Add typedef

     typedef int (*funcPtr)(int);

 6. Profit!


int functionTakingIntReturningInt(int i)
    return i + 1;

int main(int argc, char *argv[]) 
    // "old" style C code - using "&" take address of the function.
    functionTakingFunctionPointerOldStyle( NULL );
    functionTakingFunctionPointerOldStyle( & FuncionTakingIntReturningInt );

    // "new" style C code - don't need "&" for function type.
    functionTakingFunctionPointerNewStyle( NULL );
    functionTakingFunctionPointerNewStyle( FuncionTakingIntReturningInt );

    // blocks
    functionTakingBlock( NULL );
    functionTakingBlock( ^(int i){ return i + 1; } );


old style pf = 0x0

old style pf = 0x1004aa980
pf(12) = 13

new style pf = 0x0

new style pf = 0x1004aa980
pf(12) = 13

block pf = 0x0

block pf = 0x1004ab0f0
pf(12) = 13

Wednesday, April 30, 2014

myGraph 1.0.3 is Now Available on the Apple Store

myGraph 1.0.3 is Now Available on the Apple Store

myGraph lets you design fully-customizable graph paper, save it, share it, and print it on any AirPrint™-enabled printer. You have your choice of unlimited colors, line widths, and line spacing, so you can always have graph paper perfectly designed to your specific needs.

myGraph is perfect for interior designers or landscape designers, crafters, engineers, students, teachers, and more.

In myGraph you may select from predefined graph-papers or create your own. You may choose from an unlimited spectrum of colors. And, set grid spacing in fractions or decimals, in English or metric units.

Your graph-paper’s line-width and primary and alternate colors are under your full control. Want green instead of blue? Thick lines or thin? You can make it so!

Printing requires a printer supporting AirPrint™. You can share myGraph’s graph-paper through email, DropBox and other apps on your iPhone or iPad. Import myGraph’s graph-paper into painting or drawing programs.

Supports standard paper sizes for US and metric printers.

What's New in myGraph version: 1.0.3:

  • Fix issue with scrolling in the information view. It wasn't allowing the user to scroll to the end of the text. Now, it allows scrolling.
  • Performs faster.
  • Fixed memory leaks.

View in iTunes

Download myGraph in the App Store

Tuesday, April 22, 2014

myGraph 1.0.3 Beta Testing

Would you like to beta test for the iOS app myGraph by Sizeography™?

myGraph lets you design and print grids or graph paper, and save your designs so you can print them again. Create or select a grid, choose the color, spacing, and line-width of the grid, and optionally specify an alternate color and line-width for accent lines. Then you can print, share, or open a grid in another iOS app on your device.

PS: While we are trying to be as careful as possible, there are risks in running beta software on your iOS device. While we have not seen any problems other than myGraph freezing up or crashing, there is always a risk of data loss. Please be careful to backup your iDevice before testing.

If you decide to help us test, please try the following after you get the beta app installed:

  1. Try creating different designs of graph paper -- choosing colors, spacing, line-width and so on. If you really like a grid or graph paper that you designed, you can note the settings that you used to create that design and send me the notes and the pdf output for that design -- and I could feature that on our website, with a link to your homepage, if you so desire.
  2. Please try all the features that you can see. Check out the Help text and see if it makes sense. If you experience a hang or crash, please report the steps that you took to get that to happen. You can make screen-captures and send those to me.
  3. myGraph supports "Open In..." and "Share..." as well as "Print...". One of the "Open In..." choices is eMail, so go ahead and send me ONE email as part of your testing.

To sign up for testing CLICK HERE!

(Sizeography™ is a division of Upstart Technology™, CEO Cynthia Wunsch, CTO Keith Ray.)

Wednesday, April 2, 2014


http://feedly.com/e/-sUatCMU birth of the light-saber

http://feeds.boingboing.net/~r/boingboing/iBag/~3/_6-Tz9H199E/story01.htm Rigged stock-trading? Also see Daily Show interview

http://feedproxy.google.com/~r/failblog/~3/er2CdGTxGdA/8130370560 Snakes in toilets -- we need devices to keep them out -- (kickstarter, anyone?) 


"So I went back to Things, a program that’s so simple, it doesn’t have a manual. (It’s also Mac only; sorry.) I had the basics down in under two minutes. You click on the Projects button and give the project a name–You Again, Kitchen, Chores, Car, whatever. Under that you click on the Add button and you get a line in your To List so you can break down the job into small parts: Synopsis, Hang Shelf, Wash Dishes, Call Toyoto, whatever. 

"Then you assign a due date for each To Do. That’s it. It does other things–you can assign tags and add notes, etc.–but it does the one thing I need–generate daily to-do lists–and it does it really well."  

"My first to do lists weren’t broken down into small enough tasks, so I’d look at my list for a day and realized it would take forty hours to do what I’d scheduled in twelve. Back to revising the lists, stretching out the time periods for getting things done, making the tasks smaller. My second to-do lists were much better, until I realized that scheduling sixteen-hour work days wasn’t a good idea, either. I can do that for one or two, even three days, but week after week? No. So I went back in and reassigned due dates again, which is easy to do in the program."


"As the day of our first release planning event grew closer, I noticed that there were some blank faces among my extended leadership team when I referred to various aspects of what we needed to do. My heart sank as I asked the team, “Who has read the book?“. A couple of hands were raised. “Who has finished the book?“. Only one hand (and yes he still works with me!). “Who doesn’t own the book?“. At least four or five hands were sheepishly raised. “OK” I said “Change of plan. We are all going to buy the book. If you cannot afford the book, let me know and I will arrange a book for you. Then we are going to read the book together. We are going to form a book club!” As Deming said, “without theory there is no learning”. 
"For the next 3 months I met with my extended leadership team for an hour a week. Each week one member of the team lead a discussion on a chapter or two. We would discuss the concepts covered, how they might apply to our situation and agreed on the ideas we wanted to implement. Book club was compulsory and if one team member had something more important to do then book club was rescheduled. Shared understating and agreement was paramount if we were going to be successful. 
"Visitors to the EDW Release Train are often shocked when they hear that I called a mandatory weekly meeting to read a book. I am always quick to remind them that no one would hesitate to call a “business” meeting, so why wouldn’t we want to make time for a meeting focused on learning ways to improve our “business”."

"If you buy an ebook from anyone other than Amazon, you’re buying an EPUB file. Apple and Google, in particular, have aggressively supported EPUB 3 in their iBooks and Google Play stores. As an ebook author, iBooks and the Google Play reader are a dream come true: I can write the book, style it as I please with modern CSS, and be confident that readers will see the text as I intended. 
"For sales on the Kindle Store, I need to generate a KF8 with kindlegen. I have to painstakingly craft my EPUB files so as not to conflict with the limitations in Amazon’s undocumented subset of EPUB3."

http://feedly.com/k/19JcS1I "quartoOpen source ebook formatter (under development) 

"Fear of success, just like fear of failure, can paralyze you. Can you find a way to create an experiment that will allow you to succeed, in one small way? Then, use the results to learn from that experiment? 
"If you have the growth mindset, it’s not about you as a boxed-in person. It’s about you as an experiment. You build your emotional resilience and your experiences to help you along the way."