Monday 10 September 2012

building simple applications with EasyGui library



i have been working on the python GUI library from few days now and found this amazing library to build simple gui application in matter of mins.

EasyGui uses the Tkinter to create the various gui components, its not as complex as PyQt or pygtk but fair enough to create a applications

here is example of simple file viewer which can be used to open a text files or code file for preview

#demo applicatio to create gui application using the easygui python library 

#importing the library file 
from easygui import *
import os
import sys

#simple application to browse and view files

#declaring the class fileviewer
class fileviewer:

    def __init__(self):
        #file open prompt
        self.menu()
        
    def menu(self):
        ch=indexbox('Simple File Viewer','Menu',['View File','Exit'])
        if ch ==0:
            #open file select and opne the file
            self.open_file()
            self.menu()
        elif ch ==1:
            #exit the applicaiton
            sys.exit()
            

    def open_file(self):
        #open the file in codebox
        file_name=fileopenbox("please select file to be opened")
        filename = os.path.normpath(file_name)
        text = open(filename,'rb').read()
        codebox("Contents of file " + filename, text=text)
        
        
if __name__ == '__main__':
    fileviewer()





Friday 29 June 2012

simple cakephp CRUD operation

had some time to work on very popular framework cakephp, never find time and patience lookup the code generator console in cake. just jumped into coding and like to keep this handy... for creating a quick CRUD template 

 
<?php
simple crud operation in cakephp 2.x

