Wednesday, August 31, 2022

@decorators in Python

People have confusion about how to use python decorators in the proper way and how it works. The main reason for it is there are several ways to use decorators. In this article, we will discuss the basics of decoration and demonstrate all types of uses. 

First, we will learn a few terminologies.

First-class objects in a programming language are entities that behave just like normal objects. They can be referenced by variables, stored in data structures like list or dict, passed as arguments to another function, returned as a value from another function.
In mathematics and computer science, a higher-order function (HOF) is a function that does at least one of the following:
  • takes one or more functions as arguments (i.e. a procedural parameter, which is a parameter of a procedure that is itself a procedure),
  • returns a function as its result.
All other functions are first-order functions. 

Functions in Python are first class citizens. This means that they support operations such as being passed as an argument, returned from a function, modified, and assigned to a variable. This is a fundamental concept to understand before we delve into creating Python decorators. Let's checkout the code's from datacamp.com.

Assigning Functions to Variables
def plus_one(number):
    return number + 1

add_one = plus_one
add_one(5)
"""
output:

6
"""
Defining Functions Inside other Functions

def plus_one(number):
    def add_one(number):
        return number + 1


    result = add_one(number)
    return result
plus_one(4)
"""
output:

5
"""

Passing Functions as Arguments to other Functions


def plus_one(number):
    return number + 1

def function_call(function):
    number_to_add = 5
    return function(number_to_add)

function_call(plus_one)
"""
output:

6
"""
Functions Returning other Functions

def hello_function():
    def say_hi():
        return "Hi"
    return say_hi
hello = hello_function()
hello()
"""
output:

Hi
"""
Creating Decorators

def my_decorator(func):
    def wrapper():
        print("Before the func call.")
        func()
        print("After the func call.")

    return wrapper


def say_hello():
    print("Hello!")


say_hello = my_decorator(say_hello)
say_hello()
"""
output:

Before the func call.
Hello!
After the func call.
"""
Now same thing will be done by using @ symbol

def my_decorator(func):
    def wrapper():
        print("Before the func call.")
        func()
        print("After the func call.")

    return wrapper


@my_decorator
def say_hello():
    print("Hello!")


say_hello()
"""
output:

Before the func call.
Hello!
After the func call.
"""
So, @my_decorator is just an easier way of saying say_whee = my_decorator(say_whee). It’s how you apply a decorator to a function.


Now I will demonstrate 7 types of decorator implementation examples. These are
  1. Class implementation of function decorator without argument
  2. Function implementation of function decorator without argument
  3. Class implementation of function decorator with argument
  4. Function implementation of function decorator with argument
  5. Class implementation of class decorator without argument
  6. Function implementation of class decorator without argument
  7. Decorator chaining 
All these example codes are available at github.com

Class implementation of function decorator without argument

class MyClassDecorator(object):

    def __init__(self, f):
        print('__init__() called | function:' + str(f.__name__))
        self.f = f

    def __call__(self, *args, **kwargs):
        print('__call__() called | function:' + str(self.f.__name__) + ' | args: ' + str(args) + ' | kwargs:' + str(
            kwargs))
        self.f(*args, **kwargs)


@MyClassDecorator
def display_function(a, b, c):
    print("display_function() called")


@MyClassDecorator
def display_function_no_call(a, b, c):
    print("display_function_no_call() called")


print("Decoration finished for display_function() and display_function_no_call()")

display_function(1, 2, 3)
print("display_function() executed")

"""
output:

__init__() called | function:display_function
__init__() called | function:display_function_no_call
Decoration finished for display_function() and display_function_no_call()
__call__() called | function:display_function | args: (1, 2, 3) | kwargs:{}
display_function() called
display_function() executed
"""

Function implementation of function decorator without argument

def my_decorator(f):
    print('my_decorator() called | function:' + str(f.__name__))

    def wrapped(*args, **kwargs):
        print('wrapped() called |  function:' + str(f.__name__) + ' | args:' + str(args) + '| kwargs:' + str(kwargs))
        f(*args)  # calling the original function

    return wrapped


@my_decorator
def display_function(a, b, c):
    print("display_function() called")


@my_decorator
def display_function_no_call(a, b, c):
    print("display_function_no_call() called")


print("Decoration finished for display_function() and display_function_no_call()")

display_function(1, 2, 3)
print("display_function() executed")

