Metaprogramming Examples and Applications

Metaprogramming is the writing of programs that can write/manipulate the program itself or other programs. If you are using PHP and MySQL, you are already metaprogramming.

<?php
$title = mysql_real_escape_string($_GET['search']);
$r = mysql_query("SELECT * FROM database1.table1 WHERE PageTitle = '" . $search . "'");
// ......
?>

By concatenating the user-submitted data, you generated a MySQL query.

In fact, PHP generates HTML, PHP is a meta-programming language. Don’t think PHP can only generate HTML. PHP can also generate CSS and JavaScipt. In some sites, you can customize the background color of your profile. The color you’ve chosen will be part of the CSS of your profile.

<style type='text/css'>
#profile {
  background-color: <?php echo $userperf['BackgroundColor'] ?>;
  <?php if ($userpref['BackgroundImage']) { echo 'background-image: ' . $userpref['BackgroundImage'] } ?>
  color: <?php echo $userpref['TextColor'] ?>
  /* ...... */
}
</style>

You can’t get the client’s IP address with JavaScript, but PHP can. The following code generates JavaScript code that alerts your IP address.

<script type='text/javascript'>alert("Your IP address is:<?php echo $_SERVER['REMOTE_ADDR'] ?></script>")

Metaprogramming allows you to change a general-propose to a domain-specific language, for example, changing Ruby to a domain-specific language by changing the way you program.

In Ruby, there are methods such as attr_reader and attr_writer, they are not keywords, instead, they made use of metaprogramming.

class Module # if the class Module exists, extend the class Module
   def attr_reader (*syms) # define the method attr_reader
     syms.each do |sym|
        class_eval %{def #{sym} # define the method dynamically based on the names given
                         @#{sym}
                       end}
     end
   end
end

There is no type checking in Ruby, writing same thing such as if arg1.kind_of? String is inconvenient, so you can use the Ruby metaprogramming capabilities to automate it: Use methods to generate methods.

First, you extend the class Module.

class Module

end

Then, add the method for the type-checking functionality,

class Module
  def type_checked(name, *types, &block)
    class_eval do
      define_method(name) do |*args|
        i = 0
        if args.length < types.length
          raise ArgumentError.new "Not enough number of arguments. Excepting #{types.length}. Got #{args.length}"
        end
        types.each do |type|
          if not args[i].kind_of? type
            raise TypeError.new "Excepting #{type} for paramter #{i}. Got #{args[i].class}."
          end
          i += 1
        end
        block.call(*args)
      end
    end
  end
end

Now you can use type_checked like a keyword.

class Test
  type_checked :add, Fixnum, Fixnum do |x, y|
    x + y
  end
end

It will make (Test.new)add("hello", "world") throw an exception because “hello” and “world” are Strings.

You can even implement unit calculation in Ruby.

class Module
  def unit(name, x)
    class_eval "def #{name}; self * #{x}; end;"
  end
end
class Numeric
  unit :mm, 0.001
  unit :cm, 0.01
  unit :dm, 0.1
  unit :m, 1
  unit :km, 1000
end

Because we extended the class Numeric, all numbers will have properties such as cm and mm. 10.cm will evaluate to 0.1, because 10cm = 0.1m.

In Python, you can use decorators to achieve metaprogramming. Decorators are like @deco, they are put before function definitions.

Here is a type-checking script in Python:

def accepts(*args):
  def de(func):
    def f(*fargs, **fkwargs):
      i = 0
      for a_type in args:
        if a_type != type(fargs[i]):
          raise TypeError("Expecting %s for argument %d. Got %s." % (a_type, i, type(fargs[i])))
      i += 1
      return func(*fargs, **fkwargs)
    return f
  return de

@accepts(int, int)
def add(a, b):
  return a + b

By adding @accepts(int, int) decorator before the function, you wrap the function with the type-checking routine, while you need to write them one-by-one normally.

Don’t think JavaScript does not have class inheritance. JavaScript is a functional and dynamic programming language.
You can use prototypes for class extending and class inheritance.

function Base() { }
function Derived() { } // class Derived extends Base { public Derived() : Base() { } }
Derived.prototype = new Base();

// add method alert to String s.
String.prototype.alert = function() { alert(this) }
"Hello, world!".alert();

Metaprogramming links:

Tags: , , , , , , ,

Monday, September 7th, 2009 Programming, Tutorial, Web Design/Development Comments Off

3 Seconds of Nightmare

