Thursday, January 28, 2016

echo color text in console

echo color text in console by using some escape sequences:

myecho('Hello World', 'green', 'background');

function myecho($msg, $color = 'green', $ground = 'foreground') {
  $colorArr = array();
  $colorArr['foreground'] = array(
    'black' => '0;30',
    'dark_gray' => '1;30',
    'red' => '0;31',
    'bold_red' => '1;31',
    'green' => '0;32',
    'bold_green' => '1;32',
    'brown' => '0;33',
    'yellow' => '1;33',
    'blue' => '0;34',
    'bold_blue' => '1;34',
    'purple' => '0;35',
    'bold_purple' => '1;35',
    'cyan' => '0;36',
    'bold_cyan' => '1;36',
    'white' => '1;37',
    'bold_gray' => '0;37',
  );

  $colorArr['background'] = array(
    'black' => '40',
    'red' => '41',
    'magenta' => '45',
    'yellow' => '43',
    'green' => '42',
    'blue' => '44',
    'cyan' => '46',
    'light_gray' => '47',
  );

  if (isset($colorArr[$ground][$color])) {
    echo "\033[" . $colorArr[$ground][$color] . "m" . $msg . "\033[0m";
  }
  else {
    echo $msg;
  }
}

Note: Google bash color for detail.

Reference:

http://stackoverflow.com/questions/1691646/php-echo-text-color

http://www.ingeniousmalarkey.com/2011/02/add-color-to-php-echo-in-cli.html

Sunday, January 24, 2016

post data to the user register form

# vim test.js

(function ($) {
  $('#edit-submit').on('click', function(event){
    event.preventDefault();

    var _formData = $('#user-register-form').serializeArray();

    _formData.push({name: '_drupal_ajax', value: 1});
    _formData.push({name: '_triggering_element_name', value: 'op'});
    _formData.push({name: '_triggering_element_value', value: 'Save'});

    $.ajax({method: 'POST', url: '/userregisterform?ajax_form=1&_wrapper_format=drupal_ajax', dataType: 'json', data: _formData})
      .done(function(data) {
        console.log(data);
      })
      .fail(function(data) {
        console.log(data);
      });
  });
})(jQuery);

# vim TestController.php

<?php
namespace Drupal\hello_world\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;

class TestController extends ControllerBase {
  public function registeruser() {
    // register a new user
    //$values = [];
    //$values['name'] = 'robo-user';
    //$values['mail'] = 'robouser@example.com';
    //$values['pass']['pass1'] = 'password';
    //$values['pass']['pass2'] = 'password';
    //$values['op'] = t('Create new account');

    $form_state = new \Drupal\Core\Form\FormState();
    $form_state->setValues($_POST);

    \Drupal::formBuilder()->submitForm('\Drupal\user\RegisterForm', $form_state);

    $errors = $form_state->getErrors();

    if (empty($errors)) {
      // Return new user session to client.
      $uid = \Drupal::service('user.auth')->authenticate($_POST['name'], $_POST['pass']);
      return new JsonResponse(array( 'uid' => $uid, 'name' => $_POST['name']));
    }
    else {
      return new JsonResponse(array('errors' => $errors));
    }
  }
}
?>

Reference:

http://www.wembassy.com/blog/chris-mcintosh/create-angularjs-headless-drupal-8-application

Saturday, January 23, 2016

Using Ajax Forms in Drupal 8

# vim myexample.info.yml

name: My Example Module
description: My Example Module.
package: Custom

type: module
core: 8.x

# vim myexample.routing.yml

myexample.content:
  path: '/myexample'
  defaults:
    _controller: '\Drupal\myexample\Controller\MyexampleController::content'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

# vim src/Controller/MyexampleController.php

<?php
/**
 * @file
 * Contains \Drupal\myexample\Controller\MyexampleController.
 */

namespace Drupal\myexample\Controller;

use Drupal\Core\Controller\ControllerBase;

use Symfony\Component\HttpFoundation\Response;

class MyexampleController extends ControllerBase {
  public function content() {
    $contactform = \Drupal::formBuilder()->getForm('Drupal\myexample\Form\ContactForm');

    return [
      '#type' => 'markup',
      '#markup' => $this->t('Hello, World!'),
      'contactform' => $contactform,
    ];
  }
}
?>

# vim src/Form/ContactForm.php

<?php
/**
 * @file
 * Contains \Drupal\myexample\Form\ContactForm.
 */

