国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

函數(shù)集

Carbs / 1237人閱讀

摘要:統(tǒng)計(jì)數(shù)組元素個(gè)數(shù)循環(huán)刪除目錄無(wú)限極分類生成樹安徽省浙江省合肥市長(zhǎng)豐縣安慶市如何取數(shù)據(jù)格式化的樹形數(shù)據(jù)數(shù)組排序是數(shù)字?jǐn)?shù)組寫法遇到字符串的時(shí)候就要的第三個(gè)參數(shù)是的初始值閉包中只接受一個(gè)或者多個(gè)參數(shù),閉包的參數(shù)數(shù)量和本身的參數(shù)數(shù)量必須

統(tǒng)計(jì)數(shù)組元素個(gè)數(shù)

$arr = array(
      "1011,1003,1008,1001,1000,1004,1012",
      "1009",
      "1011,1003,1111"
    );
$result = array();
foreach ($arr as $str) {
  $str_arr = explode(",", $str);
  foreach ($str_arr as $v) {
    // $result[$v] = isset($result[$v]) ? $result[$v] : 0;
    // $result[$v] = $result[$v] + 1;
    $result[$v] = isset($result[$v]) ? $result[$v]+1 : 1;
  }
}

print_r($result);
//Array
(

[1011] => 2
[1003] => 2
[1008] => 1
[1001] => 1
[1000] => 1
[1004] => 1
[1012] => 1
[1009] => 1
[1111] => 1

)

循環(huán)刪除目錄

function cleanup_directory($dir) {
  foreach (new DirectoryIterator($dir) as $file) {
    if ($file->isDir()) {
      if (! $file->isDot()) {
        cleanup_directory($file->getPathname());
      }
    } else {
       unlink($file->getPathname());
    }
  }
   rmdir($dir);
}

3.無(wú)限極分類生成樹

function generateTree($items){

    $tree = array();

    foreach($items as $item){

        if(isset($items[$item["pid"]])){

            $items[$item["pid"]]["son"][] = &$items[$item["id"]];

        }else{

            $tree[] = &$items[$item["id"]];

        }

    }

    return $tree;

}
function generateTree2($items){

    foreach($items as $item)

        $items[$item["pid"]]["son"][$item["id"]] = &$items[$item["id"]];

    return isset($items[0]["son"]) ? $items[0]["son"] : array();

}


$items = array(

    1 => array("id" => 1, "pid" => 0, "name" => "安徽省"),

    2 => array("id" => 2, "pid" => 0, "name" => "浙江省"),

    3 => array("id" => 3, "pid" => 1, "name" => "合肥市"),

    4 => array("id" => 4, "pid" => 3, "name" => "長(zhǎng)豐縣"),

    5 => array("id" => 5, "pid" => 1, "name" => "安慶市"),

);

print_r(generateTree($items));
/**

 * 如何取數(shù)據(jù)格式化的樹形數(shù)據(jù)

 */

$tree = generateTree($items);

function getTreeData($tree){

    foreach($tree as $t){

        echo $t["name"]."
"; if(isset($t["son"])){ getTreeData($t["son"]); } } }

4.數(shù)組排序 a - b 是數(shù)字?jǐn)?shù)組寫法 遇到字符串的時(shí)候就要

var test = ["ab", "ac", "bd", "bc"];
test.sort(function(a, b) {
    if(a < b) {
        return -1;
    }

    if(a > b) {
        return 1;
    }

    return 0;
});

5.array_reduce

$raw = [1,2,3,4,5,];
// array_reduce 的第三個(gè)參數(shù)是 $result 的初始值
array_reduce($raw, function($result, $value) {
    $result[$value] = $value;

    return $result;
}, []);
// [1 => 1, 2 => 2, ... 5 => 5]

6.arraymap 閉包中只接受一個(gè)或者多個(gè)參數(shù),閉包的參數(shù)數(shù)量和 arraymap 本身的參數(shù)數(shù)量必須一致

$input = ["key" => "value"];
array_map(function($key, $value) {

    echo $key . $value;
}, array_keys($input), $input)
// "keyvalue"
$double = function($item) {
  return 2 * $item;
}

$result = array_map($double, [1,2,3]);

// 2 4 6

7.繁殖兔子

$month = 12;
   $fab = array();
 
   $fab[0] = 1;
   $fab[1] = 1;
 
     for ($i = 2; $i < $month; $i++)
     {
         $fab[$i] = $fab[$i - 1] + $fab[$i - 2];
     }
 
     for ($i = 0; $i < $month; $i++)
     {
         echo sprintf("第{%d}個(gè)月兔子為:{%d}",$i, $fab[$i])."
"; }

8 .datetime

function getCurMonthFirstDay($date)
{
    return date("Y-m-01", strtotime($date));
}
 getCurMonthLastDay("2015-07-23")
function getCurMonthLastDay($date)
{
    return date("Y-m-d", strtotime(date("Y-m-01", strtotime($date)) . " +1 month -1 day"));
}

9.加密解密

function encrypt($data, $key)

{

    $key    =   md5($key);

    $x      =   0;

    $len    =   strlen($data);

    $l      =   strlen($key);

    $char   =   "";

    for ($i = 0; $i < $len; $i++)

    {

        if ($x == $l)

        {

            $x = 0;

        }

        $char .= $key{$x};

        $x++;

    }

    $str    =   "";

    for ($i = 0; $i < $len; $i++)

    {

        $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);

    }

    return base64_encode($str);

}

 

function decrypt($data, $key)

{

    $key = md5($key);

    $x = 0;

    $data = base64_decode($data);

    $len = strlen($data);

    $l = strlen($key);

    $char = "";

    for ($i = 0; $i < $len; $i++)

    {

        if ($x == $l)

        {

            $x = 0;

        }

        $char .= substr($key, $x, 1);

        $x++;

    }

    $str = "";

    for ($i = 0; $i < $len; $i++)

    {

        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))

        {

            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));

        }

        else

        {

            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));

        }

    }

    return $str;

}

10 . 多維數(shù)組降級(jí)

function array_flatten($arr) {
    $result = [];

    array_walk_recursive($arr, function($value) use (&$result) {
        $result[] = $value;
    });

    return $result;
}
print_r(array_flatten([1,[2,3],[4,5]]));// [1,[2,3],[4,5]] => [1,2,3,4,5]
//  var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
var test = [1,2,3,[4,5,6],[7,8]];
[].concat.apply([], test); // [1,2,3,4,5,6,7,8] 對(duì)于 test 數(shù)組中的每一個(gè) value, 將它 concat 到空數(shù)組 [] 中去,而因?yàn)?concat 是 Array 的 prototype,所以我們用一個(gè)空 array 作載體
var test1 = [1,2,[3,[4,[5]]]];

function flatten(arr) {
   return arr.reduce(function(pre, cur) {
        if(Array.isArray(cur)) {
            return flatten(pre.concat(cur));
        }

        return pre.concat(cur);
   }, []);
}

// [1,2,3,4,5]

11.json_encode中文

