Hyper Competitive Sleep Losing Entrepreneurs?

I remarked to a friend that Mark Suster’s entrepreneurial roots show in his approach to being a VC – he’s come out of nowhere and in short order aggressively pushed himself into being one of the most relevant voices out there. He seems to be working a lot harder than the others guys, exactly as you’d expect an entrepreneur to be. Not exactly what you’d expect of a VC.

His blog is fantastic, and I quite often agree with his advice.

That’s why I found it odd that his The Best Entrepreneurs Are Hyper Competitive & Hate Losing struck such a dissonant chord with me.

Shuffling through the successful business people I know and trying to gauge whether they would be the type of people who are obsessed with winning, even in a family game of scrabble, I don’t come to a clear conclusion. I know hyper competitive people, but I also know plenty of people who are able to separate their business behavior from their personal behavior. And not obsess with beating the competition.

Maybe that’s what’s not sitting well with me – Mark’s definition of winning seems to be beating the competition.

Some of the best entrepreneurs I know don’t obsess with the competition. They obsess with their own behavior.

Here’s a contrived example – look at Apple. Do you see Jobs competing with the others in the industries he enters, or do you see him trying create the best possible product, distinctly separate from what his competitors are doing?

Frankly I have a hard time picturing a lot of these guys stressing out over scrabble or Guitar Hero.

Mark’s a very successful guy and his approach has certainly worked for him, but I disagree that you need to be obsessed with winning in the way that Mark describes it.

Look at this way: you could destroy all your competitors and still not win. You could also win without destroying any of your competitors.

First, pick the right game. Then, pay attention to playing that game as best it can be played. Competing may be an important tactical part of playing the game, but it’s probably not the part to obsess over.

Django-mptt: Tree Storage in Django: A Brief Overview

django-mptt is a library for storing tree oriented data using the Django ORM. It allows you to place your model instances into a tree structure and efficiently query for ancestors and children.

Here’s a brief tutorial on how to use it:

After installing, you’ll need to modify your model to include a “parent” field, and register it with mptt:

class Person(models.Model):
    contact   = models.ForeignKey( Contact, db_index=True )
    role      = models.CharField(max_length=20, blank=True)
    parent    = models.ForeignKey('self', null=True, blank=True, related_name='children')

    def __unicode__(self):
        return "Person: <%s>" % (self.contact.email, )

mptt.register(Person)

mptt dynamically adds fields to your model, so you’ll need to syncdb after you’ve added the parent attribute and the mptt.register call to your model.

The basics are fairly easy to use:

To move a node to the root of the tree, use move_to with a targe of None:

person1.move_to(None)
person1.save()

To make a node the child of another, set its parent:

person2.parent = person1
person2.save()

To find the children of a node, use the children field:

>>>person1.children.all()
[<Person: Person: <test2@testing.com>>, <Person: Person: <test3@testing.com>>]

Here’s a little snippet of code to setup a 15 node tree where each node has two child nodes:

contacts = []
people = []
for n in range(15):
    c = mod.Contact(email="test" + str(n) + "@testing.com")
    c.save()
    contacts.append(c)
    p = mod.Person(contact=c)
    p.save()
    people.append(p)

people[0].move_to(None)  # Root
people[0].save()
for n in range(1,15):
    people[n].parent = people[(n-1)/2]
    people[n].save()

Now let’s take a look around:

>>>people[7].parent
<Person: Person: <test3@testing.com>>

>>>people[3].children.all()
[<Person: Person: <test7@testing.com>>, <Person: Person: <test8@testing.com>>]

Now let’s move things around a bit; we’ll take person3, which is 2 levels down from the root, and make it a direct child of the root:

>>>people[3].parent = people[0]
>>>people[3].save()

>>>people[0].children.all()
[<Person: Person: <test1@testing.com>> <Person: Person: <test2@testing.com>>, <Person: Person: <test3@testing.com>>]

And we can look at the ancestors of a given node:

people[14].get_ancestors()

