Creating a child theme | Wordpress

If you make changes to a theme’s files, those changes are likely to be overwritten when you next update the theme. In order to prevent that from happening, we create a child theme in which you can make create copies of a theme’s files and tweak them, without fear of it being overwritten by any future theme updates.

All you need to do is create one folder, and stylesheet and functions file. And make sure that you have FTP access, before you continue reading this documentation.

Log into your website using your favorite FTP client, such as FileZilla, and navigate to wp-content/themes/ directory. This is the directory where all your themes are living a happy life.

Now, you need to create a new folder for your child theme. You can name it anything. For this example, we will be creating a child theme of Zerif Lite, so we will name it zerif-lite-child.

Once you have created your folder, you need to create a style.css file inside that folder. Your stylesheet will consist some vital information inside it, so paste the following in it using your favorite text editor:

/*
   Theme Name: Zerif Pro Child
   Theme URI: https://www.themeisle.com/ 
   Description: This is a custom child theme I have created.
   Author: Chuck Norris Author
   URI: https://www.themeisle.com/ 
   Template: zerif-pro
   Version: 0.1 
*/

Now, we need to load the stylesheet of the parent theme. Create a file named functions.php in the child theme folder, edit it, and paste the following:

<?php
add_action( 'wp_enqueue_scripts', 'child_enqueue_styles',99);
function child_enqueue_styles() {
    $parent_style = 'parent-style';
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
  wp_enqueue_style( 'child-style',get_stylesheet_directory_uri() . '/custom.css', array( $parent_style ));
}
if ( get_stylesheet() !== get_template() ) {
    add_filter( 'pre_update_option_theme_mods_' . get_stylesheet(), function ( $value, $old_value ) {
         update_option( 'theme_mods_' . get_template(), $value );
         return $old_value; // prevent update to child theme mods
    }, 10, 2 );
    add_filter( 'pre_option_theme_mods_' . get_stylesheet(), function ( $default ) {
        return get_option( 'theme_mods_' . get_template(), $default );
    } );
}
?>

Now, Create a file named custom.css in the child theme folder, and add your CSS code there. It make easier to handle CSS code in separate file.

That's all. You just to save your progress and that's it.

Recovery after change in IP or hostname | Wordpress

If the wordpress site/blog is inaccessible following a change in the IP or the hostname, use the following option to reset the siteurl in the database manually.

mysql> update wp_options set option_value='<new ip/hostname>' where option_name='siteurl';

This might not always be the case, as you might not always have direct access to the database on the web host. Refer to Changing The Site URL to get this done in various restricted environments.

There might be a case where the site/blog is up and running but you end up being unable to access the admin portal (wp-admin). Add the following lines to your wp-config.php to regain access.

Note: Both settings should include the http:// part and should not have a slash "/" at the end.

define('WP_HOME','<new ip/hostname>');
define('WP_SITEURL','<new ip/hostname>');

Optimal file permissions | Wordpress

When setting up a Wordpress site/blog, the web server may need access to the files. The following configuration for the file permissions could be optimal and resolve most of the issues related to file permissions.

One of the errors due to incorrect file permissions is show below. Wordpress doesn't have enough privileges to perform a plugin install.

sudo chown www-data:www-data -R *         # Let apache be owner
sudo find . -type d -exec chmod 755 {} \; # Set dir permissions rwxr-xr-x
sudo find . -type f -exec chmod 644 {} \; # Set file permissions rw-r--r--

After the setup it is better to tighten the access rights, according to Hardening WordPress all files except for wp-content should be writable by your user account only. wp-content must be writable by www-data too.

Using node.js to run a simple web server

You can use Connect and ServeStatic with Node.js for this:
  1. Install connect and serve-static with NPM
    $ npm install connect serve-static
  2. Create server.js file with this content:
    var connect = require('connect');
    var serveStatic = require('serve-static');
    connect().use(serveStatic(__dirname)).listen(8080);
  3. Run with Node.js
    $ node server.js
You can now go to http://localhost:8080/yourfile.html

Add power to the Mac's built-in Finder | XtraFinder

XtraFinder is a plugin for Mac OS's built in Finder. It has most of the features one would miss in the default options of Finder.