"""
output:

my_decorator() called | function:display_function
my_decorator() called | function:display_function_no_call
Decoration finished for display_function() and display_function_no_call()
wrapped() called |  function:display_function | args:(1, 2, 3)| kwargs:{}
display_function() called
display_function() executed
"""

Class implementation of function decorator with argument

class MyClassDecorator(object):

    def __init__(self, *deco_args, **deco_kwargs):
        print('__init__() called  | args: ' + str(deco_args) + ' | kwargs:' + str(deco_kwargs))

    def __call__(self, f):
        print('__call__() called | function:' + str(f.__name__))

        def wrapped(*args, **kwargs):
            print(
                'wrapped() called |  function:' + str(f.__name__) + ' | args:' + str(args) + '| kwargs:' + str(kwargs))
            return f(*args, **kwargs)

        return wrapped


@MyClassDecorator("arg1", "arg2")
def display_function(a, b, c):
    print("display_function() called")


@MyClassDecorator("no_call_arg1", "no_call_arg2")
def display_function_no_call(a, b, c):
    print("display_function_no_call() called")


print("Decoration finished for display_function() and display_function_no_call()")

display_function(1, 2, 3)
print("display_function() executed")

"""
output:

__init__() called  | args: ('arg1', 'arg2') | kwargs:{}
__call__() called | function:display_function
__init__() called  | args: ('no_call_arg1', 'no_call_arg2') | kwargs:{}
__call__() called | function:display_function_no_call
Decoration finished for display_function() and display_function_no_call()
wrapped() called |  function:display_function | args:(1, 2, 3)| kwargs:{}
display_function() called
display_function() executed
"""
Function implementation of function decorator with argument

def my_decorator(*deco_args, **deco_kwargs):
    print('my_decorator() called | args: ' + str(deco_args) + ' | kwargs:' + str(deco_kwargs))

    def inner(f):
        print('inner(f) called  |  function:' + str(f.__name__) + ' || ( Have access to  deco_args: ' + str(
            deco_args) + ' | deco_kwargs:' + str(deco_kwargs) + ')')

        def wrapped(*args, **kwargs):
            print(
                'wrapped() called |  function:' + str(f.__name__) + ' | args:' + str(args) + '| kwargs:' + str(
                    kwargs) + ' || ( Have access to  deco_args: ' + str(
                    deco_args) + ' | deco_kwargs:' + str(deco_kwargs) + ')')
            return f(*args, **kwargs)  # calling the original function and return

        return wrapped

    return inner


@my_decorator("arg1", "arg2")
def display_function(a, b, c):
    print("display_function() called")


@my_decorator("no_call_arg1", "no_call_arg2")
def display_function_no_call(a, b, c):
    print("display_function_no_call() called")


print("Decoration finished for display_function() and display_function_no_call()")

display_function(1, 2, 3)
print("display_function() executed")

"""
output:

my_decorator() called | args: ('arg1', 'arg2') | kwargs:{}
inner(f) called  |  function:display_function || ( Have access to  deco_args: ('arg1', 'arg2') | deco_kwargs:{})
my_decorator() called | args: ('no_call_arg1', 'no_call_arg2') | kwargs:{}
inner(f) called  |  function:display_function_no_call || ( Have access to  deco_args: ('no_call_arg1', 'no_call_arg2') | deco_kwargs:{})
Decoration finished for display_function() and display_function_no_call()
wrapped() called |  function:display_function | args:(1, 2, 3)| kwargs:{} || ( Have access to  deco_args: ('arg1', 'arg2') | deco_kwargs:{})
display_function() called
display_function() executed
"""
Class implementation of class decorator without argument

class MyClassDecorator:
    # accept the class as argument
    def __init__(self, _class):
        print('__init__() called | class:' + str(_class.__name__))
        self._class = _class

    # accept the class's __init__ method arguments
    def __call__(self, name):
        print('__call__() called | class:' + str(self._class.__name__) + ' | arg:' + str(name))

        # define a new display method
        def new_display(self):
            print('new_display() called')
            print('Name: ', self.name)
            print('PIN: 1234')

        # replace display with new_display
        self._class.display = new_display

        # return the instance of the class
        obj = self._class(name)
        print('returning modified class object')
        return obj


@MyClassDecorator
class Employee:
    def __init__(self, name):
        print('original __init__() called' + ' | arg:' + str(name))
        self.name = name

    def display(self):
        print('original display() called')
        print('Name: ', self.name)


