GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Monday, May 30, 2011

Function Pointer As Struct Member

Function pointer as struct member - with arguments:

#include <stdio.h>

struct aritmathic{
    int a;
    int b;
    int (*add)(int, int);
    int (*subtract)(int, int);
    int (*multiply)(int, int);
};

int Add(int a, int b){
    return (a+b);
}

int Subtract(int a, int b){
    return (a-b);
}

int Multiply(int a, int b){
    return (a*b);
}

int main(){

    struct aritmathic ar;
    ar.a = 4;
    ar.b = 5;

    ar.add = Add;
    ar.subtract = Subtract;
    ar.multiply = Multiply;

    int a = ar.add(ar.a, ar.b);
    int b = ar.subtract(ar.a, ar.b);
    int c = ar.multiply(ar.a, ar.b);   

    printf("%d\n%d\n%d", a, b, c);

    return 0;
}


Simpler version for above:
#include <stdio.h>

struct aritmathic{
    int a;
    int b;
    int (*add) (struct aritmathic*);
    int (*subtract) (struct aritmathic*);
    int (*multiply) (struct aritmathic*);
};

int Add(struct aritmathic* ar){
    return (ar->a + ar->b);
}

int Subtract(struct aritmathic* ar){
    return (ar->a - ar->b);
}

int Multiply(struct aritmathic* ar){
    return (ar->a * ar->b);
}

int main(){

    struct aritmathic ar;
    ar.a = 4;
    ar.b = 5;

    ar.add = Add;
    ar.subtract = Subtract;
    ar.multiply = Multiply;

    int a = ar.add(&ar);
    int b = ar.subtract(&ar);
    int c = ar.multiply(&ar);   

    printf("%d\n%d\n%d", a, b, c);

    return 0;
}

Share/Bookmark
Below is a simple example of function pointer as a member of struct:

#include <stdio.h>

struct data{
    void(*hello)();
};

void hello(){
    puts("Hello comes from C");
}

int main(){
    // the first way
    struct data d;
    d.hello = hello;
    d.hello();

    // the alternate way
    struct data dd;
    struct data* ptr = &dd;
    ptr->hello = *hello;
    ptr->hello();
  
    return 0;
}

Share/Bookmark

Friday, May 20, 2011

Better Looking Search Box

<div id="search">
    <form>
         <input type="text" id="text"/>
         <input type="submit" id="submit" value="Search"/>
     </form>
</div>

<style>
#search{
     border: 1px solid #ccc;
     max-width: -moz-fit-content;
     padding: 1px;
     -moz-border-radius: 5px;
}
#text{
     border: 0px solid #ccc;
     -moz-border-radius: 5px 0px 0px 5px;
     padding-left: 10px;
}
#submit{
     background: #88f;
     color: #fff;
     font: 14px arial;
     font-weight: bold;
     border: 0px solid #000;
     padding: 1px 5px;
     -moz-border-radius: 0px 5px 5px 0px;
     cursor: pointer;
}
#submit:hover{
     background: #55f;
}
form{
     margin: 0px;
     padding: 0px;
}
</style>

The result:


Share/Bookmark

Tuesday, May 17, 2011

SSL - Generate RSA Key

To simply generate rsa key to stdout in default 512
OpenSSL> genrsa
For 1024
OpenSSL> genrsa 1024
For saving it to file
OpenSSL> genrsa -out mykey.pem 1024

To generate public RSA key, use
OpenSSL> rsa -in mykey.pem -pubout

Read more on here
Share/Bookmark

OpenSSL Introduction

To encrypt a text file use:
OpenSSL> enc -base64 -in myfile.txt
or
OpenSSL> enc -base64 -in myfile.txt -out myfile.txt.enc
or just a test using pipe
D:\git\bin>echo "Hello World" | openssl enc -base64
To decrypt, use
OpenSSL> enc -base64 -d -in myfile.txt.enc
To decrypt from pipe, use
D:\git\bin>echo "encrypted" | openssl enc -base64 -d
Learn more on here
Share/Bookmark

Sunday, May 15, 2011

YUI - Starting

Introduction

Here's a sample for how to start using YUI framework.
First, linking for the API

Code:

<script src="http://yui.yahooapis.com/3.3.0/build/yui/yui-min.js" charset="utf-8"></script>
Second, make your control

Code:

<input type="text" id="ac-input"/>
Third, write the code

Code:

<script>
YUI.use('autocomplete', function(Y){
        Y.one('#ac-input').plug(Y.Plugin.AutoComplete, {
            source: ['apple','amazon','air','america']
    });
});
</script>


Share/Bookmark

Saturday, May 14, 2011

CSS - Advanced

Introduction

Here's some code that show some advanced of CSS that is practical for use.

Rounded Box

It's easy to make a rounded box. Even you don't need use image for it.

