GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Thursday, April 28, 2011

C - Default Function

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    char *name;
    char *city;
    int age;
}data;

int addName(data *d){
    d->name = "lady gaga";

    return 0;
}

int addCity(data *d){
    d->city = "new york";

    return 0;
}

int addAge(data *d){
    d->age = 24;

    return 0;
}

int set_default(data *d){

    addName(d);
    addCity(d);
    addAge(d);

    return 0;
}

char* getName(data *d){
    return d->name;
}

char* getCity(data* d){
    return d->city;
}

int getAge(data* d){
    return d->age;
}

int changeName(data* d, const char* name){
    d->name = (char *)malloc(1*sizeof(char));
    strcpy(d->name, name);

    return 0;
}

int changeCity(data* d, const char* city){
    d->city = (char *) malloc(1*sizeof(char));
    strcpy(d->city, city);

    return 0;
}

int changeAge(data* d, int age){
    d->age = age;

    return 0;
}

int main(int c){
    system("color 5f");

    data* list;
    list = (data*) malloc(10*sizeof(data));

    set_default(list);



    printf("%s, %d of %s",getName(list), getAge(list), getCity(list));

    return 0;
}

Share/Bookmark

C - Member Using DMA

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    char *name;
    char *city;
    int age;
}data;

int addName(data *d){
    d->name = "lady gaga";

    return 0;
}

int addCity(data *d){
    d->city = "new york";

    return 0;
}

int addAge(data *d){
    d->age = 24;

    return 0;
}

char* getName(data *d){
    return d->name;
}

char* getCity(data* d){
    return d->city;
}
int getAge(data* d){
    return d->age;
}

int changeName(data* d, const char* name){
    d->name = (char *)malloc(1*sizeof(char));
    strcpy(d->name, name);

    return 0;
}

int changeCity(data* d, const char* city){
    d->city = (char *) malloc(1*sizeof(char));
    strcpy(d->city, city);

    return 0;
}

int changeAge(data* d, int age){
    d->age = age;

    return 0;
}

int main(int c){
    system("color 5f");

    data* list;
    list = (data*) malloc(10*sizeof(data));

    addName(list);
    addCity(list);
    addAge(list);

    changeName(list, "Luna Maya");
    changeCity(list, "Denpasar");
    changeAge(list, 27);

    printf("%s, %d of %s",getName(list), getAge(list), getCity(list));

    return 0;
}

Share/Bookmark

C - Complete Pointer And Struct

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    char *name;
    char *city;
    int age;
}data;
int addName(data *d){
    d->name = "lady gaga";

    return 0;
}
int addCity(data *d){
    d->city = "new york";

    return 0;
}
int addAge(data *d){
    d->age = 24;

    return 0;
}
char* getName(data *d){
    return d->name;
}
char* getCity(data* d){
    return d->city;
}
int getAge(data* d){
    return d->age;
}
int main(int c){
    system("color 5f");

    data* list;
    list = (data*) malloc(1*sizeof(data));
    addName(list);
    addCity(list);
    addAge(list);
    printf("%s, %d of %s",getName(list), getAge(list), getCity(list));

    return 0;
}

Share/Bookmark

C - Pointer Behind Struct

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    char *name;
    char *city;
    int age;
}data;

int addName(data *d){
    d->name = "lady gaga";

    return 0;
}

int addCity(data *d){
    d->city = "new york";

    return 0;
}

int addAge(data *d){
    d->age = 24;

    return 0;
}

int main(int c){
    system("color 5f");

    data* list;
    list = (data*) malloc(1*sizeof(data));

    addName(list);
    addCity(list);
    addAge(list);

    printf("%s, %d of %s",list->name, list->age, list->city);

    return 0;
}

Share/Bookmark

C - The Reaon Behind Pointer

1. Pure of array
========================

#include <stdio.h>
#include <stdlib.h>

int setFirst(char n[]){

    n[0] = 'l';
    n[1] = 'a';
    n[2] = 'd';
    n[3] = 'y';

    return 0;
}

Share/Bookmark

Wednesday, April 27, 2011

Python - Web Server