namespace Drupal\myexample\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Ajax\HtmlCommand;

/**
 * Implements an example form.
 */
class ContactForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'contact_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    #$form['#action'] = '/contactformsubmit';

    $form['contact_name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Contact Name'),
    );

    $form['email'] = array(
      '#type' => 'textfield',
      '#ajax' => array(
        'callback' => array($this, 'validateEmailAjax'),
        'event' => 'blur',
        'effect' => 'fade',
      ),
    );

    $form['actions'] = array(
      '#type' => 'actions',
      'submit' => array(
        '#type' => 'submit',
        '#value' => $this->t('Save'),
        '#button_type' => 'primary',
      ),
    );

    return $form;
  }

  /**
   * Validates that the email field is correct.
   */
  protected function validateEmail(array &$form, FormStateInterface $form_state) {
    return valid_email_address($form_state->getValue('email'));
  }

  /**
   * Ajax callback to validate the email field.
   */
  public function validateEmailAjax(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $valid = $this->validateEmail($form, $form_state);

    if ($valid) {
      $css = ['border' => '1px solid green'];
      $message = $this->t('Email ok.');
    }
    else {
      $css = ['border' => '1px solid red'];
      $message = $this->t('Email not valid.');
    }

    $response->addCommand(new CssCommand('#edit-email', $css));
    $response->addCommand(new HtmlCommand('.email-valid-message', $message));

    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    #file_put_contents('/tmp/debug1', print_r($form, TRUE) . PHP_EOL, FILE_APPEND);

    if (strlen($form_state->getValue('contact_name')) < 3) {
      $form_state->setErrorByName('contact_name', $this->t('The contact name is too short.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('Contact name @contact_name', array('@contact_name' => $form_state->getValue('contact_name'))));
  }
}
?>

Reference:

http://www.sitepoint.com/using-ajax-forms-drupal-8/

http://www.kalose.net/oss/drupal-8-ajax-forms/

https://www.drupal.org/node/2117411

To redirect both stdout output and stderr error to a file

0: stdin
1: stdout
2: stderr

Note that the order of redirections is significant. For example, the command

              ls > dirlist 2>&1

directs both standard output and standard error to the file dirlist, while the command

              ls 2>&1 > dirlist

directs only the standard output to file dirlist, because the standard error was duplicated from the standard output before the standard output was redirected to dirlist.

Redirecting Standard Output and Standard Error:

This construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be redirected to the file whose name is the expansion of word.

There are two formats for redirecting standard output and standard error:

              &>word

and

              >&word

Of the two forms, the first is preferred. This is semantically equivalent to

              >word 2>&1

To redirect both stdout output and stderr error to a file:

# find . &> /tmp/test.txt

Redirects STDOUT to log and than replaces STDERR with the redirected STDOUT:

# some_cmd > log 2>&1

Replaces STDERR with STDOUT and then redirects the original STDOUT to log:

# some_cmd 2>&1 > log

Lookup the manual and find keyword redirection for detail:

# man bash

Reference:

http://stackoverflow.com/questions/4699790/cmd-21-log-vs-cmd-log-21

http://superuser.com/questions/71428/what-does-21-do-in-command-line

http://stackoverflow.com/questions/818255/in-the-shell-what-does-21-mean

To include the custom or external js css files

drupal_add_js and drupal_add_css have been deprecated in Drupal 8. The new way to include the Javascript or css files in Drupal 8:

# vim myexample.libraries.yml

this_is_test_lib_name:
  version: 1.x
  css:
    theme:
      css/myexample.css: {}
  js:
    js/myexample.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

# vim myexample.module

<?php
/**
 * Implements hook_preprocess_page().
 */
function myexample_preprocess_page(&$variables) {
  $variables['#attached']['library'][] =  'myexample/this_is_test_lib_name';
}
?>

# vim myexample/js/myexample.js

(function ($) {
  console.log('ready');
})(jQuery);

or

(function ($, Drupal, window) {
  console.log('ready');
})(jQuery, Drupal, window);

Note: underscore.js and backbone.js are in core in Drupal 8.
Note: One other change you may have noticed: Drupal.settings is now drupalSettings.

Reference:

http://atendesigngroup.com/blog/looking-at-drupal-8-javascript-changes

get a Drupal 8 node programmatically with console in an external script

get a Drupal 8 node programmatically with console in an external script

Install Drush by download the latest stable release using the code below or browse to github.com/drush-ops/drush/releases:

# wget http://files.drush.org/drush.phar

Test your Drush install:

# php drush.phar core-status

Rename to `drush` instead of `php drush.phar`. Destination can be anywhere on $PATH:

# chmod +x drush.phar
# mv drush.phar /usr/local/bin/drush

Enrich the bash startup file with completion and aliases:

# drush init

More detail: http://www.drush.org/en/master/install/

Read Drush help:

# drush help

Run your script:

# vim test.php

<?php
use Drupal\node\Entity\Node;

$node = Node::load(6);

echo '<pre>' . print_r($node, TRUE) . '</pre>';
?>

# drush --root=/www/drupal-8.0.1 --uri=drupal8.cent-exp.local php-script test.php

# drush --root=/www/drupal-8.0.1 --uri=drupal8.cent-exp.local --debug php-script test.php

# drush --root=/www/drupal-8.0.1 --uri=drupal8.cent-exp.local --debug --verbose php-script test.php

To create a new node:

<?php
use Drupal\node\Entity\Node;

$node = Node::create(array(
    'type' => 'page',
    'title' => 'your title',
    'langcode' => 'en',
    'uid' => '1',
    'status' => 1,
    'field_firstname' => 'My First Name',
    #'field_fields' => array(),
));

$node->save();

Friday, January 22, 2016

XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource

XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource

APIs are the threads that let you stitch together a rich web experience. But this experience has a hard time translating to the browser, where the options for cross-domain requests are limited to techniques like JSON-P (which has limited use due to security concerns) or setting up a custom proxy (which can be a pain to set up and maintain).

Cross-Origin Resource Sharing (CORS) is a W3C spec that allows cross-domain communication from the browser. By building on top of the XMLHttpRequest object, CORS allows developers to work with the same idioms as same-domain requests.

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data.

As you can see from this example, CORS support requires coordination between both the server and client. Luckily, if you are a client-side developer you are shielded from most of these details. The rest of this article shows how clients can make cross-origin requests, and how servers can configure themselves to support CORS.

Method 1:

On the remote server, add:

<?php
header('Access-Control-Allow-Origin: http://symfony.cent-dev.local');
#header('Access-Control-Allow-Headers: X-Requested-With');
#header('Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS');
?>

Then, go observe the response in the browser at client side. You will see the three lines above.

Method 2:

On the remote server, edit your Apache configuration file:

<ifModule mod_headers.c>
    Header set Access-Control-Allow-Origin: http://symfony.cent-dev.local
</ifModule>

Note: you can replace http://symfony.cent-dev.local to a wildcard *.

Note: and don't forget to load module: a2enmod headers

Method 3:

Add a proxy script on your server, ex: proxy.php then having your client side script to access the proxy.php script.

The proxy.php script then send the request to the remote server.

Reference:

http://www.html5rocks.com/en/tutorials/cors/
http://www.html5rocks.com/en/tutorials/file/xhr2/#toc-cors
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
http://www.andlabs.org/html5.html
https://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity

Thursday, January 21, 2016

simply accounting - How to connect to MySQL Server

simply accounting - How to connect to MySQL Server

Since you do not seem very familiar with ODBC and MySQL, we may be able to help you more if you describe what it is you are trying to do.

To fill the Connector/ODBC form, do the following:

1-Open Simply, go to Help > About Simply Accounting by Sage and click on Support Info... On the right side, take note of the Computer name and Port number.

2-On the ODBC form you need to fill the following fields:

Server: The Computer name from Help > About

User: Your user name (sysadmin or other with 3rd party access rights)

Password: Well, the user's password or blank if no password

Database: simply

Click on the Connect Options tab:

Port: the port number from Help > About

You'll then be able to connect. Note that Simply must be opened to connect through ODBC.

Some Files/Directories you might be interested in:
[] C:\Documents and Settings\All Users\Documents\Sage Software\ConnectionManager\ConnectionManager.ini

[] C:\Program Files (x86)\winsim\ConnectionManager\MySqlBinary\5.0.38\dbengine.ini

[] C:\Documents and Settings\All Users\Documents\Sage Software

[] C:\Documents and Settings\All Users\Documents\Sage Software\Simply Accounting

[] C:\Documents and Settings\All Users\Documents\Simply Accounting

[] C:\Documents and Settings\danny\My Documents\Simply Accounting

Add these lines to C:\Program Files (x86)\winsim\ConnectionManager\MySqlBinary\5.0.38\dbengine.ini
# binary log
log-bin=mysql-bin
# port number
port = 13541
# data dir
datadir = C:\\test\\asdf.SAJ
# log all the queries log (including select, insert, update, and all).
log

Create a file called c:\mysql-init.txt with following content:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'YourPassWordHere' WITH GRANT OPTION;
GRANT SUPER ON *.* TO 'root'@'localhost';
FLUSH PRIVILEGES;

Note: without granting the super privileges, you will see the following message:

Sage.Simply.DataTypes.ConnectionException: TRIGGER command denied to user 'root'@'localhost' for table 'titrec' ---> MySql.Data.MySqlClient.MySqlException: TRIGGER command denied to user 'root'@'localhost' for table 'titrec'

Run MySQL and create a new user called root on start up:
start > run > cmd.exe

C:\> "C:\Program Files (x86)\winsim\ConnectionManager\MySqlBinary\5.0.38\mysql\mysqld-nt.exe" --defaults-file="C:\\Program Files (x86)\\winsim\\ConnectionManager\\MySqlBinary\\5.0.38\\dbengine.ini" --init-file="C:\\mysql-init.txt"

http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html

Commands you might be interested in:

Login to mysql:
cmd> mysql -u sysadmin -p --port=13541
cmd> mysql -u root -p --port=13541

Note: Simply Accounting default username: sysadmin.

Manually shutdown mysql:
cmd> mysqladmin -u root -p -P 13540 shutdown

View mysql binary log:
cmd> mysqlbinlog C:\test\asdf.SAJ\mysql-bin.000007

Simply Accounting MySQL database fine tune Tips:

Edit C:\Documents and Settings\All Users\Documents\Sage Software\ConnectionManager\ConnectionManager.ini, under the [settings] section:
[settings]
# Note: Simply Accounting Connection Manager will use below setting to overwrite mysql's "innodb_buffer_pool_size".
Buffer Pool Size=1024

Edit C:\Program Files (x86)\winsim\ConnectionManager\MySqlBinary\5.0.38\dbengine.ini, under the [mysqld] sectioin:
[mysqld]
### Modified by Jun
# Note: do not change innodb_buffer_pool_size here, since it will have no effect because Simply Accounting Connection Manager has its own setting to overwrite it. You can either go to Simply Accounting Connection Manager and adjust the "memory buffer size",
# or edit C:\Documents and Settings\All Users\Documents\Sage Software\ConnectionManager\ConnectionManager.ini, under the settings section:
# [settings]
# Buffer Pool Size=1024
#
# Note: the "number of connection attempts" in Simply Accounting Connection manager is "max_connect_errors".
#
# Note: If you modify the innodb_log_file_size, MySQL will fail to restart and InnoDB will complain about the size of the changed log file.
# The proper way to increase the innodb_log_file_size:
# 1. shutdown mysql server.
# 2. make backup of data and log files (ibdata1 and ib_logfile*).
# 3. remove InnoDB log files (ib_logfile*).
# 4. set new value for innodb_log_file_size in my.cnf
# 5. start mysqld
# 6. check error logs to ensure everything went fine.
# Reference: http://dev.mysql.com/doc/refman/5.5/en/innodb-data-log-reconfiguration.html
#innodb_buffer_pool_size=1G
innodb_additional_mem_pool_size=16M
innodb_log_buffer_size=8M
innodb_log_file_size=128M
innodb_log_files_in_group=2
max_allowed_packet = 16M
default-storage-engine = InnoDB
# turn this on if you prefer separate inoodb file for each table.
#innodb_file_per_table
# log all the queries log (including select, insert, update, and all).
#log
# Port number to use for connections.
#port=13540
# Path to the database root.
#datadir=D:/SimplyAccounting/company1/9901.SAJ
### skip DNS domain name resolve to avoid network slow issue.
skip-name-resolve

Simply Accounting Default dbengine.ini:
[mysqld]
max_connections=100
innodb_log_buffer_size=1M
innodb_log_file_size=2M
innodb_thread_concurrency=8
innodb_lock_wait_timeout=10
innodb_support_xa=0
innodb_autoextend_increment=1
wait_timeout=2147483
lower_case_table_names=1
connect_timeout=10

Use following commands to verify the settings:
mysql> SHOW VARIABLES LIKE 'innodb_buffer_%';
mysql> SHOW VARIABLES LIKE 'innodb_additional_%';
mysql> SHOW VARIABLES LIKE 'innodb_log_%';

MySQL fine tune Tips:
What is the buffer size currently set to? If it is 56 MB, try increasing to 128 and test. Here is the recommendation from the Help Menu:

Memory buffer size (in MB). The amount of system memory allocated to cache company data used to populate reports, search/lookup results, and record lists in Simply.

Tips:

If a large number of records and transactions are stored in your company database, and you have sufficient RAM installed on your computer, you may be able to fine-tune Simply Accounting's performance by increasing the memory reserved for Connection Manager operations. Be careful! If you set this number too high, you may prevent other applications from running, including Simply Accounting.

We recommend that you increase the buffer size in increments of 10MB, and never exceed 60% of total physical RAM installed in your PC. If you are unable to run other applications after increasing the buffer size, click the Default button to reset the buffer to it's default size.

You can manually edit the Buffer Pool Size setting in the ConnectionManager.ini file.This setting will overwrite any existing value for innodb_log_buffer_size set in the MySQL dbengine.ini file.
I would increase to 128 as a starting place and keep it there for a while and observe. If you experience resources issues (either with Simply Accounting or another product) begin lowering the buffer.

Use bigger log files and third party database
If you want to use bigger log files setting, you have to dump the simply database and restore it to avoid "log sequence number in the future" error

- close all simply clients.

- open Simply Connection Manager, and make sure there is no connection at all.

- copy the simply db folder to Jun's machine.

- start working on jun's machine

- use the latest Simply DB

- start simply with default setting

- look at the error logs, make sure there is no error.

- close simply and restart it

- look at the error logs, make sure there is no error.

- do a mysql dump with -R option (to include routines, functions, stored procedures):

cmd> e:
cmd> mysqldump -u root -p -P 13540 -R simply > 2012-07-20_1126_simply.sql
cmd> mysqldump -u root -p -P 13540 mysql > 2012-07-20_1126_mysql.sql

Note: You don't need to backup information_schema database, since information_schema is a virtual database, rebuilt each time MySQL is restarted, so there is no point in backing it up because you can't restore it anyway.

- close simply client, and go to Simply Connection Manager to make sure there is no more connections.

- Go to Task Manager to make sure mysqld-nt.exe is not running.

- start mysql server manually:
cmd> "C:\Program Files (x86)\winsim\ConnectionManager\MySqlBinary\5.0.38\mysql\mysqld-nt.exe" --defaults-file="C:\\Program Files (x86)\\winsim\\ConnectionManager\\MySqlBinary\\5.0.38\\dbengine.ini"

- delete simply database:
cmd> mysql -u root -p -P 13540
mysql> drop database simply;
mysql> exit

- shutdown mysql manually:
cmd> mysqladmin -u root -p -P 13540 shutdown

- Go to Task Manager to make sure mysqld-nt.exe is not running.

- Go to c:\mycompany\9901.SAJ, and backup and delete these files:
ib_logfile*
ibdata1

- use the custom dbengine.ini setting:
C:\Program Files (x86)\winsim\ConnectionManager\MySqlBinary\5.0.38\dbengine.ini

- Use Simply Connection Manager to adjust the Memory Buffer size to 1024 MB.

Note: make sure you do "Stop service" and "Start Service" in Simply Connection Manager.

or you prefer to modify the file manually:

add/modify this line in C:\Documents and Settings\All Users\Documents\Sage Software\ConnectionManager\ConnectionManager.ini:
Buffer Pool Size=1024

- start mysql server manually:
cmd> "C:\Program Files (x86)\winsim\ConnectionManager\MySqlBinary\5.0.38\mysql\mysqld-nt.exe" --defaults-file="C:\\Program Files (x86)\\winsim\\ConnectionManager\\MySqlBinary\\5.0.38\\dbengine.ini" --init-file="C:\\mysql-init.txt"

- use navicat to create a new simply database.
name: simply
character set: latin1 -- cp1252 West European
collation: latin1_general_ci

- restore simply database:
cmd> e:
cmd> mysql -u root -p -P 13540 simply < 2012-07-20_1126_simply.sql

 - check log files

- close all the connections.

- shutdown mysql manually:
cmd> mysqladmin -u root -p -P 13540 shutdown

- start simply client

- make sure mysql setting is on:
mysql> SHOW VARIABLES LIKE '%pool%'
innodb_additional_mem_pool_size 16777216
innodb_buffer_pool_size 1073741824

- check log files

- create a drupal database

- restore drupal database
cmd> mysql -u root -p -P 13540 drupal < drupal.sql

- make the www user have the right to access drupal database.

 - make another backup (with -R option) after everything is done:
cmd> e:
cmd> mysqldump -u root -p -P 13540 -R simply > 2012-07-20_1818_simply.sql

Reference:

http://www.simplyaccounting.com/community/forums/p/5399/19091.aspx#19091
http://community.simplyaccounting.com/community/forums/p/3326/11683.aspx

Sunday, January 17, 2016

To run Red Hat KVM virtualization inside VMware workstation

On VMware, edit the virtual machine setting > Hardware tab > processor > check "Virtualize Intel VT-x/EPT or AMD-v/RVI".

To check whether the processor supports hardware virtualization:

# lscpu | grep -i virtualization

Virtualization:        VT-x

Note: VT-x for Intel processors and AMD-V for AMD processors.

The presence of this flag confirms that the processor on this host support hardware virtualization:

# grep -E 'vmx|svm' /proc/cpuinfo

flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts mmx fxsr sse sse2 ss ht syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts nopl xtopology tsc_reliable nonstop_tsc aperfmperf eagerfpu pni pclmulqdq vmx ssse3 cx16 pcid sse4_1 sse4_2 x2apic popcnt aes xsave avx f16c rdrand hypervisor lahf_lm ida arat epb xsaveopt pln pts dtherm tpr_shadow vnmi ept vpid fsgsbase smep

Note: vmx (for Intel processors) or svm (for AMD processors).

Look up group install:

# yum group list virtual*

Available environment groups:
   Virtualization Host

# yum group info "Virtualization Host"

Environment Group: Virtualization Host
 Environment-Id: virtualization-host-environment
 Description: Minimal virtualization host.
 Mandatory Groups:
   +base
   +core
   +virtualization-hypervisor
   +virtualization-tools
 Optional Groups:
   +debugging
   +network-file-system-client
   +remote-system-management
   +virtualization-platform

Install the virtualization environment group:

# yum -y group install "Virtualization Host"

Saturday, January 16, 2016

Verifying Package Attributes

To identify which package the file is associated with:

# rpm -qf /etc/passwd

setup-2.8.71-4.el7.noarch

# rpm -qi setup

To compare the attributes of a file on the current system with the original file in the package database:

# rpm -Vf /etc/passwd

To verify the attributes for all the files included in a package with details:

# rpm -Vv setup

Mount an ISO image file in Red Hat

If you have copied the Red Hat 7 ISO image to a directory on the system, you can mount the ISO image file by running the following command:

# mount -o loop /var/rhel7iso/rhel-server-7.0-x86_64-dvd.iso /mnt

Note: The loop option tells the mount command that what is being mounted is not a block mountable device file but a mountable image file.

# df -h | grep mnt

To mount from DVD:

# mount /dev/cdrom /mnt

做大事人的 10個特徵,很準,算算看 據說 超過5個,你註定要發達了!

做大事人的 10個特徵,很準,算算看 據說 超過5個,你註定要發達了!

一、忍得住孤獨
人生想要獲得成功,必須忍得住孤獨,

尤其是在創業之初,很多時候為了達成目標,可能別人在休息時,我們還一個人在默默無聞的付出,

這種過程是非常孤獨的,但如果能挺得過去,我們將會比別人取得更大的成功。

二、耐得住寂寞
為了生活、為了工作、為了事業,往往很多時候我們都不能陪在親人朋友的身邊,

而是必須佔用很多的休息時間和與家人團聚的時間。我們是否能夠耐得住這種寂寞?

三、挺得住痛苦
人生道路並非一帆風順,一路上難免會有很多坎坷、淚水、痛苦。痛苦之後往往會有兩種結果:

一是委靡不振;二是更加強大,我們在經歷了痛苦之後究竟是委靡不振還是更加強大?取決於我們是否能挺得住痛苦?

四、頂得住壓​​力
沒壓力就會沒動力,大家都知道這個簡單的道理,但是很多人卻在遇到壓力時選擇了逃避和放棄。

只有當我們擺正心態,坦然的面對壓力時,才會給我們的成長和發展注入無限動力。

五、擋得住誘惑
做人做事必須堅守自己的理想和原則。只要我們所堅守的是正確的事情,哪怕會有短暫的痛苦,

也應該堅持下去;如果我們所做的是錯誤的事情,哪怕會得到短暫的快樂,也應該堅決拒之!

生活中處處都會存在著各種各樣的誘惑,如果定力不強,這些誘惑會隨時影響並阻礙著我們前進的步伐,

甚至會讓自己迷失前進的方向,陷入短暫利益的漩窩中。

在種種誘惑面前我們要一如繼往的堅持自己正確的原則和理想。

六、經得起折騰
每一次的失敗、每一次的淚水和汗水總是在不斷的折騰著我們,

因此讓我們的發展道路充滿荊棘,但經過無數次的折騰才會讓我們從中深刻的體會到生活的真諦,

我們試問自己能一而再、再而三的經得起折騰嗎?當經歷無數次的折騰後,我們還能堅持嗎?

七、受得起打擊
當面對他人一次又一次的冷嘲熱諷、當面對客戶對我們一次又一次的打擊時,

我們能經受得起嗎?我們是否還能保持最初的激情,同時堅守自己的目標?

我們是否還能保持不下降指標而是持續不斷的增加措施?

在市場開發中,當客戶毫不客氣的讓我們“滾”時,我們會保持一種什麼樣的心態呢?

我們是繼續爭取還是馬上灰溜溜的離開而從此不再爭取面談?

無論是個人還是集體不在打擊中成長,就在打擊中消亡!

八、丟得起面子
面子是自己給自己的,不是別人給的。

害怕丟面子會讓自己丟一輩子的面子,害怕失敗會失敗一輩子!

害怕丟面子往往帶來的結果是打腫臉充胖子,會讓自己更加痛苦,從而丟掉更大的面子,讓自己陷入一種惡性循環!

九、擔得起責任
“責任”一詞在生活、工作中都隨時被我們掛在嘴邊,屢見不鮮。

字典中關於對“責任”的解釋:份內應做而未做或者未做好應當為此承擔的過失。

責任分為三種:家庭責任​​、企業責任、社會責任。

在家庭中我們扮演著兒女、父親、丈夫、妻子、等角色;在企業中我們扮演著員工、管理者、領導或者老闆的角色;

在社會中我們扮演著公民、律師、老師、企業家等等角色,

總之每個人在不同的場合都扮演著不同的角色,然而我們是否能真正的用行動來承擔起自己在各種場合下的角色?

十、提得起精神
當我們在連續多天加班或超負荷工作後,是否能提起精神為了自己目標而繼續衝刺?

Reference:

http://www.cmoney.tw/notes/note-detail.aspx?nid=27865

Saturday, January 9, 2016

Insert text is very slow in Vim

Read from the local file (super fast):

:read file

Try to set syntax off:

:set syntax=off

Vim tries to keep your work safe and doesn't assume you can type several thousand characters per second. Read :help swap-file for some details on the buffering. The solution to your problem is this:

Turn off vim's swapfile while you are pasting text:

:set noswapfile

Turning off swap is not safe for normal operations! Immediately after the paste:

:set swapfile

See :help swapfile for more details.

Folding could be the problem:

set foldenable              " can slow Vim down with some plugins
set foldlevelstart=99       " can slow Vim down with some plugins
set foldmethod=syntax       " can slow Vim down with some plugins

According to vim's help (:help foldmethod), the syntax setting caused vim to use syntax highlighting to determine how to automatically fold my code.

Other things to check/toggle are syntax, filetype, wrap and line length (some plugins can be slow with very long lines).

Running Vim without your current settings is a good starting point:

# vim -u NONE

Reference:

http://stackoverflow.com/questions/15086155/vim-insert-mode-is-very-slow-with-400-lines
http://superuser.com/questions/550669/my-copy-of-vim-is-running-extremely-slowly-when-i-edit-medium-to-large-eg-1000

Thursday, January 7, 2016

Get the first day and last day range of the current quarter

Get the first day and last day range of the current quarter:

SELECT
  CAST(MAKEDATE(YEAR(CURDATE()), 1) AS DATETIME) + INTERVAL (QUARTER(CURDATE()) - 1) QUARTER
, CAST(MAKEDATE(YEAR(CURDATE()), 1) AS DATETIME) + INTERVAL (QUARTER(CURDATE()) - 0) QUARTER

Get the first day and last day range of the last quarter:

SELECT
  CAST(MAKEDATE(YEAR(CURDATE()), 1) AS DATETIME) + INTERVAL (QUARTER(CURDATE()) - 2) QUARTER
, CAST(MAKEDATE(YEAR(CURDATE()), 1) AS DATETIME) + INTERVAL (QUARTER(CURDATE()) - 1) QUARTER

Get the first day and last day range of the next quarter:

SELECT
  CAST(MAKEDATE(YEAR(CURDATE()), 1) AS DATETIME) + INTERVAL (QUARTER(CURDATE()) + 0) QUARTER
, CAST(MAKEDATE(YEAR(CURDATE()), 1) AS DATETIME) + INTERVAL (QUARTER(CURDATE()) + 1) QUARTER

Wednesday, January 6, 2016

Burn bootable ISO image to a USB drive

Burn bootable ISO image to a USB drive

Fedora LiveUSB Creator - is a cross-platform tool for easily installing live operating systems on to USB flash drives.

https://fedorahosted.org/liveusb-creator/

UNetbootin - allows you to create bootable Live USB drives for Ubuntu and other Linux distributions without burning a CD.

http://unetbootin.sourceforge.net/

Monday, January 4, 2016

Disable RSS feed link and request new password link in Drupal

Disable RSS feed link and request new password link in Drupal

<?php
/**
 * Implementation of hook_menu_alter().
 */
function mymodule_trigger_menu_alter(&$callback) {
  ### remove the rss.xml link
  unset($callback['rss.xml']);

  ### disable "request new password" function.
  $callback['user/password']['access callback'] = FALSE;
  $callback['user/password']['access arguments'] = array(FALSE);
}
?>

Sunday, January 3, 2016

Untrack *.pyc binary files from git

git update-index should do what you want

This will tell git you want to start ignoring the changes to the file

# git update-index --assume-unchanged path/to/file

When you want to start keeping track again

# git update-index --no-assume-unchanged path/to/file

Github Documentation: update-index

or

# git rm -r --cached path/to/file

Reference:

http://stackoverflow.com/questions/6964297/untrack-files-from-git

Saturday, January 2, 2016

Install PHP 7 Nightly Built on CentOS 7

Install PHP 7 Nightly Built on CentOS 7

Add a new repository:

# vim /etc/yum.repos.d/php7-nightly.repo

[zend-php7]
name = PHP7 nightly by Zend Technologies
baseurl = http://repos.zend.com/zend-server/early-access/php7/repos/centos/
gpgcheck=0

Note: the default installation path will be: /usr/local/php7

Install PHP 7 from the PHP official development repository:

# yum install php7-nightly

Copy the configuration files:

# cd /usr/local/php7/etc
# cp php-fpm.conf.default php-fpm.conf
# cp php-fpm.d/www.conf.default php-fpm.d/www.conf

# cd ~/tmp
# wget http://ca1.php.net/get/php-7.0.1.tar.xz/from/this/mirror -O php-7.0.1.tar.xz
# tar Jxvf php-7.0.1.tar.xz
# cp ~/tmp/php-7.0.1/php.ini* /usr/local/php7/etc/
# cd /usr/local/php7/etc
# cp php.ini-development php.ini

Edit www.conf:

# vim /usr/local/php7/etc/php-fpm.d/www.conf

user = apache
group = apache

Edit php.ini:

# vim /usr/local/php7/etc/php.ini

zend_extension=opcache.so
opcache.enable=1
opcache.enable_cli=1

Start php-fpm in background:

# /usr/local/php7/sbin/php-fpm -D

# ps auxww|grep php

root     43345  0.0  0.1 421576  7376 ?        Ss   Jan01   0:03 php-fpm: master process (/usr/local/php7/etc/php-fpm.conf)
apache   43346  0.0  1.0 429736 42760 ?        S    Jan01   0:05 php-fpm: pool www
apache   43347  0.0  1.0 429924 42276 ?        S    Jan01   0:07 php-fpm: pool www
apache   44123  0.0  0.9 429388 37168 ?        S    Jan01   0:00 php-fpm: pool www

Friday, January 1, 2016

Call an external program from MySQL trigger

Call an external program from MySQL trigger

MySQL provides a way to implement your own functions, its called User Defined Functions (UDF)

sys_eval - executes an arbitrary command, and returns it's output.
sys_exec - executes an arbitrary command, and returns it's exit code.
sys_get - gets the value of an environment variable.
sys_set - create an environment variable, or update the value of an existing environment variable.

http://www.mysqludf.org/

https://github.com/mysqludf

http://dev.mysql.com/doc/refman/5.0/en/adding-udf.html