php

Preg_replace regex delete tags link url completely with text inside using php

31 Dec , 2011  

We need to completely remove anchor links with text inside using PHP. Then, we can use preg_replace() and removing all tags links with string completely by :

1
preg_replace('/<a[^>]*>(.*)</a>/iU','', $text);

Or seconds alternative is :

1
preg_replace('#(<a.*?>).*?(</a>)#', '', $text);

Now you can remove / delete all anchor links 🙂

,

php

Preg_replace regex remove domain name in text / string using PHP

31 Dec , 2011  

This is how to remove any domain name (TLD) in text or string using preg_replace in PHP. Basically, we want to get rid off any domain name in text for instance :

This is paragraph that contain many text and string also with some domain name called : wpscale.com

To strip off the domain name in paragraph :
More…

,

engine

Solve Vagrant “The guest additions do not match the install version of VirtualBox”

30 Dec , 2011  

After upgrading my Virtualbox, I try build my base box and got this errors :

1
2
3
4
5
6
7
8
[ff] The guest additions on this VM do not match the install version of
VirtualBox! This may cause things such as forwarded ports, shared
folders, and more to not work properly. If any of those things fail on
this machine, please update the guest additions and repackage the
box.

Guest Additions Version: 4.1.6
VirtualBox Version: 4.1.8

Yeap, this is happen because I have Ubuntu Oneiric on base box with old Guest Additions Version. Then, let go to the solution. First, remember your Virtualbox Version and download VBoxGuestAdditions with related version. For instance :

1
wget -c http://download.virtualbox.org/virtualbox/4.1.8/VBoxGuestAdditions_4.1.8.iso

Then we will mount and install VboxGuestAddition by :

1
2
3
sudo umount /mnt
sudo mount VBoxGuestAdditions_4.1.8.iso -o loop /mnt
sudo sh /mnt/VBoxLinuxAdditions.run

Now try to “vagrant halt” and “vagrant up” again to see if this works! 🙂

,

engine

Running WordPressure NodeJS in EC2

30 Dec , 2011  

Today I see Dchud release WordPressure, NodeJS + Python apps which aggregate new post in WordPress.com Real-time. Curious how it would be, then I put my unused domain ani-rss.org as my experiments. I use Amazon EC2 with Ubuntu 11.10 64bit (Oneiric). So, here are the steps.

1. Install base packages

1
sudo apt-get install git redis-server

2. Install NodeJS

1
2
3
4
5
6
7
8
9
10
11
12
13
cd ~/
sudo apt-get install git-core curl build-essential openssl libssl-dev pkg-config
mkdir ~/local
wget -c http://nodejs.org/dist/v0.6.6/node-v0.6.6.tar.gz
tar -xvvf node-v0.6.5.tar.gz
cd node-v0.6.5
export JOBS=2
./configure --prefix=$HOME/local/node
make
make install
echo 'export PATH=$HOME/local/node/bin:$PATH' >> ~/.profile
echo 'export NODE_PATH=$HOME/local/node:$HOME/local/node/lib/node_modules' >> ~/.profile
source ~/.profile

Configure /etc/environment to run NodeJS every boot startup:

1
2
3
NODE="/home/ubuntu/local/node"
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:$NODE/bin:$NODE/lib/node_modules"
#PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"

3. Download repository

1
2
git clone https://github.com/dchud/wordpressure.git && cd wordpressure
npm install -g

4. Install Python Dependencies

1
sudo pip install -r requirements.pip

configuration

Solving could should increase server_names_hash_bucket_size: 32 NGINX Ubuntu

29 Dec , 2011  

After I configure several sites that have a long names in NGINX virtualhost, I restart my NGINX and got this error :

1
2
3
sudo service nginx restart
Restarting nginx: nginx: [emerg] could not build the server_names_hash, you should increase server_names_hash_bucket_size: 32
nginx: configuration file /etc/nginx/nginx.conf test failed

Well this is because my NGINX conf only limit server_name into 32 chars. We need to extend it by uncomment “server_names_hash_bucket_size 64;” in nginx.conf :

/etc/nginx/nginx.conf :

1
2
3
4
5
6
7
http {
     ....
     server_names_hash_bucket_size 64;
     # server_name_in_redirect off;

     ....
}

Problem solved! 😀

,

engine

How to receive reset password hpcloud by whitelist email in gmail account

29 Dec , 2011  