Some of the interesting features are:
  • Tabs & Dual Panel.
  • Arrange folders on top.
  • Cut & Paste. Copy queue.
  • Global hotkeys.
  • "Copy Path", "Show Hidden Items", "Hide Desktop", "Refresh", "New File", "Copy to", "Move to", "New Terminal Here", "Make Symbolic Link", "Contents", "Attributes", … .
  • Legacy label for OSX 10.9 & 10.10. Light text on dark background. Transparent window.
  • Colorful icons in Sidebar.
  • Size of selected items in Status Bar.
  • Automatically adjust width of columns.
  • Press Enter or Return to open selection.
  • Display folder item count in List view.
  • Middle-click to open folder in new window or new tab.

Time sync with NTP server

A simple time lag on a remote server could be the root-cause of many issues ranging from missing logs to data inconsistencies. The following technique can help in syncing the server with the NTP server to reset the lag.

Check for NTP server that is referenced currently
root~# ntpq -p
remote refid st t when poll reach delay offset jitter
===========================================================
pool.ntp.org .INIT. 16 u - 1024 0 0.000 0.000 0.000
Compare current date on local machine vs NTP server
root~# rdate -n -p pool.ntp.org
Mon Jun 16 18:44:46 UTC 2014
root~# date
Mon Jun 16 18:25:03 UTC 2014
Update local machine Time (remove “-p” from rdate command)
root~# rdate -n pool.ntp.org
Mon Jun 16 18:45:35 UTC 2014
root~# date
Mon Jun 16 18:45:37 UTC 2014

MySQL | Backup and restoration using mysqldump

The mysqldump client is a utility that dumps one or more MySQL database for backup or transfer to another SQL server. It can be used to dump one table at a time as well. All that is required is connectivity to the database server and access privileges to the database.

Backup a single table.
mysqldump -u username -p db_name table_name > table_name_dump.sql
Backup multiple tables.
mysqldump -u username -p db_name table1_name table2_name > dump.sql
Restore the single table back to the database.
mysql -u username -p db_name < /path/to/table_name_dump.sql
Backup an entire database. The command can be altered to backup multiple databases just like tables.
mysqldump -u username -p db_name > db_backup.sql
Backup all the databases in the server.
mysqldump -u username -p --all-databases > all_db_backup.sql
Restore the database.
mysqldump -u username -p < db_backup.sql

VirtualBox Guest Additions on Linux | Missing kernel headers

If you think the VirtualBox Guest Additions has not installed correctly/completely, do the following:
sudo /etc/init.d/vboxadd setup
If there are any error messages, please refer to the following file for hints.
/var/log/vboxadd-install.log
If there are errors similar to the one shown below, read further for the solution.
/tmp/vbox.0/Makefile.include.header:97: *** Error: unable to find the sources of your current Linux kernel. Specify KERN_DIR=<directory> and run Make again.  Stop.
Install the headers for the current running kernel.
sudo apt-get install linux-headers-$(uname -r)
Re-install the Guest Additions.
sudo /etc/init.d/vboxadd setup
Try if things are working fine. Say mount a shared folder.
sudo mount -t vboxsf share /home/jack/host
The above scenario was faced and resolved on Debian Squeeze. The commands should hold good for any Linux distro.

Log methods | Android

  • Log.e: This is for when bad stuff happens. Use this tag in places like inside a catch statment. You know and error has occurred and therefore you're logging an error.
  • Log.w: Use this when you suspect something shady is going on. You may not be completely in full on error mode, but maybe you recovered from some unexpected behavior. Basically, use this to log stuff you didn't expect to happen but isn't necessarily an error. Kind of like a "hey, this happened, and it's weird, we should look into it."
  • Log.i: Use this to post useful information to the log. For example: that you have successfully connected to a server. Basically use it to report successes.
  • Log.d: Use this for debugging purposes. If you want to print out a bunch of messages so you can log the exact flow of your program, use this. If you want to keep a log of variable values, use this.
  • Log.v: Use this when you want to go absolutely nuts with your logging. If for some reason you've decided to log every little thing in a particular part of your app, use the Log.v tag.