Code

<div>You don't need image for making box looks like rounded</div>

<style>
div{
    border: 1px solid #af0;
    padding: 5px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    border-radius: 4px;
}
</style>
The result will be:
You don't need image for making box looks like rounded


Share/Bookmark

Tuesday, May 10, 2011

GAE - Template

Introduction

Template makes your life easier. it separating between code logic of your program to what should display on the browser. Here's I just show up what the crucial template case that not handled by Django documentation.

Displaying List of Articles

It's really some often occurance for us to display item list. It's like blog post that consits of title, date, and content. Or it like personal data that consists of name, email, address and more. Here's for example we has some blog post:

Data Content

TitleContent
GAE TemplateGAE Template is use Django template system. So when you are accustomed for using Django, it's good for you.
GAE RuntimeThere are two available runtime for you. The first is Java and the second is Python. Whatever you choose, it should based on your preference for the language and your current skills.
GAE DatastoreIn GAE, your data is saved in database, but you never handle it directly, because Google Datastore that handles it, and in all your time, you handle the datastore. The operation for data in datastore is like in native sql, but it's more abstract than it that is called GQL - Google Query Language.
For example you want to display the data on the home page, what you need is you main the logic code that retrieves the data using Google datastore query.

Program code: main.py

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template

class Blog(db.Model):     title = db.StringProperty()
    content = db.TextProperty()

class MainPage(webapp.RequestHandler):
    blog = Blog()
    query = db.GqlQuery("SELECT * FROM Blog")
    data = []
    for row in query:
        mapp = {}
        mapp['title'] = row.title
        mapp['content'] = row.content
        data.append(mapp)


Share/Bookmark

GAE - Introduction

Introduction

Google App Engine is the platform for building web application. There's a built-in framework and already hosting servince provided by Google. The application environtment is two: Java and Python. Whenever you choose one, it's up to you.

How To

To starting development, you can download it first from code.google.com. Here we use Python version environment. After finishing for downloading, please install it.

The first is create directory, named "Hello" in whatever you want to place it - for example in "D:\\Hello". The second, is create two files: app.yaml and main.py, and then write this code.


Share/Bookmark

Monday, May 9, 2011

JS -- AJAX

Introduction

AJAX is a mechenisme for communicating with server through background. It enables your client web site to load and sending data from and to server respectively without reloading the page.

Sending Data To Server

Here's a simple example on how to use ajax.

Program Code: Client Side

<input type="text" id="name"/>
<input type="button" value="Send" onclick="sending()"/>

<script>

function sending(){

  var name = document.getElementById('name').value;
  var ajax = new XMLHttpRequest();
  ajax.open("GET", "hello.php?name="+name, false);
  ajax.send();

}

</script>
It's not so complicated. The fisrt, you have the data. The second, you declare an object instance of ajax throught XMLHttpRequest. Then you send your data through ajax. Finish.
And on the server side, you need to write the code to handle it. Here's a code on PHP.

Program Code: hello.php

$name = $_GET['name'];
From the above code, you see that you handling the data as it comes from common request.


Share/Bookmark

JS - JSON

Introduction

JSON is a data format for transferring data as an alternative to XML. JSON is ligter than XML. The syntax is like mapping.

Program Code

var data = {
  "name": "Lady Gaga",
  "city": "New York",
  "age": 24
}
In the above example, we have JSON data format.


Share/Bookmark

Sunday, May 8, 2011

Python - File Reading And Writing

Introduction

File operation is necessary in every programming.In Python, file handling is comparatively easier than the other language.

Reading A File

For reading a file, you can use open built-in method with or without "r" mode as a second arguments.

Program Code

finput = open("lola.txt")
print finput
data = finput.read()
print data

Output

<open file 'none.txt', mode 'r' at 0x00B34440>
Welcome to Python world. Python is a nice language. It's fun to learn. And it's easy to use.
In the above code, we open file accesss using open built in method and supply its argument with filename. Then we use read method to read all the contents of the file, and save it in variable data.


Share/Bookmark

Python - Dictionary

Introduction

Python dictionary data structure is like a map in another language like java or associative array in php. It's use a name value pairs.

How To

You use bracket for declaring and defining it. Here's a code.

Program Code

data = {"name":"lady gaga", "city":"new york", "age":24}
print data

Output

{"name":"lady gaga", "city":"new york", "age":24}


Share/Bookmark

Python - Tuple

Introduction

Tuple is like a list. That is it's a container of data. It also can contain different type of data. But the difference of tupple and list is that the tuple data cannot be modified after it's defined. You cannot modify or delete an element in the tuple. There's some data structure that suitable used tuple than list. For example the day names in a week, the month names in a year, the songs of lady gaga monster ball album. The different things a gain for tuple than list is that tuple definition is using ( and ). Other is same as list.