Yesterday, I wanna login into my hpcloud account and accidentally forgot my password. Then I go to forgot password page and put my email there. Waiting for more than 3 hours, there no confirmation email yet from HPCloud in my Gmail inbox. Try with three times and no result yet. Event spambox still empty. Then I contact HPCloud through their twitter account and contact pages.. More…

,

Django

How to use reverse URL names without resource_name Django tastypie

29 Dec , 2011  

Using reverse URL in Django-tastypie with names will ease our development or making unit test. When I wrote this, I was helped by Joshbohde from Django-tastypie IRC. So, if you have some problem when using Tastypie, I suggest you ask to via IRC.

I have APP/insurance here for example. By default, I can access Django-Tastypie Resource API with reverse(), eg :

1
2
3
from django.core.urlresolvers import reverse

url = reverse('api_dispatch_list', kwargs={'resource_name': 'insurance'})

I thinks it’s too long here. Then, we can use “names” django url feature. Now, let we define our api.py, eg :
More…

,

wordpress

How to run cron and execute function inside plugin in WordPress 3

28 Dec , 2011  

Running cronjobs in WordPress is easy but seem there are lack of documentation that talking about this. Especially, if we want to running our custom plugin in WordPress from our cronjobs. Actually, there are two methods of running cron in WordPress. First, it’s running from loaded pages. Seconds, it’s running through cron UNIX servers (wget, lynx, or somethings).

For instance, I have plugin called “montage”, so I will defined scheduler event here :
More…

,

Server

Setup VPS / Server from beginning for WordPress sites with NGINX + MySQL Ubuntu

27 Dec , 2011  

I will guide you about how to setup brand new VPS / Server to host WordPress with optimize configuration. I prefer use NGINX + MySQL here. Remember, I start from zero configuration with mean no software installed , no pre-installed program and default Ubuntu. If you want to install several VPS / Server, then you can try “terminator” console and set broadcast.
More…

,

Django

Django tastypie One to Many fields related models reverse backward

27 Dec , 2011  

One to Many fields in Django Tastypie is easy if we search on Models on foward. Which we query from models who have Foreign Key. But, reverse query from related manager is a little bit complex. Because we know :

Unlike Django’s ORM, Tastypie does not automatically create reverse relations. This is because there is substantial technical complexity involved, as well as perhaps unintentionally exposing related data in an incorrect way to the end user of the API.

So, to make reverse Relationship with Django tastypie, we should define several things. Wrong things will lead you into this kind of error :

1
reverse for 'api_dispatch_detail' with arguments '()

More…

,

wordpress

Download image and attach into post programmatically in WordPress 3

24 Dec , 2011  

All we know, we can use wp_insert_post() to create content programmatically in WordPress. But, there more magic goodies bag in WordPress. We can download images and attach into post programmatically by using media_sideload_image(). There are several issue while using this function because lack of documentation about how to implement it.

The common error when using media_sideload_image() :
1. It generate blank page with errors.
2. Undefined function media_sideload_image()
3. Undefined function download_url()
More…

,

php

Run latest PhantomJS with shell_exec PHP on Ubuntu 11.10 Oneiric

24 Dec , 2011  

Running PhantomJS with exec() or shell_exec PHP and grab it results may lead you into several headache problems. Several web that talking how to run phantomjs in PHP just send me into fail results. I will show you several pitfalls for instance, here a small scripts to run PhantomJS :

test.php :

1
2
3
4
<?php
$result = shell_exec('phantomjs --version');
echo $result;
?>

More…

,

Django

Learn how to make custom filter debug variables with ipdb in Django 1.3

22 Dec , 2011  

Template filter in Django is great. We usually use it when processing variable that passed from views into templates. There are several built-in filters in Django that powerfull to process variable in templates. You can see them on https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#ref-templates-builtins-filters. Here are some basic template filter eg :

1
{{ bon|upper }}

If you already have debug background using Pdb / Ipdb, then we will implement it into templates. We want to debug variable in templates using Pdb / Ipdb. So, first we need to create “templatetags” folder.
More…

,

Django

Separate settings.py while developing many apps in Django for your sake

22 Dec , 2011  

Developing many apps in Django can’t avoided when system getting large and growing. Usually, a new Django developer put all configuration of several APPS in “ONLY” settings.py. Is this wrong? No! Is this effective ? Not really!. What I mean, you will have no problem if APPS just sit in development stage. But, when you moved it into production, need to test APPS independently or put into another development workspace then you will see devil what I mean.