And as a bonus...
  • Log.wtf: Use this when stuff goes absolutely, horribly, holy-crap wrong. You know those catch blocks where you're catching errors that you never should get...yea, if you wanna log them use Log.wtf

Function atoi | An implementation

According to C++ Reference the function atoi is described as follows:
int atoi(const char* str);
  • The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value. 
  • The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
  • If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned. 

The following is an attempt to implement the function in C.
int stringToInt(const char* input) { // C implementation
    int ans = 0;
    int sign = 1;

    if (!input) {
        return ans;
    }

    //Check for sign at the beginning
    if ( (*input == '-' && (sign = -1) ) || (*input == '+') ) {
        input++;
    }

    while (*input) {
        //If the character is a digit, use it
        if (*input >= '0' && *input <= '9') {
            ans = ans * 10 + (*input - '0') ;
        } else { // Return once a non-digit charcter is encountered
            return ans * sign;
        }
        input++;
    }
    return ans * sign;
}
A simpler implementation (though costlier) can be done in C++.
int stringToInt(std::string& input) { //C++ implementation
    int ans = 0;

    if (!input) {
        return ans;
    }

    //store the string as an input string stream
    std::istringstream iss(input);

    //if the conversion fails or does not reach eof, the conversion is not a success
    if ( (iss >> std::ws >> ans).fail() || !(iss >> std::ws).eof() ) {
        //Throwing a custom exception
        StringToIntException e("Illegal characters in string input");
        throw e;
    } else {
        return ans;
    }
}

IP-SM-Gateway | Transport & Service level Interworking

Transport Level Interworking Service Level Interworking
When the original SMS content is brought to the IMS side, the IP-SM-GW chooses to apply this method to forward a MAP message to the IMS domain. When receiving a Short Message from a legacy domain, the IP-SM-GW translates the Short Message payload to a plain/text payload of an Instant Message.
This method can be applied only when the recipient UE is capable of SMS support (e.g. Smartphone). This method is applied when the recipient UE does not support native SMS (e.g. VoIP based IM client).
In this case the binary payload of the received MAP message is just uploaded into a SIP message. This message will now use the SIP MESSAGE method and his payload will be signaled as ’application/vnd.3gpp.sms’

GDB | Core file analysis

All that is required to use the GNU Debugger (gdb) is the core file and the binary/executable file (with debugging symbols included) that actually caused the core. If the same version is not available, the closest one can be used.

