Software update

(I have been waiting a while to post this picture, it seemed like a good idea to do it today what with the huge flap about the iOS 8.0.1 software update failure…)

I think my computer is trying to tell me that there is a software update…

update_dialog

BTW, Happy Birthday to Justin Bruening, who played Michael Knight on the Knight Rider TV series from 2008.

Cross a bridge at night

OK, here is a scenario. Four people on a journey together need to cross a bridge at night as quickly as possible. Among the four of them, they have one flashlight. They cannot continue their journey until all four reach the other side together. Since the bridge is narrow and slippery, and it is pitch black out being night and all, they decide to have two people cross with the flashlight, then one person returns with the flashlight back to the original side, and they continue until everyone is on the other side.

Oh, and also, the people can all walk at different paces, so when two people cross together, it takes them the amount of time that it takes the slower person to cover the distance.

For example, let’s say that the four people that need to cross can cover the distance of the bridge in 1 minute, 2 minutes, 5 minutes, and 10 minutes. What would be the shortest possible time?

The naive solution would be to have the 1 minute person be the primary flashlight runner and send them with the 2 minute person, return, then the 5 minute person, return, and finally cross with the 10 minute person, for a grand total of 19 minutes.

Now of course this is not the optimal solution, but more on that in a minute.

So how would we design an algorithm to solve this problem? Conventional wisdom says to create some kind of tree where you iterate through all of the possible combinations of initial crossings, then off those branches, combinations of reverse crossings, etc. Then once the tree is built, you can walk to all the branch tips and calculate the times, and then just display the shortest time.

But why do something logical? With all this computing power, I say that we implement my favorite algorithm for producing solutions to problems… The Monte Carlo method.

Here is the code for a C# .NET console app I threw together to solve this issue:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace BridgeAtNight
{
    public class BridgeState
    {
        public List<int> peopleOnLeft;
        public List<int> peopleOnRight;
        public int totalTime;
        public string peopleMovement;
 
        public BridgeState(int[] people)
        {
            totalTime = 0;
            peopleMovement = "";
            peopleOnLeft = new List<int>(people);
            peopleOnRight = new List<int>();
        }
 
        public void MoveLeftToRight(int leftToRight1, int leftToRight2)
        {
            peopleMovement = peopleMovement + string.Format("{0}>> {1}>> ", leftToRight1, leftToRight2);
            totalTime += Math.Max(leftToRight1, leftToRight2);
 
            peopleOnRight.Add(leftToRight1);
            peopleOnRight.Add(leftToRight2);
            peopleOnRight.Sort();
 
            peopleOnLeft.Remove(leftToRight1);
            peopleOnLeft.Remove(leftToRight2);
        }
 
        public void MoveRightToLeft(int rightToLeft)
        {
            peopleMovement = peopleMovement + string.Format("{0}<< ", rightToLeft);
            totalTime += rightToLeft;
 
            peopleOnLeft.Add(rightToLeft);
            peopleOnLeft.Sort();
 
            peopleOnRight.Remove(rightToLeft);
        }
 
        public void SolveWithNaivete()
        {
            peopleOnLeft.Sort();
            while (peopleOnLeft.Count > 1)
            {
                // move 2 people from the left to the right
                int leftToRight1 = peopleOnLeft[0];
                int leftToRight2 = peopleOnLeft[1];
                MoveLeftToRight(leftToRight1, leftToRight2);
 
                // move 1 person from right to left if there are any remaining people on the left
                if (peopleOnLeft.Count > 0)
                {
                    int rightToLeft = peopleOnRight[0];
                    MoveRightToLeft(rightToLeft);
                }
            }
 
            Console.WriteLine("Solution with naivete:");
            Console.WriteLine(string.Format("Time: {0} minutes", totalTime));
            Console.WriteLine(string.Format("Sequence: {0}", peopleMovement));
        }
 
        public void SolveRandomly()
        {
            Random rnd = new Random();
            while (peopleOnLeft.Count > 1)
            {
                // move 2 people from the left to the right
                var leftToRightRandom = peopleOnLeft.OrderBy(x => rnd.Next()).Take(2).ToList();
                int leftToRight1 = leftToRightRandom[0];
                int leftToRight2 = leftToRightRandom[1];
                MoveLeftToRight(leftToRight1, leftToRight2);
 
                // move 1 person from right to left if there are any remaining people on the left
                if (peopleOnLeft.Count > 0)
                {
                    var rightToLeftRandom = peopleOnRight.OrderBy(x => rnd.Next()).Take(1).ToList();
                    int rightToLeft = rightToLeftRandom[0];
                    MoveRightToLeft(rightToLeft);
                }
            }
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            BridgeState naiveBridgeState = new BridgeState(new int[] { 1, 2, 5, 10 });
            naiveBridgeState.SolveWithNaivete();
 
            List<string> bestTimeResults = new List<string>();
            int bestTime = 999999;
            for (int idx = 1; idx < 1000000; idx++)
            {
                BridgeState randomBridgeState = new BridgeState(new int[] { 1, 2, 5, 10 });
                randomBridgeState.SolveRandomly();
                if (randomBridgeState.totalTime < bestTime)
                {
                    Console.WriteLine(string.Format("Better random solution found in pass {0}:", idx));
                    Console.WriteLine(string.Format("Time: {0} minutes", randomBridgeState.totalTime));
                    Console.WriteLine(string.Format("Sequence: {0}", randomBridgeState.peopleMovement));
                    bestTime = randomBridgeState.totalTime;
                    bestTimeResults = new List<string>();
                    bestTimeResults.Add(randomBridgeState.peopleMovement);
                }
                else if (randomBridgeState.totalTime == bestTime)
                {
                    if (!bestTimeResults.Contains(randomBridgeState.peopleMovement))
                    {
                        Console.WriteLine(string.Format("Sequence: {0}", randomBridgeState.peopleMovement));
                        bestTimeResults.Add(randomBridgeState.peopleMovement);
                    }
                }
            }
 
            Console.WriteLine("Press any key to exit the application");
            Console.ReadKey();
        }
    }
}