function json_encode_wrapper ($result)
{
    if(defined("JSON_UNESCAPED_UNICODE")){
        return json_encode($result,JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK);
    }else {
        return preg_replace(
            array("#u([0-9a-f][0-9a-f][0-9a-f][0-9a-f])#ie", "/"(d+)"/",),
            array("iconv("UCS-2", "UTF-8", pack("H4", "1"))", "1"),
            json_encode($result)
        );
    }
}

12.二維數(shù)組去重

$arr = array(

    array("id"=>"2","title"=>"...","ding"=>"1","jing"=>"1","time"=>"...","url"=>"...","dj"=>"..."),

    array("id"=>"2","title"=>"...","ding"=>"1","jing"=>"1","time"=>"...","url"=>"...","dj"=>"...")

);
function about_unique($arr=array()){  
   /*將該種二維數(shù)組看成一維數(shù)組,則      該一維數(shù)組的value值有相同的則干掉只留一個(gè),并將該一維      數(shù)組用重排后的索引數(shù)組返回,而返回的一維數(shù)組中的每個(gè)元素都是      原始key值形成的關(guān)聯(lián)數(shù)組    */    
$keys =array();
   $temp = array();
   foreach($arr[0] as $k=>$arrays) {
    /*數(shù)組記錄下關(guān)聯(lián)數(shù)組的key值*/     
    $keys[] = $k;
   }
   //return $keys;    /*降維*/    
foreach($arr as $k=>$v) {
    $v = join(",",$v);  //降維     
    $temp[] = $v;
   }
   $temp = array_unique($temp); //去掉重復(fù)的內(nèi)容    
foreach ($temp as $k => $v){
    /*再將拆開(kāi)的數(shù)組按索引數(shù)組重新組裝*/     
    $temp[$k] = explode(",",$v);  
   } 
   //return $temp;    /*再將拆開(kāi)的數(shù)組按關(guān)聯(lián)數(shù)組key值重新組裝*/    
foreach($temp as $k=>$v) {
    foreach($v as $kkk=>$ck) {
     $data[$k][$keys[$kkk]] = $temp[$k][$kkk];
    }
   }
   return $data;
  }

13.格式化字節(jié)大小

/**
* 格式化字節(jié)大小
* @param  number $size      字節(jié)數(shù)
* @param  string $delimiter 數(shù)字和單位分隔符
* @return string            格式化后的帶單位的大小
* @author 
*/
function format_bytes($size, $delimiter = "") {
  $units = array("B", "KB", "MB", "GB", "TB", "PB");
  for ($i = 0; $size >= 1024 && $i < 6; $i++) $size /= 1024;
  return round($size, 2) . $delimiter . $units[$i];
}

14.3分鐘前

/**
* 將指定時(shí)間戳轉(zhuǎn)換為截止當(dāng)前的xx時(shí)間前的格式  例如 return "3分鐘前""
* @param string|int $timestamp unix時(shí)間戳
* @return string
*/
function time_ago($timestamp) {
    $etime = time() - $timestamp;
    if ($etime < 1) return "剛剛";     
    $interval = array (         
      12 * 30 * 24 * 60 * 60  =>  "年前 (".date("Y-m-d", $timestamp).")",
      30 * 24 * 60 * 60       =>  "個(gè)月前 (".date("m-d", $timestamp).")",
      7 * 24 * 60 * 60        =>  "周前 (".date("m-d", $timestamp).")",
      24 * 60 * 60            =>  "天前",
      60 * 60                 =>  "小時(shí)前",
      60                      =>  "分鐘前",
      1                       =>  "秒前"
    );
    foreach ($interval as $secs => $str) {
        $d = $etime / $secs;
        if ($d >= 1) {
            $r = round($d);
            return $r . $str;
        }
    };
}

15.身份證號(hào)

/**
* 判斷參數(shù)字符串是否為天朝身份證號(hào)
* @param $id 需要被判斷的字符串或數(shù)字
* @return mixed false 或 array[有內(nèi)容的array boolean為真]
*/
function is_citizen_id($id) {
    //長(zhǎng)度效驗(yàn)  18位身份證中的X為大寫
    $id  = strtoupper($id);
    if(!(preg_match("/^d{17}(d|X)$/",$id) || preg_match("/^d{15}$/",$id))) {
      return false;
    }
    //15位老號(hào)碼轉(zhuǎn)換為18位 并轉(zhuǎn)換成字符串
    $Wi          = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1); 
    $Ai          = array("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"); 
    $cardNoSum   = 0;
    if(strlen($id)==16) {
        $id        = substr(0, 6)."19".substr(6, 9); 
        for($i = 0; $i < 17; $i++) {
          $cardNoSum += substr($id,$i,1) * $Wi[$i];
        }  
        $seq       = $cardNoSum % 11; 
        $id        = $id.$Ai[$seq];
    }
    //效驗(yàn)18位身份證最后一位字符的合法性
    $cardNoSum   = 0;
    $id17        = substr($id,0,17);
    $lastString  = substr($id,17,1);
    for($i = 0; $i < 17; $i++) {
        $cardNoSum += substr($id,$i,1) * $Wi[$i];
    }  
    $seq         = $cardNoSum % 11;
    $realString  = $Ai[$seq];
    if($lastString!=$realString) {return false;}
    //地域效驗(yàn)
    $oCity       =  array(11=>"北京",12=>"天津",13=>"河北",14=>"山西",15=>"內(nèi)蒙古",21=>"遼寧",22=>"吉林",23=>"黑龍江",31=>"上海",32=>"江蘇",33=>"浙江",34=>"安徽",35=>"福建",36=>"江西",37=>"山東",41=>"河南",42=>"湖北",43=>"湖南",44=>"廣東",45=>"廣西",46=>"海南",50=>"重慶",51=>"四川",52=>"貴州",53=>"云南",54=>"西藏",61=>"陜西",62=>"甘肅",63=>"青海",64=>"寧夏",65=>"新疆",71=>"臺(tái)灣",81=>"香港",82=>"澳門",91=>"國(guó)外");
    $City        = substr($id, 0, 2);
    $BirthYear   = substr($id, 6, 4);
    $BirthMonth  = substr($id, 10, 2);
    $BirthDay    = substr($id, 12, 2);
    $Sex         = substr($id, 16,1) % 2 ;//男1 女0
    //$Sexcn       = $Sex?"男":"女";
    //地域驗(yàn)證
    if(is_null($oCity[$City])) {return false;}
    //出生日期效驗(yàn)
    if($BirthYear>2078 || $BirthYear<1900) {return false;}
    $RealDate    = strtotime($BirthYear."-".$BirthMonth."-".$BirthDay);
    if(date("Y",$RealDate)!=$BirthYear || date("m",$RealDate)!=$BirthMonth || date("d",$RealDate)!=$BirthDay) {
        return false;
    }
    return array("id"=>$id,"location"=>$oCity[$City],"Y"=>$BirthYear,"m"=>$BirthMonth,"d"=>$BirthDay,"sex"=>$Sex);
}

16.獲取二維數(shù)組中某個(gè)key的集合

$user = array( 0 => array( "id" => 1, "name" => "張三", "email" => "zhangsan@sina.com", ), 1 => array( "id" => 2, "name" => "李四", "email" => "lisi@163.com", ), 2 => array( "id" => 5, "name" => "王五", "email" => "10000@qq.com", ), ...... );
$ids = array(); $ids = array_map("array_shift", $user);
$ids = array_column($user, "id");//php5.5
$names = array(); $names = array_reduce($user, create_function("$v,$w", "$v[$w["id"]]=$w["name"];return $v;"));