Fantastic Mr. Fox: See It

I’m a big fan of Fantastic Mr. Fox. We just watched it again and it was a hit with everyone from the 2 year old to grandma.

The dialog an voice acting are excellent, and the animation is really refreshing. The story is smart and is different enough from your typical Disney fare to be a welcome change.

I recommend it, go see it.

Feels Like A New Stage Of The Web

I was doing some log analysis this morning and was struck by the variety of user agents accessing Xpenser. Quite a bit of mobile access with quite a variety of different browsers, as well as some more exotic items (various tablet PCs I don’t recognize, etc).

Then there’s the API access that’s been picking up quite significantly – in fact, I wouldn’t be surprised if it overtakes regular web access in a little while.

For quite a while the web we had a fairly uniform set of entry points – IE and FireFox for the most part, with a smattering of others thrown in. There is so much more variety now, and the variety is significant – for example, the difference between a mobile device and a desktop browser is much more significant than between IE and FF.

I’m hoping other modes of access become commonplace as well – boxee, tablet PCs, etc.

It feels like we’re at a transition point from uniformity to diversity again. This will mean pain the short term as we adjust, but a richer and more encompassing experience once we make it to the other side.

I’m looking forward to it.

Move Files Older Than X Days To Another Directory

Here’s a little script for finding files modified more than 7 days ago and moving them to another directory:


find . -type f -mtime +7 -print > /tmp/old_files.txt
cat /tmp/old_files.txt | while read line; do mv "$line" ../old_files ; done

Why Google Launched Google Public DNS

I’ve seen a bit of uninformed chatter on this, so let me add my own uninformed 2 cents:

First, I think Google actually does want the web to be faster and better. They recognize that the web is their platform and any improvement to it has an eventual benefit for them.

But Google DNS also provides other benefits. It’s true that there is an advertising opportunity in hijacking mis-typed domains and displaying ads against them, as OpenDNS does. This is potentially a large market – domain squatters, for example, make a tidy living doing something similar. I don’t think Google will actually do this. At least not anytime soon – it’d just be too creepy coming from Google.

What Google is really after is data. In particular, traffic and usage data.

By using Google DNS you effectively tell Google exactly what sites you’re visiting, when. Google gets access to your browsing patterns without having to install a toolbar or spyware on your computer.

How valuable would usage data be to Google? Knowing exactly what sites you visited, when, and how frequently?

Extremely valuable. They could use this information to develop refined models of your interests and behavior, and use it to better target ads to you. Nice.

However, their privacy policy states that they won’t do this.

What they will do is use the data to form a better model of the web.  They’ll know, for example, how popular sites really are and how much traffic they get. They’ll also be able to build user and browsing pattern models – eg. people who use facebook are also likely to use sites X, Y, and Z. They’ll use this data to improve search and advertising.

Look for Google to start offering its DNS services for free to internet provides, corporations, or anybody else with large amounts of users. Instead of paying ISPs for access to their usage logs, now they can get their own, and it’ll only cost them the overhead of running a large scale DNS service.

Peter Norvig’s message has been that more data trumps better algorithms. Google DNS is a beautiful way for Google to get a tremendous amount of data with very little intrusion while looking (and behaving) like saints.

How To List Files In A Package in Ubuntu

dpkg -L package-name

How To Enable Vi Syntax Highlighting In Ubuntu

Note to self, as I seem to need to do this on every new install:

Ubuntu ships with vim-tiny, which doesn’t support syntax highlighting. Do this:

sudo apt-get remove vim-tiny
sudo apt-get install vim
sudo vi /etc/vim/vimrc
( Remove the quote mark from the "syntax on" line, uncommenting it)

The Power of Stories In Shaping Views of Cultures

Impressive Ted Talk by Chimamanda Adichie on how stories, and in particular “single stories”, shape our views of cultures. Many parallels with how people typically see Iran.

A great quote from the talk: “The problem with stereotypes is not that they are untrue – it is that they are incomplete“.

On Niche News And Self Administered Blinders

