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:

  jQuery(ELEMENT_FORM).validate({
    errorLabelContainer: ELEMENT_ERROR_DIV,
    wrapper: 'div',
    rules: {
      textboxEmailAddress: {
        required: true,
        email: true
      }
    },
    messages: {
      textboxEmailAddress: {
        required: ERROR_EMAIL_ADDRESS_REQUIRED
      }
    },
    ....

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};

  jQuery(ELEMENT_FORM).validate({
            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.

I Have Found Python and I Am a Changed Man

Ok so maybe the title is full of sensationalism, but in some ways it’s true.

In the beginning there was Microsoft.

When I started programming at the unusually late age of 24, I was brought into the world by Microsoft. At the time, ASP was still in fair use and .Net was the new wonder drug and no one, not even Microsoft, could nail down what it was exactly. It was a miracle in a bottle, an olde time elixir. It would fix everything known and even unknown unknowns. Now personally, I had only really taken a liking to the style of C++. I preferred brackets to subs and never minded semi-colons. So you can imagine when I found out about “the C#” , I was all about it. Looking back now, it does seem sort of silly since there really wasn’t that much of a difference between VB.Net and C#, but d—-it I was going to get my semi-colons or here go hell come. Naturally this meant I would start a journey of 8+ or so years into the Microsoft frontier.

Have Carrot and Stick, Will Travel

I think one of the strongest suits of the .Net framework was Microsoft’s need to constantly improve it. Now these improvements weren’t overnight but it seems like they made a lot of improvements in relatively short time. Every version just seemed to have the answer to every question I didn’t know I needed to ask. It was like they were reading the mind of future me and adding features based on that mind. Yeah ok, it’s a little ego centric to suppose that future me was the only person asking for such things, but I’m cool with my version. I can still remember how annoyed I was that the place I was working for wasn’t going to invest in 2.0 for a while, thus keeping me from my coveted generics. (Pretty sure I said the word to the point it didn’t sound a like word anymore) And honestly, a little nerd rage was expected since I didn’t want to type every parameter as Object. I can also remember how in awe I was of Linq and some of the semi-functional programming concepts being introduced with 3.0/3.5. It seemed like as soon as I started to covet something new, BAM it was there. So really, I had no reason to ever stray from .Net because I was always well taken care of. Course then something changed and it was Microsoft’s fault.

There some things you can’t unsee

Remember that thing named Linq? Well Linq was more in line with the whole .Net mystique. It wasn’t just a way to manipulate lists, it was a whole lot more. With Linq came a few nice concepts like typed delegate, anonymous types, type inference on a much larger scale, extension methods, and a whole slew of other larger concepts like Entity Framework. It was kind of like taking a trip to the moon. Sure the whole moon thing is great, but the massive amount of new technologies that came from just getting there was where the real gold was. In the development of Linq, Microsoft had to come up with new stuff to even run the concept of Linq. At some level it was touted as Microsoft’s attempt to bring a more dynamic and functional look to C#. Now no one was claiming that C# was a functional language but d—ed if it didn’t try. After all, it’s not easy to make something more dynamic when the underlying technology is meant to be more static. Between being able to easily pass methods around like objects and using lambda expressions to simplify dealing with lists, it was a huge step forward and personally a large shift in my programming paradigm. (Yes I just used paradigm in my blog.) So where’s the catch? It’s simple, my eyes were opened to stunning new concepts. The use of Linq, lambda expressions, and Func/Action got me to start looking at programming as a whole in a different way. I wanted to be more dynamic. I wanted to start solving old issues using all this exciting stuff. And because of this I started expecting more and pushing .Net to the limits. For the first time in my programming career, the carrot was chasing me.

Model View what?

If Linq was the straw that broke the camel’s back, then MVC was the bus that ran it over by mistake. For years I had been in the standard world of Web Forms. Something that at one time seemed to be a beautiful bridge between the web and stand alone projects was now looking worse and worse. All the issues I had with Web Forms were now being magnified by the overall streamlined approach with MVC. It was such a strong double-hit between Linq and MVC that I just couldn’t ignore the outside world anymore. It’s sort of like that moment when you realize that your parents are human just like you. It makes you think that maybe everything you knew wasn’t actually the only way to do things. That maybe there’s something more out there. Maybe, just maybe, people didn’t eat cold pizza with syrup. This was the moment when I started wondering if there was something greater out there. (Just like Vger) Because I had never dabbled in anything outside of .Net (except a regrettable affair with PHP that still worries me that someday a little PHP will show up at my door claiming that I’m it’s dad) so this concept was brand new to me. Of course anyone who wasn’t completely clueless like me would have known that MVC had been used by things like Java for quite a few years. To makes matters ever worse, the poor camel was struck by a huge meteor named Javascript. Yes, I typed Javascript. With MVC came my heavy use of Javascript and it’s much fancier suit and tie JQuery, and guess what? I noticed that most of the cool new dynamic stuff for .Net was being used in Javascript all the while. I had shied away from Javascript for a long time since I was brainwashed into thinking it was evil. Just use post backs and server side code. Stay away from the language that we dare not speak its name. Problem was, it is almost a need when using MVC unless you want to refresh the page on any form post. Long story short, I was reeling from all this new information.

Every silver lining has a dark cloud

One thing that I didn’t like about most examples of how the model and view work together was the use of a dictionary to hold values that would appear on the view. I’ve never liked magic string programming so I naturally went with typed views. This meant that for every view I would have a model class working alongside to help pass values in a much more clean and safe way. The issue? A whole f–king lot of models. So much that it almost became a separate project in itself to hold all of them. Something just didn’t seem right about this. One of the nice things about C# is it’s more rigid feel to keep people from screwing things up (unlike the magic string theory). Problem was, for rapid development this just didn’t cut it. And let’s be honest, in the real world (unless you are the lucky few that have decent deadlines, i.e., top-end jobs) rapid is all we get. This left me in an uncomfortable place. We’re talking showing-up-to-school-naked-and-realizing-it’s-not-a-dream-this-time uncomfortable.

In time all things become clear

It would seem natural that if I liked all the more dynamic features of .Net and Javascript, I would possibly try to find a language that suited my needs. Well there’s an old thought in psychology: People don’t change unless something makes them. And as much as I’d like to say I braved the new world on my own, it really was more of a wake up call. While Microsoft has done a lot to add needed complexity to the framework, they continue to add far too much simplicity.

Not to long ago, some time after 4.0 was just about to go “gold” I read a couple articles on how easy programming was becoming in the .Net world, and how salaries for .Net were starting to drop. To sum it up, Microsoft has always tried to walk two lines: Cater to the more expert programmer AND the drag-and-drop programmer. Some nice examples would be from 2.0 in generics and update panels. Generics are still not understood by drag-and-drop programmers (as I have been shown on many occasions) but man they love their update panels. I mean it’s ajax without actually knowing anything about it. And I think this is where .Net is going to head. I think as elitist programmers we’d like to think that knowing design patterns and how to successfully design a streamlined system is important but honestly, it isn’t. And I’m saying this as a person who has had 7+ jobs jobs in the last 9+ years. Businesses want results. They don’t care if it costs them more in the end if you hack something together. I’ve never really met a company that thought that far ahead, and in some ways I can understand this. Getting to the market first can be a huge advantage. The “Just get something out now and worry about it later” mantra is prevalent in all walks of business. It’s hard to convince companies to take more time to develop a more solid system. Because of this, things like update panels and drag-and-drop design are still hanging strong which by proxy means having a solid understanding of how things work really doesn’t matter as much.

Though way too lengthy of a side bar, the point is that this is the event I needed to change. Because Python is a more fringe language but is used by some really good companies, it seemed like a reasonable switch… or at least something to experiment with. There is nothing really drag-and-drop about it.

If at first you don’t succeed…

I will admit that at first I was a little apprehensive about Python. It just didn’t seem to offer anything that C# didn’t… again at first. However, the more I used Python and Pylons, the more free I felt. All those years of pushing and expecting rigidity were washing away. Don’t me wrong, it took a while to really get how powerful Python can be. I mean stuff like adding properties to objects dynamically was nice, but that was also in 4.0. Passing methods like objects: C#… well at least with some restrictions. But with that being said, having options like that without the need for typing parameters and done so with a natural feel made it pretty well suited for web development. I’m not going to spout the virtues of Python and I’m pretty sure I’ve derailed this post quite a bit, but the moral of the story is simple:

There’s more out there than Microsoft/.Net. Now I realize that probably 2/5 readers (not a fraction but an actual guess on how many people will read this) will be thinking ‘DUH’ but this isn’t really written for people who know this already. This is written so that even Microsoft slappies like me can break free of a what I thought was the be-all and end-all, and really learn something new that isn’t new to .Net. I’ve built my career around .Net and have no doubt it will most likely be what I’m paid to use for a while. With that being said, there’s absolutely nothing wrong with trying new paths. Is Python the language to do this for you? I have no idea. Maybe it’s Ruby or (maybe(the(language(is(Lisp))))). That I can’t tell you. Only thing I can tell you is that you won’t know until you get out and try something new. You can’t possibly know what’s out there if you stay at the house that Microsoft built. In a world with too few eggs and a ton of baskets, you really can’t afford keep things the same.

Python: Added Folder By Namespace Won’t Import…. How To Make A Namespace.

Ran into this last night and it was giving me some issues. Basically, I added a folder (unitTest) and then some .py files to it. So my folder structure is something like:

pyzzazz/unitTest/validation/validationTest.py

Now one would assume you could do this:

from python.unitTest.validation.validationTest import someTestMethod

Problem was that the IDE (PYCHARM PLUG) was telling that it couldn’t see the unitTest namespace. After some nerd rage and searching, turns out that Python by nature doesn’t assume .py files outside of the main folder structure “belong” to it. The fix is simple though, add a blank __init__.py file to the folder. In my case, I added a blank __init__.py file to the unitTestFolder. Then and only then would the above namespace actually work. Here’s something on the __init__.py file

Are you a good programmer?

Something I’ve struggled with for a long time is how to define a good programmer. It’s not an easy task since it’s fairly subjective and there are a lot of different opinions on this. So many that you could say that this is just another drop in the bucket of irrelevancy known as byatool.com. But a post being pointless hasn’t stopped me before, so damned if it will stop me now.

The first question that a person might ask after reading the title of this page is: Do you really think the iPad will revolutionize the way schools handle reading material? And that is a fine question, but a bit off topic. So if I were to tell you what first question to ask, I would tell you to ask: Who the hell are I..you to ask you…me if I’m eh you’re? Oh f–k it, you get the picture. And the answer is: No one really. ANTI CLIMATIC!!!11oneonesevenone I’m not the world’s best programmer and won’t be winning the prestigious Byatool Programmer of the Year award. (And sadly I’m the only one in the running.)

But what I do have is a thirst… No, not that kind. I have thirst for knowledge.

Yeah yeah, I know “cliche”. However, the point is still there AND that’s only part of it. You see the thirst for knowledge is only a step, and it’s the easy one. Anyone can WANT to learn more, it’s taking the time to DO more. It’s not enough just to show up.

And I think it’s the doing that separates the real from the others. The doing is what separates. Separation is bound to doing. Doing separation. F–k where was I?

Look, despite what people tell you, life is not a box of chocolates otherwise we’d all be morbidly obese… and happy. Life is more like… one of those damned invisible fences with a shocking dog collar. Yeah you’re going to get zapped more often than not but at some point you’ll find that one area in the fence next to some kind of electricity tower that screws with the fence and allows you to break on through. Course most likely you’ve already lost most of your brain living so close to an electricity tower, so in reality you’re just breaking through to a life of madness and too dumb to know it.

But this was a really stupid analogy anyhow that doesn’t really make any f–king sense, so who cares?

The point, if there ever was one (which even I’m debating at this moment), is it is never easy. NEVER. It’s always a struggle. It’s always a pain in the a–, but it’s necessary. Why? Because it defines what a good programmer is. The struggle. Or more to the point, the perseverance. It’s so easy to just be happy with what there is now. You know, the old “If it ain’t broke, then let’s run the wheels off it” mentality that I think comes from an earlier generation. (Most likely the generation of any given current professional programmer)

Fact is, it’s OK to try something new. It’s OK to venture out into the unknown. And more importantly, YES YOU WILL BE SCURRED AND GET FRUSTRATED AT SOME POINT! This is completely natural. You aren’t stupid. It isn’t just you that feels that way. You aren’t a mutant because you are afraid you’ll fail. Sure I don’t doubt there are people out there that just naturally jump into the unknown, feel no fear, and figure it out in a day. That’s why they are billionaires and rare. For the rest of us relatively poor goofs, we have to deal with all of that AND perform.

Just remember, you have been conditioned by multitudes of areas to be afraid of change. Hell, even your brain fights change because it’s far more efficient to keep things as they are. It’s even a basic principle of existence: path of least resistance. What am I getting at? Just do it. Be that person. Fight your way into the new world.

Why? BECAUSE YOU’RE A GOOD PROGRAMMER. And if this doesn’t sound like you, well you know what you have to do. Well two things: One is to stop being such a baby and set a dentist appointment for your annual check up. Cavities are no laughing matter. Second is to stop letting your fears and comfort get in the way of your growth. After all, this is your (And I’m assuming) profession. It’s your job to be the best you can be.

It’s going to suck. It’s going to be nerve wracking. It’s going to push you to your limits… and you’re going to like it. Just remember to repeat to yourself, “F–k the noise, it can’t fade me.” (I’m not exactly sure what that means but it sounds tough.)

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.

Get your own “Tool” blog!

Have you ever thought about writing your own blog?  Well now you can have it! And for only $5!  NetDevInc.com (The brains of this operation, not the comedy) has teamed up with FiveRR.com to bring you the Deal of the Year!

You get:

  • Help setting up your domain name
  • Web hosting for 3 months
  • WordPress Installed
  • Free themes and useful plug-ins
  • And MORE !!!

Check out our offer at http://bit.ly/WordPressForFiveDollars

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.

ANSWER:

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

mako.directories=projectName:folderWhereYourTemplatesAre

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:

mako.directories=pyzazz:templates

MORE USELESS WORDS:

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?