There's some options to build a web server using Python:
1. Using BaseHTTPServer
from BaseHTTPServer import *
def run(server_class=BaseHTTPServer.HTTPServer,
    handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
    server_address = ("", 8000)
    httpd = server_class(server_address, handler_class)
    httpd.server_forever()

run()

2. Using SimplerHTTPServer
import SimpleHTTPServer
import SocketServer

PORT = 8001

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SockerServer.TCPServer(("", PORT), Handler)
print "Serving at port: ', PORT
httpd.serve_forever()

Or you can invoke it using
python.exe -m SimpleHTTPServer 8000
Share/Bookmark

Wednesday, April 20, 2011

Java - Packaging

The firstly build the nice directory, for example:
C:\project
    |- bin
    |- src
        |- com
            |- lucia
                |- Boo.java

Then compile your java file using:
C:\project javac -d bin src\com\lucia\Boo.java

The above command will make a binary class file inside your bin directory plus the package.

C:\project> javac -d bin -sourcepath src src\com\lucia\Main.java
C:\project> java -cp bin com.lucia.Main
See more on: http://www.ibm.com/developerworks/library/j-classpath-windows/
Share/Bookmark

Tuesday, April 19, 2011

Django - Login Logout

# views.py
def login(request):
    login = None
    if request.user.is_authenticated(): # check if user has login
        login = True
    else:
        login = False
    return render_to_response('polls/login.html', {'title': 'Login Logout Page', 'login':login})


def loginprocess(request):
    from django.contrib.auth import authenticate, login, logout
    from django.http import HttpResponseRedirect

    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)

    if user is not None:
        if user.is_active:
            login(request, user)  # login script
            return HttpResponseRedirect('http://localhost:8000/login')
        else:
            return render_to_response('polls/login.html', {'title': 'Disabled Account'})
    else:
        return render_to_response('polls/login.html', {'title': 'Not Registered Account'})
      

def logout(request):
    from django.contrib.auth import logout
    from django.http import HttpResponseRedirect

    logout(request)
    return HttpResponseRedirect('http://localhost:8000')

Share/Bookmark

Monday, April 18, 2011

Django - Redirection

This is a simple example of redirection mechanism in Django.
from django.http import HttpResponseRedirect
def my_view(request):
    return HttpResponseRedirect('http://google.com')
Share/Bookmark

Zend - Paginator

<?php

$request = $this->getRequest();
$page = $request->getParam('page');
if(!isset($page) || $page<1) $page=1;

$registry = Zend_Registry::getInstance();

$db = $registry['db'];
$result = $db->fetchAll("SELECT * FROM data");



// the core paginator
$paginator = Zend_Paginator::factory($result);
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber($page);
$this->view->paginator = $paginator;

if($page==1){
    $this->view->previous = $page;
}else{
    $this->view->previous = $page-1;
}

$this->view->next = $page+1;


?>


Then on your view, use:

<?php include "header.phtml";?>
<?php
    $output = '<ul>';
    foreach($this->paginator as $row){
        $output .= '<li>'.$row['id'].' '.$row['name'].' '.$row['city'].' '.$row['age'].'</li>';
    }
    echo $output.'</ul>';
?>
<a href="<?php echo $this->baseUrl();?>/index/front/page/5">5</a> |
<a href="<?php echo $this->baseUrl();?>/index/front/page/<?php echo $this->next;?>">Next</a> |
<a href="<?php echo $this->baseUrl();?>/index/front/page/<?php echo $this->previous;?>">Previous</a>
<?php include "footer.phtml";?>
Share/Bookmark

Sunday, April 17, 2011

Apache - Removing index.php