Run the gdb using the following command:
$ gdb <binary_file_path> <core_file_path>
On the gdb prompt, use the following commands for further debugging:
$ bt                    
(short for backtrace, to get a stack trace and each frame's number from the time of the crash)

$ where
(an alternative to backtrace)

$ frame <stack_frame_number>
(replace number with the corresponding number in the stack trace to select a particular stack frame)

$ list
(to see code around that function)

$ info locals 
(to see the local variables)

$ print <name_of_variable> 
(replacing "name_of_variable" with a variable name, to see its value)

$ help
(to see additional commands)

MySQL | Table and Database sizes

The SQL script below can list out the entire databases size
SELECT table_schema "Data Base Name", SUM( data_length + index_length) / 1024 / 1024 "Data Base Size in MB" FROM information_schema.TABLES GROUP BY table_schema ;
Locating The MySQL Stored Data in the file-system can also help
/var/lib/mysql$ ls -lh

Building Google libphonenumber on Linux

I’m using CentOS 6.0 and following are the steps I’m using to build libphonenumber for C++.

1. Check out libphonenumber

$ svn checkout http://libphonenumber.googlecode.com/svn/trunk/ libphonenumber-read-only

2. Build and install cmake. (This is because libphonenumber requires cmake v2.8 or above, but the version comes with OS is 2.6.4)
Go to http://www.cmake.org and download the latest cmake source file, extract, and then build it.

$ tar zxvf cmake-2.8.7.tar.gz
$ cd cmake-2.8.7
$ ./configure
$ make
$ sudo make install

3. Build and install Protocol Buffers:
Go to http://code.google.com/p/protobuf/ and download source file, extract and build it.

$ tar jxvf protobuf-2.4.1.tar.bz2
$ cd protobuf-2.4.1
$ ./configure
$ make
$ sudo make install

4. Google Test (http://code.google.com/p/googletest/)
This is a little tricky to build and install. Finally, the steps I take is:

$ unzip gtest-1.6.0.zip
$ mkdir mybuild
$ cd mybuild
$ cmake -Dgtest_build_tests=ON ${GTEST_DIR}
$ cmake -G"Unix Makefiles" ..
$ make
$ sudo cp -r ../include/gtest /usr/local/include
$ sudo cp lib*.a /usr/local/lib

5. RE2 (http://code.google.com/p/re2/)
Check out the code and build it.

$ hg clone https://re2.googlecode.com/hg re2
$ cd re2
$ make test
$ sudo make install
$ sudo make testinstall

6. ICU (http://site.icu-project.org/download)
I used the prebuild file for RHEL6-32, and it seems to work well.

$ icu4c-4_8_1_1-RHEL6-i386.tgz

7. Install boost and boost-devel by yum

$ sudo yum install boost
$ sudo yum install boost-devel

8. Build libphonenumber C++:

$ cd libphonenumber/cpp
$ mkdir build
$ cd build
$ cmake ..
$ make

Finally, the libphonenumber.so will be appear in the build directory.

MySQL | Events

Events in MySQL 

How about having a database-only crontab? What if there is a requirement to run certain DB operations on a predetermined schedule? MySQL events (added since version 5.1.6) is the solution.

Events vs. Triggers

Sure, triggers can be used to schedule DB operations. However, they are limited in the sense that, a trigger can be fired only before or after certain operations. e.g., before or after an INSERT. On the other hand, events offer time based and periodic scheduling which is independent of the inherent DB operations.
 
Getting Started  

Before getting your hands dirty, we need to make sure that MySQL events is enabled. In other words, the event_scheduler should be running. This is required as it comes disabled by default.

Before directly enabling the MySQL events it is good to check the current status. One of the following two queries would do the job.

mysql> SHOW VARIABLES LIKE "EVENT_SCHEDULER";
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| event_scheduler | OFF   |
+-----------------+-------+
1 row in set (0.00 sec)

If above query returns the value ON, you are good to go. Otherwise, you have to enable it manually as shown below.

mysql> SET GLOBAL event_scheduler=ON;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW VARIABLES LIKE "EVENT_SCHEDULER";
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| event_scheduler | ON    |
+-----------------+-------+
1 row in set (0.00 sec)

Another query to check if events are enabled is

mysql> SHOW PROCESSLIST; +------+-----------------+----------------+------+---------+------+------------------------+------------------+ | Id   | User            | Host           | db   | Command | Time | State                  | Info             | +------+-----------------+----------------+------+---------+------+------------------------+------------------+ |    2 | usr             | host.net:38456 | db12 | Sleep   | 1357 |                        | NULL             | | 1365 | usr             | localhost      | db12 | Query   |    0 | NULL                   | SHOW PROCESSLIST | | 1366 | event_scheduler | localhost      | NULL | Daemon  |   18 | Waiting on empty queue | NULL             | +------+-----------------+----------------+------+---------+------+------------------------+------------------+ 3 rows in set (0.00 sec)

We can explicitly see the event_scheduler running from the above output. Another option to ensure the scheduler starts when MySQL is launched is with the command-line option --event-scheduler=ON 

Setting event_scheduler=ON in your MySQL configuration file (my.cnf or my.ini on Windows) will enable the event_scheduler to be running by default.

Writing an event

The syntax is almost similar to the one used to write a stored procedure in MySQL. The intention here is to invoke a (pre-written) stored procedure (This call can be replaced by one or more SQL statements as per the requirement) at a specific time.

DELIMITER $$            
CREATE EVENT ScheduleWM
ON SCHEDULE AT '2012-03-13 22:03:00'
DO
BEGIN
call ManageWM();
END $$
DELIMITER ;

Scheduling can be done in multiple ways:
  • Run once at an absolute date/time:
    AT ‘YYYY-MM-DD HH:MM.SS’
    e.g. AT ’2011-06-01 02:00.00′
  • Run once at a relative time period:
    AT CURRENT_TIMESTAMP + INTERVAL n [HOUR|MONTH|WEEK|DAY|MINUTE]
    e.g. AT CURRENT_TIMESTAMP + INTERVAL 1 DAY  
Easy? Now, many such events can exist on the database. To list them all, the following query can be used.

mysql> show events;
Empty set (0.00 sec)

Surprise... There are no events!
The reason being that, the event has finished executing at the scheduled time and it is gone. The default behavior of an event is such that, it gets deleter from the server after a successful execution.

See it for yourself.

mysql> show create event ScheduleWM\G
*************************** 1. row ***************************
               Event: ScheduleWM
            sql_mode:
           time_zone: SYSTEM
        Create Event: CREATE DEFINER=`sms`@`localhost` EVENT `ScheduleWM` ON SCHEDULE AT '2012-03-13 23:03:00' ON COMPLETION NOT PRESERVE ENABLE DO BEGIN
call ManageWM();
END
character_set_client: latin1
collation_connection: latin1_swedish_ci
  Database Collation: latin1_swedish_ci
1 row in set (0.00 sec)

You can observe a line that says, ON COMPLETION NOT PRESERVE. This was not part of the event we creates. So this has to be the default behavior added to it. Now we can play with this to make out event immortal :). Just as you guessed; preserve it on completion.

DELIMITER $$            
CREATE EVENT ScheduleWM
ON SCHEDULE AT '2012-03-13 22:03:00'
ON COMPLETION PRESERVE
DO
BEGIN
call ManageWM();
END $$
DELIMITER ;

Does it make much sense, to preserve an event, that is meant for a one-time execution? After all default behaviors do make some sense. A much more meaningful use case to preserve an event would be a repetitive event. Let us create one such event. Or... why don't we edit the event, that we had created before (if it still exists)? Even better!

DELIMITER $$            
ALTER EVENT ScheduleWM
ON SCHEDULE EVERY 1 MINUTE
DO
BEGIN
call ManageWM();
END $$
DELIMITER ;

We have now scheduled the event to run every 1 minute. Till when?

Periodic scheduling, again can be done is multiple ways:
  • Run at specific intervals forever:
    EVERY n [HOUR|MONTH|WEEK|DAY|MINUTE]
    e.g. EVERY 1 DAY
  • Run at specific intervals during a specific period:
    EVERY n [HOUR|MONTH|WEEK|DAY|MINUTE] STARTS date ENDS date
    e.g. EVERY 1 DAY STARTS CURRENT_TIMESTAMP + INTERVAL 1 WEEK ENDS ’2012-01-01 00:00.00′
What if we want to stop our altered event to stop running? It still keeps running once a minute. There are 2 ways. We could alter it once again to set the STARTS and ENDS clause. Or... we could just delete the event.

mysql> DROP EVENT ScheduleWM;
Query OK, 0 rows affected (0.00 sec)

mysql> show events;
Empty set (0.00 sec)

One last thing we can do with an event.

mysql> ALTER EVENT ScheduleWM RENAME TO NewScheduleWM;
Query OK, 0 rows affected (0.00 sec)

No prizes for guessing what this does!

Mount USB Drive in Linux | How to

To use an USB drive in Linux, just insert it into the USB drive slot on your PC. Usually a pop-up will appear and guide you. If it does not happen, type 'dmesg' command & locate your USB drive. The output should be something like this.

$ dmesg
...
...
USB Mass Storage Device Found /dev/sda1 ...
...

If you are unable to locate it in the above mentioned way, use the 'fdisk -l' command at the prompt. In addition the existing partitions, you will get some additional output as follows.

$ fdisk -l
...
...
Disk /dev/sda: 8036 MB, 8036285952 bytes
255 heads, 63 sectors/track, 977 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1         978     7847904    c  W95 FAT32 (LBA)
Partition 1 has different physical/logical endings:
     phys=(976, 254, 63) logical=(977, 5, 51)

The /dev/sda1 is where your Linux has a new block device for your USB drive. You need to mount it now to access its contents. This can be done by the mount command using the following 2 steps.

$ mkdir /mnt/usb
$ mount /dev/sda1 /mnt/usb

Now, you can navigate to the /mnt/usb directory and access the contents in the USB drive. When you want to disconnect your USB drive after usage, do not forget to unmount it using the following command.

$ umount /dev/sda1 /mnt/usb