Friday, February 27, 2015

Apache Permission denied access to 403 Forbidden

There are a few things that could be the problem.

Make sure it's not denied by Apache:

<Directory /path/to/webroot>
    Order allow,deny
    Allow from all
</Directory>

So if you have created a VirtualHost or an Alias that does not fall under this /path/to/webroot apache will have denied access to it. The solution in that case is to add another Directory entry in your httpd.conf to allow access to that directory.

If you are using a .htaccess file to control the access permission, make sure you do:

<Directory "/var/www/html">
  ### Changing from None to All
  AllowOverride All
</Directory>

# ls -la .htaccess

-rw-rw----. 1 dev apache 6543 Feb 27 17:26 .htaccess

Make sure Apache has Read, Execute Permissions:

# ls -lad /var/www/html/

drwxr-xr-x. 4 root root 49 Feb 27 01:25 /var/www/html/

If running Security Enhanced Linux (SELinux):

# chcon -R --type=httpd_sys_content_t /var/www/html/magento19

Or for read and write permission:

# chcon -R -t httpd_sys_rw_content_t /var/www/html/magento19/app/etc

Apache 2.4.3 (or maybe slightly earlier) added a new security feature that often results in this error:

You would also see a log message of the form "client denied by server configuration". The feature is requiring a user identity to access a directory.

It is turned on by DEFAULT in the httpd.conf that ships with Apache. You can see the enabling of the feature with the directive.

Require all denied

This basically says to deny access to all users. To fix this problem, either remove the denied directive (or much better) add the following directive to the directories you want to grant access to:

Require all granted

as in

<Directory "your directory here">
   Order allow,deny
   Allow from all
   # New directive needed in Apache 2.4.3: 
   Require all granted
</Directory>

Reference:

http://www.petefreitag.com/item/793.cfm
http://stackoverflow.com/questions/6959189/apache-virtualhost-403-forbidden

Configuring Magento To Use Redis

Enable the Cm_RedisSession module:

# vim app/etc/modules/Cm_RedisSession.xml

<active>true</active>

Copy the necessary codes from app/etc/local.xml.additional to app/etc/local.xml:

Put the following code inside <global>   </global>.

# vim app/etc/local.xml

<!-- example of redis cache -->
        <cache>
            <backend>Mage_Cache_Backend_Redis</backend>
            <backend_options>
                <server>127.0.0.1</server> <!-- or absolute path to unix socket for better performance -->
                <port>6379</port>
                <database>0</database>
                <password></password>
                <force_standalone>0</force_standalone>  <!-- 0 for phpredis, 1 for standalone PHP -->
                <connect_retries>1</connect_retries>    <!-- Reduces errors due to random connection failures -->
                <automatic_cleaning_factor>0</automatic_cleaning_factor> <!-- Disabled by default -->
                <compress_data>1</compress_data>  <!-- 0-9 for compression level, recommended: 0 or 1 -->
                <compress_tags>1</compress_tags>  <!-- 0-9 for compression level, recommended: 0 or 1 -->
                <compress_threshold>20480</compress_threshold>  <!-- Strings below this size will not be compressed -->
                <compression_lib>gzip</compression_lib> <!-- Supports gzip, lzf and snappy -->
                <persistent>1</persistent> <!-- persistence value, 0: not in use, > 0 used as persistence ID -->
            </backend_options>
        </cache>

        <!-- example of redis full page cache -->
        <full_page_cache>
            <backend>Mage_Cache_Backend_Redis</backend>
            <backend_options>
                <server>127.0.0.1</server> <!-- or absolute path to unix socket for better performance -->
                <port>6379</port>
                <database>1</database>
                <password></password>
                <force_standalone>0</force_standalone>  <!-- 0 for phpredis, 1 for standalone PHP -->
                <connect_retries>1</connect_retries>    <!-- Reduces errors due to random connection failures -->
                <automatic_cleaning_factor>0</automatic_cleaning_factor> <!-- Disabled by default -->
                <!-- in FPC data is already gzipped, no need to do this twice -->
                <compress_data>0</compress_data>  <!-- 0-9 for compression level, recommended: 0 or 1 -->
                <compress_tags>1</compress_tags>  <!-- 0-9 for compression level, recommended: 0 or 1 -->
                <compress_threshold>20480</compress_threshold>  <!-- Strings below this size will not be compressed -->
                <compression_lib>gzip</compression_lib> <!-- Supports gzip, lzf and snappy -->
                <lifetimelimit>43200</lifetimelimit> <!-- set lifetime for keys without TTL -->
                <persistent>2</persistent>
            </backend_options>
        </full_page_cache>

        <!-- example of redis session storage -->
        <session_save>db</session_save>
        <redis_session>                       <!-- All options seen here are the defaults -->
            <host>127.0.0.1</host>            <!-- Specify an absolute path if using a unix socket -->
            <port>6379</port>
            <password></password>             <!-- Specify if your Redis server requires authentication -->
            <timeout>2.5</timeout>            <!-- This is the Redis connection timeout, not the locking timeout -->
            <persistent></persistent>         <!-- Specify unique string to enable persistent connections. E.g.: sess-db0; bugs with phpredis and php-fpm are known: https://github.com/nicolasff/phpredis/issues/70 -->
            <db>0</db>                        <!-- Redis database number; protection from accidental loss is improved by using a unique DB number for sessions -->
            <compression_threshold>2048</compression_threshold>  <!-- Set to 0 to disable compression (recommended when suhosin.session.encrypt=on); known bug with strings over 64k: https://github.com/colinmollenhour/Cm_Cache_Backend_Redis/issues/18 -->
            <compression_lib>gzip</compression_lib>              <!-- gzip, lzf or snappy -->
            <log_level>1</log_level>               <!-- 0 (emergency: system is unusable), 4 (warning; additional information, recommended), 5 (notice: normal but significant condition), 6 (info: informational messages), 7 (debug: the most information for development/testing) -->
            <max_concurrency>6</max_concurrency>                 <!-- maximum number of processes that can wait for a lock on one session; for large production clusters, set this to at least 10% of the number of PHP processes -->
            <break_after_frontend>5</break_after_frontend>       <!-- seconds to wait for a session lock in the frontend; not as critical as admin -->
            <break_after_adminhtml>30</break_after_adminhtml>
            <bot_lifetime>7200</bot_lifetime>                    <!-- Bots get shorter session lifetimes. 0 to disable -->
        </redis_session>

Redis support across different Magento versions

Magento CE >= 1.7.0.0 and < 1.8.0.0
  • Session storage – not included
  • Cache backend – not included, after installation available as Cm_Cache_Backend_Redis

Magento CE >= 1.8.0.0
  • Session storage – included
  • Cache backend – included, available as Mage_Cache_Backend_Redis

Note: make sure you do change:

From:

<backend>Cm_Cache_Backend_Redis</backend>

To:

<backend>Mage_Cache_Backend_Redis</backend>

Note: make sure you do change the value of the following tag inside <redis_session> tag:

From:

<db>0</db>

To:

<db>2</db>

# semanage boolean -l | grep httpd_can_network

To allow Apache to connect to the Redis server by enabling all ports:

# setsebool -P httpd_can_network_connect 1

Note: If you have turned on Security-Enhanced Linux (SELinux), httpd scripts by default are not allowed to connect out to the network.

After enabling Redis as cache backend, var/cache directory of your Magento installation can be emptied and should stay empty:

# rm -rf /var/www/html/magento19/var/cache

# ls /var/www/html/magento19/var/cache

Or Log in to the Admin Panel as an administrator. Click System > Cache Management > click Flush Magento Cache at the top of the page.

Run the redis command line tool:

# redis-cli

127.0.0.1:6379> info keyspace
127.0.0.1:6379> select 0
127.0.0.1:6379> keys *
127.0.0.1:6379> flushdb
127.0.0.1:6379> keys *

Some of the commands you’ll be using most of the time are definitely:

  • FLUSHALL – clear all databases
  • SELECT # – select database under index #
  • FLUSHDB – empty currently selected database
  • KEYS * – list all keys from currently selected

Reference:

http://inchoo.net/magento/using-redis-cache-backend-and-session-storage-in-magento/
http://www.magentocommerce.com/knowledge-base/entry/redis-magento-ce-ee

Thursday, February 26, 2015

Changing reset Magento base domain URLs

SELECT * FROM core_config_data WHERE path like '%base_url%';

SELECT * FROM core_config_data WHERE path = 'admin/url/custom';

UPDATE core_config_data SET value = 'http://domainname/' WHERE path = 'web/unsecure/base_url';

UPDATE core_config_data SET value = 'http://domainname/' WHERE path = 'web/secure/base_url';

Creating an Amazon EC2 instance

Remove SSH Host Key Pairs:

If you plan to share an AMI derived from a public AMI, remove the existing SSH host key pairs located in /etc/ssh. This forces SSH to generate new unique SSH key pairs when someone launches an instance using your AMI, improving security and reducing the likelihood of "man-in-the-middle" attacks.

You can securely remove all of these files with the following command.

# shred -u /etc/ssh/*_key /etc/ssh/*_key.pub

Restart the sshd service:

# systemctl restart sshd.service

Switch to root account:

# sudo su -

Reference:

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/building-shared-amis.html

Wednesday, February 25, 2015

To add white space before element's content?

Solution 1:

p {
  text-indent: 10px;
}


Solution 2:

use the unicode of a non breaking space.

p::before {
  content: "\00a0 ";
}

Solution 3:

p::first-letter {
  border-left: 1em solid red;
}

Tuesday, February 24, 2015

Get product information with stock quantity

Solution 1:

<?php
if (php_sapi_name() !== 'cli' || !empty($_SERVER['REMOTE_ADDR'])) {
  echo 'Must be called from the command line.';
  exit(1);
}

ini_set('max_execution_time', 28800);

require_once '/www/magento1.9.1_us/app/Mage.php';

#Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
#Mage::app();

getProductInfoArr();

