Tuesday, November 20, 2012

Style Sheets and Scripts Not Reloading

One of the problems I often encountered before in front-end side development for the web was style sheet and script caching.  It's not really a problem, as it is convenient and actually makes a lot of sense since these things shouldn't be reloaded every time.  But during development, there were a number of times I forgot about this and just pulled my hair in frustration, wondering why my changes do not reflect whenever I refresh the page, why my style sheets and scripts are not reloaded even if I do "shift-reload".

And of course it's because of caching.  So one of my colleagues taught me this:

<link rel="stylesheet"
href="/path/to/style.css?x=<?php echo time() ?>"
type="text/css">

This is in php, but you can do something similar with your choice of language.  Here, since time() gets the current timestamp and is thus ever changing, this way your styles and scripts will always be reloaded every time you refresh your page because of a different href from the one that has already been cached.

Note!  Only do this during development, so your style sheets and scripts will be cached when live.


:D

Sunday, October 21, 2012

PHP Performance Benchmarks

So a friend gave me a link that contains performance benchmarks for PHP.  It's really interesting because you might find a thing or two which you previously believed to be the best way to implement something, when actually it's the worst.  But that's just the worst case.  Still, I think it's pretty useful to know what to avoid, and the alternatives to it.  Here's the link:
        http://maettig.com/code/php/php-performance-benchmarks.php

To summarize, I will list the best implementation in terms of speed for each of the cases from the link above.  Of course, these may be the fastest implementation but they might not exactly be the simplest implementation or the most convenient, but that depends on your needs.

  1. Check if a string is empty
              if (empty($var))     - 3 ms
      X      if ($var == "")    - 44ms

  2. Compare two strings
              $a == $b     - 6 ms

  3. Check for substring (if a string contains another string)
              strpos($haystack, $needle) !== false     - 4 ms
      X      ereg($needle, $haystack)    - 31 ms

  4. Check if a string starts with another string
              strpos($haystack, $needle) === 0    - 4 ms
              strpos($haystack, $needle)    - 4 ms

  5. Check if a string ends with another string
              substr($haystack, -strlen($needle)) === $needle     - 6 ms

  6. Replace a string inside another string
              str_replace($search, $replace, $subject)     - 8 ms
      X      ereg_replace($search, $replace, $subject)     - 41 ms

  7. Trim characters from the beginning and end of a string
              trim($string, ",")     - 1 ms
      X      preg_replace('/^,*|,*$/m', "", $string)     - 47 ms

  8. Split a string into an array
              explode(",", $string)     - 10 ms

  9. Loop a numerical indexed array of strings
              $i = count($array); while($i--)     - 1 ms
              for ($i = 0, $count = count($array); $i < $count; $i++)
                        - 1 ms
      X      for ($i = 0; $i < count($array); $i++)     - 43 ms

  10. Implode an array
              "$array[0] $array[1] $array[2]"     - 5 ms
              implode(" ", $array)     - 5ms

Though differences in execution time between some implementations may be small, I still think it's good to optimize as much as we can.  I know I might be biased on this since I prefer to optimize time over space - actually, having said this, I am indeed biased - but I believe that there is no harm in switching some lines of code, as long as it does what it's supposed to do, only a little faster. :)

Sunday, October 14, 2012

HTML4 to HTML5

At first, I really didn't know what changed from HTML4 to HTML5.  But then of course, HTML5 wouldn't be released if there weren't any improvements from its predecessor.

New Elements.  This probably is the most apparent change from HTML4 to HTML5 for me.  The new elements are added for better webpage structure and semantics, instead of just using div's for every section of your webpage.  Here are some of them:
  • Header
  • Footer
  • Section
  • Article
  • Nav
  • Aside
The difference of these new elements from the simple div?  They have their specific and unique functions that cater just what you need.

Dated Out Styling Tags.  There is a change in the approach of building webpages: HTML provides the structure of the document, and everything else is just presentation.  CSS is responsible for that.  So the tags that focus mainly on the appearance of the webpages have been deprecated in HTML5: <b>, <i>, <font>, etc.  I think this makes a lot of sense, because your webpage will not be tightly-coupled with its style - you can easily modify your design without having to touch the skeleton of your document.

Independence.  I couldn't think of another word, sorry about that, hahaha.  HTML5 can play video and audio files on its own, without the requirement of third-party applications (which I think is pretty cool).  And it can also run video games (yes, video games!) in the browser on its own.