17.判斷一個(gè)數(shù)是否為素?cái)?shù)

function isPrime(number) {

   // If your browser doesn"t support the method Number.isInteger of ECMAScript 6,
   // you can implement your own pretty easily
   if (typeof number !== "number" || !Number.isInteger(number)) {
      // Alternatively you can throw an error.
      return false;
   }
 
   if (number < 2) {
      return false;
   }
    
   if (number === 2) {
      return true;
   } else if (number % 2 === 0) {
      return false;
   }
 
   var squareRoot = Math.sqrt(number);
   for(var i = 3; i <= squareRoot; i += 2) {
      if (number % i === 0) {
         return false;
      }
   }
 
   return true;
}
function isPrime($n) {//TurkHackTeam AVP production
? ? if ($n <= 3) {
? ? ? ? return $n > 1;
? ? } else if ($n % 2 === 0 || $n % 3 === 0) {
? ? ? ? return false;
? ? } else {
? ? ? ? for ($i = 5; $i * $i <= $n; $i += 6) {
? ? ? ? ? ? if ($n % $i === 0 || $n % ($i + 2) === 0) {
? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return true;
? ? }
}

18.閉包

var nodes = document.getElementsByTagName("button");
for (var i = 0; i < nodes.length; i++) {
   nodes[i].addEventListener("click", (function(i) {
      return function() {
         console.log("You clicked element #" + i);
      }
   })(i));
}
//將函數(shù)移動(dòng)到循環(huán)外部即可(創(chuàng)建了一個(gè)新的閉包對(duì)象)
function handlerWrapper(i) {
   return function() {
      console.log("You clicked element #" + i);
   }
}
 
var nodes = document.getElementsByTagName("button");
for (var i = 0; i < nodes.length; i++) {
   nodes[i].addEventListener("click", handlerWrapper(i));
}

19.事件循環(huán) Event Loop

function printing() {
   console.log(1); 
   setTimeout(function() { console.log(2); }, 1000); 
   setTimeout(function() { console.log(3); }, 0); 
   console.log(4);
}
 //即使setTimeout的延遲為0,其回調(diào)也會(huì)被加入到那些沒(méi)有延遲的函數(shù)隊(duì)列之后。
printing();//1432

20.字典排序

def mysort():
    dic = {"a":31, "bc":5, "c":3, "asd":4, "aa":74, "d":0}
    dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True)
    print dict//[("aa", 74), ("a", 31), ("bc", 5), ("asd", 4), ("c", 3), ("d", 0)]

21.數(shù)值縮寫

var abbr = function (number) {
    var abbrList = ["", "K", "M", "G", "T", "P", "E", "Z", "Y"];
    var step = 1000;
    var i = 0;
    var j = abbrList.length;

    while (number >= step && ++i < j) {
        number = number / step;
    }

    if (i === j) {
        i = j - 1;
    }
    

    return number + abbrList[i];
};

22.數(shù)字千位分隔符

var format = function (number) {
    return String(number).replace(/(d)(?=(d{3})+$)/g, "$1,");
};

23.實(shí)現(xiàn)隨機(jī)顏色值

var randomColor = function () {
    var letters = "0123456789ABCDEF";
    var ret = "#";

    for (var i = 0; i < 6; i++) {
        ret += letters[Math.round(Math.random() * 15)];
    }

    return ret;
};
var randomColor = function () {
    return "#" + Math.random().toString(16).substr(2, 6);
};

24.時(shí)間格式化輸出

//formatDate(new Date(1409894060000), "yyyy-MM-dd HH:mm:ss 星期w") 2014-09-05 13:14:20 星期五
function formatDate(oDate, sFormation) {
    var obj = {
        yyyy:oDate.getFullYear(),
        yy:(""+ oDate.getFullYear()).slice(-2),//非常精辟的方法
        M:oDate.getMonth()+1,
        MM:("0"+ (oDate.getMonth()+1)).slice(-2),
        d:oDate.getDate(),
        dd:("0" + oDate.getDate()).slice(-2),
        H:oDate.getHours(),
        HH:("0" + oDate.getHours()).slice(-2),
        h:oDate.getHours() % 12,
        hh:("0"+oDate.getHours() % 12).slice(-2),
        m:oDate.getMinutes(),
        mm:("0" + oDate.getMinutes()).slice(-2),
        s:oDate.getSeconds(),
        ss:("0" + oDate.getSeconds()).slice(-2),
        w:["日", "一", "二", "三", "四", "五", "六"][oDate.getDay()]
    };
    return sFormation.replace(/([a-z]+)/ig,function($1){return obj[$1]});
}

25.斐波那契數(shù)列

function fibonacci(n) {
    if(n ==1 || n == 2){
        return 1
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

26.數(shù)組去重

Array.prototype.distinct=function(){
    var arr=[];
    var obj={};
    for(var i=0;i

27.刪除元素

function array_delete($array, $element) {
    return array_diff($array, [$element]);
   // if(($key = array_search($array, $element)) !== false) {
      //  unset($array[$key]);
   // }
//$array = array_filter($array, function($e) use ($del_val) {
 //   return ($e !== $del_val);
//});
//$array = array(14,22,37,42,58,61,73,82,96,10);
//array_splice($array, array_search(58, $array ), 1);
}

array_delete( [312, 401, 1599, 3], 401 ) // returns [312, 1599, 3]

28.RandomString

def random_string(length):
    return "".join(random.choice(string.letters + string.digits) for i in xrange(length))


function generateRandomString($length = 10) {
    $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $charactersLength = strlen($characters);
    $randomString = "";
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
//$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
//$string = bin2hex(openssl_random_pseudo_bytes(10));20 char long hexdec string

29.保存文件

$ch = curl_init("http://example.com/image.php");
$fp = fopen("/my/folder/flower.gif", "wb");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

30.插入數(shù)組元素

function array_insert(&$array, $position, $insert)
{
    if (is_int($position)) {
        array_splice($array, $position, 0, $insert);
    } else {
        $pos   = array_search($position, array_keys($array));
        $array = array_merge(
            array_slice($array, 0, $pos),
            $insert,
            array_slice($array, $pos)
        );
    }
}
$arr = [
    "name"  => [
        "type"      => "string",
        "maxlength" => "30",
    ],
    "email" => [
        "type"      => "email",
        "maxlength" => "150",
    ],
];

array_insert(
    $arr,
    "email",
    [
        "phone" => [
            "type"   => "string",
            "format" => "phone",
        ],
    ]
);
// ->
array (
  "name" =>
  array (
    "type" => "string",
    "maxlength" => "30",
  ),
  "phone" =>
  array (
    "type" => "string",
    "format" => "phone",
  ),
  "email" =>
  array (
    "type" => "email",
    "maxlength" => "150",
  ),
)

31.驗(yàn)證ip

function validate_ip($ip)
    {
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) === false)
            return false;
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) === false)
            return false;
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false && filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false)
            return false;

        return true;
    }
    function validate_ip($ip)
{
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false)
    {
        return false;
    }

    self::$ip = sprintf("%u", ip2long($ip)); // you seem to want this

    return true;
}

