GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Friday, December 31, 2010

Reading File In Python

To read a text file, use:
fp = open("file.txt","r");
print fp.read()

For writing to a file, use:
fp = open("data.txt","w");
write("Hello World");
fp.close();
       
Share/Bookmark

Monday, December 27, 2010

C++ Template Function

Templeate function used for flexibility of the type. So you can do programming like in scripting language. See this code:

templace
myType getMin( myType a, myType b){   
   if(a
        return a;
   }else{
        return b;
   }
}

The you call it by:
int x = 2;
int y = 3;
int c = getMin(x,y);
cout << c << endl;
output>> 2

You can use this function for long data type:
long x = 456789;
long y = 456788;
int c = getMin(x,y);
cout << c << endl;
output>> 456788

More example:
template
Lol addTwo(Lol x){
    Lol r = x + 2;
    return r;
}

then call it by
cout << addTwo(2) << endl;
output>> 5
       
For using two kind of different data type, use
template
A addTwo(A a, B b){
     A r = a+b;
    return r;
}

then call it by:
int x = 4;
long y = 45;
cout << addTwo(x,y) << endl;
output>> 49
          
Share/Bookmark

Iterating Method In Java

For a given array, to iterate over the whole elements in the array, use:

String[] names = new String[]{"lady gaga","barack obama","larry page"};
for(String s: names){
    System.out.println(s);
}

output:
lady gaga
barack obama
larry page
     
Share/Bookmark

Saturday, December 25, 2010

Batch Basic

Batch file is a file that consift of DOS command. What you can do in command prompt, will also can be done in batch file. Type this code in hello.bat, and then execute it with
C:\hello.bat lady gaga

@ECHO OFF
ECHO hello, %1


To make a variable, type:
SET name=Lady Gaga
echo %name%
PAUSE


IF Statements:
@ECHO OFF
SET a=luna
SET b=luna

IF %a%==%b% GOTO luna

ECHO Sorry, Lady!

:luna
ECHO You may win, Luna!
         
Share/Bookmark

Thursday, December 23, 2010

Procedure In Pascal

Here's a code on how write a procedure in Pascal:

Without Parameters

Program UsingProc;

uses wincrt;

procedure hello;
var
    name : string;
begin
    name := 'lady gaga';
    writeln(name);
end;

begin
    hello;
end.

With Parameters:

Program UsingProcParam;

uses wincrt;

procedure hello(name : integer);
begin
    writeln(name);
end;

begin
    hello('lady gaga');
end.
          
Share/Bookmark

Looping In Pascal

Here's a code on how to loop over a number of times;

For Loop:

Program forLoop;

uses wincrt;

var
    i : integer;
    c : char;

begin
    
    for i := 0 to 100 do
    begin
        writeln(i,'. Holla World');
    end;

    writeln('==========================');
    for i := 100 downto 10 do
    begin
        writeln(i,'. Holla World Again');
    end;

    writeln('===========================');

    for c := 'a' to 'z' do
    begin
        writeln(c,'. characters');
    end;

end.


While Loop:

Program whileLoop; 

uses wincrt;

var
    i : integer;

begin

    i := 0;
    while i<100 do
    begin
        writeln(i,'. Less than 100');
        i := i+1;
    end;

end.






Repeat Until

Program untilLoop;

uses wincrt;

var 
    i : integer;

begin   
    i := 1;
    Repeat
        writeln(i,'. Holla World');
        writeln('This holla comes from turbo pascal');
        i := i + 1;
    until i = 100;

end.
         

Share/Bookmark

If Else In Pascal

Here's a code on how to write a decision programs.

Program Sleeping;

uses wincrt;

var
    sleep : boolean;

begin

    sleep := true;

    if (not sleep) then
    begin
        writeln('Lady gaga still sleep');
        writeln('So please keep silent');
    end
    else
    begin
        writeln('You can do what you want');
        writeln('And this is a free area');
    end;

end.
Share/Bookmark

Variable In Pascal

Program Lady;

uses wincrt;

var
    name   : string;
    female : boolean;
    age    : integer;
    weight : real;

begin

    name := 'Lady Gaga';
    female := true;
    age := 23;
    weight := 49.89

    writeln('Personal Data');
    writeln('Name: ',name);
    writeln('Female: ',female);
    writeln('Age: ',age);
    writeln('Weight: ',weight);

end.

