what is Encapsulation

Encapsulation: - wrapping of data in single unit. also we can say hiding the information of essential details. Example: You have a mobile phone.... there it some interface which helps u to interact with cell phone and u can uses the services of mobile phone. But the actually working in cell phone is hide. u don't know how it works internally.

Encapsulation:-- Information hiding.
Abstraction:-- Implementation hiding.

How To Install Subversion/SVN in Ubuntu on Command Line

To install Subversion/SVN in Ubuntu on the command line, open the Terminal by pressing together: Ctrl + Alt + T

Run this command to install Subversion/SVN:

sudo apt-get install subversion

Git Commands – Quick Reference



These common Git commands are listed here for quick reference.

Create a new branch in Git


$ git branch Branch_Name


See all branches:


$ git branch -a


Checkout a branch in Git


$ git checkout Branch_Name


Delete all directories named “_vti_cnf”


$ find . -type d -name '_vti_cnf' -print0 | xargs -0 git rm -r --


Add files to be committed: add only files created or modified, not those deleted.


$ git add .


Add files to be committed: add only files deleted or modified, not those created.


$ git add -u


Add files to be committed: add all files, deleted, modified, or created.


$ git add -A


Remove a directory from a Git repository


$ git rm -r -f Directory_Name


Remove existing files from a Git repository


$ git rm -r --cached File_Name


Undo a previous commit


$ git revert HEAD


Delete a branch in Git, locally


$ git branch -D work


Delete a remote branch (i.e. at GitHub.com)


$ git push origin --delete work


List all existing tags


$ git tag


Tag a new release version


$ git tag -a 1.3.6 -m "Tagging 1.3.6"


Tag the new release on GitHub.com


$ git push origin --tags

List All wp-cron Scheduled Events

This returns an array of all scheduled WP cron events. For each cron event, it gives the hook name, the recurrence schedule, and the time interval in seconds.

_get_cron_array()

Example Usage

echo '
'; 

print_r( _get_cron_array() ); 
echo '
';

Run a wp_schedule_event Recurrence Every 3 Minutes

By default, wp_schedule_event lets you choose a recurrence interval of ‘hourly’, ‘twicedaily’, or ‘daily’ for WP Cron jobs. Here, I show you how to add a custom recurrence interval of 3 minutes.

You may want to run a WP Cron job every 3 minutes, or so, for testing purposes. To add an interval of 3 minutes to the WP Cron schedules, use this:

function isa_add_every_three_minutes( $schedules ) {

    $schedules['every_three_minutes'] = array(
            'interval'  => 180,
            'display'   => __( 'Every 3 Minutes', 'textdomain' )
    );
     
    return $schedules;
}
add_filter( 'cron_schedules', 'isa_add_every_three_minutes' );

Now, you can use ‘every_three_minutes’ as the recurrence parameter when you use wp_schedule_event:

wp_schedule_event( time(), 'every_three_minutes', 'your_cron_function' );

Scheduled Cron Job in wordpress

if (!wp_next_scheduled('my_task_hook')) {

    wp_schedule_event(time(), 'hourly', 'my_task_hook');


add_action('my_task_hook', 'my_task_function');

function my_task_function() {

    wp_mail('nileshyadav326@gmail.com', 'Automatic email', 'Automatic scheduled email from WordPress.');

}

Resume Extracting .tar.gz File That Terminated Before Finishing

If you are extracting a very large .tar.gz file, the process can be terminated before it finishes. This can sometimes help:

Run the command again, but add the -k flag so that it will skip over any files that have already been extracted.

So if you were extracting sample.tar.gz, like this:

tar -xvzf sample.tar.gz

Then, after it gets terminated before finishing, run this (it has the -k flag):

tar -xvkf sample.tar.gz

Cryptography in PHP + Android



HOW TO USE IT (JAVA):



mcrypt = new MCrypt();

/*** encrypt */
String encrypted = MCrypt.bytesToHex(mcrypt.encrypt("plaintext"));

/*** decrypt */
String decrypted = new String(mcrypt.decrypt(encrypted));


HOW TO USE IT (PHP):




$mcrypt = new MCrypt();

#Encrypt
$encrypted = $mcrypt->encrypt("plaintext");

#Decrypt
$decrypted = $mcrypt->decrypt($encrypted);


Library Java:



import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class MCrypt {

private String iv = "fedcba9876543210"; //Dummy iv (CHANGE IT!)
private IvParameterSpec ivspec;
private SecretKeySpec keyspec;
private Cipher cipher;

private String SecretKey = "0123456789abcdef"; //Dummy secretKey (CHANGE IT!)

public MCrypt()
{
ivspec = new IvParameterSpec(iv.getBytes());
keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");

try {
cipher = Cipher.getInstance("AES/CBC/NoPadding");
}
catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public byte[] encrypt(String text) throws Exception
{
if(text == null || text.length() == 0)
throw new Exception("Empty string");

byte[] encrypted = null;

try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);

encrypted = cipher.doFinal(padString(text).getBytes());
}
catch (Exception e)
{
throw new Exception("[encrypt] " + e.getMessage());
}

return encrypted;
}

public byte[] decrypt(String code) throws Exception
{
if(code == null || code.length() == 0)
throw new Exception("Empty string");

byte[] decrypted = null;

try {
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

decrypted = cipher.doFinal(hexToBytes(code));
}
catch (Exception e)
{
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}

public static String bytesToHex(byte[] data)
{
if (data==null) return null;

int len = data.length;
String str = "";
for (int i=0; i
if ((data[i]&0xFF)<16)
str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
else
str = str + java.lang.Integer.toHexString(data[i]&0xFF);
}
return str;
}

public static byte[] hexToBytes(String str)
{
if (str==null) {
return null;
}
else if (str.length() < 2) {
return null;
}
else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
}
return buffer;
}
}