For removing index.php on url, type this code to an .htaccess file:
RewriteEngine On
RewriteRule ^[a-z]/* index.php


The process the script in the file of index.php

<?php

    // you can process the url use this one
    $q = $_SERVER['REQUEST_URI'];

    $queries = explode('/',$q);
   
    $page = $queries[1];

    if($page == 'css'){
        include "css/index.php";
    }else if($page == 'js'){
        include "js/index.php";
    }else if($page == 'hello'){
        include ("hello.php");
    }else{
        include "404.php";
    }
?>
Share/Bookmark

Saturday, April 16, 2011

Apache - Building Pretty URL

<?php
    $q = $_SERVER['REQUEST_URI'];
    $queries = explode('/',$q);  // the url: /index.php/hello/somevalue/somevalue
    var_dump($queries);
    $page = $queries[2];
    $value1 = $queries[3];
    $value2 = $queries[4];
    if($page == 'holla'){
        include "holla.php";
    }else if($page == 'hello'){
        include "hello.php";
    }else if($page == '' && $queries[1] = 'index.php'){
        include "front.php";
    }else{
        include "404.php";
    }
?>

And the htaccess file is like this one:
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule .* index.php [L]
Share/Bookmark

Apache - Safe URL

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

The above .htaccess file, will direct whatever the url that no available in the server to catch.php file
Share/Bookmark

Django - Custom Response

HttpResponse is the basic for manipulating response to client.
For displaying an xml file, use
response = HttpResponse(mimetype="text/xml")
response.write('<?xml version="1.0"?>')
response.write('<data>No Data</data>')
return response

For displaying image, use
im = Image.open("nature.png")   # use PIL library
response = HttpResponse(mimetype="image/png")
im.save(response, "PNG")
return response
Share/Bookmark

Zend - SOAP Web Service

Below is a three file:
1. mywebservie.php - defining class that used in this web service
2. webservice.php - WSDL document and Soap server creation
3. hello.php - a client that request a service from the soap server
You can find nice guide here: http://www.phpriot.com/articles/zend-soap/6


Share/Bookmark

Zend - Consuming Web Service

Here's a code on how to consume a web service from a SOAP server. read more one http://www.phpriot.com/articles/zend-soap/6

file: hello.php
<?php
require_once "Zend/Soap/Client.php";
$client = new Zend_Soap_Client("http://localhost/webservice.php?wsdl");
echo $client->getDate();
echo $client->getAgeString('Lady Gaga', 24);
Share/Bookmark

Zend - Creating SOAP Server

After you create and define your custom class and the corrisponding WSDL document, now you can create SOAP server. Read more on http://www.phpriot.com/articles/zend-soap/6

file: webservice.php
<?php
require_once 'mywebservice.php';
if($_SERVER['QUERY_STRING'] == 'wsdl'){
    // WSDL document creation
}else{
   // SOAP Server creation
   require_once "Zend/Soap/Server.php";
    $soapServer = new Zend_Soap_Server("http://localhost/webservice.php?wsdl");
    $soapServer->setClass('MyWebService');
    $soapServer->handle();
}
Share/Bookmark

Zend - Creating WSDL Document

To create a WSDL document using Zend, you need to make a common class in a php file. For example
file: mywebservice.php
<?php

/**
 * Web service methods
 */
class MyWebService
{
    /**
     * Get the server date and time
     *
     * @return string
     */
     public function getDate()
     {     
        return date('c');
    }
   
    /**
     * Get a nicely formatted string of a person's age
     *
     * @param string $name The name of a person
     * @param int $age The age of a person
     * @return string
     */
     public function getAgeString($name, $age)
     {
        return sprintf('%s is %d years old', $name, $age);
     }
}

?>

Then create another php file, webservice.php
<?php

require_once "mywebservice.php";
require_once "Zend/Soap/AutoDiscover.php";

$auto = new Zend_Soap_AutoDiscover();
$auto->setClass('MyWebService');
$auto->handle();
?>

Then now, point out your  browser to http://localhost/webservice.php - you will get an WSDL document. Read more on: http://www.phpriot.com/articles/zend-soap/6
Share/Bookmark

PHP - The First Web Services

This is my first web service I try to do that successfully executed:
index.php
<?php
require_once "nusoap.php";

$server = new soap_server;
$server->register('hello');

function hello($name){
    return 'Hello, '.$name.' From Soap Server';
}

$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>

While the client code is:
<?php
require_once 'nusoap.php';

$client = new SoapClient(
    null,
    array(
        'location' => 'http://localhost/index.php',
        'uri' => 'http://localhost:80',
        'soap_version' => '0.9.5',
    )
);

$result = $client->hello('Barack Obama');
print_r($result);
?>
Share/Bookmark

Friday, April 15, 2011

XML - Creating XSL File

For linking an xml file with its stylesheet file, add a line of code:
<xsl-stylesheet type="text/xsl" href="main.xsl">

Then defining your xsl file by
<?xml version="1.0">
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<data>
    <item>
        ...
    </item>
</data>
Share/Bookmark

Zend - Validation

To validate an input, use Zend_Validate class and an implementation of the class that use it:

require_once "Zend/Validate.php";
require_once "Zend/Validate/StringLength.php";

$validator = new Zend_Validate_StringLength(5);
$input = "Coming Here";

if($validator->isValid($input)){
     // success code
}else{
     // error code
     echo current($validator->getMessages());
}
Share/Bookmark

