Not Dead …

Just wanted to make note that if you do come across my blog here that it would appear that it is dead. That’s not quite true, it is merely mostly dead. I enjoy sharing what I’ve learned and I think in the coming months I will have much more interesting things to write about. I look forward to getting back on the horse and furthering a flow of information.

Let’s Update Phonecalls

Now, this will just be a short post as it is really just an idea I had but I think that’s it’s time for Generation 2.0 of phone calls.

It occurred to me during our daily scrum call this morning that more and more we have to listen to useless information as we try to make phone calls. Now, companies have been trying to reduce how much you have to sit there and wait for your options but in most cases you have to wait till you hear the option that you need or until it lets you make a selection. It certainly makes phone calls a giant pain and I’m sure I’m stating the obvious here. So let’s rework how phones interact with each other.

We are really at the start of a phone call revolution with services like Google voice and Skype really taking voice data and transferring it to phone lines, but what if we did a bit of the reverse. The time has come where phones (home, cell, business, etc.) all have screens on them for showing some sort of information. What if we could start a phone call with a data transmission which would be interpreted by the phone to display a list of options / key commands that are available to the user right off the bat. Phone lines have been transmitting data for a long time that sending such a small amount of information would be quick and painless and it would merely have to be the phone would have to interpret such information.

Imagine it, you call up Verizon service on your desk phone or smart phone and instead of hear “Thank you for calling verizon, please listen closely as our options might have changed. Press 1. To do something, Press 2 to do something else. Press 7 if none of the above, press 9 to hear these options again” You could could call them up and hear “Thank you for calling Verizon, please review the options on your phone or press * to hear them aloud” and you look at your phone to see what is available to you. Simple, elegant, glorious.

Google Voice would wind up being infinitely more useable since I know they have all these I can press to do different things but I don’t know what they are. Dialing in to conference calls would be simple and straight forward and we wind up minimizing the amount of junk voice messages we have to hear when doing anything over the phone.

Now, I’m sure this isn’t as simple as I’m making things out to be. There would certainly have to be infrastructure changes and phones would start needing to actually be able to process this new information, perhaps even requiring a call back so that phones that don’t accept it will automatically have things read aloud, but I think there’s potential there and would make life a little easier.

Follow up – Java Musings

So, I haven’t written anything for a long time and that’s an unfortunate situation so I decided to sit down and get something written. One of the items that I’ve had in mind for a bit is a follow up to a post I did back in February regarding something I was wishing for in the java language. My original post was a bit more robust but in the end all I really wanted was to stop having to create general getters and setters for every field in every class. The amount of boiler plate for common stuff was just getting on my nerves.

I was quite pleased, and honestly a bit surprised, when I started working with objective-c and found the property mechanic. For those that aren’t aware, objective-c provides the ability to declare a property for a class within its declaration:@property (attributes) Type name;

And then within the implementation you just need to do: @synthesize name;

This will tell the compiler to automatically generate a getter and a setter (unless read only) without all the unnecessary cruft of the manual implementations. How wonderful is that? It is concise, easy to read, allows basic customization via the attributes, and still gives you the ability to override method creation as necessary.

I know it doesn’t really mean anything but I still say it would go great with Java if they could implement it.

[iOS] Building a Reusable Number Picker

It’s been a while since I made a post. Back around memorial day weekend I was about to start on my first ever iOS project, never having worked on Objective-C on have been wanting to do a post of some of the interesting bits of working with it for the first time. Unfortunately, this is not that post.

Instead, I’m going to discuss a little spark of ingenuity that came to me while I was refactoring the source code I was working on. The code had several times where it needed to create a picker to build a number using several rollers. One of the problems with just extracting out the common code was that there were several different pickers with n columns, decimals, or different limits to accomodate.

I find it somewhat strange that the Cocoa libraries don’t already provide a number picker implementation when they do provide one for dates. Oh well, that’s where this comes in. Before I begin going into actual code I do have to indicate that I haven’t quite extracted this out into a class where everyone can take advantage but when I get to that I will update this post with a link to the inevitable github repo. I also haven’t gotten to refining the class yet so there will certainly be some updates needing to be made, so bear with me (and feel free to comment with improvements and I’ll make sure to get them in now, or you can wait till the repo exists and make some pull requests).

