Wednesday, January 15, 2014

CTabcontrol with each tab containing a widget (Yii)

Suppose in Yii, we want to pass the content of a widget to a tab in the tab control

<?php
ob_start();
$this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$vulnerdataProvider,
    'itemView'=>'_latest_vulner'
));
$tab1Content=ob_get_contents();
ob_end_clean();

$this->widget('zii.widgets.jui.CJuiTabs',array(
    'tabs'=>array(
        'Tab1'=> array('content' => $tab1Content,'id' => 'tab1'),
        'tab2'=>array('content'=>'Content for tab 2', 'id'=>'tab2'),
    ),
    // additional javascript options for the tabs plugin
    'options'=>array(
        'collapsible'=>true,
    ),
));
?>

CTabView with partial view in each tab (Yii)

Suppose using Yii framework and we want to add a tab control in which each tab shows a partial view, the following codes shows how this can be done:

<?php
$nc_view=$this->renderPartial('_viewNodeConfig', array('project'=>$model), $return=true);
$user_view=$this->renderPartial('_viewUser', array('project'=>$model), $return=true);
$sim_view=$this->renderPartial('_viewSimulation', array('project'=>$model), $return=true);

$this->widget('CTabView',array(
    'activeTab'=>'tab2',
    'tabs'=>array(
        'tab1'=>array(
            'title'=>'Users',
            'content'=>$user_view,
        ),
        'tab2'=>array(
            'title'=>'Node Types',
            'content'=>$nc_view,
        ),
        'tab3'=>array(
            'title'=>'Simulations',
            'content'=>$sim_view,
        )
    ),
    'htmlOptions'=>array(
        //'style'=>'width:500px;'
    )
));
?>
In the above codes, the _viewNodeConfig.php is a partial view which looks like the following:
<?php 
$node_configs=new CActiveDataProvider('NodeConfig', 
    array(
     'criteria'=>array( 
      'condition'=>'audit_project_id=:projectId', 
      'params'=>array(':projectId'=>$project->id),
     ),
     'pagination'=>array( 
      'pageSize'=>4,
     ), 
    )
   );
   
$this->widget('zii.widgets.CListView', array(
 'dataProvider'=>$node_configs,
 'viewData'=>array('project'=>$project),
 'itemView'=>'/nodeConfig/_view',
)); 
?>

Sunday, January 12, 2014

Cascade delete in Yii model by overriding beforeDelete() and afterDelete() method

Yii provides Cascade using relations with the cascade constraint defined in database, which allows the user to delete cascade data when a model is deleted. However, in some cases, the user may want to perform this on his own (e.g. there may be some sophisticated conditioning involved during the cascade delete, or other resources such as images to be deleted associated with the model). In such a case, the user can override the beforeDelete() and afterDelete() method to perform the clean up (e.g. delete images and cascaded objects associated with the deleted model). Suppose we have a model class Project, and we want to delete a set of users as well as an image associated with the deleted Project model:

Step 1: Override beforeDelete()