print("Decoration finished for Employee Class")
obj = Employee('Towhidul Haque Roni')
print("Employee obj created")
obj.display()
print("display() executed")

"""
output:

__init__() called | class:Employee
Decoration finished for Employee Class
__call__() called | class:Employee | arg:Towhidul Haque Roni
original __init__() called | arg:Towhidul Haque Roni
returning modified class object
Employee obj created
new_display() called
Name:  Towhidul Haque Roni
PIN: 1234
display() executed
"""

Function implementation of class decorator without argument

def my_decorator(_class):
    print('my_decorator() called for the class: ' + str(_class.__name__))

    # define a new display method
    def new_display(self):
        print('new_display() called')
        print('Name: ', self.name)
        print('PIN: 1234')

    # replace the display with new_display
    # (if the display method did not exist in the class,
    # the new_display would have been added to the class as the display method)
    _class.display = new_display

    # return the modified employee
    print('returning modified class (not object)')
    return _class


@my_decorator
class Employee:
    def __init__(self, name):
        print('original __init__() called' + ' | arg:' + str(name))
        self.name = name

    def display(self):
        print('original display() called')
        print('Name:', self.name)


print("Decoration finished for Employee Class")
obj = Employee('Towhidul Haque Roni')
print("Employee obj created")
obj.display()
print("display() executed")

"""
output:

my_decorator() called for the class: Employee
returning modified class (not object)
Decoration finished for Employee Class
original __init__() called | arg:Towhidul Haque Roni
Employee obj created
new_display() called
Name:  Towhidul Haque Roni
PIN: 1234
display() executed
"""
Decorator chaining 

def register(*decorators):
    """
    This decorator is for chaining multiple decorators.
    :param decorators:args(the decorators as arguments)
    :return: callable object
    """

    def register_wrapper(func):
        for deco in decorators[::-1]:
            func = deco(func)
        func._decorators = decorators
        return func

    return register_wrapper


def deco1(f):
    def wrapper(*args, **kwds):
        print('-' * 100)
        fn = f(*args, **kwds)
        print('-' * 100)
        return fn

    return wrapper


def deco2(f):
    def wrapper(*args, **kwds):
        print('*' * 100)
        fn = f(*args, **kwds)
        print('*' * 100)
        return fn

    return wrapper


def deco3(f):
    def wrapper(*args, **kwds):
        print('#' * 100)
        fn = f(*args, **kwds)
        print('#' * 100)
        return fn

    return wrapper


class Foo(object):
    @deco1
    @deco2
    @deco3
    def bar(self):
        print('I am bar')


class AnotherFoo(object):
    @register(deco1, deco2, deco3)
    def bar(self):
        print('I am bar')


foo = Foo()
foo.bar()
print('\n\n~~~~ Alternate Way to Annotate ~~~~\n\n')
another_foo = AnotherFoo()
another_foo.bar()
print(another_foo.bar._decorators)


"""
output:

----------------------------------------------------------------------------------------------------
****************************************************************************************************
####################################################################################################
I am bar
####################################################################################################
****************************************************************************************************
----------------------------------------------------------------------------------------------------


~~~~ Alternate Way to Annotate ~~~~


----------------------------------------------------------------------------------------------------
****************************************************************************************************
####################################################################################################
I am bar
####################################################################################################
****************************************************************************************************
----------------------------------------------------------------------------------------------------
(<function deco1 at 0x7f50c7e6c940>, <function deco2 at 0x7f50c7e6c9d0>, <function deco3 at 0x7f50c7e6ca60>)

"""
You can comment any suggestions on it. If you enjoyed the article and want updates about my new article, please follow me.


Thursday, March 31, 2022

Django development environment quick start

Today I will show you how to set up a really simple Django development environment directly on the Docker container without a local Django installation. We will also run a PostgreSQL server in a docker container.


I am assuming that you have already installed Docker and Docker-compose. If not, there are pretty goods docs on docker's official website. Follow them to install on your OS (Windows/macOS/Linux). I am using macOS, but others will be almost similar (if you find it difficult, just put a comment below). 


Follow the below steps to quick start Django development on the Docker environment 

1) Make a project directory, e.g.-TestApp

2) Create a file name Dockerfile on the directory and add the following lines 


FROM python:3.9.1


LABEL maintainer="roni@wiseturn.net"

LABEL vendor="wiseturn.net"


ENV PYTHONDONTWRITEBYTECODE=1

