Monday, 17 September 2012

php array append

PHP: append an element to the end of the array


NoteIf you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
---- http://php.net/manual/en/function.array-push.php

Example:

$elements = array(1,2,3,4,5,6);

foreach ($elements as $elem)
    $newArray[] = $elem;

print_r($newArray);
//sample output: Array ( [0] => 1[1] => 2[2] => 3[3] => 4...)

Yii findbyattributes using IN Clause

How to use SQL IN clause based on Yii findbyattributes?

Solution:


put an array as an value for an specific attribute:
$model=new Model();
$result=$model->findAllByAttributes(array('Id'=>array(6,7,8,9)));

Sunday, 16 September 2012

Yii clientScript registerScript (example)

Function : Generate a piece of specific js script.

Example:

HTML: 
we have a button: 

<!--  {'func':'abc','par':'123'} is JSON format (key:value)! -->

<input type="button" onclick="myFunction({'func':'abc','par':'123'})" value='click me'/>

PHP ajax:


<?php 
//Specify an ajax handler: 
//Controller : Ajax, Action: handler $ajaxUrl = $this->createUrl('ajax/handler'); 
$script = "function  myFunction (param){  
           $.ajax({  
                    'type': 'GET',  
                    'url': '$ajaxUrl',  
                    'data': param,
//!!!!!if returned results are not json formatted, please delete dataType !!!!!!.
                    'dataType', 'json'  
                    'success': function(msg){
                               //success code put here!  
                               }";

//register the script(generate the js).
// CClientScript::POS_END: gen js code after the html page is fully loaded. 
//the position of the JavaScript code. Valid values include the following:
      • CClientScript::POS_HEAD : the script is inserted in the head section right before the title element.
      • CClientScript::POS_BEGIN : the script is inserted at the beginning of the body section.
      • CClientScript::POS_END : the script is inserted at the end of the body section.
      • CClientScript::POS_LOAD : the script is inserted in the window.onload() function.
      • CClientScript::POS_READY : the script is inserted in the jQuery's ready function.


Yii::app()->clientScript->registerScript('updates', $script,        CClientScript::POS_END);
?>

PHP controller:

<?php 
class AjaxController extends Controller
{
public $defaultAction = 'Handler';
public function actionHandler()
{
    $func = $_GET['func'];
    $param = $_GET['par'];
}
}
?>

For more info, about CClientScript : http://www.yiiframework.com/doc/api/1.1/CClientScript


帮自己宣传一下刚上线的网站 梦奇网;目前的提供的服务是 签证搜索 和 时间和日期。谢谢大家支持,SEO下!






Friday, 8 June 2012

Yii Three ways to update counters

Using Yii, there are probably three ways to update counters:

  1. Model->save();
  2. Model->saveCounters();
  3. Model->updateCounters();
For all these methods, we have to get the object before performing the updating process. i.e.,  

$obj = YourObject->model()->findByPk($id);

Difference among them:

1.$obj->visits += 1; 
  $obj->save();

2.$obj->saveCounters(array('visits'=>'1'));

3.$obj->updateCounters(array('visits'=>'1', 'id'=>$id));

The Trick is:
  1. Better to use saveCounters()!
  2. If you use updateCounters(), pls make sure you have put id in a condition as highlighted in the code. Otherwise, the 'visits' field for all records +1.


Monday, 21 May 2012

jQuery Insert text into textarea

jQuery Insert text into textarea:



jQuery.fn.extend({
insertAtCaret: function(myValue){
 return this.each(function(i) {
   if (document.selection) {
     //For browsers like Internet Explorer
     this.focus();
     sel = document.selection.createRange();
     sel.text = myValue;
     this.focus();
   }
   else if (this.selectionStart || this.selectionStart == '0') {
     //For browsers like Firefox and Webkit based
     var startPos = this.selectionStart;
     var endPos = this.selectionEnd;
     var scrollTop = this.scrollTop;
     this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
     this.focus();
     this.selectionStart = startPos + myValue.length;
     this.selectionEnd = startPos + myValue.length;
     this.scrollTop = scrollTop;
   } else {
     this.value += myValue;
     this.focus();
   }
 })
}
});
Usage:


$("#elem_id").insertAtCaret('text');

Tuesday, 1 May 2012

Axis Webserivce how to solve: java.lang.reflect.InvocationTargetException

Axis Webserivce how to solve:  java.lang.reflect.InvocationTargetException


Config: Tomcat 5.5 + Axis 1.4 , called by PHP SoapClient, 


Status: While visiting localhost:xxx?wsdl the dom tree can be seen. But called from PHP, it raises the  java.lang.reflect.InvocationTargetException.


Solution:
    1. copy all .jar files from tomcat/common/lib to Tomcat\webapps\ROOT\axis\WEB-INF\lib.
    2. Make sure there is no enum in your web service class!!!! Very important!!!
         E.g.:


        public class Search {


       // remove this !!!!!! it will raise java.lang.reflect.InvocationTargetException
         public enum Color { 
            RED , BLUE,GREEN,BLACK ;
         }
public XXX search(){


        }
    }

Friday, 20 April 2012

Lucene: How to make searching faster


How to make searching faster

Here are some things to try to speed up the seaching speed of your Lucene application. Please see ImproveIndexingSpeed for how to speed up indexing.
  • Be sure you really need to speed things up. Many of the ideas here are simple to try, but others will necessarily add some complexity to your application. So be sure your searching speed is indeed too slow and the slowness is indeed within Lucene.
  • Make sure you are using the latest version of Lucene.
  • Use a local filesystem. Remote filesystems are typically quite a bit slower for searching. If the index must be remote, try to mount the remote filesystem as a "readonly" mount. In some cases this could improve performance.
  • Get faster hardware, especially a faster IO system. Flash-based Solid State Drives works very well for Lucene searches. As seek-times for SSD's are about 100 times faster than traditional platter-based harddrives, the usual penalty for seeking is virtually eliminated. This means that SSD-equipped machines need less RAM for file caching and that searchers require less warm-up time before they respond quickly.
  • Tune the OS
    One tunable that stands out on Linux is swappiness (http://kerneltrap.org/node/3000), which controls how aggressively the OS will swap out RAM used by processes in favor of the IO Cache. Most Linux distros default this to a highish number (meaning, aggressive) but this can easily cause horrible search latency, especially if you are searching a large index with a low query rate. Experiment by turning swappiness down or off entirely (by setting it to 0). Windows also has a checkbox, under My Computer -> Properties -> Advanced -> Performance Settings -> Advanced -> Memory Usage, that lets you favor Programs or System Cache, that's likely doing something similar.
  • Open the IndexReader with readOnly=true. This makes a big difference when multiple threads are sharing the same reader, as it removes certain sources of thread contention.
  • On non-Windows platform, using NIOFSDirectory instead of FSDirectory.
    This also removes sources of contention when accessing the underlying files. Unfortunately, due to a longstanding bug on Windows in Sun's JRE (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6265734 -- feel particularly free to go vote for it), NIOFSDirectory gets poor performance on Windows.
  • Add RAM to your hardware and/or increase the heap size for the JVM. For a large index, searching can use alot of RAM. If you don't have enough RAM or your JVM is not running with a large enough HEAP size then the JVM can hit swapping and thrashing at which point everything will run slowly.
  • Use one instance of IndexSearcher.
    Share a single IndexSearcher across queries and across threads in your application.
  • When measuring performance, disregard the first query.
    The first query to a searcher pays the price of initializing caches (especially when sorting by fields) and thus will skew your results (assuming you re-use the searcher for many queries). On the other hand, if you re-run the same query again and again, results won't be realistic either, because the operating system will use its cache to speed up IO operations. On Linux (kernel 2.6.16 and later) you can clean the disk cache using sync ; echo 3 > /proc/sys/vm/drop_caches. See http://linux-mm.org/Drop_Caches for details.
  • Re-open the IndexSearcher only when necessary.
    You must re-open the IndexSearcher in order to make newly committed changes visible to searching. However, re-opening the searcher has a certain overhead (noticeable mostly with large indexes and with sorting turned on) and should thus be minimized. Consider using a so called warming technique which allows the searcher to warm up its caches before the first query hits.
  • Decrease mergeFactor. Smaller mergeFactors mean fewer segments and searching will be faster. However, this will slow down indexing speed, so you should test values to strike an appropriate balance for your application.
  • Limit usage of stored fields and term vectors. Retrieving these from the index is quite costly. Typically you should only retrieve these for the current "page" the user will see, not for all documents in the full result set. For each document retrieved, Lucene must seek to a different location in various files. Try sorting the documents you need to retrieve by docID order first.
  • Use FieldSelector to carefully pick which fields are loaded, and how they are loaded, when you retrieve a document.
  • Don't iterate over more hits than needed.
    Iterating over all hits is slow for two reasons. Firstly, the search() method that returns a Hits object re-executes the search internally when you need more than 100 hits. Solution: use the search method that takes a HitCollector instead. Secondly, the hits will probably be spread over the disk so accessing them all requires much I/O activity. This cannot easily be avoided unless the index is small enough to be loaded into RAM. If you don't need the complete documents but only one (small) field you could also use the FieldCache class to cache that one field and have fast access to it.
  • When using fuzzy queries use a minimum prefix length.
    Fuzzy queries perform CPU-intensive string comparisons - avoid comparing all unique terms with the user input by only examining terms starting with the first "N" characters. This prefix length is a property on both QueryParser and FuzzyQuery - default is zero so ALL terms are compared.
  • Consider using filters. It can be much more efficient to restrict results to a part of the index using a cached bit set filter rather than using a query clause. This is especially true for restrictions that match a great number of documents of a large index. Filters are typically used to restrict the results to a category but could in many cases be used to replace any query clause. One difference between using a Query and a Filter is that the Query has an impact on the score while a Filter does not.
  • Find the bottleneck.
    Complex query analysis or heavy post-processing of results are examples of hidden bottlenecks for searches. Profiling with at tool such as VisualVM helps locating the problem.

Thursday, 19 April 2012

PHP Solution for SoapClient Webservice: java.lang.IllegalAccessException can not access a member of class

PHP Solution for SoapClient Webservice:


java.lang.IllegalAccessException can not access a member of class:


Add Public keyword in front of your class declaration!


e.g.,


public class ClassName {
}

Wednesday, 18 April 2012

Lucene 3.6 make use of IKAnalyzer 3.2 stable (how to get token from tokenstream)

First things first, make sure all versions are compatible! Cos some interfaces are updated for lucene 3.6, meanwhile some methods are depreciated as well!


In this version: we use Lucene 3.6, IKAnalyzer 3.2. For built-in analyzers such as simple,  standard analyzers, this method also can be applied.





  1. package com.segment;  
  2.   
  3. import java.io.StringReader;  
  4. import org.apache.lucene.analysis.Analyzer;  
  5. import org.apache.lucene.analysis.Token;  
  6. import org.apache.lucene.analysis.TokenStream;  
  7. import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;  
  8. import org.apache.lucene.analysis.tokenattributes.TermAttribute;  
  9. import org.apache.lucene.util.AttributeImpl;  
  10. import org.wltea.analyzer.lucene.IKAnalyzer;  
  11.   
  12.   
  13. public class Segment {  
  14.     public static String show(Analyzer a, String s) throws Exception {  
  15.   
  16.         StringReader reader = new StringReader(s);  
  17.         TokenStream ts = a.tokenStream(s, reader);  
  18.         String s1 = ""s2 = "";  
  19.         boolean hasnextts.incrementToken();  
  20.         //Token t = ts.next();  
  21.         while (hasnext) {  
  22.             //AttributeImpl ta = new AttributeImpl();  
  23.             CharTermAttribute ta = ts.getAttribute(CharTermAttribute.class);  
  24.             //TermAttribute ta = ts.getAttribute(TermAttribute.class);  
  25.               
  26.             s2 = ta.toString() + " ";  
  27.             s1 += s2;  
  28.             hasnext = ts.incrementToken();  
  29.         }  
  30.         return s1;  
  31.     }  
  32.   
  33.     public String segment(String s) throws Exception {  
  34.         Analyzer a = new IKAnalyzer();  
  35.         return show(a, s);  
  36.     }  
  37.     public static void main(String args[])  
  38.     {  
  39.         String name = "some test strings here!!!";  
  40.         Segment s = new Segment();  
  41.         String test = "";  
  42.         try {  
  43.             System.out.println(test+s.segment(name));  
  44.         } catch (Exception e) {  
  45.             // TODO Auto-generated catch block  
  46.             e.printStackTrace();  
  47.         }  
  48.     }  
  49.   
  50. }