If you build APPS that have several VARIABLE that need configure in settings.py, you will see a potential problem. If you want to testing APPS into isolated area, yes you will see a potential problem.
More…

,

Python module

Install python PIL ( Python image Library ) on Ubuntu 11.10 Oneiric

20 Dec , 2011  

Installing PIL in Ubuntu 11.10 Oneiric 64-bit using pip raise problem on JPEG, Zlib or freetype support. First, you need to uninstall PIL by :

1
sudo pip uninstall PIL

Then you should install default Ubuntu packages :

1
sudo apt-get install libjpeg8 libjpeg62-dev libfreetype6 libfreetype6-dev

We should fix PIL path libraries by :

1
2
3
sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib

More…

,

Django

Solve “error_message”: “‘WSGIRequest’ object has no attribute ‘items'”

16 Dec , 2011  

When you need to pass “request” into some instance, maybe on Django-haystack or some another django apps, somehow you got this kind of error :

1
2
"error_message": "'WSGIRequest' object has no attribute 'items'",
"traceback": "Traceback (most recent call last):nn File "/usr/local/lib/python2.7/dist-packages/tastypie/resources.py", line 192, in wrappern response = callback(request, *args, **kwargs)nn File "/home/vagrant/htdocs/ff/airport/../airport/services/api.py", line 61, in get_searchn page = paginator.page()nn File "/usr/local/lib/python2.7/dist-packages/tastypie/paginator.py", line 164, in pagen meta['previous'] = self.get_previous(limit, offset)nn File "/usr/local/lib/python2.7/dist-packages/tastypie/paginator.py", line 123, in get_previousn return self._generate_uri(limit, offset-limit)nn File "/usr/local/lib/python2.7/dist-packages/tastypie/paginator.py", line 139, in _generate_urin request_params = dict([k, v.encode('utf-8')] for k, v in self.request_data.items())nnAttributeError: 'WSGIRequest' object has no attribute 'items'n"

More…

,

Django

Solve psycopg2.ProgrammingError: autocommit in Django 1.3.1 + Postgresql run test

15 Dec , 2011  

When I test my django application which use Postgresql and using python-psycopg2 (Ubuntu 11.10) as wrapper, I got this kind of error :

Run python manage.py myapp :

1
2
3
4
5
6
7
Creating test database for alias 'default'...
Traceback (most recent call last):
  File "manage.py", line 14, in <module>
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/creation.py", line 481, in set_autocommit
    self.connection.connection.autocommit = True
psycopg2.ProgrammingError: autocommit cannot be used inside a transaction
</module>

More…

,

function

Deep Dive into Python Path Construction

15 Dec , 2011  

Today I found great tutorial that explain how sys.path is working. Follow this link to see through :

If a script is executed, the interpreter sets the first entry of sys.path to that script’s directory. If Python is launched interactively, the first entry is the empty string (“”), meaning Python will scan the present working directory first. The next entries of sys.path are the contents of the PYTHONPATH environment variable, if it exists. Then, installation-dependent entries are appended (example below).

When initializing, the interpreter normally imports the site module automatically. The module, on import, executes code to find .pth files in known site-packages directory locations, which themselves contain entries which are either paths to add to sys.path, or import calls. If we really want to trace what’s going on, we can launch a Python interpreter with -S to prevent loading the site module automatically, and instead trace the import.

http://blog.adamdklein.com/?p=492 More…

,

Django

Creating Form automatically with ModelForm in Django 1.3

13 Dec , 2011  

Building form in Django 1.3 is pretty easy with ModelForm. Basically, when we create Model, it will need some CRUD from then. Django give Modelform to ease our steps from defining forms which may have same description with models. For instance, I have models.py which contain Query models :

1
2
3
4
5
6
7
8
9
10
11
12
from django.db import models
from django.forms import ModelForm

class Query(models.Model):
    """Models for logging incoming query and requester"""    
    name = models.CharField(max_length=255)
    url  = models.TextField()
    source = models.CharField(max_length=255)
    request = models.CharField(max_length=255)
   
    def __unicode__(self):
        return u'%s %s %s' % (self.name, self.source, self.request)

Then I want to show Query forms in template (index.html) which have same definition with models. So, I will use Modelform.
More…

,

Django

How to saving dict into models in Views Django

