2011/12/22

Apache2 Server 的啟用/重啟


Apache 常用小知識

Apache 的主要設定檔是 httpd.conf ,其他的設定檔都是被 Include 進來的;
Apache 的首頁目錄以 DocumentRoot 決定,首頁檔案則以 DirectoryIndex 決定;
Apache 可以透過虛擬主機的設定以指定不同主機名稱到不同的 DocumentRoot 下;
Apache 是多執行緒的軟體,可以啟動多個程序來負責 WWW。主要的模組有 prefork 及 worker, 最大可連線的數量以 MaxClients 來決定。
若要正確的讓瀏覽器顯示網頁的編碼格式,最好在網頁上宣告語系,並將 Apache 的設定檔 httpd.conf 內的 AddDefaultCharset 設定值取消;
在 Apache 可瀏覽的目錄權限設定上 (Options 參數),最好將 Indexes拿掉;
透過 AllowOverride 與 .htaccess 可讓使用者在自己管理的目錄下制訂自己的風格;
Apache 本身提供一個 apachectl (RedHat/CentOS) / rcapache (SUSE等) 的 script 讓使用者得以快速管理其 apache 的服務;
HTTP 使用的是明碼傳送,目前 WWW 可利用 SSL 等機制來進行資料加密的傳輸。資料如果比較重要時,務必以 SSL 或者是保護目錄來保護。




Apache2 Server 的啟用/重啟

對於不同的 Linux Distributions,Apache 啟用的方式略有不同,主要有三種(apachectl, httpd, apache2):