To create an array variable, use:
var
    i : Array[0..9] of Integer;
    names : Array[0..4] of string;
    names : Array['A'..'F'] of string;
          

Share/Bookmark

Hello Pascal

This code is ran under Turbo Pascal platform:
The complete structure of the program is:
program   ...;
uses      ...;
label     ...;
const     ...;
type      ...;
procedure ...;
function  ...;
begin
    statement;
end.

Example:

program Hello;

uses wincrt;

begin

    writeln('Hello, Pascal');

end.
Share/Bookmark

MySQL Revoke User

With REVOKE statement, you hope that some grants will be removed.

mysql> REVOKE insert ON *.* FROM 'luna'@'localhost';
Query OK, 0 rows affected (0.02 sec)

mysql> REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'luna'@'localhost';
Query OK, 0 rows affected (0.02 sec)
Share/Bookmark

MySQL Giving Privileges To User

Give all privileges to 'luna'@'localhost':
mysql> GRANT ALL PRIVILEGES ON *.* TO 'luna'@'localhost' 
       WITH GRANTS OPTION;
Query OK, 0 rows affected (0.00 sec)

To show what the grant of a specified user, please type:
mysql> SHOW GRANTS FOR 'luna'@'localhost';
+------------------------------------------+
| Grants for luna@localhost                |
+------------------------------------------+
| GRANT USAGE ON *.* TO 'luna'@'localhost' |
+------------------------------------------+
1 row in set (0.00 sec)

To give some grants, please type:
mysql> GRANTS SELECT, UPDATE, INSERT, DELETE, CREATE, DROP ON
       bankAccount.* TO 'luna'@'localhost';
Query OK, 0 rows affected (0.01 sec)

To give some grants for a table, type:
mysql> GRANTS SELECT, UPDATE, INSERT, DELETE, CREATE, DROP ON
       customer.data TO 'luna'@'localhost';
Query OK, 0 rows affected (0.01 sec)
               


Share/Bookmark

MySQL - Basic User Administration

The most basic type is:
mysql> CREATE USER 'luna'@'localhost';
Query OK, 0 rows affected (0.03 sec)

When password is needed, type:
mysql> CREATE USER 'luna'@'localhost' IDENTIFIED BY 'password';
Query OK, 0 rows affected (0.00 sec)

To remove a user, type:
mysql> DROP USER 'luna'@'localhost';
Query OK, 0 rows affected (0.00 sec)
Share/Bookmark

Looping In Jython

>>> for i in range(3):
...     print i
0
1
2
Share/Bookmark

Method In Jython

Here's a code that much like Python:
>>> def getLol():
...     print "Hello, Lol"
...
>>> getLol()
Hello, Lol
Share/Bookmark

Class In Jython

Here's a code on how to define a class in Jython:

>>> class Hello:
...    def __init__(self,name="no name"):
...        self.name = name
...    def greeting(self):
...        print "Hello, ",self.name
...
>>> luna = Hello("Luna Maya")
>>> luna.greeting()
Hello, Luna Maya
Share/Bookmark

Create Cookie In PHP

Here's a code on how to create cookie:
<?php
setcookie("name","lady gaga");
?>

And here to retrieve it:
<?php
echo $_COOKIE("name");
>?

To get all variable in cookies:
<?php
print_r($_COOKIE);
>?
                   
Share/Bookmark

Wednesday, December 22, 2010

Reading Text Files In Jython

>>> file = open("data.txt","r");
>>> for line in file.readlines():
...    print line
...
Holla the world
This come from text file
>>> file.close()
    
Share/Bookmark

Swing Application From Jython

>>> from javax.swing import *
>>> def hello():
...     frame = JFrame("Holla, Jython")
...     frame.setSize(400,300)
...     frame.setLocation(200,100)
...     frame.show()
... 
>>> hello()
             

Share/Bookmark

First Script In Jython

To get Jython, please download it from Jython web site. After you download, you need to install it by command:
C:\java -jar jython_installer.2.2.1.jar
After the installation completes, please move to jython\bin directory and run jython.bat
C:\jython\bin\jython.bat

>>> print "Hello, Jython"
Hello, Jython

>>> from java.util import Vector
>>> v = Vector()
>>> dir(v)
>>> v.add('larry page')
>>> v.add('barack obama')
>>> v.add('bill gates')
>>> for value in v:
>>>     print v
larry page
barack obama
Publish Post

