SHA256 Checksum on Mac OS X

Yesterday I managed to figure out how to generate a SHA256 checksum of a file on Mac OS X, so I added this line to my ~/.bashrc:

alias sha256='shasum -a 256' # "sha256 myfile" to use
Posted in Development | 2 Comments

Facebook Like integration

So you have a Page on Facebook, and you wish to tie it to your own website?

Example: Zolomon’s Facebook Page already have 235 likes. But zolomon.com only got 20 likes. So, what do you do? You can’t add the 20 likes to the Page, not the other way around either (as far as I can tell!)

This is what you do.
STEP 1: You go to: http://developers.facebook.com/docs/reference/plugins/like and generate the code for your Like button, insert it where you want it into your HTML – NOTE: the URL for the href-attribute should be the URL to your Facebook Page! Like: http://www.facebook.com/#!/pages/Leonard-Gren-Photography/128745703830488.

STEP 2: Then, further down the page you generate your meta-tags, insert this between the head-tags.

STEP 3: You go to http://developers.facebook.com/docs/reference/javascript/ and steal that juicy asynchronous call to load that lovely Facebook SDK for JavaScript!

STEP 4: The last thing to do, add this into your HTML-element: xmlns=”http://www.w3.org/1999/xhtml” xmlns:fb=”http://www.facebook.com/2008/fbml”

Posted in Development, Webdesign, webdev | Leave a comment

Watchdog @ github

(Really tired at the time of writing – if you see any obvious improvements, by all means, let me know!)

Recently I’ve been working double time – and to cram even more productivity into my schedule I’ve moved from developing on my PC to my MAC. I have also made the transition from manual .css-editing to the use of www.sass-lang.com which is a real time-saver! The beauty with the tool, Sass/scss (Sassy-CSS), is that it compiles your CSS on the fly as soon as it notices a change!

(EDIT: Okay, so lvh just informed me about Less and it kind of wins over Sass if you don’t mind JavaScript! It actually seems like the future, makes my script feel like all for nothing! *sheds a tear*)

Usually I just used FileZilla and my text editor of choice to upload any changes I did. But now, that wasn’t immediately possible. So I thought, since I’m already trying to become better at Python, that I would try and script this!

My thoughts went something like the following:

  1. Write some more Sassy CSS
  2. Wait for the new css to generate
  3. Upload the new/modified css to my specified ftp
  4. Refresh website
  5. PROFIT!