To start, here’s our header file to indicate our public interface.

#import "AbstractPickerViewController.h"

@interface AbstractNumberPickerViewController:AbstractPickerViewController

@property (strong, nonatomic, readonly) NSNumber *maxValue;

@property (strong, nonatomic, readonly) NSArray *columnValues;

@property (strong, nonatomic, readonly) NSArray *labels;

- (id) init:(NSNumber *)maxValue;

- (id) initWithLabels:(NSNumber *)maxValue labels:(NSArray *)labels;

- (NSArray *) split:(NSNumber *)val;

- (NSArray *) splitAndPad:(NSNumber *)val;

- (NSNumber *) getValue;

- (NSString *) getSelectedLabel;

- (NSInteger) getLabelColumnNum;

- (void) setPickerToCurrentValue:(NSNumber *)val;

- (void) setPickerToCurrentValue:(NSNumber *)val label:(NSString *)label;
@end

To begin with we have our class declaration and we see that we are also extending an AbstractPickerViewController. This class is actually just a utility base class that provides some capabilities for viewing the picker in a popover for iPads or an action sheet for iPhones. I wouldn’t worry about this right now though as it is purely for viewing capabilities.

Next we have the fields of the class, all read only as the are for gathering information after creation, not modifying them. After those, we have our initializers. Obviously the easiest way to initialize a picker for numbers is with a number so we have 2 init methods, one that takes just the number of the max (currently this just sets it to the highest digit and as many 9s as necessary to allow for numbers leading up to there, so for 5000 it would be 5999) and another that takes the max number as well as a list of labels. The labels are useful for different situations like if you wanted to do file sizes (kb, mb, gb, etc.) or a # of animals or whatever.

Finally we have our public messages. Now, some of these are merely exposed so that I could create test cases, I suppose I could leave them as undefined in the header and use @selectors to execute them in my tests so perhaps I’ll do that when I refactor. Ideally the 4 messages that should be exposed are the last 4, getValue, getSelectedLabel, and the 2 setPickerToCurrentValue messages. We will take a look at all of these things now.


#pragma mark - initializers

- (id) init:(NSNumber *)maxValue {
  self = [self init];
  decimalColumn = -1;
  NSArray *digits = [self split:maxValue];

  _columnValues = [[NSMutableArray alloc] init];
  for (int i = 0; i <; [digits count]; i++) {
    int max = 9;
    int colVal = [(NSNumber *)[digits objectAtIndex:i] intValue];
    if (i == 0) {
      max = colVal;
    }

    NSMutableArray *column = [[NSMutableArray alloc] init];
    for (int j = 0; j <;= max; j++) {
      [column addObject:[NSNumber numberWithInt:j]];
    }
    [_columnValues addObject:column];
  }
  return self;
}

- (NSArray *) split:(NSNumber *)val {
  _maxValue = val;
  if (val &amp;&amp; [val intValue] >;= 0) {
    NSString *stringVal = [self getNumberString:val];
    return [self splitStringToArray:stringVal];
  }
  return nil;
}

- (NSArray *) splitStringToArray:(NSString *)stringVal {
  NSMutableArray *splitVal = [[NSMutableArray alloc] init];

  for (int i = 0; i <; [stringVal length]; i++) {
    unichar num = [stringVal characterAtIndex:i];

    NSString *numStr = [NSString stringWithFormat:@&quot;%c&quot;, num];
    NSLog(@&quot;Parsed digit %@&quot;, numStr);
    if ([numStr isEqualToString:@&quot;.&quot;]) {
      if (decimalColumn == -1) {
         decimalColumn = i;
      }
      num = [stringVal characterAtIndex:++i];
      numStr = [NSString stringWithFormat:@&quot;%c&quot;, num];
    }
    [splitVal addObject:[NSNumber numberWithInt:[numStr intValue]]];
  }
  return splitVal;
}

- (NSString *) getNumberString:(NSNumber *)val {
  NSString *stringVal = [val stringValue];
  if ([stringVal hasPrefix:@&quot;0.&quot;]) {
    stringVal = [stringVal stringByReplacingOccurrencesOfString:@&quot;0.&quot; withString:@&quot;.&quot;];
  }
  return stringVal;
}

