Off Topic: Finally Hit 500 on Deadlift

Yeah I know, kind of lame to announce this on a programming blog, but this is a huge thing for me. I’ve come close to 500 quite a few times but there was always something that set me back. It isn’t the best lift ever, but still happy with it overall as I didn’t cheat the pull in any way. And as making claims without proof on the internet is pretty common, I figured I’d post the video.

Looking to set a new personal record on the bench at 330 this week. 325 is something that I’ve done on a few occasions, but like I said, something always came up.

WARNING: Sound is probably bad unless you want to hear a nerd war cry at the end… That and apparently I swore at the end too.

Pycharm: Change Error Alert Color/Style

Once again I’m using my blog to help remind myself of something later, but you know what? I’m OK with that.

Took a little bit to find this one, but changing the color of Errors and Warnings makes it hell of lot easier to find them. Go figure that the default “barely more grey than white” color doesn’t do the same.

Anyways:

File -> Settings -> IDE Settings -> Colors & Fonts -gt; General

At that point you’ll see stuff to the left with a bunch of colors. (Default Text) Just click on either Error or Warning to change them. After you’ve done that, feel free to go back to your project and find all the errors you couldn’t see before. It’s OK that you have errors though. Awesome as I am, even I make mistakes. Haha just kidding. Be ashamed of yourself.

Mock SQLAlchemy scoped_session query and Why Python is My BFF

sqlAlchemy has sessionmaker to create a session from which you can use query to get whatever you need. For example:

someSession.query(SomeTableRepresentationObject).filter...ect

If you’ve used sqlalchemy, nothing new going on here but it wouldn’t be me if I didn’t point out the obvious and take three sentences to do so.

Now what you may run into is something like this:

def getCountOfUsersByUserName(userName, session):
  return session.query(User).filter(User.userName == userName).count()

Ok now that I typed that out, I see it’s kind of a dumb method. But f–k it, what’s done is done.

Now from a testing situation, this could look tough. After all if you come from a more static language background like I did, you should know how hard things can be to mock at times. (.Net Session… I’m looking at you with judging eyes. Sooooo judging.) But this isn’t a static language, it’s Python.

For purposes of making things less confusing, which is hard for me, when I use the word “Object” I mean method OR class. And remember as always, “banana” is the safe word.

You see, to mock that out all you need is an object that has a query object that takes in something and a filter object on the query object that takes in something and has a count method on it. Yeah that totally makes sense. Try working it backward.

Filter has one parameter and a count method on it. Whatever that parameter is, it doesn’t matter since it is Python. As long as Filter takes in one parameter, you have a winner.

Query, like Filter, takes in one parameter and has a object named Filter on it. Once again, it doesn’t matter what’s passed into Query, just that it takes something in.

Session is basically an object that has no parameters and has a Query object on it.

Now in a static language, this would be annoying. You would need 3 interfaces and mock a whole ton of stuff dynamically with something like Rhino Mocks or just create a bunch of classes of those interfaces that you can pass in. Either way, there are complications. Once you get into things like Web Session or ViewState, it’s a ton of work. Python? Eh, you can do it in 20ish lines. How you ask? Well I’ll show you how!

	class mockFilter(object): #This is the ONE parameter constructor
		def __init__(self):
			self._count = 0
			self._first = dynamicObject()

		def first(self):  #This is the another method that's just coming along for the ride.
			return self._first

		def count(self):  #This is the needed Count method
			return self._count

	class mockQuery(object): #This is the ONE parameter constructor
		def __init__(self):
			self._filter = mockFilter()

		def filter(self, placeHolder): #This is used to mimic the query.filter() call
			return self._filter 

	class mockSession(object):
		def __init__(self):
			self._query = mockQuery()
			self.dirty = []

		def flush(self):
			pass

		def query(self, placeHolder):  #This is used to mimic the session.query call
			return self._query

  #and this... THIS IS SPARTA!!1111... yeah I know, I'm about 3 years too late on that joke.

How does this work? Say I have the method from above:

def getCountOfUsersByUserName(userName, session):
  return session.query(User).filter(User.userName == userName).count()

I could test it using this:

  session = mockSession()
  session.query('').filter('')._count = 0 #Initialize the mock session so it returns 0 from count()

  getCountOfUsersByUserName('sadas', session)

And boom, you have mocking in ten minutes or less or your code is free.

As you can see, the highly dynamic nature of Python makes it a great fit for any project that will need unit tests and mocking. And which project doesn’t? You know what I’m sayin’? You now what I’m saying’? High five!

Note: dynamicObject is …. nothing but a cheesy class that inherits Object but has nothing on it. (Turns out that if I did someObject = Object() I couldn’t do this since Object by default doesn’t contain the ability to add things dynamically… and this was by design.)

