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.




Yay for that.

HTML Thing… Label versus Div or Span When it Comes to Inputs

One of the things that PyCharm tells me over and over again when it comes to HTML and Inputs is that I’m just not using those ——- — labels you —- ——- excuse for a ——- programmer. (Ok, so I might be paraphrasing a bit) Now for the most part it isn’t the end of days if you use a span or div instead. No kittens will be harmed either way. However, and I admit I must be slow for not seeing this, but labels do have one advantage as told by the dub see three:

The label element does not render as anything special for the user. However, it provides a usability improvement for mouse users, because if the user clicks on the text within the label element, it toggles the control.

Quite simple put, if the user clicks the label or the input, it will put focus on the input. Yeah so not earth shattering but for people with stupid hands like me, it just gives me a better chance of actually clicking a textbox than the massive Evony Online ad right next to it.

jQuery Validator: Build Rules and Messages Dynamically

Ok so here’s your typical code for the jQuery Validator:

    errorLabelContainer: ELEMENT_ERROR_DIV,
    wrapper: 'div',
    rules: {
      textboxEmailAddress: {
        required: true,
        email: true
    messages: {
      textboxEmailAddress: {

As you can see, the elements like “textboxEmailAddress” are hard coded in there which means if that name changes in the markup, this breaks. So the question is: How do I script the rules and messages so that I don’t have to hard code the element names?

Sorry was just waiting for you to finish you question. Ok, here’s the answer and it has to do with how great Javascript is as a language. (And oddly enough a trick I got from Python)

  var validationRules = new Object();
  validationRules[ELEMENT_TEXTBOX_EMAIL] = {required:true};

  var validationMessages = new Object();
  validationMessages[ELEMENT_TEXTBOX_EMAIL] = {required:ERROR_EMAIL_REQUIRED};

            errorLabelContainer: ELEMENT_ERROR_DIV,
            wrapper: 'div',
            rules: validationRules,
            messages: validationMessages,

Where ELEMENT_TEXTBOX_EMAIL is a constant somewhere. How does this work? Well because the way dynamic languages like Javascript and Python work, objects can be treated like dictionaries which means you can add properties to them the way you would add a record to a dictionary:

  someObject['somePropertyName'] = 'hi';

is just like:

  someObject.somePropertyName = 'hi';

In fact I’m pretty sure the new Dynamic keyword in C# works in the same manor.

Now you could be a annoying and point out that replacing textboxEmailAddress with ELEMENT_TEXTBOX_EMAIL is still hard coding, and I would agree… to a point. The constant does two things:

1) Removes a “magic string” from your code.

2) Makes it really easy to update that string if the element name/id is changed in the HTML. Having only to look at one place to replace is a lot easier than 1+ places.

So there, smarty pants. What you gots to say now?

Simple Property Merge for Python Objects

Not sure if this is useful to other people, but then again if I cared that would make me human.

So here’s a quick way to merge two objects in python:

def mergeObjectProperties(objectToMergeFrom, objectToMergeTo):
    Used to copy properties from one object to another if there isn't a naming conflict;
    for property in objectToMergeFrom.__dict__:
        #Check to make sure it can't be called... ie a method.
        #Also make sure the objectobjectToMergeTo doesn't have a property of the same name.
        if not callable(objectToMergeFrom.__dict__[property]) and not hasattr(objectToMergeTo, property):
            setattr(objectToMergeTo, property, getattr(objectToMergeFrom, property))

    return objectToMergeTo

This is a good example of how the whole dynamic addition of properties happens in Python. The objects in this example have a __dict__ property that is basically where the property/method/other stuff information is held in dictionary form. What does this mean? It means that if you use the setattr method you can then later call the property like you would normally.

  setattr(someObject, 'someProperty', 'some value')

  someObject.someProperty == 'some value

Knowing this is important as it allows you to really do some fun dynamic stuff that a lot of other languages just don’t allow.

jQuery Validator: Adding a Custom Method

File this one under “Posted to take less time to find the answer”:

If you’re using jQuery Validator and the built in validation methods just aren’t cutting, there’s a way you can add your own method to the validator itself. For this example let’s start some pretend time. Uhg I said pretend time not f–ked up fantasy time… Really, a horse? Really?

Now that we have that clear: Let’s pretend you have a form with three textboxes and you want to make sure one and only one is filled out. This doesn’t exactly fit the built in methods. Now you could try using the “required” method and replace it with a delegate. Could do that, but it ‘s  actually trickier than it sounds due to how required method actually works.  So what’s an easier way? Just add a method to the validator:

    jQuery.validator.addMethod('correctCountFilled', function(value, element) {
        var fullCount = 0;
        if(jQuery('#someTextBox1').val().length > 0){
            fullCount +=1;

        if(jQuery('#someTextBox2').val().length > 0){
            fullCount +=1;

        if(jQuery('#someTextBox3').val().length > 0){
            fullCount +=1;

        return fullCount == 1;

Then the call is done lika dis:


  rules: {
            someTextBox1: {
                correctCountFilled:  true  //This is the name of the method added and what it expects to come back when called to be valid.
  messages: {
            someTextBox1: {
                correctCountFilled: 'Some error message like pointing out how yours is a superior intellect.'

As you can see, the method returns false if all are empty or more than one is filled in. The method call on the validator expects “true” to be valid, so anything but one textbox being filled in will trigger the error message. Fairly easy, huh? Now go forth, be fruitful, and don’t multiply by mistake.

Python, Pyramid, and Mako… How to get Mako Working With Pyramid…

Well looks like Pylons is now Pyramids, and here go hell come. Now I could go on explaining the differences (Which most likely I will once I get farther in), but this is more just a quick post.


In the development.ini file, place this under the [app:pytrends] area


For example, the project I have is pyzazz (Don’t ask me what that is cause I don’t even know) and the template folder is… well templates. So I have it as:



When using pylons I used mako. It was fast and well it was by default. Now the default template engine is Chameleon which (Sorry Chameleon creator) sucks. First time using it, it was throwing parser errors in javascript lines like:

 if (urlParams.actual && urlParams.actual == 'true')

and it forced me to end an input with the </input> tag. And if you know anything about HTML, input tags DO NOT HAVE END TAGS. True story, go check w3.org if you feel like. Little things like that just annoy the hell out of me. Yeah I know it’s just html and javascript, the runts in the litter as far as programmers care, but you still can’t jack things up like that. And on that note: if someone who uses chameleon (Or helped write it) actually comes here, you are welcome to shoot down my claims.

Linq and Stack… Take versus Pop

So this might be filed under “Who f—ing cares” but I thought it was somewhat interesting. If you’ve ever used a Stack, you should be familiar with Pop and Peek. If not, here’s a little diddy from a guy named diddy. Actually that’s a lie. I have no affiliation Sean “Puffy” “Puff Daddy” “P Diddy” “Whatever he’s called now” Combs. We do share the same first name though. (Annnnnd wait for incoming lawsuit over using his name on this site)

A stack is a first in last in first out structure that in the .Net world uses two methods to get values back from it: Pop and Peek. Pop will give you the item AND remove it from the stack. Peek will merely give you the item but leave it safely on the stack.

What’s the point of this post? I’ll tell you when I find out.

Now when using Linq with a stack, you might get in trouble if you assume the Take method uses pop to get the value:

  return stackToUse.Take(count).ToList();

You would think that this would use Pop since Pop really is the “natural” (For lack of a better word) function of a stack. Most languages can guarantee a Push and Pop for stacks, but not all languages have a Peek. So it would be normal to assume the default is Pop. Problem is: It’s not. The Take method actually uses the Peek method. So these two methods will give a completely different return:

    ///Uses Pop
    ///  Return list with have "count" number of items and stackToUse will have the original
    ///    count of items minus "count"
    public static List<Object> CreateListFromPopOnStack(Stack<Object> stackToUse, Int32 count)
      return Enumerable.Range(0, count).Select(item => stackToUse.Pop()).ToList();

    ///Uses Take/Peek
    ///  Return list will have "count" number of items and stackToUse will have still have
    ///     the same number of items it came in with.
    public static List<Object> CreateListFromTakeOnStack(Stack<Object> stackToUse, Int32 count)
      return stackToUse.Take(count).ToList();

In the end, this is a rare case you will actually need to know, but what the hell? Why not know it?

CruiseControl.Net and CVS: Multiple Modules

Something I ran into is trying to check multiple modules for changes since the project I am trying to “modernize” is spread across what cvs calls modules. Really all they are is projects separated in the same trunk, but whatever. The point is I didn’t want to have to check the root directory where all projects are housed in order to see if just 5 have changed. Turns out it’s pretty easy. Just a disclaimer though: I’m still learning Cruise Control from scratch which means there might be a better way. This one however is simple and works… just like me. Well at least he simple part.

  <sourcecontrol type="multi">
        <executable>C:\Program Files (x86)\cvsnt\cvs.exe</executable>

        <executable>C:\Program Files (x86)\cvsnt\cvs.exe</executable>

        <executable>C:\Program Files (x86)\cvsnt\cvs.exe</executable>

        <executable>C:\Program Files (x86)\cvsnt\cvs.exe</executable>

The secret is the “multi” key word in the sourcecontrol tag and then adding the many cvs tags with the correct values.

Spark View Engine, ASP.Net MVC, and You

So one of the things I was forced to use, semi kicking and screaming, at one point in my illustrious career was the Spark View Engine for ASP.Net MVC. Actually that’s not totally true. I only kicked for a bit then skipped the screaming once I noticed what it did: It took all the ugly <% %> junk out of the html… my beautiful html… and made things like for loops much nicer. Mind you, this is mererly the tip of the ice pick… eh berg I meant berg… there’s a lot more to it. It handles things like Master Pages and Partial Controls pretty darn well as well as caching javascript files on the go. Sounds good? Well it should and if it doesn’t, I don’t think we can be friends.

First off, I just wanted to quickly write something up on how to get it all going and because I’m such a nice guy I even have a project that is ready to go for common use. The catch is that I made it in 2010 so if you don’t have that yet, you could be screwed. Then again I could type out a lot of the steps too. You just don’t know.

First off you can either get the assemblies from my hosted project, or you can go here and get it. Either way, I don’t care. No really, I don’t. Not just sayin’. The care cup had run dry.

The two assemblies you need to reference in your project are:


Next add this line to the Application_Start method in the Global.asax.cs file:

  ViewEngines.Engines.Add(new SparkViewFactory());

After that, you’ll have to add a little somethin’ somethin’ to your web.config. I know, I know. This is all so very hard. Live strong like Lance.

      <section name="spark" type="Spark.Configuration.SparkSectionHandler, Spark"/>
      <compilation debug="true" defaultLanguage="CSharp">
          <add assembly="PhotoShare.UI" /> //Whatever the actual UI project is
      <pages automaticEncoding="false"> //If you want it to auto HTML encode post/get stuff
          <add namespace="System"/>
          <add namespace="System.Collections.Generic"/>
          <add namespace="System.Linq"/>
          <add namespace="System.Web.Mvc"/>

Ok so the web config is ready. Now what?

Well now you are going to create a master page. That’s right you are. Don’t fight me on this. I’m way cooler than you.

There is a little directory structure hard coding going on since by default you have to have things in certain places for Spark. Oh well. All Master Pages go in a directory named “Layouts” in the “Views” directory. So something like:


D— it. Forgot about that little tid bit too. Spark files have to be named .spark. Well actually I think there’s a way to call them whatever you want, but lets just go with defaults for now smarty pants.

And for the hard part, the html for the master page.

        <use content="Middle" />

HOLY HECK THAT’S HARD! Now there needs to be a controller. So just create one in the controllers folder. In my project it’s called this:


And then go ahead and create a view for index. Once you’ve done that, rename the extension from aspx to spark. Now for the html:

  <use master="Application"/>

    <content name="Middle">
        hi there

And that’s it really. As you can see, the placeholder on the master page (use content=”Middle”) is referred to on the child page.

To make testing this page easy, I would suggest changing the routing in the Global.asax.cs file to:

          new { controller = "SparkTest", action = "Index"}

And you should see something like:

  hi there aasdfasdfa

Proving that both the master page and the child page are printing stuff out.

You might be wondering why you should do all of this? If you aren’t, you are one hell of a lemming. And not the cool kind like those little guys that blow themselves up for the betterment of the lemming collective.  You’re that stupid one the just sits there with its hand out shaking its head.

A quick example:

       <div> hihihihih </div>

Compared to:

  <div if="something.IsTrue"> hihihihih </div>

Small example, but I think its pretty obvious why the second is so much better. And this is just scratching the surface on what spark does really.  I’d suggest looking here for more. I’d also suggest a new hair cut because… just wow.

Failure scanning CollectionGen.dll for extensions.

Quick hit, you might get this if you try loading the bin directory of the nantcontrib project AND YOU DIDN’T FOLLOW THIS POST.

Solution, FOLLOW THIS POST or you can simply remove the CollectionGen.dll from the bin directory. However if you do that, you aren’t helping my bounce rate and that makes you a Communist… unless you are a Communist then it makes you a Capitalist.