private static String padString(String source)
{
char paddingChar = ' ';
int size = 16;
int x = source.length() % size;
int padLength = size - x;

for (int i = 0; i < padLength; i++)
{
source += paddingChar;
}

return source;
}
}


Library PHP:



class MCrypt
{
private $iv = 'fedcba9876543210'; #Same as in JAVA
private $key = '0123456789abcdef'; #Same as in JAVA

function __construct() {}

function encrypt($str)
{
//$key = $this->hex2bin($key);
$iv = $this->iv;

$td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);

mcrypt_generic_init($td, $this->key, $iv);
$encrypted = mcrypt_generic($td, $str);

mcrypt_generic_deinit($td);
mcrypt_module_close($td);

return bin2hex($encrypted);
}

function decrypt($code)
{
//$key = $this->hex2bin($key);
$code = $this->hex2bin($code);
$iv = $this->iv;

$td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);

mcrypt_generic_init($td, $this->key, $iv);
$decrypted = mdecrypt_generic($td, $code);

mcrypt_generic_deinit($td);
mcrypt_module_close($td);

return utf8_encode(trim($decrypted));
}

protected function hex2bin($hexdata)
{
$bindata = '';

for ($i = 0; $i < strlen($hexdata); $i += 2) {
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}

return $bindata;
}

}

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

The modes of operation currently available are: 

OFB
CBC
CFB
CTR

SOAP-ERROR: Parsing WSDL: Couldn't load from

For some versions of php, the SoapClient does not send http user agent information. What php versions do you have on the server vs your local WAMP?
Try to set the user agent explicitly, using a context stream as follows:
try{

    $opts = array(
        'http'=>array(
            'user_agent' => 'PHPSoapClient'
            )
        );

    $context = stream_context_create($opts);
    $client = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl',
                             array('stream_context' => $context,
                                   'cache_wsdl' => WSDL_CACHE_NONE));

    $result = $client->checkVat(array(
                                    'countryCode' => 'DK',
                                    'vatNumber' => '47458714'
                                    ));
    print_r($result);
}
catch(Exception $e){
    echo $e->getMessage();
}

if  still not work check below Conditions


The combination of HTTP over IPv6, and missing HTTP User Agent string, seems to give the web service problems.

To verify this, try the following on your linux host:
curl  -A ''  -6 http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl
this IPv6 request fails.
curl  -A 'cURL User Agent'  -6 http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl
this IPv6 request succeeds.
curl  -A ''  -4 http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl
curl  -A 'cURL User Agent'  -4 http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl
both these IPv4 request succeeds.
Interesting case :) I guess your linux host resolves ec.europa.eu to its IPv6 address, and that your version of SoapClient did not add a user agent string by default.

Get Product Grand Total in Woo commerce.

$grand_total = $order->calculate_totals();

Get Product Ordered Currency in Woo commerce.

$currency = $order->get_order_currency();

That it.

Custom tracking code for the thanks page (woo themes, Woo Commerce ) snippets

/**
 * Add Tracking Code to the Order Recieved Page
 */