So high and low, I searched and searched, and IRC:ed and IRC:ed (#python@irc.freenode.net, gorakhargosh & lvh, word up!) – and finally (during my quest I found KQueue, pyinotify – both of which I dismissed due to lack for MAC support) I came across this lovely git (pun intended): https://github.com/gorakhargosh/watchdog (the creator is a totally rad chap!) that provides an awesome API for file based system events! For example; monitoring a directory recursively for file changes (added, deleted, modified, etc!) would be pure cake walk!

So I quickly hacked together (you can’t even imagine how much I learned in one evening – argparser, ConfigParser, ftplib – just to name a few!) this lovely little script (pure hax, but oh my how it works):

The watcher.py

import ConfigParser
import os
import time
import sys
import logging
import argparse

from ftplib import FTP
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

print "REMEMBER TO UPDATE CONFIG FILE AND USE CORRECT [SECTION]"

logging.basicConfig(level=logging.DEBUG)

class MyEventHandler(FileSystemEventHandler):
    """Custom EventHandler"""
    def catch_all_handler(self, event):
        logging.debug(event)

    def on_moved(self, event):
        self.catch_all_handler(event)

    def on_created(self, event):
        self.catch_all_handler(event)

    def on_deleted(self, event):
        self.catch_all_handler(event)

    def on_modified(self, event):
        global ext
        self.catch_all_handler(event)
        fileextension = os.path.splitext(event.src_path)[-1]
        if fileextension in extensions.split(';'):
            ftpLogin()
            ftpGoTo(destination)
            ftpUpload(event.src_path)

parser = argparse.ArgumentParser(description='Automatically uploads watched files to specified ftp.')
parser.add_argument('-dir', help='The directory to watch')
parser.add_argument('-cfg', help='The section to use')
args = parser.parse_args()

path = args.dir
print "Current path:", path

# Read config
filename = args.cfg
config = ConfigParser.SafeConfigParser()
config.read(filename)
print "Current config:", filename

# Fetch config data for this project
host = config.get('zolomon.com', 'host')
port = config.get('zolomon.com', 'port')
username = config.get('zolomon.com', 'username')
password = config.get('zolomon.com', 'password')
directory = config.get('zolomon.com', 'dir')
files = config.get('zolomon.com', 'file')
destination = config.get('zolomon.com', 'destination')
extensions = config.get('zolomon.com', 'extensions')

ftp = None # our FTP variable.. It's global, need to learn how to unuglify this!

def ftpLogin():
    """Log in"""
    global ftp
    try:
        ftp = FTP(host, username, password)
        print "logged in"
    except (socket.error, socket.gaierror), e:
        print 'ERROR: cannot login anonymously'
        ftp.quit()
        exit()
        print '*** Logged in as', username

def ftpGoTo(path):
    """Go to this path"""
    global ftp
    try:
        ftp.cwd(path) # Change working directory...
        print "changed path"
    except ftplib.error_perm:
        print 'ERROR: cannot CD to "%s"' % destination
        ftp.quit()
        exit()
        print '*** Changed dir to "%s"' % ftp.pwd()

def ftpUpload(file):
    """Upload this file"""
    global ftp
    if os.path.exists(file):
        ext = os.path.splitext(file)[1]
        try:
            if ext in (".css", ".htm", ".html", ".php"):
                ftp.storlines("STOR " + destination + file.split('/')[-1], open(file))
            else:
                # If it's something else, it's probably a binary file
                ftp.storbinary("STOR " + destination + file.split('/')[-1], open(file, "rb"), 1024)
            print "uploaded %s" % file
        except ftplib.error_perm:
            print 'Error: cannot store file "%s"' % file
            os.unlink(directory + file)
        else:
            print '*** Uploaded "%s"' % file

event_handler = MyEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
    ftp.quit()
observer.join()

And to use it I created a tiny app to create a config file; behold – the new_config.py!

import ConfigParser

config = ConfigParser.RawConfigParser()

config.add_section('zolomon.com') # section name (I can just copy this for every site!)
config.set('zolomon.com', 'host', 'ftp.hosturl.com') # ftp host
config.set('zolomon.com', 'port', '21') # ftp port
config.set('zolomon.com', 'username', 'EnterHackerAlias') # zolomon
config.set('zolomon.com', 'password', 'AristotlesWasAHipster') # He was!
config.set('zolomon.com', 'dir', '/Users/zolomon/Documents/code/web/kettis/') # Same as below
config.set('zolomon.com', 'file', 'style.css;index.php') # Too tired to remember if I actually use these :P
config.set('zolomon.com', 'destination', '/public_html/web/kettis/') # The destination for uploads
config.set('zolomon.com', 'extensions', '.css;.php;.html;.htm') # Extensions to upload into 'destination'

# write config to file
filename = 'zolomon.com.cfg'
with open(filename, 'wb') as configfile:
    config.write(configfile)
Posted in Development, webdev | 4 Comments

I’m flattrd!

Today I woke up to a nice message over at Facebook saying that I’ve been featured on Flattr.com!

Featured on Flattr.com

Posted in Misc | Leave a comment

Symphony of Science

Posted in Misc | Leave a comment

LottaDjossou.se

Just finished a new website for a client based on their own design, go check it out at lottadjossou.se! (flash warning)

Posted in Development, Webdesign | Leave a comment

Fyraartill.eu

Just finished another website to promote the new Swedish movie “Fyra år till, en komedi av Tova Magnusson”; http://fyraartill.eu
Template borrowed from the Smashing HTML5! article.

Fyra år till, en komedi av Tova Magnusson

Posted in Development, Misc, Webdesign | Leave a comment

Platon & Ceasar: A Divide & Conquer Task Manager

Today at work, the greatest idea ever was spawned inside my head.

Imagine a terribly complex problem that you have to solve. You have too much on your mind to cope with it all, but if you had a way of breaking the problem down into subtasks you might be able to handle it. That’s what I’m going to provide.

An easy way to break down tasks into manageable piece. Divide et impera .

Imagine the tree structure of an XML file. Root node is the main problem. Child nodes are subtasks.
Most often you only wish to see the big picture of a problem, less is more. How do you solve that? With a stack based system based. Nodes in all its glory!

Traversing a stack of subtasks will be much easier to work with, and will hide data not related to your current problem, a pleasant feature for the easily distracted.

What’s in it for me:

  • I get to play around with XML some more. Xpath – YAY!
  • Lovely custom user controls – GDI+ yumyumyum
  • Solving yet another problem
  • A way of becoming more productive – not for me, but for everyone else as well!
  • I’ll become a Git, bit by bit - pun intended

More information will be posted soon (with images)!

Posted in Development | Leave a comment

New programming jargon coined

Breakdancing, when you set break points all over the place.

Posted in Development, Misc | Tagged | Leave a comment

Comparing colours

Today I ran into an interesting problem – how should I compare two colors to tell which one is darker than the other? I managed to find a very nice solution via Google!

public int Compare(Color x, Color y)
{
	if (x.ToArgb() == y.ToArgb())
		return 0;
	float hx, hy, sx, sy, bx, by;

	// get saturation values
	sx = x.GetSaturation();
	sy = y.GetSaturation();
	// get hue values
	hx = x.GetHue();
	hy = y.GetHue();
	// get brightness values
	bx = x.GetBrightness();
	by = y.GetBrightness();

	// determine order
	// 1 : hue
	if (hx < hy)
		return -1;
	else if (hx > hy)
		return 1;
	else
	{
		// 2 : saturation
		if (sx < sy)
			return -1;
		else if (sx > sy)
			return 1;
		else
		{
			// 3 : brightness
			if (bx < by)
				return -1;
			else if (bx > by)
				return 1;
			else
				return 0;
		}
	}
}
Posted in Development | 5 Comments