create a controller which extend the base framework controller class
class TestsController extend AppController {
//read about class name convention in detail for the cakephp 

public $name = 'tests';
public $helper=array('Html','Form'); //for creating the form and html link in the view 
public function add(){
 if ($this->request->is('post')) {  //check whether request type is post before accepting the data 
            if ($this->Page->save($this->request->data)) {// save the data
                $this->Session->setFlash('Your data has been saved.'); // generate a flash message 
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('Unable to add your data.');
            }
        }
}


public function index(){
$this->set('test', $this->Test->find('all')); 
/* model which look up in the databases table "tests" and fetch all the content */ 
}

public function edit($id = null){
          $this->Test->id = $id;   // set the id to the model id value
                 if ($this->request->is('get')) { // check request type
               $this->request->data = $this->Test->read(); //read record with id and display the form regularly 
                 } else {
                      if ($this->Test->save($this->request->data)) {  // if post request save the data
                          $this->Session->setFlash('Your data has been updated.');
                          $this->redirect(array('action' => 'index'));
                     } else {
                          $this->Session->setFlash('Unable to update your data.');
                 }
}

   public function view($id=null){
        $this->Test->id = $id; //action to display the content or view the content
        $this->set('test', $this->Test->read());
   }

 public function delete($id=null){ // critical action 

   if ($this->request->is('get')) {
        throw new MethodNotAllowedException(); // throw error if request is get and break
        }
  
            if ($this->Test->delete($id)) { // deleted 
                 $this->Session->setFlash('The page with id: ' . $id . ' has been deleted.');
                  $this->redirect(array('action' => 'index'));
           
               }

}



}
?>






Thursday 12 April 2012

zend CRUD action example

hi


starting off with create action / add action
 class ExampleController extends Zend_Controller_Action{  
 public function createAction(){  
    $form = // create a form or call a model form class  
    if ($this->getRequest()->isPost()) { // processing the form after the submission  
        if ($form->isValid($this->_request->getPost())) // check wheather the form data is valid  
    {  
 // do stuff  
         }  
                    }  
 }  
 $this->view->form=$form; // send the form to the view  
 }  
 //update action and modified action  
 class ExampleController extends Zend_Controller_Action{  
 public function updateAction(){  
     $id = $this->getRequest()->getParam('id');  
    $form = // create a form or call a model form class  
   if ($id > 0) {  
 if ($this->getRequest()->isPost()){  
      if ($form->isValid($this->_request->getPost())){  
            //if valid do some stuff  
 }else{  
   //reload the form with error message  
 }  
 }else{  
      //if the form not submitted load the form with default values  
 }  
 }  
 $this->view->form=$form; // send the form to the view  
 }  
 }  
 // view action  
 class ExampleController extends Zend_Controller_Action{  
 public function viewAction(){  
  $id = $this->getRequest()->getParam('id');  
 if($id>0){  
 // display content in the view template file  
 }  
 }  
 }  
 // delete acion  
 class ExampleController extends Zend_Controller_Action{  
 public function deleteAction(){  
    $id = $this->getRequest()->getParam('id');  
    if ($sid > 0) {  
    //do some stuff  
    $this->db->delete("id = $id");  
    $this->_redirect('');//redirection  
    }  
   }  
 }  

Sunday 18 March 2012

palindrome in ruby

working with ruby code

simple method to check whether given string is palindrome. method will return true if the given string is palindrome or return false
 def palindrome?(string)  
   str=string.downcase;  
   str=str.gsub(/[^a-z]/,'');  
   return str.eql? str.reverse;  
 end  

Wednesday 15 February 2012

yii framework popup example


in this example i will implement a simple popup form to create action from controller.i am using the gii for generating the code for the CRUD

code inside controller
 public function actionCreate()  
     {  
         $model=new ExampleModel;  
         // Uncomment the following line if AJAX validation is needed  
         //$this->performAjaxValidation($model);  
          if(isset($_POST['Apply']))  
          {  
             $model->attributes=$_POST['Apply'];  
          if($model->save()){ //save the record to the database  
        if (Yii::app()->request->isAjaxRequest) // check for ajax request  
          {  
         echo CJSON::encode(array(  // display message  
                   'status'=>'success',  
                   'div'=>"Classroom successfully added"  
               ));  
              exit;         
      }  
      else{  
    $this->redirect(array('post/view','id'=>$model->aid)); // if the condition fail redirect the user to post/view  
                       }  
                   }  
         }  
   if (Yii::app()->request->isAjaxRequest) // check the condition  
   {  
    echo CJSON::encode(array(  
    'status'=>'failure',  
    'div'=>$this->renderPartial('_form', array('model'=>$model), true)));  
      exit;         
   }  
   else{  
      $this->render('create',array(  // return the form  
      'model'=>$model,  
    ));  
                 }  
  $this->refreash();  
     }  
 below section is the code need to insert inside your view file where ever you want the popup to be displayed  
 code inside your view  
 <?php  
  echo CHtml::link('apply for job', "", // the link for open the dialog  
   array(  
     'style'=>'cursor: pointer; text-decoration: underline;',  
     'onclick'=>"{addClassroom(); $('#dialogClassroom').dialog('open');}"));  
 ?>  
 <?php  
 $this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog  
   'id'=>'dialogClassroom',  
   'options'=>array(  
     'title'=>'Create classroom',  
     'autoOpen'=>false,  
     'modal'=>true,  
     'width'=>550,  
     'height'=>470,  
   ),  
 ));?>  
 <?php  
 $this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog  
   'id'=>'dialogClassroom',  
   'options'=>array(  
     'title'=>'Create classroom',  
     'autoOpen'=>false,  
     'modal'=>true,  
     'width'=>550,  
     'height'=>470,  
   ),  
 ));?>  
 <div class="divForForm"></div>  
 <?php $this->endWidget();?>  
 <script type="text/javascript">  
 // here is the magic  
 function addClassroom()  
 {  
   <?php echo CHtml::ajax(array(   // code for the javascript  
       'url'=>array('apply/create&id='.$model->id),  
       'data'=> "js:$(this).serialize()",  
       'type'=>'post',  
       'dataType'=>'json',  
       'success'=>"function(data)  
       {  
         if (data.status == 'failure')  
         {  
           $('#dialogClassroom div.divForForm').html(data.div);  
              // Here is the trick: on submit-> once again this function!  
           $('#dialogClassroom div.divForForm form').submit(addClassroom);  
         }  
         else  
         {  
           $('#dialogClassroom div.divForForm').html(data.div);  
           setTimeout(\"$('#dialogClassroom').dialog('close') \",300);  
         }  
       } ",  
       ))?>;  
   return false;  
 }  
 </script>  

Friday 13 January 2012

the first time login in drupal

hi

it certainly look pretty simple to detect the first time login event using hook_user to check for "login" operation and check the users object "$user->login" value.

code:


 <?  
  function mycustom_user($op,&$edit,&$account,$category = NULL){  
 if($op == 'login'){  
 if($account->login == 0){ // check the last login  
 //do stuff here  
 }  
 }  
 }  
 ?>  



this work just fine if you want to impletement a redirection once the user login for the first time.

but what if you have to check users first time login on search page or user profile page.in that particular condition the above code does not work. because the
the value of user->login will be updated as soon as user login.

there is a simple module which manage the user Statistics called user_stats 
it manage the user login count which comes in handy here.

here is the code to get the login count from user_stats

 <?php  
  global $user  
 if(user_stats_get_stats('login_count',$user->uid) == 1){ //check that its user first time login  
 drupal_set_message("some message");  
 //do the stuff  
 }  
 ?>  

 
well you can use this module in many way for getting reg date much more..

well this come in very handy to solve my problem.