Betrayed by language

Orwell, "Politics and the English Language"

The media has widely reported that the Secret Service recently allowed an armed, deranged person to jump over the White House fence and enter the mansion. The agency director, Julia Pierson, quickly disintegrated in the wake of bipartisan pressure to resign.

I don’t know Ms. Pierson. She may have performed well in prior posts. Perhaps not.

But her use of language during her testimony to Congress betrays her as a bureaucrat more concerned with management than leadership. Consider her response to an inquiry about agency staffing:

“I do know we have provided a human capital strategy to Congress at their request.”

No leader who is concerned with the actual effectiveness of her organization in the real world would resort to deliberately obscure terminology in this fashion. A better response would be clearer and more direct. Perhaps:

“We provided Congress with a staffing plan at their request.”

or,

“We submitted a report to Congress on how we plan to staff the agency.”

Finally, a leader does not lapse into passive voice in matters as serious as this. Ms. Pierson testified that:

“It is obvious that mistakes were made.”

Who made mistakes? What was the nature of there errors? How about:

“We failed to respond to a serious threat to the President.”

The passive voice points a detachment from responsibility and a failure of leadership.

Unit testing with Swift and Core Data

The problem

Unit testing with Core Data can be complicated. We want to reduce any dependencies in order to isolate the class under test. But Core Data itself is a big dependency. Graham Lee wrote a couple blog posts[1],[2] several years ago on patterns for testing Core Data applications. He describes two patterns for isolating the the class under test. While Graham prefers to remove the Core Data dependency entirely, I’ve tended to use his second pattern by creating an in-memory Core Data stack that I build up and tear down with each test. I’ve done this for years using Objective-C; but now that Swift has come on the scene, I’ve had to adapt the process somewhat; and I’ll describe that here.

Application test example

We’ll start out by constructing a prototypical Employee/Manager model in a sample app. I’ve called the product (and module) name “Zoom”. This is important to know because we’ll need to prepend out NSManagedObject model class names in the model editor with the module name. Because of what I regard as an Xcode 6 bug, you should not prefix the class names in the model editor until after you’ve generated the class files assuming you want Xcode to do that step for you. If you namespace the class names beforehand, then the NSManagedObject subclass generation function in Xcode 6 won’t work properly.

Entities and NSManagedObject subclasses

With that in mind, create two entities: Boss and Employee. Give the Boss entity, attributes of firstName (String) and lastName (String). Give the Employee entity, attributes of firstName, lastName, salary (Integer 16), and dateHired (Date).

swift core data class nameConfigure the relationships between Boss and Employee. That should be obvious Boss to Employee is To-many and then the reciprocal to keep Core Data happy.

Remember to set the Class field in the Entity inspector; but leave off the namespace if you’re first generating the NSManagedObject subclasses. Your generated Employee class should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
import Foundation
import CoreData

class Employee: NSManagedObject {

@NSManaged var firstName: String
@NSManaged var lastName: String
@NSManaged var dateHired: NSDate
@NSManaged var salary: NSNumber
@NSManaged var boss: Boss

}

and the Boss class should look like this:

1
2
3
4
5
6
7
8
9
10
import Foundation
import CoreData

class Boss: NSManagedObject {

@NSManaged var lastName: String
@NSManaged var firstName: String
@NSManaged var employees: NSSet

}

When generating the subclasses for your model entities, remember to add the files to both the main target and the unit test target. The same goes for the model file itself. Now that we’ve set up the NSManagedObject subclasses for our Core Data entities, we can namespace the classes in the model editor:

swift core data class name

The Core Data stack

In my main application, I’ll just use the templated Core Data stack. It works as a starting point and it also can serve as the in-memory stack for our unit tests. To simplify testing of classes that use Core Data, I start with a base class that sets up and tears down our in-memory stack. We’ll call that class CoreDataTestCase.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

