SQL Injection Tutorial in php

SQL injectionThis article explains basics of SQL Injection with an example that shows SQL Injection, and provides methods to prevent from these attacks. As the name suggests,this attack can be done with SQL queries. Many web developers are unaware of how an attacker can tamper with the SQL queries. SQL-Injection can be done on a web application…

For Example Read more…..

Java 2D Pacman Game

In this part of the Java 2D games tutorial we will create a simple Pacman game clone.

Pacman is an arcade game originally developed by a Japanese company Namco in 1980. Pacman became one of the most popular arcade games ever.

Development

The following code example is a remake of a Pacman game by Brian Postma available at javaboutique. I have modified and simplified the code. So that it is easier to understand.

The goal of the game is to collect all the points in the maze and avoid the ghosts. The pacman is animated in two ways. His position in the maze and his body. We animate his body with four images, depending on the direction. The animation is used to create the illusion of pacman opening and closing his mouth. The maze consists of 15 x 15 squares. The structure of the maze is based on a simple array of integers. Pacman has three lives. We also count the score.

The game consists of two files.

Board.java
package pacman;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Board extends JPanel implements ActionListener {

    Dimension d;
    Font smallfont = new Font("Helvetica", Font.BOLD, 14);

    FontMetrics fmsmall, fmlarge;
    Image ii;
    Color dotcolor = new Color(192, 192, 0);
    Color mazecolor;

    boolean ingame = false;
    boolean dying = false;

    final int blocksize = 24;
    final int nrofblocks = 15;
    final int scrsize = nrofblocks * blocksize;
    final int pacanimdelay = 2;
    final int pacmananimcount = 4;
    final int maxghosts = 12;
    final int pacmanspeed = 6;

    int pacanimcount = pacanimdelay;
    int pacanimdir = 1;
    int pacmananimpos = 0;
    int nrofghosts = 6;
    int pacsleft, score;
    int deathcounter;
    int[] dx, dy;
    int[] ghostx, ghosty, ghostdx, ghostdy, ghostspeed;

    Image ghost;
    Image pacman1, pacman2up, pacman2left, pacman2right, pacman2down;
    Image pacman3up, pacman3down, pacman3left, pacman3right;
    Image pacman4up, pacman4down, pacman4left, pacman4right;

    int pacmanx, pacmany, pacmandx, pacmandy;
    int reqdx, reqdy, viewdx, viewdy;

    final short leveldata[] =
    { 19, 26, 26, 26, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 22,
      21, 0,  0,  0,  17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20,
      21, 0,  0,  0,  17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 
      21, 0,  0,  0,  17, 16, 16, 24, 16, 16, 16, 16, 16, 16, 20, 
      17, 18, 18, 18, 16, 16, 20, 0,  17, 16, 16, 16, 16, 16, 20,
      17, 16, 16, 16, 16, 16, 20, 0,  17, 16, 16, 16, 16, 24, 20, 
      25, 16, 16, 16, 24, 24, 28, 0,  25, 24, 24, 16, 20, 0,  21, 
      1,  17, 16, 20, 0,  0,  0,  0,  0,  0,  0,  17, 20, 0,  21,
      1,  17, 16, 16, 18, 18, 22, 0,  19, 18, 18, 16, 20, 0,  21,
      1,  17, 16, 16, 16, 16, 20, 0,  17, 16, 16, 16, 20, 0,  21, 
      1,  17, 16, 16, 16, 16, 20, 0,  17, 16, 16, 16, 20, 0,  21,
      1,  17, 16, 16, 16, 16, 16, 18, 16, 16, 16, 16, 20, 0,  21,
      1,  17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 0,  21,
      1,  25, 24, 24, 24, 24, 24, 24, 24, 24, 16, 16, 16, 18, 20,
      9,  8,  8,  8,  8,  8,  8,  8,  8,  8,  25, 24, 24, 24, 28 };

    final int validspeeds[] = { 1, 2, 3, 4, 6, 8 };
    final int maxspeed = 6;

    int currentspeed = 3;
    short[] screendata;
    Timer timer;

    public Board() {

        GetImages();

        addKeyListener(new TAdapter());

        screendata = new short[nrofblocks * nrofblocks];
        mazecolor = new Color(5, 100, 5);
        setFocusable(true);

        d = new Dimension(400, 400);

        setBackground(Color.black);
        setDoubleBuffered(true);

        ghostx = new int[maxghosts];
        ghostdx = new int[maxghosts];
        ghosty = new int[maxghosts];
        ghostdy = new int[maxghosts];
        ghostspeed = new int[maxghosts];
        dx = new int[4];
        dy = new int[4];
        timer = new Timer(40, this);
        timer.start();
    }

    public void addNotify() {
        super.addNotify();
        GameInit();
    }

    public void DoAnim() {
        pacanimcount--;
        if (pacanimcount <= 0) {
            pacanimcount = pacanimdelay;
            pacmananimpos = pacmananimpos + pacanimdir;
            if (pacmananimpos == (pacmananimcount - 1) || pacmananimpos == 0)
                pacanimdir = -pacanimdir;
        }
    }

    public void PlayGame(Graphics2D g2d) {
        if (dying) {
            Death();
        } else {
            MovePacMan();
            DrawPacMan(g2d);
            moveGhosts(g2d);
            CheckMaze();
        }
    }

    public void ShowIntroScreen(Graphics2D g2d) {

        g2d.setColor(new Color(0, 32, 48));
        g2d.fillRect(50, scrsize / 2 - 30, scrsize - 100, 50);
        g2d.setColor(Color.white);
        g2d.drawRect(50, scrsize / 2 - 30, scrsize - 100, 50);

        String s = "Press s to start.";
        Font small = new Font("Helvetica", Font.BOLD, 14);
        FontMetrics metr = this.getFontMetrics(small);

        g2d.setColor(Color.white);
        g2d.setFont(small);
        g2d.drawString(s, (scrsize - metr.stringWidth(s)) / 2, scrsize / 2);
    }

    public void DrawScore(Graphics2D g) {
        int i;
        String s;

        g.setFont(smallfont);
        g.setColor(new Color(96, 128, 255));
        s = "Score: " + score;
        g.drawString(s, scrsize / 2 + 96, scrsize + 16);
        for (i = 0; i < pacsleft; i++) {
            g.drawImage(pacman3left, i * 28 + 8, scrsize + 1, this);
        }
    }

    public void CheckMaze() {
        short i = 0;
        boolean finished = true;

        while (i < nrofblocks * nrofblocks && finished) {
            if ((screendata[i] & 48) != 0)
                finished = false;
            i++;
        }

        if (finished) {
            score += 50;

            if (nrofghosts < maxghosts)
                nrofghosts++;
            if (currentspeed < maxspeed)
                currentspeed++;
            LevelInit();
        }
    }

    public void Death() {

        pacsleft--;
        if (pacsleft == 0)
            ingame = false;
        LevelContinue();
    }

    public void moveGhosts(Graphics2D g2d) {
        short i;
        int pos;
        int count;

        for (i = 0; i < nrofghosts; i++) {
            if (ghostx[i] % blocksize == 0 && ghosty[i] % blocksize == 0) {
                pos =
 ghostx[i] / blocksize + nrofblocks * (int)(ghosty[i] / blocksize);

                count = 0;
                if ((screendata[pos] & 1) == 0 && ghostdx[i] != 1) {
                    dx[count] = -1;
                    dy[count] = 0;
                    count++;
                }
                if ((screendata[pos] & 2) == 0 && ghostdy[i] != 1) {
                    dx[count] = 0;
                    dy[count] = -1;
                    count++;
                }
                if ((screendata[pos] & 4) == 0 && ghostdx[i] != -1) {
                    dx[count] = 1;
                    dy[count] = 0;
                    count++;
                }
                if ((screendata[pos] & 8) == 0 && ghostdy[i] != -1) {
                    dx[count] = 0;
                    dy[count] = 1;
                    count++;
                }

                if (count == 0) {
                    if ((screendata[pos] & 15) == 15) {
                        ghostdx[i] = 0;
                        ghostdy[i] = 0;
                    } else {
                        ghostdx[i] = -ghostdx[i];
                        ghostdy[i] = -ghostdy[i];
                    }
                } else {
                    count = (int)(Math.random() * count);
                    if (count > 3)
                        count = 3;
                    ghostdx[i] = dx[count];
                    ghostdy[i] = dy[count];
                }

            }
            ghostx[i] = ghostx[i] + (ghostdx[i] * ghostspeed[i]);
            ghosty[i] = ghosty[i] + (ghostdy[i] * ghostspeed[i]);
            DrawGhost(g2d, ghostx[i] + 1, ghosty[i] + 1);

            if (pacmanx > (ghostx[i] - 12) && pacmanx < (ghostx[i] + 12) &&
                pacmany > (ghosty[i] - 12) && pacmany < (ghosty[i] + 12) &&
                ingame) {

                dying = true;
                deathcounter = 64;

            }
        }
    }

    public void DrawGhost(Graphics2D g2d, int x, int y) {
        g2d.drawImage(ghost, x, y, this);
    }

    public void MovePacMan() {
        int pos;
        short ch;

        if (reqdx == -pacmandx && reqdy == -pacmandy) {
            pacmandx = reqdx;
            pacmandy = reqdy;
            viewdx = pacmandx;
            viewdy = pacmandy;
        }
        if (pacmanx % blocksize == 0 && pacmany % blocksize == 0) {
            pos =
 pacmanx / blocksize + nrofblocks * (int)(pacmany / blocksize);
            ch = screendata[pos];

            if ((ch & 16) != 0) {
                screendata[pos] = (short)(ch & 15);
                score++;
            }

            if (reqdx != 0 || reqdy != 0) {
                if (!((reqdx == -1 && reqdy == 0 && (ch & 1) != 0) ||
                      (reqdx == 1 && reqdy == 0 && (ch & 4) != 0) ||
                      (reqdx == 0 && reqdy == -1 && (ch & 2) != 0) ||
                      (reqdx == 0 && reqdy == 1 && (ch & 8) != 0))) {
                    pacmandx = reqdx;
                    pacmandy = reqdy;
                    viewdx = pacmandx;
                    viewdy = pacmandy;
                }
            }

            // Check for standstill
            if ((pacmandx == -1 && pacmandy == 0 && (ch & 1) != 0) ||
                (pacmandx == 1 && pacmandy == 0 && (ch & 4) != 0) ||
                (pacmandx == 0 && pacmandy == -1 && (ch & 2) != 0) ||
                (pacmandx == 0 && pacmandy == 1 && (ch & 8) != 0)) {
                pacmandx = 0;
                pacmandy = 0;
            }
        }
        pacmanx = pacmanx + pacmanspeed * pacmandx;
        pacmany = pacmany + pacmanspeed * pacmandy;
    }

    public void DrawPacMan(Graphics2D g2d) {
        if (viewdx == -1)
            DrawPacManLeft(g2d);
        else if (viewdx == 1)
            DrawPacManRight(g2d);
        else if (viewdy == -1)
            DrawPacManUp(g2d);
        else
            DrawPacManDown(g2d);
    }

    public void DrawPacManUp(Graphics2D g2d) {
        switch (pacmananimpos) {
        case 1:
            g2d.drawImage(pacman2up, pacmanx + 1, pacmany + 1, this);
            break;
        case 2:
            g2d.drawImage(pacman3up, pacmanx + 1, pacmany + 1, this);
            break;
        case 3:
            g2d.drawImage(pacman4up, pacmanx + 1, pacmany + 1, this);
            break;
        default:
            g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this);
            break;
        }
    }

    public void DrawPacManDown(Graphics2D g2d) {
        switch (pacmananimpos) {
        case 1:
            g2d.drawImage(pacman2down, pacmanx + 1, pacmany + 1, this);
            break;
        case 2:
            g2d.drawImage(pacman3down, pacmanx + 1, pacmany + 1, this);
            break;
        case 3:
            g2d.drawImage(pacman4down, pacmanx + 1, pacmany + 1, this);
            break;
        default:
            g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this);
            break;
        }
    }

    public void DrawPacManLeft(Graphics2D g2d) {
        switch (pacmananimpos) {
        case 1:
            g2d.drawImage(pacman2left, pacmanx + 1, pacmany + 1, this);
            break;
        case 2:
            g2d.drawImage(pacman3left, pacmanx + 1, pacmany + 1, this);
            break;
        case 3:
            g2d.drawImage(pacman4left, pacmanx + 1, pacmany + 1, this);
            break;
        default:
            g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this);
            break;
        }
    }

    public void DrawPacManRight(Graphics2D g2d) {
        switch (pacmananimpos) {
        case 1:
            g2d.drawImage(pacman2right, pacmanx + 1, pacmany + 1, this);
            break;
        case 2:
            g2d.drawImage(pacman3right, pacmanx + 1, pacmany + 1, this);
            break;
        case 3:
            g2d.drawImage(pacman4right, pacmanx + 1, pacmany + 1, this);
            break;
        default:
            g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this);
            break;
        }
    }

    public void DrawMaze(Graphics2D g2d) {
        short i = 0;
        int x, y;

        for (y = 0; y < scrsize; y += blocksize) {
            for (x = 0; x < scrsize; x += blocksize) {
                g2d.setColor(mazecolor);
                g2d.setStroke(new BasicStroke(2));

                if ((screendata[i] & 1) != 0) // draws left
                {
                    g2d.drawLine(x, y, x, y + blocksize - 1);
                }
                if ((screendata[i] & 2) != 0) // draws top
                {
                    g2d.drawLine(x, y, x + blocksize - 1, y);
                }
                if ((screendata[i] & 4) != 0) // draws right
                {
                    g2d.drawLine(x + blocksize - 1, y, x + blocksize - 1,
                                 y + blocksize - 1);
                }
                if ((screendata[i] & 8) != 0) // draws bottom
                {
                    g2d.drawLine(x, y + blocksize - 1, x + blocksize - 1,
                                 y + blocksize - 1);
                }
                if ((screendata[i] & 16) != 0) // draws point
                {
                    g2d.setColor(dotcolor);
                    g2d.fillRect(x + 11, y + 11, 2, 2);
                }
                i++;
            }
        }
    }

    public void GameInit() {
        pacsleft = 3;
        score = 0;
        LevelInit();
        nrofghosts = 6;
        currentspeed = 3;
    }

    public void LevelInit() {
        int i;
        for (i = 0; i < nrofblocks * nrofblocks; i++)
            screendata[i] = leveldata[i];

        LevelContinue();
    }

    public void LevelContinue() {
        short i;
        int dx = 1;
        int random;

        for (i = 0; i < nrofghosts; i++) {
            ghosty[i] = 4 * blocksize;
            ghostx[i] = 4 * blocksize;
            ghostdy[i] = 0;
            ghostdx[i] = dx;
            dx = -dx;
            random = (int)(Math.random() * (currentspeed + 1));
            if (random > currentspeed)
                random = currentspeed;
            ghostspeed[i] = validspeeds[random];
        }

        pacmanx = 7 * blocksize;
        pacmany = 11 * blocksize;
        pacmandx = 0;
        pacmandy = 0;
        reqdx = 0;
        reqdy = 0;
        viewdx = -1;
        viewdy = 0;
        dying = false;
    }

    public void GetImages()
    {

      ghost = new ImageIcon(Board.class.getResource("../pacpix/ghost.png")).getImage();
      pacman1 = new ImageIcon(Board.class.getResource("../pacpix/pacman.png")).getImage();
      pacman2up = new ImageIcon(Board.class.getResource("../pacpix/up1.png")).getImage();
      pacman3up = new ImageIcon(Board.class.getResource("../pacpix/up2.png")).getImage();
      pacman4up = new ImageIcon(Board.class.getResource("../pacpix/up3.png")).getImage();
      pacman2down = new ImageIcon(Board.class.getResource("../pacpix/down1.png")).getImage();
      pacman3down = new ImageIcon(Board.class.getResource("../pacpix/down2.png")).getImage(); 
      pacman4down = new ImageIcon(Board.class.getResource("../pacpix/down3.png")).getImage();
      pacman2left = new ImageIcon(Board.class.getResource("../pacpix/left1.png")).getImage();
      pacman3left = new ImageIcon(Board.class.getResource("../pacpix/left2.png")).getImage();
      pacman4left = new ImageIcon(Board.class.getResource("../pacpix/left3.png")).getImage();
      pacman2right = new ImageIcon(Board.class.getResource("../pacpix/right1.png")).getImage();
      pacman3right = new ImageIcon(Board.class.getResource("../pacpix/right2.png")).getImage();
      pacman4right = new ImageIcon(Board.class.getResource("../pacpix/right3.png")).getImage();

    }

    public void paint(Graphics g)
    {
      super.paint(g);

      Graphics2D g2d = (Graphics2D) g;

      g2d.setColor(Color.black);
      g2d.fillRect(0, 0, d.width, d.height);

      DrawMaze(g2d);
      DrawScore(g2d);
      DoAnim();
      if (ingame)
        PlayGame(g2d);
      else
        ShowIntroScreen(g2d);

      g.drawImage(ii, 5, 5, this);
      Toolkit.getDefaultToolkit().sync();
      g.dispose();
    }

    class TAdapter extends KeyAdapter {
        public void keyPressed(KeyEvent e) {

          int key = e.getKeyCode();

          if (ingame)
          {
            if (key == KeyEvent.VK_LEFT)
            {
              reqdx=-1;
              reqdy=0;
            }
            else if (key == KeyEvent.VK_RIGHT)
            {
              reqdx=1;
              reqdy=0;
            }
            else if (key == KeyEvent.VK_UP)
            {
              reqdx=0;
              reqdy=-1;
            }
            else if (key == KeyEvent.VK_DOWN)
            {
              reqdx=0;
              reqdy=1;
            }
            else if (key == KeyEvent.VK_ESCAPE && timer.isRunning())
            {
              ingame=false;
            }
            else if (key == KeyEvent.VK_PAUSE) {
                if (timer.isRunning())
                    timer.stop();
                else timer.start();
            }
          }
          else
          {
            if (key == 's' || key == 'S')
          {
              ingame=true;
              GameInit();
            }
          }
      }

          public void keyReleased(KeyEvent e) {
              int key = e.getKeyCode();

              if (key == Event.LEFT || key == Event.RIGHT || 
                 key == Event.UP ||  key == Event.DOWN)
              {
                reqdx=0;
                reqdy=0;
              }
          }
      }

    public void actionPerformed(ActionEvent e) {
        repaint();  
    }
}

