Wednesday, December 15, 2010

How to unlock Iphone 4 iOS 4.1 at baseband 2.10.04?

I have an iPhone 4 with iOS 4.1 at baseband 2.10.04. I want to use the iPhone on a different network as I am traveling out of country? Can anyone point me in the right direction?
I will write a how-to tutorial once I can do it on my iPhone 4.

Friday, November 19, 2010

Bouncing Orbs

I recently finished a major milestone for a C++/SDL game development course. It is my first mini-game/animation. It was an awesome programming  experience. It was amazing to learn things like parallax scrolling, creating explosions, save/restore of animation state in Xml(expat). Thank you Dr. Malloy.

Tuesday, November 2, 2010

Python - Writing a traceroute using sockets

I recently learned, how to write a traceroute using socket programming in python. I am sharing it below. I don't take any credit for the code. I may have picked bits and pieces from various different resources on the Internet, as a part of my learning process. It's not very elegant but demonstrates the purpose. Perhaps, some day I can improve it and add few enhancements to it.

#!/usr/bin/python
import sys
import socket

def traceroute(dest_name):
    dest_addr = socket.gethostbyname(dest_name)
    port = 33434
    max_hops = 30
    print dest_name
    icmp = socket.getprotobyname('icmp')
    udp = socket.getprotobyname('udp')
    ttl = 1
    while True:
        print ttl,
        recv_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, udp)
        send_socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
        recv_socket.bind(("", port))
        send_socket.sendto("", (dest_name, port))
        curr_addr = None
        curr_name = None
        try:
            _, curr_addr = recv_socket.recvfrom(512)
            curr_addr = curr_addr[0]

            try:
                curr_name = socket.gethostbyaddr(curr_addr)[0]
            except socket.error:
                curr_name = curr_addr
        except socket.error:
            pass
        finally:
            send_socket.close()
            recv_socket.close()

        if curr_addr is not None:
            curr_host = "%s (%s)" % (curr_name, curr_addr)
        else:
            curr_host = "*"
        print "%d\t%s" % (ttl, curr_host)

        ttl += 1
        if curr_addr == dest_addr or ttl > max_hops:
            break

if __name__ == "__main__":
    traceroute(sys.argv[1])


Can be executed as -

>sudo ./traceroute.py xharpreetx.com

Thursday, October 7, 2010

C++ - Maps and Vectors

 I have been learning something really exciting this semester. It is a grad course called Object oriented software development using C++. Apart from learning the pillars of object orientation i.e. encapsulation, inheritance and polymorphism, I have got a chance to delve into game programming. It is a challenging domain and I will post some of my animation/game videos sometime soon.
The other day, I was writing some code to familiarize myself with vectors and maps. Here it goes -
#include <iostream>
#include
<map>
#include
<vector>
using std::string;
using std::cout;
using std::endl;
using std::vector;

//Todo: check how to use overloading for 'print' function
void print(std::map
<string,int> &m) {
  std::map
<string,int>::const_iterator it;
  for(it=m.begin();it!=m.end();++it) {
    std::cout << (it)->first << " = " << (it)->second << std::endl; 
  }
}
//Todo: check how to use overloading for 'print' function
void print(vector
<int> v) {
  vector
<int>::const_iterator it;
  for(it=v.begin();it!=v.end();++it) {
    std::cout<< (*it) << std::endl;
  }
}

void initializevec(vector
<int> &vec) {
  for (unsigned int i = 0 ; i < 20; ++i) {
    vec.push_back(i);
    //demonstrates how capacity grows as size of vector increases
    cout << "size = " << vec.size() << " capacity = " << vec.capacity() << endl;
  }
}

int main() {
  cout<< " MAP " << endl;
  std::map
<string,int> mymap;
  mymap["b"] = 1;
  mymap["a"] = 2;
  mymap["c"] = 5;
  mymap["d"] = 3;

  print(mymap);
  cout << "size = " << mymap.size() << endl;

  std::map
<string,int>::iterator it = mymap.find("c");
  cout<< "Deleting 'c' ... " <
  mymap.erase(it);
  print(mymap);
  cout << "size = " << mymap.size() << endl;   
  std::cout << std::endl;

  cout<< " VECTOR " << endl;
  vector
<int> vec;
  initializevec(vec);

  vec.push_back(13);
  print(vec);

  return 0;
}

Compile using -
g++ -W -Wall -Weffc++ -ggdb -O0 filename.cpp

It demonstrates some basic operations of maps and vectors. It was nice to understand how vectors increase their 'capacity' to accommodate new elements.

Friday, September 17, 2010

Yii - data grid view with some customization of cell content format