function getProductInfoArr($optArr = array()) {
  $outArr = array();

  $collection = Mage::getModel('catalog/product')
    ->getCollection()
    #->addAttributeToSelect('*')
    ->addAttributeToSelect(array('id', 'sku'))
    ->joinTable(
      array('s' => 'cataloginventory/stock_item'),
      'product_id = entity_id',
      array('qty' => 'qty'), // array('field_name_alias' => 'field_name') // Make sure you do use lower case for the alias.
      '{{table}}.stock_id = 1',
      'inner'
    )
    ->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
    ->load();

  #echo '<pre>' . $collection->getSelect()->__toString() . '</pre>';

  foreach ($collection as $prodObj) {
    #echo '<pre>' . print_r($prodObj->debug(), TRUE) . '</pre>';

    $outArr[$prodObj->getSku()] = array(
      'itemId' => $prodObj->getId(),
      'itemQty' => (int) $prodObj->getQty(),
    );
  }

  return $outArr;
}
?>

Solution 2:

<?php
if (php_sapi_name() !== 'cli' || !empty($_SERVER['REMOTE_ADDR'])) {
  echo 'Must be called from the command line.';
  exit(1);
}

ini_set('max_execution_time', 28800);

require_once '/www/magento1.9.1_us/app/Mage.php';

#Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
#Mage::app();

getProductInfoArr();

function getProductInfoArr($optArr = array()) {
  $outArr = array();

  $collection = Mage::getModel('catalog/product')
    ->getCollection()
    #->addAttributeToSelect('*')
    ->addAttributeToSelect(array('id', 'sku'))
    ->joinField(
      'qty',
      'cataloginventory/stock_item',
      'qty',
      'product_id = entity_id',
      '{{table}}.stock_id = 1',
      'inner'
    )
    ->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
    ->load();

  #echo '<pre>' . $collection->getSelect()->__toString() . '</pre>';

  foreach ($collection as $prodObj) {
    #echo '<pre>' . print_r($prodObj->debug(), TRUE) . '</pre>';

    $outArr[$prodObj->getSku()] = array(
      'itemId' => $prodObj->getId(),
      'itemQty' => (int) $prodObj->getQty(),
    );
  }

  return $outArr;
}
?>

update product stock programmatically through command line in Magento

SQL:

SELECT * FROM cataloginventory_stock_status;

SELECT * FROM cataloginventory_stock_item;

Code:

<?php
if (php_sapi_name() !== 'cli' || !empty($_SERVER['REMOTE_ADDR'])) {
  echo 'Must be called from the command line.';
  exit(1);
}

ini_set('max_execution_time', 28800);

require_once '/www/magento1.9.1/app/Mage.php';

#Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
#Mage::app();

$prodId = 1;
$prodQty = 105;

$updateStockByProductId = updateStockByProductId($prodId, $prodQty);

if ($updateStockByProductId === TRUE) {
  echo 'Yes';
}
else {
  echo 'No';
}

function myUpdateStockByProductId($itemId, $itemQty) {
  $itemId = (int) $itemId;
  $itemQty = (int) $itemQty;

  $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($itemId);

  if (!$stockItem->getId()) {
    $stockItem->setData('product_id', $itemId);
    $stockItem->setData('stock_id', 1);
  }

  if ($stockItem->getId() > 0) {
    $stockItem->setData('use_config_manage_stock', 1);
    $stockItem->setData('manage_stock', 1);
    $stockItem->setData('qty', $itemQty);
    $stockItem->setData('is_in_stock', ($itemQty > 0 ? 1 : 0));
    $stockItem->save();

    if ($stockItem->getQty() === $itemQty) {
      return TRUE;
    }
  }

  return FALSE;
}
?>

Programmatically creating importing simple product

To add import Magento simple products programmatically:

The following script will create import the product with image, price, weight, description, related products, categories, inventory and more information.

<?php
if (php_sapi_name() !== 'cli' || !empty($_SERVER['REMOTE_ADDR'])) {
  echo "Must be called from the command line.";
  exit(1);
}

ini_set('max_execution_time', 28800);

require_once '/www/magento1.9.1/app/Mage.php';

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
#Mage::app();

importCar();

function importCar() {
  $carSizeArr = array_flip(myGetAttributeOptionArr('car_size'));
  $carColorArr = array_flip(myGetAttributeOptionArr('car_color'));

  $rowArr = explode("\n", file_get_contents('data_car.txt'));

  $count = 0;

  foreach ($rowArr as $row) {
    if (empty($row)) {
      continue;
    }

    list($itemName, $itemNum, $weight, $price, $size, $color) = explode("\t", $row);

    $itemImage = '/www/magento1.9.1/skin/frontend/my/default/images/items/3char/' . $itemNum . '.png';

    if (empty($carSizeArr[$size])) {
      echo '[ERROR] ' . $size . ' no such size.' . PHP_EOL;
      continue;
    }

    if (empty($carColorArr[$color])) {
      echo '[ERROR] ' . $color . ' no such color.' . PHP_EOL;
      continue;
    }

    if (file_exists($itemImage) !== TRUE) {
      echo '[ERROR] ' . $itemImage . ' not exist.' . $itemName . PHP_EOL;
      continue;
    }

    $sizeId = $carSizeArr[$size];
    $colorId = $carColorArr[$color];

    $prodObj = array(
      'itemNum' => $itemNum,
      'itemName' => $itemName,
      'categoryIds' => array(4, 5),
      'attributeSetId' => 9, // default is 4.
      'car_size' => $sizeId,
      'car_color' => $colorId,
      'weight' => $weight,
      'price' => $price,
      'itemImage' => $itemImage,
      'relatedLinkData' => array(
        1 => array('position' => 0),
        2 => array('position' => 0),
      ),
    );

    myAddProduct($prodObj);
    #break;

    $count++;
  }

  echo $count . ' records imported.' . PHP_EOL;
}

function myGetAttributeArrByAttributeSet($attributeSetId) {
  $attributes = Mage::getModel('catalog/product_attribute_api')->items($attributeSetId);

  foreach($attributes as $_attribute){
    print_r($_attribute);
  }
}

function myGetAttributeOptionArr($attributeCode) {
  $outArr = array();
  $optArr = Mage::getSingleton('eav/config')->getAttribute('catalog_product', $attributeCode)->getSource()->getAllOptions();

  foreach ($optArr as $val) {
    if (empty($val['value']) || empty($val['label'])) {
      continue;
    }

    $outArr[$val['value']] = $val['label'];
  }

  return $outArr;
}

function myAddProduct($prodObj) {
  try {
    $product = Mage::getModel('catalog/product');
    $product
      #->setStoreId(1) //you can set data in store scope
      ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
      ->setAttributeSetId($prodObj['attributeSetId']) //ID of a attribute set named 'default'
      ->setTypeId('simple') //product type
      ->setCreatedAt(strtotime('now')) //product creation time
      #->setUpdatedAt(strtotime('now')) //product update time
      ->setSku($prodObj['itemNum']) //SKU
      ->setName($prodObj['itemName']) //product name
      ->setWeight($prodObj['weight'])
      ->setStatus(1) //product status (1 - enabled, 2 - disabled)
      ->setTaxClassId(2) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
      ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
      #->setManufacturer(28) //manufacturer id
      #->setColor(24)
      #->setNewsFromDate(strtotime('now')) //product set as new from
      #->setNewsToDate('06/30/2015') //product set as new to
      #->setCountryOfManufacture('AF') //country of manufacture (2-letter country code)
      ->setPrice($prodObj['price']) //price in form 11.22
      #->setCost(22.33) //price in form 11.22
      #->setSpecialPrice(3.44) //special price in form 11.22
      #->setSpecialFromDate(strtotime('now')) //special price from (MM-DD-YYYY)
      #->setSpecialToDate('06/30/2015') //special price to (MM-DD-YYYY)
      #->setMsrpEnabled(1) //enable MAP
      #->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
      #->setMsrp(99.99) //Manufacturer's Suggested Retail Price
      #->setMetaTitle('test meta title')
      #->setMetaKeyword('testproduct')
      #->setMetaDescription('test meta description')
      ->setDescription($prodObj['itemName'])
      ->setShortDescription($prodObj['itemName'])
      ->setMediaGallery (array('images'=>array (), 'values'=>array ())) //media gallery initialization
      ->addImageToMediaGallery($prodObj['itemImage'], array('image','thumbnail','small_image'), false, false) //assigning image, thumb and small image to media gallery
      ->setStockData(array(
          'use_config_manage_stock' => 1, //'Use config settings' checkbox
          'manage_stock'=>1, //manage stock
          #'min_sale_qty'=>1, //Minimum Qty Allowed in Shopping Cart
          #'max_sale_qty'=>2, //Maximum Qty Allowed in Shopping Cart
          'is_in_stock' => 1, //Stock Availability
          'qty' => 100, //qty
      ))
      ->setCategoryIds($prodObj['categoryIds']) //assign product to categories
      ->setRelatedLinkData($prodObj['relatedLinkData']) // related products
      ;
    $product->save();

    if (isset($prodObj['walker_size'], $prodObj['walker_color']) && is_numeric($prodObj['walker_size']) && is_numeric($prodObj['walker_color'])) {
      $product->setData('car_size', $prodObj['car_size'])->getResource()->saveAttribute($product, 'car_size');
      $product->setData('car_color', $prodObj['car_color'])->getResource()->saveAttribute($product, 'car_color');
    }
  }
  catch (Exception $e) {
    Mage::log($e->getMessage());
  }
}
?>

Reference:

http://inchoo.net/magento/programming-magento/programatically-manually-creating-simple-magento-product/
http://www.magentogeek.com/create-a-simple-product-magento-programmatically/

magento set store id programatically

$store_id = 'your_store_id_here';
$mageRunCode = 'store view code';
$mageRunType = 'store';

Mage::app()->setCurrentStore($store_id);
Mage::run($mageRunCode, $mageRunType);

Reference:

http://stackoverflow.com/questions/9870417/magento-set-store-id-programatically

Monday, February 23, 2015

set up color prompt in csh tcsh on FreeBSD

