PHP Date Time

May 11, 2008 § Leave a comment

is more or less annoying. Before fanbois comment me to oblivion, let me explain why.

DateTime and DateTimeZone are objects. They can be created using new DateTime() and new DateTimeZone() calls.

Why is it not documented anywhere? Instead, the documentation points to global function calls.

The global function for new DateTime is date_create(), while global function for new DateTimeZone is timezone_open(). How intuitive.

Talk about intuitiveness. date() does not return DateTime object. It returns string, but of course, that’s how it always be.

Now let’s talk about timezone_open(…). If you pass an invalid parameter, it WILL return false, but, it will also throw:

Warning: timezone_open() [function.timezone_open]: Unknown or bad timezone

Damn, that behavior is reported here.

More about timezone, did you know that you can call setTimezone() on DateTime object? I found it out by lucky guess. Where’s that documented on php.net?

Finally, when calling dateObject->format(‘U’), I was expecting to get “Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)” –> pulled from php.net. But I didn’t get such results.

The seconds returned was not based on UTC timezone. It was based on the default php.ini, which was local timezone (PST).

So make sure before formatting to UTC, you call:

dateObject->setTimezone(new DateTimeZone(‘UTC’)) or

dateObject->setTimezone(timezone_open(‘UTC’)) or

don’t even bother creating object, just use: gmmktime()

Have fun with DateTime!

References:

Advertisements

cherrypy.subscribe or cherrypy.on_start or cherrypy.on_stop

February 29, 2008 § Leave a comment

Sometimes, on your web application, there are other processes that happen independently from typical HTTP requests.

The type of such processes can be:

  • daemon / cron.
  • setup / deployment script.

If such processes are not registered to cherrypy, cherrypy might not be able to auto-reload properly when server-side codes changed. In general it is nice to have those processes starting/stopping properly relative to the web server (cherrypy in this case).

In cherrypy 3.1, processes like those can be registered via callback using cherrypy.subscribe function. See below:

  • engine.subscribe(‘start’, callback).
  • engine.subscribe(‘stop’, callback).
  • engine.subscribe(‘start_thread’, callback).
  • engine.subscribe(‘stop_thread’, callback).

Above functions in cherrypy 3.0 are:

  • engine.on_start_engine_list.append(callback).
  • engine.on_stop_engine_list.append(callback).
  • engine.on_start_thread_list.append(callback).
  • engine.on_stop_thread_list.append(callback).

References:

Javascript: Array.sort()

February 20, 2008 § Leave a comment

What is it?

It is a global function that’s a built-in of Array object.

Syntax:

Array.sort(comparisonFunction);

How to use sort():

  • If sort function is being used without comparisonFunction parameter, the values inside array will first be converted into string, and sorted lexically.
  • If sort function is used with comparisonFunction, it must return either 1, 0, or -1 depending on the comparison.

Here is a sample of comparisonFunction:

function compare(a, b)

{

if ( a < b ) { return -1; }

else if ( a > b ) { return 1; }

else () { return 0; }

}

Reference:

http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:sort

TurboGears part 1: First Encounter

February 5, 2008 § Leave a comment

I’ve been reading TurboGears website, wiki, & FAQ for almost 2 weeks, now it’s about time to build something with it.

Below are steps I’ve done to have some sort of “Hello World” stuff.

Some Basic Pre-Assumptions

  • You have already installed Python
  • You will want to install easy_install. Read this for install instruction. Easy Install is like apt-get for Python modules.

Installation

  • Download tgsetup.py from TurboGears website. Then run the script by calling python tgsetup.py
  • The process above will install a whole bunch of TurboGears component such as:
    • Kid(think CakePHP’s thml or Rails’ rhtml)
    • CherryPy(think of WebServer)
  • SQLObject (think Rails ActiveRecord) is preferred by TurboGears, so we need to install it. In your command-line console, type: easy_install sqlobject.
  • When above are all finished, it’s time to create new project.

Creating New Project

  • TurboGears gives you tg-admin tool (just like Rails’ generate or CakePHP bake script), so let’s use it.
  • tg-admin is an interactive command-line tool which help you building some basic structure for your application.
  • When this process is finished, see if your project is runnable.

Run the Web Server, See if Your Project is Runnable

  • Inside your project directory, from command-line, type: python start-{your_project_name}.py
  • By default, the web server (which is CherryPy) is using port: 8080. If that’s being used, change the configuration, which I will tell you how below.

Changing the Configuration

  • The default configuration of TurboGears is pretty light weight, not quite real life setting. If you don’t like it, modify dev.cfg file.
  • Inside dev.cfg file, you can:
    • use MySQL instead of SQLLite
    • Change the port of your Web Server
    • and more…
  • Try restarting the server, see if your new configuration works.

Well, congratulation, you just created the structure for your next WEB 2.0 project!

In the next series, I will describe my adventure, using TurboGears, to build: Calculator! The next big thing in Web 2.0 world.