I used to read the local newspaper. It was a fairly poor quality view of world events.

As news sources moved to the web I started to read a wider variety of sources – BBC, Le Monde, Haaretz, NY Times, Google News, various Iranian publications, and so forth. I had a better view.

As RSS took over I started to spend more time in Google Reader, with a larger number of sources. The sources, however, were hand-picked by me and the topics they covered were much more niche.

Sure, I had the feed from the NY Times, BBC, etc, but they just couldn’t compete with the blogs. I would only read them occasionally, and finally I gave up and removed them from my feed.

Nowadays I hang out on Twitter, to the detriment of Google Reader.

My sources of news are even more niche, even more hand-picked, and the news itself is headline-only.

It strikes me that I’ve lost something valuable here. I went from being exposed to a world view, much of which I didn’t agree with, to a series of very short, niche, hand-picked news sources.

I have unwittingly self-applied blinders.

An odd and disturbing trend. Nothing is stopping me from regaining the world view, other than my own choices. Yet I remain mostly blind.

How Interviewing Job Applicants Has Changed

I’m noticing how much the practice of finding a candidate and interviewing them has changed over the years.

First step is to look up the person on the web. Since I’m looking for a technical person I’m expecting a blog, contributions to open source projects, a twitter presence, etc. If I don’t find them, the candidate becomes less attractive.

If I do find a blog or twitter feed, I take some time to read them. You can tell a lot about a person with just a short overview – for example, even a delicious feed can give you a very good feel for how good someone is technically.

Hopefully the person has an open source project or two they’ve contributed. If so you can dive right into the code and get a good sense of their skills at work. I love this – you can see great coders almost immediately. And of course bad ones.

If the person is still looking good it’s time for a review of the resume and their linkedin profile.

By the time I followup with the person I have a very good sense of who this person is, what they’ve done in the past, and what their real-world coding looks like. The people who make it to the interview are so well filtered you almost can’t go wrong.

It’s very time consuming, but if you’re as fanatical about hiring good people as I am it’s worth it.

Contrast this with the old pile-o-resumes approach, or the recruiter-filter-by-keyword approach, and I think we’re in a much better place.

Now if I could only find a recruiter I could trust to do the technical deep dive I’ve described here and be ingenious enough to find diamonds in the rough I’d be a very happy man.

Eclipse + PyDev : I Recommend It

I used to be a vi guy who finally made the move to graphical editors. I looked for the simplest, lightest possible solutions, using ConTEXT for quite a while.

Some years ago I was forced into using Eclipse for reasons I can’t quite recall; probably Java development. I didn’t like it – the forced Project concept, the bloat, the general slowness.

Eventually I got comfortable with it, got PyDev installed, and made it my primary development environment. These days most of my development lives in Eclipse.

With the 1.5 release PyDev included quite a few previously pay-only features in the free / open source version. Since then I’ve found I’ve become even more productive in the environment, and now actually enjoy it.

In particular, the code analysis is very useful. I love the fact that it points out unused imports and variables as well as syntax errors. Going through old code I was surprised at how many spurious imports I had, as well as a few actual errors in code that had been in production for several years in rarely exercised branches.

If you’re doing python development I recommend you take a look at Eclipse+PyDev. I was surprised at the level of increased productivity it brought me.

Why I Love Venture Capital(ists) Too

My buddy Paul Kedrosky (disclosure: an advisor to my company) has an interesting piece on why he loves venture capitalists. I love them too, but mostly for a singular reason.

Paul’s posts starts with some excellent arguments, but alas, in the third paragraph he starts to lose me ;-)

To pick on a few things:

“the idea that anyone at all would build a business around funding startups is the remarkable thing”. Indeed. So is the fact that there exist professional gamblers. The odds are against them, most lose money, but a few end up with very good returns.

“Failure rates among venture-backed firms are lower in the first few years, but higher later on”. What we’re saying here is that companies who start out with more money take a longer amount of time to run out of money. Hmm. I don’t know if that says anything about the nature of VCs, other than they carry money.