There are undoubtedly some optimizations I can make to this code above, such as ordering the times in the MoveLeftToRight function. However, I was kind of surprised to see this run, as sometimes the optimal solution of 17 minutes was found in the first few thousand random walk throughs, and other times it would take a few hundred thousand walk throughs before the 17 minute solution was found. To me, it did not seem like there were enough different combinations that would make it so difficult to randomly find the solution.

For those who cannot/will not run this code, the crux of the biscuit, given the times of the walkers above (1 minute, 2 minutes, 5 minutes, and 10 minutes), is to send the slowest people across together once there is someone faster on the other side. Or in other words, first send 1 and 2 across, then have 1 come back. Then, send 5 and 10 across, and have 2 come back. Then 1 and 2 make the final crossing.

BTW, Happy Talk Like A Pirate Day today.

VB.NET simpler Async Await example

Well, I couldn’t let this rest, so here is an even simpler example of doing Async Await in VB.NET.

For this example code, I created a simple forms application with two buttons named cmdSynchronous and cmdAsynchronous, a label called lblStatus, and just to demonstrate the UI locking up effect, a combo box with some entries in it. Here is the code behind this form:

Public Class Form1
 
    Sub LongOperation()
 
        Threading.Thread.Sleep(5000)
 
    End Sub
 
    Private Sub cmdSynchronous_Click(sender As Object, e As EventArgs) Handles cmdSynchronous.Click
 
        lblStatus.Text = "Running a long operation synchronously... (UI thread should lock up)"
        Application.DoEvents()  ' needed here so that the label will update

        LongOperation()
 
        lblStatus.Text = "Done running the long operation synchronously."
 
    End Sub
 
    Private Async Sub cmdAsynchronous_Click(sender As Object, e As EventArgs) Handles cmdAsynchronous.Click
 
        lblStatus.Text = "Running a long operation asynchronously... (UI thread should be fully responsive)"
 
        Await Task.Run(Sub()
                           LongOperation()
                       End Sub)
 
        lblStatus.Text = "Done running the long operation asynchronously."
 
    End Sub
 
End Class

Notice that both button click events call the LongOperation method, which just sleeps for 5 seconds. However, the synchronous button click will lock up the UI (try to open the combo box, you will see that it waits until the sleep is done before displaying the choice list), whereas the asynchronous one will not.

Now in general, you would probably want to keep the tasks from piling up, as they would if you keep clicking the asynchronous button. I leave this as an exercise to the reader on preventing this problem.

BTW, Happy Birthday to Gary Hoey and Terje Rypdal, two of my favorite guitarists.

VB.NET simple Async Await example

I scoured the interwebs looking for a VB.NET simple Async Await example, and kind of came up empty. So, I decided to try to use bits and pieces of the examples I could find to roll my own.

The background here is that I am working on an application that accesses resources on the internet, and did not want to block the UI while the communications code was running.

Here is the code that I came up with:

Async Function GetDetails(theID As String) As Task
 
    Dim url As String
    url = GET_DETAILS_URL & "?theid=" & theID
 
    Dim request As WebRequest = WebRequest.Create(url)
    Dim response As WebResponse = Await request.GetResponseAsync()
    Dim dataStream As Stream = response.GetResponseStream()
    Dim reader As New StreamReader(dataStream)
    Dim responseFromServer As String = reader.ReadToEnd()
 
    reader.Close()
    response.Close()
 
    ' do something here with responseFromServer

