Archive for the ‘Technical’ Category

Some ways to get value from request in Symfony2

April 15th, 2012 | admin

In symfony2, if you want to get value from request, you have many ways:

forst, bind request to form, then you can use the entity, official document has details.

If you are using formtype, there is another two ways to get value,

first:

$postData = $request->request->get('slackiss_bundle_qingbundle_registertype');
$name_value = $postData['email'];

second:

$email = = $form["email"]->getData();

or

$defaultData = array('message' => 'Type your message here');
$form = $this->createFormBuilder($defaultData)
->add('name', 'text')
->add('email', 'email')
->add('message', 'textarea')
->getForm();

if ($request->getMethod() == 'POST') {
$form->bindRequest($request);

// data is an array with "name", "email", and "message" keys
$data = $form->getData();
}

If you do not use formtype, I mean, you are not using {{form_widget}}, you can get values:


echo $request->request->get('email');

About $request, the code is like:

public function doAction(Request $request)
{
}

or

$request = $this->getRequest();

Some resource to learn mootools

March 1st, 2012 | admin

First of all, docs.mootools.net

You can not leave this website away: http://www.mootorial.com/

I like the book: http://www.apress.com/9781430209836

Install PostgreSQL on OpenSuse 12.1

February 6th, 2012 | admin

First,

$sudo zypper install postgresql postgresql-server pgadmin3

Start server

$sudo rcpostgresql start

Change password for postgres user

$sudo postgres -c psql postgres
ALTER USER postgres WITH PASSWORD 'postgres';
\q

Error!

“IDENT authentication failed for user”

Hence, if you do not use IDENT, edit the /var/lib/pgsql/data/pg_hba.conf file and change “ident” to “md5″. Say, for instance, the lines below

local all all ident
host all all 127.0.0.1/32 ident
host all all ::1/128 ident

to

local all all md5
host all all 127.0.0.1/32 md5
host all all ::1/128 md5

Once done,restart postgreSQL as follows:

opensuse:~ # rcpostgresql restart

Create and Delete users

To create an user

opensuse:~ # su postgres

postgresql@opensuse:~> createuser -D

for user with password

postgresql@opensuse:~> createuser -D -p

To delete user

postgresql@opensuse:~> dropuser

Installing Oracle (sun) Java 1.7u2 openSUSE 12.1

February 6th, 2012 | admin

Download the RPM version of Java from www.oracle.com (in my case I downloaded 1.7u1).

The one I downloaded was: jdk-7u2-linux-i586.rpm

Install the jdk with yast2, zypper, or by double clicking the rpm within dolphin or nautilus:

sudo zypper in jdk-7u2-linux-i586.rpm -y

Now you have to setup the alternatives so you can use switch between Iced Tea, which is default, and the Oracle Java.

First install the alternative:

sudo /usr/sbin/update-alternatives --install "/usr/bin/java" "java" "/usr/java/jdk1.7.0_02/bin/java" 40

Now install the alternative for your browser plugin:

sudo /usr/sbin/update-alternatives --install "/usr/lib/browser-plugins/javaplugin.so" "javaplugin" "/usr/java/jdk1.7.0_02/jre/lib/i386/libnpjp2.so" 40

Note: the first quotes are pointing to the path, the the name of the alternative script, and the 3rd is the location to point to. The numbers at the end is the priority in case it was set to automode.

Now you have to configure the alternatives, first we’ll do java:

sudo /usr/sbin/update-alternatives java

Choose the number associated with /usr/java/jdk1.7.0_01/bin/java, in my case it was 1.

Now lets configure javaplugin:

sudo /usr/sbin/update-alternatives javaplugin

Choose the number associated with /usr/java/jdk1.7.0_01/jre/lib/i386/libnpjp2.so, in my case it was 1.

First, for the haters. I do linux for a living on servers, so I’m used to sudo, and that’s why I use it on my laptop.

Second, also for the other haters. Yes, I could have added some super high priority and kept it on auto, but I like doing it manually.

For the rest, you can check to see what you currently have set by running:

/usr/sbin/update-alternatives --query (or --display) java (or javaplugin)