Program Code

days = ("sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday")
print days
print "The length of the days: ", len(days)


Share/Bookmark

Python - List

Introduction

List is a data structure in Python. It's like an array in other programming languages. But list in Python is more powerful, because it can contain different data type.

Program Code

name = ["lady gaga", "luna maya", "aura kasih"]
print name

Output

["lady gaga", "luna maya", "aura kasih"]


Share/Bookmark

Wednesday, May 4, 2011

C - Define

#define MODULE_AUTHOR(auth) printf("Author: %s\n",auth)
#define MODULE_DESCRIPTION(desc) printf("Description: %s\n", desc)

MODULE_AUTHOR("Irfanudin Ridho");
MODULE_DESCRIPTION("File System");

Share/Bookmark

Tuesday, May 3, 2011

C - String Memory Handling

1. memcpy
char name[] = "lady gaga and barack obama";
char data[100];
memcpy(data, name, strlen(name)+1);
puts(data);

2. memset
char name[] = "lady gaga";
memset(name, '*', 5);
puts(name);

3. memmove
char name[] = "lady gaga and luna maya";
memmove(name+0, name+5, 4); // placed, starting, num
puts(name);
Share/Bookmark

C - Iterate Pointer Of Char

To iterate a pointer of char, it's just need like doing with custom looping
char *data = "lady gaga";
for(; *data!='\0'; data++){
    putchar(*data);
}

Or using this one:
while(*data != '\0'){
    putchar(*data);
    data++;
}
Share/Bookmark

C - Malloc And Calloc

When we use malloc? We use it when we have a pointer, and we want to initialize it.
char name[] = "lady gaga";
char *ptr;
ptr = (char*) malloc(sizeof(name) * sizeof(char))

And then it's okey to initialize it through assignment or strcpy
ptr = name;
or 
strcpy(ptr, name);

Calloc is same as malloc:
ptr = (char*) calloc(sizeof(name), sizeof(char))

When you need copy an array of char to an array of char, the one way is use strcpy function
char name[] = "Indonesia";
char data[100];
strcpy(data, name);

Share/Bookmark

Python - Class and Static Methods

class Advanced(object):
    def __init__(self, name):
        self.name = name
    def Description():
        return 'This is an advanced class.'
    def ClassDescription(cls):
        return 'This is advanced class: %s' % repr(cls)
    Description = staticmethod(Description)
    ClassDescription = classmethod(ClassDescription)

obj1 = Advanced('Nectarine')
print obj1.Description()
print obj1.ClassDescription()
print '=' * 30
print Advanced.Description()
print  Advanced.ClassDescription()

This is an advanced class.
This is advanced class: <class __main__.Advanced at 0x401c926c>
==============================
This is an advanced class.
This is advanced class: <class __main__.Advanced at 0x401c926c>

Share/Bookmark

Python - Static Data

>> class One:
...    age = 45
...    def inc(self):
...        One.age = One.age + 1
...    def get(self):
...        return One.age
...
>> a = One()
>> b = One()
>> a.inc()
>> b.get()
>> a.inc()
>> b.get()
Share/Bookmark

Python - Pipe

>> import os
>> cmd = "dir"
>> fp = popen(cmd)
>> print fp.read()
>> fp.close()
Share/Bookmark

Python - anydbm Module

>> import anydbm
>> db = anydbm.open("data.db","c")
>> db["lady"] = "Gaga"
>> db["luna"] = "Maya"
>> print db["lady"]
Share/Bookmark

Mics - ub IP List