Zend - Log

To write a log, include two file of Zend:
require_once "Zend/Log.php";
require_once "Zend/Log/Writer/Stream.php";

$logger = new Zend_Log();
$writer = new Zend_Log_Writer_Stream("log.txt");

$logger->addWriter($writer);
$logger->log('Informational formation', Zend_Log::INFO);
$logger->info('Infor message');
Share/Bookmark

Zend - Feed

<?php

require_once "Zend/Controller/Action.php";
require_once "Zend/Feed.php";

class IndexController extends Zend_Controller_Action{

    public function indexAction(){
        $this->_redirect('index/front');
    }
    public function frontAction(){
        $feed = Zend_Feed::import('http://images.apple.com/main/rss/hotnews/hotnews.rss');

        $output = '<h1>Title: '.$feed->title().'</h1>';
        $output .= '<h2>Link: '.$feed->link().'</h2>';
        $output .= '<h3>Description: '.$feed->description().'</h3>';
       
        foreach($feed as $item){
            $output .= '<div>';
            $output .= '<h2><a href="'.$item->link().'">'.$item->title().'</a></h2>';
            $output .= '<div>'.$item->description().'</div>';
            $output .= '</div>';
        }

        echo $output;

       // print xml document
       print $feed->saveXML();
    }

}

Share/Bookmark

Zend - Example For Using Lucene

<?php

require_once "Zend/Controller/Action.php";
require_once "Zend/Search/Lucene.php";


class IndexController extends Zend_Controller_Action{

    public function indexAction(){
        $this->_redirect('index/front');
    }


    public function frontAction(){
        $index = new Zend_Search_Lucene('lola', true);
       
        $doc = new Zend_Search_Lucene_Document();
       
        $contents = array(
            'Google is greate one for our company. so when we are ready to make it, please make some time to be user for you',
            'Apple is another sompany for using with some simple of the example for this one.',
            'Microsoft is another one for the coming of the yeras for this one. It has windows',
        );
        $titles = array(
            'Google is technology company mobile',
            'Apple is mobile leader company',
            'Microsoft is king for desktop',
        );
        $links = array(
            'http://google.com',
            'http://apple.com',
            'http://microsoft.com',
        );
       
        for($i=0; $i<count($links); $i++){
            $doc->addField(Zend_Search_Lucene_Field::Keyword('link', $links[$i]));
            $doc->addField(Zend_Search_Lucene_Field::Text('title', $titles[$i]));
            $doc->addField(Zend_Search_Lucene_Field::Unstored('contents', $contents[$i]));
            $index->addDocument($doc);
        }
       
       
        $index->commit();
        echo $index->count()." Documents indexed";

    }
   
   
    public function renderAction(){
   
        $request = $this->getRequest();
        $query = $request->getParam('query');
       
        $index = new Zend_Search_Lucene('lola');
        $hits = $index->find($query);
       
        $output = '<div id="search">';
       
        $output .= '<p>Total Index: '.$index->count().' documents</p>';
        $output .= '<p>Search For: '.$query.' has resulted on '.count($hits).'</p>';
        foreach($hits as $hit){
            $output .= '<div id="item">';
            $output .= '<h2><a href="'.$hit->link.'">'.$hit->title.'</a> '.$hit->score.'</h2>';
            $output .= '</div>';
        }
        $output .= '</div>';
       
        echo $output;
    }   

}

// see more: http://devzone.zend.com/article/91

Share/Bookmark

Zend - Lucene Search

To create a search application using Zend, you use lucene class:

<?php
require_once "Zend/Search/Lucene.php";

$index = new Zend_Search_Lucene('lola', true);
The above code will create a directory folder for search index. There are five files for it:
1. read.lock.file
2. write.lock.file
3. segments_1
4. segments_2
5. segments_gen

$doc->addField(Zend_Search_Lucene_Field::Keyword('link', '<a href="#">Boo</a>'));
$doc->addField(Zend_Search_Lucene_Field::Text('title', 'Hello World'));
$doc->addField(Zend_Search_Lucene_Field::Unstored('contents', 'This is description'));
$index->addDocument($doc);
$index->commit();
echo $index->count()." Documents indexed";

For displaying the result:

$index = new Zend_Search_Lucene('lola');
$query = 'World';
$hits = $index->find($query);
echo "Index contains: ".$index->count()." documents.<br/>";
        echo "Search for: \"".$query."\" returned \"".count($hits)."\" hits";