The Commons.java file has some common constants.

final short leveldata[] =
{ 19, 26, 26, 26, 18, ... };

These numbers make up the maze. They provide information out of which we create the corners and the points. For example number 19 in the upper left corner means, that the square will have top and left borders and a point. (16 + 2 + 1)

 public void doAnim() {
     pacanimcount--;
     if (pacanimcount <= 0) {
         pacanimcount = pacanimdelay;
         pacmananimpos = pacmananimpos + pacanimdir;
         if (pacmananimpos == (pacmananimcount - 1) || pacmananimpos == 0)
             pacanimdir = -pacanimdir;
     }
 }

The doAnim() counts the pacmananimpos variable, which determines what pacman image is drawn. There are four pacman images. There is also a pacanimdelay variable, which makes the animation a bit slower. Otherwise the pacman would open his mouth too fast.

boolean finished = true;

while (i < nrofblocks * nrofblocks && finished) {
    if ((screendata[i] & 16) != 0)
        finished = false;
    i++;
}

This code is part of the checkMaze() method. It checks, if there are any points left for the Pacman to eat. Number 16 stands for a point. If all points are consumed, we move to the next level.

Next we will examine the moveGhosts() method. The ghosts move one square and then decide, if they change the direction.

if (ghostx[i] % blocksize == 0 && ghosty[i] % blocksize == 0) {

Continue only if you have finished moving one square.

pos = ghostx[i] / blocksize + nrofblocks * (int)(ghosty[i] / blocksize);

This line determines, where the ghost is situated. In which position/square. There are 225 theoretical positions. (A ghost cannot move over walls. )

if ((screendata[pos] & 1) == 0 && ghostdx[i] != 1) {
    dx[count] = -1;
    dy[count] = 0;
    count++;
}

If there is no obstacle on the left and the ghost is not already moving to the right, the ghost will move to the left. What does this code really mean? If the ghost enters a tunnel, he will continue in the same direction until he is out of the tunnel. Moving of ghosts is partly random. We do not apply this randomness inside long tunnels. The ghost might get stuck there.

if (pacmanx > (ghostx[i] - 12) && pacmanx < (ghostx[i] + 12) &&
    pacmany > (ghosty[i] - 12) && pacmany < (ghosty[i] + 12) &&
    ingame) {

    dying = true;
    deathcounter = 64;
}

If there is a collision between ghosts and a pacman, the pacman dies.

Next we are going to examine the movePacman() method. The reqdx and reqdy variables are determined in the TAdapter inner class. These variables are controlled with cursor keys.

if ((ch & 16) != 0) {
    screendata[pos] = (short)(ch & 15);
    score++;
}

If the pacman moves to a position, where there is a point, we remove it from the maze and increase the score value.

if ((pacmandx == -1 && pacmandy == 0 && (ch & 1) != 0) ||
    (pacmandx == 1 && pacmandy == 0 && (ch & 4) != 0) ||
    (pacmandx == 0 && pacmandy == -1 && (ch & 2) != 0) ||
    (pacmandx == 0 && pacmandy == 1 && (ch & 8) != 0)) {
    pacmandx = 0;
    pacmandy = 0;
}

If the pacman cannot move further it his current direction, there is a standstill.

public void drawPacMan(Graphics2D g2d) {
    if (viewdx == -1)
        drawPacManLeft(g2d);
    else if (viewdx == 1)
        drawPacManRight(g2d);
    else if (viewdy == -1)
        drawPacManUp(g2d);
    else
        drawPacManDown(g2d);
}

There are four possible directions for a pacman. There are four images for all directions. The images are used to animate pacman opening a closing his mouth.

The drawMaze() method draws the maze out of the numbers in the screendata array. Number 1 is a left border, 2 is a top border, 4 is a right border, 8 is a bottom border and 16 is a point. We simply go through all 225 squares int the maze. For example we have 9 in the screendata array. We have the first bit (1) and the fourth bit (8) set. So we draw a bottom and a left border on this particular square.

if ((screendata[i] & 1) != 0) // draws left
{
    g2d.drawLine(x, y, x, y + blocksize - 1);
}

Draw a left border if the first bit of a number is set.

PacMan.java
package packman;

import javax.swing.JFrame;

import pacman.Board;

public class PacMan extends JFrame
{

  public PacMan()
  {
    add(new Board());
    setTitle("Pacman");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(380, 420);
    setLocationRelativeTo(null);
    setVisible(true);
  }  public static void main(String[] args) {
      new PacMan();
  }
}

This is a PacMan file with a main method.

Pacman

Figure: Pacman

This was the Pacman game.

 

Google Map Geocoding Tutorial with Example

google-map-reverse-geocodingGoogle Map API has been a great way to show geographical information on web. A lot of mashup tools like this, have been created around Google Maps to show a wide variety of data. In my previous article about Introduction to Google Maps API, I had described basic APIs to integrate Google Map in your webpage. In this small article we will discuss a great feature of Google Maps API that can be used to locate any City/Country/Place on Map. This is called Geocoding.
20756_Free Shipping Plus VIP Exclusive Perks & Savings with code: CX13J027
Google Maps API provides a wonderful API called Geocoding API that enables you to fetch any location and pin point it on Google Map. GClientGeocoder is the class that we use to get the geocoder that get us the location. We will use getLatLng() method to get latitude/longitude of any location.
Check the following code.

var place =  "New York";
geocoder = new GClientGeocoder();
geocoder.getLatLng(place, function(point) {
    if (!point) {
        alert(place + " not found");
    } else {
        var info = "<h3>"+place+"</h3>Latitude: "+point.y+"  Longitude:"+point.x;
        var marker = new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(info);
    }
});

In above code snippet we passed string “New York” and a handler function to getLatLng() method of GClientGeocoder. GClientGeocoder class will call google server for the location and when it gets the result, it pass the result to the handler function that we specified. Thus handler function will get point (GPoint) object from which we can get the latitude and longitude of location. In above code we have created a marker and placed it on the map.

Online Demo

Google Map Reverse Geocode Example

Create your own Search Engine(Interface) using Google Custom Search API

google-api-real-time-search
Google Custom Search API are wonderful tools to create some awesome search engine like tools. Also if you want to add a search option to your website and customize the look and feel of your search results, Google Custom Search API serve best to you.
Ring in Spring with Stunning Lingerie from Journelle and get $25 OFF purchases of $200 or more! Use promo code: SPRING200. Offer valid 2/22/13-4/30/13. Shop Now

I have created a Real Time Search engine (I call it real time as it search as you type). I am really impressed by the speed/response of Google Search API.

DEMO

google-search-technology

DEMO

The Code

I will show the code for one of the search api that I implemented in demo page. Let us see how to implement Web Search API.

Step 1: Generate Google Search API Key and Include JavaScript

In order to use Google Search API, you have to first generate a Key for you. Go to following page and signup your self for the Key.
Sign up for Google API Key

Next step is to include the Google Search API javascript. Don’t forget to mention your key in the below code.

<script src="http://www.google.com/jsapi?key=YOURKEY" type="text/javascript"></script>
<script type="text/javascript">
    google.load('search', '1');
</script>

Primary

Step 2: Add HTML Container for Web Search

We will create a textbox and a button that will take input for search. And a DIV that will be populated by results:

<input type="text" title="Real Time Search" name="searchbox"/>
<input type="button" id="searchbtn" value="Search" onclick="search(searchbox.value)"/>
<div class="data" id="web-content"></div>

When user will write a query and push Search button, a request will be made to Google Search using Custom Search API and the results are fetched. These results are then copied into the DIV.

Step 3: JavaScript to call Google Search API

We will use following JavaScript to call the Google Search API and copy the results in our container DIV.
The code in plain english is:
1. Create an object to connect Google Web search using class google.search.WebSearch.
2. Set a callback function that will get call once the results for the search are fetched.
3. Call the execute() method with search query as argument.
4. In callback function, iterate through the results and copy it to container DIV.

webSearch = new google.search.WebSearch();
webSearch.setSearchCompleteCallback(this, webSearchComplete, [webSearch]);
function webSearchComplete (searcher, searchNum) {
    var contentDiv = document.getElementById('web-content');
    contentDiv.innerHTML = '';
    var results = searcher.results;
    var newResultsDiv = document.createElement('div');
    newResultsDiv.id = 'web-content';
    for (var i = 0; i < results.length; i++) {
      var result = results[i];
      var resultHTML = '<div>';
      resultHTML += '<a href="' + result.unescapedUrl + '" target="_blank"><b>' +
                        result.titleNoFormatting + '</b></a><br/>' +
                        result.content +
                        '<div/>';
      newResultsDiv.innerHTML += resultHTML;
    }
    contentDiv.appendChild(newResultsDiv);
}
function search(query) {
    webSearch.execute(query);
}

Click for Online Demo

Enhanced by Zemanta

Step by step instructions to download and install LoadRunner

In the past few months, HP has done a lot of changes to the download location for various software that they offer. Here are the new and updated step-by-step instructions to download and install HP LoadRunner.

  1. Go to LoadRunner Download location.
  2. Hit TRIALS AND DEMOS dropdown and click HP LOADRUNNER 11.0 EVALUATION. download-loadrunner-trial
  3. You will be asked to sign-in to HP Passport Single Sign On service. In case you’ve not registered earlier, complete the ‘New User registration’ form and you will be redirected to evaluation software terms of use. download-loadrunner-sign-in
  4. Click “I Agree” as shown below download-loadrunner-terms-of-use
  5. Download the two files 1) Software_HP_LoadRunner_11.00_T7177_15013.zip and 2) Software_HP_LoadRunner_11.00_T7177_15013.z01 as shown below. [You can also download this file to read more instructions from HP]download-loadrunner-both-files
  6. The two files shown above are around 3.2 GB (1.5 GB + 1.8GB) in size. It may take around 2-3 hrs to download (depending upon your internet speed)
  7. Make sure both files are present in the same folder and both files have exactly the same name except for the extension (.zip and .z01).
  8. Download and install Winzip or WinRar. (7zip won’t work here)
  9. Double click on the .zip file and you will see .iso file.download-loadrunner-iso-trial
  10. Extract this iso file using your favorite unzipping software.( I prefer a nice and free utility software called 7zip which can be downloaded here.  You can download and install this utility.)
  11. Once extracted, go inside the folder T7177-15013 and open Install.pdf  file.
  12. Install.pdf contains step-by-step instructions on installing LoadRunner on Windows and Unix platform. Just remember that wherever the instructions refer to installation disk you should go to the folder T7177-15013
  13. That’s It. HP LoadRunner is now installed. Enjoy!