('dudde.ub.ac.id', '175.45.184.100')
('DI-PPTI', '175.45.184.101')
('mail.ub.ac.id', '175.45.184.111')
('simpeg.ub.ac.id', '175.45.184.116')
('hostingdosen.ub.ac.id', '175.45.184.118')
('external-gw.ub.ac.id', '175.45.184.129')
('internal-gw.ub.ac.id', '175.45.184.130')
('dmz-gw.ub.ac.id', '175.45.184.131')
('collo-gw.ub.ac.id', '175.45.184.132')
('inherent-gw.ub.ac.id', '175.45.184.138')
('proxy.ub.ac.id', '175.45.184.162')
('radius.ub.ac.id', '175.45.184.163')
('ns1.ub.ac.id', '175.45.184.164')
('ns2.ub.ac.id', '175.45.184.165')
('central-sw.ub.ac.id', '175.45.184.167')
('proxy2.ub.ac.id', '175.45.184.168')
('ldap.ub.ac.id', '175.45.184.170')
('lpse.ub.ac.id', '175.45.184.51')
('lpse-lat.ub.ac.id', '175.45.184.52')
('smtp-lpse.ub.ac.id', '175.45.184.55')
('simak-db.ub.ac.id', '175.45.184.57')
('siam-sv1.ub.ac.id', '175.45.184.58')
('esxi4.ub.ac.id', '175.45.184.59')
('blog.ub.ac.id', '175.45.184.60')
('devel-gw.ub.ac.id', '175.45.184.66')
('bais.ub.ac.id', '175.45.184.67')
('netmon.ub.ac.id', '175.45.184.68')
('www.ub.ac.id', '175.45.184.70')
('mail.ub.ac.id', '175.45.184.71')
('students-mail.ub.ac.id', '175.45.184.72')
('ftp.ub.ac.id', '175.45.184.73')
('ws.ub.ac.id', '175.45.184.75')
('siakad.ub.ac.id', '175.45.184.76')
('bridgedb.ub.ac.id', '175.45.184.77')
('siakad-db.ub.ac.id', '175.45.184.78')
('keudb.ub.ac.id', '175.45.184.79')
('sikeu.ub.ac.id', '175.45.184.80')
('smtp-gw.ub.ac.id', '175.45.184.81')
('lists.ub.ac.id', '175.45.184.82')
('inherent.ub.ac.id', '175.45.184.83')
('lecture.ub.ac.id', '175.45.184.85')
('siam.ub.ac.id', '175.45.184.86')
('hosting2.ub.ac.id', '175.45.184.87')
('hvm1.ub.ac.id', '175.45.184.89')
('selma.ub.ac.id', '175.45.184.90')
('hosting.ub.ac.id', '175.45.184.92')

Share/Bookmark

C++ - Building Manipulator

ostream &sep(ostream &stream){
    stream << '\t';
    return stream;
}
Share/Bookmark

Monday, May 2, 2011

C++ - Manipulaltion Output

    cout << "Table" << endl;
    cout << setw(15) << setiosflags(ios::left) << "Name";
    cout << setw(15) << setiosflags(ios::left) << "City";
    cout << setw(10) << setiosflags(ios::left) << "Age" << endl;

    string names[] = {"lady gaga","luna maya","aura kasih","barack obama"};
    string cities[] = {"new york","denpasar","jakarta","white house"};
    int ages[] = {24, 27, 25, 50};
    cout << "===================================" << endl;
    for(int i=0;i<4;i++){
        cout << setw(15) << setiosflags(ios::left) << names[i];
        cout << setw(15) << setiosflags(ios::left) << cities[i];
        cout << setw(10) << setiosflags(ios::left) << ages[i] << endl;
    }

Share/Bookmark

Python - Build Web Client

This is a small code for emulating on how to a web client connect to server:

file: client.py
import socket

HOST = 'localhost'
PORT = 6003
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))

# request line
http_data = 'GET /index.php HTTP/1.1\n'

# header line - all are optional but Host
http_data = http_data + 'Host: localhost:80\n'  # required
http_data = http_data + 'From: irfan.ub@gmail.com\n'
http_data = http_data + 'User-Agent: Lucia Browser\n'
http_data = http_data + 'Keep-Alive: 10\n'
http_data = http_data + 'Accept: text/html\n'
http_data = http_data + 'Connection: close\n'

# separation line - required
http_data = http_data + '\n'    # required

client.send(http_data)

data = client.recv(1024*5)
client.close()
print 'Received\n=================\n', data

The response header is like this:
Received
=================
HTTP/1.1 200 OK
Date: Sun, 01 May 2011 22:19:28 GMT
Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_
color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By: PHP/5.3.1
Set-Cookie: PHPSESSID=ajunliavga128hlvcou4chigv6; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 114
Connection: close
Content-Type: text/html

<form action="test.php" method="post">
<input type="text" name="text"/> Holla</form>
<a href="test.php">Test</a>
Share/Bookmark

Python - Bulding Web Server

Here's a short code on how to build workable web server:

name: server.py
import socket

HOST = ''
PORT = 6003

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(2)
conn, addr = server.accept()

print 'Connected by', addr

# initial lines
data = 'HTTP/1.0 404 Not Found\n'

# header lines - all are optional
data = data + 'Date: Fri, 31 Dec 2011 10:12:13 GMT\n'
data = data + 'Content-Type: text/html\n'
data = data + 'Content-Length: 22\n'
data = data + 'Server: Lucia Web Server\n'

# separating lines. needed
data = data + '\n'

# body
data = data + '<html><head><title>Hello World</title></head><body>'
data = data + '<h1>hello World</h1></body></html>'

# receiving the request headers from browser
datas = conn.recv(1024)
print datas


# send the response header plus the body
conn.send(data)
conn.close()



These the request header of the browser:

GET /index.html HTTP/1.1
Host: localhost:6003
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.17) Gecko/2
0110420 SVD Firefox/3.6.17
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive


Accessed from telnet
>>telnet
telnet>> open localhost 6003 HTTP/1.0 /index.hmtl

Share/Bookmark

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