- (id) initWithLabels:(NSNumber *)maxValue labels:(NSArray *)labels {
  self = [self init:maxValue];
  _labels = labels;
  [_columnValues addObject:labels];
  return self;
}

Here we have our initializers, nothing much interesting about the one with labels but the really interesting pieces here lie within the init with the max number so let’s take a moment to step through what’s going on here. So first we have:

decimalColumn = -1;
NSArray *digits = [self split:maxValue];

First we have the decimalColumn reset to -1 to make sure there is a value as well as it being invalid. Next we split the max number provided into an appropriate number of columns (i.e 123 becomes [1,2,3])

We set the decimalColumn to -1 to make sure that it has been reset and then we split the provided number into an array of values instead (i.e. 123 becomes ['1','2','3]). We do this by looping converting the number to a string and stripping out a leading 0 if the number provided was a float <; 0 and then taking that string and looping through each character and putting it’s numeric value into the return array. If we encounter a decimal point we skip over it and note where we found it in the decimalColumn variable. After we have the split number value we then want to set up the values that each column will provide the user to pick from. This is done by first indicating what the maximum value the first column should be and for each expected column to enter a value from 0 – max (9 in most cases). Additionally, note that we have the capabilities in there to provide for adding commas to necessary positions as well as the decimal point in the correct column. Next we have the functional portions for getting our selections:


#pragma mark - instance methods

- (NSNumber *) getValue {
  NSString *pickerNum = [self getPickerNumberAsString];
  return [NSNumber numberWithFloat:[pickerNum floatValue]];
}

- (NSString *) getPickerNumberAsString {
  NSMutableString *val = [NSMutableString stringWithString:@""];
  int columns = [self getNumberColumnCount];

  for (int i = 0; i <; columns; i++) {
    if (i == decimalColumn) {
      [val appendFormat:@".%d", [self.pickerView selectedRowInComponent:i]];
    } else {
      [val appendFormat:@"%d", [self.pickerView selectedRowInComponent:i]];
    }
  }
  return val;
}

- (NSString *) getSelectedLabel {
  NSString *labelVal = @"";
  if (_labels != nil) {
    labelVal = [_labels objectAtIndex:[self.pickerView
    selectedRowInComponent:
    ([_columnValues count] - 1)]];
  }
  return labelVal;
}

- (NSInteger) getNumberColumnCount {
  int columns = [_columnValues count];
  if (_labels != nil) {
    columns--;
  }
  return columns;
}

Here we have our simple methods for actually getting our selected values. Our getValue method just loops through our columns and appends each digit to a string and returns an NSNumber object that was created from the string value’s floatValue method. Nothing much special going on here. Let me know if anything is confusing here.

Finally we have the following set current value methods.

- (void) setPickerToCurrentValue:(NSNumber *)val {
  NSArray *splitVal = [self splitAndPad:val];
  int diff = [self getNumberColumnCount] - [splitVal count];
  NSLog(@"Setting %d column out of a possible %d, difference of %d",
   [splitVal count], [self getNumberColumnCount], diff);

  for (int i = 0; i <; [self getNumberColumnCount]; i++) {
    if (i <; diff) {
      [self.pickerView selectRow:0 inComponent:i animated:NO];
      NSLog(@"row selection 0");
    } else {
      int row = [(NSNumber *)[splitVal objectAtIndex:(i-diff)] intValue];
      NSLog(@"row selection %d", row);
      [self.pickerView selectRow:row inComponent:i animated:NO];
    }
  }
}

- (NSArray *) splitAndPad:(NSNumber *)val {
  NSMutableArray *splitVal = [[self split:val] mutableCopy];
  int countNumberCols = [self getNumberColumnCount];
  if ([splitVal count] <; countNumberCols) {
    int numFloatPrecision = 0;
    int stringLength = countNumberCols;
    if (decimalColumn >;= 0) {
      stringLength++;
      numFloatPrecision = countNumberCols - decimalColumn;
    }

    NSString *formatted = [NSString stringWithFormat:@"%0*.*f",
     stringLength, numFloatPrecision,
     [val floatValue]];
    NSLog(@"Front: %d Back: %d", stringLength, numFloatPrecision);
    NSLog(@"Did we format correctly? %@", formatted);
    return [self splitStringToArray:formatted];
  }
  return splitVal;
}

- (void) setPickerToCurrentValue:(NSNumber *)val label:(NSString *)label {
  [self setPickerToCurrentValue:val];
  for (int i = 0; i <; [_labels count]; i++) {
    NSString *labelVal = [_labels objectAtIndex:i];
    if ([labelVal isEqualToString:label]) {
      [self.pickerView selectRow:i
                     inComponent:([_columnValues count] - 1)
                        animated:NO];
    }
  }
}

Now, here we have the most interesting bit that needed to be considered in developing this, basically when I have, say 5 columns but the selected value is only 3 digits, how do I compensate for those missing digits? Even more so, how can I handle floats if I have 2 float digits and I pass in 2 digits, or 1.1 when there is NN.NN total format? This was an interesting problem to solve (and it’s not quite there yet since I don’t do floating point rounds so 1.234 can properly set NN.NN) but I think the solution that was added is pretty nifty.

The setPickerToCurrentValue:(NSNumber*) interface seems to have remnants of my previous attempt so I will have to clean those up but the main item to look at is the splitAndPad method. We start this by determining the length of the input number string as well as the length of the floating points. We can then use those values to utilize the string formatting to pad the end of the string with as many 0s are necessary as well as padding the front of the string so that we will end up with a numeric string with the exact length of maximum length. We can then split this string up into the column values we will set and we use that array to set our column values.

I’ve left out other methods, such as those of the picker delegate, but I feel like if you want to take this implementation and use it before I get my repo set up you can easily implement those for yourself. I hope that this will be helpful for some folks and I will do my best to get that repository up with a valid implementation. I look forward to others helping make this even better for the future.

Just as a note [Titanium]

Just want to make this known to anyone starting up with Titanium since I ran into some issues that I initially attributed to my timely upgrade to OSX Lion.

In my lab work through the TCAD certification training I wound up with an application that suddenly wouldn’t work on Android which I could have sworn was working prior. Unfortunately, my commit habits were not as often as they perhaps should have been and I couldn’t just roll back to find out the exact cause. However, when I did do some roll backs I found the problem I was looking for, but it was nothing like what I expected. Apparently there is an inconsistency in the Titanium APIs which makes it so there are 2 separate application level addEventListener() methods, one in the Ti.API namespace and one in the Ti.App namespace. Supposedly these methods do not function any differently, but there is one fatal difference in that apparently the one in the Ti.API package does not work with Android (at least the V8 engine)

So just remember, don’t use Ti.API.addEventListener() in your application unless you’re never planning on making it cross platform, use Ti.App.addEventListener() instead.

Note that this extends to the fireEvent method as well.

Having a Work Diary

“A diary you say? Why that’s for sissy’s and little girls…”

I don’t know why you would say that but a diary is a great way of keeping a record of your thoughts and feelings over time. You could rename it and just call it a “Journal”, if that makes you feel better, but it winds up being the same thing. Either way, I have recently started doing this at work and I believe that it will prove to be an invaluable tool.

My tool of choice thus far has been Evernote as it provides effortless creation of new notes, organization and tagging, and syncing between where ever I feel like writing (computer, phone, ipad, web), though the Mac / iOS clients leave some easy access formatting to be desired. It is simple for me to just open it up and create a new note with a title and tags as necessary. After I’m finished I can also easily search through all of my notes to try to locate specific notes. I can also upload documents and pictures and whatnot that might be useful for me to remember situations and record notes right along with the items. It’s a great tool but it’s not for everyone and you can easily just pop open Notepad, Google Docs, Microsoft OneNote or whatever if you’d like.

Now, the way I find myself doing things is to type as if I am speaking, much like I do here on the blog though even more informal. It’s easiest to feel like you are trying to explain to someone else whatever it is that you are noting down because it will likely be yourself who you are explaining things to and you can easily translate your own words into instructions later if need be. This will help you have a record of your thoughts as you were going through your work and can be just one more step in replicating a problem, solution or experiment that you’ve been working with. For example, the reason I started doing this recently was because I had a task to complete an implementation on something that had been prototyped beforehand but there was no documentation on the setup, the technologies used, or the work performed. As I worked through the setup I tried to make sure I took notes to myself so that I could replicate every step along the way, as well as avoid problems I encountered, and eventually transform those into instructions for someone else to do the same. Additionally, as I work I can go back through my notes and update them with formatting changes or other indicators and add new notes to answer questions or denote false logic that you’ve come across later.

The ability to read through your notes and see what you thought before and the outcomes of learning more information can be invaluable to keep up to date and re-follow your train of thought so that you don’t fall into the same traps over and over again. How many times have you read through something and thought to yourself “Shouldn’t that be X” or “How can that be …” only to realize the answer but forget it the next time you come across it? It can’t just be me, but being able to answer your own question right there is a wonderful tool.

Side Note: If you happen to be studying, Evernote has an Application Evernote Peek which is meant to work on an iPad in conjunction with a smart cover to give you note card-eque capabilities to your Evernote notes. I haven’t actually used it myself, just thought it was relevant.

Additionally, one of the nice features of, at the very least, Evernote is the ability to add check boxes directly into your notes so if you are going through writing notes and you are making note of the different things that still need to be accomplished you can easily just plop a check box right into your text and you’ll know by looking at it that there is something you need to do. I tend to translate these tasks into items in my Omnifocus todo list and create a link back to my Evernote note so that I could easily get back to my information as necessary.

So now that you’ve got my thoughts on the matter, go ahead and start your own work diary and I’m sure you’ll enjoy not stepping on your own toes (metaphorically) all the time.

Wrapping functions to Add Aspects [JavaScript]

I have been recently working through all of the training videos and the associated labs for trying to get my TCAD certification (which I got last night thanks to some free takes associated with the Titanium 2.0 release) and figured that one of the little things I had done in my local data lab was a pretty nice way of doing things so I decided to share.

Most languages have ways of being able to execute common code or setting things up, with Java you’ve got Aspects or Injection, but the problem is that you’ve got to add additional technologies to your stack to make things work. One of the nice things about JavaScript is that the language is so flexible  and amazingly robust right out of the box. I’m going to talk right now about the ability to wrap functions.

Now, in the lab I mentioned the main task you need to implement operations against a SQLite database, which you want to make sure you aren’t leaving open connections so you want to open and close the database connections every time. Now, I could just add those 2 lines to every function, it’s not like it’s much, but I’d rather not. So I created the following:

function getDatabaseFunction(callFunction) {
    return function(fugitive) {
        db = Ti.Database.open('TiBountyHunter');
        db.execute('CREATE TABLE IF NOT EXISTS fugitives(id INTEGER PRIMARY KEY, name TEXT, captured INTEGER, url TEXT, capturedLat REAL, capturedLong REAL);');

        var returnVal = callFunction(fugitive);
        db.close();
        return returnVal;
    }
}

Basically, what I’m doing here is defining a function that takes in another function, it will open the database (which is being assigned to a module level variable), make sure the table we are looking for exists (the only table in the application at this time) and then calls the passed in function. Upon return it will close the database and return what was returned by the other function. Very simple, very clean. An example usage is as follows:

exports.addFugitive = getDatabaseFunction(function(fugitiveName) {
    db.execute('INSERT INTO fugitives (name, captured) VALUES (?,?)', fugitiveName, false);
    Ti.API.fireEvent("uncaughtFugitivesChanged");
});

Here all we see is that we run our command to insert the fugitive into the system is merely the sql statement to do the task (and a logging statement). Easy as pie and everything is open and closed as necessary. We create the function as the parameter into the other function and we get back a function that has been wrapped to automatically open and close the db. Pretty nice huh?

Now, As you can note my function returned above has the 1 parameter defined instead of allowing to take in whatever and pass that along to the function parameter. This is more just laziness on my part since this was a lab I wasn’t interested in looking up that syntax since I haven’t had the pleasure of using it myself as of yet. However this is perfectly possible with JavaScript. Also, when I have more than 1 table to worry about that that table creation statement will get moved elsewhere.

I don’t know if this is really a “best practice” but personally I think it’s mighty nifty and saves on reused code. If you’re interested, I’ve got my lab exercise code on git hub and the full DAO can be found Here. Of course also note that this is a work in progress and lab exercises. I’m doing my best to practice good practices but learning on my own leaves some things to be desired.