32.get ip

function get_ip_address(){
    foreach (array("HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "REMOTE_ADDR") as $key){
        if (array_key_exists($key, $_SERVER) === true){
            foreach (explode(",", $_SERVER[$key]) as $ip){
                $ip = trim($ip); // just to be safe

                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                    return $ip;
                }
            }
        }
    }
}

33.選出最長(zhǎng)的單詞

function LongestWord(sen) {
    var words = sen.match(/w+/g);
    if (words !== null) {
        var maxWords = {
            index: 0,
            length: 0
        };
        for (var i = 0, length = words.length; i < length; i++) {
            if (words[i].length > maxWords.length) {
                maxWords = {
                    index: i,
                    length: words[i].length
                }
            }
        }
        return words[maxWords.index];
    }
    return words;
}

34.map

var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}];

function getNewArr(){
        
    return oldArr.map(function(item,index){
        item.full_name = [item.first_name,item.last_name].join(" ");
        return item;
    });
    
}

35.統(tǒng)計(jì)一個(gè)數(shù)組中有多少個(gè)不重復(fù)的單詞

var arr = ["apple","orange","apple","orange","pear","orange"];
//https://github.com/es-shims/es5-shim
function getWordCnt(){
    var obj = {};
    
    for(var i= 0, l = arr.length; i< l; i++){
        var item = arr[i];
        obj[item] = (obj[item] +1 ) || 1;//obj[item]為undefined則返回1
    }
    
    return obj;
}
function getWordCnt(){
    return arr.reduce(function(prev,next){
        prev[next] = (prev[next] + 1) || 1;
        return prev;
    },{});
}

36.約瑟夫環(huán)

function yuesefu($n,$m) {  
    $r=0;  
    for($i=2; $i<=$n; $i++) {
        $r=($r+$m)%$i;  
    }
    return $r+1;  
}  
echo yuesefu(10,3)."是猴王";

37.判斷一個(gè)字符串中的字符是否都在另一個(gè)中出現(xiàn)

function charsissubset($h, $n) {
    return preg_match("/[^" . preg_quote($h) . "]/u", $n) ? 0 : 1;
}

echo charsissubset("abcddcba", "abcde"); // false
echo charsissubset("abcddcba", "abcd"); // true
echo charsissubset("abcddcba", "badc"); // true
echo charsissubset("漢字", "字"); // true
echo charsissubset("漢字", "漢字"); // false

38.add(2)(3)(4)

function add(a) {
  var temp = function(b) {
    return add(a + b);
  }
  temp.valueOf = temp.toString = function() {
    return a;
  };
  return temp;
}
var ans = add(2)(3)(4);//9
function add(num){
  num += ~~add;
  add.num = num;
  return add;
}
add.valueOf = add.toString = function(){return add.num};
var ans = add(3)(4)(5)(6);  // 18

39.打印出Fibonacci數(shù)

function fn(n) {
  var a = [];
  a[0] = 0, a[1] = 1;
  for(var i = 2; i < n; i++)
    a[i] = a[i - 1] + a[i - 2];
  for(var i = 0; i < n; i++)
    console.log(a[i]);
}

40.把URL參數(shù)解析為一個(gè)對(duì)象

function parseQueryString(url) {
  var obj = {};
  var a = url.split("?");
  if(a.length === 1) return obj;
  var b = a[1].split("&");
  for(var i = 0, length = b.length; i < length; i++) {
    var c = b[i].split("=");
    obj[c[0]] = c[1];
  }
  return obj;
}
var url = "http://witmax.cn/index.php?key0=0&key1=1&key2=2";
var obj = parseQueryString(url);
console.log(obj.key0, obj.key1, obj.key2);  // 0 1 2 

41.判斷數(shù)據(jù)類型

function isNumber(obj) {
    return Object.prototype.toString.call(obj) === "[object Number]"
}//對(duì)于NaN也返回true
function isNumber(obj) {
    return obj === +obj
}
// 判斷字符串
function isString(obj) {
    return obj === obj+""
}
// 判斷布爾類型
function isBoolean(obj) {
    return obj === !!obj
}

42.javascript sleep

function sleep(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
        return;
    }
}

43.爬蟲

def splider():
    # -*- coding:utf-8 -*-
    #發(fā)送data表單數(shù)據(jù)
    import urllib2
    import urllib
    url = "http://www.someserver.com/register.cgi"
    values = {
        "name" : "Andrew",
        "location" : "NJU",
        "language" : "Python"
    }
    user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)" 
    header = {"User-Agent" : user_agent}
    data = urllib.urlencode(values) #data數(shù)據(jù)需要編碼成標(biāo)準(zhǔn)形式
    #print data
    http_handler = urllib2.HTTPHandler(debuglevel = 1)#Debug log
    https_handler = urllib2.HTTPSHandler(debuglevel = 1)
    opener = urllib2.build_opener(http_handler, https_handler)
    urllib2.install_opener(opener)
    req = urllib2.Request(url, data) #發(fā)送請(qǐng)求同時(shí)傳送data表單
    #req = urllib2.Request(url, data, header) #url 表單數(shù)據(jù) 偽裝頭部
    reponse = urllib2.urlopen(req, timeout=10) #接受反饋數(shù)據(jù)
    html = reponse.read() #讀取反饋數(shù)據(jù)
    print response.info()
    print response.getcode()
    redirected = response.geturl() == url
    """
    full_url = url + "?" + data
    data = urllib2.open(full_url)
    """
    #返回錯(cuò)誤碼, 200不是錯(cuò)誤, 不會(huì)引起異常
    headers = {
    "Referer": "http://www.cnbeta.com/articles"
    }
    proxy_handler = urllib2.ProxyHandler({"http" : "http://some-proxy.com:8080"})
    opener = urllib2.build_opener(proxy_handler)
    urllib2.install_opener(opener)  #urllib2.install_opener() 會(huì)設(shè)置 urllib2 的全局 opener
    req = urllib2.Request(
    url = "http://secure.verycd.com/signin/*/http://www.verycd.com/",
    data = post_data, 
    headers = headers
    )
    try:
        urllib2.urlopen(req)
    except urllib2.HTTPError, e:
        print e.code
        #print e.read()

44.判斷數(shù)據(jù)類型