Lets start by creating a simple table

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(128) NOT NULL,
  `activationKey` varchar(128) NOT NULL DEFAULT '',
  `createtime` int(10) NOT NULL DEFAULT '0',
  `lastvisit` int(10) NOT NULL DEFAULT '0',
  `superuser` int(1) NOT NULL DEFAULT '0',
  `status` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  KEY `status` (`status`),
  KEY `superuser` (`superuser`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Configure the database connection as shown in one of the earlier posts.

Generate the corresponding model for the table in your database by executing the following commands
>protected\yiic shell

>> model *

Now, I want to create a data grid view to show the details of the table.

To show a link to the new "users" page(with a data grid) on navigation bar, open the file ..\mytestapp\protected\views\layouts\main.php

and add the following entry, in the "mainmenu" div.


widget('zii.widgets.CMenu',array(
            'items'=>array(
array('label'=>'Home', 'url'=>array('/site/index')),
array('label'=>'Users', 'url'=>array('/site/users')),  //####### new entry
array('label'=>'About', 'url'=>array('/site/page', 'view'=>'about')),
array('label'=>'Contact', 'url'=>array('/site/contact')),
array('label'=>'Login', 'url'=>array('/site/login'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest)
),
)); ?>



The site controller needs information about where to render the new "users" page.
This can be done by adding the following method in the ..\mytestapp\protected\controllers\SiteController.php file

public function actionUsers()
    {
    $dataProvider=new CActiveDataProvider('Users');
    $this->render('users',array('dataProvider'=>$dataProvider,
                ));
    }

As you would notice that these methods should begin with "action" prefix.

Create a new file "users.php" at this location
..\mytestapp\protected\views\site\users.php

The contents of this file would look something like this-


$this->pageTitle=Yii::app()->name . ' - Users';
$this->breadcrumbs=array(
    'Users',
);

?><h1>Users

beginWidget('CActiveForm', array(
    'id'=>'members-form',
    'enableAjaxValidation'=>true,
)); ?>

widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'columns'=>array(
   array(
    'name'=>'id',
    'value'=>'CHtml::encode($data->id)'
   ),
   array(
    'name'=>'username',
    'value'=>'CHtml::encode($data->username)'
   ),
   array(
    'name'=>'createtime',
    'value'=>'CHtml::encode(date(\'Y-m-d\', $data->createtime))'  //this will format the unix timestamp to a custom date format
   ),
   array(
     'name'=>'lastvisit',              
     'value'=>'CHtml::encode(date(\'Y-m-d\', $data->lastvisit))'      // format the cell with date format
   ),
   array(
     'name'=>'status',
     'value'=>'CHtml::encode($data->status==1 ? \'Active\': \'Inactive\' )' 
// to render the gridview cell with a particular value
    ),
    ),
)); ?>
endWidget(); ?>


The page should be hosted at
http://localhost/mytestapp/index.php/site/users
or
http://localhost/mytestapp/index.php/?r=site/users

depending on the url manager setting in the config file.

Thursday, September 9, 2010

Setup and debug an Yii app in Netbeans IDE

After using Eclipse for a while I switched to Netbeans IDE for Yii development. It seems faster and easier to setup. Following is my experience of setting up the development environment.

Create a project stub using the following command -
>> yii-1.1.3.r2247\framework\yiic webapp mytestapp

Open Netbeans IDE and proceed with the following steps -
1. Click on File-> New Project
    This will open up a dialog box. Select "PHP" under "Categories" and under "Projects" select "PHP Applications with Existing Sources".


    Click Next.
2. In the "Sources Folder", input the path of "mytestapp" folder on your machine.
    Assign a project name. "mytestapp" for my case.
    Select a PHP version.
    Click Next
3. The options in this form should be set up automatically like below.
   

    Click Finish
   
    This should set up your Yii project in Netbeans IDE.
   
4. Go to "Debug" menu on the top bar on Netbeans IDE. Select "Debug Project(mytestapp)" and you should be able to debug your project.


5. "Continue(F5)" option in Debug can be used to resume a stopped debug session.
   

Tuesday, August 24, 2010

Yii - Authentication from mysql database using a md5 password

Before proceeding make sure the database has been connected to Yii application. (see previous post)
For this example, the passwords are stored in the database as md5 hash.
You may be required to change the password encoding scheme.

Edit the authenticate method in ../my_app/protected/components/UserIdentity.php to look like this -

public function authenticate()
    {
        //$users=array(
            // username => password
            //'demo'=>'demo',
            //'admin'=>'admin',
        //);
       
        $user = myUsersTable::model()->findByAttributes( array( 'my_userid_column_name' => $this->username));
        if ($user===null) { // No user was found!
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        }
        // $user->Password refers to the "password" column name from the database
        else if($user->Password !== md5("my_salt1".$this->password))
        {   
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        }
        else { // User/pass match
            $this->errorCode=self::ERROR_NONE;
        }       
        return !$this->errorCode;
    }

Enter the username/password pair on the login page and you should be good to go.