You can test your java at oracles website:

Improve Battery Management for Linux(OpenSuse12.1)

February 4th, 2012 | admin

Thanks to this article:

 

openSUSE 11.3 und höher

Zur Installation von TLP auf openSUSE müssen die folgenden Schritte in einer Root-Shell ausgeführt werden.

Hinzufügen von Repositories:

openSUSE 11.3

zypper ar -f <a href="http://download.opensuse.org/repositories/home:/cdersch:/TLP/openSUSE_11.3/home:cdersch:TLP.repo" rel="nofollow">http://download.opensuse.org/repositories/home:/cdersch:/TLP/openSUSE_11.3/home:cdersch:TLP.repo</a>

Falls Contrib Repo noch nicht aktiv:

zypper ar -f <a href="http://download.opensuse.org/repositories/openSUSE:/11.3:/Contrib/standard/openSUSE:11.3:Contrib.repo" rel="nofollow">http://download.opensuse.org/repositories/openSUSE:/11.3:/Contrib/standard/openSUSE:11.3:Contrib.repo</a>

openSUSE 11.4

zypper ar -f <a href="http://download.opensuse.org/repositories/home:/cdersch:/TLP/openSUSE_11.4/home:cdersch:TLP.repo" rel="nofollow">http://download.opensuse.org/repositories/home:/cdersch:/TLP/openSUSE_11.4/home:cdersch:TLP.repo</a>

Falls Contrib Repo noch nicht aktiv:

zypper ar -f <a href="http://download.opensuse.org/repositories/openSUSE:/11.4:/Contrib/standard/openSUSE:11.4:Contrib.repo" rel="nofollow">http://download.opensuse.org/repositories/openSUSE:/11.4:/Contrib/standard/openSUSE:11.4:Contrib.repo</a>

openSUSE 12.1

zypper ar -f <a href="http://download.opensuse.org/repositories/home:/cdersch:/TLP/openSUSE_12.1/home:cdersch:TLP.repo" rel="nofollow">http://download.opensuse.org/repositories/home:/cdersch:/TLP/openSUSE_12.1/home:cdersch:TLP.repo</a>

Falls Contrib Repo noch nicht aktiv:

zypper ar -f <a href="http://download.opensuse.org/repositories/openSUSE:/Factory:/Contrib/openSUSE_12.1/openSUSE:Factory:Contrib.repo" rel="nofollow">http://download.opensuse.org/repositories/openSUSE:/Factory:/Contrib/openSUSE_12.1/openSUSE:Factory:Contrib.repo</a>

Paketquellen aktualisieren:

zypper ref

Folgende Pakete sind zu installieren:

  • tlp (TLP Repo)
  • tp_smapi-kmp-desktop (Contrib Repo) – optional nur für ThinkPads, ermöglicht das Einstellen der Akkuladeschwellen und erweiterte Statusanzeigen.

Hinweis: Paketname muss ggf. in tp_smapi-kmp-VARIANTE angepaßt werden, die Kernelvariante lässt sich mit uname -r ermitteln.

  • smartmontools (openSUSE Repo) – optional, ermöglicht die Anzeige von SMART-Daten für die Festplatte(n) durch tlp-stat.
  • ethtool (openSUSE Repo)- optional, ermöglicht es Wake On LAN zu deaktivieren.
  • powertop (openSUSE Repo) – optional, zur Messung des Stromverbrauchs.

Die Pakete installiert man im Terminal als root mit folgendem Kommando (tp_smapi-Paketname ist ggf. anzupassen):

zypper in tlp tp_smapi-kmp-desktop smartmontools ethtool powertop

Install Vmware player on opensuse 12.1

January 29th, 2012 | admin

First, download and install it.

Then, do not forget to install gcc and kernel-source via zypper.

The most important:

sudo /usr/bin/vmware-modconfig  --icon="vmware-player" --appname=Vmware --gcc=/usr/bin/gcc --headers=/lib/modules/3.1.0-1.2-default/build/include/ --gcc-ignore-minor

Then it works well for me.

Double the time for laptop running on battery