Find Out Your Visitor’s Position Using HTML5 Geolocation

Geolocation is a way for the user to retrieve their position and share where they are. This can be done in a few ways, by using a GPS as the one in your new smartphone or connected to your computer is the most precise method. But for users without GPS the browser will use your IP and or try to find nearby WLAN stations, however this is not as precise but gives some idea of where they are. Exactly how this is done is not a W3C standard and each browser have their own way to do it.

Even though geolocation is really complicated it’s quite easy for you to implement. In this tutorial I will show you how to retrieve the user’s position and display it on a map using Google Maps. So lets get started.

Step 1. Create the HTML layout

We start of by creating a simple HTML page containing three div tags. One for the current status, one to display the data retrieved and one for displaying the user’s position on a map.

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
  <head>
    <title>HTML5 Geolocation</title>
  </head>
  <body onload="initialize()">
    <div id="status"></div>
    <div id="data"></div>
    <div id="map_canvas" style="width: 640px; height: 480px"></div>
  </body>
</html>

We also include the Google Maps API, it’s important to set sensors=false in the URL, otherwise Google will try to find out the user’s position for us.

The initialize function we’re calling on load will try to fetch the position for us.

Step 2. Retrieve the Position

Next it’s time to create our initialize function which will call the geolocation API to get the position data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Initialize geolocation
function initialize() {
  if (navigator.geolocation) {
    document.getElementById('status').innerHTML = 'Checking...';
    navigator.geolocation.getCurrentPosition(
      onSuccess,
      onError, {
        enableHighAccuracy: true,
        timeout: 20000,
        maximumAge: 120000
      });
  }
  else {
    document.getElementById('status').innerHTML = 'Geolocation not supported.';
  }
}