1.
Shell>> /usr/local/apache2/bin/apachectl -k start (Red Hat)
2.
Shell>> /usr/local/apache2/bin/httpd -k start (when you don't have apachectl in Red Hat)



3.

Shell>> /etc/init.d/apache2 start (Ubuntu, Debian, SUSE)

apachetcl和httpd的路徑可能因安裝方式而有不同,請注意。但在某些情況下不用輸入路徑。
http://mepopedia.com/?page=146

2011/12/21

取得jQueryUI Tabs的當前tab panel

節選並翻譯自http://stackoverflow.com/questions/300078/jquery-ui-tabs-get-currently-selected-tab-index 雖然該帖子已經有些時日,不過我沒有發現有人提及這個方案: 如果不在Tab的事件(tab events ,http://jqueryui.com/demos/tabs/#events )中,如何取得當前tab ( "selected tab" )--當前選中的tab的下面的顯示內容的panel。我有一個簡單的方式... 


  1. var curTab = $( '.ui-tabs-panel:not(.ui-tabs-hide)' );  

你可以很容易的得到索引號index, 完全正確, 下面是其文檔中提及的方式 


  1. var $tabs = $( '#example' ).tabs();  
  2. var selected = $tabs.tabs( 'option' ,  'selected' );  // => 0  


不過你可以用我說的方式來獲取索引號index 或者其他任何當前panel的屬性.. 

  1. var curTab = $( '.ui-tabs-panel:not(.ui-tabs-hide)' ),  
  2.     curTabIndex = curTab.index(),  
  3.     curTabID = curTab.prop( "id" ),  
  4.     curTabCls = curTab.attr( "class" );  

2011/12/20

被遺忘的 toFixed()

javascript 的 toFixed(n) 可以將數字round up 到小數點後n 個位

var num = 0;

num = new Number(21);
num.toFixed(1) --> 21.0

num = new Number(21.3456);
num.toFixed(0) --> 21
num.toFixed(2) --> 21.35
num.toFixed(4) --> 21.3456

2011/12/14

java replaceAll with $

as $ is one of the symbol used in regular expression
it will fail at replpace all


solution

replace all $ to \\$
String a = "$38 Apple";
a = a.replaceAll("\\$", "\\\\\\$");

replace
String b = "testing testing REPLACE_ME testing testing";
String finalStr= start.replaceAll("REPLACE_ME", a);

2011/12/09

Ebay API SDK Add Item

從今天起,進入api開發的code階段。 這個階段預計有三部分,上傳產品,更新產品,刪除產品。每個部分都以固定價格的產品為例,其他如訂單管理,可變價格產品的管理等,需要讀者自己延伸。 因為每個人編碼習慣不同,所以編寫code的方式也不盡相同,但是為了便於大家更好的理解,這裡的例子都會盡量簡單一些。 對於不同種類的產品,參數可能會大致不相同,但基本的設置無外乎就這些。對於Variation的產品,比如一雙鞋,有43,42,44等尺寸這些產品,一定要仔細參照上邊的code是如何設置的,即便如此,也不能保證一次上傳就能成功,最好就是把返回信息$res保存起來,針對不同error,逐個解決。



class uploadProductToEbay {

 protected $_session = null;
 protected $_cs = null;
 protected $_logger = null;
 protected $_basedir = '';

    public function __construct()
    {
         require_once 'ebay/EbatNs_1_0_679/EbatNs_ServiceProxy.php';
  require_once 'ebay/EbatNs_1_0_679/EbatNs_Logger.php';
  require_once 'ebay/EbatNs_1_0_679/AddFixedPriceItemRequestType.php';
  require_once 'ebay/EbatNs_1_0_679/AddFixedPriceItemResponseType.php';

 
  $this->_basedir = Mage::getBaseDir();
  $this->_session = new EbatNs_Session(Mage::getBaseDir().'yourpath/ebay.config.php');
  $this->_cs      = new EbatNs_ServiceProxy($this->_session);
  $this->_logger  = new EbatNs_Logger();
    }
    public function addEbayProduct($product_data){//$product_data是从db里取得数据,比如产品title,只需在db里更改就可以了

                $req = new AddFixedPriceItemRequestType();
  $item = new ItemType();

  $item->SKU = $product_data['customlabel'];// 产品编号
  $item->Country = 'US';//国家
  $item->AutoPay = true;//paypal支付的话,如果你不想有损失,就老老实实设为true
  $item->Description = trim($product_data['*description']);//描述,不能有ebay规定的敏感字符
  $item->ListingDuration = $product_data['*duration'];
  $item->Title = $product_data['title'];//需少于80字符,不能有ebay规定的敏感字符
  $item->Currency = 'USD';//币种
  $item->ListingType = 'FixedPriceItem';//固定价格产品
  $item->SubTitle = $product_data['subtitle'];
  $item->StartPrice = $product_data['*startprice'];
  $item->ConditionID = $product_data['conditionid'];
  $item->Quantity = round($product_data['*quantity']) ;
  $item->Location = $product_data['*location'];//卖家邮编
 
  $item->DispatchTimeMax = $product_data['*dipatch_time_max'];//最大耗费时间
  $item->PaymentMethods = 'PayPal';//支付方式
  $item->PayPalEmailAddress = $product_data['paypal_email_address'];//paypal账号
 
  $pdts  = new PictureDetailsType();//产品图片部分
  $pdts->GalleryType = $product_data['gallery_type'];
  if(preg_match('/https/',$product_data['picurl']))
   $product_data['picurl'] = str_replace('https','http',$product_data['picurl']);
  $pdts->PictureURL = $product_data['picurl'];
  $item->PictureDetails = $pdts;
 
  $item->PrimaryCategory = new CategoryType();
  $item->PrimaryCategory->CategoryID = $product_data['category'];//分类id
  $item->Site = 'US';
 
  $sdt  = new ShippingDetailsType();
  $ssot = new ShippingServiceOptionsType();
  $issot = new InternationalShippingServiceOptionsType();
  $stt  = new SalesTaxType();
 
  $sdt->ShippingType = 'Flat';
  $sdt->PromotionalShippingDiscount = $product_data['promotional_shipping_discount'];
  $sdt->InternationalPromotionalShippingDiscount = $product_data['intl_promotional_shipping_discount'];
  $sdt->ShippingDiscountProfileID = $product_data['shipping_discount_profile_id'];
  $sdt->InternationalShippingDiscountProfileID = $product_data['intl_shipping_discount_profile_id'];
  $stt->SalesTaxState = $product_data['SalesTaxState'];
  $stt->SalesTaxPercent = $product_data['SalesTaxPercent'];
  $sdt->SalesTax = $stt;
 
  //第一种shipping设置
  $ssot->ShippingServicePriority = round($product_data['shipping1_priority']);
  $ssot->ShippingService = $product_data['shipping1_option'];
  $ssot->ShippingServiceCost = $product_data['shipping1_cost'];
  $sdt->ShippingServiceOptions[] = $ssot ;
 
  //第二种shipping设置,还可以有更多种
  $ssot2 = new ShippingServiceOptionsType();
  $ssot2->ShippingServicePriority = round($product_data['shipping2_priority']);
  $ssot2->ShippingService = $product_data['shipping2_option'];
  $ssot2->ShippingServiceCost = $product_data['shipping2_cost'];
  $sdt->ShippingServiceOptions[] = $ssot2 ;

  //第一种国际的shipping设置,主要针对美国以外的国家
  $issot->ShippingServicePriority = round($product_data['intlshipping1_priority']);
  $issot->ShippingService = $product_data['intlshipping1_option'];
  $issot->ShippingServiceCost = $product_data['intlshipping1_cost'];
  $issot->ShippingServiceAdditionalCost = $product_data['intlshipping1_addition'];
  $issot->ShipToLocation = $product_data['intlshipping1_location'];
  $sdt->InternationalShippingServiceOption[] = $issot ;
 
  //第二种国际的shipping设置,还可以有更多种
  $issot2 = new InternationalShippingServiceOptionsType();
  $issot2->ShippingServicePriority = round($product_data['intlshipping2_priority']);
  $issot2->ShippingService = $product_data['intlshipping2_option'];
  $issot2->ShippingServiceCost = $product_data['intlshipping2_cost'];
  $issot2->ShippingServiceAdditionalCost = $product_data['intlshipping2_addition'];
  $issot2->ShipToLocation = $product_data['intlshipping2_location'];
  $sdt->InternationalShippingServiceOption[] = $issot2 ;
 
  $item->ShippingDetails = $sdt;
 
  //退换货设置
  $rpt  = new ReturnPolicyType();
  $rpt->ReturnsAcceptedOption = $product_data['*return_accepted_option'];//如ReturnsAccepted 表示接受退换货
  $rpt->RefundOption = $product_data['refund_option'];//如MoneyBack 以现金方式返还
  $rpt->ReturnsWithinOption = $product_data['returns_with_option'];//如Days_30 30天内有效
  $rpt->Description = $product_data['additional_details'];//一些备注
  $rpt->ShippingCostPaidByOption = $product_data['shipping_cost_paid_by'];//如Buyer 购买者承担退货运费
  $item->ReturnPolicy = $rpt;
 
  $lcrpt = new ListingCheckoutRedirectPreferenceType();
  $lcrpt->SellerThirdPartyUsername = $product_data['seller_third_party_username'];
  $item->ListingCheckoutRedirectPreference = $lcrpt;
 
  $item->ShipToLocations = $product_data['ShipToLocations'];//如Worldwide,可送往世界各国
 

  //一些产品属性,如适合对象:男士,质地:棉  等等
  $nvlat_si = new NameValueListArrayType();
  $specific = unserialize($product_data['specific']);
  foreach ($specific as $k=>$v){
   $nvlt_si  = new NameValueListType();
   $nvlt_si->Name = $k;
   $nvlt_si->setValue($v);
   $nvlat_si->NameValueList[] = $nvlt_si;
  }
  $item->ItemSpecifics = $nvlat_si;
 
  /* *
  *
  *处理关联产品
  *
  */
  if($product_data['relationship'] == "Variation"){
 
   $vt    = new VariationsType();
   //$v     = new VariationType();
   $nvlat = new NameValueListArrayType();
   $nvlt  = new NameValueListType();
 
   $nvlt->Name = $product_data['Specification'];//如 Bracelet Length

   //$size_array如array('6.25 inches','6.50 inches','6.75 inches')
   $size_array = explode(';',$product_data['relationship_detail']);
   $i=1;
   foreach ($size_array as $size){
    $nvlt->setValue($size,$i++);
   }
   $nvlat->NameValueList = $nvlt;
   $vt->VariationSpecificsSet = $nvlat;
 
   //不同尺码的产品信息
   $relation = unserialize($product_data['relation']);
   foreach ($relation as $pd){
    $v     = new VariationType();
    $nvlat = new NameValueListArrayType();
    $nvlt  = new NameValueListType();
   
    $v->SKU = $pd['sku'];//产品编号
    $v->Quantity = $pd['qty'];//库存
    $v->StartPrice = $pd['price'];
    $nvlt->Name = $product_data['Specification'];
    $nvlt->setValue($pd['size']);//产品尺寸,颜色等属性
    $nvlat->setNameValueList($nvlt);
    $v->VariationSpecifics = $nvlat;
    $vt->Variation[] = $v;

   }
  }

  $item->Variations = $vt;
  $req->Item = $item;
  $res = $this->_cs->AddFixedPriceItem($req);//$res为返回信息,成功,失败,失败原因等


  return $res->ItemID;
    }
}

轉自http://blog.csdn.net/shangxiaoxue/article/details/6949037

2011/11/17

php中require/include 包含相對路徑的解決辦法

在PHP中require,include一個文件時,大都是用相對路徑,是個很頭疼的問題。

問題:
在1.php中通過include("../B/2.php")來引入B目錄下的2.php文件;
在index.php中通過include("A/1.php")來引入A目錄下的1.php文件;
運行出來當然會出現問題,找不到../B/2.php文件。

這是因為:
1.php被編譯到index.php中執行,也就是相當於1.php同index.php一樣位於網站根目錄下,但是在1.php別忘記了一斷代碼include("../B/2 .php");

"../"意味著什麼?上一級目錄,現在1.php已經在根目錄下了,這時候再上一級,那就已經找不到2.php了,所以問題就出現在此。

很多人會想到include("/B/2.php"),這樣不就好了,同樣不行php不同於我們的jsp,在include中使用"/"並不是我們所想像的網站根目錄,它代表的的當前的目錄,因此還是不行。
既然不能用相對的,那我們可以改用絕對路徑的方式。只是在包含文件之前,先包含一個global.php文件。

這個文件的內容是:
chdir(dirname(__FILE__));
它的作用是將當前目錄切換到global.php所在的路徑。 將global.php放在根目時錄下,在這之後包含的所有文件就會以根目錄為基準了。

例如,在2.php中引用1.php,則,通過2步:

1.require(dirname(__FILE__).'/../global.php');//視具體的目錄情況,反正是要指回到根目錄下的global.php 
 2.require('A/1.php')//從根目錄開始定位


這樣的話,不管頁面在哪一級目錄,我都可以去引用,不用再擔心路徑問題了!

2011/07/26

facebook sharer.php

set icon and description

<link rel="image_src" href="http://icons.iconarchive.com/icons/walrick/openphone/256/Phone-icon.png" />
<meta name="description" content="TESTING: This is the description of my webpage that I really want to have shared on Facebook!" />

2011/05/25

[DEBUG]jquery drop down menu hover後快速閃動

http://www.queness.com/resources/html/dropdownmenu/index.html

做DROP DOWN MENU 時, 用左JQUERY的 SLIDEUP同 SLIDEDOWN 來用作ANIMATION , 好似以上網址中的DEMO 咁

$('#nav li').hover(
function () {
//show its submenu
$('ul', this).slideDown(100);

},
function () {
//hide its submenu
$('ul', this).slideUp(100);
}
);
但發現到一個BUG, 就係當你好快咁mouseenter , 再好快咁mouseleave 個submenu, bug就產生了, 竟然見到個sub menu 不斷咁出現→消失→出現→消失...

最後發覺, 係個animation 問題, 當你移出/移入pointer既時候, slidedown animation 未完成又開始做slideup animation, 就會loop死左

解決方法原來好簡單, 就是在開始ANIMATION前STOP左去先

$('#nav li').hover(
function () {
//show its submenu
$('ul', this).stop(true, true).slideDown(100);

},
function () {
//hide its submenu
$('ul', this).stop(true, true).slideUp(100);
}
);

完成!

2011/05/20

jquery 改iframe content

有時逼不得已要用到iframe, 而iframe 入要的內容又想改wo
咁點做好呢?

以下方法只適用於same domain, protocol and port~!

//HTML
<iframe src="" frameborder="0" scrolling="no" id="iframe1" />

//JS
//找出header然後remove
$("#iframe1").attr('src', 'someURL');

$('#iframe1').live('load', function (){
    $("#iframe1").contents().find("div.header").remove();
});

[ mysql ] Convert timestamp to date

SELECT FROM_UNIXTIME


mysql> SELECT FROM_UNIXTIME(1196440219)

-> '2007-11-30 10:30:19'

2011/05/19

scrolling at android

寫完個webapp 發覺在日android 上scroll 得好差, 好窒
逐個factor 試下有冇關係la
唔關圖事
唔關layer 事
唔關gradient 事
!!! 原來係關box-shadow 事

一加左真係好似scroll 唔到咁
但只限android browser, ios ok~~

ps: 我only 試了android2.2的機~

2011/05/02

[PHP] convert Object to Array

測試webservice發現回傳回來的值為Object,如下:
[schema] => stdClass Object
        (
            [element] => stdClass Object
                (
                    [complexType] => stdClass Object
                        (
                            [choice] => stdClass Object
                                (
                                    [element] => stdClass Object
                                        (
                                            [complexType] => stdClass Object
                                                (
                                                    [sequence] => Array
                                                        (
                                                            [a] => 0
                                                            [b] => 1
                                                            => 2
                                                            [d] => 3
                                                            [e] => 4                                                            
                                                        )

                                                )
                                        )
                                )
                        )
                )
        )
我一時之間也不知道要如何是好,上傳搜尋一下,發現一個不錯的function,可以將Object 轉換成 Array,我使用後沒什麼問題提供給大家參考
function std_class_object_to_array($stdclassobject)
{
   $_array = is_object($stdclassobject) ? get_object_vars($stdclassobject) : stdclassobject;

foreach ($_array as $key => $value) {
$value = (is_array($value) || is_object($value)) ? std_class_object_to_array($value) : $value;
$array[$key] = $value;
}

    return $array;
}

使用方法如下
$test=std_class_object_to_array($schema);
$a=trim($test[element][complexType][choice][element][complexType][sequence]['a']);
這樣就可以取出a的值了

2011/04/25

local search at html page

如果想幫個網站的一版做search function
以下的code 係好幫
一search 就會highlight 所有keyword

我用左jquery~
function highlightKeyword(){
var keyword = $('#keyword').attr('value');
keyword='('+keyword+')';

var patt=new RegExp(keyword,'gi');

var oriHTML = $('#body').html();

// 用regular expression 去replace keyword 的style
var newHTML=oriHTML.replace(patt, '<span style="color:#000000; background-color:yellow; font-weight:bold;">$1</span>');

$('#body').html(newHTML);
}

2011/04/20

例子 - select in jquery


目的是左面SELECT選擇時, 右面PARENT ITEM跟著一起轉
特別地方是只match option內的html (因為value不能比較) , 而html也不是全等, 只是"match"


jQuery("select#edit-field-category-und").change(function(){ //事件發生
    //一次印出
    var word = jQuery("select#edit-field-category-und option:selected").html();
   // jQuery("#edit-menu-parent option:contains("+word+")").attr('checked',true);
   jQuery("select#edit-menu-parent").children().each(function(){
      if (jQuery(this).text().match(word)){
          //jQuery給法
          jQuery(this).attr("selected","true");
 
      }
    });

});

jQuery對select tag的操作


  • get
    • 取出選擇的值
      $("select#Club").val();
      $('select#Club option:selected').text();

      以上2方法在單選時相同,但複選時,
      val()會用逗號分開 ex. AA, BB
      text()不會 ex. AABB
    • 取出array
      $("select#Club").children("[@selected]").each(function(){
          alert(this.text());
      });
  • set
    • 使某option變為selected
      $("#select1").children().each(function(){
          if ($(this).text()=="option you want"){
              //jQuery給法
              $(this).attr("selected","true"); //或是給selected也可

              //javascript給法
              this.selected = true;
          }
      });
    • 讓新增的option直接為selected
      var option = jQuery("new option");
      $('
      select#Club').append(option);
      $(option).attr("selected","true"); //讓option為selected
      $('
      select#Club').trigger("change"); //最後要觸發select的change事件
    • select下拉框的第二個元素為當前選中值
      $('select#Club')[0].selectedIndex = 1;//不知為何要加[0]
      =========== K. T. Chen 提到 ==========================
      在$("")加[0]的意思是把jQuery物件轉為DOM物件。這樣子jQuery物件才能使用DOM底下的selectedIndex方法。
  • event
    //改變時的事件
    $("select#Club").change(function(){ //事件發生
        //一次印出
        alert($(this).val());

        //印出選到多個值
        jQuery('option:selected', this).each(function(){
            alert(this.value);
        });
    });
  • 移除
    removeOption(index/value/regex[, selectedOnly])
    $('select#Clubs option:selected').remove();


//純javascirpt
<select onchange="alert('Index: ' + this.selectedIndex
+ '\nValue: ' + this.options[this.selectedIndex].value)">
...
</select>

2011/04/15

"disabled" 的INPUT 是不能POST的

 簡單例子...下面有張FORM, 第一個input disable了, 第二個正常

<FORM action="test.php" method="post">
    <P>
      First name: <INPUT type="text" name='firstname' value='hihi' disabled><BR>
      Last name: <INPUT type="text" name='lastname' ><BR>

       <INPUT type="submit" value="Send">
    </P>
 </FORM>

即使firstname裝有value, 但最後只有lastname 被POST 出.....

小小的定義問題, 但已令我浪費左好多時間!!!

2011/04/10

jquery $.each 的問題

用jquery 的$.each 好好用
尤其係對array 入面的野
但當我要splice 個array 的時候就好唔方便了 ><

SAMPLE:
$.each(array, function(i, item){
    if (!item.name || item.name == '' ){
        array.splice(i, 1);
        i--;
    }
});

這是冇用的
因為個i 係每個function 計
改變唔到出面個i
所以就算splice 到都會出error...

要用普通的for loop 得 ~

2011/04/03

iphone4 css style sheet

因為iphone4 個resolution 有d 唔同

所以有時css 的setting 都會唔到


呢個方就可以令iphone4 食多一張css

<link
    rel="stylesheet" type="text/css" href="iphone4.css"
    media="only screen and (-webkit-min-device-pixel-ratio: 2)"
/>


或者可以咁

@media only screen and (-webkit-min-device-pixel-ratio: 2 ) {
    body{color:red;}
}

2011/03/30

[CodeIgniter] Form Post data 簡短寫法

codeigniter (ci) 當用form post data的時候要逐個input對應太麻煩了...

例子:
 $data = array(
       'baioti'   => $this->input->post('biaoti'),
        'neirong'     => $this->input->post('neirong'),
        'zuozhe' => $this->input->post('zuozhe'),
         'shijian'    => (string) date('Y-m-j'),
                        );
  $this->db->insert('news',$data);

轉換成新寫法:


$data =$_POST;
$data["shijian"]=(string) date('Y-m-j');
$this->db->insert('news',$data);


以上代碼因為字段太少,不會有很明顯的縮短,但是當你添加的內容需要很多字段的時候,可以明顯縮短許多許多!


當然這樣用的前提是,表單中的域要與數據庫中的字段要對應


有時當直接想用來Insert/update DB時, 會發現"submit" 都同時post去update了...而db沒有"submit "這column, 所以出現error, 這時只要在assign value前加上


unset($_POST['submit']);
$data =$_POST;
$data["shijian"]=(string) date('Y-m-j');
$this->db->insert('news',$data);


得左!

2011/03/28

讓webapp 似 native app 的幾個tag

1. home screen icon
iphone 3g/3gs: 57px X 57px
iphone 4: 114px X 114px
ipad: 96px X 96px
但其實正方形都ok~

<!-- 會加gloss effect -->
<link rel="apple-touch-icon" href="icon.png"/> 
<!-- 不會加gloss effect -->
<link rel="apple-touch-icon-precomposed" href="icon.png"/> 

2. 收起safari 的toolbars
<meta name="apple-mobile-web-app-capable" content="yes">

3. 加 start up image
一定是320px X 460px
<link rel="apple-touch-startup-image" href="startup.png">

EXTRA:
改最高那條status bar 的顏色
content 可以是 default, black, black-translucent
<meta name="apple-mobile-web-app-status-bar-style" content="black">

定義viewport
user-scalable=no <-- 不讓人放大或縮少你的webpage
<meta name = "viewport" content = "user-scalable=no, width=device-width">

reference link:
http://developer.apple.com/library/safari/#documentation/appleapplications/reference/safariwebcontent/ConfiguringWebApplications/ConfiguringWebApplications.html

2011/03/25

css webkit gradient radial

.gradient_radial{
    /*
    *第一個是type (有linear 同radial)
    *第二個是開始的位置, x 同y, 用%, 用space 分隔
    *第三個是第一個㘣的radius
    *第四個是結束的位置, x 同y, 用%, 用space 分隔
    *第五個是第二個㘣的radius
    *第六個是開始的color, 一定要有from
    *最後一個是結束的color, 一定要有to
    *
    *第六個同最後一個中間可以加 color-stop(位置, 顏色), 咁就可以做出幾隻色的gradient
    *
    *如果第一個圓的radius 大過第二個圓的radius, d 顏面就會掉轉 (由出至入)   
    */
    background: -webkit-gradient(radial, 70% 70%, 20, 50% 50%, 130,
    from(red),
    color-stop(16%, orange),
    color-stop(33%, yellow),
    color-stop(49%, green),
    color-stop(66%, blue),
    color-stop(83%, indigo),
    to(violet));
}

2011/03/22

CodeIgniter - split() 和eregi() is deprecated

可能是舊VERSION PHP 的關係

有時未必support split() 和eregi()的功能...

這時只要轉代取function 就可以了

split()  ->explode()

eregi() -> preg_match()

注意: preg_match() 的pattern 要加pattern "/word/i"

2011/03/21

[Magento] 更改language drop down menu

magento 最煩既一樣野就係你搵唔到個file出黎改....

當然你可以去admin config 個 show path hints, 但有時template 入面再有template, 就不免要人手入去搵

今日想改langauge 個drop down menu, 變左<a href=""....>既link

路徑幾經辛苦找到是base\default\template\page\switch\

language.phtml, 把select tag comment掉, 

我希望做到, 當store view是中文的時候, 顯示"eng" link ; 當英文的是時候, 顯示"中文"link

這時要了解一下magento 部份api function...

$this->getCurrentStoreId();    // (int) 取得store view的id (e.g. 中文→ 1 , 英文 →2)

$this->getStores() ;      //  (array) 取得所有store view的data  (包含id, name)

$_lang = $this->getStores() ;   //   先用variable裝住佢

$_lang->getId()              // 取得array中的store id

$_lang->getName()    // 取得array 中的store name

$_lang->getCurrentUrl()  //取得array中的url

基本上有齊以上function就能做大部份....

e.g.



<?php $curr_lang = $this->getCurrentStoreId();?>
<?php foreach ($this->getStores() as $_lang): ?>
<?php if ( $this->htmlEscape($_lang->getId())!= $curr_lang ) { ?>
        <a href="<?php echo $_lang->getCurrentUrl() ?>"><img
src="<?php echo $this->getSkinUrl('images/flag_' . $this->htmlEscape($_lang->getName()) . '.gif') ?>"
alt="<?php echo $this->htmlEscape($_lang->getName()) ?>"/></a>
<?php }?>
    <?php endforeach; ?>

2011/03/19

css webkit gradient linear

用css 去砌d 好靚的gradient
gradient
主要分linear同 radial
但暫時仲未統一
所以個個browser 的寫法都唔同

.gradient_linear{
    /*
    *第一個是type (有linear 同radial)
    *第二個是開始的位置, x 同y, 用space 分隔
    *第三個是結束的位置, x 同y, 用space 分隔
    *第四個是開始的color, 一定要有from
    *最後一個是結束的color, 一定要有to
    *
    *第四個同最後一個中間可以加 color-stop(位置, 顏色), 咁就可以做出幾隻色的gradient
    */

   /*圖一*/
   background: -webkit-gradient(linear, left top, left bottom,
   from(yellow),
   to(blue));

   /*圖二*/
    background: -webkit-gradient(linear, left top, right bottom,
    from(red),
    color-stop(16%, orange),
    color-stop(33%, yellow),
    color-stop(49%, green),
    color-stop(66%, blue),
    color-stop(83%, indigo),
    to(violet));
}

圖一

圖二

drop down menu

兩個幾好用的drop down menu

唔依賴framework 的~


tiny drop down
http://www.scriptiny.com/2008/11/drop-down-menu/

會有d fade in / fade out 的effect
但ie 6 睇會有d 奇怪

用法:
var menu=new menu.dd('menu');
menu.init('menu','menuhover');
(放在page 的最後, or onload 之後)
再用ul li set class


Professional dropdown #2
http://www.stunicholls.com/menu/pro_dropdown_2.html
唔駛用javascript, 用ul li set class 就ok 了

冇任何effect, 好直接, 好clean

2011/03/18

java write to file

點樣可以將d string output 做一個file 呢~?

其實好簡單的~

有幾個方法都得
咁我就用左其中一個la

//filePath: 目標file 的path e.g: /logs/example/output.txt
//str: 要寫落file 的text
public static void writeToFile(String filePath, String str){
    try {     
        // 開個file, 如果冇呢個file, 就會自動create
        FileOutputStream outFile = new FileOutputStream(filePath);

        // 寫string 落個file, 但要轉做bytes 先
        outFile.write(sb.toString().getBytes("UTF-8"));

         // 以防d bytes 未寫好, 要flush 一下
        outFile.flush();

         //  寫完後 close 個file =], 完
        outFile.close();

    } catch (IOException e){
        e.printStackTrace();
    }
}

2011/03/16

iphone4 detection 找出iphon4

一個用javascript 找出iphone 4 的方法
iphone 4 的mon 同其他iphone 主要唔同之處係個mon
因為個mon 的display 唔同, 所以寫website 的時候要用唔同的方法~~

  1. 先用user agent 找出iphone
  2. 再用webkit 獨有的javascript object  (devicePixelRatio) , 因為iphone 4 有 retina display, 所以device ratio 會是2, iphone 3 同iphone 3gs 是 1

vas isiPhone4 = false;
var userAgent = window.navigator.userAgent;
if (userAgent.toLowerCase().indexOf('iphone') != -1){
  // is iphone
  if (window.devicePixelRatio && window.devicePixelRatio == 2){
    // is iphone4
    isiPhone4 = true;
  }
}

useful websites

some testing browser website

HTML5 (可以知道唔同browsers support html5 的情況)


CSS3 (唔同browser 對css3 selector 的tester)
http://tools.css3.info/selectors-test/test.html

2011/03/14

(Drupal)Photoshop 根本轉唔到ICO...但可以裝PLUGIN

整完Drupal site, 最後發覺唔記得轉browser logo, 開一開ps 完來唔support

原來有plugin

ICO (Windows Icon) file format plugin for Photoshop

Copyright 2002-2011 Toby Thain, toby@telegraphics.com.au
The plugin gives Photoshop the ability to directly Open and Save Windows icon (.ICO) and cursor (.CUR) files (saving .CUR files is supported by version 2.1 or later)


http://www.telegraphics.com.au/svn/icoformat/trunk/dist/README.html


裝完再export 的時候, 就多了個選項了!

--------------------------------------------------------------
但轉icon 時, 若果就咁replace misc 入面既ico , 或者放root, 或者放theme, 係轉唔到icon既!

要入番 appearance -> [theme] - > shortcut icon setting 

2011/03/13

css3 border-radius

border-radius 係可以好簡單整到圓角邊

支援的browser: firefox, chrome, safari, ie9
ff4 以上先supoort 冇browser prefix
ie9 唔駛prefix的


.border_radius{
    border:10px solid #ffdd00;
    
    /*
    *4個角都是以20px 為radius 的圓角
    *(圖1)
    */
    border-radius: 20px; 
    -webkit-border-radius: 20px; 
    -moz-border-radius: 20px;    
    
    
    /*
    *左上角 同 右下角 是10px, 右上角 同 左下角 是40px
    *有-webkit-字頭會好奇怪, 要小心~!
    *(圖2)
    */
    border-radius: 10px 40px;
    -webkit-border-radius: 10px 40px;
    -moz-border-radius: 10px 40px;
    
    
    /*
    *左上角 是10px, 右上角 同 左下角 是20px, 右下角 是40px
    *(圖3)
    */
    border-radius: 10px 20px 40px;
    -webkit-border-radius: 10px 20px 40px;
    -moz-border-radius: 10px 20px 40px;
    

    /*
    *由左上角開始順時針的4個角
    *(圖4)
    */
    border-radius: 10px 20px 30px 40px;    
    -webkit-border-radius: 10px 20px 30px 40px;    
    -moz-border-radius: 10px 20px 30px 40px;    

    
    /*
    *border-*, -webkit-border-*, -moz-border-radius-* *: 指某一個角 
    *-moz- 的寫法有少少唔同, 要小心~!
    *(圖4)
    */
    border-top-left-radius:10px;
    border-top-right-radius:20px;
    border-bottom-right-radius:30px;
    border-bottom-left-radius:40px;    
    -webkit-border-top-left-radius:10px;
    -webkit-border-top-right-radius:20px;
    -webkit-border-bottom-right-radius:30px;
    -webkit-border-bottom-left-radius:40px;    
    -moz-border-radius-topleft:10px;
    -moz-border-radius-topright:20px;
    -moz-border-radius-bottomright:30px;
    -moz-border-radius-bottomleft:40px;
}

圖1

圖2
圖3


圖4

css3 box-shadow

box shadow 可以好易幫d box 打陰影
圖片都得, 但inset 就冇效果

支援的browser: firefox, chrome, safari, opera, ie9
ff4 以上先supoort 冇browser prefix

.box_shadow{
    box-shadow: 5px -5px 8px 3px #0000ff, -10px -10px 15px 5px #ff0000 inset;
    -webkit-box-shadow: 5px -5px 8px 3px #0000ff, -10px -10px 15px 5px #ff0000 inset;
    -moz-box-shadow: 5px -5px 8px 3px #0000ff, -10px -10px 15px 5px #ff0000 inset;
}

第1個 (5px): x 的偏離, 正數係右面, 負數係左面
第2個 (-5px): y 的偏離, 正數係下面, 負數係上面
第3個 (8px):  blur 的長度, 個影的邊邊幾長 (可有可無)
第4個 (3px): 影的大小, 每邊長多幾多px (可有可無)
第5個 (#0000ff): 影的顏色
第6個 (inset): 影是向外定向內 (ourset/ inset), default 係outset (可有可無) (向內的話唔計padding)

可以set多過一個shadow, 用',' 分隔

.box_shadow 的效果

2011/03/12

css3 text-shadow

text-shadow 係css3 的standard
唔駛加browser prefix 都用到 =]
支援的browser: firefox, chrome, safari, opera [no ie =.=]

.text_shadow{
    text-shadow: 5px -10px 20px #ff0000;
}

第1個 (5px): x 的偏離, 正數係右面, 負數係左面
第2個 (-10px): y 的偏離, 正數係下面, 負數係上面
第3個 (20px): blur 的長度 (越大越濛)
第4個 (#ff0000): 顏色

 可以有幾個shadow 的, 用 ',' 分隔
.text_shadow 的效果

2011/03/10

js change obj to param string

js 用會 {id:12, name:'user'} 來做data,
點可以好快咁變成 id=12&name=user 呢?
ajax call 時好好用的~!

var params = {id:12, name:'user'};

jquery:
$.param(params);
PS: space 會變做+


prototype:
Object.toQueryString(params);
PS: space 會變做%20


sql get all child cat by parent id

改少少就可以拎哂所有child
平時冇咩用, 但searching 好有用 =]

SELECT t1.* FROM category AS t1
LEFT JOIN category AS t2 ON t2.category_id= t1.parent
LEFT JOIN category AS t3 ON t3.category_id =t2.parent
WHERE 
(t1.category_id = [child_id] OR t2.category_id = [child_id] OR t3.category_id = [child_id])
 ORDER BY t1.LEVEL

js trim

how to trim a string using js?

function trim(str){
 return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}


function trim(str){
 return str.replace(/^\s+|\s+$/g, '');
}

str = trim(str);


jquery:
str = $.trim(str);


str =  str.strip();

2011/03/09

DRUPAL 7中能夠TRIM Teaser的地方

今日搵了很久, 為何在content type 的teaser選了trim length, 但frontend 仍然不見效果..

原來我除了在content type trim了,還在 views 裏的"field"  再trim了一次, 例如在content type set 了length 300: , 之後pass到view裏即使set 到trim 350也沒有效果, 因為一早被content type的override了!

當一個node 經panels, views ,block 顯示既時候, 真的要set好rule 搞清楚次序, 因為太多setting 可以互相override, 見一個set一次的話之後debug就頭痛了..

關於module 互相override的次序, 其實都可以check得番, 就係去database 睇"system"既table, 睇番你想睇既module, 留意weight, 通常會係0, views既default 係10 , 通常taxonamy, node 等等都會被view override 

但對於node .tpl file 同view 比較, 好似node .tpl file 永遠係最高prority, 這個有待確認

2011/03/08

sql ifnull

如果sql 要用concat 但又有null, 咁 ifnull 就好好用了
因為concat null 會成個value 變null 的

SELECT CONCAT(IFNULL(FIRSTNAME, ''), ' ', IFNULL(LASTNAME, '') AS FULLNAME FROM USER;

sql group_concat group by

今日先知原來有group_concat
會自動將那個column 的value 用 ',' group
完全救左我~!!

SELECT Class, GROUP_CONCAT(Animal) AS Animal FROM Zoo GROUP BY Family;

table
Class   Animal
===========
Fish   Goldfish
Fish   Grouper
Mammal Tiger
Mammal Lion


Result:
Fish   Goldfish,Grouper
Mammal  Tiger,Lion

"Update" SQL joining more than 1 tables

平時用CODE做, UPDATE SQL 都係好簡單, 但如果想做複雜少少既UPDATE, 其實亦可以COMBINE 埋 SELECT 一齊UPDATE , 但個SYNTAX有少少唔同

假設我select 左一堆node type係 "recipe" ,同profile_values 係"member"既row出黎

select * from node ,users ,profile_values 
where node.type='recipe' 
and users.uid = node.uid 
and profile_values.nid = node.nid
and profile_values.value='member'

之後我想將result 既某一個column (e.g. language )一次過update做新value
update node ,users ,profile_values 
set node.language ='sc_kit_cn' 
where node.type='recipe' and users.uid = node.uid 
and profile_values.nid = node.nid
and profile_values.value='member'

簡單講, 
就係將from 既table list 放去update後面
set 既column一定要簡番要update既table
where 果堆照keep番