January 17th, 2012 | admin

Tested under Mandriva&OpenSuse&Slackware, all works well.

$sudo zypper install powertop
$sudo zypper install  laptop-mode-tools
$sudo zypper install cpufrequtils

also check out cpufreq-utils
http://forums.opensuse.org/blogs/jdm…ls-package-40/

Thanks, quota for remark see following:

 

I have written a bash script file designed to work with the cpufrequtils package and the programs cpufreq-info (for reading CPU speed info) and cpufreq-set (to set CPU speed governor and frequency).

This is my third attempt at writing a bash shell to interface with these two packages. After creating a blog on how to use YaST to set your CPU speed with yast-power-management you can read about here: YaST Power Management – Control Your CPU Energy Usage How To & FAQ – Blogs – openSUSE Forums, several forum users indicated they used the cpufreq utilities instead. So, I decided to see if any sort of value added bash script could be put together to work with this program set. Changes made to your CPU speed only last until you reboot your computer, but you may find the information and function it provides to be useful.

Version 1.10 of C.F.U. (works with openSUSE 12.1) Adds new features and bug fixes:

1. New Help Display is included
2. C.F.U. includes menu automation. Type cfu -h for more details
3. Better Detection for the cpufrequtils to work and to be installed
4. Better detection of available speeds usable on your PC

To use the bash script file cfu, you need to download the following text from SUSE Paste (Actual Link is shown below) into a text editor like kwrite:

C.F.U. – CPU Frequency Utility – Version 1.10

Save the text as the file cfu in the /home area bin folder (example is: /home/username/bin, also known as ~/bin). It is possible to directly download cfu from a terminal session (You must delete or rename the old version first):

rm ~/bin/cfu
wget -nc http://paste.opensuse.org/view/download/72458191 -O ~/bin/cfu

This script must be marked executable to be used. Please run the following Terminal command:

chmod +x ~/bin/cfu

It is even possible to string all three of these commands together as one. Copy the following command, open up a terminal session, paste it in and press enter:

rm ~/bin/cfu ; wget -nc http://paste.opensuse.org/view/download/72458191 -O ~/bin/cfu ; chmod +x ~/bin/cfu

To use cfu, open a terminal session and type in:

cfu &lt;OR&gt; cfu -h

If the cpufrequtils package is not installed, you will be prompted to install it. In order to change your governor or CPU speed, you must supply the root user password. Same goes for installing the cpufrequtils package if it is missing. As always, I would love to hear about any comments or problems you might have using cfu.

Thank You,

Compare dates with Twig

January 12th, 2012 | admin

Here is a trick to compare two dates in Twig. Convert them as string with the date filter, with first the year, then the month and finally the day:

myDate|date('Y-m-d')

Then, you can compare strings because the chronological order is the same than the lexicographical order:

{% if date1|date('Y-m-d') > date2|date('Y-m-d') %}
    {# ... #}
{% endif %}

Tip. If you want to get the current date, you can give the string now to the date filter:

{% if "now"|date('Y-m-d') > date2|date('Y-m-d') %}
    {# ... #}
{% endif %}

Symfony2 Coding Standards

January 12th, 2012 | admin

Remember that the main advantage of standards is that every piece of code looks and feels familiar, it’s not about this or that being more readable.

Since a picture – or some code – is worth a thousand words, here’s a short example containing most features described below:

<!--?php 

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com-->
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Acme;

class Foo
{
    const SOME_CONST = 42;

    private $foo;

    /**
     * @param string $dummy Some argument description
     */
    public function __construct($dummy)
    {
        $this-&gt;foo = $this-&gt;transform($dummy);
    }

    /**
     * @param string $dummy Some argument description
     * @return string|null Transformed input
     */
    private function transform($dummy)
    {
        if (true === $dummy) {
            return;
        }
        if ('string' === $dummy) {
            $dummy = substr($dummy, 0, 5);
        }

        return $dummy;
    }
}

Structure

  • Never use short tags ( closing tag;
  • Indentation is done by steps of four spaces (tabs are never allowed);
  • Use the linefeed character (0x0A) to end lines;
  • Add a single space after each comma delimiter;
  • Don’t put spaces after an opening parenthesis and before a closing one;
  • Add a single space around operators (==, &&, …);
  • Add a single space before the opening parenthesis of a control keyword (if, else, for, while, …);
  • Add a blank line before return statements, unless the return is alone inside a statement-group (like an if statement);
  • Don’t add trailing spaces at the end of lines;
  • Use braces to indicate control structure body regardless of the number of statements it contains;
  • Put braces on their own line for classes, methods, and functions declaration;
  • Separate the conditional statements (if, else, …) and the opening brace with a single space and no blank line;
  • Declare visibility explicitly for class, methods, and properties (usage of var is prohibited);
  • Use lowercase PHP native typed constants: false, true, and null. The same goes for array();
  • Use uppercase strings for constants with words separated with underscores;
  • Define one class per file;
  • Declare class properties before methods;
  • Declare public methods first, then protected ones and finally private ones.

Naming Conventions

        • Use camelCase, not underscores, for variable, function and method names;
        • Use underscores for option, argument, parameter names;
        • Use namespaces for all classes;
        • Suffix interfaces with Interface;
        • Use alphanumeric characters and underscores for file names;
        • Don’t forget to look at the more verbose Conventions document for more subjective naming considerations.

Documentation

      • Add PHPDoc blocks for all classes, methods, and functions;
      • Omit the @return tag if the method does not return anything;
      • The @package and @subpackage annotations are not used.

Put braces on their own line for classes, methods, and functions declaration;

Unit testing for Symfony2 repositories with PHPUnit

January 12th, 2012 | admin

Here is the workflow I have to add a new function in an entity repository. Let’s say I have a blog and I want to get the most seen posts by counting the visits for each post. Here is the workflow I have:

Write the functions structure in the repository
Write the test structure test class
Write the DQL query with the console
Write the test in the test class
Write the query in the repository

1
The usual way to do add a query in a repository to add a new function that query the database and return the results:

namespace Acme\BlogBundle\Repository;
use Doctrine\ORM\EntityRepository;

class PostRepository extends EntityRepository {
    public function getMostSeen() {
        // query database and return results
    }
}

But this is hard to debug. I prefer to have for each query, two functions: one that build the query (that can easily be tested and debugged) and another one that execute that query and return result:

namespace Acme\BlogBundle\Repository;
use Doctrine\ORM\EntityRepository;

class PostRepository extends EntityRepository {
    public function qbMostSeen() {
        return $this->createQueryBuilder('p')
                    -> // ...
    }

    public function getMostSeen() {
        return $this->qbMostSeen()
                    ->getQuery()
                    ->getResult();
    }
}

2
The test class will be in the Tests directory of the bundle:

namespace Acme\BlogBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class PostRespositoryTest extends WebTestCase {
    // ...
}

But we want to be able to instantiate PostRepository and for that we need the Entity Manager and a kernel (that we don’t have by default). So let’s add setUp() that will be executed before the tests:

namespace Acme\BlogBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class PostRespositoryTest extends WebTestCase {
    private $repo;

    public function setUp() {
        $kernel = static::createKernel();
        $this->repo = $kernel->boot();
        $this->repo = $kernel->getContainer()
                             ->get('doctrine.orm.entity_manager')
                             ->getRepository('AcmeBlogBundle:Post');
    }
}

We add our tests:
on the query itself: here we compare the query DQL to the DQL we are going to write
on the results: here we check that we have some results

public function testMostSeen()
{
    $this->assertEquals(
        $this->repo->qbMostSeen()->getDql(),
        "..." // the DQL query
    );

    $this->assertNotEquals(0, count($this->repo->getMostSeen()));
}

You can add your tests on either the query or the results.
3
Write the DQL. Let’s write the DQL step by step testing each step with the console. Here, we get all the posts:

app/console doctrine:query:dql --max-result=5 "SELECT p.title FROM Acme\BlogBundle\Entity\Post p"

then we add one by one parts of our query, testing on our database to check the result every time. A left join to get all the visits:

SELECT p.title, v.id
FROM Acme\BlogBundle\Entity\Post p
LEFT JOIN p.visits v

then we add the visit count:

SELECT p.title, COUNT(v) AS visit_count
FROM Acme\BlogBundle\Entity\Post p
LEFT JOIN p.visits v
GROUP BY p.title

and we order by visit count:

SELECT p.title, COUNT(v) AS visit_count
FROM Acme\BlogBundle\Entity\Post p
LEFT JOIN p.visits v
GROUP BY p.title
ORDER BY visit_count DESC

Now that we are happy with the query, we can finish to write our tests.
4
Just insert the DQL in the test:

$this->assertEquals(
    $this->repo->qbMostSeen()->getDql(),
    "SELECT p.title, COUNT(v) AS visit_count FROM Acme\BlogBundle\Entity\Post p LEFT JOIN p.visits v GROUP BY p.title ORDER BY visit_count DESC"
);

5
Finally, write the query until PHPUnit is green!

namespace Acme\BlogBundle\Repository;
use Doctrine\ORM\EntityRepository;

class PostRepository extends EntityRepository {
    public function qbMostSeen() {
        return $this->createQueryBuilder('p')
                    ->select('p.title', 'COUNT(v) AS visit_counts')
                    ->leftJoin('p.visits', 'v')
                    ->orderBy('visit_counts', 'DESC');
    }

    public function getMostSeen() {
        return $this->qbMostSeen()
                    ->getQuery()
                    ->getResult();
    }
}


Pro tip

You might want to add the alias dql to your shell environment (.bash_profile, .zsh/zshaliases or whatever):

alias dql="app/console doctrine:query:dql"

so you can just run in your shell:

dql "SELECT p.title FROM Acme\BlogBundle\Entity\Post p"

Feel free to ask questions right here

Thanks to the origin author here.

Learn more about Unit Test for Symfony2

January 12th, 2012 | admin

First of all, install PHPUnit:


$ pear channel-discover pear.phpunit.de
$ pear channel-discover components.ez.no
$ pear channel-discover pear.symfony-project.com
$ pear install phpunit/PHPUnit

Then you can start to use PHP Unit like:


$phpunit -c app/

If you want to get report on HTML format, add parameter:


$ phpunit -c app/ --coverage-html=cov/

Not everybody has xdebug installed, maybe you will meet some problems like:

The Xdebug extension is not loaded. No code coverage will be generated.

That means you need to install xdebug for your PHP5. If you are using OpenSuse, it has a PHP Extensions repository, you can find more details from the following site:


http://download.opensuse.org/repositories/

and

http://download.opensuse.org/repositories/server:/php:/extensions/openSUSE_12.1/server:php:extensions.repo

You just need to install it simply as:

$sudo zypper ar  http://download.opensuse.org/repositories/server:/php:/extensions/openSUSE_12.1/server:php:extensions.repo

$sudo zypper install php5-xdebug

Now you fix the problem.

Start

OK, Let’s start to mark some tips about unit test for Symfony2.

First, a simple unit test:

// src/Acme/DemoBundle/Tests/Utility/CalculatorTest.php
namespace Acme\DemoBundle\Tests\Utility;

use Acme\DemoBundle\Utility\Calculator;

class CalculatorTest extends \PHPUnit_Framework_TestCase
{
public function testAdd()
{
$calc = new Calculator();
$result = $calc-&gt;add(30, 12);

// assert that our calculator added the numbers correctly!
$this-&gt;assertEquals(42, $result);
}
}

You can run unit test via:

# run all tests in the Utility directory
$ phpunit -c app src/Acme/DemoBundle/Tests/Utility/

# run tests for the Calculator class
$ phpunit -c app src/Acme/DemoBundle/Tests/Utility/CalculatorTest.php

# run all tests for the entire Bundle
$ phpunit -c app src/Acme/DemoBundle/

What about a functional unit test?

// src/Acme/DemoBundle/Tests/Controller/DemoControllerTest.php
namespace Acme\DemoBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DemoControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();

$crawler = $client-&gt;request('GET', '/demo/hello/Fabien');

$this-&gt;assertTrue($crawler-&gt;filter('html:contains("Hello Fabien")')-&gt;count() &gt; 0);
}
}

Something more about links:

$link = $crawler-&gt;filter('a:contains("Greet")')-&gt;eq(1)-&gt;link();

$crawler = $client-&gt;click($link);

And form:


$form = $crawler-&gt;selectButton('submit')-&gt;form();

// set some values
$form['name'] = 'Lucas';
$form['form_name[subject]'] = 'Hey there!';

// submit the form
$crawler = $client-&gt;submit($form);

Now that you can easily navigate through an application, use assertions to test that it actually does what you expect it to. Use the Crawler to make assertions on the DOM:

// Assert that the response matches a given CSS selector.
$this-&gt;assertTrue($crawler-&gt;filter('h1')-&gt;count() &gt; 0);

Or, test against the Response content directly if you just want to assert that the content contains some text, or if the Response is not an XML/HTML document:

$this-&gt;assertRegExp('/Hello Fabien/', $client-&gt;getResponse()-&gt;getContent());

The test Client simulates an HTTP client like a browser and makes requests into your Symfony2 application:

$crawler = $client-&gt;request('GET', '/hello/Fabien');

The request() method takes the HTTP method and a URL as arguments and returns a Crawler instance.

Use the Crawler to find DOM elements in the Response. These elements can then be used to click on links and submit forms:

$link = $crawler-&gt;selectLink('Go elsewhere...')-&gt;link();
$crawler = $client-&gt;click($link);

$form = $crawler-&gt;selectButton('validate')-&gt;form();
$crawler = $client-&gt;submit($form, array('name' =&gt; 'Fabien'));

The click() and submit() methods both return a Crawler object. These methods are the best way to browse your application as it takes care of a lot of things for you, like detecting the HTTP method from a form and giving you a nice API for uploading files.

The request method can also be used to simulate form submissions directly or perform more complex requests:

// Directly submit a form (but using the Crawler is easier!)
$client-&gt;request('POST', '/submit', array('name' =&gt; 'Fabien'));

// Form submission with a file upload
use Symfony\Component\HttpFoundation\File\UploadedFile;

$photo = new UploadedFile(
'/path/to/photo.jpg',
'photo.jpg',
'image/jpeg',
123
);
// or
$photo = array(
'tmp_name' =&gt; '/path/to/photo.jpg',
'name' =&gt; 'photo.jpg',
'type' =&gt; 'image/jpeg',
'size' =&gt; 123,
'error' =&gt; UPLOAD_ERR_OK
);
$client-&gt;request(
'POST',
'/submit',
array('name' =&gt; 'Fabien'),
array('photo' =&gt; $photo)
);

// Perform a DELETE requests, and pass HTTP headers
$client-&gt;request(
'DELETE',
'/post/12',
array(),
array(),
array('PHP_AUTH_USER' =&gt; 'username', 'PHP_AUTH_PW' =&gt; 'pa$$word')
);

Last but not least, you can force each request to be executed in its own PHP process to avoid any side-effects when working with several clients in the same script:

$client-&gt;insulate();

Browsing

The Client supports many operations that can be done in a real browser:


$client-&gt;back();
$client-&gt;forward();
$client-&gt;reload();

// Clears all cookies and the history
$client-&gt;restart();
Accessing Internal Objects

If you use the client to test your application, you might want to access the client’s internal objects:


$history = $client-&gt;getHistory();
$cookieJar = $client-&gt;getCookieJar();

You can also get the objects related to the latest request:


$request = $client-&gt;getRequest();
$response = $client-&gt;getResponse();
$crawler = $client-&gt;getCrawler();

If your requests are not insulated, you can also access the Container and the Kernel:

$container = $client-&gt;getContainer();
$kernel = $client-&gt;getKernel();

Accessing the Container

It’s highly recommended that a functional test only tests the Response. But under certain very rare circumstances, you might want to access some internal objects to write assertions. In such cases, you can access the dependency injection container:


$container = $client-&gt;getContainer();

Be warned that this does not work if you insulate the client or if you use an HTTP layer. For a list of services available in your application, use the container:debug console task.

 

Something more details you should refer to the official symfony book from here.

Enable PHP5.3 on hostgator

January 8th, 2012 | admin

Anywhere, .htaccess:

Action application/x-hg-php53 /cgi-sys/php53
AddHandler application/x-hg-php53 .php

Register Globals and other php settings

January 8th, 2012 | admin

To turn register globals off, you will need to change the settings in the php.ini file to:
register_globals = Off

Note the upper case letter O in Off.

Same steps apply to all other php settings. (e.g. magic_quotes, auto_append, allow_url_fopen)

It is recommended that you modify the existing default php.ini file in your home directory, if one exists. If not, we can upload a pre-made php.ini file for you, and you may change it as you need. Simply contact HostGator via live chat or phone.

Instead of having us create and setup the php.ini file for you, you can place your php.ini file in your Home Directory (/home/username/) yourself and then add this code to your primary .htaccess (/home/username/public_html/.htaccess). Be sure to replace “username” with your actual cPanel user name.

 <IfModule mod_suphp.c>
 suPHP_ConfigPath /home/username
 <Files php.ini>
 order allow,deny
 deny from all
 </Files>
 </IfModule>

Auto restart your lamp vps/server

January 4th, 2012 | admin

loadavg_restart_lamp.sh

#!/bin/sh

# crontab: */3 * * * * /usr/local/slackiss/restart_lamp/loadavg_restart_lamp.sh >> /var/log/restart_lamp.log

TOP_SYS_LOAD_NUM=5
SYS_LOAD_NUM=`uptime | awk '{print $(NF-2)}' | sed 's/,//'`  

MIN_RAM=64
FREE_RAM=`free -m| grep Mem|awk '{print $4}'`

echo $(date +"%y-%m-%d") `uptime`
if [ `echo "$TOP_SYS_LOAD_NUM < $SYS_LOAD_NUM"|bc` -eq 1 ] ||  [ `echo "$FREE_RAM < $MIN_RAM"|bc` -eq 1 ]
then
    echo "#0#" $(date +"%y-%m-%d %H:%M:%S") "pkill httpd" `ps -ef | grep httpd | wc -l`
    /usr/sbin/apachectl stop
    /etc/init.d/mysqld restart
    sleep 8
    pkill httpd
    sleep 8
    for i in 1 2 3
    do
        if [ `pgrep httpd | wc -l` -le 0 ]
        then
            /usr/sbin/apachectl start
            sleep 30
            echo "#1#" $(date +"%y-%m-%d %H:%M:%S") "start httpd" `ps -ef | grep httpd | wc -l`
        fi
    done
else
    if [ `pgrep httpd | wc -l` -le 0 ]
    then
        /usr/sbin/apachectl start
        sleep 30
        echo "#2#" $(date +"%y-%m-%d %H:%M:%S") "start httpd" `ps -ef | grep httpd | wc -l`
    fi
fi

How to read from stdin

December 23rd, 2011 | admin

Reading from stdin is not something familiar to many php coders, so here are a few ways to read in the puzzle you are given from stdin using the PHP CLI.

$s=fgets(STDIN);

Reads in a complete line of input as a string, complete with end of line character.

$c=fgetc(STDIN);

Reads in a single character.

Also worth looking at are fscanf(), fgetcsv(), fread()

To test your scripts you can use this command from a linux shell (other operating systems may differ)

php your_script.php < test.txt

Where test.txt is a plain text file containing your sample input.

If you want to join codegolf.com's challenages via PHP language, you need to know how to read from stdin via PHP CLI.

codegolf.com forum

CSS3 support for Internet Explorer 6, 7, and 8

December 23rd, 2011 | admin

What is it?

IE-CSS3 is a script to provide Internet Explorer support for some new styles available in the upcoming CSS3 standard.
How it works

If you’re viewing this page in Internet Explorer, some of the elements have been rebuilt by the script in Vector Markup Language (VML), an IE-specific vector drawing language. VML supports things that are missing from IE’s CSS implementation like rounded corners and blur effects.
How to use it

Just add CSS styles as you normally would, but include one new line:

.box {
-moz-border-radius: 15px; /* Firefox */
-webkit-border-radius: 15px; /* Safari and Chrome */
border-radius: 15px; /* Opera 10.5+, future browsers, and now also Internet Explorer 6+ using IE-CSS3 */

-moz-box-shadow: 10px 10px 20px #000; /* Firefox */
-webkit-box-shadow: 10px 10px 20px #000; /* Safari and Chrome */
box-shadow: 10px 10px 20px #000; /* Opera 10.5+, future browsers and IE6+ using IE-CSS3 */

behavior: url(ie-css3.htc); /* This lets IE know to call the script on all elements which get the ‘box’ class */
}

Issues and Workarounds

You would expect URLs in behavior: url(…) to be relative to the current directory as they are in a background-image: url(…) style for example, but instead Microsoft decided to ignore standards here and make them relative to the docroot instead. So behavior: url(ie-css3.htc) should work if ie-css3.htc is in the root directory of the site.

You will probably run into issues with z-index, especially if embedding one IE-CSS3 enabled element inside of another. There are two simple workarounds:

Set the z-index of the IE-CSS3 element to a number larger than its surrounding elements.
Make sure the IE-CSS3 element is positioned, such as with position: relative or position: absolute

Sometimes an IE-CSS3 element will show up at a slightly different position than the original, untouched element. There could be a few reasons for this:

You have broken tags somewhere in your markup, probably above the IE-CSS3 element.
You are experiencing misc IE6 and IE7 bugs. Try adding the styles zoom: 1 and/or position: relative to the IE-CSS3 element and its immediate parent. You could also try removing any margins on the IE-CSS3 element and/or its parent, use padding instead.

Styles and their status
Style What works What doesn’t work
border-radius

Setting a radius for all four corners
Element borders

Setting a radius for individual corners separately

box-shadow

Blur size
Offset

Any color other than #000

text-shadow

Blur size
Offset
Color

The shadow looks a little bit different than it does in FF/Safari/Chrome, I’m not sure why

Catch here.

Install Git on Centos 5x

December 20th, 2011 | admin

<code>$rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-4.noarch.rpm
</code>
<code>#yum install git</code>

Remove ibus, back to fcitx.

December 14th, 2011 | admin

$sudo zypper install fcitx fcitx-qt4 fcitx-devel fcitx-config-kde4
$sudo vim /etc/sysconfig/language

change :
INPUT_METHOD="fcitx"

Then,

export XMODIFIERS="@im=fcitx"
export GTK_IM_MODULE=fcitx
#export QT_IM_SWITCHER=imsw-multi #I do not know more about this line
export QT_IM_MODULE=fcitx

Reboot.

Enable mod_rewrite for OpenSuse 12.1

December 13th, 2011 | admin

I can not believe that mod_rewrite is not enabled by default on OpenSuse 12.1

First,

$sudo vim /etc/sysconfig/apache2

find the following line, it must look like:

APACHE_MODULES="suexec access actions alias auth auth_dbm autoindex cgi dir env expires
include log_config mime negotiation setenvif userdir ssl php5"

Add “rewrite” between “”.

Then,

$sudo /etc/init.d/apache2 restart

Now it works.

Repository for OpenSuse 12.1 in China

December 12th, 2011 | admin

http://mirrors.ustc.edu.cn/opensuse/distribution/12.1/repo/oss/

http://mirrors.ustc.edu.cn/opensuse/distribution/12.1/repo/non-oss/

http://mirrors.ustc.edu.cn/opensuse/update/12.1/

http://geeko.ioda.net/mirror/ati/openSUSE_12.1/

http://packman.inode.at/suse/12.1/

http://download.videolan.org/pub/vlc/SuSE/12.1/

#for Alipay, stardict and so on

http://download.opensuse.org/repositories/home:/hillwood/openSUSE_12.1/

http://download.opensuse.org/repositories/home:/swyear/openSUSE_12.1/

http://download.opensuse.org/repositories/home:/opensuse_zh/openSUSE_12.1/