function type(o) {
    var t, c, n;
    if (o === null) 
        return "null";
    if (o !== o)
        return "nan";
    if ((t = typeof o) !== "object") 
        return t;  // 識(shí)別原始值的類型和函數(shù)
    if ((c = classof(o)) !== "Object")
        return c;  // 識(shí)別出大多數(shù)內(nèi)置類型
    if (o.constructor && typeof o.constructor === "function" &&
        (n = o.constructor.getName()))
        return n;  //如果對(duì)象構(gòu)造函數(shù)名字存在, 則返回
    return "Object";  // 無(wú)法識(shí)別類型返回"Object"
}
function classof(o) {
    return Object.prototype.toString.call(o).slice(8, -1);
}
Function.prototype.getName = function() {
    if ("name" in this)
        return this.name;
    return this.name = this.toString().match(/functions*([^(]*)(/)[1];
}

45.實(shí)現(xiàn)千分位分隔

function mysplit(s){
        if(/[^0-9.]/.test(s)) return "invalid value";
        s=s.replace(/^(d*)$/,"$1.");
        s=(s+"00").replace(/(d*.dd)d*/,"$1");
        s=s.replace(".",",");
        var re=/(d)(d{3},)/;
        while(re.test(s))
            s=s.replace(re,"$1,$2");
        s=s.replace(/,(dd)$/,".$1");
        return "¥" + s.replace(/^./,"0.")
    }

46.隨機(jī)產(chǎn)生顏色

function randomVal(val){
        return Math.floor(Math.random()*(val + 1));
    }

    function randomColor(){
        return "rgb(" + randomVal(255) + "," + randomVal(255) + "," + randomVal(255) + ")";
    }

47.生成隨機(jī)的IP地址,規(guī)則類似于192.168.11.0/24

RANDOM_IP_POOL=["192.168.10.222/0"]
def __get_random_ip():
    str_ip = RANDOM_IP_POOL[random.randint(0,len(RANDOM_IP_POOL) - 1)]
    str_ip_addr = str_ip.split("/")[0]
    str_ip_mask = str_ip.split("/")[1]
    ip_addr = struct.unpack(">I",socket.inet_aton(str_ip_addr))[0]
    mask = 0x0
    for i in range(31, 31 - int(str_ip_mask), -1):
        mask = mask | ( 1 << i)
    ip_addr_min = ip_addr & (mask & 0xffffffff)
    ip_addr_max = ip_addr | (~mask & 0xffffffff)
    return socket.inet_ntoa(struct.pack(">I", random.randint(ip_addr_min, ip_addr_max)))

48.倒計(jì)時(shí)

var total = 500;
var timer = null;

var tiktock = document.getElementById("tiktock");
var btn = document.getElementById("btn");

function countdown(){
    timer = setInterval(function(){
        total--;
        if (total<=0) {
            clearInterval(timer);
            tiktock.innerHTML= "0:00";
        }else{
            var ss = Math.floor(total/100);
            var ms = total-Math.floor(total/100)*100;
            tiktock.innerHTML=ss + ":" + ms;
        }
    },10);
};
btn.addEventListener("click", countdown, false);

49.[1,2,3] ->"{1,2,3}"

class intSet(object):

def __init__(self):
    # creat an empty set of integers
    self.vals = []

def insert(self, e):
    # assume e is an interger, and insert it 
    if not(e in self.vals):
        self.vals.append(e)

def member(self, e):
    return e in self.vals

def remove(self, e):
    try:
        self.vals.remove(e)
    except:
        raise ValueError(str(e) + "not found")


def __str__(self):
    # return a string representation of self
    self.vals.sort()
    return "{" + ",".join([str(e) for e in self.vals]) + "}"

50.轉(zhuǎn)義過(guò)濾

//純數(shù)字的參數(shù)intval強(qiáng)制取整
//其他參數(shù)值進(jìn)行過(guò)濾或者轉(zhuǎn)義
//filter_input() 函數(shù)來(lái)過(guò)濾一個(gè) POST 變量
if (!filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL))
 {
 echo "E-Mail is not valid";
 }
else
 {
 echo "E-Mail is valid";
 }
    protected function zaddslashes($string, $force = 0, $strip = FALSE)
    {   
        if (!defined("MAGIC_QUOTES_GPC"))
        {   
         define("MAGIC_QUOTES_GPC", "");
        }   
        if (!MAGIC_QUOTES_GPC || $force)
        {   
         if (is_array($string)) {
             foreach ($string as $key => $val)
             {   
                 $string[$key] = $this->zaddslashes($val, $force, $strip);
             }   
         }   
         else
         {   
             $string = ($strip ? stripslashes($string) : $string);
             $string = htmlspecialchars($string);
         }   
        }   
        return $string;
     }

51.構(gòu)造IP

function getIPaddress()
{
? ? $IPaddress = "";
? ? if (isset($_SERVER)) {
? ? ? ? if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
? ? ? ? ? ? $IPaddress = $_SERVER["HTTP_X_FORWARDED_FOR"];
? ? ? ? } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
? ? ? ? ? ? $IPaddress = $_SERVER["HTTP_CLIENT_IP"];
? ? ? ? } else {
? ? ? ? ? ? $IPaddress = $_SERVER["REMOTE_ADDR"];
? ? ? ? }
? ? } else {
? ? ? ? if (getenv("HTTP_X_FORWARDED_FOR")) {
? ? ? ? ? ? $IPaddress = getenv("HTTP_X_FORWARDED_FOR");
? ? ? ? } else if (getenv("HTTP_CLIENT_IP")) {
? ? ? ? ? ? $IPaddress = getenv("HTTP_CLIENT_IP");
? ? ? ? } else {
? ? ? ? ? ? $IPaddress = getenv("REMOTE_ADDR");
? ? ? ? }
? ? }
? ? return $IPaddress;
}
function curlPost($url, $post="", $autoFollow=0){
        $ch = curl_init();
        $user_agent = "Safari Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.73.11 (KHTML, like Gecko) Version/7.0.1 Safari/5
        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($ch, CURLOPT_HEADER, 0); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-FORWARDED-FOR:61.135.169.125", "CLIENT-IP:".getIPaddress()));  //構(gòu)造IP
        curl_setopt($ch, CURLOPT_REFERER, "http://www.baidu.com/");   //構(gòu)造來(lái)路
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        if($autoFollow){
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);  //啟動(dòng)跳轉(zhuǎn)鏈接
            curl_setopt($ch, CURLOPT_AUTOREFERER, true);  //多級(jí)自動(dòng)跳轉(zhuǎn)
        }   
        //  
        if($post!=""){
            curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }   
        
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

52.文件名生成唯一

function unique_filename() {
    $time = !empty($_SERVER["REQUEST_TIME_FLOAT"]) ? $_SERVER["REQUEST_TIME_FLOAT"] : mt_rand();
    $addr = !empty($_SERVER["REMOTE_ADDR"])        ? $_SERVER["REMOTE_ADDR"]        : mt_rand();
    $port = !empty($_SERVER["REMOTE_PORT"])        ? $_SERVER["REMOTE_PORT"]        : mt_rand();
    $ua   = !empty($_SERVER["HTTP_USER_AGENT"])    ? $_SERVER["HTTP_USER_AGENT"]    : mt_rand();
    return md5(uniqid(mt_rand(), true).$time.$addr.$port.$ua.mt_rand());
}

53.PHP實(shí)現(xiàn)鉤子和插件系統(tǒng)

/**
 * Attach (or remove) multiple callbacks to an event and trigger those callbacks when that event is called.
 * 綁定或移除多個(gè)回調(diào)函數(shù)到事件,當(dāng)事件被調(diào)用時(shí)觸發(fā)回調(diào)函數(shù).
 *
 * @param string $event name
 * @param mixed  $value the optional value to pass to each callback
 * @param mixed  $callback the method or function to call - FALSE to remove all callbacks for event
 */