“But that doesn’t mean VCs are quacks. Or that what they do isn’t hard. Or that it’s unimportant. Because it is important, and the good ones are smart, and what they do is very, very hard.” - I can almost make the same case for degenerate gamblers: what they do is hard, and the good ones are smart. Most are quacks though.

The difference is what they use their money for.

The saving grace of venture capitalists, god bless them all, is that they put their money to use in building business and innovation.

It’s not about loving venture capitalists. It’s about loving their money. And how they use their money.

Now think about it: hand somebody a big pile of money, pay them a handsome income, and have people begging them for money all day every day. What type of personality do think will emerge in them? Is it all possible they’ll start to think a little too highly of themselves?

So here’s to venture capital. I think it was Steve Martin who said something like: France is a  lovely country, except for all those damned French who live there. Well, venture capital is a lovely country too.

I kid, I kid. Particularly the VCs I’m talking to next week, plus all my VC friends, plus everyone I’m likely to raise money from in the future, I really don’t mean you guys. You guys bring a lot of value to the table besides money. You really do. I meant the other guys.

Seriously, I kid.

Let’s finish with a quote that made me laugh from an entrepreneur buddy of mine (who shall remain nameless): “I aspire to live a lifestyle where my hobbies are funded by other people’s money. Two ways I know to do that: get NSF funding or raise venture capital.”

Where To Eat in NYC, From A Local

I asked my brother Pooya, a former resident of Manhattan, what bridge-and-tunnel (off-island) adventures he’d recommend and where we should eat. Here’s his response, for your benefit:


Hey man,

For directions to all these places, use hotstop, gives you subway and walking directions, very nice, there’s an iphone version too.

First of all, why would you ever want to get off the island?

But if you do, definitely go to Brooklyn instead of Queens, the only interesting thing in Queens is little india.  In Brooklyn, you can go to Prospect park, the whole neighborhood there is pretty cool in a hipsterish kinda way. You could also go all the way out to Coney Island, kinda neat to see once, they have the nathans hot dogs and the old rollercoasters.
F train towards Coney Island, get off at Prospect park (for Prospect park) or go all the way and get to Coney Island.

BROOKLYN:

My recommendation, take the F train to Prospect park, look around the park and then walk around the corner to the Brooklyn Botanic Gardens, makes a nice day.

You can also head to the Bronx to see the zoo (though living in San Diego, it’s probably not worth it).  If you want to get away from the city feel, you can hop over to Governor’s island, go down to battery park, head a little north and there’s a free ferry that takes you out to this almost deserted island, used to be a navy base or something, take some picnic food and lounge out looking back at the manhattan skyline.  But given your limited time, I would recommend sticking to Manhattan.

Places to Eat:

Check out all the menus and phone numbers: menupages .

Village:

John’s Pizza – good pizza in the village, whole pies only, no slices, another branch in times sq and lots more to eat in the village, so up to you [Me: I wasn't crazy about John's Pizza, but plenty of people like it]