First we check if the browser actually supports geolocation. Browser who supports geolocation are Internet Explorer 9, Firefox 3.5+, Chrome 5+, Opera 10.6+ and Safari 5+. So it’s quite widely supported already, but if the user has an old browser we show them a message telling them that geolocation is not supported.

Next we set the status message to “Checking…” to tell the user that we’re trying to fetch the location data since this might take some time. Then we call navigator.geolocation.getCurrentPosition which will try to retrieve the user’s position, it calls the onSuccess function if it succeeds, otherwise it will call the onError. These functions will be created in the next two steps.

There’s also a few optional parameters to the getCurrentPosition function. These are enableHighAccuracy which tells the web browser to try using the clients GPS if possible, the default value for this is false. The timeout parameter tells the browser how long we’re ready to wait to get the position in milliseconds, the default value is infinite. Lastly we have the maximumAge parameter which tells the browser how old the position cache is allowed to be in milliseconds, the default value for maximumAge is 0 which turns off cache completely.

Since geolocation is a big privacy concern the W3C standards requires the user to agree to share their position before the location is sent to the website, so when we call the getCurrentPosition a information bar will be shown to the user where the user has to allow us to get the position, if the user denies the onError will be function will be called.

Tip

Don’t rely fully on getting the user’s location since the user might deny your site from retrieving the position or something might go wrong. Always have a fallback solution if retrieving the position is critical.

