Archive for the ‘Programming’ Category

How to change frequency on CakePHP’s describe query

Posted on November 15th, 2008 in CakePHP, Php, Programming | No Comments »

By default if you set the debug to 0 in your core.php the frequency of executing a describe query is 999 days, but if your developing your application the duration is 10 sections, meaning every 10 sections it would ask your database to describe the tables that you need in your controller. To change the 10 sections to a higher value you could do this.

open configure.php in cake/libs/
locate the function __loadBootstrap
inside this function locate the following
if (Configure::read() >= 1) {
$duration = '+10 seconds';
} else {
$duration = '+999 days';
}

Change the ‘+10 seconds’ according to your requirement, say you want to describe a query every 1 minute, you would change it to
if (Configure::read() >= 1) {
$duration = '+1 minute';
} else {
$duration = '+999 days';
}

Get Total count from datastore in app engine

Posted on November 3rd, 2008 in App Engine, Google, Programming | No Comments »

Before you continue to read the post, i have to warn you that this is not the best way of getting the total count and there would be a possible inaccuracy and may not be scalable (http://groups.google.com/group/google-appengine/browse_thread/thread/3abb2868ab5fc304?pli=1), please use shared counter as what david suggested.

Here is a way on how to get the total count from a datastore in app engine, this uses memcache to cache the count for one minute (you can change this by passing an argument), i’m not sure but this seems to be better coz it doesn’t need you to do some writing on datastore.

from google.appengine.api import memcache
def get_total_count(self,model,cacheTime = 60,maxNumber = 10):
cacheName = model.kind() + “_totalCount”
total = memcache.get(cacheName)
if total == None:
index = 0
currentTotal = total = len(model.all().fetch(maxNumber,0 ))
while currentTotal == maxNumber:
index += 1
currentTotal = len(model.all().fetch(maxNumber,maxNumber * index))
total += currentTotal
memcache.add(cacheName, total, cacheTime)
return total

To call it on your get function:
self.response.out.write(str(get_total_count(self,<your model>))
or
self.response.out.write(str(get_total_count(self,<your model>,3600,1000))

* Remember that the maxNumber argument can only support upto 1000 and i encourage you to set it to 1000 if your datastore is big

Explanation to the codes:
cacheName = model.kind() + “_totalCount”
Create a variable and name it as our model’s name with an underscore totalCount (you can change this one)

total = memcache.get(cacheName)
if total == None:
index = 0

Change if there is already a cached value, if not set a index variable to 0 and ….

currentTotal = total = len(model.all().fetch(maxNumber,0 ))
Set the currentTotal and total variable to the len of a fetched row limit by maxNumber starting with the row 0

while currentTotal == maxNumber:
index += 1
currentTotal = len(model.all().fetch(maxNumber,maxNumber * index))
total += currentTotal

Loop until the currentTotal is not equal to the maxNumber and add the currentTotal to the total variable and add one to the index. Why do a while loop on currentTotal == maxNumber? Since we set a upper limit on the maximum number of rows we could fetch, it logically means that if we loop with the upper limit it would come to a point where it would never be equal to that limit.

memcache.add(cacheName, total, cacheTime)
Cache our total

Hope i’m right and it helps :)

CamelCase in Python / Django

Posted on October 30th, 2008 in App Engine, Programming | No Comments »

Here is a small script for making CamelCase string in python

import re
from string import capitalize
def camelcase(value):
return "".join([capitalize(w) for w in re.split(re.compile("[\W_]*”), value)])

in django just add
@register.filter

making it
import re
from string import capitalize
@register.filter
def camelcase(value):
return "".join([capitalize(w) for w in re.split(re.compile("[\W_]*”), value)])

Hope it help.

Searching tv shows in chinese video sites

Posted on October 29th, 2008 in Hacks, Other | No Comments »

Say you want to watch your favorite tv shows online, (hulu is not available in other place, those people think that the only country in the world is US), and you really want to watch it. You can go to Chinese video sites like youku.com and search for the shows that you want to watch, all you have to do is locate the search box and start searching. But how?

Usually they would name tv shows like heroes 第三季 07, or heroes第三季 第07集, now what does this mean? The first Chinese words, 第三季, means the 3rd quarter or the 3rd season, then the 2nd Chinese words, 第07集, means the 7th part or the 7th article or 7th set. Now what if i want to watch the 2nd episode in season 2? You would search something like ‘heroes 第二季 第2集’ or ‘heroes 第二季 第二集’ .

If we put it into a mathematical formula it should be something like
let search = x 第y季 第z集
where x is your favorite tv shows
y is the season number
z is the episode number

And here are the numbers for you to substitute from
1 = 一
2 = 二
3 = 三
4 = 四
5 = 五
6 = 六
7 = 七
8 = 八
9 = 九
10 = 十

So getting heroes season 1 ep 9 is like
search = heroes 第一季 第九集

What about numbers getter than ten? To get numbers beyond 10 you have to mix them in the formula
let num = x十y (the second character is not a plus but the Chinese ten 十)
where x be the multiplier of ten except 1, you will understand why except one later on
where y is from one to nine, then y would be added to the results of x十

Say you want to search for the 25th, it should be
二十五
Why? x is the multiplier then 2(10), 二十, is 20 then add 5,五, then its equal to 25, 二十五
Thirty four would be 三十四
Forty nine would be 四十九

You could simple rephase the formula to
let num = (x multiply to 10) plus y

Now from 11 to 19, you don’t need to add 一 to the front coz its the same with or without it.
And so 18 would be 十八
Fifteen would be 十五

If you find this way to complicated then you can use Google Translate, btw i’m not Chinese, i just studied in Hong Kong when i was small so i do know their language a bit.

Hope it helps and lets all hope that big media company would realize that there people outside US.

Why you might hate the template system in django

Posted on October 26th, 2008 in Programming | 2 Comments »

Okay first of all I did try hard to love it but there are just so many annoying things about it that i really don’t like and here are some of them:

1) They have so many if statement that actually brakes the beauty of python, so you have if, ifchange, ifequal, and ifnotequal. Instead of just doing something like
{% if thisVariable == thatVariable %}

2) You cannot pass multiple arguments to custom filter, you can only pass 1 or 2 arguments, i don’t know what they were thinking when they decided this, but i hope they fix this quickly coz not all of time you only have to pass 1 or 2 arguments. (http://code.djangoproject.com/ticket/1199)

3) Templates are so strict that you cannot use underscore on an object. While this is good in terms of security and design, it adds up to your production time. Solving this would bring us to the next number

4) You need to use filter even if you don’t like to, say you just like to compare 2 numbers, ideally if #1 would be followed then its {% if a > b %} but nope, you have to do it on your custom filter. See everything that is not on the build-in filters of django you have to do it on your own even if that feature is part of python.

5) You cannot have 0 arguments on filters, say you just want to check if something is logged in or not, you cannot call the filter with {{ is_login }} but you need to pass a dummy argument like {{ 1|is_login }}

Now i know im just new with django but this stuff makes me feel that i’m not using python anymore, i say this when compared it to other templating system like smarty. Its a template engine but somehow you still feel that your using php. I hope django fix their template system

Alternate row colors in App Engine

Posted on October 20th, 2008 in App Engine, Google, Programming | No Comments »

You have a senario where you need to have alternating colors in each rows of data in app engine or django, how can you achieve this? Here is a simple solution on doing it (This took me more than 30 mins to find out the solution coz most of the time they will give you php’s solution on alternating rows)
{% for video in videos %}
<div class="row {% cycle odd,even %}">
{{ video.title }}
<div class="youtubeLink">
<a href="{{ video.youtube_id }}">
{{ video.youtube_id }}
</a>
</div>
</div>
{% endfor %}

The main solution is this code
{% cycle odd,even %}

What this do is that it cycles around each row and returns the right index (odd or even). And with this function you are not bound to just 2 selections, if you want more you could just do something like
{% cycle one,two,three,four %}

Hope this helps.

Zend Framework inside CakePHP 1.2

Posted on October 12th, 2008 in Php, Programming | 1 Comment »

Zend Framework’s beauty is it’s range of services or web API, like Delicious, Flickr, GData and a lot more. build into it by default. CakePHP’s beauty is that you can extend it, extend it way up to the point where you can import other framework and make use of that framework’s feature. Having said that, Zend inside CakePHP would be totally awesome. The inspiration behind was this blog post http://britg.com/2008/07/07/using-the-zend-framework-in-cakephp/ but i will show you how to use the flickr service.

First download the minimal version of Zend Framework (It will ask you 2-3 times on what you want to download and will ask for you to login/register and i think this is insane). Anyway after downloading extract the files to your folder so that you will have a folder structure like
vendors
---Zend
------Everything that is inside the folder library/Zend

After that, as what britg.com said about the config file, import the following lines in core.php
ini_set('include_path',ini_get('include_path') . PATH_SEPARATOR . '/path/to/vendors/');

Alibris

Then you’re ready to use Zend’s feature in cake.
function getArtistImage($id){
$this->Artist->id = $artistId;
$artistData = $this->Artist->read();
if($artistData){
App::import("vendor",'Zend_Service_Flickr',array("file"=>'Zend/Service/Flickr.php'));
$flickr = new Zend_Service_Flickr('your flickr api key');
$artistName = $artistData['Artist']['name'];
$results = $flickr->tagSearch($artistName);
$this->set(compact(”results”,”artistName”));
}
}

Then in your view
<? foreach ($results as $result): ?>
<img src="<?=$result->Small->uri;?>"
height="<?=$result->Small->height;?>" width="<?=$result->Small->width;?>"
>
<? endforeach; ?>

To further explain a bit
App::import(”vendor”,’Zend_Service_Flickr’,array(”file”=>’Zend/Service/Flickr.php’));
– this imported the flickr api

$flickr = new Zend_Service_Flickr(’your flickr api key’);
– this creates a new instance of the flickr service

$artistName = $artistData['Artist']['name'];
$results = $flickr->tagSearch($artistName);
– this searches the artist’s name on the tags on flickr

Here is an example of this post
http://monmonja.com/music/lyrics/flickr/87