class CoreDataTestCase:XCTestCase {
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = NSBundle.mainBundle().URLForResource("Zoom", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application’s saved data."
if coordinator!.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil, error: &error) == nil {
coordinator = nil
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application’s saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSLog("Unresolved error (error), (error!.userInfo)")
abort()
}

return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext? = {
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()

override func setUp() {

}

override func tearDown() {
managedObjectContext = nil
}
}

Example test class

We’ll derive our test classes from this base class. For example, to test our Boss class, we could begin with a test case class that derives from CoreDataTestCase:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import Foundation
import CoreData
import XCTest

class BossTestCase: CoreDataTestCase {
var boss:Boss?

override func setUp() {
super.setUp()
let entity = NSEntityDescription.entityForName("Boss", inManagedObjectContext: managedObjectContext!)
boss = Boss(entity: entity!, insertIntoManagedObjectContext: managedObjectContext)
}

func testThatWeCanCreateBoss() {
XCTAssertNotNil(self.boss, "unable to create a boss")
}
}

Conclusion

Creating an in-memory store doesn’t completely eliminate the Core Data dependency; but it reduces the pre-test assumptions considerably and makes for more controlled testing in Core Data applications.


  1. Lee, Graham. (6 September, 2009) Unit testing Core Data-driven apps. Retrieved Septeber 28, 2014, from http://iamleeg.blogspot.com/2009/09/unit-testing-core-data-driven-apps.html

  2. Lee, Graham. (10 January, 2010) Unit testing Core Data-drive apps, fit the second. Retrieved September 28, 2014, from http://iamleeg.blogspot.com/2010/01/unit-testing-core-data-driven-apps-fit.html

Richard Morgan on Kicking the Facebook Habit

Today Richard Morgan wrote an brilliant witty piece “Kicking the Facebook Habit” in the New York Times.

His comments on the reactions of his Facebook connections to his suddent departure are predictable but amusing:

When my friends tried to check in on me, they saw only an Error 404-style page. A typical note from an over-30 friend was “Are you O.K.?” A typical under-30 note was “Did you block me on Facebook?” Their self-centered hysteria only amplified my abstinence.

I left Facebook nearly two years ago, an act that leaves me now with only the most minimal curiosity about what’s happening there.

'Music in Practice' on photocopying

I recently stumbled on the website “Music in Practice” which is a great resource for violin teachers and parents.

One of the articles that caught my attention was “Photocopying Helps Focus” which outlines the ways in which making extra copies of the music can help with practice. Sue Hunt, the author, refers to several ways that photocopying can be an aid to practice. A few caught my eye:

  • Photocopying creates clean copies to use so that cumulative marks on the score don’t cloud what’s really important in practice during the week.
  • You can slice and dice the copies and rearrange them so that just the passages of interest appear on a single page. Although it’s hardly necessary to go to this much trouble, I use a flat-bed scanner to scan the music. Sometimes marks are already on the score; so I use Photoshop to clean up the original images, then I begin to take pieces of the music and clip them into a new document. For example, ViolinGirl is learning “The Two Grenadiers” from Book 2 now. I want her to practice all of the retakes because they all use the same technique (small circle bow at the frog.) On the first page of the new document, I write out the instructions from the teacher and put the passages lined up down the page. It reduces the temptation to just keep playing through to the next phrase. I did the same, then with other types of learning spots, categorizing them into similar applications of technique. It keeps us focused on one technique at a time.
  • For the longest time, I’ve been craning my neck to see measure numbers when we are in a lesson. ViolinGirl’s teacher gives an instruction for a particular passage and I want to make note of that instruction. It’s difficult without the music in front of me; so I’ve begun to bring clean copies of the most recent working pieces to the lesson so that I can mark them up as the teacher makes comments. It’s much easier than trying to verbalize the instructions in my notes. Now I use lesson copies.

Waiting on multiple asynchronous tasks

The concurrency tools on iOS and Mac are numerous and the decision about which technology to employ often comes down to the level of abstraction that the developer wants to use. For many concurrency problems, NSOperation and NSOperationQueue is sufficient.

One nearly intractable problem that I face in several applications is the need to wait on multiple web service calls to complete before starting another process. I use AFNetworking almost exclusively in my applications because it simplifies asynchronous web service work. In this case, dispatch groups and NSOperationQueue don’t work, because we only know when the job has been submitted, not when it has been completed. We need to be able to wait on multiple already-asynchronous tasks to complete. In this post, I’ll describe how I go about solving the problem.

Let’s say I have an object Foo that needs to be registered with my web service. Foo has a category that handles the registration process and executes a completion block. The solution I’m describing uses dispatch_group_enter and dispatch_group_leave along with waiting on a background queue. In this scenario, I must wait for the group to complete on a background queue because I’m firing off the asynchronous web services calls on the main queue. If I wait on the same main queue, than I block its execution and I’m deadlocked. So, my dispatch_group_wait is on a background queue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
for( Foo *foo in pendingRegistrations ) {
dispatch_group_enter(uploadGroup);
[foo uploadRegistrationWithCompletionBlock:^{
dispatch_group_leave(uploadGroup);
}];
}
// wait on another queue
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_group_wait(uploadGroup, DISPATCH_TIME_FOREVER);

// now I can do something that depends on all of the registration uploads
// to have been completed.

// perhaps I may even want to do those back on the main queue:
dispatch_async(dispatch_get_main_queue(), ^{
// do something on the main queue after our wait
});
});

Progressions




“Par les soirs bleus d’été, j’irai dans les sentiers,

Picoté par les blés, fouler l’herbe menue,

Rêveur, j’en sentirai la fraîcheur à mes pieds.

Je laisserai le vent baigner ma tête nue.”

“Je ne parlerai pas, je ne penserai rien :

Mais l’amour infini me montera dans l’âme,

Et j’irai loin, bien loin, comme un bohémien,

Par la Nature, heureux comme avec une femme.”

Sensations, Rimbaud

Spirograph in Swift

Erica Sadun published a cool little Swift playground that draws images like the old Spirograph that we played with as kids. The thing is, it wasn’t immediately clear how to use it. I fooled around with it and got it working.

Here’s Erica’s part:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import UIKit

struct SpirographGenerator : GeneratorType {

var pointOffset, dTheta, dR, minorRadius, majorRadius : Double
var theta = 0.0
typealias Element = CGPoint

init(majorRadius : Double, minorRadius : Double, pointOffset : Double, samples : Double)
{
self.pointOffset = pointOffset
self.dTheta = Double(M_PI) * (2.0) / samples
self.majorRadius = majorRadius
self.minorRadius = minorRadius
self.dR = majorRadius - minorRadius
}

mutating func next() -> CGPoint? {
var xT : Double = dR * cos(theta) + pointOffset * cos(dR * theta / minorRadius)
var yT : Double = dR * sin(theta) + pointOffset * sin (dR * theta / minorRadius)
theta = theta + dTheta
return CGPoint(x: CGFloat(xT), y: CGFloat(yT))
}
}

Now, how do you produce images from that? Basically, you just need to create an image context and draw into it. Here’s my part:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//  sample size
let n = 100

// offset in the image
let (majorRadius:Double, minorRadius:Double) = (48,-47)

// iterations
let iterations = 15


var spiro = SpirographGenerator(majorRadius: majorRadius, minorRadius: minorRadius, pointOffset: 13, samples: Double(n))

let dimension_2:CGFloat = 125

// image size
let size = CGSizeMake(dimension_2 * 2, dimension_2 * 2)

UIGraphicsBeginImageContext(size)
let ctx = UIGraphicsGetCurrentContext()
for i in 0…iterations*n {
let p:CGPoint? = spiro.next()
NSLog(“%@”,NSStringFromCGPoint(p!))
if i == 0 {
CGContextMoveToPoint(ctx, p!.x+dimension_2, p!.y+dimension_2)
}
else {
CGContextAddLineToPoint(ctx, p!.x+dimension_2, p!.y+dimension_2)
}

}
CGContextStrokePath(ctx)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

