## Monday, June 22, 2009

### How to display pretty code in Blogger

Posted by Danny Tarlow
I've been posting more code directly to the blog lately, so I figured it was time to figure out how to make it look nicer. Thanks to Alex Gorbatchev and techqi, this should be pretty easy.

Here's a test displaying the ultra-famous 24 line Affinity Propagation MATLAB implementation:
```N=size(S,1); A=zeros(N,N); R=zeros(N,N); % Initialize messages
S=S+(eps*S+realmin*100).*rand(N,N); % Remove degeneracies
lam=0.5; % Set damping factor
for iter=1:100
% Compute responsibilities
Rold=R;
AS=A+S; [Y,I]=max(AS,[],2);
for i=1:N AS(i,I(i))=-realmax; end;
[Y2,I2]=max(AS,[],2);
R=S-repmat(Y,[1,N]);
for i=1:N R(i,I(i))=S(i,I(i))-Y2(i); end;
R=(1-lam)*R+lam*Rold; % Dampen responsibilities

% Compute availabilities
Aold=A;
Rp=max(R,0); for k=1:N Rp(k,k)=R(k,k); end;
A=repmat(sum(Rp,1),[N,1])-Rp;
dA=diag(A); A=min(A,0); for k=1:N A(k,k)=dA(k); end;
A=(1-lam)*A+lam*Aold; % Dampen availabilities
end;
E=R+A; % Pseudomarginals
I=find(diag(E)>0); K=length(I); % Indices of exemplars
[tmp c]=max(S(:,I),[],2); c(I)=1:K; idx=I(c); % Assignments
```

Edit: not working yet

Edit: working, but I had to change global line break settings to not convert line breaks. Now all my old posts have the paragraphs messed up.

Edit: I made a couple modifications.
• I moved the CSS for syntaxhighlighter directly into my Blogger template so that it loads faster.
• I changed the color of the line to the left of the text from green to something that matches my color scheme a bit better

Samuel said...

You can also use a syntax highlighter like Pygments. In the following article I demonstrate the usage of this great tool : http://gissolved.blogspot.com/2009/05/python-toolbox-2-pygments.html

Danny Tarlow said...

This looks like a cool tool to use if you're running the backend of a website, but I kind of like the convenience of javascript doing all the parsing -- I'm not sure I'd want to run my code through a command line tool every time I wanted to post or modify it on the blog.

Kevin said...

Hmm another solution is what I have done for my blogpost here