And yes, I just quoted myself. I am that awesome.

jQuery Validation with Multiple Checkboxes

So this one is done on request and because I am a kind of merciful god I will grant this request.

For those bullet point programmers:

Now when I say validation, I mean the validation plugin. and this example is built using concepts in this post.

Here’s the markup:

 
<form id="formCheckBoxValidation" method="post" action="checkboxValidation.html">
	<input type="checkbox" id="checkBoxList" name="checkBoxList" value="One">
	<input type="checkbox" id="checkBoxList" name="checkBoxList" value="Two">
	<input type="checkbox" id="checkBoxList" name="checkBoxList" value="Three">
	<input type="checkbox" id="checkBoxList" name="checkBoxList" value="Four">
	<input type="checkbox" id="checkBoxList" name="checkBoxList" value="Five">
	<br />
	<input type="submit" id="buttonCheckBoxValidation">
</form>
<div>
	<div id="divError" name="divError" style="display:none;"></div>
</div>

<form id="formCheckBoxValidationDifferentName" method="post" action="checkboxValidation.html">
	<input type="checkbox" id="checkBoxListOne" name="checkBoxListOne" value="One">
	<input type="checkbox" id="checkBoxListTwo" name="checkBoxListTwo" value="Two">
	<input type="checkbox" id="checkBoxListThree" name="checkBoxListThree" value="Three">
	<br />
	<input type="submit" id="buttonCheckBoxValidationDifferentName">
</form>
<div>
	<div id="divErrorDifferentName" name="divErrorDifferentName" style="display:none;"></div>
</div>

For this example I’m actually presenting two examples(Say ‘example’ again, I dare you, I double dare you m—erf—er, say ‘example’ one more God d–n time!): If the checkboxes are linked by id and if the checkboxes are not linked at all. There is actually a difference. You see, if they share the same id, the required method can be used since it will treat them all as the same element and therefore if even on is checked, there is a value. Otherwise, you have to check all the checkboxes to see if at least one is checked. (Yeah, that made total sense.)

Here’s the check checkboxes method:

//Add a method to the validator that checks to see if at least one of the
//  three checkboxes specified are checked.
jQuery.validator.addMethod(‘atLeastOneChecked’, function(value, element) {
	var checkedCount = 0;

	if (jQuery(‘#checkBoxListOne’).is(‘:checked’)){
		checkedCount += 1;
	}

	if (jQuery(‘#checkBoxListTwo’).is(‘:checked’)){
		checkedCount += 1;
	}

	if (jQuery(‘#checkBoxListThree’).is(‘:checked’)){
		checkedCount += 1;
	}

	return checkedCount > 0;
});

Oooooh baby.

Now for setting up the validation:

//This is for the first checkbox area where every checkbox has the same id causing them
//  to be a group and therefore the default required works.
var validationRules = new Object();
validationRules['checkBoxList'] = {required:true};

var validationMessages = new Object();
validationMessages['checkBoxList'] = {required:'at least one has be checked.'};

jQuery('#formCheckBoxValidation').validate({
	errorLabelContainer: '#divError',
	wrapper: 'div',
	rules: validationRules,
	messages: validationMessages,
	onfocusout: false,
	onkeyup: false,
	submitHandler: function (label) {
		alert('hooray');
	}
});

//This is for the second checkbox area where every checkbox has a different name
//  and therefore the atLeastOneChecked method must be used.
validationRules = new Object();
validationRules['checkBoxListOne'] = {atLeastOneChecked:true};

validationMessages = new Object();
validationMessages['checkBoxListOne'] = {atLeastOneChecked:'at least one has be checked.'};

jQuery('#formCheckBoxValidationDifferentName').validate({
	errorLabelContainer: '#divErrorDifferentName',
	wrapper: 'div',
	rules: validationRules,
	messages: validationMessages,
	onfocusout: false,
	onkeyup: false,
	submitHandler: function (label) {
		alert('hooray');
	}
});

In the words of Q-Bert: @#$% yeah!

SqlAlchemy: Self Referential Many To Many

Ok this was just plain annoying to figure out. A couple of misteps and a few F—! later I finally got it. So the situation is this:

You have a table for user to ignore users. So it’s basically a many to many where both sides of the relationship are the user table. The creation might look like this:

class User(Base):
    __tablename__ = "User"
    id = Column(String(36), primary_key=True, default=lambda : str(uuid1()))

Basically a table named User and it has a primary key. Yee haw. Now for the hanging table:

class UserIgnore(Base):
    __tablename__ = "UserIgnore"
    id = Column(String(36), primary_key=True, default=lambda : str(uuid1()))

    ignored_by_id = Column("ignored_by_id", String(36), ForeignKey("User.id"))
    ignored_by = relationship("User", backref="ignored_list",  primaryjoin=(User.id == ignored_by_id))
    ignored_id = Column("ignored_id", String(36), ForeignKey("User.id"))
    ignored = relationship("User", backref="ignored_by_list",  primaryjoin=(User.id == ignored_id))

Basically you need a table/object with two columns: ignored_by_id (The one doing the ignoring) and ignored_id (The one being ignored). And at this point the word “ignored” should look like it’s not even a word anymore because I’ve typed it too much already.

Now the relationship is made using two different properties:

    ...
    ignored_by = relationship("User", backref="ignored_list",  primaryjoin=(User.id == ignored_by_id))
    ...
    ignored = relationship("User", backref="ignored_by_list",  primaryjoin=(User.id == ignored_id))

As you can see, I had to hit it from both angles. (I’d hit it! LOLOLOLHARHARORAALROARH) Not only how to describe the relationship from ignorer to ignoree (Those are words now) but also in reverse. That way I can have a constructor like this:

    def __init__(self, user, userToIgnore):
        self.ignored_by = user
        self.ignored = userToIgnore

And also if I do something like this:

    UserIgnore(_user, _user2)
    UserIgnore(_user2, _user)

I can have it all save correctly just by adding _user to the session or saving _user id at some point.

Also both those lists will be added to the User object without having to do anything further.

someUser.ignored_list

or

someUser.ignored_by_list

Yay for that.

Talent Versus Persistence

Let me tell you about my one time mentor Dan, and no Dan isn’t a fictional character to make a point. Dan (Cousineau) is a multi time NASKA national champion, quite a few gold medals in world competition, not to mention an accomplished BJJ practitioner. I had the pleasure of being one of his students for many years and being able to compete for the Dragon Karate Team.

Now with that out of the way, I’ll attempt to get to a point.

For the most part, when I was competing (post 1996) the prototypical national champion for weapons (Or forms for that matter) was somewhere between 5-6 to 5-10 and 150 to a buck seventy. As forms became more “flashy”, it was very helpful to be light and compact. (Examples like Jon Valera or Mike Chatr.. Chatura… Chat and later on Steve Terada and the legendary Kim Do) Then there was Dan. Dan was 6’1″ and (sorry Dan ) 240ish. He was about as far from prototypical that one could get… and he still won constantly.

I think the word “talent” gets thrown around a lot without people really knowing what it means. In my ten or so years of competition, I saw a lot of “talent”. There were people that were just plain gifted. It came so easy to them that it was just like breathing, but they weren’t the best. They weren’t the ones taking home National Championships. Why? Because they weren’t persistent.

Dan wasn’t a champion because he was gifted. I’m not sure anyone ever said he was “talented”. Excellent? Yes. Elite? For sure. But “talented”? That’s just an insult. Wait… what? Insult?

You see, I think when people say “talented” what they actually mean is “lucky” or “just born with it”. I think it’s used almost as an excuse by people that don’t want to work for anything. There was nothing “talented” about Dan. He was a hard worker. He was the guy that ran a school, worked another job, and still managed to practice with any free time he had. (Even outside before work) He was the guy that would be training on Saturday and Sunday mornings. (In fact one thing he used to say when we trained on Sunday mornings was “Everyone else you’re competing against is sleeping right now.”) It wasn’t something he was given by some god or genetics. It was pure time, work, and persistence. He never stopped, he never gave up, and he never took it easy. He lived by the mantra of “Second place is first loser.” To call him “talented” is to ignore the countless hours he gave to his training. The weekends of traveling to anywhere from California to Germany. The overwhelming drive it took to keep competing. That is what made Dan elite. That is what made people like John Valera and Steve Terada champions. They were the ones that pushed on where most would fold. In the world of the elite, there are only the persistent. The gifted ones were left far behind.

Now the question you might have right now is: Is this going somewhere? And yes I say. Yes it is.

I think the “talented” frame of mind is too prevalent in world of programming. I think most programmers are too comfortable to just slap “talented” on anyone who excels at programming. Now it’s true, some people are just smarter than others. For every Dan Cousineau in the world, there are five others that fit the prototypical programming mold. However, I’m willing to bet most truly great programmers, “gifted” or not, live to program. They spend a lot of time outside of work programming. When other people are out getting drunk, they are perfecting their craft. They are the ones that push past the fear that most have when moving into new territory and just do it. They persist. They don’t give up. They don’t make excuses. They do.

If you want to be a truly great programmer, or hell even slightly better than average like me, you have to do. You can’t sit around in a pity party going on about how someone else has it better. You can’t make excuses for why other people are excelling. You can’t just blindly slap the “talented” word on someone and console yourself when you see that person getting out of your reach.

Or you can. But just remember that out there, somewhere, there’s a Dan Cousineau busting his a– while you sit around wading in your tears.

The choice is yours.