Javascript: Chrome is a lot more restrict

Today I ran into an issue where simple javascript would stop running for no apparent reason.

I finally traced the problem down to where I was handling the response on a jquery.form callback:

 

                            if (response.message instanceof Array) {
                                var html = "";
                                for (var line in response.message) {
                                    html += "<li>" + line + "</li>";
                                }
                            } else {
                                html = response.message;
                            }
                            $("#errorMessages ul").html(html);

 

Since I was missing "var" in the for loop for response.message, chrome would thrown an error, and no more code would run on the iframe…

Noting that it was working yesterday, that drove me nuts for a while.

 

Kohana: Buffering output on view and rendering it before in the source code

Sometimes you need to hack the order the source code is going to be rendered in a view:

– You want an extra piece of CSS that only aplies to that view, so you think it's not worth creating a single CSS file and including in your mashed file

– You need the same as above for javascript

– Your mind has not completely grasped the way to organize code in MVC  🙂

 

 

Here's a way to do it:

 

in your view you add something like this:

<?php View::start_buffer('head_end'); ?>
<style>
    ::-moz-selection {
        background: #b3d4fc;
        text-shadow: none;
    }

</style>
<?php  View::end_buffer('head_end'); ?>

 

Then, by taking advantage of the wonderful cascading file system that Kohana gives you, you create a View.php class in your application folder that will need to extend the render() function (I'm just adding the relevant changes for this to work; you can have your own extra sauce):

 

class View extends Kohana_View
{
    static public $buffers = array();

    public static function start_buffer($buffer_name)
    {
        self::$buffers[$buffer_name] = '';
        ob_start();
    }

    public static function end_buffer($buffer_name)
    {
        self::$buffers[$buffer_name] = ob_get_clean();
    }

    public function render($file = NULL)
    {
        $rendered = parent::render($file);

        if (! empty(self::$buffers['head_end']))
        {
            $rendered = str_replace('</head>', self::$buffers['head_end'] . '</head>', $rendered);
        }
        return $rendered;
    }

}

 

The buffer names are completely arbitrary, you can make them any way to want.

I leave up to you to improve the way each buffer will be mapped to different locations in the source code.

Drop me a line with your changes

mysql: Dumping single database table and restoring

Sometimes you need to dump a single table from a mysql table and restore it somewhere else. Here's what you need:

 

1. Dump the table (compress it so it will take shorter to transfer over the network)

 

mysqldump -h <HOST> -u <USERNAME> -p <DATABASE> <TABLE> | gzip > <DUMP_FILENAME>.gz

 

HOST is the hostname or IP address of the mysql server

USERNAME is a user with access to the database and table

DATABASE and TABLE are self explanatory

DUMP_FILE is the name you want for the file containing the compressed dump

 

2. Transfer the file where you need it to be, with "cp" or "scp"

 

 

cp <DUMP_FILENAME>.hz  folder/new_name

scp <DUMP_FILENAME>.hz  user@machine:folder

 

 

Android: ANDROID_BIN which android unexpected error occured

$ ./create ~/projects/shoppingbuddy com.PortNumber53.ShoppingBuddy ShoppingBuddyAn unexpected error occurred: ANDROID_BIN="${ANDROID_BIN:=$( which android )}" exited with 1
Deleting project…

 

nano create

Change the line:

ANDROID_BIN="${ANDROID_BIN:=$( which android )}"

to be the absolute path:

ANDROID_BIN="/home/mauricio/adt-bundle-linux-x86_64-20130219/sdk/tools/android"

 

 

Raspberry Pi: installing a LAMP server

Let's put the Raspberry Pi to good use:

 

1. Install Mysql

sudo pacman -S mysql

2. Start your server

# systemctl start mysqld

3. Secure your mysql installation

# /usr/bin/mysql_secure_installation

——————-

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MySQL to secure it, we'll need the current
password for the root user.  If you've just installed MySQL, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):
OK, successfully used password, moving on…

Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.

Set root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
 … Success!

By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y
 … Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
 … Success!

By default, MySQL comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
 – Dropping test database…
 … Success!
 – Removing privileges on test database…
 … Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
 … Success!

Cleaning up…

All done!  If you've completed all of the above steps, your MySQL
installation should now be secure.

Thanks for using MySQL!

———————-

 

# nano /etc/mysql/my.cnf

 

[mysqld]

bind-address=127.0.0.1

 

 

Restart mysql

systemctl restart mysqld

 

 

================

Install PHP

 

pacman -S php php-apache libmcrypt libtool

 

nano /etc/php/php.ini

 

 

 

======================

 

nano /etc/locale.gen

enable:

en_US.UTF-8 UTF-8
en_US ISO-8859-1

 

save and generate your locales

# locale-gen

 

 

Install and Configure PostgreSQL

pacman -S postgresql

 

# mkdir -p /var/lib/postgres/data

# chown httpd:httpd -Rv /var/lib/postgres/

 

Configure Postgresql data dir

# su – postgres -c "initdb –locale en_US.UTF-8 -D '/var/lib/postgres/data'"

———————–

The files belonging to this database system will be owned by user "httpd".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

fixing permissions on existing directory /var/lib/postgres/data … ok
creating subdirectories … ok
selecting default max_connections … 100
selecting default shared_buffers … 24MB
creating configuration files … ok
creating template1 database in /var/lib/postgres/data/base/1 … ok
initializing pg_authid … ok
initializing dependencies … ok
creating system views … ok
loading system objects' descriptions … ok
creating collations … ok
creating conversions … ok
creating dictionaries … ok
setting privileges on built-in objects … ok
creating information schema … ok
loading PL/pgSQL server-side language … ok
vacuuming database template1 … ok
copying template1 to template0 … ok
copying template1 to postgres … ok

WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
–auth-local and –auth-host, the next time you run initdb.

Success. You can now start the database server using:

    postgres -D /var/lib/postgres/data
or
    pg_ctl -D /var/lib/postgres/data -l logfile start
 

——————————————

 

Enable the service

# systemctl enable postgresql

Start if you want to use it before rebooting

# systemctl start postgresql

 

Git branch in Mac OSX bash prompt

I tried using the same changes for my linux boxes on my macbook air and they didn't work, so I googled around and stumbled upon using this instead:

 

 

c_cyan=`tput setaf 6`
c_red=`tput setaf 1`
c_green=`tput setaf 2`
c_sgr0=`tput sgr0`
parse_git_branch (){
    if git rev-parse --git-dir >/dev/null 2>&1
    then
        gitver=$(git branch 2>/dev/null| sed -n '/^\*/s/^\* //p')
    else
        return 0
    fi
    echo -e $gitver
}
branch_color (){
    if git rev-parse --git-dir >/dev/null 2>&1
    then
        color=""
    if git diff --quiet 2>/dev/null >&2 
    then
        color="${c_green}"
    else
        color=${c_red}
    fi
    else
        return 0
    fi
    echo -ne $color
}

#Branch First
#PS1='[\[$(branch_color)\]$(parse_git_branch)\[${c_sgr0}\]] \u@\[${c_red}\]\w\[${c_sgr0}\]: '
#Branch Last
PS1=' \u@\[${c_red}\]\w\[${c_sgr0}\]: [\[$(branch_color)\]$(parse_git_branch)\[${c_sgr0}\]] '

 

original: http://asemanfar.com/Current-Git-Branch-in-Bash-Prompt

 

Kohana: core, adding submodules, customization

After cloning the repository, let's add the Kohana core, a few modules and customize the installation:

1. 

git submodule add git://github.com/kohana/core.git modules/system

git submodule add git://github.com/kohana/database.git modules/database

git submodule add git://github.com/kohana/cache.git modules/cache

git submodule add git://github.com/kohana/image.git modules/image

git submodule add git://github.com/kohana/pagination.git modules/pagination

 

2. Initialize the modules

 

$ git submodule init

 

$ git commit -m 'Added core kohana and initial submodules [cache,database,image,pagination]'
[master 1d5462d] Added core kohana and initial submodules [cache,database,image,pagination]
 6 files changed, 20 insertions(+)
 create mode 100644 .gitmodules
 create mode 160000 modules/cache
 create mode 160000 modules/database
 create mode 160000 modules/image
 create mode 160000 modules/pagination
 create mode 160000 modules/system
 
 
3. Push these changes
$ git pull origin master
From mt:~/domains/git.portnumber53.com/html/menospior.com
 * branch            master     -> FETCH_HEAD
Already up-to-date.
 
$ git push origin master
Counting objects: 5, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 663 bytes, done.
Total 4 (delta 0), reused 0 (delta 0)
To mt:~/domains/git.portnumber53.com/html/menospior.com.git
   8bce6b1..1d5462d  master -> master
 
 
We need some more files:
 
 

 

 

 

 

 

 

$ mkdir html
$ wget https://raw.github.com/kohana/kohana/3.2/master/index.php -O html/index.php
–2012-07-12 00:46:18–  https://raw.github.com/kohana/kohana/3.2/master/index.php
Resolving raw.github.com (raw.github.com)… 207.97.227.243
Connecting to raw.github.com (raw.github.com)|207.97.227.243|:443… connected.
HTTP request sent, awaiting response… 200 OK
Length: 3292 (3.2K) [text/plain]
Saving to: `html/index.php'
 
100%[=========================================================================>] 3,292       –.-K/s   in 0s
 
2012-07-12 00:46:19 (76.6 MB/s) – `html/index.php' saved [3292/3292]
 
$ wget https://raw.github.com/kohana/kohana/3.2/master/example.htaccess -O html/.htaccess
–2012-07-12 00:46:47–  https://raw.github.com/kohana/kohana/3.2/master/example.htaccess
Resolving raw.github.com (raw.github.com)… 207.97.227.243
Connecting to raw.github.com (raw.github.com)|207.97.227.243|:443… connected.
HTTP request sent, awaiting response… 200 OK
Length: 517 [text/plain]
Saving to: `html/.htaccess'
 
100%[=========================================================================>] 517         –.-K/s   in 0s
 
2012-07-12 00:46:48 (24.1 MB/s) – `html/.htaccess' saved [517/517]
 
$ mkdir -p modules/application
$ wget https://raw.github.com/kohana/kohana/3.2/master/application/bootstrap.php -O modules/application/bootstrap.php
–2012-07-12 00:47:32–  https://raw.github.com/kohana/kohana/3.2/master/application/bootstrap.php
Resolving raw.github.com (raw.github.com)… 207.97.227.243
Connecting to raw.github.com (raw.github.com)|207.97.227.243|:443… connected.
HTTP request sent, awaiting response… 200 OK
Length: 3612 (3.5K) [text/plain]
Saving to: `modules/application/bootstrap.php'
 
100%[=========================================================================>] 3,612       –.-K/s   in 0s
 
2012-07-12 00:47:33 (104 MB/s) – `modules/application/bootstrap.php' saved [3612/3612]
 
 
 
If you try accessing your site you should see an error:
———-

 

 

 

 

Warning: require(/bootstrap.php): failed to open stream: No such file or directory in /home/httpd/domains/menospior.dev/html/index.php on line 102

 

Fatal error: require(): Failed opening required '/bootstrap.php' (include_path='.:/php/library/php-redis:/usr/share/pear') in/home/httpd/domains/menospior.dev/html/index.php on line 102

 

 

 

———————
 
 
Let's adjust the environment:
 
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Chage a few settings:
html/index.php

$application = '../modules/application';

$modules = '../modules';

$system = '../modues/system';

 

Customize some kohana settings:

../modules/application/bootstrap.php

date_default_timezone_set('America/Los_Angeles');

 

Kohana::init(array(
'base_url'   => '/',
'index_file' => FALSE,
'cache_dir'  => DOCROOT.'../cache'
));
Kohana::$log->attach(new Log_File(DOCROOT.'../logs'));
 

 

 

 

 

 

 

 

 

Now create the logs folder

$ mkdir logs

 

 

At this point you should have a 404 error as there's no controller:

 

 

HTTP_Exception_404 [ 404 ]: The requested URL / was not found on this server.

SYSPATH/classes/kohana/request/client/internal.php [ 87 ]

82 
83 		try
84 		{
85 			if ( ! class_exists($prefix.$controller))
86 			{
87 				throw new HTTP_Exception_404('The requested URL :uri was not found on this server.',
88 													array(':uri' => $request->uri()));
89 			}
90 
91 			// Load the controller using reflection
92 			$class = new ReflectionClass($prefix.$controller);
  1. SYSPATH/classes/kohana/request/client.php [ 64 ] » Kohana_Request_Client_Internal->execute_request(arguments)

  2. SYSPATH/classes/kohana/request.php [ 1138 ] » Kohana_Request_Client->execute(arguments)

  3. DOCROOT/index.php [ 109 ] » Kohana_Request->execute()

Environment

 

 

 

This is optional:

 

$ wget https://raw.github.com/kohana/kohana/3.2/master/install.php -O html/install.php
–2012-07-12 01:43:59–  https://raw.github.com/kohana/kohana/3.2/master/install.php
Resolving raw.github.com (raw.github.com)… 207.97.227.243
Connecting to raw.github.com (raw.github.com)|207.97.227.243|:443… connected.
HTTP request sent, awaiting response… 200 OK
Length: 8411 (8.2K) [text/plain]
Saving to: `html/install.php'
 
100%[=========================================================================>] 8,411       –.-K/s   in 0s
 
2012-07-12 01:44:00 (19.5 MB/s) – `html/install.php' saved [8411/8411]
 
the step above download the install.php file that can be used to test your environment. There are a few things wrong in the script, but it can tell you if you env has all the bells and whisles to use Kohana
 
 

 

 

Problems you may want to fix:

The iconv extension is not loaded.

Uncomment the line

extension=iconv.so

in your php.ini file and restart Apache

 

Kohana requires mcrypt for the Encrypt class.

Uncomment the line

extension=mcrypt.so

in your php.ini file and restart Apache

 

Kohana requires GD v2 for the Image class.

Uncomment the line

extension=gd.so

in your php.ini file and restart Apache

 

Kohana can use the http extension for the Request_Client_External class.

Install the pecl_http extension

 

# pacman -Sy php-pear autoconf
# pecl install pecl_http
/usr/lib/gcc/arm-unknown-linux-gnueabi/4.7.1/cc1: error while loading shared libraries: libppl.so.12: cannot open shared object file: No such file or directory
pecl/pecl_http can optionally use PHP extension "iconv"
downloading pecl_http-1.7.4.tgz …
Starting to download pecl_http-1.7.4.tgz (174,503 bytes)
……………………………….done: 174,503 bytes
71 source files, building
running: phpize
Configuring for:
PHP Api Version:         20100412
Zend Module Api No:      20100525
Zend Extension Api No:   220100525
 

/usr/lib/php/modules/http.so

You should add "extension=http.so" to php.ini

 

 

Fix install.php folder checks:

 

<tr>
<th>Cache Directory</th>
<?php if (is_dir(APPPATH) AND is_dir(DOCROOT.'../cache') AND is_writable(DOCROOT.'../cache')): ?>
<td class="pass"><?php echo DOCROOT.'../cache' ?></td>
<?php else: $failed = TRUE ?>
<td class="fail">The <code><?php echo DOCROOT.'../cache' ?></code> directory is not writable.</td>
<?php endif ?>
</tr>
<tr>
<th>Logs Directory</th>
<?php if (is_dir(APPPATH) AND is_dir(DOCROOT.'../logs') AND is_writable(DOCROOT.'../logs')): ?>
<td class="pass"><?php echo DOCROOT.'../logs' ?></td>
<?php else: $failed = TRUE ?>
<td class="fail">The <code><?php DOCROOT.'../logs' ?></code> directory is not writable.</td>
<?php endif ?>
</tr>
 
 

 

Facebook: Creating your first APP in PHP

So you finally decided you want to create a Facebook app to make your million dollar idea pay off a million dollars! Great!

 

Cutting to the chase:

 

1. Install the Developers App so you can get started creating apps on Facebook.

https://developers.facebook.com/

and click Allow

2. Create and Configure your App

Click on Apps and then "Create New App"

Configure your App

 

3. Download the SDK

Get the PHP SDK here

https://developers.facebook.com/docs/reference/php/

Extract the contents to a /facebook/ folder in your public html folder on your server

 

 

4. Create your minimum App (Who needs a Hello World?)

TO-DO

5. Enhance your App

TO-DO

6. Make it work outside Facebook

TO-DO

7. Make a mobile version

TO-DO

8. Make millions

TO-DO

9. Send me stuff 🙂

 

 

Intranet: Setup a DNSCACHE for your network using DJBDNS

On this tutorial you will learn how to using DJBDNS to setup a DNS cache to help speed up queries for your local network.

 

I like using Debian, so that is the distribution I'll be using for most of my tutorials. Current version as of this, is Squeeze.

 

0.Install build-essential and daemontools and ucspi-tcp so we can get started:

# apt-get install build-essential ucspi-tcp daemontools daemontools-run

 

You can do everything as root, to make your life easier…. or just do the make commands (if you're paranoid):

 

1. Download and untar DjbDNS

# wget -q http://cr.yp.to/djbdns/djbdns-1.05.tar.gz
# tar -zxvvf djbdns-1.05.tar.gz

 

2. Add users for DjbDNS to /etc/passwd

# echo 'dnscache:*:54321:54321:dnscache:/dev/null:/dev/null' >> /etc/passwd
# echo 'dnslog:*:54322:54322:dnslog:/dev/null:/dev/null' >> /etc/passwd

 

3. Compile DjbDNS nameserver

# cd djbdns-1.05
# echo gcc -O2 -include /usr/include/errno.h > conf-cc

 

4. Compile it

# make

 

5. Install the binaries

# make setup check

 

 

6. Copy the list of IP addresses of the global DNS root servers in /etc/

# cp -rpf dnsroots.global /etc/

 

7.  Configure dnscache:

# ./dnscache-conf dnscache dnslog /etc/dnscache <IP address of this box>

 

8. Allow your network to use the DNS cache

# cd /etc/dnscache/root/ip
# touch 10.0.0

* This assumes you're using a network class A, like 10.0.0.0/24

 

9. Start the daemon

# ln -sf /etc/dnscache /etc/service/dnscache
# ps ax|grep -i readproc
 1071 ?        S      0:00 readproctitle service errors: ................................................................................................................................................................................................................................................................................................................................................................................................................
 1206 pts/1    S+     0:00 grep -i readproc
You can later check it's running using:
 
svstat /etc/service/dnscache
 
10. As root, add:
 
nameserver <IP address of this box>

 

to /etc/resolv.conf

 
 
11. Do a quick test:
(
If you're using ArchLinux, use:
pacman -Syu dnsutils
to install "host"
)
# host portnumber53.com <eth0 IP address>
Using domain server:
Name: localhost
Address: 127.0.0.1#53
Aliases:

portnumber53.com has address 205.186.185.42
portnumber53.com mail is handled by 20 ALT2.ASPMX.L.GOOGLE.com.
portnumber53.com mail is handled by 30 ASPMX2.GOOGLEMAIL.com.
portnumber53.com mail is handled by 20 ALT1.ASPMX.L.GOOGLE.com.
portnumber53.com mail is handled by 30 ASPMX3.GOOGLEMAIL.com.
portnumber53.com mail is handled by 30 ASPMX4.GOOGLEMAIL.com.
portnumber53.com mail is handled by 30 ASPMX5.GOOGLEMAIL.com.
portnumber53.com mail is handled by 10 ASPMX.L.GOOGLE.com.
 
 
12. Report success:
# ( echo 'First M. Last'; cat `cat SYSDEPS` ) \
# | mail djb-sysdeps@cr.yp.to

 

 

 

 

 

 

Don't forget to replace First M. Last with your full name.
 
 

Later on you can monitor what's going under the hood by using:

# tail -f /etc/service/dnscache/log/main/current

 

If you installed following ArchLinux AUR packages, this may work better:

 

#tail -f /etc/dnscache/log/main/current

 

 

Git: Prepare your repository – step 1

 

Here I’ll explain how you can create a new repository for your projects and use GIT for your version control needs.
 
 
For this, I’ll assume everything is already installed (git and stuff). This also assumes you’re using an Operating System and not the Vermont thing.
 
Replace “example.com” with your own domain.
 
1. Create a base repository
 
$ mkdir example.com && cd example.com

$ git init
 
 
2. Create a standard .gitignore file
 
$ nano .gitignore
 
—————————-
cgi-bin/*

upload/

.idea/*

# Compiled source #

###################

*.com

*.class

*.dll

*.exe

*.o

*.so

# Packages #

############

# it's better to unpack these files and commit the raw source

# git has its own built in compression methods

*.7z

*.dmg

*.gz

*.iso

*.jar

*.rar

*.tar

*.zip

# Logs and databases #

######################

*.log

*.sql

*.sqlite

# OS generated files #

######################

.DS_Store*

ehthumbs.db

Icon?

Thumbs.db
—————————-
 
3. Add and commit the file to your local repository.
$ git add .gitignore

$ git commit -m "Added standard gitignore file"
 
4. Prepare your local repository for transportation:
$ cd ..

$ git clone --bare example.com example.com.git

$ touch example.com.git/git-daemon-export-ok
 
5. Copy it to your server
$ scp -r example.com.git SERVER:~/PATH_ON_THE_SERVER/example.com.git
 
6. Finish preparing your repository on the server:
 
$ ssh SERVER

$ cd ~/PATH_ON_THE_SERVER/example.com.git

$ git --bare update-server-info

$ cd hooks

$ mv post-update.sample post-update

$ chmod a+x post-update
 
From this point on, you should be able to clone your repository and start working.
 
Drop me a line if this does not work for you, and I'll be glad to try and help.
 

 

  • IGlr