function event($event, $value = NULL, $callback = NULL) {
    static $events;
    if($callback !== NULL) {
        if($callback) {
            $events[$event][] = $callback; // 添加事件
        } else {
            unset($events[$event]); // 移除事件里所有的回調(diào)函數(shù)
        }
    } else if(isset($events[$event])) {
        foreach($events[$event] as $function) {
            $value = call_user_func($function, $value); // 調(diào)用事件
        }
        return $value;
    }
}
// 添加事件
event("filter_text", NULL, function($text) { return htmlspecialchars($text); });
event("filter_text", NULL, function($text) { return nl2br($text); });
// 移除事件里所有的回調(diào)函數(shù)
// event("filter_text", NULL, FALSE);
// 調(diào)用事件
$text = event("filter_text", $_POST["text"]);

54.字符串首字母大寫的實(shí)現(xiàn)方式

String.prototype.firstUpperCase = function(){
    return this.replace(/(w)(w*)/g, function($0, $1, $2) {
        return $1.toUpperCase() + $2.toLowerCase();
    });
}
//這只能改變字符串首字母
String.prototype.firstUpperCase=function(){
    return this.replace(/^S/,function(s){return s.toUpperCase();});
}

55.獲取url參數(shù)

 function getQueryString(key){
        var reg = new RegExp("(^|&)"+key+"=([^&]*)(&|$)");
        var result = window.location.search.substr(1).match(reg);
        return result?decodeURIComponent(result[2]):null;
      }
function getRequest() {   
       var url = window.location.search; //獲取url中"?"符后的字串   
       var theRequest = new Object();   
       if (url.indexOf("?") != -1) {   
          var str = url.substr(1);   
          strs = str.split("&");   
          for(var i = 0; i < strs.length; i ++) {   
             theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]); 

          }   
       }   
       return theRequest;   
    }

56.過(guò)濾

var array = [
    {
        "title": 123,
        "num": 1,
        "type": [{"name": "A", "num": 1}, {"name": "B", "num": 1}, {"name": "C", "num": 0}]
    }, {
        "title": 321,
        "num": 1,
        "type": [{"name": "D", "num": 0}, {"name": "E", "num": 1}, {"name": "F", "num": 0}]
    }];

array.forEach(function (x) {
    x.type = x.type.filter(function (y) {
        return y.num != 0;
    });
});

57.隨機(jī)生成-50到50之間的不包括0的整數(shù)

function my_rand(){
    $num = mt_rand(1, 50); 
    $rand = mt_rand(1, 10);

    return $rand > 4 ? $num : -$num;//控制生成正負(fù)數(shù)的比例為4:6
}

58.時(shí)間對(duì)比

function compareDate(date1, date2){
      var  difArr, unitArr;

      date1 = new Date(date1);
      date2 = new Date(date2);
      difArr = [date1.getFullYear() - date2.getFullYear(), date1.getMonth() -date2.getMonth(),date1.getDate() - date2.getDate(),date1.getHours() - date2.getHours(), date1.getMinutes() - date2.getMinutes(),date1.getSeconds() - date2.getSeconds()];
      unitArr = ["年","月","日","時(shí)","分","秒"]
      for(var i = 0; i < 6;i++){
        if(difArr[i] !== 0){
          return Math.abs(difArr[i]) + unitArr[i];
        }
      }
    }

59.數(shù)組去重