Step 3. On Success

Next we add an onSuccess function to our script section. This function will display the data received and call the loadMap function to load our map.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Map position retrieved successfully
function onSuccess(position) {
  var data = '';
  data += 'latitude: ' + position.coords.latitude + '<br/>';
  data += 'longitude: ' + position.coords.longitude + '<br/>';
  data += 'altitude: ' + position.coords.altitude + '<br/>';
  data += 'accuracy: ' + position.coords.accuracy + '<br/>';
  data += 'altitudeAccuracy: ' + position.coords.altitudeAccuracy + '<br/>';
  data += 'heading: ' + position.coords.heading + '<br/>';
  data += 'speed: ' + position.coords.speed + '<br/>';
  document.getElementById('data').innerHTML = data;
  loadMap(position.coords.latitude, position.coords.longitude);
}

This function is quite self explanatory, we build a string with the retrieved data found in the position variable and shows it to our user. You will always get the latitude, longitude and accuracy values but the rest is optional and will probably only be set if the user has a GPS which the data is retrieved from.

Lastly we call the loadMap function and give the latitude and longitude to show where the user is on a map.

Step 4. On Error

Since geolocation is quite complex a lot can go wrong and we need an error handler. There’s four different error codes, 0 is an unknown error, 1 occurs if you deny the browser from retrieving your location, 2 occurs if the browse somehow fails to retrieve the location and 3 if our timeout variable is too short and the timeout expired.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Error handler
function onError(err) {
  var message;
  switch (err.code) {
    case 0:
      message = 'Unknown error: ' + err.message;
      break;
    case 1:
      message = 'You denied permission to retrieve a position.';
      break;
    case 2:
      message = 'The browser was unable to determine a position: ' + error.message;
      break;
    case 3:
      message = 'The browser timed out before retrieving the position.';
      break;
  }
  document.getElementById('status').innerHTML = message;
}

