My cousing send me this funny link. I got 6/10 :p
Entries from May 2007 ↓
programmer language invertor or serial killer
May 29th, 2007 — Uncategorized
ClockTicker.py vs ClockTicket.java
May 23rd, 2007 — java, python, programming
Some people think that when scripting language abocates say “less code” is because they are lazy and that they are sacrificing performance over code. This article plans to counterpoint that with a small python/java program.
A little background first. We are working on a little project in which the server is written in python and we’ll have several clients (including one J2ME), also one of the people involve knows nothing about python. Anyway one of the proposals for server-client interaction is having the client pull every X seconds for updates. So I through of an algorithm for making this a bit more intelligent than just setting X to some value. The algorithm itself is very simple. it keeps track of the last Y plays, actually of the time they took, and then using a simple average calculation it will try to guess the next poll time. So basically if it’s a fast game (each player will play their turn fast) then the updates will be more frequent. it will also have a min poll time so clients won’t update way too often, and of course the server will have a timeout but that’s outside of the scope.
Below implementations written in python and java.
warning: sorry for the small code I’m still looking for a decent code highlighter for wordpress.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
public class ClockTicker
{
private ArrayList data;
private final int MIN;
private final int SIZE;
public ClockTicker()
{
//this(10,20)
this.SIZE=20;
this.MIN=10;
data = new ArrayList(this.SIZE);
}
public ClockTicker(int min, int size)
{
this.MIN=min;
this.SIZE=size;
data = new ArrayList(size);
}
//not going to waste my time on the other 2 constructors
public void add(Float item)
{
if (data.size() == this.SIZE)
data.remove(data.size()-1);
data.add(0,item);
}
public float next()
{
float sum = 0;
Iterator i = data.iterator();
while(i.hasNext())
sum+=(Float)i.next();
float ave = sum/data.size();
return Math.min(MIN,ave);
}
public int len()
{
return data.size();
}
public static void main(String args[])
{
ClockTicker clock = new ClockTicker();
Random random = new Random();//or could have used (float)Math.random(), this seems less ugly
for (int i = 0;i<50;i++)
{
float value = random.nextFloat();
clock.add(value);
System.out.printf(”%s,%s,%sn”,value,clock.next(),clock.len());
}
}
}
class ClockTicker():
def __init__(self,MIN=10,SIZE=20):
self.data=[]
self.MIN=MIN
self.SIZE=SIZE
def add(self,item):
if len(self.data) == self.SIZE:
self.data.pop()
self.data.insert(0,item)
def next(self):
return min(self.MIN,sum(self.data)/len(self.data))
import random
clock=ClockTicker()
for i in range(50):
value=random.random()
clock.add(value)
print value,clock.next(),len(clock.data)
python total of 19 lines, and just 11 for the ClockTicker
java total of 55 lines and 39 for the ClockTicket class, but lets be fair I use the { in a new line (hi k&r fanatics) those don’t count. so it’s -1 line for each method and class. that leaves us with.
java K&R total of 47 lines and 33 for ClockTicket.
That means the python code is close 66% shorter then the java counterpart. One thing I should point out is that I wrote the python code first and the java one is a port but if you look at the java code, it follows java conventions and IMO it’s a fair competitor.
1. lossy data types, this is probably the most important one when I was writing the java code for some reason I wrote public void add(int item) and I didn’t notice that until the ave calculation in which the result was a float, which made me saw my mistake that I actually needed a bigger number to store time deltas, even worst I forgot that the time measured since epoch was stored in a long not a float. Anyway the python code works with int,floats,doubles,probably even strings. In the java counterpart I’ll probably have to write one class for each different datatype or just handle them in the same class with method overloading.
2. default parameters: the python’s init method
def __init__(self,MIN=10,SIZE=20)
is equivalent in java to
public ClockTicker()
public ClockTicker(int min, int size)
public ClockTicker(int size)
public ClockTicker(int min)
lets leave the fact that the last two won’t compile and think of all the boilerplate code that needs to be written just to have different ways to create a constructor. in java it can be minimized with calls to this() but that is at least 3 lines of code per constructor and a couple of curses from whoever is following that code. So we are looking at at least 10 more lines to achieve the same functionality.
3. named parameters: Back to the last two constructors issue. In java it will have to either be an ugly hack inside the two constructor parameter that if you call it as ClockTicker(null,size) min will be set to default. Or an even uglier one like ClockTicker(int minOrSize) and it will guess what you are passing in. But what most sane java programmers will do is something like ClockTicker c= new ClockTicker(); c.setMin(); or c.setSize(); which means adding even more lines of code and lets not get into the issue of fixing setSize so it won’t eat already present data. in python you just do what you need ClockTicker(MIN=100) or ClockTicker(SIZE=10) and done.
4. lists,dicts,etc as native data types and not API:
This is not really a feature that will directly make the size of the code smaller, but the fact that they are fundamental data types makes the developers of the std. api use them more often. Therefore functions like sum,min and len are prepared to handle Collections of data while in the Java counterpart they need to be hand coded outside of the std. api. Which is what is happening in the next method.
5. the fake access control (public,private,etc.)
One of the first things a good java programmer learns is to make class variables private and provide methods to access them,
• this is because setters should make sure the Object don’t gets corrupted.
• changes in the internals of a class will not affect client code.
• provide a clean API
• provide security of the object
Now in practice most setters don’t check anything, noone changes the name of a variable inside the class and if they do they normally do not keep the old setter/getter pointing to the new variable, until they compile everything crashes and they go back either in the name change or readd the old setter/getter pointing at the new name. About the clean API lets suggest an alternative lets say all “private” methods start with a symbol and and by convention (something the java crowd loves) lets say that symbol is _ . So in the event that you call a method that starts with _ it will crash with an access error? hell no if you really need my private method by all means use it, now don’t come crying to me when I break your code because I changed my private stuff, fair enough right? now think of all the setters and getter that are out there. All those millions of lame, useless lines of code, waiting to be strip out of existence to make tarballs,binaries, ISOs, backups, internet transfers and compile times smaller. ohh and about security just use reflection like this or this
6. primitives issue, this is more a language flaw in java than a real advantage in LOC. We have to admit that with autoboxing it makes code smaller, although official documentation states autoboxing is slow. Therefore this is not the optimal solution to fix the headaches of working with collections and primitives
7. And just to mess around with some people, time(1) says this
for the python code
real 0m0.083s
user 0m0.040s
sys 0m0.008s
and for the java code
real 0m0.117s
user 0m0.068s
sys 0m0.012s
so in this particular case python is faster, and just in case you where wondering neither program is optimized. They where both written for readability since after all the idea of this was to show a way the polling could be implemented.
Overall the python code is more readable, has more functionality, has less LOC and is faster
life goes on
May 23rd, 2007 — tiquicia, life
It’s amazing how time flies I just when thru some fotos and found out one friend had a child which seems to be 3yrs old, another has been walking around the world, another has a boyfriend that plays in a rock band (or something like that), an old girlfriend is very happy with her new guy, and ended up becomming one of my best friends best friend, ahhh I knew that was going to happen. The same rocker girl friend graduated from university, a “el toca” todavia le dicen asi, and he is in the photos of another guy that found a girl friend that finally got him :p another one is in the other side of the world. And I have no idea what the rest of them are up to. Another is a teacher, well I was expecting that anyway :p
and I wasn’t there …
Now this impress me it’s the kind of thing that always impress, but when you know who is in the picture it’s double that.
Heroes finale
May 22nd, 2007 — Uncategorized
It sucks really
Disappointments
• not even a decent fight
• not even fireworks or special powers
Lets see all the stupid things
• Peter didn’t flew away alone, that was the obvious thing right? but no he couldn’t control his power right. lame…
• if it was really a nuke with the close explosion they will all be dead anyway.
• The logical way to end it was for Nathan and Peter to fly away, sure lets kill 2 guys instead of one. Even worst they didn’t even took Cyler, don’t you remember Odessa? he fall from 5 floors and ran away, so
• Why peter could control it before and not now, anger? oh that’s bullshit.
• Nathan takes off with Peter
Overall it’s just another filler. Think about it, it’s all the same, the people from the future are all still alive. Cylar will later kill DL, the morphing chic et all. The scar will be later (remember peter can’t die), Nathan is dead after all he had a crappy power. So Cylar or the morphing chic will take his place.
but not all is lost we know the name of Mr. Bennet
Gas cars are not that crazy?
May 22nd, 2007 — Uncategorized
Last night after the disaster of heroes finale I saw this “news” on TV, according to them gas is 90% the price of gass how about here in DR?
Now it also says that converting a car is about 5000 dollars thats 17241 galons. That’s 862 refills of my 20gls car. and I’m filling the tank up 2-3 times a month so that’s just doesn’t covers it. what are they thinking??
WS* is overarchitected
May 22nd, 2007 — Uncategorized
Ok we already knew that but take a look at this article. I just can’t believe so many things could be made out of something that simple.
A great vi/vim article.
May 22nd, 2007 — work, programming
A very nice article on vi/vim
The editing commands he shows are great. I guess what we need is more resources like this. Most vi/vim manuals out there focus on showing what each feature is and what it can do they are well … boring. With this article half way thru it I was writing the things in my vim and being impress for example I had no idea such thing as ]] existed and I knew about ‘c’ also about ‘%’ but “c%” is just amazing!
videos around 19apr
May 20th, 2007 — videos, Uncategorized
another set of links… yes I know they are old even the title is old. But I have been slacking to install this nice plugin.
A nice animation by
Hockey meats baseball, funny
Lala the penguin
A Very clever Drunk guy
vote for the worst guy
* mid management
May 15th, 2007 — work in air quotes, Uncategorized
I learn this trick today, please replace any instance of * with the correct assort of words.
So it turns out they are at it again. The * mid-management has demanded a new set of *. Now the interesting thing about this set of *, is that it’s so amorfous that it can fit everything that is “wrong” in it. It is supposed to be a security isssue, but when that fails is a bad-usage-of-resources * and if that fails then it’s the way things are done in <insert place you have never and will probable never be>.
It always starts with it’s a security issue, we must protect customers data. This way the manage to block all USB, CDROM, and peripetals in general. Of course this was because people where downloading torrents and burning them to go home. Since people started just watching stuff locally they are now on to kill the streaming. First it was by request but since a failed attempt to get move benefits from the “leaders of the real workers”, new measures needed to be taken by the * mid-management. The new rule involve adding a ban (ip/dns block) on mayor bandwith sites, yes they are talking about youtube, now when confronted with the fact that google video hosts a lot of very interesting talks like python 3000, anatomy of a debian package or conferences like javaOne, then the * switch over to the bad-usage-of-resources. I believe a little NDA stops me from telling you that is NOT an issue, because there they have the best price in the market. Any we accept the * claim that we should cut down on bandwidth usage, and then come the next one because some people where playing cards, OMG cards! people where playing cards! which made me wonder how is this a bad usage of resources or a security issue, well remember mid-*-management things of people as assets, employees are things they own, which is sad because that is all they are going to own. yes, yes I know they don’t but when your stuck with a loan for your house and/or kids it’s a little hard to not believe they own ur *.
Now the sad part of the story is that the real losers are the * at mid-management. Lets examine how they got there. They are good with numbers but not great, they are good with people but not the best, they can run a deparment but not a company and the most important part they probably got their promotion because they where high enough so they couldn’t be fired or for someone reason someone put them there. And the really sad part is that most think that being at the top is when they will finally rest, when you will finally stop * up and * down.
So the * mid management now wants people to get there at 8 leave at 5 in the mean time touch their computers for work related stuff and then sit and wait without doing anything, which is ok by mid-management standards (after all they only do what they learn) but they are forgetting the most important part of their work they they * up upper management they don’t give a * how much was paid in bandwidth (yes “free” one) they don’t care if someone is playing cards or chess or not being there half the day. Uppermanagement cares about 2 things how much we made and how much of that is profit. And what stupid mid management does not undestand is that the current state of affairs is what keeps the first happening, now of course you can make the % of profit go up by appliying all the * rules to reduce cost but then you are making the first thing harder to happen, and I’m certain that anyone from uppermanagement will fire your * if you go and tell him we increase our % of profit by 40% but we reduced our income by 50% because the measures we took made all our good employees leave the company.
Now the question is how to fight back? and yes you have to fight back because mid-management is stupid enough not to realize that the way things are is what makes the company good.
The first postmodern programming language
May 14th, 2007 — perl, programming
I just read this great article about postmodernist, well actually about perl. In fact it’s about a lot of things, which is why the article itself is postmodern
On a side note I love this quote: ” I have to be honest here. I’m with Linus–I personally want to take over the world. I want to take over the world because I’m an egomaniac. A nice sort of egomaniac, an egomaniac moderated by belief in the value of humility, but an egomaniac nonetheless.”
enjoy the reading.