ENV PYTHONUNBUFFERED=1

WORKDIR /code

COPY required-package.txt /code/

RUN pip install -r required-package.txt

COPY . /code/

3) Create a file name required-package.txt and add the following lines -


Django>=3.2,<4.0

psycopg2>=2.8

4) Then create a file name docker-compose.yml and add the following lines -


version: "3.9"

   

services:

  db:

    image: postgres

    volumes:

      - ./container-data/db:/var/lib/postgresql/data

    environment:

      - POSTGRES_NAME=postgres

      - POSTGRES_USER=postgres

      - POSTGRES_PASSWORD=postgres

  web:

    build: .

    command: python manage.py runserver 0.0.0.0:8000

    volumes:

      - .:/code

    ports:

      - "8000:8000"

    environment:

      - POSTGRES_NAME=postgres

      - POSTGRES_USER=postgres

      - POSTGRES_PASSWORD=postgres

    depends_on:

      - db

5) Now open the terminal ad go to the project directory, and enter the following command to start a Django project -


$ docker-compose run web django-admin startproject testapp .

6) All required files and folders are generated by this time. Go to testapp folder , open settings.py file add


import os 

on top of the page and replace 


DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.sqlite3',

        'NAME': BASE_DIR / 'db.sqlite3',

    }

}


with 


DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.postgresql',

        'NAME': os.environ.get('POSTGRES_NAME'),

        'USER': os.environ.get('POSTGRES_USER'),

        'PASSWORD': os.environ.get('POSTGRES_PASSWORD'),

        'HOST': 'db',

        'PORT': 5432,

    }

}

7) Now, to run the containers, execute the following commands -


$ docker-compose down

$ docker-compose build

$ docker-compose up -d


8) Now open your browser and go http://localhost:8000; you will see the Django welcome page.


This tutorial is for a quick start; next, I will post explaining these and how to do it for the professional app.

Wednesday, February 7, 2018

Start Your Spring development with IntelliJ IDEA in 3 Minutes


Lots of my students and juniors keep telling me that, setting up a “Spring” development environment is a big hassle. There are many tutorials are available in the web but they are not comfortable with those. May be the tools we are using are slightly different with them or it is just a time consuming for the initial setting up. That is why I choose to write a post them to start a spring project from scratch, hopefully it will help others too. I am using “IntelliJ IDEA” ultimate IDE (as usual) and maven for build automation tool. I will deploy it on JBoss server (similar on Apache Tomcat or Oracle WebLogic).
  
You will find lots of good tutorials on downloading and setting up IDE (Idea) and web-server (JBoss) and the basic knowledge on Spring MVC, so I am omitting those things (if you don’t find it on Google, make a comments on the below comment section).

    Please follow steps by steps –
1)    Go to  New Project -> Maven , don’t select archetype and press Next

2)    Write GroupId, ArtifactId, Version like this.


groupId will identify your project uniquely across all projects, so we need to enforce a naming schema. It has to follow the package name rules, what means that has to be at least as a domain name you control, and you can create as many subgroups as you want. Example-
com.roni

artifactId is the name of the jar without version. If you created it then you can choose whatever name you want with lowercase letters and no strange symbols. If it's a third party jar you have to take the name of the jar as it's distributed. Example-
springtest

version if you distribute it then you can choose any typical version with numbers and dots (1.0, 1.1, 1.0.1, ...). In this example, we will keep the default-
1.0-SNAPSHOT

3)    Press Next then write the Project Name and select the project location, then click Finish  



4)    Open the maven pom.xml file (if not opened yet automatically) and add the following lines inside the project tag.-
<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <packaging>war</packaging>

    <properties>
        <spring.version>4.3.0.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>


You can choose enable auto import option or you have to click import changes whenever you have made any change on the pom.xml


5)    Create webapp and WEB-INF directory in the main folder as shown below –


6)    Create web.xml file in WEB-INF and write the following lines-

<?xml version="1.0" encoding="ISO-8859-1" ?>

<web-app id="WebApp_ID" version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Spring Test Application</display-name>
    <description>
        This is a simple spring mvc app
    </description>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>


   

7)    Now create dispatcher-servlet.xml file on WEB-INF directory and add the following lines on it


   
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <mvc:annotation-driven/>
    <context:component-scan base-package="com.roni.springtest.controllers"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>




Here base-package is your java package, which we will going to create on the next steps.