PHP annoyance: MySQL now() vs PHP time()

January 23, 2008 § 3 Comments

When your DBA is thinking differently than you, you might get:

MySQL

field: created_on

type: DATE

while, on PHP side:

$created_on = time();

Below is simple script that get rid of such annoyance.

From PHP to MySQL:

$created_on = date(‘Y-m-d H:i:s’, time());

From MySQL to PHP:

$query = “SELECT created_on FROM some_table WHERE id=1”;

$row = mysql_fetch_array(mysql_query($query));

$created_on = $row[‘created_on’]; //created_on from MySQL in DATE format

list($date, $time) = explode(‘ ‘, $created_on);

list($y, $m, $d) = explode(‘-‘, $date);

list($h, $i, $s) = explode(‘-‘, $time);

$created_on = mktime($h, $i, $s, $m, $d, $y); //created_on timestamp

Why Python?

January 20, 2008 § 3 Comments

Among other programming languages, why choose Python?

Let’s go over the basics first, these traits also exist in other programming languages:

  • Python is interpreted Programming Language. It is also a high-level programming language. Therefore, just like Ruby or Perl, Python is easy to learn and easy to get up to speed on sizable projects.
  • Python is also object-oriented language. But that’s nothing new, most modern programming languages are object-oriented anyway.

Naturally, readers will ask, if Python can only do what MY programming language already can… Why do I have to learn it? Below is my reasoning why… and hopefully readers will convert to Python 😛

1. Python does not have funky sigils or special system_call functions. The only one you have to memorize is: __someDefaultMethods__ By not having too many special characters, programmers spend less time browsing documentation or mailing list on Google.

2. Python tabbed indentation actually contributes to highly readable code. Readable code helps especially when you are juggling many different projects every week, it allows you to remember quickly what you did last time.

3. Python’s power and scalability is proven not hype.

4. For Back-end Programmers, Database Designer, and System Engineers:

  • Look at Twisted[1]. It is one kick ass networking library. It supports many networking protocols that allows building web servers, email, or chat easier.
  • Look at SQLAlchemy[2][3], I never seen ORM so powerful and yet so easy to learn.

5. For Application Developers:

  • Django is a complete out-of-the-box Web Framework. Their slogan — “For Perfectionists with deadlines”
  • TurboGear is also another awesome complete Web Framework solution. But I suggest readers wait until they included SQLAlchemy as their new database stack.

6. For Javascript Developers:

  • Look at Mochikit, It is a complete javascript framework that’s very Pythonic. Mochikit is still just Javascript, but have Python’s sense of elegance.

Below are quotes from Eric Raymond on why he likes Python:

— “In Python, I was actually dealing with an exceptionally good design. Most languages have so much friction and awkwardness built into their design that you learn most of their feature set long before your misstep rate drops anywhere near zero. Python was the first general-purpose language I’d ever used that reversed this process.

— “It (Python) is compact–you can hold its entire feature set (and at least a concept index of its libraries) in your head. C is a famously compact language. Perl is notoriously not;

— “What I really wanted was code that would analyze the shape and members of the initializer, query the class definitions themselves about their members, and then adjust itself to impedance-match the two sets… …This kind of thing is called metaclass hacking… …Thirty-two lines, counting comments… …Brace yourself: this code only took me about ninety minutes to write—and it worked correctly the first time I ran it.

— “So the real punchline of the story is this: weeks and months after writing fetchmailconf, I could still read the fetchmailconf code…

Summary:

Hopefully I provided enough examples on why Python can be your next favorite programming language. Programming in Python is fun indeed.

Resources:

  1. http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions
  2. http://www.sqlalchemy.org/
  3. http://en.wikipedia.org/wiki/SQLAlchemy
  4. If you are new in Programming, this E-book can help
  5. Why use Python in Windows XP?
  6. Python Doc – String
  7. Python Doc – Common OS path manipulation
  8. If you are familiar with apt-get, Python have something similar for its modules: easy_install

What Others Said about Why Python:

Ruby: @, @@, !, ?, #, and {}

January 14, 2008 § Leave a comment

This is post is intended to be a quick reference page for basic ruby consumption.

What is @

It is a sigil for instance variable. That means, the variable scope is within an instance of a class.

What is @@

It is a sigil for class variable. When defined in a class, duh,  the value is shared by all of its instances.

What is !

Ruby allows its function namespace to have exclamation point(!). When a function is declared with (!) sign, it means that the function will overwrite the caller’s value. For example:

test = “awesome”

test.reverse!

puts test # test value is: emosewa


What is ?

Just like exclamation point, question mark is allowed in Ruby’s function namespace. When a function is ended with (?), the function is expected to return boolean value.

What is #

It is a sigil to mark the beginning of comment.

What is {}

It could means:

  1. a Hash. When assigned to a variable.
  2. beginning & end of a block (anonymous function).

Where Am I?

You are currently browsing the tutorial category at RAPD.