I haven't really explored HTML5 that much, only a couple of experiments with the canvas and video tags (will probably post them soon).  But I find it really interesting, and I believe it has a lot of potential, especially in games (hurrah!).  I hope more browsers will support it soon.


^^

Tuesday, August 21, 2012

IE Shenanigan Part 1: Javascript Array

NO trailing comma/s on your javascript arrays.

<script type='text/javascript'>

    var myArray = {
        "a":"apple",
        "b":"banana",
        "c":"carrot", // this, here, is a trailing comma
    }

</script>

If you encounter a javascript error in your page when using Internet Explorer, you might want to check your javascript arrays for trailing commas.  While other browsers don't mind, apparently IE doesn't want those kinds of things, so better remove them and try loading your page again.


Sunday, August 5, 2012

SVN: Merging a Branch to Trunk

svn merge - apply the changes between two sources to a working copy path

Usage:
    svn merge <source> -r<X>:<Y> <dest>
where X is the revision from where your branch was copied, and Y is the revision you want to merge your branch into.  The value of Y is usually the latest revision of trunk, or HEAD.

Switching a branch back to trunk
Note:  \ means that the command continues on to the succeeding line/s.
  1. Get the revision number from when your branch was created.
    • Option 1:  switch to the branch, and find the revision your branch began at:

           svn switch http://examplesvn.com/svn/  \
                project/branches/branch_name

           svn log --stop-on-copy

      This will display the commits that have been made in branch_name back to the point it was created.  The oldest revision here will be used as the value of X.

    • Option 2:  find the revision your branch began at without switching:

           svn log --stop-on-copy http://examplesvn.com/  \
                svn/project/branches/branch_name


      This, too, will behave the same way as option 1.

  2. Switch to destination, in this case, trunk.

         svn switch http://examplesvn.com/svn/project/trunk

  3. Test-run the merging.

         svn merge http://examplesvn.com/svn/project/  \
              branches/branch_name -rX:HEAD . --dry-run


    where X is the revision when branch_name was created, and HEAD (the actual string, not a representative of a value) is the latest revision of your current working copy, trunk, which is also your destination set to ".".  This command will simulate the actual merging, display the conflicts, if any (this is what you want to watch out for), and the rest of the changes to be made if this was an actual merge.

    Note.  This is actually a good practice, since you will see what's going to happen upon merging, without the risk of destroying your current working copy.

  4. Merge.  If the dry-run is successful and looks good to you, proceed with merging:

         svn merge http://examplesvn.com/svn/project/  \
              branches/branch_name -rX:HEAD .


  5. Check status.  Check if the changes are reflected.

         svn status

  6. Commit.  If everything is ok - changes are reflected, conflicts have been resolved, etc - commit the current changes by the merge.

         svn commit -m "MERGING branches/branch_name to trunk"