Now you should just be able to view the image by clicking on the eye icon. By varying the radii and the number of iterations, you can produce some neat images in an Xcode 6 Playground.

spirograph image

Edited on 2014-08-29 16-13-31 Generator is now GeneratorType and fixed issue with diappearing * symbols here and there.

John Gatto on school as a form of adoption

John Gatto has a way of cutting straight to the core issues in education:

“Schooling is a form of adoption. You give your kid up in his or her most plastic years to a group of strangers. You accept a promise, sometimes stated and more often implied that the state through its agents knows better how to raise your children and educate them than you, your neighbors, your grandparents, your local traditions do. And that your kid will be better off so adopted.”

“But by the time the child returns to the family, or has the option of doing that, very few want to. Their parents are some form of friendly stranger too and why not? In the key hours of growing up, strangers have reared the kid.”[1]

In a few words, Gatto encapsulates the main reasons we’re homeschooling. These remarkable years of childhood are full of opportunity and openness to every possibility. Turning kids over to a school regardless of how well-meaning that school may be, means that you must tacitly agree to a set of values and priorities with which you may not agree.

In school districts around the country, the state has decided that music is unimportant relative to other subjects that it wishes to teach. If you send your child to public school, you either agree to their ordering of priorities or you do it on your own time. But there is no time left. Apart from the extraordinary kid, there’s is just too little energy, time, and enthusiasm left. But aside from the logistical difficultes, there remains the fundamental problem that when you leave your children to be adopted by schools, you agree to a set of cultural values that may lie in opposition to your own.

“Before you can reach a point of effectiveness in defending your own children or your principles against the assault of blind social machinery, you have to stop conspiring against yourself by attempting to negotiate with a set of abstract principles and rules which, by its nature, cannot respond. Under all its disguises, that is what institutional schooling is, an abstraction which has escaped its handlers. Nobody can reform it. First you have to realize that human values are the stuff of madness to a system; in systems-logic the schools we have are already the schools the system needs; the only way they could be much improved is to have kids eat, sleep, live, and die there.”[2]

Ordinarily I don’t harbor the sort of paranoia and hyperbole that seems to drive most libertarians; and there is a libertarian streak in what Gatto stresses about contemporary public education. But the system turns out kids by design who follow a concept of the good life that is too foreign from our own.


  1. Gatto, J. (Original date unknown). The Open Boat. Retrieved August 10, 2014, from http://www.the-open-boat.com/Gatto.html

  2. Gatto, J. (Original date unknown). Two Social Revolutions Become One - John Taylor Gatto. Retrieved August 10, 2014, from http://www.johntaylorgatto.com/chapters/16a.htm

Key-value coding in Swift

Key-value coding, long a staple of the Cocoa API, is accessible in Swift, with some caveats.

KVC in Swift requires NSObject

First and foremost, classes on which you intend to use KVC must descend from NSObject. It doesn’t work on base classes. So, this won’t compile:

1
2
3
4
5
6
7
8
9
10
class Boo {
var bar:Bool

init() {
bar = 0
}
}

var b:Boo = Boo()
b.setValue(true, forKey:“bar”) // this line won’t compile

but if we make Boo a subclass of NSObject, everything works as expected.

Optionals don’t work

Perhaps there’s a way of making this work; but I haven’t found it. Consider this class:

1
2
3
4
5
6
class Foo:NSObject {
var bar:Int = 0
var status:Bool = false
var name:String = “”
var boo:Int = 1
}

then we can use KVC:

1
2
f.setValue(42, forKey: “boo”)
let v:Int = f.valueForKey(“boo”) as Int

but if we change the variable boo to an optional:

1
var boo:Int? = 1

then we cannot use KVC.