Add a variable idCache to the User model class in protected/models/User.php:
private $idCache;
Next override the beforeDelete() method to assign User->id to idCache:
public function beforeDelete()
{
 $this->idCache = $this->id;

 return parent::beforeDelete();
}
The purpose of having idCache is to cache the User->id attribute in the beforeDelete() method and use it in the afterDelete() method (since the $User->id will no longer be available in the afterDelete() method

Step 2: Override afterDelete()

Next we will delete the associated users and image to the deleted Project model by overriding the afterDelete() method:
public function afterDelete()
{
 $criteria = new CDbCriteria(array(
   'condition' => 'project_id=:projectId',
   'params' => array(
    ':projectId' => $this->idCache),
  ));

 $users_associated_with_project = User::model()->findAll($criteria);

 foreach ($users_associated_with_project as $user)
 {
  $user->delete();
 }
 
 $filename=$this->getImagePath($this->idCache);
 if(file_exists($filename))
 {
  unlink($filename);
 }

 parent::afterDelete();
}

Create CListView of a model class in another model's view (Yii)

Suppose we have two models: Project and User, in which each Project owns a number of Users. We wish to display a list of associated users in the project instance's view

Modify the protected/views/project/view.php by adding the following line in the script file:

<?php $this->renderPartial('_viewUser', array('project'=>$model)); ?>

Next create a partial view protected/views/project/_viewUser.php with the following codes for its implementation:

<?php 
$users=new CActiveDataProvider('User', 
    array(
     'criteria'=>array( 
      'condition'=>'audit_project_id=:projectId', 
      'params'=>array(':projectId'=>$project->id),
     ),
    ),
    array( 
     'pagination'=>array( 
      'pageSize'=>20,
     ), 
    )
   );
   
$this->widget('zii.widgets.CListView', array(
 'dataProvider'=>$users,
 'viewData'=>array('project'=>$project),
 'itemView'=>'/user/_view',
)); 
?>

Cascade create a model and attach it to another model in Controller in a One-to-Many relationship (Yii)

Suppose we have a situation where we a set of users, each of which belong to a particular project. In Yii, we already create two models, namely Project and User. The User model class contains an attribute project_id, which is the id attribute value of the associated Project model. Now a user cannot be created without knowing the project_id it is associated with

Step 1:

In the protected/views/project/view.php, add a link to create user associated with the project:

<?php echo CHtml::link(CHtml::encode('Create user under the project'), array('user/create', 'project_id'=>$model->id)); ?>
The project_id allows the UserController (i.e. the controller associated with the User model) to identify the project_id to which the created user should be associated with.

Step 2:

In the protected/controllers/UserController.php, add a private member variable _project:

private $_project = null;

Next in the UserController.php, find the method filters(), and add one line for projectContext filter:

/**
 * @return array action filters
 */
public function filters()
{
 return array(
  'accessControl', // perform access control for CRUD operations
  'projectContext + create index admin', //check to ensure valid event context
 );
}

Next in the UserController.php, defines the following methods:

public function filterProjectContext($filterChain) 
{
 //set the project identifier based on either the GET or POST input
 //request variables, since we allow both types for our actions 
 $project_id = null;
 if(isset($_GET['project_id'])) 
  $project_id = $_GET['project_id'];
 else
  if(isset($_POST['project_id'])) 
   $project_id = $_POST['project_id'];
 $this->loadProject($project_id);
 //complete the running of other filters and execute the requested action
 $filterChain->run();
}

protected function loadProject($project_id) 
{ 
 //if the project property is null, create it based on input id 
 if($this->_project===null) 
 {
  $this->_project=Project::model()->findbyPk($project_id); 
  if($this->_project===null)
  { 
   throw new CHttpException(404,'The requested project does not exist.'); 
  }
 }
 return $this->_project;
}
The above method allows Yii code to create and assign the _project with the content from database using the project_id passed in from Step 1. As a result, before the actionCreate() method is invoked, the _project is already properly initialized based project_id attribute passed in. The final step is to assign $user->project_id in the actionCreate() method of the UserController class, as shown below:
public function actionCreate()
{
 $model=new User;
 $model->project_id=$this->_project->id;

 // Uncomment the following line if AJAX validation is needed
 // $this->performAjaxValidation($model);

 if(isset($_POST['User']))
 {
  $model->attributes=$_POST['User'];
  if($model->save())
   $this->redirect(array('view','id'=>$model->id));
 }

 $this->render('create',array(
  'model'=>$model,
 ));
}

Use of beforeSave() and beforeValidate() for Yii models when writing to database

beforeValidate() is very handy for performing validation of the model before it is save to the database in Yii, below shows an example of how it is used in a Yii model class Project

protected function beforeValidate() 
{
 if($this->isNewRecord)
 {
  // set the create date, last updated date and the user doing the creating
  $this->audit_create_time=$this->audit_update_time=new CDbExpression('NOW()');
  $this->audit_update_time=new CDbExpression('NOW()'); 
  
  $existing_proj=Project::model()->find('projname=?', array($this->projname));
  if(isset($existing_proj))
  {
   return false;
  }
 }
 else
 {
  //not a new record, so just set the last updated time and last updated user id
  $this->audit_update_time=new CDbExpression('NOW()'); 
 }
 
 return parent::beforeValidate();
}
The above code checks whether a project with the same projname already exist in the database, if yes, then the validation return false, it also updates the create time and update time depending on whether the action is to create or update a project.

beforeSave() is useful to perform additional data processing before a model is saved to the database, below shows an example of how it is used in a Yii model class User

public function beforeSave()
{  
 if($this->isNewRecord)
 {
  $this->audit_db_create_time=$this->audit_db_update_time=new CDbExpression('NOW()');
 }
 else
 {
  $this->audit_db_update_time=new CDbExpression('NOW()'); 
 }
 
 $this->password=$this->encrypt($this->password);
 
 return TRUE;
}
The above code encrypt the password before it is saved to the database, it also updates the create time and update time for writing the model to the database depending on whether the action is to create or update a user

Some useful HTML elements in Yii

Create Html Link in Yii

  1. The code below creates a html link to user view which has id = 23
    <?php echo CHtml::link(CHtml::encode('View User with ID = 23'), array('user/view', 'id'=>23)); ?>
    
  2. The code below creates a html link to the html form for creating a user
  3. <?php echo CHtml::link(CHtml::encode('Create User'), array('user/create')); ?>
    

Create Html Label in Yii

The code below creates a html label

<?php echo CHtml::label(CHtml::encode('Some Text'), 'Some Text'); ?>

Create Html ComboBox in Yii

The code below creates a html combobox

<?php echo $form->dropDownList($model, 'field_name', array(1=>'test1', 2=>'test2'));?>
The code belows creates a html combobox with list data populating dropdown from database values
<?php echo $form->dropDownList($model,'node_types_id', CHtml::listData(NodeTypes::model()->findAll(array('order' => 'name')),'id','name'));?>

Thursday, January 9, 2014

Explore Network-Network interface from a client to a host using Traceroute

Traceroute (tracert on Windows OS) is a program that allows user to examine and explore a network by sending packet one hop further at a time (which then returns back and the round trip time to that hop can be computed) until reaching the destination host.

To use it on Windows, open the command line and enter the following example:
tracert www.uw.edu


Moving signal in frequency domain (MATLAB)

In this post, i am going to show how a moving signal (in time domain) remain unchanged in the frequency domain using MATLAB

The following codes generate a 21 moving signal with the same profile defined by sech(x)

clear all; close all; clc;

T=30;
n=512;

t2=linspace(-T/2, T/2, n+1);

t=t2(1:n);

k=(2*pi/T)*[0:n/2-1 -n/2:-1];
ks=fftshift(k);

slice=0:0.5:10;

[T, S]=meshgrid(t, slice);
[K, S]=meshgrid(ks, slice);

U=sech(T-10*sin(S));
subplot(2, 1, 1);
waterfall(T, S, U), colormap([0 0 0]), view(-15, 70);

[X,Y] = meshgrid(xgv,ygv) replicates the grid vectors xgv and ygv to produce a full grid. This grid is represented by the output coordinate arrays X and Y. The output coordinate arrays X and Y contain copies of the grid vectors xgv and ygv respectively. The sizes of the output arrays are determined by the length of the grid vectors. For grid vectors xgv and ygv of length M and N respectively, X and Y will have N rows and M columns.

U=sech(T-10*sin(S)).*exp(i*0*T) creates the 21 moving signals in time domain in a matrix of size length(slice)*length(t)

waterfall(T, S, U) plots the moving signals as shown in the figure below

Image and video hosting by TinyPic

The following MATLAB code plot the moving signals in both the time domain and frequency domain

clear all; close all; clc;

T=30;
n=512;

t2=linspace(-T/2, T/2, n+1);

t=t2(1:n);

k=(2*pi/T)*[0:n/2-1 -n/2:-1];
ks=fftshift(k);

slice=0:0.5:10;

[T, S]=meshgrid(t, slice);
[K, S]=meshgrid(ks, slice);

U=sech(T-10*sin(S));
subplot(2, 1, 1);
waterfall(T, S, U), colormap([0 0 0]), view(-15, 70);

for j=1:length(slice)
    UT(j, :)=abs(fftshift(fft(U(j, :))));
end


subplot(2, 1, 2);
waterfall(K, S, UT), colormap([0 0 0]), view(-15, 70);

The figure below shows the moving signals in both the time domain and frequency domain, it can be seen that the frequency spectrum of all the moving signals remain unchanged

Image and video hosting by TinyPic

Wednesday, January 8, 2014

Convergence to signal through repeated sampling to average out white-noise in signals (MATLAB)

Normally a filter such as Guassian filter requires that the user knows that frequency they want to look over. However, if a signal is given to a user without telling him/her where to look for the desired signal frequency, the Guassian filter approach may not work, in this case, we can make use of the idea that white noises are always out of phases and random. In this case, we can repeatedly sample signals containing white noise and average them in the frequency domain, potentially cancelling out the white noise

The MATLAB code below creates a noisy signal (un in time domain and utn in frequency domain) from the sech(t) function (u in time domain and ut in frequency domain

clear all; close all; clc;

T=30;
n=512;

t2=linspace(-T/2, T/2, n+1);

t=t2(1:n);

k=(2*pi/T)*[0:n/2-1 -n/2:-1];
ks=fftshift(k);

u=sech(t);

ut=fft(u);
noise=30;
utn=ut+noise*(randn(1, n)+i*randn(1, n));
un=ifft(utn);

subplot(2, 1, 1); plot(t, u, 'k', t, un);
subplot(2, 1, 2); plot(ks, abs(fftshift(ut)), 'k', ks, abs(fftshift(utn)));

Below shows the noisy signal and the original signal in both time and frequency domain

Image and video hosting by TinyPic

The following MATLAB code creates 30 sample noisy signals then take the average of the signals in the frequency domain, which is then converted back to the time domain using ifft

clear all; close all; clc;

T=30;
n=512;

t2=linspace(-T/2, T/2, n+1);

t=t2(1:n);

k=(2*pi/T)*[0:n/2-1 -n/2:-1];
ks=fftshift(k);

u=sech(t);

ut=fft(u);
noise=30;
avg=zeros(1, n);
realizations=30;
for j=1:realizations % 30 sample signals in time and frequency domain, each with periodic domain of T=30
    utn=ut+noise*(randn(1, n)+i*randn(1, n));
    un=ifft(utn);
    avg=avg+utn;
end

unf=ifft(avg);
avg=abs(fftshift(avg))/realizations;

subplot(2, 1, 1); plot(t, u, 'r', t, un, 'c', t, unf, 'k');
subplot(2, 1, 2); plot(ks, abs(fftshift(ut)), 'r', ks, abs(fftshift(utn)), 'c', ks, avg, 'k');

The figure below shows the filtered results using the convergence via averaging of signal samples in frequency domain

Image and video hosting by TinyPic

The MATLAB code below further shows an animation of convergence as the number of samples taken is increased.

clear all; close all; clc;

T=30;
n=512;

t2=linspace(-T/2, T/2, n+1);

t=t2(1:n);

k=(2*pi/T)*[0:n/2-1 -n/2:-1];
ks=fftshift(k);

u=sech(t);

ut=fft(u);
noise=30;
avg=zeros(1, n);
realizations=30;
for j=1:realizations % 30 sample signals in time and frequency domain, each with periodic domain of T=30
    utn=ut+noise*(randn(1, n)+i*randn(1, n));
    un=ifft(utn);
    avg=avg+utn;
    
    avg2=abs(fftshift(avg))/realizations;
    unf2=ifft(avg);
    subplot(2, 1, 1); plot(t, u, 'k', t, unf2);
    subplot(2, 1, 2); plot(ks, abs(fftshift(ut)), 'r', ks, avg2, 'k');
    
    pause(0.5);
end

unf=ifft(avg);
avg=abs(fftshift(avg))/realizations;

subplot(2, 1, 1); plot(t, u, 'r', t, un, 'c', t, unf, 'k');
subplot(2, 1, 2); plot(ks, abs(fftshift(ut)), 'r', ks, abs(fftshift(utn)), 'c', ks, avg, 'k');

Denoising via Filtering in MATLAB

In this post, i am going to show how to denoise a signal using a Gaussian filter in MATLAB

The MATLAB code below generates a noisy signal (i.e., un) from the function sech(x) (i.e., u) by adding a white noise via its frequency domain spectrum (ut is the fft of u and utn is the fft of un)

clear all; close all; clc;

T=30;
n=512;

t2=linspace(-T/2, T/2, n+1);

t=t2(1:n);

k=(2*pi/T)*[0:n/2-1 -n/2:-1];
ks=fftshift(k);

u=sech(t);

ut=fft(u);
noise=7;
utn=ut+noise*(randn(1, n)+i*randn(1, n));
un=ifft(utn);

subplot(2, 1, 1); plot(t, u, 'k', t, abs(un), 'm');
subplot(2, 1, 2); plot(ks, abs(fftshift(ut))/max(abs(fftshift(ut))), 'k', ks, abs(fftshift(utn))/max(abs(fftshift(utn))), 'm');

axis([-25 25 0 1]);

The figure below shows the resulting plots

Image and video hosting by TinyPic

The MATLAB code below shows the use of a gaussian filter which is multiplied with the fft of the noisy signal (i.e., utn) to obtained the fft of a filtered noisy signal (i.e., utnf) which is then converted back to the time domain filtered noisy signal (i.e., unf) that is denoised

clear all; close all; clc;

T=30;
n=512;

t2=linspace(-T/2, T/2, n+1);

t=t2(1:n);

k=(2*pi/T)*[0:n/2-1 -n/2:-1];
ks=fftshift(k);

u=sech(t);

ut=fft(u);
noise=7;
utn=ut+noise*(randn(1, n)+i*randn(1, n));
un=ifft(utn);

filter=exp(-k.^2); %guassian filter
utnf=filter.*utn;

unf=ifft(utnf);

subplot(2, 1, 1); plot(t, u, 'k', t, un, 'm', t, unf, 'g');
subplot(2, 1, 2); plot(ks, abs(fftshift(ut))/max(abs(fftshift(ut))), 'k', ks, abs(fftshift(utn))/max(abs(fftshift(utn))), 'm', ...
    ks, fftshift(filter), 'b', ...
    ks, abs(fftshift(utnf))/max(abs(fftshift(utnf))), 'g');

axis([-25 25 0 1]);

The figure below shows the resulting plots (where the green line shows the denoised signal in time and frequency domain

Image and video hosting by TinyPic

Note that in the above MATLAB code it assume that the user knows the frequency they want to look at (in this case it is centered at k=0), therefore the gaussian filter is center at that frequency range (i.e. that guassian is centered at k=0)

The following MATLAB code allows user to vary the width (i.e., sigma) and the location (i.e., the mu) of the Guassian signal

clear all; close all; clc;

T=30;
n=512;

t2=linspace(-T/2, T/2, n+1);

t=t2(1:n);

k=(2*pi/T)*[0:n/2-1 -n/2:-1];
ks=fftshift(k);

u=sech(t);

ut=fft(u);
noise=7;
utn=ut+noise*(randn(1, n)+i*randn(1, n));
un=ifft(utn);

sigma=1;
mu=0;

filter=1 / (sigma * (2*pi)^0.5) * exp(-(k-mu).^2/(2*sigma&2)); %guassian filter
utnf=filter.*utn;

unf=ifft(utnf);

subplot(2, 1, 1); plot(t, u, 'k', t, un, 'm', t, unf, 'g');
subplot(2, 1, 2); plot(ks, abs(fftshift(ut))/max(abs(fftshift(ut))), 'k', ks, abs(fftshift(utn))/max(abs(fftshift(utn))), 'm', ...
    ks, fftshift(filter), 'b', ...
    ks, abs(fftshift(utnf))/max(abs(fftshift(utnf))), 'g');

axis([-25 25 0 1]);

Add noise to the time series signal using Fourier Transform and Frequency Domain Power Spectrum in MATLAB

In this post, i am going to show how to add noise to the time series signal (assume the time series signal is sech(t) in this post) via its frequency domain spectrum in MATLAB

The MATLAB code below plots the time domain (i.e., u) and frequency domain (i.e., ut) of signal sech(t) (using 512 points in time domain data with periodic domain set to T=30)

clear all; close all; clc;

T=30;
n=512;

t2=linspace(-T/2, T/2, n+1);

t=t2(1:n);

k=(2*pi/T)*[0:n/2-1 -n/2:-1];
ks=fftshift(k);

u=sech(t);

ut=fft(u);

subplot(2, 1, 1); plot(t, u);
subplot(2, 1, 2); plot(ks, abs(fftshift(ut))/max(abs(fftshift(ut))));

axis([-25 25 0 1]);

The code abs(fftshift(ut))/max(abs(fftshift(ut))) normalize the power spectrum value to be between 0 and 1

The code below shows the resulting plot

Image and video hosting by TinyPic

The code below adds a white noise with normal distribution (noise~N(0, 1)) to the frequency domain (i.e., utn) which is then converted to back to the time domain (i.e. un)

clear all; close all; clc;

T=30;
n=512;

t2=linspace(-T/2, T/2, n+1);

t=t2(1:n);

k=(2*pi/T)*[0:n/2-1 -n/2:-1];
ks=fftshift(k);

u=sech(t);

ut=fft(u);
noise=1;
utn=ut+noise*(randn(1, n)+i*randn(1, n));
un=ifft(utn);

subplot(2, 1, 1); plot(t, u, 'k', t, abs(un), 'm');
subplot(2, 1, 2); plot(ks, abs(fftshift(ut))/max(abs(fftshift(ut))), 'k', ks, abs(fftshift(utn))/max(abs(fftshift(utn))), 'm');

axis([-25 25 0 1]);

The image below shows the resulting plot

Image and video hosting by TinyPic

Inverse Fast Fourier Transformation in MATLAB

In this, i am going to show how the inverse fast fourier transformation can be used to find the $n^{th}$ derivative of a hyperbolic secant function sech(x)

Fourier transform has the an amazing property: $\hat{f^{(n)}(k)}=(ik)^n\hat{f(k)}$ where $k$ is the frequency of the Fourier Transform $\hat{f(k)}=\frac{1}{2L} \int_{-L/2}^{L/2} f(x)exp(-i k \pi x/L)dx$ and $f^{(n)}$ is the $n^{th}$ derivative of the function $f(x)$. Therefore $\hat{f^{(n)}(k)}$ is the Fourier transform of the $n^{th}$ derivative of $f(x)$.

Due to this property, we can find the $n^{th}$ derivative of $f(x)$ by first obtaining the $\hat{f^{(n)}(k)}$ then performing an inverse Fourier transform

The sample code below first computes the first and second derivative of sech(x) (i.e. ud and u2d) then compare it against the ones computed using the method described above using inverse Fourier Transform (ifft) (i.e. uds and u2ds) and finally plot ud versus uds

clear all; close all; clc;

L=20;
n=128;

x2=linspace(-L/2, L/2, n+1);

x=x2(1:n);

k=(2*pi/L)*[0:n/2-1 -n/2:-1];

u=sech(x);
ud=-sech(x).*tanh(x);
u2d=sech(x)-2*sech(x).^3;

ut=fft(u);

uds=ifft((i*k).*ut);
u2ds=ifft((i*k).^2.*ut);

ks=fftshift(k);

plot(x, ud, 'r', x, uds, 'mo');

Fast Fourier Transform Sample Code in MATLAB

The following matlab code computes and plots the fourier transform of the gaussian function exp(x^2) (the periodic domain is set to -L / 2 to L / 2) in MATLAB:

clear all; close all; clc;

L=20;
n=128;

x2=linspace(-L/2, L/2, n+1);

x=x2(1:n);

k=(2*pi/L)*[0:n/2-1 -n/2:-1];

u=exp(-x.^2);

ut=fft(u);

plot(fftshift(k), abs(fftshift(ut)));

The MATLAB function fft run in O(n * log(n)) complexity and assumes the periodic domain from 0 to 2*pi, therefore the value vector k is scaled for that the frequency spectrum ut corresponds to (-L/2, L/2). Note that n is power of 2 since the reason fft is able to speed up from O(n^2) to O(n*log(n)) using divide and conquest by dividing the computation into two separate computation each time. linspace() generates (n+1) values evenly from -L/2 to L/2 (inclusive, therefore should be n+1 instead of n, but x takes only the first n values from x2). fftshift rearranges the outputs of fft, fft2, and fftn by moving the zero-frequency component to the center of the array.