Mamouns (you know about) [Me: we always end up eating here a ridiculous number of times. Really excellent falafels. I recommend the falafel sandwich with baba ganouj. In fact my mouth is watering as I write this. The MacDougal location is nice; you can walk over to Rocco's for desert from there: 119 MacDougal St, New York, NY 10012 212-674-8685]

Rocco’s – dessert, definitely get the canolis
243 Bleecker Street (past 6th Ave) [Me: I ended up over dosing on canolis. The mini eclairs, the napoleans, and just about everything else is good too, so experiment]

Brunos – dessert, especially the chocolate mousse
506 Laguardia Pl & Bleecker St (near wash sq park, NYU)

Thai: Spice – cool looking place and good food, great value (on your way from the village to union sq)
39 E 13th St (at University Pl) [Me: Spice is not high end, but it's actually really good. Another place we ended up eating at multiple times. Several locations in the city so it's easy to get to.]

Sushi – Tomoe Sushi is a nice place, but surprisingly the prepared sushi from Morton Williams supermarket (Bleecker and LaGuardia) is also fresh and excellent.

Times Sq Area:

John’s Pizza – best thing if you have to be in Times Sq for a play or something
260 W 44th St (Btwn 7th & 8th Ave)

Margon – Cuban sandwich place, deli style – get a cuban sandwich or the special (oh crap, forgot the ham thing, still get an oxtail soup)
136 W 46th St  (Btwn 6th & 7th Ave)

Lupa – if you’re going to do a an up-scale meal but dont want to spend too much, this italian place is great, modern (mario battali place)
170 Thompson St (Btwn Houston & Bleecker St)

Soho:

Lombardis pizza – crowded, but worth it, you can call ahead and pick up
32 Spring St  (At Mott St)

Sullivan St Bakery- great soho snack as you’re shopping, fresh bread, the olive is great
533 W 47th St (Btwn 10th & 11th Ave)

Kees Chocolates – you have to try the passion fruit chocolates, take some home too
80 Thompson Street (Spring St)

Katz Deli – really for pastrami so not sure if it’s worth it for you guys
205 E Houston St | At Ludlow St

Central Park area:

Burger Joint – great burgers, simple menu, buy and take to the park for a picnic
118 W 57th St
(Btwn 6th & 7th Ave) – hard to find, in the lobby of the Le Meridien hotel, look for a small neon burger sign or just ask in the lobby

Other random places:

Sahara’s – Turkish place on the east side mid 20’s , fresh bread, appetizers
513 2nd Ave (Btwn 28th & 29th St)

Shake shack – Burgers in Madison Sq Park
11 Madison Ave | At 23rd St

Pomme Frites – Belgian fries, lots of topping choices, east village snack if you’re near st. marks
123 2nd Ave | Btwn 7th St & St Marks Pl [Me: these are really excellent, give them a try]
Hopefully that’s enough to get you started.  Keep in mind I haven’t lived there in 3 years so things may have changed, but I’ve been going to my favorites (Katz, Lomardis, Brunos, Roccos) regularly on my visits and can still vouch for them,

Enjoy and bon appetit.


Other random thoughts from me:

Taking out a row boat in central park is surprisingly fun. I recommend it.

The trip back to JFK, should you decide to take the metro and AirTrain, is extremely long. Coupled with the fact that most airlines don’t offer food anymore on the flight, you’ll want to bring some food with you. A couple of slices of pizza and some pad thai from Spice will do you well.

Turns out Delta charges for checking in even a single bag. That annoys me, so I don’t think I’ll be flying them again.

Yahoo Mail WTF?!

I still have a big soft spot in my heart for Yahoo, but Yahoo mail, WTF?

Yahoo Mail WTF?

Of the entire screen only the area I’ve highlighted in orange is dedicated to the contents of the message. And this is with the app maximized to full screen.

The interface is unusable as a mail reader: I can’t read the email message.

How on earth did the product people agree to this? Where’s the customer advocate?

Tim Bray on Design Patterns, Threads, and COM

From Tim Bray:

My experience suggests that there are few surer ways to doom a big software project than via the Design Patterns religion. Also, that multi-threading is part of the problem, not part of the solution; that essentially no application programmer understands threads well enough to avoid deadlocks and races and horrible non-repeatable bugs. And that COM was one of the most colossal piles of crap my profession ever foisted on itself.

You may have read my own two cents on design patterns (hate them) and threads (not a huge fan).

On Gmail Fail, Rot, and Broken Windows

Gmail is once again unavailable this morning. Normally I’d let it go – fail happens – but it’s part of a disturbing trend that looks a lot like neglect. The service has been getting slower and slower over the last few months, with search taking ridiculous amounts of time.

Why is it disturbing?

It’s important to understand that Google doesn’t directly make money on email. Think of it as a loss-leader of sorts.

Yes, I know there’s advertising on there. I also know a bit about advertising systems.

Gmail brings in a relatively a much smaller amount of revenue than Adwords and Adsense, and the margins are much lower. You have to pay for all that Gmail infrastructure, and click-thru rates on email ads (or ads placed next to most other compelling content) are very low.

Google is smart enough to know where their money comes from, and they go to great pains to ensure their search remains superior. They invest a lot in search.

But what do you do with properties that make money, but at small amounts and with much lower margins?

For example, Yahoo Finance, Small Business, My Yahoo, and many of the other businesses are nice, profitable business, but not large enough or high-margin enough to get a lot of love or resources.

You neglect them. You put resources on projects that move the top or the bottom line.

My concern with Gmail is the trend that looks like neglect. It’s a relatively large property for Google, but it’s been experiencing problems. I know fail happens, but I also know that if Google put their mind to it they could make it much more available than it has been.

As Google branches out into more new and different products, it needs to be very mindful of neglect. Rot at the edges of your systems deteriorate the overall perception of your offerings. And search market share is very dependent on perception: witness the studies that removed branding from Google, Yahoo, and Microsoft search results and found nearly identical user satisfaction scores. 

So Google’s outlook has to be: if we’re going to do something we’re going to do it extremely well. The apple philosophy.

And if we’re not doing something extremely well, we need to fix it or shut it down. 

It’s a tough balance – how do you foster innovation and allow people to quickly create and launch projects, while maintaining a commitment to long term maintenance of quality?

It’s crucial to identify your core offerings, mark the rest as alpha, beta, “labs”, or any other label that signals the service might go away, and be absolutely fanatical about the quality of the core offerings on a continuous basis.

Here’s hoping Gmail gets its act together so I don’t once again have to switch providers.

On Presenting At And Attending TechCrunch 50 and Demo

I was fortunate enough to attend both TC50 (thank you Heather, Michael, and Jason) and Demo (thank you Matt and Chris) and have a booth at one. Thoughts:

If you’re presenting or have a booth,

Have something to say. Don’t look confused, wondering how to describe your company – you should’ve practiced this ad nauseum by the time you get to the show. That goes for everybody at your booth – if they’re at the booth, they should know what to say.

Say it. Briefly. Tell me what you do and why I should care in 30 seconds. Have a 3 minute version. Give me a chance to escape after 3 minutes. If I still care, delve into details and exchange contact info.

Have a Hollywood pitch. Nivi of Venture Hacks came up with ours – the first time I described Xpenser to him he said “cool – Tripit for expenses”. I’ve been using it since. You want to be “the something of something”. Sounds silly but it really works – Jason Calacanis, for example, told me he got what we did the moment I told him our hollywood pitch.

Pick one thing. You’re three people. You can’t possibly be solving all of the world’s problems. Pick one problem, present a solution for it. If you find yourself saying “or, we could do XYZ”, then you’re probably screwing up.

Demo. Don’t talk about it, show it. Both Demo and TC50 companies have been very good with this actually.

Explain how you will make money. Maybe you haven’t figured it out yet; that’s probably ok. But you will be asked, so have something to say.

Address the competition, particularly if they’re 900 pound gorillas. If your product is a better facebook, google reader, twitter, yelp, etc, at least acknowledge the competitor. If you’re showing me a page that looks just like facebook updates, I’m going to be thinking you’re competing with facebook. Tell me how you are not, of if you are how you’ll beat them.

Don’t look glum. I don’t care if you’ve had a bad day. I was having a particularly rough day when we had our booth at TC50, and was derailed from my plans to mope all day only by my partner’s persistent professionalism. Suck it up and present. I did and we ended up getting some fantastic coverage for Xpenser.

Don’t look bored. If you’re bored how do you expect people to be interested?

Don’t be shy. If you see someone wandering around and somewhat receptive, grab them. If you’re sitting in your chair as people walk by you’re doing it wrong.

Attendees and presenters alike:

Network. Meet someone new, shake a few hands. This is the main reason you’re at the conference. Some conferences do a good job of providing you with opportunities – O’Reilly conferences, for example, include an online app that allows you to find other attendees and connect with them. All conferences should do this. Demo in particular would be a great candidate for this, since the attendees are likely to be interesting to each other.

At the last Hadoop conference, for example, where I was actually very interested in the presentations, I ended up catching only 4 presentations in person. The rest of the time I was talking to people in the hallway, catching up with old colleagues, etc. Best conference I’ve been to in a while.

VCs and investors working booths: good on you. I’ve been impressed by the number of investors actually putting in real work. Henry Oh, for example, was absolutely a machine and left me very impressed. If you’re an investor, what better opportunity to see your investment in action, gauge feedback, and see how your team interacts with people? Take the time to show up and man a booth; the golf course will still be there tomorrow.

So how would I compare TC50 and Demo? Bottom line is they’re both excellent shows and you should do your very best to get into either. If you get accepted to either you can’t lose. Each reflects the personality of its founders; TC50 is louder and has more ambient energy, Demo is more professional and structured. TC50 is very web/online focused, Demo has a broader range of technologies.

I preferred TC50’s approach to the presentations. After each company presents they get immediate feedback from a panel of experts. At Demo the feedback comes in a lump after all of the session’s companies have presented. Having the immediate feedback helps complete the story on each company and provides a natural break.

I preferred Demo’s scheduling and focus on the booths. At Demo attendees spend  a good bit of time at the Pavilion where the presenter booths are. This is a very good thing – they get a chance to actually interact with and touch the products. At TC50 the booths seemed a bit more like an obstacle on the way to and from the main presentation area.

Very Tiny Javascript/jQuery Templating

I was in need of very simple templating capabilities in Javascript, and with the smallest library I found weighing in at 500 lines found myself compelled to write a solution. Here it is:


function render(text, data) {
	pieces = text.split(/\{(\w+)\}/)
	for (var i=0; i < pieces.length; i++ ) {
		if (i%2 == 1) {
			pieces[i] = data[pieces[i]];
		}
	}
	return pieces.join('');
}

It simply looks for variables in curly brackets and replaces them with values from a dictionary (or associative array).

I was going to add looping capabilities, but found I was ok doing the looping in javascript - that is, instead of having the loop in the html template, I'd create small html snippets that I would render in via a javascript loop and insert into the document.

Sample usage:

html:


<p id="something">Hello {name}, I wish you would {verb}.</p>

javscript:


render($('#something').html(), {name: 'Joe', verb: 'disappear' } );

So to replace the text with the rendered version:


$('#something').html( render($('#something').html(), {name: 'Joe', verb: 'disappear' } ) );

Finding and Fixing Slow MySQL Queries

Notes to self, for future reference.

Edit /etc/mysql/my.cnf . Uncomment the following lines:

log_slow_queries        = /var/log/mysql/mysql-slow.log
long_query_time = 2
log-queries-not-using-indexes

This enables logging of slow queries and queries not making use of indexes.

Now tail -f the mysql-slow.log file. You’ll see the slow and non-index-using queries.

Grab a query that you’d like to examine. Open a mysql shell and run “explain” on it:

explain your_query_here;

You’ll see output that looks like:

+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table               | type | possible_keys | key  | key_len | ref  | rows | Extra       |
+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+
|  1 | SIMPLE      | some_table          | ALL  | NULL          | NULL | NULL    | NULL |  166 | Using where |
+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+

Look at the rows and key fields in particular. rows shows how many rows were examined for query – you don’t want to see a high number. If you’re not using an index you may be doing a full-table-scan, examining every single row to find the value you’re looking for.

key shows which index, if any, was used. If you see NULL then no index was used.

To make the query go faster you may need an index. Look at the query and see what your’e selecting based on, and then create the corresponding index. For example, if we’re doing the selection based on the “myfield” field, you could create the index:

CREATE INDEX myapp_mytable_myfield_idx on myapp_mytable(myfield);

Once you create the index you should see that query no longer appearing in the slow query log.

Rinse and repeat for other queries.

Next Page »