foreach($hits as $hit){
     echo "<ul>";
     echo "<li>".$hit->link."</li>";
     echo "<li>".$hit->title."</li>";
     echo "<li>".$hit->score."</li>";
      echo "</ul>";
}
Share/Bookmark

Sunday, April 10, 2011

Zend - Linking CSS File

You can use either one of this below in your view file:
<?php
    $this->headLink()->appendStylesheet($this->baseUrl().'/css/style.css');
    echo $this->headLink();
?>

Or just use:
<link rel="stylesheet" href="<?php echo $this->baseUrl();?>/css/style.css"/>
Share/Bookmark

Zend - .htaccess

RewriteEngine On
RewriteRule .* index.php

Instead of using the above .htaccess file, use this below one:
RewriteEngine On
RewriteCond $1 !^(index\.php|img/*|js/*|css/*)
RewriteRule ^(.*)$ index.php/$1 [L]
Share/Bookmark

Zend - Built In Helpers

Helper is a function that you call from views.

1. Button Helpers
<?php
    $attr = array(
        'style' => 'background: yellow; border: 1px solid #ccc;',
    );
    echo $this->formButton('init', 'Init', $attr);
?>
Share/Bookmark

Zend - Zend Helper

File: application/views/helpers/HelloHelper.php

<?php

require_once 'Zend/View/Helper/Abstract.php';

class Zend_View_Helper_HelloHelper extends Zend_View_Helper_Abstract{
    function helloHelper(){
        return 'Hello Comes From Helper';
    }
}

?>

Then in the views file, call it using:
<?php echo $this->helloHelper();?>
Share/Bookmark

Zend - Authentication

    public function authAction(){
        $request = $this->getRequest();
        $registry = Zend_Registry::getInstance();
        $auth = Zend_Auth::getInstance();
       
        $db = $registry['db'];
       
        $authAdapter = new Zend_Auth_Adapter_DbTable($db);
        $authAdapter->setTableName('users')
                    ->setIdentityColumn('username')
                    ->setCredentialColumn('password');
                   
        // set the input credential values
        $uname = $request->getParam('username');
        $passwd = $request->getParam('password');
        $authAdapter->setIdentity($uname);
        $authAdapter->setCredential(md5($passwd));
       
        // perform the auth query, saving the result
        $result = $auth->authenticate($authAdapter);
       
        if($result->isValid()){
            $data = $authAdapter->getResultRowObject(null, 'passwd');
            $auth->getStorage()->write($data);
            $this->_redirect('/user/userpage');
        }else{
            $this->_redirect('/user/loginform');
        }
    }
   
    public function userpageAction(){
        $auth = Zend_Auth::getInstance();
       
        if(!$auth->hasIdentity()){
            $this->_redirect('/user/loginform');
        }
       
        $request = $this->getRequest();
        $user = $auth->getIdentity();
        $real_name = $user->real_name;
        $username = $user->username;
        $url = $request->getBaseURL().'/user/logout';
       
        $this->view->assign('username', $real_name);
        $this->view->assign('url', $url);
       
    }
   
    public function logoutAction(){
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        $this->_redirect('/user');
    }

Share/Bookmark

Zend - Database Style

$db = new Zend_Db_Adapter_Pdo_Mysql($params)

To update data, do like
$data = array(
    'name' => 'Lady Gaga',
    'city' => 'New York',
);
$db->update('user_table', $data, 'id = 1');

For insert data, do like
$data = array(
    'name' => 'Lady Gaga',
    'city' => 'New York',
    'age' => 24
);
$db->insert('user_table', $data);

For deleting data, use
$db->delete('user', 'id = '.$id);

For querying table, use:
$result = $db->fetchRow('SELECT * FROM user_table WHERE id=1');
echo $result['first_name'];
echo $result['last_name'];

$result = $db->fetchAssoc('SELECT * FROM user_table');
for($i=0; $i<count($result); $i++){
     echo $result[$i]['first_name'];
     echo $result[$i]['last_name'];
}
Share/Bookmark

Zend - Inserting Data To Database

user require_once to include
Zend/Db/Adapter/Pdo/Mysql.php

Then use this code on function
$params = array(
    'host' => 'localhost',
    'username' => 'root',
    'password' => 'pass',
    'dbname' => 'zend',
);
$db = new Zend_Db_Adapter_Pdo_Mysql($params);
$data = array(
    'name' => 'Lady Gaga',
    'city' => 'New York',
    'age' => 45,
);
$db->insert('table', $data);
$result = $db->fetchAssoc('SELECT * FROM table');

Share/Bookmark

Zend - Folder Structures

The folder structure is:
htdocs
    - hello
        - application
            - controllers
            - models
            - views
                - filters
                - helpers
                - scripts
                    - folder for every controller
        - library   
            - Zend
        - tests
        - web_root           
            - css
            - js
            - img
            - index.php
            - .htaccess
   

Share/Bookmark

Saturday, April 9, 2011

SQL - A Little Complex

A little complex queries:
 $q = "SELECT forum_topic.id, forum_topic.title, forum_user.username, forum_topic.date, forum_topic.time, count(forum_reply.tid) as 'count' FROM forum_user, forum_topic, forum_reply WHERE forum_user.id=forum_topic.uid AND forum_topic.id=forum_reply.tid GROUP BY forum_reply.tid";
Share/Bookmark

Thursday, April 7, 2011

C - Function Call

Here's a way on how to call function like the most avaiable in many software, like PHP, Apache or other software that built by C:
#define PO_FUNC(bar) bar()
What that means is that whenever you want to call a function, you do it by
PO_FUNC(your_function_name)

Here's an example:
#include <stdio.h>
#define PO_FUNC(bar) bar()

void hello(){
    printf("Hello For All");
}

int main(int argc, char* argv[]){
    PO_FUNC(hello);    // This is the same case as hello()
    return 0;
}
Share/Bookmark

Wednesday, April 6, 2011

Smarty - Inheritance

To include another template file in a template file, for example you want to include footer and header
index.tpl
<html>
</head>
<title>Hello</title>
</head>
<body>
{include file="header.tpl" param="New York"}
<h1>Main Body</h1>
{include file="footer.tpl"}
</body>
</html>

What's the more powerful than this one is inheritance:
parent.tpl
<html>
<head>
<title>Hello</title>
</head>
<body>
{block name="content"}Default Content{/blcok}
</body>
</html>

child.tpl
{block name="content"}The New Content{/block}
Share/Bookmark

Smarty - Basic Syntax

Your main file is php file: index.php
Then your template file is a file that has .tpl extension
In index file, you write:
<?php
require_once('../libs/Smarty.class.php');

$smarty = new Smarty();
$smarty->assign('title', 'Personal Web Service');

$smarty->display('index.tpl');

?>

Then your tempate file, looks like:
<h1>Title: {$title}</h1>

Share/Bookmark

Smarty - Starting Up

Download Smarty template engine..
In your project directory, create 4 directories
1. cache
2. configs
3. templates - places your tempalete file here (.tpl)
5. templates_c

In your php file that need transfer data to template file, use include the smarty class file
require("../libs/Smarty.class.php");
$smarty = new Smarty();
Share/Bookmark

Tuesday, April 5, 2011

Django - Admin Page

To make your application visible from admin panel, try to make admin.py in your app directory. But before do it, lets update some file:
1. urls.py -> uncomment line 4,5,15
2. settings.py -> uncomment line 94

from data.models import Personal
from django.contrib import admin

admin.site.register(Personal)

Remember that this use:
project = dj
app = data
site = Personal
 
Share/Bookmark

Django - Shell

from django.db import models

# Create your models here.

class Personal(models.Model):
    name = models.CharField(max_length=20)
    city = models.CharField(max_length=20)
    age = models.IntegerField()
    
    def __unicode__(self):
        return self.name

For example, you have models file like the above one, then on python manage.py shell (data is your project)
>>> from data.models import Personal
>>> p = Personal.objects.all()
>>> p = Personal(name='lady gaga', city='new york', age=24)
>>> p.save()     # flush the buffer
>>> p.name = 'Lady Gagah'   #updating
>>> p.save()
Share/Bookmark

CakePHP - Metadata Digging

On view file, you can show the metada on the CakePHP:
<?php
var_dump($this);
var_dump($form);
var_dump($html);
?>
Share/Bookmark

PHP - Caching The Page

<?php

    date_default_timezone_set('Asia/Jakarta');
   
    // get the url as file name
    $file = md5($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
   
    $cachefile = 'cache/'.$file.'.html';
   
    // get this page file name
    $file_page = __FILE__;

    if (file_exists($cachefile) && (filemtime($file_page)) < filemtime($cachefile)) {

        // this must be included because the file cache comes from here.
        include($cachefile);

        echo "<!– Cached ".date('H:i', filemtime($cachefile))." –>n";

        exit;

    }

    ob_start(); // start the output buffer

?>

<h1>...Everything Here Is Cached...</h1>


<?php

    $fp = fopen($cachefile, 'w'); // open the cache file for writing

    fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file

    fclose($fp); // close the file

    ob_end_flush(); // Send the output to the browser

?>

Share/Bookmark

Monday, April 4, 2011

Apache - Customize Errof Page

In your .htaccess file, write:
ErrorDocument 404 /error.html
It needs to add trailing slash to work.
Share/Bookmark

Apache - RewriteEngine

RewriteEngine module is used for rediracting a url to another one. If you want to redirect index.php to hello.php, you write .htaccess file

RewriteEngine On
RewriteRule ^index\.html$ hello.php

Then when user access domain.com, the will get what the contents in hello.php without see the the intuitive url.
Share/Bookmark

Apache - Automatic Include File

To automate an include file, write in your htaccess file:
php_value auto_prepend_file path/to/file.php
php_value auto_append_file path/to/file.php
Share/Bookmark

Python - Console I/O

Input:
1. For input just percharacter character
    initial = sys.stdin.read(1)
2. For evaluating expression:
    sum = input('Enter expression: ')
3. For string input:
    name = raw_input('Enter your name: ')
Share/Bookmark

CakePHP - Creating Elements

Elements is a lightweight html component. It lies on the app\view\elements\hello.ctp
Then on the view, you can access it by
<?php echo $this->element('hello'); ?>
And you can also pass the value from the view to the element by second arguments, like this one:
<?php echo $this->element('hello',array('name'=>'Lady Gaga'));?>
Share/Bookmark

CakePHP - Creating Layout

Layout is a part of presentation side of CakePHP. Just copy the default.ctp in cake/libs/view/layouts/default.ctp to app/views/layout/default.ctp
The customize it:
1. Loading title:
<?php echo $title_for_layout;?>
2. Loading content
<?php echo $content_for_layout;?>
3. Loading css file that lies on webroot/css/some.css
<?php echo $html->css('filname_without_extenstion');?>
4. Loading javascript file that lies on webroot/js/some.js
    a. In controller file, add var $helpers = array('Javascript');
    b. In the layout, add <?php echo $javascript->link('filename_without_ext');?>
Share/Bookmark

Saturday, April 2, 2011

CakePHP - The Structure

When you are ready to build an application after simple setting of configuration, do this:
1. Create a table name like posts
    id int not null auto_increment key,
    title char(50),
    body text,
    created datetime,
    modified datetime

2. The insert some data to it
3. Make controller file in E:\xampp\htdocs\cakephp\app\controllers\posts_controller.php
<?php

class PostsController extends AppController{
    var $name = 'Posts';
    function index(){
        $this->set('posts',$this->Post->find('all'));
    }
    function view($id=null){
        $this->Post->id = $id;
        $this->set('post',$this->Post->read());
        $this->set('hello','This comes from bill');
    }
}

4. Make model file E:\xampp\htdocs\cakephp\app\models\post.php
<?php
class Post extends AppModel{
    var $name = 'Post';
}
5. Make the view file:
    a. index.ctp in E:\xampp\htdocs\cakephp\app\views\posts\index.ctp

<h1>Blog posts</h1>
<table>
<tr>
 <th>Id</th>
 <th>Title</th>
 <th>Created</th> 
</tr>
<!-- Here is where we loop through our $posts array, printing out post info -->
<?php foreach ($posts as $post): ?>
 <tr>
<td><?php echo $post['Post']['id']; ?></td>
 <td>
 <?php echo $html->link($post['Post']['title'],
array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>
 </td>
 <td><?php echo $post['Post']['created']; ?></td>
</tr>
<?php endforeach; ?>
 
 </table>
 

    b. view.ctp E:\xampp\htdocs\cakephp\app\views\posts\view.ctp

<h1><?php echo $post['Post']['title']?></h1>
<p><small>Created: <?php echo $post['Post']['created']?></small></p>
<p><?php echo $post['Post']['body']?></p>

<?php print_r($post);?>
<?php print $hello;?>

Share/Bookmark