End Function
 
Async Sub lstItems_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstItems.SelectedIndexChanged
 
    Dim idx As Integer = lstItems.SelectedIndex
 
    ' get the selected item
    Dim theItem As Object = itemsList(idx)
    Dim theItemID As String = theItem.itemID.ToString()
    Await GetDetails(theItemID)
 
End Sub

BTW, Happy Bennington Battle Day to our Green Mountain friends.

Twitter REST API is very finicky

The post title says it all.

I have been trying to put together some code that calls the Twitter REST API, and found it to be extremely finicky. If you do not have everything just right, you will get back a frustrating error message that says “Could not authenticate you” and “code 32″. Not super helpful.

Most of the issues I had were in building the base string that gets sent to Twitter. If this string is not built exactly as it needs to be built, things will just not work.

Here is what I found about building the base string through trial and error, and with exhaustive searches of the Google and Stack Overflow:

  • After the endpoint URL, make sure that your query string parameters are in alphabetical order
  • If you are putting into the base string part of a query that needs to be URL encoded, then it needs to be double encoded inside the base string

For example, on this double encoding thing, if you want to search for “Twitter API”, the search part of your query string, once URL encoded would look like this:

%26q%3DTwitter%20API

However, you need to double encode the search text so that it looks like this instead:

%26q%3DTwitter%2520API

BTW, Happy Birthday to Brian May, guitarist from the legendary rock group Queen.

Swift (or in other words, “Et tu, Objective-C?”)

Well the WWDC keynote has come and gone. And what do you know, a developer conference keynote geared towards developers. I guess all those bloggers and press types that took up some of the WWDC tickets from us actual developers are pretty disappointed today, as there were no shiny new devices shown.

The big announcement in my opinion was Swift, which will be the successor to Objective-C for developing on the Mac and iOS platforms. It looks somewhat interesting, as yet again they have lowered the bar and made it much easier to develop software for their platforms. But this is a disadvantage as well as a strength, as folks will continue to churn out the clones and inferior products that clutter up the App Store.

I applaud Apple for creating Swift and not recycling an existing language such as Ruby, Python, or Javascript, as these languages all come with their own baggage. Hopefully I will not be throwing away the 6 years of experience that I have built up with Objective-C and they will allow it to be used for the foreseeable future.

Ah, I miss the days when retain/release separated the men from the boys in the iOS world…

There was some good news in the presentations from yesterday. In the Platforms State of the Union presentation, they indicated that the 100 device barrier for beta testing and internal testing will essentially be rendered moot through Apple’s integration of TestFlight. This feature can’t come soon enough for me, so please hurry up Apple.

BTW, so many birthdays today, not sure where to begin… Kerry King of Slayer (happy 50th), Ian Hunter most famously of Mott the Hoople, Chuck Barris of the Gong Show… But the name that jumps out for me is Tristan Rogers, currently portraying Colin on The Young And The Restless. Happy Birthday, mate!

resignFirstResponder does not put away keyboard on UIModalPresentationFormSheet

I started to use a few view controllers inside of navigation controllers that are presented with the UIModalPresentationFormSheet style, and to my dismay discovered that the resignFirstResponder call does not make the keyboard disappear.

Apparently there is a reason for this, if you are interested you can look it up and get a full explanation. For my purposes, I was just happy to discover that overriding the disablesAutomaticKeyboardDismissal method and returning NO seems to do the trick. Basically, now when I need to present a navigation controller in this fashion, I alloc the navigation controller with the class of MyNavigationController instead of UIViewController. Here is the code for MyNavigationController.m:

#import "MyNavigationController.h"
 
@implementation MyNavigationController
 
- (BOOL)shouldAutorotate
{
    return YES;
}
 
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}
 
- (BOOL)disablesAutomaticKeyboardDismissal
{
    return NO;
}
 
@end

You will of course need to change the rotation methods to your own needs.

Today, I have a double BTW for you. Happy birthday to Joe Bonamassa, one of my favorite guitar players and all around performers. And on a sad note, one year ago today, Jeanne Cooper, the grand old dame of The Young and The Restless, passed away. The show has not been the same without her.

Unable to simultaneously satisfy constraints

All of a sudden, I started getting this error popping up in the console while developing my iOS 7 app:

2014-04-30 11:32:27.199 MyApp[4495:60b] Unable to simultaneously satisfy constraints.
	Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; 
	(2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't
	understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSAutoresizingMaskLayoutConstraint:0x1946a510 h=-&- v=-&- DetailTableView:0xe39ce00.width == UIView:0x2613afd0.width - 293>",
    "<NSAutoresizingMaskLayoutConstraint:0x12ccfd50 h=--& v=-&- H:[UITransitionView:0x12ca7570(768)]>",
    "<NSAutoresizingMaskLayoutConstraint:0xcf18c40 h=-&- v=-&- UIView:0x2613afd0.width == ADTransitionView:0xcf16f20.width - 768>",
    "<NSAutoresizingMaskLayoutConstraint:0xcf19bb0 h=-&- v=-&- ADTransitionView:0xcf16f20.width == UITransitionView:0x12ca7570.width>"
)
 
Will attempt to recover by breaking constraint 
<NSAutoresizingMaskLayoutConstraint:0x1946a510 h=-&- v=-&- DetailTableView:0xe39ce00.width == UIView:0x2613afd0.width - 293>
 
Break on objc_exception_throw to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

A few notes about the app:

1. I am still a noob when it comes to Auto Layout, so I have been kind of easing into it on some of the less critical areas of the app, but the part of the app in question is still all springs and struts.
2. I am using the ADTransitionView library to do customized view controller transitions.
3. It did not do this until this morning.

If I hit continue a couple of times on the debug console, the app moves along as if there is no problem, so this is not a critical issue, but I still wanted to find out how to take care of this issue first, and then try to figure out what triggered it.

The way that I was able to get around the issue was to look at all of the nib files that make up my view controller, table view, and cells. I found that one of the component nib files was still flagged to use Auto Layout, even though there were no constraints of any kind in that nib file. When I turned off the Auto Layout flag on that file and ran the app, it started to transition between view controllers without the ‘Unable to simultaneously satisfy constraints’ message.

BTW, Happy Birthday to Phil “Scrap Iron” Garner, who was an infielder for the Pittsburgh Pirates in the late 70’s and early 80’s.

Windows 8.1 Update 1 error 80073712

It can be very frustrating when you end up searching for help with a Windows Update issue. There are so many moving parts on a Windows system that it is next to impossible to track everything reliably.

While trying to put the Windows 8.1 Update 1 on my Windows 8 virtual machine inside of Parallels Desktop on my iMac, I was getting error 80073712 in the update settings control panel. There is no shortage of materials to look at if you search for that particular error code, the tricky part is finding which one will help solve the particular problem with my installation.

I was finally able to find this procedure, and it did the job as I am now running Windows 8.1 Update 1. I will abbreviate it here, for the full source material click on the link below the list:

  • Get an administrator command prompt
  • Enter this command (I am running the 64 bit version, you will need a different command to work with 32-bit or Win 8 RT, see the link for more information):
    dism /online /remove-package /packagename:Package_for_KB2919355~31bf3856ad364e35~amd64~~6.3.1.14
  • Enter this command:
    DISM.exe /Online /Cleanup-image /Restorehealth
  • Enter this command:
    dism /online /cleanup-image /startcomponentcleanup
  • Exit the command prompt and attempt to run the update again

Even though the 2nd command above gave me an error, I went through the whole procedure, and it worked correctly. Here is the link to the forum posting on Microsoft’s web site with the full message:

Windows 8.1 Update 1 Failing to Install with errors 80070020, 80073712 and 0x800f081f

BTW, a posthumous Happy Birthday to Bruno Kirby, who played the limo driver in This Is Spinal Tap.

NSString to UIImage

I had the need to take a regular old NSString and get a UIImage representation of that text. It seems like a relatively straightforward thing to do, so here is the code that I put together:

+ (UIImage *)imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
 
+ (UIImage *)imageWithString:(NSString *)theString font:(UIFont *)theFont color:(UIColor *)theColor
{
    UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    tempLabel.backgroundColor = [UIColor clearColor];
    tempLabel.textColor = theColor;
    tempLabel.font = theFont;
    tempLabel.text = theString;
    [tempLabel sizeToFit];
 
    return [self imageWithView:tempLabel];
}

As an added bonus, if you happen to be using Font Awesome in your iOS project (and let’s be honest, if you aren’t, you should be), here is a bonus method:

+ (UIImage *)imageWithFontAwesomeIcon:(NSString *)faIcon fontSize:(CGFloat)fontSize color:(UIColor *)fontColor
{
    return [self imageWithString:[NSString fontAwesomeIconStringForIconIdentifier:faIcon]
                            font:[UIFont fontWithName:kFontAwesomeFamilyName size:fontSize]
                           color:fontColor];
}

BTW, Happy Birthday to Brian Setzer, who is a fantastic guitar player and singer.