# vim ~/.cshrc

  set colorRed = "%{\033[0;31m%}"
  set colorGreen = "%{\033[0;32m%}"
  set colorGreenBold = "%{\033[1;32m%}"
  set colorYellow = "%{\033[0;33m%}"
  set colorBlue = "%{\033[0;34m%}"
  set colorMagenta = "%{\033[0;35m%}"
  set colorCyan = "%{\033[0;36m%}"
  set colorWhite = "%{\033[0;37m%}"
  set colorEnd = "%{\033[0m%}" # This is needed at the end.

  ### default prompt
  #set prompt = "%n@%m:%/ %# "

  ### color prompt
  set prompt = "${colorBlue}%n${colorCyan}@%m ${colorCyan}%/ %#${colorEnd} "

  set promptchars = "%#"

  # Clean up after ourselves...
  unset colorRed colorGreen colorGreenBold colorYellow colorBlue colorMagenta colorCyan colorWhite colorEnd

%n
  The username.

%m
  The hostname up to the first . dot.

%/
  The current working directory.

%~
  The current working directory, but with one's home directory represented by `~' and other users' home directories represented by `~user' as per Filename substitution. `~user' substi- tution happens only if the shell has already used `~user' in a pathname in the current ses- sion.

%#
  A `#' if the shell is running  with  privileges,  a `%' if not.

Reference:
http://www.cs.umd.edu/~srhuang/teaching/code_snippets/prompt_color.tcsh.html
http://www.nparikh.org/unix/prompt.php

csh tcsh prompt option variable

Shell prompts are extremely customizable. You can customize them in two ways: (1) by using command characters that print out special things and (2) by using colors. Also, customizing the prompt is different in different shells; I'm going to cover tcsh and zsh here. bash is the other popular shell, but I think it sucks, and I never use it, so I'm not going to waste any time on it.
tcsh
I'll start with tcsh, since it's the default BSD and Mac OS X shell. Here's a very simple prompt:
hostname%
That prompt is created with the following command:
setenv PROMPT '%m%# '
The %m is called a formatting sequence, and it is expanded to the hostname of your computer when tcsh outputs your prompt. Similarly, %# equals '>' (or the first character of thepromptchars shell variable) if you're a normal user, or '#' (or the second character of promptchars) if you're root. Any letter with a % before it will be treated as a formatting sequence, so if you want to print a % sign, use %%. (Quick side note: you want the extra space at the end, or else the input will be squashed up against the prompt, and it's ugly and hard to read.) A popular prompt is the following:
Formatted: 
[user@hostname:/current/path]% 


Code
[%n@%m:%c]%#
%n is the username and %c is the current path. Instead of going through millions of examples illustrating all the different kinds of prompts you can have, I'm just going to include the complete list of formatting sequences from the tcsh(1) manpage:
%/  The current working directory.
%~  The  current working directory, but with one's
   home directory represented by  `~'  and  other
   users' home directories represented by `~user'
   as per Filename substitution.  `~user' substi-
   tution  happens  only if the shell has already
   used `~user' in a pathname in the current ses-
   sion.
%c[[0]n], %.[[0]n]
   The  trailing component of the current working
   directory, or n trailing components if a digit
   n  is given.  If n begins with `0', the number
   of skipped  components  precede  the  trailing
   component(s)  in  the format `/trail-
   ing'.  If the ellipsis shell variable is  set,
   skipped   components  are  represented  by  an
   ellipsis so the whole  becomes  `...trailing'.
   `~' substitution is done as in `%~' above, but
   the `~' component  is  ignored  when  counting
   trailing components.
%C  Like %c, but without `~' substitution.
%h, %!, !
   The current history event number.
%M  The full hostname (e.g. jaguar.apple.com).
%m  The hostname up to the first `.' (e.g. jaguar).
%S (%s)
   Start (stop) standout (reverse) mode.
%B (%b)
   Start (stop) boldfacing mode.
%U (%u)
   Start (stop) underline mode.
%t, %@
   The time of day in 12-hour AM/PM format.
%T  Like  `%t', but in 24-hour format (but see the
   ampm shell variable).
%p  The `precise' time of  day  in  12-hour  AM/PM
   format, with seconds.
%P  Like  `%p', but in 24-hour format (but see the
   ampm shell variable).
\c  c is parsed as in bindkey.
^c  c is parsed as in bindkey.
%%  A single `%'.
%n  The user name.
%d  The weekday in `Day' format.
%D  The day in `dd' format.
%w  The month in `Mon' format.
%W  The month in `mm' format.
%y  The year in `yy' format.
%Y  The year in `yyyy' format.
%l  The shell's tty.
%L  Clears from the end of the prompt  to  end  of
   the display or the end of the line.
%$  Expands the shell or environment variable name
   immediately after the `$'.
%#  `>' (or the first character of the promptchars
   shell  variable) for normal users, `#' (or the
   second character of promptchars) for the supe-
   ruser.
%{string%}
   Includes  string as a literal escape sequence.
   It should be  used  only  to  change  terminal
   attributes  and  should  not  move  the cursor
   location.  This cannot be the last sequence in
   prompt.
%?  The  return  code of the command executed just
   before the prompt.
%R  In prompt2, the  status  of  the  parser.   In
   prompt3,  the  corrected  string.  In history,
   the history string.
Next, on to color. This directly builds on the previous section by adding color escape sequences to the formatting sequences you can use. The following code colors the hostname red:
%{\033[31m%}%m%{\033[0m%}
The '31' and the %m have been bolded above because those are the only things you change. The 31 is the color code, and the %m is obviously where you put whatever you want to color. The rest of it is the same for every color coding; the beginning starts coloring, and the stuff afterwards stops coloring ('0' switches it back to default text color). You can use the following color codes:
30 - black
31 - red
32 - green
33 - yellow
34 - blue
35 - magenta
36 - cyan
37 - white
Not quite the same as a full Photoshop palette, but you can make a pretty nice prompt with it. Also, you can modify it further by including another control char:
%{\033[1;31m%}%m%{\033[0m%}
In this case, the '1' will make the following color bold. You can use the following modifiers:
0 - normal
1 - bold
2 - normal again
3 - background color
4 - underline the text
5 - blinking
You can also specify both a foreground and a background color. Use the following syntax to get (fairly hideous looking) Christmas colors:
%{\033[2;41;32m%}%m%{\033[0m%}
The '41' is the background color, and the '31' is the foreground color. The background color codes are the same as the foreground color codes, except they're 40-47 instead of 30-37.
Finally, you can also have a right-justified prompt. This is stored in the RPROMPT variable, and formatted in exactly the same way as PROMPT. People often like putting the time (%p) in RPROMPT.

zsh
zsh is customized in an extremely similar way. You still use formatting sequences, although some of them are a little different. The color codes are the same, although the color escape sequence is a little different. Other than that, it's pretty easy to move back and forth between a zsh and a tcsh prompt. The formatting sequences are the following (from zshmisc(1)):
%%     A `%'.

%)     A `)'.

%d
%/     Present  working  directory  ($PWD).  If an integer
   follows the `%', it specifies a number of  trailing
   components  of  $PWD  to show; zero means the whole
   path.  A negative integer specifies leading  compo-
   nents, i.e. %-1d specifies the first component.

%~     As  %d and %/, but if $PWD has a named directory as
   its prefix, that part is replaced by a `~' followed
   by  the  name  of the directory.  If it starts with
   $HOME, that part is replaced by a `~'.

%h
%!     Current history event number.

%L     The current value of $SHLVL.

%M     The full machine hostname.

%m     The hostname up to the first `.'.  An  integer  may
   follow  the  `%'  to specify how many components of
   the hostname are desired.  With a negative integer,
   trailing components of the hostname are shown.

%S (%s)
   Start (stop) standout mode.

%U (%u)
   Start (stop) underline mode.

%B (%b)
   Start (stop) boldface mode.

%t
%@     Current time of day, in 12-hour, am/pm format.

%T     Current time of day, in 24-hour format.

%*     Current  time  of  day in 24-hour format, with sec-
   onds.

%n     $USERNAME.

%N     The name of the  script,  sourced  file,  or  shell
   function that zsh is currently executing, whichever
   was started most recently.  If there is none,  this
   is  equivalent to the parameter $0.  An integer may
   follow the `%' to specify a number of trailing path
   components  to  show;  zero means the full path.  A
   negative integer specifies leading components.

%i     The line number currently  being  executed  in  the
   script,  sourced  file,  or shell function given by
   %N.  This is most useful for debugging as  part  of
   $PS4.

%w     The date in day-dd format.

%W     The date in mm/dd/yy format.

%D     The date in yy-mm-dd format.

%D{string}
   string  is  formatted  using the strftime function.
   See strftime(3) for more details.  Three additional
   codes  are  available:   %f  prints  the day of the
   month, like %e but without any preceding  space  if
   the  day is a single digit, and %K/%L correspond to
   %k/%l for the hour of the day (24/12 hour clock) in
   the same way.

%l     The  line  (tty)  the  user is logged in on without
   /dev/ prefix.  If name starts with /dev/tty this is
   stripped.

%y     The  line  (tty)  the  user is logged in on without
   /dev/ prefix.  It does  not  treat  /dev/tty*  spe-
   cially.

%?     The  return  code of the last command executed just
   before the prompt.

%_     The status of the parser, i.e. the shell constructs
   (like `if' and `for') that have been started on the
   command line. If given an integer number that  many
   strings  will  be  printed;  zero or negative or no
   integer means print as many as there are.  This  is
   most  useful  in prompts PS2 for continuation lines
   and PS4 for debugging with the  XTRACE  option;  in
   the  latter  case  it  will  also work non-interac-
   tively.

%E     Clears to end of line.