bill gates
         
Share/Bookmark

Swing JRadioButton

To use this component, it's needed to use ButtonGroup:

import java.awt.*:
import javax.swing.*;

public Main{

   public static void main(String[] args){

        JFrame frame = new JFrame("Radio Button");

        JRadioButton rbApel = new JRadioButton("Apel");
        JRadioButton rbNanas = new JRadioButton("Nanas");
        JRadioButton rbJambu = new JRadioButton("Jambu"):

        ButtonGroup group = new ButtonGroup();
        group.add(rbApel);
        group.add(rbNanas);
        group.add(rbJambu);

        frame.add(rbApel);
        frame.add(rbNanas);
        frame.add(rbJambu);

        frame.setSize(400, 300);
        frame.setLocation(200, 100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
   }
}
Share/Bookmark

Swing JCheckBox

import javax.swing.*;
import java.awt.*;


public Main{

    public static void main(String[] args){

        JFrame frame = new JFrame("CheckBox Application");

        JCheckBox cbJambu = new JCheckBox("Jambu");
        JCheckBox cbNanas = new JCheckBox("Nanas");
        JCheckBox cbApel = new JCheckBox("Apel");

        frame.add(cbJambu);
        frame.add(cbNanas);
        frame.add(cbApel);

        frame.setSize(400, 300);
        frame.setLocation(200, 100);
        frame.setDefaultCloseOPeration(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Share/Bookmark

Swing JEditorPane

This component can be made to load a text string or other. For file you can use: file:\\d:\\data.txt

import javax.swing.*:

public class Main{

    public static void main(String[] args){

        JFrame frame = new JFrame("JEditorPane Application");

        JEditorPane editPane = new JEditorPane();

        try{
            editPane.setPage("http://google.com");
        }catch(Exception ex){
            ex.printStackTrace();
        }

        frame.add(editPane);
        frame.setSize(400, 300);
        frame.setLocation(200, 100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
   }
}
Share/Bookmark

Swing JTabbedPane

Here's a code on how to show about JTabbedPane: Layout for tabbed pane is BorderLayout by default.

import javax.swing.*;

public class Main{

    public static void main(String[] args){

        JFrame frame = new JFrame("Tab Pane Application");

        JTabbedPane tabPane = new JTabbedPane();

        tabPane.addTab("General", new JButton("Exit"));
        tabPane.addTab("Configuration");
        tabPane.addTab("Advance");

        frame.add(tabPane);
        frame.setSize(400, 300);
        frame.setLocation(200, 100);
        frame.setDefaultCloseOporation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }
}
Share/Bookmark

attr jQuery

Here's a bit of code on how to use attr:
var id = $('#satu').attr('id');
$('#dua').attr('id','lola');
$('#tiga').attr({'id':'empat','class':four','title':
                 'A Sample Of Text'});    // Object literal
Share/Bookmark

css jQuery

To get the value, just type:
var color = $('#satu').css('background-color'); // get the value
$('#dua').css('background-color','red');        // set the value
$('#tiga').css({'color':'blue', 'font-size':'24px', 
                'background-color':'lime'});
Share/Bookmark

jQuery Ajax - Save And Receive Data

Here's a code on how to send some data to the server and then notify the user that the saved data has completes:

$.ajax({
    type: "POST",
    url: "some.php",
    data: "name=lady&city=ny",
    success: function(msg){
        alert('Data saved: '+msg);
         }
});
Share/Bookmark

Ajax In JQuery

Here's a code on how to get to ajax through jQuery:

$.ajax({
    data: 'test.html',
    success: function(data){
        $('#satu').text(data);
        alert('Load data successfully');
    }
});



Share/Bookmark

Invoking Java From Matlab

You can build a Java application using Matlab:

>> java
>> f = javax.swing.JFrame('A Java Application');
>> f.setSize(400,300);
>> f.setLocation(200, 100);
>> f.setVisible(true);

Then you can add some attribute
>> layout = java.awt.FlowLayout();
>> f.getContentPane().setLayout(layout);

>> bExit = javax.swing.JButton("Exit");
>> f.getContentPane().add(bExit);

          
Share/Bookmark

Defining Function In Matlab

Firstly, type this code and then save it - addTwo.m
function output = addTwo(input)
% This function will add the input with 2
output = 2 + input;

In Matlab interactive mode, type:
>> addTwo(3)
ans 5

The function also can have more than one input and output arguments. Save this code to addThen.m:
function [add,dot] = addThen(input)
% This function will add and also will multiply 
% the input arguments.
add = input + input;
dot = input * input;

Then in Matlab IDE, type
>> [a,b] = addThen(4)
a = 8
b = 16
  
    
Share/Bookmark

If Else In Matlab

Type to test:

>> sleep = true;
>> if sleep
disp('Do sleep');
end
Do sleep

>> a = 2;
>> if a>3
disp('Nothing');
else
disp('Do sleep')
end
Do sleep


Share/Bookmark

Looping In Matlab

For do looping in Matlab, type:
>> for i=0:20    % do looping for 0 till 20
disp(i)
end

>> for i=0:2:20   % do looping for 0 till 20 step 2
disp(i)
end

     
For while looping, do:
>> i = 0;
>> while (i<10)
disp(i)
i = i + 1;
end 
       
Share/Bookmark

Basic Graphics In Matlab

To create a graphics, type:

>> figure
>> x = 0:0.1:2*pi;
>> y = sin(x);
>> plot(x, y);

Miscelaneous commands:
>> close       % Close the active graphics window
>> close all   % Close the graphics window
>> clf         % Clear the window from the graph
>> hold on     % Keep the line in the previous display
>> hold off    % Lose the line in the previous display
>> grid        % Toggle for grid
>> cla         % Clear axis
>> box         % Toggle box
>> rotate3d    % Make the graph so can moving like a 3D objects
            
Share/Bookmark

Data Analysis Using Matlab

Creating a matrix by type:
>> data = [2 3;
           4 5;
           8 3];

>> max(data)   
8 5

>> min(data)
2 3

>> mean(data)
4.6667 3.6667

>> median(data)
4 3

>> sort(data)
2 3
4 3
8 5

>> sum(data)
14 11

>> data<5
1 1
1 0
0 1
        
Share/Bookmark

Matrics In Matlab

To create a matric, type:
>> data = [1 2;
           3 4] 

>> data(1,2)    % Get the cross of the 1st row and the 2nd column
2               % var(row, col)

>> data(end,end)   % Get the end of row and column
4

>> data(1:2,1)  % Get elements cross at rows 1 till 2 and col 1
1
3

>> data(1:2,1:2)   % Get rows 1 till 2 and col 1 till 2
1 2                % var(r1:r2, c1:c2)
3 4                % r1:r2 = row1 till row2

>> data(:,1)    % Get all rows at col 1
1
3

>> data(1,:)    % Get all rows at row 1
1 2

>>  data(:)    % Get all elements in consecutive order

Detele rows or columns:
>> data(1,:)    % Delete all elements at the first row
>> data(:,1)    % Delete all elements at the first column

Generating built in matric style:
>> zeros(r,c)    % Creating zero matrix by r and c dimension
>> magic(d)      % Creating random matrix by d and d dimension
>> ones(r,c)     % Creating 1 matrix by r and c dimension
>> rand(r,c)     % Creating random matrix by r and c dimension
>> randn(r,c)    % Creating random matrix (negative included) 
                 % by r and c dimension
>> eye(d)        % Creating a diagonal matrix
          
Share/Bookmark

Vector In Matlab

In Matlab, data structure vector and matrix:
>> id = [4 5 6 2 4]
4 5 6 2 4
>> id = 1:5    % start:end
1 2 3 4 5
>> id = 1:2:10    % start:step:end
1 3 5 7 9

How to access elements in matrix:
>> id = [4 5 6 7 8]
4 5 6 7 8
>> id(1)    % Get the 1st element of the id
4
>> id([1 2 3])    % Get the 1st, 2nd, 3rd elements of id
4 5 6
>> id(1:3)    % Get the 1st till the 3rd elements
4 5 6
>> id(end)    % Get the last element
8
          
Share/Bookmark

Regex In Javascript

pattern in search. g modifiers treat to all elements matched. i modifiers treat incase-sensitive

anElement.innerHTML = "Indonesia".search(/do/i);    // return 4
output> 4

elem.innerHTML = "indonesia".split(/[aiueo]/);
output> ,nd,n,s,,    // 6 array elements

elem.innerHTML = /wo/.test("Hello world");    
output> true;


String method for Regex:
1. search(pattern) : index
2. split(pattern)  : array >< match
3. replace(pattern,textReplacer): string
4. match(pattern)  : array >< split

var hello = "Hello world";
elem.innerHTML = hello.search(/world/ig); 
output> 6
elem.innerHTML = hello.split(/[aiueo]/ig);
output> h,ll, w,rld
elem.innerHTML = hello.replace(/world/,"lady gaga");
output> hello lady gaga  
elem.innerHTML = hello.match(/[aiueo]/);
output> e,o,o   

                 
Share/Bookmark

String Operation In Javascript

Declare a string variable:
var desc = "Helping others who want to help themself";

To get the length of the string, use:
elem.innerHTML = desc.length;
output> 40

elem.innerHTML = desc.toUpperCase();
output> HELPING OTHERS WHO WANT TO HELP THEMSELF

elem.innerHTML = desc.toLowerCase();
output> helping others who want to help themself

elem.innerHTML = desc.charAt(0);    // char at first index.
output> H

elem.innerHTML = desc.charAt(desc.length-1)); // the last char
output> f

var zero = "indonesia";
var one = " sunday";
var two = " friday";
elem.innerHTML = zero.concat(one, two);    // new string
output> indonesia sunday friday

var hello = "Hello World";
elem.innerHTML = hello.indexOf("Wor");
output> 6
elem.innerHTML = hello.indexOf("WORLD");    // nothing
output> -1
elem.innerHTML = hello.indexOf("o");
output> 4
elem.innerHTML = hello.lastIndexOf("o");
output> 7

var hello = "Hello World";
elem.innerHTML = hello.slice(1);
output> ello World
elem.innerHTML = hello.slice(hello.indexOf("W"));
output> World

var abc = "ABCDE";
elem.innerHTML = hello.substr(2,2);
output> CD

Share/Bookmark

Perl Subroutines

To create a subroutine in Perl, type:
sub hello
{
    print "Hello, World!\n";
}

To call it, type:
&hello;
or
$hello($_);
or
$hello(1+2,$_);
            
Share/Bookmark

Expressions In JavaFX

Block expression is surrounded by curly bracket:
var total = {
    var value = [1..10];
    var sum = 0;
    for( v in value){
        sum = sum + v;
    }
    sum;
}

If Else block:
var a = 4;
if(a>5){
println("4 is greater than 5");
}else{
println("4 is less than 5");
}

Range expression:
var seq = [1..100];
var seq2 = [1..100 step 2];
var seqDesc = [100..1 step -1];

For expression:
var data = [1..100 step 2];
for(d in data){
    println(d);
}

While expression:
var i = 0;
while(i<10){
    println(i);
    i++;
}

         
Share/Bookmark

JavaFX Sequence

To create a sequence, type:
var names = ["lady gaga","steve jobs","bill gates"];
var ages = [24, 55, 58];
var value = [1..100];
var valued = value[n | n>50];    // greater than 50

To access an element from this sequence, use [ ] operator:
println(names[0]);    // print out lady gaga
println(value[70]);

To know how much size of the sequence, use:
println(sizeof names);

Use insert command to insert an element into sequence:
insert "barack obama" into names;
insert "larry page" after names[0];
insert "sergey brin" before names[0];
           
Use delete command to delete an element from sequence:
delete names[0];                 // delete lady gaga
delete "barack obama" from names;

Reversing sequence elements order:
value = reverse value;
     
Share/Bookmark

JavaFX Object Literal

To create an object literal, the procedures are:

1. create a class file named Data.fx

    public class Data{
        public var name: String;
        public var city: String;
        public var age: Integer;
        public function setName(name){
            this.name = name;
        }
        public function getName(){
            return this.name;
        }
    }

2. Create a var to Object literal in main program

    var lady = Data{
        name: "Lady Gaga";
        city: "New York";
        age: 24;
    }

3. Now you are ready to use it:

    println("Name: {lady.name}");
    println("City: {lady.city}");
    println("Age: {lady.age}");

    lady.setName("Stefani Joanne Angelina Germanotta");
    println(lady.getName());

           

Share/Bookmark

Function In JavaFX

Function concept in JavaFX is so simple like in Javascript:

function hello(name:String){
    println("Hello, {name}!");
}

To call it, use:
hello("Lady Gaga");

Other samples:
function add(x:Integer,y:Integer){
    println("Add: {x} + {y} = {x+y}");
}

function add(x:Integer,y:Integer){
    return x+y;
}
         
Share/Bookmark