8)    Now create the package and a new Controller class SpringTestController in it. Write the following codes –

package com.roni.springtest.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * User: Towhidul Haque Roni
 * Date: 2/7/2018
 * Time: 2:39 PM
 */
@Controller
public class SpringTestController {

    @GetMapping("/")
    public String index(Model m) {
        m.addAttribute("aVariable", "Hello World");
        return "index";
    }
}




9)    Create directory views in WEB-INF and create index.jsp file on it. Write the following lines on it-
<!DOCTYPE html>
<html>
<body>

    <h1>Spring MVC Test</h1>

    <p>${aVariable}</p>

</body>
</html>

10)    Now if you click Run from Run menu for the first time, you will be prompt to Edit Configuration. If you click, following menu will  appear –


11)    Click the top most left + sing, then scroll down and you will see the JBoss Server. Select the local, If you have already configured the JBoss server it will appear in the application server dropdown list, if not then click Configure and it will require to show the JBoss home directory. I have downloaded the jboss-eap-7.1.0 and unzip it and showed the path ( jboss-eap-7.1.0\jboss-eap-7.1 ) as a home directory.

12)    Then go to Deployment , click the right most + sign and add springtest.war artifacts like below  -




13)    Now click Run, hopefully you will be able to see the output like below –


Enjoy!!! I hope that it will save your time. On the upcoming post, I will do REST web service and spring data within 5 minutes setting up time.

Friday, March 27, 2015

How to Run Glassfish 3 on JDK8 /JRE8



  

Have you updated your PC with new Java 8? Are you using glassfish3 because of unstable glassfish 4 or support or any other reason? Now you will face problem as there is no option to run the glassfish 3 on JRE8. If you have earlier JDK too,  you will get  the error of  'Unsupported major.minor version' during the deployment of app with new jar (compiled with newt JDK ). Here is a little trick I have done to do so –
        1) Open the file ‘domain.xml’ located at
${GLASSFISH_HOME}\glassfish\domains\domain1\config

Edit the ‘java-home’ for example replace –
java-home="C:\Program Files\Java\jdk1.6.0_45"
by
java-home="C:\Program Files\Java\jdk1.8.0_40"

        2) Then open the file ‘osgi.properties’ located at

${GLASSFISH_HOME}\glassfish\config
Append the following line at the end –
jre-1.8=${jre-1.7}
        3) Done… run and enjoy :)
You can check your Glassfish’s JDK from- 
 http://localhost:4848/management/domain/version?verbose=true

Monday, September 10, 2012

Intellij Idea key scheme for Eclipse



I’m a diehard fan of intellij idea. I also developed few android apps on idea. Just missing the UI drag and drop option but it will come in the version 12.  Already preview option is available from version 11. There are some projects on going in my office and I have to use eclipse, so I have to know the shortcut of eclipse. But suddenly I found an idea key scheme for eclipse.  Download the latest jar from the following URL –
Then put the jar on “plugins” directory of the eclipse and restart the eclipse IDE.
Now you will see idea schema on Keys (Window->Preferences->General->Keys).
Thanks to Santhosh to make our life easy :)

Sunday, May 8, 2011

Making jar by IntelliJ IDEA

Few people told me why are you using idea, it is not possible to create jar from it. Actually this idea about idea is totally wrong. To make a jar from idea go to

File -> Project Structure -> Artifacts

Then click the plus sign to add a jar setting. The “Create Jar from Modules” window will appear. Select the module and main class.

1) Choose extract to the target jar to include all the library jars include in your jar. Then press Apply and Ok. After than you will see a “Build ‘moduleName.jar:’ artifact” option in Build menu. It’s simple.

Or

2) And if you choose “copy to output directory and link via manifest” the edit the manifest to locate the library jars in Class-Path tag ex-(lib/one.jar lib/two.jar). Remind that if you execute the jar from a folder which folder is located in the project root directory and your library jars are located on a “lib” folder which is also in the root project directory, then add class path like (Class-Path: ../lib/one.jar ../lib/two.jar)

Wednesday, January 20, 2010

git color customize

Did you watch the movie Matrix? I think the answer is obviously yes. I am a very good fan of that movie. After watching this movie, my Linux theme, wallpaper , screensaver changed to that theme, specially the terminal. I use Konsole with Green and black schema. So it is a little bit fuzzy when I use “git diff” with default auto color system of git. So I customize the color by editing the “.gitconfig” file on my home directory.