%#     A `#' if the shell is running  with  privileges,  a
   `%'  if not.  Equivalent to `%(!.#.%%)'.  The defi-
   nition of `privileged', for these purposes, is that
   either  the  effective  user  ID  is  zero,  or, if
   POSIX.1e capabilities are supported, that at  least
   one capability is raised in either the Effective or
   Inheritable capability vectors.

%v     The value of the first element of the  psvar  array
   parameter.  Following the `%' with an integer gives
   that element of the array.  Negative integers count
   from the end of the array.

%{...%}
   Include a string as a literal escape sequence.  The
   string within the braces should not change the cur-
   sor position.  Brace pairs can nest.

%(x.true-text.false-text)
   Specifies a ternary expression.  The character fol-
   lowing the x is arbitrary; the  same  character  is
   used  to  separate  the  text for the `true' result
   from that for the `false' result.   This  separator
   may  not appear in the true-text, except as part of
   a %-escape sequence.   A  `)'  may  appear  in  the
   false-text  as  `%)'.  true-text and false-text may
   both contain arbitrarily-nested  escape  sequences,
   including further ternary expressions.

   The left parenthesis may be preceded or followed by
   a positive integer n, which defaults  to  zero.   A
   negative  integer  will  be  multiplied by -1.  The
   test character x may be any of the following:

   c
   .
   ~      True  if  the  current  path,  with   prefix
    replacement, has at least n elements.
   /
   C      True  if  the  current  absolute path has at
    least n elements.
   t      True if the time in minutes is equal to n.
   T      True if the time in hours is equal to n.
   d      True if the day of the month is equal to  n.
   D      True  if  the month is equal to n (January =
    0).
   w      True if the day of the week is  equal  to  n
    (Sunday = 0).
   ?      True  if the exit status of the last command
    was n.
   #      True if the effective  uid  of  the  current
    process is n.
   g      True  if  the  effective  gid of the current
    process is n.
   l      True if at least n characters  have  already
    been printed on the current line.
   L      True if the SHLVL parameter is at least n.
   S      True if the SECONDS parameter is at least n.
   v      True if the array psvar has at least n  ele-
    ments.
   _      True  if  at  least  n shell constructs were
    started.
   !      True if the shell  is  running  with  privi-
    leges.