This function is also quite easy to understand, we get the error as a parameter to our function and shows the user a message depending on the error code retrieved.

Step 5. Display the Map

Next we display a map in our map_canvas div. This has really nothing to do with the HTML5 geolocation. So I won’t explain this for you, but it shouldn’t be too hard to understand.

Tip

If you want to learn more about Google maps check out their API here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Integration with google maps
function loadMap(lat, lng) {
  var latlng = new google.maps.LatLng(lat, lng);
  var settings = {
    zoom: 14,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById('map_canvas'), settings);
  var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title: 'Your Position!'
  }); 
  document.getElementById('status').innerHTML = 'Position Found!';
}

That’s all for today. You can try out or download the finished code below.

Example

Try out the finished example here: Example.

Download

Download the source from here: Download

Black horizontal HTML and CSS dropdown menu

Simple and modern looking black menu template, horizontal dropdown web navigation. I will make and share more color skins in one of next posts. Customizable width size, current width of the menu is 950px (to change it edit 5th row in CSS file). If you have an average CSS knowledge, it will be easy to understand and update any detail in CSS code.

Check also two more web navigations in PSD format – website navigation menus set and horizontal HTML & CSS navigation.

horizontal dropdown menu

//

//

//

//

File Size (ZIP): 5 KB

Full size – JPG preview: Black dropdown menu