[color]
ui = auto
[color "branch"]
current = yellow reverse
local = yellow
remote = white
[color "diff"]
meta = yellow bold
frag = magenta bold
old = red bold
new = white bold
[color "status"]
added = yellow
changed = red
untracked = cyan
[user]
name = Towhidul Haque Roni
email = towhid@xyz.net

Thursday, January 14, 2010

Make IDEA faster

I was working on a renowned XYZ software company. They prefer IntelliJ IDEA as a IDE. My senor collogue give me some task and I was working on the IDEA. He found the IDE is too slow and suggest me to increase the virtual memory. So I have change it in the “idea.vmoptions” file located on (/idea/bin).
======================================
-Xms700m
-Xmx1024m
-XX:MaxPermSize=450m
-ea
=====================================
But it seems too slow for scrolling the codes on IDEA. Then my senior suggests me to use version 6 instead of version 8. But I was working with IDEA 8 and looking for a solution. Suddenly senior bro came to me and wanted to see my progress. When he found IDEA version 8 he became angry and warn me he will delete all my code. I was so scared though I have IDEA local history and git ;) . Then I suddenly found the solution that it frequently uses graphics card but I know that it is not NFS(my favorite game :P) so I can disable that by including
-Dsun.java2d.pmoffscreen=false
At the end of the “idea.vmoptions” file. And the problem solved :D

Wednesday, October 14, 2009

How to setup an ftp server on Linux

[root@roni ~]# yum install vsftpd

Loaded plugins: fastestmirror

Loading mirror speeds from cached hostfile

* base: mirror.cs.vt.edu

* updates: mirror.atlanticmetro.net

* addons: chi-10g-1-mirror.fastsoft.net

* extras: updates.interworx.info

Setting up Install Process

Parsing package install arguments

Package vsftpd-2.0.5-12.el5_3.1.i386 already installed and latest version

Nothing to do

[root@roni ~]# vi /etc/vsftpd/vsftpd.conf

Find and edit

xferlog_std_format=NO
log_ftp_protocol=YES
chroot_local_user=YES
banner_file=/etc/vsftpd/issue

to create a message compliant with the local site policy or a legal disclaimer:

[root@roni ~]# vi /etc/vsftpd/issue

NOTICE

Put whatever your message to the user.......

[root@roni ~]# chkconfig vsftpd on

[root@roni ~]# service vsftpd start

Starting vsftpd for vsftpd: [ OK ]

[root@roni ~]# netstat -tulpn | grep :21

tcp 0 0 0.0.0.0:21 0.0.0.0:* LISTEN 29119/vsftpd

[root@roni ~]# vi /etc/sysconfig/iptables

Add this line

RH-Firewall-1-INPUT -m state --state NEW -p tcp --dport 21 -j ACCEPT

[root@roni ~]# vi /etc/sysconfig/iptables-config

Edit

IPTABLES_MODULES="ip_conntrack_ftp"

[root@roni ~]# service iptables restart

to view the log file

[root@roni ~]# tail -f /var/log/vsftpd.log

Wed Jul 8 08:23:01 2009 [pid 2379] [ftp] FTP command: Client "202.148.56.8", "CWD /srv/"

Wed Jul 8 08:23:01 2009 [pid 2379] [ftp] FTP response: Client "202.148.56.8", "550 Failed to change directory."

Wed Jul 8 08:23:01 2009 [pid 2383] [ftp] FTP command: Client "202.148.56.8", "PWD"

Wed Jul 8 08:23:01 2009 [pid 2383] [ftp] FTP response: Client "202.148.56.8", "257 "/""

Wed Jul 8 08:23:01 2009 [pid 2383] [ftp] FTP command: Client "202.148.56.8", "CWD /srv/svn/"

Wed Jul 8 08:23:01 2009 [pid 2383] [ftp] FTP response: Client "202.148.56.8", "550 Failed to change directory."

Wed Jul 8 08:23:02 2009 [pid 2383] [ftp] FTP command: Client "202.148.56.8", "NOOP"

Wed Jul 8 08:23:02 2009 [pid 2383] [ftp] FTP response: Client "202.148.56.8", "200 NOOP ok."

Wed Jul 8 08:23:02 2009 [pid 2383] [ftp] FTP command: Client "202.148.56.8", "CWD /srv/svn/RONI/"


@decorators in Python

People have confusion about how to use python decorators in the proper way and how it works. The main reason for it is there are several way...