%string>
%[xstring]
   Specifies truncation behaviour for the remainder of
   the prompt string.  The third, deprecated, form  is
   equivalent  to  `%xstringx',  i.e.  x may be `<' or
   `>'.  The numeric argument, which in the third form
   may appear immediately after the `[', specifies the
   maximum permitted length  of  the  various  strings
   that  can  be  displayed in the prompt.  The string
   will be displayed in place of the truncated portion
   of  any  string;  note this does not undergo prompt
   expansion.

   The forms with `<' truncate  at  the  left  of  the
   string,  and  the  forms  with  `>' truncate at the
   right of the string.  For example, if  the  current
   directory  is  `/home/pike',  the prompt `%8<..<%/'
   will expand to `..e/pike'.   In  this  string,  the
   terminating character (`<', `>' or `]'), or in fact
   any character, may be quoted by  a  preceding  `\';
   note  when  using print -P, however, that this must
   be doubled as the string is also subject  to  stan-
   dard  print  processing,  in  addition to any back-
   slashes removed by a  double  quoted  string:   the
   worst case is therefore `print -P "%<\\\\<<..."'.

   If  the string is longer than the specified trunca-
   tion length, it will  appear  in  full,  completely
   replacing the truncated string.

   The  part of the prompt string to be truncated runs
   to the end of the string, or to the end of the next
   enclosing  group  of  the `%(' construct, or to the
   next truncation encountered at  the  same  grouping
   level  (i.e.  truncations  inside  a `%(' are sepa-
   rate), which ever comes first.   In  particular,  a
   truncation  with  argument  zero (e.g. `%<<') marks
   the end of the range of the string to be  truncated
   while  turning  off  truncation  from there on. For
   example, the prompt '%10<...<%~%<<%# ' will print a
   truncated  representation of the current directory,
   followed by a `%' or  `#',  followed  by  a  space.
   Without  the  `%<<',  those two characters would be
   included in the string to be truncated.

%c
%.
%C     Trailing component of $PWD.  An integer may  follow
   the  `%'  to  get  more than one component.  Unless
   `%C' is used, tilde contraction is performed first.
   These are deprecated as %c and %C are equivalent to
   %1~ and %1/, respectively, while explicit  positive
   integers have the same effect as for the latter two
   sequences.
As you can likely tell, zsh has some absurdly powerful prompt characters, but reasonably simple prompts are extremely similar to their tcsh counterparts:
tcsh:
[%n@%m:%c]%#

zsh:
[%n@%m:%/]%#
Not such a huge difference. The color sequence is slightly different, so use this kind of formatting:
%{\e[0;31m%}%m%{\e[0m%}

Again, the bold parts are the parts you edit. Also, you can customize RPROMPT in the same way.

http://www.nparikh.org/unix/prompt.php

To get the total quantity of all the items in your cart

To get the total quantity of all the items in your cart:

echo Mage::getModel('checkout/cart')->getQuote()->getItemsQty();

To get the total number of items in your cart:

echo Mage::getModel('checkout/cart')->getQuote()->getItemsCount();

Sunday, February 22, 2015

PHP get exit code status of a command execution

Solution 1:

<?php
$cmd = 'ls -lpas';

# Execute the shell command
$shellOutput = shell_exec($cmd . ' > /dev/null; echo $?');

# Return execute status;
echo trim($shellOutput); 
?>

Solution 2:

$cmd = 'echo hi';
my_runShellCmd($cmd);

function my_runShellCmd($cmd) {
  return trim(shell_exec($cmd . ' > /dev/null; echo $?')) === '0' ? TRUE : FALSE;
}

to alias a function with a different name in PHP

Solution 1:

function AliasFunctionName($optArr = array())  {
  OriginalFunctionName($optArr);
}

Solution 2 (PHP 5.3+):

If you are worried about having to change AliasFunctionName() should you change the number of parameters for OriginalFunctionName() then you might want to do the following instead:

function AliasFunctionName() { 
  return call_user_func_array('OriginalFunctionName', func_get_args());
}

Solution 3 (PHP 5.6+):

use function OriginalFunctionName as AliasFunctionName;

Reference:

http://stackoverflow.com/questions/1688711/can-we-alias-a-function-in-php

Saturday, February 21, 2015

move cursor to the beginning of the selected text in visual mode

To the beginning of the selected text:

`<

To the end of the selected text:

`>

For example:

vmap ,s :call MyFunction()<CR>`<

To temporarily disable auto convert tab to spaces in Vim

: set noexpandtab

Friday, February 20, 2015

Preventing SQL injection when using MySQL query directly

Okay, researched this one a little bit. If you can get an instance of a DB_Adapter (which I believe that resource call will return), this shouldn't be too tough. Deep down inside, Magento is based on Zend Framework, and the DB adapter specifically is descended from Zend_Db_Adapter, so you can use those methods for free. See the link before for more examples, but here's the syntax provided in the docs, which should escape your input automagically:

$write = Mage::getSingleton("core/resource")->getConnection("core_write");

// Concatenated with . for readability
$query = "insert into mage_example "
       . "(name, email, company, description, status, date) values "
       . "(:name, :email, :company, :desc, 0, NOW())";

$binds = array(
    'name'    => "name' or 1=1",
    'email'   => "email",
    'company' => "company",
    'desc'    => "desc",
);
$write->query($query, $binds);

Reference:

http://stackoverflow.com/questions/3575160/using-magento-methods-to-write-insert-queries-with-care-for-sql-injection
http://www.framework.zend.com/manual/en/zend.db.adapter.html

Form action Add to Cart Product URL in Magento

Solution 1:

$_productId = '166';
$_product = Mage::getModel('catalog/product')->load($_productId);
$_url = $this->getSubmitUrl($_product);

Solution 2:

$_productId = '166';
$_product = Mage::getModel('catalog/product')->load($_productId);
$_url = Mage::helper('checkout/cart')->getAddUrl($_product);

Thursday, February 19, 2015

Show product description on cart page in Magento

app/design/frontend/my/default/template/checkout/cart/item/default.phtml

Solution 1:

<?php 
$_itemObj = Mage::getModel('catalog/product')->load($_item->getProductId());
echo $this->htmlEscape($_itemObj->getShortDescription());
?>

Solution 2:

<?php echo $this->htmlEscape( Mage::getModel('catalog/product')->load($_item->getProductId())->getShortDescription() ); ?>

Magento Add to cart formkey

Method 1:

echo $this->getBlockHtml('formkey'); // show a form hidden input field.

echo htmlspecialchars($this->getBlockHtml('formkey'));

Method 2:

$_formKey = Mage::getSingleton('core/session')->getFormKey();

echo '<input name="form_key" type="hidden" value="' . $_formKey . '">';

Wednesday, February 18, 2015

FileZilla sftp/scp fails at connection, but ssh is OK.

FileZilla sftp/scp fails at connection, but ssh is OK.

Status: Connecting to 192.168.6.9...
Status: Connected to 192.168.6.9
Error: Connection timed out
Error: Could not connect to server

sftp and/or scp may fail at connection time if you have shell initialization (.profile, .bashrc, .cshrc, etc) which produces output for non-interactive sessions. This output confuses the sftp/scp client. You can verify if your shell is doing this by executing:

# ssh yourhost /usr/bin/true

If the above command produces any output, then you need to modify your shell initialization.

The reason why this issue occurred was because I have a command that will output a string. The script has been fixed:

######
# start up ssh-agent automatically when a new bash session starts.
# Note: the reason why I added -n "$SSH_TTY" is because without it, sftp and/or scp may fail at connection time if you have shell initialization (.profile, .bashrc, .cshrc, etc) which produces output for non-interactive sessions. This output confuses the sftp/scp client.
# Note: the other way: if [ -z "$SSH_AUTH_SOCK" -a -x "$SSHAGENT" ]; then
######
SSHAGENT=/usr/bin/ssh-agent
SSHAGENTARGS="-s"

if [[ -z "$SSH_AUTH_SOCK" && -n "$SSH_TTY" && -a "$SSHAGENT" && -x "$SSHAGENT" ]]; then
  eval `$SSHAGENT $SSHAGENTARGS`
  trap "kill $SSH_AGENT_PID" 0
fi

http://www.openssh.com/faq.html#2.9
http://serverfault.com/questions/485487/use-bashrc-without-breaking-sftp
http://blog.killtheradio.net/how-tos/ssh-agent-on-cygwin/

Tuesday, February 17, 2015

20 Linux YUM (Yellowdog Updater, Modified) Commands for Package Management

20 Linux YUM (Yellowdog Updater, Modified) Commands for Package Management

In this article, we will learn how to install, update, remove, find packages, manage packages and repositories on Linux systems using YUM (Yellowdog Updater Modified) tool developed by RedHat. The example commands shown in this article are practically tested on our CentOS 6.3 server, you can use these material for study purpose, certifications or just to explore ways to install new packages and keep your system up-to-date. The basic requirement of this article is, you must have a basic understanding of commands and a working Linux operating system, where you can explore and practice all the commands listed below.

What is YUM?

YUM (Yellowdog Updater Modified) is an open source command-line as well as graphical based package management tool for RPM (RedHat Package Manager) based Linux systems. It allows users and system administrator to easily install, update, remove or search software packages on a systems. It was developed and released by Seth Vidal under GPL (General Public License) as an open source, means anyone can allowed to download and access the code to fix bugs and develop customized packages. YUM uses numerous third party repositories to install packages automatically by resolving their dependencies issues.

1. Install a Package with YUM

To install a package called Firefox 14, just run the below command it will automatically find and install all required dependencies for Firefox.

# yum install firefox
Loaded plugins: fastestmirror
Dependencies Resolved

================================================================================================
 Package                    Arch        Version                    Repository            Size        
================================================================================================
Updating:
firefox                        i686        10.0.6-1.el6.centos     updates             20 M
Updating for dependencies:
 xulrunner                     i686        10.0.6-1.el6.centos     updates             12 M

Transaction Summary
================================================================================================
Install       0 Package(s)
Upgrade       2 Package(s)

Total download size: 32 M
Is this ok [y/N]: y
Downloading Packages:
(1/2): firefox-10.0.6-1.el6.centos.i686.rpm                                |  20 MB   01:10
(2/2): xulrunner-10.0.6-1.el6.centos.i686.rpm                              |  12 MB   00:52
------------------------------------------------------------------------------------------------
Total                                                           63 kB/s |  32 MB   02:04

Updated:
  firefox.i686 0:10.0.6-1.el6.centos

Dependency Updated:
  xulrunner.i686 0:10.0.6-1.el6.centos

Complete!

The above command will ask confirmation before installing any package on your system. If you want to install packages automatically without asking any confirmation, use option -y as shown in below example.

# yum -y install firefox

2. Removing a Package with YUM

To remove a package completely with their all dependencies, just run the following command as shown below.

# yum remove firefox
Loaded plugins: fastestmirror
Setting up Remove Process
Resolving Dependencies
--> Running transaction check
---> Package firefox.i686 0:10.0.6-1.el6.centos set to be erased
--> Finished Dependency Resolution

Dependencies Resolved

====================================================================================================
 Package                    Arch        Version                        Repository            Size        
====================================================================================================
Removing:
 firefox                    i686        10.0.6-1.el6.centos            @updates              23 M

Transaction Summary
====================================================================================================
Remove        1 Package(s)
Reinstall     0 Package(s)
Downgrade     0 Package(s)

Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Erasing        : firefox-10.0.6-1.el6.centos.i686                                                                                                                          1/1

Removed:
  firefox.i686 0:10.0.6-1.el6.centos

Complete!

Same way the above command will ask confirmation before removing a package. To disable confirmation prompt just add option -y as shown in below.

# yum -y remove firefox

3. Updating a Package using YUM

Let’s say you have outdated version of MySQL package and you want to update it to the latest stable version. Just run the following command it will automatically resolves all dependencies issues and install them.

# yum update mysql
Loaded plugins: fastestmirror
Dependencies Resolved

============================================================================================================
 Package            Arch                Version                    Repository                    Size
============================================================================================================
Updating:
 vsftpd             i386                2.0.5-24.el5_8.1           updates                       144 k

Transaction Summary
============================================================================================================
Install       0 Package(s)
Upgrade       1 Package(s)

Total size: 144 k
Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Updating       : vsftpd                                                                     1/2
  Cleanup        : vsftpd                                                                     2/2

Updated:
  vsftpd.i386 0:2.0.5-24.el5_8.1

Complete!

4. List a Package using YUM

Use the list function to search for the specific package with name. For example to search for a package called openssh, use the command.

# yum list openssh
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.neu.edu.cn
 * epel: mirror.neu.edu.cn
 * extras: mirror.neu.edu.cn
 * rpmforge: mirror.nl.leaseweb.net
 * updates: mirror.nus.edu.sg
Installed Packages
openssh.i386                                       4.3p2-72.el5_6.3                                                                      installed
Available Packages                                 4.3p2-82.el5                                                                          base

To make your search more accurate, define package name with their version, in case you know. For example to search for a specific version openssh-4.3p2 of the package, use the command.

# yum list openssh-4.3p2

5. Search for a Package using YUM

If you don’t remember the exact name of the package, then use search function to search all the available packages to match the name of the package you specified. For example, to search all the packages that matches the word .

# yum search vsftpd
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.neu.edu.cn
 * epel: mirror.neu.edu.cn
 * extras: mirror.neu.edu.cn
 * rpmforge: mirror.nl.leaseweb.net
 * updates: ftp.iitm.ac.in
============================== Matched: vsftpd ========================
ccze.i386 : A robust log colorizer
pure-ftpd-selinux.i386 : SELinux support for Pure-FTPD
vsftpd.i386 : vsftpd - Very Secure Ftp Daemon

6. Get Information of a Package using YUM

Say you would like to know information of a package before installing it. To get information of a package just issue the below command.

# yum info firefox
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.neu.edu.cn
 * epel: mirror.neu.edu.cn
 * extras: mirror.neu.edu.cn
 * rpmforge: mirror.nl.leaseweb.net
 * updates: ftp.iitm.ac.in
Available Packages
Name       : firefox
Arch       : i386
Version    : 10.0.6
Release    : 1.el5.centos
Size       : 20 M
Repo       : updates
Summary    : Mozilla Firefox Web browser
URL        : http://www.mozilla.org/projects/firefox/
License    : MPLv1.1 or GPLv2+ or LGPLv2+
Description: Mozilla Firefox is an open-source web browser, designed for standards
           : compliance, performance and portability.

7. List all Available Packages using YUM

To list all the available packages in the Yum database, use the below command.

# yum list | less

8. List all Installed Packages using YUM

To list all the installed packages on a system, just issue below command, it will display all the installed packages.

# yum list installed | less

9. Yum Provides Function

Yum provides function is used to find which package a specific file belongs to. For example, if you would like to know the name of the package that has the /etc/httpd/conf/httpd.conf.

# yum provides /etc/httpd/conf/httpd.conf
Loaded plugins: fastestmirror
httpd-2.2.3-63.el5.centos.i386 : Apache HTTP Server
Repo        : base
Matched from:
Filename    : /etc/httpd/conf/httpd.conf

httpd-2.2.3-63.el5.centos.1.i386 : Apache HTTP Server
Repo        : updates
Matched from:
Filename    : /etc/httpd/conf/httpd.conf

httpd-2.2.3-65.el5.centos.i386 : Apache HTTP Server
Repo        : updates
Matched from:
Filename    : /etc/httpd/conf/httpd.conf

httpd-2.2.3-53.el5.centos.1.i386 : Apache HTTP Server
Repo        : installed
Matched from:
Other       : Provides-match: /etc/httpd/conf/httpd.conf

10. Check for Available Updates using Yum

To find how many of installed packages on your system have updates available, to check use the following command.

# yum check-update

11. Update System using Yum

To keep your system up-to-date with all security and binary package updates, run the following command. It will install all latest patches and security updates to your system.

# yum update

12. List all available Group Packages

In Linux, number of packages are bundled to particular group. Instead of installing individual packages with yum, you can install particular group that will install all the related packages that belongs to the group. For example to list all the available groups, just issue following command.

# yum grouplist
Installed Groups:
   Administration Tools
   DNS Name Server
   Dialup Networking Support
   Editors
   Engineering and Scientific
   FTP Server
   Graphics
   Java Development
   Legacy Network Server
Available Groups:
   Authoring and Publishing
   Base
   Beagle
   Cluster Storage
   Clustering
   Development Libraries
   Development Tools
   Eclipse
   Educational Software
   KDE (K Desktop Environment)
   KDE Software Development

13. Install a Group Packages

To install a particular package group, we use option as groupinstall. Fore example, to install “MySQL Database“, just execute the below command.

# yum groupinstall 'MySQL Database'
Dependencies Resolved

=================================================================================================
Package        Arch      Version    Repository        Size
=================================================================================================
Updating:
 unixODBC                           i386      2.2.11-10.el5      base              290 k
Installing for dependencies:
 unixODBC-libs                      i386      2.2.11-10.el5      base              551 k

Transaction Summary
=================================================================================================
Install       1 Package(s)
Upgrade       1 Package(s)

Total size: 841 k
Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing     : unixODBC-libs 1/3
  Updating       : unixODBC         2/3
  Cleanup        : unixODBC         3/3

Dependency Installed:
  unixODBC-libs.i386 0:2.2.11-10.el5

Updated:
  unixODBC.i386 0:2.2.11-10.el5

Complete!

14. Update a Group Packages

To update any existing installed group packages, just run the following command as shown below.

# yum groupupdate 'DNS Name Server'

Dependencies Resolved
================================================================================================================
 Package   Arch         Version    Repository           Size
================================================================================================================
Updating:
 bind                           i386            30:9.3.6-20.P1.el5_8.2          updates              981 k
 bind-chroot                    i386            30:9.3.6-20.P1.el5_8.2          updates              47 k
Updating for dependencies:
 bind-libs                      i386            30:9.3.6-20.P1.el5_8.2          updates              864 k
 bind-utils                     i386            30:9.3.6-20.P1.el5_8.2          updates              174 k

Transaction Summary
================================================================================================================
Install       0 Package(s)
Upgrade       4 Package(s)

Total size: 2.0 M
Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Updating       : bind-libs            1/8
  Updating       : bind                 2/8
  Updating       : bind-chroot          3/8
  Updating       : bind-utils           4/8
  Cleanup        : bind                 5/8
  Cleanup        : bind-chroot          6/8
  Cleanup        : bind-utils           7/8
  Cleanup        : bind-libs            8/8

Updated:
  bind.i386 30:9.3.6-20.P1.el5_8.2                  bind-chroot.i386 30:9.3.6-20.P1.el5_8.2

Dependency Updated:
  bind-libs.i386 30:9.3.6-20.P1.el5_8.2             bind-utils.i386 30:9.3.6-20.P1.el5_8.2

Complete!

15. Remove a Group Packages

To delete or remove any existing installed group from the system, just use below command.

# yum groupremove 'DNS Name Server'

Dependencies Resolved

===========================================================================================================
 Package                Arch              Version                         Repository          Size
===========================================================================================================
Removing:
 bind                   i386              30:9.3.6-20.P1.el5_8.2          installed           2.1 M
 bind-chroot            i386              30:9.3.6-20.P1.el5_8.2          installed           0.0

Transaction Summary
===========================================================================================================
Remove        2 Package(s)
Reinstall     0 Package(s)
Downgrade     0 Package(s)

Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Erasing        : bind                                                   1/2
warning: /etc/sysconfig/named saved as /etc/sysconfig/named.rpmsave
  Erasing        : bind-chroot                                            2/2

Removed:
  bind.i386 30:9.3.6-20.P1.el5_8.2                                        bind-chroot.i386 30:9.3.6-20.P1.el5_8.2

Complete!

16. List Enabled Yum Repositories

To list all enabled Yum repositories in your system, use following option.

# yum repolist

repo id                     repo name                                            status
base                        CentOS-5 - Base                                      enabled:  2,725
epel                        Extra Packages for Enterprise Linux 5 - i386         enabled:  5,783
extras                      CentOS-5 - Extras                                    enabled:    282
mod-pagespeed               mod-pagespeed                                        enabled:      1
rpmforge                    RHEL 5 - RPMforge.net - dag                          enabled: 11,290
updates                     CentOS-5 - Updates                                   enabled:    743
repolist: 20,824

16. List all Enabled and Disabled Yum Repositories

The following command will display all enabled and disabled yum repositories on the system.

# yum repolist all

repo id                     repo name                                            status
C5.0-base                   CentOS-5.0 - Base                                    disabled
C5.0-centosplus             CentOS-5.0 - Plus                                    disabled
C5.0-extras                 CentOS-5.0 - Extras                                  disabled
base                        CentOS-5 - Base                                      enabled:  2,725
epel                        Extra Packages for Enterprise Linux 5 - i386         enabled:  5,783
extras                      CentOS-5 - Extras                                    enabled:    282
repolist: 20,824

17. Install a Package from Specific Repository

To install a particular package from a specific enabled or disabled repository, you must use –enablerepo option in your yum command. For example to Install PhpMyAdmin 3.5.2 package, just execute the command.

# yum --enablerepo=epel install phpmyadmin

Dependencies Resolved
=============================================================================================
 Package                Arch           Version            Repository           Size
=============================================================================================
Installing:
 phpMyAdmin             noarch         3.5.1-1.el6        epel                 4.2 M

Transaction Summary
=============================================================================================
Install       1 Package(s)

Total download size: 4.2 M
Installed size: 17 M
Is this ok [y/N]: y
Downloading Packages:
phpMyAdmin-3.5.1-1.el6.noarch.rpm                       | 4.2 MB     00:25
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : phpMyAdmin-3.5.1-1.el6.noarch             1/1
  Verifying  : phpMyAdmin-3.5.1-1.el6.noarch             1/1

Installed:
  phpMyAdmin.noarch 0:3.5.1-1.el6

Complete!

18. Interactive Yum Shell

Yum utility provides a custom shell where you can execute multiple commands.

# yum shell
Loaded plugins: fastestmirror
Setting up Yum Shell
> update httpd
Loading mirror speeds from cached hostfile
 * base: mirrors.sin3.sg.voxel.net
 * epel: ftp.riken.jp
 * extras: mirrors.sin3.sg.voxel.net
 * updates: mirrors.sin3.sg.voxel.net
Setting up Update Process
>

19. Clean Yum Cache

By default yum keeps all the repository enabled package data in /var/cache/yum/ with each sub-directory, to clean all cached files from enabled repository, you need to run the following command regularly to clean up all the cache and make sure that there is nothing unnecessary space is using. We don’t want to give the output of the below command, because we like to keep cached data as it is.

# yum clean all

20. View History of Yum

To view all the past transactions of yum command, just use the following command.

# yum history

Loaded plugins: fastestmirror
ID     | Login user               | Date and time    | Action(s)      | Altered
-------------------------------------------------------------------------------
    10 | root               | 2012-08-11 15:19 | Install        |    3
     9 | root               | 2012-08-11 15:11 | Install        |    1
     8 | root               | 2012-08-11 15:10 | Erase          |    1 EE
     7 | root               | 2012-08-10 17:44 | Install        |    1
     6 | root               | 2012-08-10 12:19 | Install        |    2
     5 | root               | 2012-08-10 12:14 | Install        |    3
     4 | root               | 2012-08-10 12:12 | I, U           |   13 E<
     3 | root               | 2012-08-09 13:01 | Install        |    1 >
     2 | root               | 2012-08-08 20:13 | I, U           |  292 EE
     1 | System            | 2012-08-08 17:15 | Install        |  560
history list

We have tried to cover all the basic to advance yum commands with their examples. If anything related to yum commands may have missed out. Please update us through our comment box. So, we keep updating the same based on feedback’s received.

Reference:

http://www.tecmint.com/20-linux-yum-yellowdog-updater-modified-commands-for-package-mangement/

Thursday, February 12, 2015

include custom library functions

We are going to create a Magento helper.

app/code/local/My/Blockgen/etc/config.xml:

<?xml version="1.0"?>
<config>
    <modules>
        <My_Blockgen>
            <version>1.0.0</version>
        </My_Blockgen>
    </modules>
    <global>
        <helpers>
            <blockgen>
                <class>My_Blockgen_Helper</class>
            </blockgen>
        </helpers>
    </global>
</config>

app/etc/modules/My_Blockgen.xml:

<?xml version="1.0"?>
<config>
    <modules>
        <My_Blockgen>
            <active>true</active>
            <codePool>local</codePool>
        </My_Blockgen>
    </modules>
</config>

app/code/local/My/Blockgen/Helper/Stdlib.php:

<?php
class My_Blockgen_Helper_Stdlib extends Mage_Core_Helper_Abstract
{
  public function sayHello()
  {
    return 'Hello World!';
  }   
}
?>

Test the function:

$helper = Mage::helper('blockgen/stdlib');
echo $helper->sayHello();

Or

echo Mage::helper('blockgen/stdlib')->sayHello();

Sort numeric and literal columns in Vim

Sort normally:

:'<,'>sort

Sort numerically:

:'<,'>sort n

Sort on second column:

:'<,'>sort -k 2
:'<,'>sort /.*\%2v/

Sort and remove duplicated lines:

:'<,'>sort u

Reference:

http://stackoverflow.com/questions/1355004/how-to-sort-numeric-and-literal-columns-in-vim

The css !important rule overrides that particular property

p {
    color: red !important;
}
#thing {
    color: green;
}

<p id="thing">Will be RED.</p>

The paragraph will be red, even though the ID selector has higher specificity. The !important rule overrides that particular property.

Reference:

http://css-tricks.com/when-using-important-is-the-right-choice/

New order email confirmation not being sent (magento 1.9.1)

In magento 1.9.1.0, magento has added new feature, they store the order email in "Core_email_queue" table to send the mail of order. we have to set the cron.php in server

The corn.php file set the "core_email_queue_send_all" in cron schedule table. when crone execute the "send" method called from Mage_Core_Model_Email_Queue. They send the mail to customer.

If your mail system(smtp, zend_mail) works fine; disabling mailQueue may solve your problem.

/app/code/core/Mage/Core/Model/Email/Template.php

Change Line 407

if ($this->hasQueue() && $this->getQueue() instanceof Mage_Core_Model_Email_Queue) {

to

if (false /\*$this->hasQueue() && $this->getQueue() instanceof Mage_Core_Model_Email_Queue\*/) {

Reference:

http://magento.stackexchange.com/questions/45571/new-order-email-confirmation-not-being-sent-magento-1-9-1

Wednesday, February 11, 2015

PHP file_put_contents is not working on CentOS Linux

When I tried to use PHP to write the debug information to the /tmp directory, I've noticed that my data was not written to the file I have specified. I was wondering why my file was not created, or it's empty. My first assumption was because of SELinux (tail -F /var/log/audit/audit.log). However, it has nothing to do with SELinux. It turned out that both Apache and PHP-FPM use a private /tmp directory. So, the location would be:

/tmp/systemd-private-<uuid>/debug1

instead of:

/tmp/debug1

Note: this is only important if you want to access the files from outside apache.

Sample PHP code:

<?php
$date = date('Y-m-d H:i:s');
$fileName = '/tmp/debug1';

echo $date;
echo "<br>\n";

$charCount = file_put_contents($fileName, 'test message ' . $date);
echo $charCount . ' characters written';
echo "<br>\n";

$str = file_get_contents($fileName);
echo $str;
echo "<br>\n";
?>

Find the debug log file:

# find /tmp -type f -mmin -500 | xargs -I {} ls -l {}

Note: if you run the sample PHP script above through command line, the debug1 would be stored in /tmp/debug1.

Note: if you run the sample PHP script above through the browser, the debug1 would be stored in /tmp/systemd-private-<uuid>/debug1.

The Private Tmp setting are defined in systemd service files:

# grep -ri 'PrivateTmp' /usr/lib/systemd/system

Reference:

http://0pointer.de/blog/projects/security.html

http://blog.oddbit.com/2012/11/05/fedora-private-tmp/

http://danwalsh.livejournal.com/51459.html

404 error Page not found when accessing the Admin login page

I have encountered the following error message:

404 error: Page not found.

Then, I looked at the system.log file:

# tail var/log/system.log

2015-02-11T18:41:01+00:00 ERR (3): Recoverable Error: Argument 1 passed to Mage_Core_Model_Store::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in /var/www/html/magento1.9.1/app/code/core/Mage/Core/Model/App.php on line 634 and defined  in /var/www/html/magento1.9.1/app/code/core/Mage/Core/Model/Store.php on line 453

2015-02-11T18:41:01+00:00 ERR (3): Recoverable Error: Argument 1 passed to Mage_Core_Model_Store_Group::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in /var/www/html/magento1.9.1/app/code/core/Mage/Core/Model/App.php on line 654 and defined  in /var/www/html/magento1.9.1/app/code/core/Mage/Core/Model/Store/Group.php on line 275

The cause of the problem turned out to be I have used Navicat to dump the MySQL database instead of the built-in mysqldump tool. When using Navicat to dump the MySQL database, it did not include the following command:

/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

Which caused some of records in some table to have the wrong data of the primary key.

You can either:

1. use the built-in mysqldump tool to dump the MySQL database again and make a restore.

2. use the following queries to update the records:

SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;

Be sure to clear your cache:

# rm -rf var/cache/*

Reference:

http://stackoverflow.com/questions/5178066/error-404-not-found-in-magento-admin-login-page

Tuesday, February 10, 2015

dbModel read resource does not implement Zend_Db_Adapter_Abstract

a:4:{i:0;s:65:"dbModel read resource does not implement Zend_Db_Adapter_Abstract";i:1;s:1555:"#0 /var/www/html/magento1.9.1/app/code/core/Mage/Core/Model/Resource/Db/Collection/Abstract.php(134): Varien_Data_Collection_Db->setConnection(false)
#1 /var/www/html/magento1.9.1/app/code/core/Mage/Core/Model/Config.php(1348): Mage_Core_Model_Resource_Db_Collection_Abstract->__construct(Object(Mage_Core_Model_Resource_Website))
#2 /var/www/html/magento1.9.1/app/code/core/Mage/Core/Model/Config.php(1380): Mage_Core_Model_Config->getModelInstance('core_resource/w...', Object(Mage_Core_Model_Resource_Website))
#3 /var/www/html/magento1.9.1/app/Mage.php(491): Mage_Core_Model_Config->getResourceModelInstance('core/website_co...', Object(Mage_Core_Model_Resource_Website))
#4 /var/www/html/magento1.9.1/app/code/core/Mage/Core/Model/Abstract.php(208): Mage::getResourceModel('core/website_co...', Object(Mage_Core_Model_Resource_Website))
#5 /var/www/html/magento1.9.1/app/code/core/Mage/Core/Model/Abstract.php(213): Mage_Core_Model_Abstract->getResourceCollection()
#6 /var/www/html/magento1.9.1/app/code/core/Mage/Core/Model/App.php(608): Mage_Core_Model_Abstract->getCollection()
#7 /var/www/html/magento1.9.1/app/code/core/Mage/Core/Model/App.php(466): Mage_Core_Model_App->_initStores()
#8 /var/www/html/magento1.9.1/app/code/core/Mage/Core/Model/App.php(349): Mage_Core_Model_App->_initCurrentStore('us_mylutionwal...', 'website')
#9 /var/www/html/magento1.9.1/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#10 /var/www/html/magento1.9.1/index.php(87): Mage::run('us_mylutionwal...', 'website')
#11 {main}";s:3:"url";s:1:"/";s:11:"script_name";s:10:"/index.php";}

The solution is to clear everything in var/cache and make sure the permission is correct:

# rm -rf /www/magento1.9.1/var/cache/*
# find /www/magento1.9.1/ | xargs -I {} chown svn:apache {}
# find /www/magento1.9.1/ -type d | xargs -I {} chmod 770 {}
# find /www/magento1.9.1/ -type f | xargs -I {} chmod 660 {}

CentOS 7 send email when hosting Drupal or Magento

Get the current SELinux setting:
# getsebool httpd_can_sendmail
# sestatus -b | grep httpd_can

Set the SELinux setting:
# setsebool httpd_can_sendmail 1
# setsebool httpd_can_network_connect 1

Set the SELinux setting (permanently):
# setsebool -P httpd_can_sendmail 1
# setsebool -P httpd_can_network_connect 1

Send a testing email:
# cat testmail
Subject: test
test

# sendmail -v yourmail@example.com < testmail

Check mail queue:
# mailq

Reference:

https://www.drupal.org/node/1593684
http://www.how2centos.com/disable-selinux-centos-6/

PayPal gateway has rejected request. The transaction was refused as a result of a duplicate invoice ID supplied.

10536 Invalid Data The transaction was refused as a result of a duplicate invoice ID supplied. Attempt with a new invoice ID.

1. Log on to https://www.sandbox.paypal.com/

2. Click on "Profile" button.

3. Under the Security and risk settings, click on "Payment receiving preferences".

4. check the "No, allow multiple payments per invoice ID" checkbox.

5. Click on "Save" button.

Reference:

https://developer.paypal.com/docs/classic/api/errorcodes/

Set the default payment method Paypal direct and hide the Paypal express method

Edit your app/design/frontend/my/default/template/checkout/onepage/payment/methods.phtml

<script>
  $j('#p_method_paypal_direct').prop('checked', 'checked');
  payment.switchMethod('paypal_direct');
  $j('#checkout-payment-method-load > dt').css('display', 'none');
</script>

There has been an error processing your request

There has been an error processing your request

Exception printing is disabled by default for security reasons.

Error log record number: 673618173351

Go to magento/var/report and open the file with the Error log record number name i.e 673618173351 in your case. In that file you can find the complete description of the error.

For log files like system.log and exception.log, go to magento/var/log/.

http://stackoverflow.com/questions/15473705/there-has-been-an-error-processing-your-request-error-log-record-number

Jquery selector for the label of a checkbox

<input type="checkbox" name="filter" id="comedyclubs"/>
<label for="comedyclubs">Comedy Clubs</label>

$("label[for='comedyclubs']")

Reference:

http://stackoverflow.com/questions/1186416/jquery-selector-for-the-label-of-a-checkbox
http://docs.jquery.com/Selectors/attributeEquals#attributevalue

Monday, February 9, 2015

Create a barcode with PHP PEAR Image_Barcode2

Create a barcode with PHP PEAR Image_Barcode2

Install PEAR Image Barcode 2 on FreeBSD
# pkg_info | grep -i pear
pear-1.9.4_1 PEAR framework for PHP

# pear install Image_Barcode2-0.2.1

# ls /usr/local/share/pear/Image
Barcode2
Barcode2.php

Code:

<?php
function _str2barcodeBase64($str) {
  include_once "Image/Barcode2.php";

  $str = empty($str) ? 'test' : $str;
  $type = 'code128';
  $imgtype = 'png';
  $bSendToBrowser = FALSE;
  $height = 15;
  $width = 2;

  $img = Image_Barcode2::draw($str, $type, $imgtype, $bSendToBrowser, $height, $width);

  ob_start();
    imagepng($img);
    $imgBase64 = base64_encode(ob_get_contents());
  ob_end_clean();

  imagedestroy($img);

  return '<img src="data:image/' . $imgtype . ';base64,' . $imgBase64 . '">';
}

?>

Reference:

http://pear.php.net/package/Image_Barcode2/

running multiple PHP process in background

Method 1:

<?php
exec('php fileName.php > /dev/null 2>&1 &');
?>

Note: If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

Method 2:

pcntl_fork()

PHP standard deviation

PHP standard deviation

Sometimes your data is only a sample of the whole population. We can still estimate the Standard Deviation. But when you use the sample as an estimate of the whole population, the Standard Deviation formula changes to this:

The important change is "N-1" instead of "N" (which is called "Bessel's correction").

<?
function standard_deviation($aValues, $bSample = FALSE) {
  $dNum = $dNumOrig = count($aValues);
  $fSum = array_sum($aValues);
  $fMean = $fSum / $dNum;
  $fVariance = 0.0;

  foreach ($aValues as $i) {
    $fVariance += pow($i - $fMean, 2);
  }

  if ($bSample) {
    $dNum -= 1;
  }

  $fVariance = (double) sqrt($fVariance / $dNum);

  return array(
    'fUCL' => $fMean + $fVariance,  // Upper Control Limit
    'fLCL' => $fMean - $fVariance,  // Lower Control Limit
    'fMean' => $fMean,  // Average
    'fSum' => $fSum,
    'dNum' => $dNumOrig,
    'fVariance' => $fVariance,
  );
}

$arr = array(9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4);
$rs = standard_deviation($arr);

foreach ($arr as $val) {
  if ($val >= $rs['fLCL'] && $val <= $rs['fUCL']) {
    echo $val . ' inside of the range.' . "\n";
  }
  else {
    echo $val . ' outside of the range.' . "\n";
  }
}
?>

Reference:

http://www.mathsisfun.com/data/standard-deviation-formulas.html
http://www.mathsisfun.com/data/standard-deviation.html

convert hex to string

<?php
$str = 'OMP60/';

echo strToHex($str);

function strToHex($string){
    $hex = '';
    for ($i=0; $i<strlen($string); $i++){
        $ord = ord($string[$i]);
        $hexCode = dechex($ord);
        $hex .= substr('0'.$hexCode, -2) . ' ';
    }
    return strToUpper($hex);
}

function hexToStr($hex){
    $string='';
    for ($i=0; $i < strlen($hex)-1; $i+=2){
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}
?>

Does file_get_contents() have a timeout setting?

The default timeout is defined by default_socket_timeout ini-setting, which is 60 seconds. You can also change it on the fly:

ini_set('default_socket_timeout', 900); // 900 Seconds = 15 Minutes

Another way, to set a timeout, would be to use stream_context_create to set the timeout as HTTP context options of the HTTP stream wrapper in use:

$ctx = stream_context_create(array('http'=>
    array(
        'timeout' => 1200, // 1 200 Seconds = 20 Minutes
    )
));

echo file_get_contents('http://example.com/', false, $ctx);

Reference:

http://stackoverflow.com/questions/10236166/does-file-get-contents-have-a-timeout-setting

高創意智商的5項能力

在寫了二十五年關於創新和創意的文章,訪問過數百位商業、設計及科技領域的領導者之後,我發現創意完全不含任何「稀有」成分,是所有人都可以培養的特質。「創意智慧」存在於多種不同的領域與專業中,也存在於生活的各個面向中。許多從來不認為自己有創意的人,其實都在用一種與音樂家或作家相仿的技能在創作。最重要的是,「創意智商」具有社會性:我們可以透過向別人學習,與別人合作及分享,來提升自己的創意能力。

我們活在一個「我不知道」的世界,無法猜到接下來將發生什麼問題,更無法預測答案。我們必須讓自己準備好去爭取目前還不存在的工作,運用還沒發明的技術,解決尚未發現的問題。

創意智商涵蓋的五項能力

知識探勘(KNOWLEDGE MINING)。創意智商所依據的知識不是制式測驗中會考的那種。今天最有創意的創業者、思想家和藝術家都能觸及對人們真正有意義的事物,而且就始於他們自己覺得有意義之處。他們了解到,對一個世代或族群重要的事物,對別的世代或族群可能無關緊要。在發展新的創意時,他們並不針對「未滿足的需要」,而是以自己的經驗與渴望,作為籌劃新公司及新技術的起點。當自己的經驗不敷使用時,他們不求助於傳統的市場調查,而是直接回到源頭,與更深入浸淫於該文化中的人合作。

創意源源不絕的人擅長以新奇的方式串連四面八方的資訊。他們知道如何遴選材料來發展創意─將不同領域的資訊結合起來,或者回過頭去發掘被遺忘的想法和做法,用以面對新的挑戰。有些人具備極深厚的領域知識,憑直覺便可知道當中缺少哪些元素。

架構(FRAMING)是一枚聚焦鏡,它引導著我們走過這瞬息萬變、光怪陸離的世界。無論你有什麼抱負,無論你屬於哪個產業,關鍵策略都是要了解自己的參考架構──了解你看世界的方式與別人有何不同。懂得架構技巧的人更能夠根據當下的情況、環境,以及與自己互動的群體,來調整自己的觀點。不過,這不表示他們會遺忘自己的抱負,或忽略那些對自己有意義的事情。相反地,他們會不斷「抽驗」,確認自己的偏見是否影響了對話,或自己的世界觀是否局限了發想更佳創意的能力。架構的概念雖源自社會學與人類學理論,但我確實看過創意人如何神乎其技地架構他們的世界與互動。

隨著一些最悠久的金融機構與企業在我們眼前分崩離析,這段時間,「架構」已成為快速適應意外變化的必備工具。例如,過去當人們想到醫療時,總是將焦點擺在治療疾病;現在,梅約診所等首屈一指的醫療機構則著重於安適。在教育界,史丹福等頂尖大學都開始利用搜尋及資訊網路傳播技術,讓學生能隨時隨地學習。

玩耍(PLAYING)不是小孩子的專利,它是一種複雜的行為,能催生出改變人類生活的技術和企業。我們在許多不同的「遊樂場」都可以發現創意,這些空間(不一定是實體空間)允許人們玩耍,建立新規則,找出各種贏的方法。海軍陸戰隊、科學家及工程師都用「玩耍」來發展致勝方案,解決有時生死攸關的難題。

許多創新圈子的人總喜歡說成就大業「需要失敗」。但為何將創意流程的一個必經步驟定義為「失敗」?如果能抱著一種玩耍的心態,我們就會更願意冒險,探索各種可能,並學習如何在不確定中穿梭自如,不會烙上失敗的印記而致無力再戰。

在現今社會中,遊戲是成長最快的社會結構。一個在多人線上遊戲中成長的世代正以他們的經驗,在金融、教育、運動、製造、醫藥、音樂及藝術等領域建立新的商業模式。許多企業發現,趣味與競爭是絕佳的動力來源,於是它們將遊戲納入員工招募流程。而或許最令人興奮的發展,是有許多機構開始實驗用遊戲來推行公益活動。

在玩遊戲以及學習有效地設計遊戲當中,人們學會如何創造新的產品和服務,以及如何建立屬於自己的一套複雜社會體系。遊戲玩家建立社群,而不只是累積顧客。遊戲是活潑、互動且引人入勝的,解法可能有無數種。對於習慣天天搜尋、等於在「搜尋」模式中成長的世代,遊戲是可用於學習的完美組織結構。

自造(MAKING)是創意智商的第四項能力。在當今全球經濟中,最令人興奮的一項改變莫過於「自造」的異軍突起。數十年來,經濟體系慣常獎勵心智敏捷的人,例如華爾街交易員、美國企業界的諮商、策略與品牌塑造顧問等等。但現在,我們正在經歷一場自造者復興運動。多虧新技術大量發明,還有創作工具的普及,譬如Photoshop、3D印表機與Behance 創意社群等等,我們開始動手做了。

「自造文化」的復興,加上開放源碼理念的普及、社群媒體銷售通路的興起,以及向DIY與在地生產靠攏的消費趨勢,都使得「自造」再次成為創新的關鍵元素。Kickstarter和Grind 等社群網站所開啟的新式創投培育模式,讓今天的新創計畫比過去更容易募得資金。

將創意從發想帶往生產面的轉進(PIVOTING)是五項能力中最後一項。傳統的創意概念將新點子的發想與新產品的製造一分為二,但真正有創意的人不止於發想,還轉進到製造過程。「轉進」將創意帶離紙上談兵的階段,打造出新的產品和事業,讓創意重新扮演起資本主義中推動創新與成長的關鍵角色。但是,該怎麼做呢?

顛覆性的創新大多出於那些懷抱理想的個人,他們激發了一群忠實的追隨者加入其社群。不過,我們在創新方面的投資並未完全反映這一點:我們多半都在協助老牌的大企業提升創意,到頭來,常只得到漸進式的創新。這麼說來,近年改變人類生活的重要創新究竟來自何處?Google、臉書、Zipcar、維基百科(Wikipedia)及Kickstarter,它們的創辦人都是個人,而非大企業。這並不代表大企業就無法創新;但如果大企業能以新創公司為師,將會有出色的創新表現。

這五項能力提供了一個新的基礎,讓我們能建立一套更有活力的經濟體制。具有這般創意智慧的人正指出一條新的商業道路,引導我們找回資本主義的初衷,而非過去數十年來以金融為主的模式。我稱它為「獨立資本主義」(Indie Capitalism),因為它並不具備一般人認為經濟應有的規範與觀念。

獨立資本主義傾向以社會而非買賣為基礎。它的核心要件是人脈網絡而非市場。它創造價值的方式是打造新事物,而非買賣舊東西。獨立資本家關心什麼對人們有意義,而非人們有何「未滿足的需要」。獨立資本主義所重視的價值從全球經濟走向地方經濟。全球化依然很重要,但就連最大的跨國企業也了解擁抱「在地」價值的必要性,例如在地方上創造就業機會,向鄰近的農場與工廠採購原料,以及打造永續的產品和服務等等。

創意智慧關乎工具,而非腦子裡的靈感燈泡。我們必須主動去做,而非等待好事發生。創意智慧不僅包括那些靈光一閃的片刻,還包括後續的行動,也就是能幫助你將點子付諸實現的勤奮工作與團隊合作。

創意可以成為稀鬆平常的例行公事,而非曇花一現的偶發事件。(摘錄整理自第二章)



快!找出你的創新產值(Creative Intelligence)

布魯斯 • 納思邦(Bruce Nussbaum)/著;譚平/譯

原點出版

售價:380元



作者簡介

布魯斯.納思邦

Bruce Nussbaum

《商業週刊》前副總編輯、得獎作家,自1990年代開始撰寫設計及創新的相關報導。現任Parsons設計學院「創新與設計」教授。

曾創立「創新與設計」線上頻道,創辦《IN:創新內幕》季刊,並在《快速公司》及《哈佛商業評論》網站撰寫部落格。

Reference:

http://www.ithome.com.tw/article/93112

Sunday, February 8, 2015

Get attribute options values and lables by attribute code

<?php
$myColorArr = myGetAttributeOptionArr('my_color');

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

function myGetAttributeOptionArr($attributeCode) {
  $outArr = array();
  $optArr = Mage::getSingleton('eav/config')->getAttribute('catalog_product', $attributeCode)->getSource()->getAllOptions();

  foreach ($optArr as $val) {
    if (empty($val['value']) || empty($val['label'])) {
      continue;
    }

    $outArr[$val['value']] = $val['label'];
  }

  return $outArr;
}
?>

Get attributes of a attribute set in Magento

Method 1:

$attributes = Mage::getModel('catalog/product_attribute_api')->items($attributeSetId);

foreach($attributes as $_attribute){
  print_r($_attribute);
}

Method 2:

You don't necessarily need to access the API class. There is a more natural approach available. If you have a product:

/** @var Mage_Catalog_Model_Product $product **/
$attributes = $product->getTypeInstance(true)->getSetAttributes($product);

If not:

$attributes = Mage::getModel('catalog/product')->getResource()
  ->loadAllAttributes()
  ->getSortedAttributes($attributeSetId);

Reference:

http://stackoverflow.com/questions/18627559/get-the-attributes-for-attribute-set-in-magento
http://www.blog.magepsycho.com/playing-with-attribute-set-in-magento/