function wc_ninja_checkout_analytics($order_id) {
    $order = new WC_Order($order_id);
    $order_no = $order->get_order_number();
    $grand_total = $order->calculate_totals();
    $shipping_total = $order->calculate_shipping();
    $tax_total = $order->calculate_taxes();
    $currency = $order->get_order_currency();
    $items = $order->get_items();
?>

    <!-- Paste Tracking Code Under Here -->
    <script>
        ga('require', 'ecommerce', 'ecommerce.js');

        ga('ecommerce:addTransaction', {
            'id': '<?php echo $order_no; ?>', // Transaction ID
            'affiliation': '', // Affiliation or store name
            'revenue': '<?php echo $grand_total; ?>', // Grand Total
            'shipping': '<?php echo $shipping_total; ?>', // Shipping cost
            'tax': '<?php echo $tax_total; ?>', // Tax.
            'currency': '<?php echo $currency; ?>' // Local currency code.
        });
    </script>  
    <!-- End Tracking Code -->

    <?php
    // Output the loop
    foreach ($order->get_items() as $item) {
        // Getting some information
        $product = new WC_Product($item['product_id']);
        ?>  
        <!-- Paste Tracking Code Under Here -->
        <script>
            ga('ecommerce:addItem', {
                'id': '<?php echo $order_no; ?>', // Transaction ID.
                'name': '<?php echo $item['name']; ?>', // Product name.
                'sku': '<?php echo $product->get_sku(); ?>', // SKU/code.
                'category': '<?php echo $item['variation_id']; ?>', // Category or variation.
                'price': '<?php echo $item['line_total']; ?>', // Unit price.
                'quantity': '<?php echo $item['qty']; ?>', // Quantity.
                'currency': '<?php echo $currency; ?>'   // Local currency code.
            });
            ga('ecommerce:send');
        </script>  
        <!-- End Tracking Code -->

<?php }  }
add_action('woocommerce_thankyou', 'wc_ninja_checkout_analytics');

SQL Server – Dynamic Order By Clause

Yes, I’m too busy for SQL scripting job these recent weeks. I have a union select query that needed to be sorted per union but since it is not allowed to have order by in my unions, I have to resort sorting outside the union using dynamic order by clause.
It is really easy because there is a pre-determined number of fields and that only the field change. My query need to be sorted by two fields and those fields depends on a certain variable.
Here is the order by part:
1
2
3
order by
    case when @result_option = 1 then delivery_date else delivery_date_08 end,
    case when @result_option = 1 then name_abbr else name_kanji end

A Simple MySQL Backup Script

It was time to deploy the project into the production server. Almost everything is complete. The pages are running smoothly, the scheduler for current weather forecast and the database is fully optimized.
One lacking is the daily database backup. I decided it to be daily since it is not that critical, so here is my script for the daily MySQL Backup.
1
2
3
4
5
#!/bin/bash
filename='db_name'
date=`date +%Y-%m-%d-%H-%M-%S`
backup="/home/user/test_db_backup/$filename.$date.gz"
mysqldump rani -u db_user -pthePassw0rd | gzip -c > $backup
It simply backs up the database using mysqldump utility, and pipe it to gzip utility to compress the file and finally saves into the backup path. By the way it uses the current date and time appended to the filename.

MySQL Backup Strategy

The Story

A few months ago, while at home, my supervisor called me. The incident was that our client’s QR System stops working on a certain module. I learn that the possible cause was a table corruption, so the the story starts.
We went to the client the next day to check what was wrong. I found out that a table is indeed corrupt. We tried to repair the table using myisamchk but it just worsen the problem.
Good thing is that every batch of record on the table has an equivalent CSV file. We restored the latest backup which is from two days ago then restored the rest using the CSV files. So that’s how we started a better backup plan.

Backup Strategy

We are using MyISAM for our table engines. Of course we are using MySQL for Windows. Since most of our operations are more on write (INSERT/UPDATE), we decided to change the table engine to InnoDB to provide better consistency and performance.
This is the summary of the backup plan.
  1. Use InnoDB (for transactional databases)
  2. Enable database logging
  3. Schedule automatic backup
  4. Teach the user to backup every night
Since we thought that InnoDB is the right engine for our type of application, we changed all our tables to InnoDB engine. Though phpMyAdmin row count annoyances occurred, we can simply ignore incorrect row count in phpMyAdmin.
To enable database logging for MySQL, here are the simple steps:
1. Choose a location (preferably on a different drive or partition) to store the logs.
2. Edit my.ini (for Windows and my.cnf for Linux). Add this line:
1
log-bin="/path/to_data_dir/prefix"
This will enable logging of binary files for MySQL and the prefix is a string which will be the prefix for your log file name.
3. Schedule automatic backup and schedule manual backup.

Additional Settings

As advised from MySQL Performance Blog, here are some additional settings for tuning up InnoDB performance.
Edit my.ini or my.cnf and modify / add the following contents:
1
2
#innodb_flush_log_at_trx_commit - set the value to 2
innodb_flush_log_at_trx_commit=2
Of course you need to adjust innodb_buffer_pool_size to a higher level.

The Backup Commands

Since we are logging every transactions into a file, we need also to make sure that logs are also flushed so that it will not eat up your precious disk space. The commands below is taken from a sample where replication is used but is also applicable in general on a single MySQL database server.
Grant your user to flush logs and other privileges. (Login to MySQL from the console first)
1
grant RELOAD, SUPER, REPLICATION CLIENT on *.* to 'your_user'@'your_host';
To do a full backup from the command line:
1
mysqldump db_name -u user -pPassword --single-transaction --flush-logs --master-data=2 --delete-master-logs > filename.sql
And to restore from a binary log:
1
mysqlbinlog log_file | mysql -h server_name
Although late, allow me to greet you, HAPPY NEW YEAR!