//傳入數(shù)組
  function unique(arr){
    var tmpArr = [];
    for(var i=0; i

60.繼承

/*
 * 基類,定義屬性
 */
function Person(name, age) {
    this.name = name;
    this.age = age;
}

/*
 * 基類,定義方法
 */
Person.prototype.selfIntroduce = function () {
    console.log("name: " + this.name);
    console.log("age: " + this.age);
}

/*
 * 子類,定義子類的屬性
 */
function Student(name, age, school) {
  // 調(diào)用基類的構(gòu)造函數(shù)
    Person.call(this, name, age);
    this.school = school;
}

// 使子類繼承基類
Student.prototype = new Person();

/*
 * 定義子類的方法
 */
Student.prototype.goToSchool = function() {
  // some code..
}

/*
 * 擴(kuò)展并調(diào)用了超類的方法
 */
Student.prototype.selfIntroduce = function () {
    Student.prototype.__proto__.selfIntroduce.call(this);
    console.log("school: " + this.school);
}

var student = new Student("John", 22, "My School");
student.selfIntroduce();

61.Unicode和Utf-8編碼的互相轉(zhuǎn)換

/**
 * utf8字符轉(zhuǎn)換成Unicode字符
 * @param  [type] $utf8_str Utf-8字符
 * @return [type]           Unicode字符
 */
function utf8_str_to_unicode($utf8_str) {
    $unicode = 0;
    $unicode = (ord($utf8_str[0]) & 0x1F) << 12;
    $unicode |= (ord($utf8_str[1]) & 0x3F) << 6;
    $unicode |= (ord($utf8_str[2]) & 0x3F);
    return dechex($unicode);
}

/**
 * Unicode字符轉(zhuǎn)換成utf8字符
 * @param  [type] $unicode_str Unicode字符
 * @return [type]              Utf-8字符
 */
function unicode_to_utf8($unicode_str) {
    $utf8_str = "";
    $code = intval(hexdec($unicode_str));
    //這里注意轉(zhuǎn)換出來(lái)的code一定得是整形,這樣才會(huì)正確的按位操作
    $ord_1 = decbin(0xe0 | ($code >> 12));
    $ord_2 = decbin(0x80 | (($code >> 6) & 0x3f));
    $ord_3 = decbin(0x80 | ($code & 0x3f));
    $utf8_str = chr(bindec($ord_1)) . chr(bindec($ord_2)) . chr(bindec($ord_3));
    return $utf8_str;
}

62.gzip編碼

function curl_get($url, $gzip=false){
 $curl = curl_init($url);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
 if($gzip) curl_setopt($curl, CURLOPT_ENCODING, "gzip"); // 關(guān)鍵在這里
 $content = curl_exec($curl);
 curl_close($curl);
 return $content;
}
$url = "http://api.stackexchange.com/2.2/tags?order=asc&sort=popular&site=stackoverflow&tag=qt";
//$data = file_get_contents("compress.zlib://".$url);

63.Python中文時(shí)間

#!/usr/bin/env 
# -*- coding: utf-8 -*-

from datetime import datetime
nt=datetime.now()
print(nt.strftime("%Y年%m月%d日 %H時(shí)%M分%S秒").decode("utf-8"))#2015年08月10日 11時(shí)25分04秒
print(nt.strftime("%Y{y}%m{m}%djtj7p5d").format(y="年", m="月", d="日"))

64.list分組,按照下標(biāo)順序分成3組:[3, 8, 9] [4, 1, 10] [6, 7, 2, 5]

a=[1,2,3,4,5,6,7,8,9,10]
[a[i:i+3] for i in xrange(0,len(a),3)]

64.curl上傳文件

$ch = curl_init();

$data = array("name" => "Foo", "file" => "@/home/vagrant/test.png");

curl_setopt($ch, CURLOPT_URL, "http://localhost/test/curl/load_file.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);    // 5.6 給改成 true了, 弄回去 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);

65.IP地址轉(zhuǎn)換為整數(shù)型

$ipArr  = explode(".",$_SERVER["REMOTE_ADDR"]);
$ip     = $ipArr[0] * 0x1000000
        + $ipArr[1] * 0x10000
        + $ipArr[2] * 0x100
        + $ipArr[3];
        //數(shù)字型的IP轉(zhuǎn)為字符型:
$ipVal = $row["client_IP"];
$ipArr = array(
        0 => floor(  $ipVal / 0x1000000) );
$ipVint   = $ipVal-($ipArr[0]*0x1000000); // for clarity
$ipArr[1] = ($ipVint & 0xFF0000)  >> 16;
$ipArr[2] = ($ipVint & 0xFF00  )  >> 8;
$ipArr[3] =  $ipVint & 0xFF;
$ipDotted = implode(".", $ipArr);

66.保存base64圖片

$base64_url = "data:image/jpeg;base64,xxxxxxxxxxxxxxxxxxxxxx";
$base64_body = substr(strstr($base64_url,","),1);
$data= base64_decode($base64_body );

//存儲(chǔ)or創(chuàng)建圖片:

file_put_contents($file_path,$data);

或$image = imagecreatefromstring($data);
 $size  =  getimagesizefromstring ( $data);var_dump($size);

//讀取圖片文件,轉(zhuǎn)換成base64編碼格式
$image_file = "test.jpg";
$image_info = getimagesize($image_file);
$base64_image_content = "data:{$image_info["mime"]};base64," . chunk_split(base64_encode(file_get_contents($image_file)));
 
//保存base64字符串為圖片
//匹配出圖片的格式
if (preg_match("/^(data:s*image/(w+);base64,)/", $base64_image_content, $result)){
  $type = $result[2];
  $new_file = "./test.{$type}";
  if (file_put_contents($new_file, base64_decode(str_replace($result[1], "", $base64_image_content)))){
    echo "新文件保存成功:", $new_file;
  }
 
}
?>
 

67.日志記錄print_r( $value, true )

/**

錯(cuò)誤日志類
*/
class C_Log
{
/**

日志保存目錄

@var string
*/
private $path = "";
/**

只能運(yùn)行一個(gè)實(shí)例

@var [type]
*/
private static $instance;
/**

構(gòu)造函數(shù)

初始化日志文件地址
*/
function __construct($path)
{
$this->path = $path;
}

public function logPrint($name,$value)
{

   //獲取時(shí)間
   $_o = date("Y-m-d H:m:s",time())."
";
   $_o .= "==".  $name . "==";
   //打印內(nèi)容
   if( is_array( $value ) || is_object( $value ) ){
       $_o .= print_r( $value, true ). "
";
     } else {
         $_o .= $value. "
";
     }
     //輸出到文件
     $this->_log($_o);
}
/**fdf

打印日志

@return [type] [description]
*/
private function _log($log){
error_log($log,3,$this->path);
}
/**

輸出日志

@return [type] [description]
*/
public static function log($name, $value)
{
if (empty(self::$instance)) {

   self::$instance = new C_Log(__DIR__."/error_log.log");
}
self::$instance->logPrint($name, $value);
}
}

68.過(guò)濾子類

function getByClass(parent, classname) {
    var tags = parent.getElementsByTagName("*");
    return [].filter.call(tags, function(t) {
        return t.classList.contains(classname);
    });
}
//

function getByClass(parent, classname) {
    return parent.querySelectorAll("." + classname);
}

69.JSON.stringify

function setProp(obj) {
    for (var p in obj) {
        switch (typeof (obj[p])) {
            case "object":
                setProp(obj[p]);
                break;
            case "undefined":
                obj[p] = "";
                break;
        }
    }
    return obj;
}

JSON.stringify(setProp({ a: 1, b: 2, c: undefined }));//{"a":1,"b":2,"c":""}

70.判斷用戶的IP是否局域網(wǎng)IP

function is_local_ip($ip_addr = null) {
    if (is_null($ip_addr)) {
        $ip_addr = $_SERVER["REMOTE_ADDR"];
    }
    $ip = ip2long($ip_addr);
    return $ip & 0xffff0000 == 0xc0a80000 // 192.168.0.0/16
        || $ip & 0xfff00000 == 0xac100000 // 172.16.0.0/12
        || $ip & 0xff000000 == 0xa0000000 // 10.0.0.0/8
        || $ip & 0xff000000 == 0x7f000000 // 127.0.0.0/8
    ;
}

71.遍歷出當(dāng)月的所有日子和星期

var d = new Date();         // 這是當(dāng)天
d.setDate(1);               // 這就是1號(hào)
var weekday = d.getDay();   // 1號(hào)星期幾,從星期天為0開(kāi)始

d.setMonth(d.getMonth() + 1);
d.setDate(0);               // 這兩句得到最當(dāng)月最后一天
var end = d.getDate();      // 最后一天的日,比如8月就是31

var days = [];
for (var i = 0; i < end; i++) {
    days[i] = {
        day: i + 1,
        week: (weekday + i) % 7
    }
}


console.log(days);

72.Downloading Data From localStorage

var myData = {
    "a": "a",
    "b": "b",
    "c": "c"
};
// add it to our localstorage
localStorage.setItem("data", JSON.stringify(myData));

// encode the data into base64
base64 = window.btoa(localStorage.getItem("data"));

// create an a tag
var a = document.createElement("a");
a.href = "data:application/octet-stream;base64," + base64;
a.innerHTML = "Download";

// add to the body
document.body.appendChild(a);

73."數(shù)據(jù)類型"判斷函數(shù)

function datatypeof(arg){
    return Object.prototype.toString.call(arg).match(/[objects(w+)]/)[1];
}

74.二維數(shù)組去除重復(fù),重復(fù)值相加

$arr = array(
    array("id" => 123, "name" => "張三", "amount"=>"1"),
    array("id" => 123, "name" => "李四", "amount" => "1"),
    array("id" => 124, "name" => "王五", "amount" => "1"),
    array("id" => 125, "name" => "趙六", "amount" => "1"),
    array("id" => 126, "name" => "趙六", "amount" => "2"),
    array("id" => 126, "name" => "趙六", "amount" => "2")
);

$new = array();

foreach($arr as $row){
    if(isset($new[$row["name"]])){
        $new[$row["name"]]["amount"] += $row["amount"];
    }else{
        $new[$row["name"]] = $row;
    }
}

75.含有從屬關(guān)系的元素重新排列

$arr = array(
    array("id"=>21, "pid"=>0, "name"=>"aaa"),
    array("id"=>22, "pid"=>0, "name"=>"bbb"),
    array("id"=>23, "pid"=>0, "name"=>"ccc"),
    array("id"=>24, "pid"=>23, "name"=>"ffffd"),
    array("id"=>25, "pid"=>23, "name"=>"eee"),
    array("id"=>26, "pid"=>22, "name"=>"fff"),
    );

$temp=[];
foreach ($arr as $item)
{
    list($id,$pid,$name) = array_values($item); // 取出數(shù)組的值并分別生成變量

    if(array_key_exists($pid, $temp)) 
    // 檢查臨時(shí)數(shù)組$temp中是否存在鍵名與$pid的值相同的鍵
    {
        $temp[$pid]["child"][]=array("id"=>$id,"pid"=>$pid,"name"=>$name);
        // 如果存在則新增數(shù)組至臨時(shí)數(shù)組中鍵名為 $pid 的子元素 child 內(nèi)
    }else
        $temp[$id]=array("id"=>$id,"pid"=>$pid,"name"=>$name);
        // 如果不存在則新增數(shù)組至臨時(shí)數(shù)組中并設(shè)定鍵名為 $id
}

$array = array_values($temp);
// 將臨時(shí)數(shù)組中以 $id 為鍵名的鍵修改為數(shù)字索引

echo "
";
print_r($array);
//or 
foreach ($arr as $item)
{
    if (array_key_exists($item["pid"], $temp))
    {       
        $temp[$item["pid"]]["child"][]=$item;
    }else
        $temp[$item["id"]]=$item;
}

76.隨機(jī)中文字符

//正則表達(dá)式匹配中文[u4e00-u9fa5]
//parseInt("4E00",16) 19968 parseInt("9FA5",16);20901
var randomHz=function(){
    eval( "var word=" +  ""u" + (Math.round(Math.random() * 20901) + 19968).toString(16)+""");
    return word;
}
for(i=0;i<100;i++){
    console.log(randomHz());
}

77.jQuery解析url

$(document).ready(function () {
    var url = "http://iwjw.com/codes/code-repository?id=12#top";
    var a = $("", { href: url});
    var sResult = "Protocol: " + a.prop("protocol") + "
" + "Host name: " + a.prop("hostname") + "
" + "Path: " + a.prop("pathname") + "
" + "Query: " + a.prop("search") + "
" + "Hash: " + a.prop("hash"); $("span").html(sResult); });

78.用JS實(shí)現(xiàn)一個(gè)數(shù)組合并的方法(要求去重)

var arr1 = ["a"];
var arr2 = ["b", "c"];
var arr3 = ["c", ["d"], "e", undefined, null];

var concat = (function(){
  // concat arr1 and arr2 without duplication.
  var concat_ = function(arr1, arr2) {
    for (var i=arr2.length-1;i>=0;i--) {
      arr1.indexOf(arr2[i]) === -1 ? arr1.push(arr2[i]) : 0;
    }
  };
  // concat arbitrary arrays.
  // Instead of alter supplied arrays, return a new one.
  return function(arr) {
    var result = arr.slice();
    for (var i=arguments.length-1;i>=1;i--) {
      concat_(result, arguments[i]);
    }
    return result;
  };
}());
執(zhí)行:concat(arr1, arr2, arr3)
返回:[ "a", null, undefined, "e", [ "d" ], "c", "b" ]
var merge = function() {
    return Array.prototype.concat.apply([], arguments)
  }

merge([1,2,4],[3,4],[5,6]);
//[1, 2, 4, 3, 4, 5, 6]

79.字節(jié)轉(zhuǎn)化

function convert($size)
{
    $unit = array("b", "kb", "mb", "gb", "tb", "pb");

    return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . " " . $unit[$i];
}
echo convert(memory_get_usage());
function cacheMem($key)
{
    static $mem = null;
    if ($mem === null) {
        $mem = new Memcache();
        $mem->connect("127.0.0.1", 11211);
    }

    $data = $mem->get($key);
    if (empty($data)) {
        $data = date("Y-m-d H:i:s");
        $mem->set($key, $data);
    }

    return $data;
}

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/85789.html

相關(guān)文章

  • 【數(shù)據(jù)科學(xué)系統(tǒng)學(xué)習(xí)】機(jī)器學(xué)習(xí)算法 # 西瓜書學(xué)習(xí)記錄 [10] 決策樹實(shí)踐

    摘要:本篇內(nèi)容為機(jī)器學(xué)習(xí)實(shí)戰(zhàn)第章決策樹部分程序清單。適用數(shù)據(jù)類型數(shù)值型和標(biāo)稱型在構(gòu)造決策樹時(shí),我們需要解決的第一個(gè)問(wèn)題就是,當(dāng)前數(shù)據(jù)集上哪個(gè)特征在劃分?jǐn)?shù)據(jù)分類時(shí)起決定性作用。下面我們會(huì)介紹如何將上述實(shí)現(xiàn)的函數(shù)功能放在一起,構(gòu)建決策樹。 本篇內(nèi)容為《機(jī)器學(xué)習(xí)實(shí)戰(zhàn)》第 3 章決策樹部分程序清單。所用代碼為 python3。 決策樹優(yōu)點(diǎn):計(jì)算復(fù)雜度不高,輸出結(jié)果易于理解,對(duì)中間值的缺失不敏感,可...

    suemi 評(píng)論0 收藏0
  • 何愷明團(tuán)隊(duì)推出Mask^X R-CNN,將實(shí)例分割擴(kuò)展到3000類

    摘要:從標(biāo)題上可以看出,這是一篇在實(shí)例分割問(wèn)題中研究擴(kuò)展分割物體類別數(shù)量的論文。試驗(yàn)結(jié)果表明,這個(gè)擴(kuò)展可以改進(jìn)基準(zhǔn)和權(quán)重傳遞方法。 今年10月,何愷明的論文Mask R-CNN摘下ICCV 2017的較佳論文獎(jiǎng)(Best Paper Award),如今,何愷明團(tuán)隊(duì)在Mask R-CNN的基礎(chǔ)上更近一步,推出了(以下稱Mask^X R-CNN)。這篇論文的第一作者是伯克利大學(xué)的在讀博士生胡戎航(清華...

    MockingBird 評(píng)論0 收藏0
  • 決策樹的Python實(shí)現(xiàn)(含代碼)

    摘要:也就是說(shuō),決策樹有兩種分類樹和回歸樹。我們可以把決策樹看作是一個(gè)規(guī)則的集合。這樣可以提高決策樹學(xué)習(xí)的效率。解決這個(gè)問(wèn)題的辦法是考慮決策樹的復(fù)雜度,對(duì)已生成的決策樹進(jìn)行簡(jiǎn)化,也就是常說(shuō)的剪枝處理。最后得到一個(gè)決策樹。 一天,小迪與小西想養(yǎng)一只寵物。 小西:小迪小迪,好想養(yǎng)一只寵物呀,但是不知道養(yǎng)那種寵物比較合適。 小迪:好呀,養(yǎng)只寵物會(huì)給我們的生活帶來(lái)很多樂(lè)趣呢。不過(guò)養(yǎng)什么寵物可要考慮好...

    yanest 評(píng)論0 收藏0
  • 如何用機(jī)器學(xué)習(xí)算法來(lái)進(jìn)行電影分類?(含Python代碼)

    摘要:電影分析近鄰算法周末,小迪與女朋友小西走出電影院,回味著剛剛看過(guò)的電影。近鄰分類電影類型小迪回到家,打開(kāi)電腦,想實(shí)現(xiàn)一個(gè)分類電影的案例。分類器并不會(huì)得到百分百正確的結(jié)果,我們可以使用很多種方法來(lái)驗(yàn)證分類器的準(zhǔn)確率。 電影分析——K近鄰算法 周末,小迪與女朋友小西走出電影院,回味著剛剛看過(guò)的電影。 小迪:剛剛的電影很精彩,打斗場(chǎng)景非常真實(shí),又是一部?jī)?yōu)秀的動(dòng)作片! 小西:是嗎?我怎么感覺(jué)這...

    animabear 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<