12 Dec , 2011  

If you deploy views and need to saving data into models, you should considering dictionaries type rather with standard. For instance, this is standard way to save data into django models :

1
2
3
4
5
# This is standar way
def index(request):
    mymodel = Bug(qid = '1', subject = 'subject',
                  content = 'content', date = '20110801')
    mymodel.save()

More…

,

function

Understanding about namespaces, attributes and scopes in Python

8 Dec , 2011  

I assume you don’t understand about namespaces, attributes and scopes in Python. Because I will explain about this three things that mostly missed by people who start learning with Python. Actually, this things will help us in the future about understanding Python even for advanced programmer. So, let begin with namespaces.

Namespaces according to Wikipedia it’s meaning for :

A namespace (sometimes also called a name scope) is an abstract container or environment created to hold a logical grouping of unique identifiers or symbols (i.e., names). An identifier defined in a namespace is associated only with that namespace. The same identifier can be independently defined in multiple namespaces. That is, the meaning associated with an identifier defined in one namespace may or may not have the same meaning as the same identifier defined in another namespace. Languages that support namespaces specify the rules that determine to which namespace an identifier (not its definition) belongs.[1]

More…

,

Django

How to Install Django 1.3.1, Apache ModWSGI and PostgreSQL in Ubuntu Oneiric 11.10

8 Dec , 2011  

Full guide to build Django 1.3.1, Apache2 + ModWSGI and PostgreSQL in Ubuntu 11.10 Oneiric. There are several dependencies packages, python modules and a little configuration to make Django run with PostgreSQL. Let start!

1. Install dependencies Ubuntu packages
We need to install base packages, python modules, postgresql , apache2 and mod-wsgi.

1
2
3
4
5
sudo apt-get update && sudo apt-get upgrade
sudo apt-get install apache2 libapache2-mod-wsgi
sudo apt-get install python-setuptools python-pip build-essential nmap python-dev
sudo apt-get install postgresql libpq-dev pgadmin3
sudo pip install psycopg2==2.4.1

2.Download and install Django 1.3.1
Go to https://www.djangoproject.com/download/ and Download latest Django version. Then extract it and install with :

1
sudo python setup.py install

Now you have Django installed in your Ubuntu 11.10 Oneiric.

3. Configure PostgreSQL
If you have MySQL based, actually PostgreSQL isn’t too different with it. First, you must configure password for default account (postgres) and you can create account later. Also, you can create database and assign user permission on it.

We will make our PostgreSQL can be accessed from remote. First, “sudo vim /etc/postgresql/9.1/main/postgresql.conf” and set this :

1
listen_addresses = '*'

Add permission to another host to access PostgreSQL remotely by editing “sudo vim /etc/postgresql/9.1/main/pg_hba.conf”. For instance, I want allowed IP range 33.33.33.1-30 ( I use Vagrant ). So I should add it :

1
host    all           all             33.33.33.1/30            md5

To reset default password for account “postgres” :

1
2
3
sudo su postgres -c psql postgres
ALTER USER postgres WITH PASSWORD '<your-new-password-here>';
q

To create new user in PostgreSQL (for instance, django_login) :

1
sudo -u postgres createuser -P django_login

To create new database in PostgreSQL :

1
2
sudo -u postgres psql
CREATE DATABASE <your-django-database> OWNER <your-username-here> ENCODING 'UTF8';

To see PostgreSQL cheatsheet : http://www.postgresonline.com/special_feature.php?sf_name=postgresql83_psql_cheatsheet&outputformat=html

Don’t forget to restart postgresql service to use new configuration by :

1
sudo service postgresql restart

4. Configure settings.py

1
2
3
4
5
6
7
8
9
10
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '<your-database-here>',      # Or path to database file if using sqlite3.
        'USER': '<your-username-here>',                      # Not used with sqlite3.
        'PASSWORD': '<your-password-here>',                  # Not used with sqlite3.
        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '5432',                      # Set to empty string for default. Not used with sqlite3.
    }
}

5. Export table postgreSQL

1
pg_dump <DATABASE> -t <TABLE> -f <FILE> -U postgres -W

6. Import table postgreSQL

1
psql <DATABASE> < <FILE> -U postgres -W

Now all it’s done. You should do “python manage.py syncdb” before running server with “python manage.py runserver”. Cheers! 🙂

,

Django