Format: HTML and CSS

Color theme: black, gray

Keywords: download horizontal menu template, black web navigation, web design elements, make your own web navigation

Author: PSD Graphics

Download HTML and CSS source:

Operating Systems and System Programming

Shellos

Course Description

Lectures



  1. Introduction, What is an Operating System Anyway???  Lecture

    favorites



  2. Concurrency: Processes, Threads, and Address Spaces  Lecture

    favorites



  3. Thread Dispatching  Lecture

    favorites



  4. Cooperating Threads  Lecture

    favorites



  5. Synchronization  Lecture

    favorites



  6. Readers-Writers; Language Support for Synchronization  Lecture

    favorites



  7. Tips for working in a Project Team/ Cooperating Processes and Deadlock  Lecture

    favorites



  8. Deadlock (continued) - Thread Scheduling  Lecture

    favorites



  9. Scheduling (continued)  - Protection: Kernel and Address Spaces  Lecture

    favorites



  10. Address Translation  Lecture

    favorites



  11. Address Translation 2, Caching and TLBs  Lecture

    favorites



  12. Caching and TLBs 2, Caching and Demand Paging  Lecture

    favorites



  13. Page Allocation and Replacement  Lecture

    favorites



  14. Page Allocation and Replacement 2, Survey of I/O Systems  Lecture

    favorites



  15. File Systems and Disk Management  Lecture

    favorites



  16. Queueing Theory, Filesystems  Lecture

    favorites



  17. Filesystems, Naming, and Directories  Lecture

    favorites



  18. Networks and Distributed Systems  Lecture

    favorites



  19. Network Protocols  Lecture

    favorites



  20. Network Protocols III Lecture

    favorites



  21. Network Communication Abstractions/RPC  Lecture

    favorites



  22. Protection and Security in Distributed Systems II  Lecture

    favorites



  23. ManyCore OS and Peer-to-Peer Systems  Lecture

    favorites