And that's it. :)


      Friday, July 27, 2012

      Ruckusing

      Definitions
      Database migrations - scripts to keep track of schema modifications.
      Ruckusing - a database migration framework written in PHP5, for managing database migrations.

      Why use database migration frameworks like ruckusing?  Again, of course because it's convenient:
      • Consistency - Schema consistency is very important.  With migrations, there is a guarantee that the project is in a consistent state across all developers and/or copies, that all developers are in sync - especially if the db is shared
      • Keeping track - You know what version your database is on, and the scripts will take care of keeping track of them for you.
      • Portability - You can easily move to a different RDBMS, because database communications are abstracted.
      • Migrating up and down - easily switch into earlier or later states of your schema
      • Tasks - you have a record of the modifications your schema underwent throughout the project

      Here are simple (and hopefully short?) steps on using ruckusing:
      1. Configure the database: edit config/database.inc.php, and enter your database details (yes, you must have a database already).  For example,

            //----------------------------
            // DATABASE CONFIGURATION
            //----------------------------
            $ruckusing_db_config = array(
                'development' =>; array(
                    'type'      =>; 'mysql',
                    'host'      =>; 'localhost',
                    'port'      =>; 3306,
                    'database'  =>; 'myproject',
                    'user'      =>; 'user',
                    'password'  =>; 'password'
                )
            );


      2. Initialize schema migrations info table: in migrations/ (ruckusing top-level directory) run

            php main.php db:setup

        This will create the table schema_migrations in your database.  This table will keep track of what version your schema is currently on.

      3. Create a script: to generate a migration script, in migrations/ run

            php generate.php action_name

        This will generate a blank script in the migrations/db/migrate/ directory, with the filename format of <timestamp>_ActionName.php.  Ideally, you name your script according to the purpose it will serve; for example, the command

            php generate.php create_users

        will generate a blank script with filename <timestamp>_CreateUsers.php (i.e., 20110517061724_CreateUsers.php).  Though not required, it is better that you name your script after its purpose, so you can easily identify what that script does.

      4. Edit your script: open your generated script in the migrations/db/migrate/ directory.  You will see two functions:

        • public function up() - called when migrating up; edit this function to contain the schema changes you want to perform (building up).  Example:

              public function up() {
                  $user = $this->;create_table("users");
                  $user->;column("name", "string");
                  $user->;column("email", "string", array('limit' =>; 100));
                  $user->;finish();

                  $this->;add_index("users", "email", array('unique' =>; true));
              } //up()


          or if you want, you can also use the execute() method, to execute direct SQL statements:

              public function up() {
                  $sql = >>>SQL
                      CREATE TABLE users (
                          id INTEGER UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
                          name VARCHAR(255),
                          email VARCHAR(100),
                          UNIQUE(email)
              >>>;SQL;
                  $this->;execute($sql);
              } //up()


        • public function down() - called when migrating down; to undo what the up() function does (tearing down).

              public function down() {
                  $this->drop_table("users");
              } //down()

      5. Migrating: after modifying your scripts, in migrations/ run

            php main.php db:migrate

        to migrate to the latest version.  This command will execute all the scripts starting from the current version your schema is on up to the latest.  In our example, this command will run the create users script, and thus create the users table.

        Additionally, you can also choose to migrate to a specific version, both higher and lower.  You can do this in two ways:

        • by specifying the version number you want to migrate to.  For example, the command

              php main.php db:migrate VERSION=3

          will either a.) migrate from the current version of your schema up to the third migration, if your schema is on a lower version than 3, or b.) migrate down to the third migration, if your schema is on a higher version than 3.

        • by specifying the timestamp from the filename of the script; for example:

              php main.php db:migrate VERSION=20110517061724

          where 20110517061724 is the timestamp from the script 20110517061724_CreateUsers.php.  The behavior is the same as that of specifying the version number.

        So if you run

            php main.php db:migrate VERSION=0

        the framework will migrate all the way down to zero - all the down() functions of all the migration scripts are executed, and all the schema modifications that were done from the first to the latest version will be reverted.

      6. Other useful stuff: here are some of the other stuff you can do with ruckusing:
        • php main.php db:version - returns the current version of your schema
        • php main.php db:schema - dumps the current schema

      Simple, right?  Much easier than managing all the sql files you've created for all your schema modifications, syncing databases accross machines, keeping track of what schema version you are on, etc.  For more details, visit http://code.google.com/p/ruckusing/ and https://github.com/ruckus/ruckusing-migrations.

      :D

      Thursday, July 26, 2012

      SVN Switch

      svn switch (sw) - update your working copy to a different URL.

      Usage:
           svn switch <source> <dest>
      or
           svn switch <source>
      if the destination is your current location.

      Examples:
      Switching the entire working copy:
           svn switch http://examplesvn.com/svn/project/trunk
           svn sw http://examplesvn.com/svn/project/branches/branch_name

      You can also choose to switch only a part/directory of your working copy:
           svn sw http://examplesvn.com/svn/project/branches/branch_name/subdir

      Important!  When switching, always be in the directory that you want to switch; if you want to switch your entire working copy, then be in the top-level directory of your working copy.

      Why switch?  It's convenient!  When working on multiple branches of your project, you don't need to checkout each branch to a different directory or location.  Also, since switch works like update, your local changes will also be preserved when you switch.

      However, although this may be the case, I personally think it is better that you commit your local changes first before switching, because you'd want to avoid..

      The S Status
      Files with the S status (when you do a svn status) are from a different version - from a different location in your repository than the directory containing them.  This usually happens when svn switch gets interrupted in the middle, because it somehow gets confused from the local changes or conflicts.


      As a final note, here are the things you'd want to think of first before switching:
      • svn info - check the URL your working copy is currently in
      • svn status (st) - check for local modifications, conflicts, or the S status
      • commit local changes first, to avoid conflicts and unexpected behaviors