The right configuration virtualhost for Apache + ModWSGI run Django

7 Dec , 2011  

We know that Django doesn’t serve files itself. Django suggest us to run separate Web server for running media and another. We may use NGINX, Lighthttpd, Cheeroke or anothers. But, there it’s not wrong to host Django with Apache + ModWSGI. I use it for development which it have monitoring to our files and auto-reload if there changes ommited. Ref: https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/modwsgi/. More…

,

Django

Solving admin CSS not loaded or not found in Django

7 Dec , 2011  

When running Django with development server, open “/admin” will show perfectly without any problem. But, running Django with Apache + ModWSGI or NGINX + UWSGI, CSS admin not loaded and not found. So, Django admin showing plain without CSS. This problem is commonly happen when we deploy Django on production. Why this is happen ?
More…

,

Django

Learning how create regex URLCONF route in Django 1.3

7 Dec , 2011  

Few developers complaining about hard to create url routes in Django. Regex always like nightmare, but we must get along with it. And don’t worry, in Django 1.3, you doesn’t need to know whole knowledge about regex. Meanwhile, design url usually common and not to complicate.

Know we see this example of URLCONF :

1
2
3
4
5
6
from django.conf.urls.defaults import patterns

urlpatterns = patterns(
    '',
    (r'^posts/$', 'posts.views.index'),
)

First thing we should know
We know that Django search python module and search urlpatterns (a Python list) variable when processing request. So, we need to import patterns from django.conf.urls.defaults and create urlpatterns variable (list).
More…

,

Django

Understanding Django Workflow, structure, files and deep inside

7 Dec , 2011  

Django is special framework that build base on Python. If you familiar with PHP Framework like CodeIgniter, CakePHP or another else, you will find Django is different. For futhermore explanation, I assume you using Ubuntu (I use 11.10) , know how to install Django and run through “python manage.py runserver”.

Back to why Django is different, actually it installed in OS as native python packages. That’s same way when you install another python modules packages through python-pip and all installed located in “/usr/local/lib/python2.7/dist-packages/”. After installed, when can execute some django command through console like “django-admin.py”. More…

,

engine

Review how to build Ubuntu Oneiric 11.10 instance on HPCloud

7 Dec , 2011  

Today I got invitation from HPCloud to test cloud services for free. I want to see if HP Cloud can surpass over Amazon EC2 and Rackspace which I have server on both of them. First, I signup with invitation code and set my payment method with credit card. If you have the invitation code like me, don’t worry about billing, HPCloud does not charge in private beta and will give notification if it does. After register my payment method, then I go through with “create server” on Compute — US West 2 – AZ1. You should “activate now” before create cloud server.

It’s pretty simple to create server instance in HPCloud panel. There are several options in create server panel like Size, Security Group, Public IP, Install Image, Key Pair and Instances. I set my Install image into Ubuntu oneiric and default for the other. Only one step taken and your server already build. It’s more simple than EC2 or Rackspace which need a few steps. More…

,

Django

How to load urlconf route apps into projects in django 1.3

6 Dec , 2011  

Django has special method to process URL and you can design the URL design however you want. To create URL design, you should create URLCONF modules. This modules will mapping url patterns to views. Before looking more, we should know about this basic things.

How Django processes a request ?

When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute:

1. Django determines the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONF setting, but if the incoming HttpRequest object has an attribute called urlconf (set by middleware request processing), its value will be used in place of the ROOT_URLCONF setting.

2. Django loads that Python module and looks for the variable urlpatterns. This should be a Python list, in the format returned by the function django.conf.urls.defaults.patterns().

3. Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.

4. Once one of the regexes matches, Django imports and calls the given view, which is a simple Python function. The view gets passed an HttpRequest as its first argument and any values captured in the regex as remaining arguments.

5. If no regex matches, or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view. See Error handling below.

More…

,

library

Deep understanding XML-RPC Server – Client in Python

6 Dec , 2011  

XMLRPC (XML Remote Procedure Call) which send XML through HTTP for transporting data is common way to communicate between Server and Client. Basically, Client can call methods with parameters on a remote server and get structured data for results. Python have XML-RPC standard library, which it’s mean native installed and ready to use.

First, I start with xmlrpclib (a class) for client access. There important objects inside xmlrpclib for communicate with remote server called ServerProxy(). Basically, you can start communicate with remote server by xmlrpclib.ServerProxy(URI).
More…

,