I woke up early in about 5AM, then I tried to go back to sleep. In the bed, I suddenly experienced a flash and my body got paralysed, I tried to move, and it was impossible. It’s even impossible to open my eyes! However, the paralysis end in less than 1 minute.

I experienced that type of paralysis for several times. I suppressed some of them by forcing me to move quickly during the flash.

In about 6:55, I experienced something different. I suddenly get paralysed, and I hear screaming sound. With images of buildings at earthquake and the sensation of falling down. I also feel the sensation of shaking in both the image and my body. That paralysis lasted for about 3 seconds (I don’t know if my sense of time work during the paralysis). That paralysis feels like a short nightmare, except the dream-like full-vision and realistic images, and I’m also conscious during the “nightmare”. (see also http://en.wikipedia.org/wiki/Sleep_paralysis#Symptoms_and_characteristics, it explained everything experienced)

After that paralysis, I got frightened and turned on the light and window, because the darkness of the room resembles the darkness of the nightmare. I also stopped sleeping after that.

I experienced many sleep paralysis before, and most of them are only immobility. It’s worse that I get paralysed in a position inside the blankets where I can’t breathe. I also had the sensations of dying some times.

Did that happened to you? Did sleep paralysis happen to you? It will happen some time in your life.

Tags: ,

Saturday, September 5th, 2009 General Comments Off

Finished Moving

Maybe you know it from Twitter, or maybe you don’t, that I moved to a new apartment. Because I didn’t have access to computer to use Twitter that time, this will explain what happened when I was moving and replace all of the tweets about moving. (This won’t be pointless like tweets)

August 30

My computer was packed in about 10 to 11 AM, forcing myself offline. In that time, my house was full of boxes, the hallways were blocked. When I was bored, I read the new Shonen Jump magazine and play my DS Lite.

When my bed was being disassembled, the lucky thing happened: I found my Pokémon Pearl and the long lost 256Mb GBA Flash Cart. When I checked my Journal item in my Pearl, I found that the last time I’ve played Pearl is in January. I barely play Pokémon Pearl, and I don’t battle competitively. The GBA Flash Cart contains 4 games I’ve played… more than 2 years ago. Mega Man Battle Network 6 : Cybeast Falzar, Rockman.EXE 4.5, Mega Man Battle Chip Challenge, and Naruto Ninja Council 1. The video game music recalls my past, but they only recalled the “Dark Season”, between September to March, where the night is much longer than day, and where the rainy weather depresses me. The rainy weather and the short daytime really cause depression (see also: Seasonal affective disorder).

My parents found that my bed was partially broken, so we decided to dump it. The bed is too small for me anyways.

At night, I slept on floor with mattress.

August 31

I woke up at about 7 to 8 AM. We packed up more stuff. In about 10AM, the moving truck was about to arrive. However, there was a problem: They didn’t know where to park. My dad even shouted the swear words at them in the 4th floor (while I saw someone with a baby, what happen if the baby copies what my dad shouted?!). The problem of the trucks were resolved by the landlord.

After that, more moving. Some boxes and furnitures are very heavy that it’s impossible to move.

We finished packing up in 1:30PM. After that, we were ready to move to the new apartment.

The new apartment is a 21st century building. It looked a lot better than old one. The old one even have design flaws such as the window. My new apartment has 2 bathrooms, a larger living room and our own laundry machine. After the sofa was carried there, I lied down on the sofa like Rakshata Chawla (of Code Geass) for a while.

In about 5 to 6 PM, we had dinner in the mall 2 roads away from the apartment. It is possible to walk to the mall from the new apartment.

I didn’t have a bed by that time, so I was still sleeping on the floor with mattress. Before my sleep, I scribbled down something in my sketchbook, I got an idea for a chess-like game (more details about it will be posted later).

September 1

I plugged in my computer in about 9AM. I immediately found an open Wi-Fi connection SSIDed dlink. I successfully connected to it and checked Twitter and my e-mail. I also chatted on AIM. However, it is so slow! Twitter takes so long to load, Sonny 2 is impossible to load and YouTube videos are even unloadable! I tried to change the settings on the network by entering http://192.168.0.1/ in the address bar. Because the Wi-Fi connection is open and used default setting. I can log in with username of admin and no (empty) password. Like the SSID said, that Wi-Fi uses D-Link. The setting pages are even powered by PHP! (it is possible to edit the PHP source code to make PHP work on small devices) I tried to change every network settings and nothing worked. The cause of the problem is the low wireless signal.

In about 2PM, my parents were going to call Shaw Cable to set up the Internet while my mom takes me to register in the high school. I was not registered yet because my mom needs to bring my birth certificate and the proof of residency. The staff wanted my birth certificate because all 3 members in my family have different last names. I even have 2 names (the Chinese one and English one).

Then we were back home. The Shaw Cable finished setting up the Internet. They even set up a digital TV system. However, they did not work yet. I stared at the white TV static noise, when I concentrated on it, I saw the noise flowing in a pattern. I saw some snakes and bats flying. They were just hallucinations.

Back to my computer, I connected with the network Shaw Cable just set up. It’s still somewhat unstable. It disconnects constantly.

At night, I and my parents went to IKEA for my new bed. However, we only end up with a pillow and some hangars. After that, we went to the Wal-Mart and McDonalds.

September 1

I woke up at 8 AM and I started to write this post in about 9AM.

Here is the list of unfinished tasks:

  • Buy a new bed for me
  • Buy more furnitures to fill the large space in the living room
  • Register me in the high school, there will be an interview
  • Buy a bookshelf or drawer to store my stuff

Tags: , , ,

Wednesday, September 2nd, 2009 General 2 Comments

Colony

Colony is a fun real-time strategy game. It even have multiplayer mode. You can play it at http://armorgames.com/play/4264/colony.

The Colony community discovered many tactics and strategies, http://www.krinlabs.com/phpBB3/viewtopic.php?f=30&t=3105 is one of the tactic/strategy thread.

Here is my strategy:

  • Build an Armory
  • Set Armory to Provide Financial Support
  • Build a Forge
  • Set Armory to Prepare Backup Energy
  • Send some Scouts and/or Romans for defense
  • Set Armory to Provide Financial Support
  • Build a Generator
  • Upgrade Forge
  • Build another Generator
  • Upgrade Generators
  • At this point, you should have 500 energy, you can demolish one of the Generators to build a Special Operations or replace it with an Outpost for tactical diversity.

I also figured out some useful tactics:

  • Put strong units such as Tanks or Gröditzes on the front, and put Meditecs and/or Snipers behind them, this lets the snipers and Meditecs live longer.
  • Send some Sakata Mk-IIs and Phantoms above them, this gives you tactical advantage because Sakatas are strong against Scouts and Phantoms are strong against ground units.
  • By putting your units in the middle of the field, you can prevent the enemy reinforcements from advancing.
  • Make sure you know the strengths and weaknesses of your units, like the types in Pokémon and Mega Man Battle Network/StarForce. The statistical guide shows the strengths and weaknesses of units.
  • If you deploy Phantoms, the opponent will deploy Scouts, then you deploy Marines, if you don’t have Marines, try a different countermeasure or you will be put in the disadvantage.
  • If the enemy has so much energy that they can spam missiles, you keep spamming Romans as decoy. Their 500 energy will be wasted.

Tags: , , ,

Monday, August 24th, 2009 Gaming 2 Comments

Processing.js Auto-Start with Apache mod_rewrite and PHP

Tired of keep adding boilerplate code for Processing.js scripts? Are you making full of Processing.js scripts and you are too lazy to share them? I wrote a script for that. You only need to upload the Processing.js scripts as .pjs file extension then you only need to type the URL to the script in your address bar. Your server will wrap it with initialization code. Very easy.

To see it in action:

Download the script here: http://www.mediafire.com/download.php?gfozzoymzew.

After you downloaded the script, create a new directory on your server, upload the files in the archive. To test if it works, type http://YOURSITE.com/PATH/sample.pjs (where YOURSITE.com is the domain of your site and PATH is the path to the Processing.js auto-loader you’ve uploaded), it will show you the sample file called sample.pjs.

Monday, August 3rd, 2009 Programming, Web Design/Development Comments Off

Windows 7 and Browser Choice in Europe

After all of these antitrust stuff, Microsoft decided to provide Windows 7 users in Europe a browser selection screen. You can read more about it at:

I think the browser descriptions in the screenshot is somewhat misleading or biased, they all say they are the best browser. Instead, they should say what unique features do they have.

When I (or maybe you) was a newbie, I think Internet Explorer was the only Web browser in the world. Microsoft fooled us. That’s why the browser selection screen was made.

The browser selection screen was only in Europe, maybe it will be implemented in North America soon.

Tags: , , , , , , ,

Saturday, August 1st, 2009 Technology Comments Off

A Simple Processing.js Game

I was trying to code something. Then I made a simple game with Processing.js. It is a game where you use your mouse to move the blue circle and avoid all red circles.

You can see it at http://uniteduniversemainsite.freehostia.com/files/processingjs/avoider.html. It uses HTML 5, so it only work for latest, beta (and higher) browsers such as Firefox 3.5, Opera 10, Safari 4 and Chrome 2. The texts such as the score and level indicator only work on Firefox 3.5.
I’m going to make a shooter game next time.

Source code:

class Enemy {
  int x;
  int y;
  int speed;

  Enemy(int x, int speed) {
    this.x = x;
    this.y = 0;
    this.speed = constrain(speed, 0, 10);
  }

  void update() {
    fill(255, 0, 0);
    stroke(128, 0, 0);
    ellipseMode(CENTER);
    ellipse(x, y, 40, 40);
    this.y += speed;
  }
}

PFont font;
ArrayList enemies;
int level;
int score;
int timer;
int count;
int playerX;
int playerY;
byte state = 0;

void setup() {
  size(400, 400);
  font = loadFont("Courier New");
  reset();
}

void reset() {
  enemies = new ArrayList();
  level = 1;
  score = 0;
  timer = 150;
  count = 150;
  playerX = 200;
  playerY = 200;
}

void draw() {
  background(0);
  if (state == 2) {
    if (score >= level * level * 10) {
      level ++;
    }
    count = (1 / level) * 200;
    timer ++;
    if (timer > count) {
      timer = 0;
      enemies.add(new Enemy(random(400), sqrt(level) / 2));
    }

    for (int i = enemies.size() - 1; i > -1; i --) {
      Enemy enemy = (Enemy) enemies.get(i);
      if (enemy.y > height) {
        enemies.remove(i);
        score += level * 2;
        continue;
      }
      if (playerX < enemy.x + 30 && playerX > enemy.x - 30 &&
        playerY < enemy.y + 30 && playerY > enemy.y - 30) {
        state = 1;
        break;
      }
      enemy.update();
    }

    playerX += constrain(mouseX - playerX, -5, 5);
    playerY += constrain(mouseY - playerY, -5, 5);

    fill(0, 0, 255);
    stroke(0, 0, 128);
    ellipseMode(CENTER);
    ellipse(playerX, playerY, 30, 30);

    fill(255);
    textFont(font, 16);
    text("Score: " + score + "  |  Level: " + level, 1, 17);
  } else if (state == 1) {
    fill(255);
    textFont(font, 48);
    text("Game Over", 1, 49);
    textFont(font, 16);
    text("Score: " + score, 15, 93);
    text("Level: " + level, 15, 110);
  } else {
    fill(255);
    textFont(font, 18);
    text("Click to start", 1, 20);
  }
}

void mousePressed() {
  if (state == 1) {
    reset();
    state = 0;
  } else if (state == 0) {
    state = 2;
  }
}

Tags: , , ,

Friday, July 31st, 2009 Programming, Web Design/Development Comments Off

Chinese Rip Offs

Now let’s look at something weird, or shocking : Chinese rip offs.
There are full of copycats in China that copy popular trademarks such as Nintendo Wii and Nokia to fool people to buy their products.

Vii is a rip off of Nintendo Wii. It imitates Nintendo Wii’s Wiimote and even their design. Vii comes with about 8 games such as golf, bowling and even fry egg. They all have horrible 2D graphics and boring gameplay. The Vii console is very light, if you open it, you can see its emptiness. Why the manufactor made the console so big? Because by imitating Wii, many iliterated and unexperienced people will get fooled (people will think it is Nintendo Wii). You can watch the Vii review video at http://www.youtube.com/watch?v=wed_bW8iiEw. As you can see, the games sucked so much. It will be a nightmare if my Wii was replaced by that Vii.

Here are more links about Vii:

Pop Station is a rip off of PSP. Its packaging imitates PSP’s packaging, and the buttons also imitate PSP. The box even say “Color Display”. Like Vii, it has horrible gameplay, graphic and sound, and nightmare. Many variations of Pop Station are made, some of them have radio (to imitate PSP’s music player), some of them look like Netbook laptop, and you can watch review videos about Pop Station at Dr. Ashen’s YouTube channel. You can watch its review video at http://www.youtube.com/watch?v=NvXleDSkB-g.

Links about Pop Station:

Poly Station 3 is a rip off of PS3. You can play without hooking it to the TV. Of course, it’s a low-quality piece of plastic junk. You can watch a video about Poly Station 3 at http://www.youtube.com/watch?v=_a6lxiB1b_I.

Links about Poly Station 3:

Neo Double Games is a rip off off Nintendo DS. Instead of using 2 screens in one game, it has 2 screens, but the second screen is obslete and it’s only used for imitation purpose. Also, some buttons do not work, because they are used to make it look like DS> You can watch its review video at http://www.youtube.com/watch?v=ow9SHsnFG2U.

More links about Neo Double Games:

Nokir is a Chinese rip off mobile company. They copy Nokia cell phones under the brand of Nokir. (in the logo, capital A and R look similar) You can read more about Nokir cell phones at http://www.newlaunches.com/archives/nokir_e828_episode_mmvx_chinese_copy_cats_strike_back.php.

Some people even rip off cars! Ferrari was ripped off under $10k. It guarantees no safety and insurance, so it’s a risk to buy it. Source: http://www.newlaunches.com/archives/chinese_make_a_fake_ferrari.php.

Other rip offs include fake iPhones, fake iPods and more. You can read more about them at http://www.newlaunches.com/archives/top_10_chinese_rip_offs.php. Even footwears are ripped off, under a mispelled name, for example: http://engrishfunny.com/2009/07/06/engrish-bna-knie/. Iliterated Chinese people made this: http://failblog.org/2008/07/22/translation-fail/, they think “Translate server error” means “Restaurant”.

Why there are so much rip offs in China? The intellectual property (IP) protection in China is poor. They could copy foreign IPs without lawsuits. Therefore, China is a big country of piracy. Almost all Windows XP discs are pirated (price is about 11 yuan). (some pirated Windows XP discs states that they are cracked by Russian hackers. Russia and China are related to communism.) Also, many Chinese people are uneducated, illiterated, and unexperienced. Therefore, they are more prone to bootlegs, pirated products and scams. (“When you are buying Vii, you are buying communism!”) The rip off manufacturors intentionally imitated major consoles such as Wii to fool people, and also to fit the poor economy. Can you imagine that your Nintendo Wii was replaced by Vii, your PS3 was replaced by PolyStation 3, and your DS was replaced by Neo Double Games. Can you imagine you are playing same boring games with horrible graphics and sound? It will be a gaming nightmare for you.

Tags: , , , ,

Thursday, July 23rd, 2009 Gaming, Technology 4 Comments

Great Flash Games

In this summer, I kept playing free Flash games. Some games are really fun and worth to play. I will list them so you can try them out. I can’t find any more good games on addictinggames.com, so I moved to Armor Games.

  • World Wars 2 – New version of the previous game World Wars. This version has card system and map of Europe. The AI also increased.
  • Phage Wars 2 – An RTS where you command your viruses to help them to multiply and you can modify their genes to give them abilities.
  • Warfare 1944 – New version of Warfare 1917. It has three deployment lines and more features such as resource points, flanking, and a new campaign.
  • Neuron – A simple shooting game, but it has great particle effects and music.
  • Exploit – A hard puzzle game. To clear the game, try to think in subproblem-based model and backtracing model.
  • Pwong – A pong game with multiple balls. It has great graphics and music.

Tags: , , ,

Thursday, July 23rd, 2009 General Comments Off

Middle of July

We finally reached the middle of July. I spent most of my time on the Internet.
In this week, I finally got Mega Man Star Force 3 : Black Ace. I finished it in 2.5 days (16 hours, incl. the time spent at collecting cards and visiting every Cyber Cores). I mastered online battling. Last time, I was fighting someone with higher HP than me and he transformed to Black Ace. However, I dodged/blocked all of his attacks (all of his attacks are lock-on-enabled). Then I used a very useful combo: DblStone + Bombalizer. Currently, my online winning percentage is 70%. I recommend you to add more SwrdFghtrXs and MadVulcnXs to your folder, it’s very useful.

Recently, I also practiced oekaki drawing. First, I could not draw anything, then, I started to adapt it. Here is a sample of what I drew: http://www.treeofbeginnings.jenviousity.com/oekaki/index.php?a_match=SpaceMan.

I finally finished watching Code Geass season 1. At last, Zero (Lelouch) left the Black Knights alone to rescue Nunnally (I had a hard time at spelling the characters’ names), then Suzaku appeared and tried to shoot Zero, then the last episode ends. According to Code Geass Wiki, Lelouch and Nunnally were sent to the Emperor and Lelouch’s memory was rewritten to forget about Nunnally and the Black Knights.

Tags: ,

Thursday, July 16th, 2009 Gaming, General 3 Comments