Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

php函数 #114

Open
mingyun opened this issue Dec 21, 2017 · 11 comments
Open

php函数 #114

mingyun opened this issue Dec 21, 2017 · 11 comments

Comments

@mingyun
Copy link
Owner

mingyun commented Dec 21, 2017

/**
 * 求两个经纬度之间的距离
 *https://www.lvtao.net/dev/1899.html
 * 赤道半径 6378.137Km ;两极半径 6359.752Km;平均半径 6371.012Km ;赤道周长 40075.7Km.
 *
 * @param float $aLng 地址A的经度
 * @param float $aLat 地址A的纬度
 * @param float $bLng 地址B的经度
 * @param float $bLat 地址B的纬度
 *
 * @return float|int 单位米
 */
function getDistance($aLng, $aLat, $bLng, $bLat)
{
    //将角度转为狐度
    $aLng    = deg2rad($aLng);
    $aLat    = deg2rad($aLat);
    $bLng    = deg2rad($bLng);
    $bLat    = deg2rad($bLat);
    $lngDiff = $aLng - $bLng;
    $latDiff = $aLat - $bLat;
    $diff = 2 * asin(sqrt(pow(sin($latDiff / 2), 2) + cos($aLat) * cos($bLat) * pow(sin($lngDiff / 2), 2))) * 6378.137 * 1000;
    return $diff;
}

echo getDistance(36.059907, 120.300687, 36.019983, 120.296447);
/**
 * Class Lunar
 * 农历 节气 节日
 * author:guoyu@xzd
 */
class Lunar
{
  public $MIN_YEAR = 1891;
  public $MAX_YEAR = 2100;
  public $lunarInfo = array(
    array(0,2,9,21936),array(6,1,30,9656),array(0,2,17,9584),array(0,2,6,21168),array(5,1,26,43344),array(0,2,13,59728),
    array(0,2,2,27296),array(3,1,22,44368),array(0,2,10,43856),array(8,1,30,19304),array(0,2,19,19168),array(0,2,8,42352),
    array(5,1,29,21096),array(0,2,16,53856),array(0,2,4,55632),array(4,1,25,27304),array(0,2,13,22176),array(0,2,2,39632),
    array(2,1,22,19176),array(0,2,10,19168),array(6,1,30,42200),array(0,2,18,42192),array(0,2,6,53840),array(5,1,26,54568),
    array(0,2,14,46400),array(0,2,3,54944),array(2,1,23,38608),array(0,2,11,38320),array(7,2,1,18872),array(0,2,20,18800),
    array(0,2,8,42160),array(5,1,28,45656),array(0,2,16,27216),array(0,2,5,27968),array(4,1,24,44456),array(0,2,13,11104),
    array(0,2,2,38256),array(2,1,23,18808),array(0,2,10,18800),array(6,1,30,25776),array(0,2,17,54432),array(0,2,6,59984),
    array(5,1,26,27976),array(0,2,14,23248),array(0,2,4,11104),array(3,1,24,37744),array(0,2,11,37600),array(7,1,31,51560),
    array(0,2,19,51536),array(0,2,8,54432),array(6,1,27,55888),array(0,2,15,46416),array(0,2,5,22176),array(4,1,25,43736),
    array(0,2,13,9680),array(0,2,2,37584),array(2,1,22,51544),array(0,2,10,43344),array(7,1,29,46248),array(0,2,17,27808),
    array(0,2,6,46416),array(5,1,27,21928),array(0,2,14,19872),array(0,2,3,42416),array(3,1,24,21176),array(0,2,12,21168),
    array(8,1,31,43344),array(0,2,18,59728),array(0,2,8,27296),array(6,1,28,44368),array(0,2,15,43856),array(0,2,5,19296),
    array(4,1,25,42352),array(0,2,13,42352),array(0,2,2,21088),array(3,1,21,59696),array(0,2,9,55632),array(7,1,30,23208),
    array(0,2,17,22176),array(0,2,6,38608),array(5,1,27,19176),array(0,2,15,19152),array(0,2,3,42192),array(4,1,23,53864),
    array(0,2,11,53840),array(8,1,31,54568),array(0,2,18,46400),array(0,2,7,46752),array(6,1,28,38608),array(0,2,16,38320),
    array(0,2,5,18864),array(4,1,25,42168),array(0,2,13,42160),array(10,2,2,45656),array(0,2,20,27216),array(0,2,9,27968),
    array(6,1,29,44448),array(0,2,17,43872),array(0,2,6,38256),array(5,1,27,18808),array(0,2,15,18800),array(0,2,4,25776),
    array(3,1,23,27216),array(0,2,10,59984),array(8,1,31,27432),array(0,2,19,23232),array(0,2,7,43872),array(5,1,28,37736),
    array(0,2,16,37600),array(0,2,5,51552),array(4,1,24,54440),array(0,2,12,54432),array(0,2,1,55888),array(2,1,22,23208),
    array(0,2,9,22176),array(7,1,29,43736),array(0,2,18,9680),array(0,2,7,37584),array(5,1,26,51544),array(0,2,14,43344),
    array(0,2,3,46240),array(4,1,23,46416),array(0,2,10,44368),array(9,1,31,21928),array(0,2,19,19360),array(0,2,8,42416),
    array(6,1,28,21176),array(0,2,16,21168),array(0,2,5,43312),array(4,1,25,29864),array(0,2,12,27296),array(0,2,1,44368),
    array(2,1,22,19880),array(0,2,10,19296),array(6,1,29,42352),array(0,2,17,42208),array(0,2,6,53856),array(5,1,26,59696),
    array(0,2,13,54576),array(0,2,3,23200),array(3,1,23,27472),array(0,2,11,38608),array(11,1,31,19176),array(0,2,19,19152),
    array(0,2,8,42192),array(6,1,28,53848),array(0,2,15,53840),array(0,2,4,54560),array(5,1,24,55968),array(0,2,12,46496),
    array(0,2,1,22224),array(2,1,22,19160),array(0,2,10,18864),array(7,1,30,42168),array(0,2,17,42160),array(0,2,6,43600),
    array(5,1,26,46376),array(0,2,14,27936),array(0,2,2,44448),array(3,1,23,21936),array(0,2,11,37744),array(8,2,1,18808),
    array(0,2,19,18800),array(0,2,8,25776),array(6,1,28,27216),array(0,2,15,59984),array(0,2,4,27424),array(4,1,24,43872),
    array(0,2,12,43744),array(0,2,2,37600),array(3,1,21,51568),array(0,2,9,51552),array(7,1,29,54440),array(0,2,17,54432),
    array(0,2,5,55888),array(5,1,26,23208),array(0,2,14,22176),array(0,2,3,42704),array(4,1,23,21224),array(0,2,11,21200),
    array(8,1,31,43352),array(0,2,19,43344),array(0,2,7,46240),array(6,1,27,46416),array(0,2,15,44368),array(0,2,5,21920),
    array(4,1,24,42448),array(0,2,12,42416),array(0,2,2,21168),array(3,1,22,43320),array(0,2,9,26928),array(7,1,29,29336),
    array(0,2,17,27296),array(0,2,6,44368),array(5,1,26,19880),array(0,2,14,19296),array(0,2,3,42352),array(4,1,24,21104),
    array(0,2,10,53856),array(8,1,30,59696),array(0,2,18,54560),array(0,2,7,55968),array(6,1,27,27472),array(0,2,15,22224),
    array(0,2,5,19168),array(4,1,25,42216),array(0,2,12,42192),array(0,2,1,53584),array(2,1,21,55592),array(0,2,9,54560)
  );
  /**
   * 将阳历转换为阴历
   * @param year 公历-年
   * @param month 公历-月
   * @param date 公历-日
   */
  public function convertSolarToLunar($year,$month,$date)
  {
    $yearData = $this->lunarInfo[$year-$this->MIN_YEAR];
    if($year==$this->MIN_YEAR&&$month<=2&&$date<=9) return array(1891,'正月','初一','辛卯',1,1,'兔');
    return $this->getLunarByBetween($year,$this->getDaysBetweenSolar($year,$month,$date,$yearData[1],$yearData[2]));
  }
  public function convertSolarMonthToLunar($year,$month,$date)
  {
    $yearData = $this->lunarInfo[$year-$this->MIN_YEAR];
    if($year==$this->MIN_YEAR&&$month<=2&&$date<=9) return array(1891,'正月','初一','辛卯',1,1,'兔');
    $month_days_ary = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    $dd = $month_days_ary[$month];
    if($this->isLeapYear($year) && $month == 2) $dd++;
    $lunar_ary = array();
    for ($i = 1; $i < $dd; $i++)
    {
      $array = $this->getLunarByBetween($year,$this->getDaysBetweenSolar($year, $month, $i, $yearData[1], $yearData[2]));
      $array[] = $year . '-' . $month . '-' . $i;
      $lunar_ary[$i] = $array;
    }
    return $lunar_ary;
  }
  /**
   * 将阴历转换为阳历
   * @param year 阴历-年
   * @param month 阴历-月,闰月处理:例如如果当年闰五月,那么第二个五月就传六月,相当于阴历有13个月,只是有的时候第13个月的天数为0
   * @param date 阴历-日
   */
  public function convertLunarToSolar($year,$month,$date)
  {
    $yearData = $this->lunarInfo[$year-$this->MIN_YEAR];
    $between = $this->getDaysBetweenLunar($year,$month,$date);
    $res = mktime(0,0,0,$yearData[1],$yearData[2],$year);
    $res = date('Y-m-d', $res+$between*24*60*60);
    $day = explode('-', $res);
    $year = $day[0];
    $month= $day[1];
    $day = $day[2];
    return array($year, $month, $day);
  }
  /**
   * 判断是否是闰年
   * @param year
   */
  public function isLeapYear($year)
  {
    return (($year%4==0 && $year%100 !=0) || ($year%400==0));
  }
  /**
   * 获取干支纪年
   * @param year
   */
  public function getLunarYearName($year)
  {
    $sky = array('','辛','壬','癸','甲','乙','丙','丁','戊','己');
    $earth = array('申','酉','戌','亥','子','丑','寅','卯','辰','巳','午','未');
    $year = $year.'';
    return $sky[$year{3}].$earth[$year%12];
  }
  /**
   * 根据阴历年获取生肖
   * @param year 阴历年
   */
  public function getYearZodiac($year)
  {
    $zodiac = array('','','','','','','','','','','','');
    return $zodiac[$year%12];
  }
  /**
   * 获取阳历月份的天数
   * @param year 阳历-年
   * @param month 阳历-月
   */
  public function getSolarMonthDays($year,$month)
  {
    $monthHash = array('1'=>31,'2'=>$this->isLeapYear($year)?29:28,'3'=>31,'4'=>30,'5'=>31,'6'=>30,'7'=>31,'8'=>31,'9'=>30,'10'=>31,'11'=>30,'12'=>31);
    return $monthHash["$month"];
  }
  /**
   * 获取阴历月份的天数
   * @param year 阴历-年
   * @param month 阴历-月,从一月开始
   */
  public function getLunarMonthDays($year,$month)
  {
    $monthData = $this->getLunarMonths($year);
    return $monthData[$month-1];
  }
  /**
   * 获取阴历每月的天数的数组
   * @param year
   */
  public function getLunarMonths($year)
  {
    $yearData = $this->lunarInfo[$year - $this->MIN_YEAR];
    $leapMonth = $yearData[0];
    $bit = decbin($yearData[3]);
    for ($i = 0; $i < strlen($bit);$i ++) $bitArray[$i] = substr($bit, $i, 1);
    for($k=0,$klen=16-count($bitArray);$k<$klen;$k++) array_unshift($bitArray, '0');
    $bitArray = array_slice($bitArray,0,($leapMonth==0?12:13));
    for($i=0; $i<count($bitArray); $i++) $bitArray[$i] = $bitArray[$i] + 29;
    return $bitArray;
  }
  /**
   * 获取农历每年的天数
   * @param year 农历年份
   */
  public function getLunarYearDays($year)
  {
    $yearData = $this->lunarInfo[$year-$this->MIN_YEAR];
    $monthArray = $this->getLunarYearMonths($year);
    $len = count($monthArray);
    return ($monthArray[$len-1]==0?$monthArray[$len-2]:$monthArray[$len-1]);
  }
  public function getLunarYearMonths($year)
  {
    $monthData = $this->getLunarMonths($year);
    $res=array();
    $temp=0;
    $yearData = $this->lunarInfo[$year-$this->MIN_YEAR];
    $len = ($yearData[0]==0?12:13);
    for($i=0;$i<$len;$i++)
    {
      $temp=0;
      for($j=0;$j<=$i;$j++) $temp+=$monthData[$j];
      array_push($res, $temp);
    }
    return $res;
  }
  /**
   * 获取闰月
   * @param year 阴历年份
   */
  public function getLeapMonth($year)
  {
    $yearData = $this->lunarInfo[$year-$this->MIN_YEAR];
    return $yearData[0];
  }
  /**
   * 计算阴历日期与正月初一相隔的天数
   * @param year
   * @param month
   * @param date
   */
  public function getDaysBetweenLunar($year,$month,$date)
  {
    $yearMonth = $this->getLunarMonths($year);
    $res=0;
    for($i=1;$i<$month;$i++) $res +=$yearMonth[$i-1];
    $res+=$date-1;
    return $res;
  }
  /**
   * 计算2个阳历日期之间的天数
   * @param year 阳历年
   * @param cmonth
   * @param cdate
   * @param dmonth 阴历正月对应的阳历月份
   * @param ddate 阴历初一对应的阳历天数
   */
  public function getDaysBetweenSolar($year,$cmonth,$cdate,$dmonth,$ddate)
  {
    $a = mktime(0,0,0,$cmonth,$cdate,$year);
    $b = mktime(0,0,0,$dmonth,$ddate,$year);
    return ceil(($a-$b)/24/3600);
  }
  /**
   * 根据距离正月初一的天数计算阴历日期
   * @param year 阳历年
   * @param between 天数
   */
  public function getLunarByBetween($year,$between)
  {
    $lunarArray = array();
    $yearMonth=array();
    $t=0;
    $e=0;
    $leapMonth=0;
    $m='';
    if($between==0)
    {
      array_push($lunarArray, $year,'正月','初一');
      $t = 1;
      $e = 1;
    }
    else
    {
      $year = $between>0? $year : ($year-1);
      $yearMonth = $this->getLunarYearMonths($year);
      $leapMonth = $this->getLeapMonth($year);
      $between = $between>0?$between : ($this->getLunarYearDays($year)+$between);
      for($i=0;$i<13;$i++)
      {
        if($between==$yearMonth[$i])
        {
          $t=$i+2;
          $e=1;
          break;
        }else if($between<$yearMonth[$i])
        {
          $t=$i+1;
          $e=$between-(empty($yearMonth[$i-1])?0:$yearMonth[$i-1])+1;
          break;
        }
      }
      $m = ($leapMonth!=0&&$t==$leapMonth+1)?('闰'.$this->getCapitalNum($t- 1,true)):$this->getCapitalNum(($leapMonth!=0&&$leapMonth+1<$t?($t-1):$t),true);
      array_push($lunarArray,$year,$m,$this->getCapitalNum($e,false));
    }
    array_push($lunarArray,$this->getLunarYearName($year));// 天干地支
    array_push($lunarArray,$t,$e);
    array_push($lunarArray,$this->getYearZodiac($year));// 12生肖
    array_push($lunarArray,$leapMonth);// 闰几月
    return $lunarArray;
  }
  /**
   * 获取数字的阴历叫法
   * @param num 数字
   * @param isMonth 是否是月份的数字
   */
  public function getCapitalNum($num,$isMonth)
  {
    $isMonth = $isMonth || false;
    $dateHash=array('0'=>'','1'=>'一','2'=>'二','3'=>'三','4'=>'四','5'=>'五','6'=>'六','7'=>'七','8'=>'八','9'=>'九','10'=>'十 ');
    $monthHash=array('0'=>'','1'=>'正月','2'=>'二月','3'=>'三月','4'=>'四月','5'=>'五月','6'=>'六月','7'=>'七月','8'=>'八月','9'=>'九月','10'=>'十月','11'=>'冬月','12'=>'腊月');
    $res='';
    if($isMonth) $res = $monthHash[$num];
    else
    {
      if($num<=10) $res = '初'.$dateHash[$num];
      else if($num>10&&$num<20) $res = '十'.$dateHash[$num-10];
      else if($num==20) $res = "二十";
      else if($num>20&&$num<30) $res = "廿".$dateHash[$num-20];
      else if($num==30) $res = "三十";
    }
    return $res;
  }
  /**
   * 节气通用算法
   */
  public function getJieQi($_year,$month,$day)
  {
    $year = substr($_year,-2)+0;
    $coefficient = array(
      array(5.4055,2019,-1),//小寒
      array(20.12,2082,1),//大寒
      array(3.87),//立春
      array(18.74,2026,-1),//雨水
      array(5.63),//惊蛰
      array(20.646,2084,1),//春分
      array(4.81),//清明
      array(20.1),//谷雨
      array(5.52,1911,1),//立夏
      array(21.04,2008,1),//小满
      array(5.678,1902,1),//芒种
      array(21.37,1928,1),//夏至
      array(7.108,2016,1),//小暑
      array(22.83,1922,1),//大暑
      array(7.5,2002,1),//立秋
      array(23.13),//处暑
      array(7.646,1927,1),//白露
      array(23.042,1942,1),//秋分
      array(8.318),//寒露
      array(23.438,2089,1),//霜降
      array(7.438,2089,1),//立冬
      array(22.36,1978,1),//小雪
      array(7.18,1954,1),//大雪
      array(21.94,2021,-1)//冬至
    );
    $term_name = array(
      "小寒","大寒","立春","雨水","惊蛰","春分","清明","谷雨",
      "立夏","小满","芒种","夏至","小暑","大暑","立秋","处暑",
      "白露","秋分","寒露","霜降","立冬","小雪","大雪","冬至");
    $idx1 = ($month-1)*2;
    $_leap_value = floor(($year-1)/4);
    $day1 = floor($year*0.2422+$coefficient[$idx1][0])-$_leap_value;
    if(isset($coefficient[$idx1][1])&&$coefficient[$idx1][1]==$_year) $day1 += $coefficient[$idx1][2];
    $day2 = floor($year*0.2422+$coefficient[$idx1+1][0])-$_leap_value;
    if(isset($coefficient[$idx1+1][1])&&$coefficient[$idx1+1][1]==$_year) $day1 += $coefficient[$idx1+1][2];
    if($day==$day1) return $term_name[$idx1];
    if($day==$day2) return $term_name[$idx1+1];
    return '';
  }
  /**
   * 获取节日:特殊的节日只能修改此函数来计算
   */
  public function getFestival($today, $nl_info = false,$config = 1)
  {
    if($config == 1)
    {
      $arr_lunar=array('01-01'=>'春节','01-15'=>'元宵节','02-02'=>'二月二','05-05'=>'端午节','07-07'=>'七夕节','08-15'=>'中秋节','09-09'=>'重阳节','12-08'=>'腊八节','12-23'=>'小年');
      $arr_solar=array('01-01'=>'元旦','02-14'=>'情人节','03-12'=>'植树节','04-01'=>'愚人节','05-01'=>'劳动节','06-01'=>'儿童节','10-01'=>'国庆节','10-31'=>'万圣节','12-24'=>'平安夜','12-25'=>'圣诞节');
    }//需要不同节日的,用不同的$config,然后配置$arr_lunar和$arr_solar
    $festivals = array();
    list($y,$m,$d) = explode('-',$today);
    if(!$nl_info) $nl_info = $this->convertSolarToLunar($y,intval($m),intval($d));
    if($nl_info[7]>0&&$nl_info[7]<$nl_info[4]) $nl_info[4]-=1;
    $md_lunar = substr('0'.$nl_info[4],-2).'-'.substr('0'.$nl_info[5],-2);
    $md_solar=substr_replace($today,'',0,5);
    isset($arr_lunar[$md_lunar])?array_push($festivals, $arr_lunar[$md_lunar]):'';
    isset($arr_solar[$md_solar])?array_push($festivals, $arr_solar[$md_solar]):'';
    $glweek = date("w",strtotime($today));  //0-6
    if($m==5&&($d>7)&&($d<15)&&($glweek==0))array_push($festivals, "母亲节");
    if($m==6&&($d>14)&&($d<22)&&($glweek==0))array_push($festivals,"父亲节");
    $jieqi = $this->getJieQi($y,$m,$d);
    if($jieqi)array_push($festivals,$jieqi);
    return implode('/',$festivals);
  }
}$lunar = new Lunar();
$month = $lunar->convertSolarToLunar(date('Y'),date('m'),date('d'));
print_r($month);
运行结果

Array
(
  [0] => 2017
  [1] => 闰六月
  [2] => 十七
  [3] => 丁酉
  [4] => 7
  [5] => 17
  [6] => 
  [7] => 6
)
多条数据,根据权限随机展示.

function getConsultant()
{
    $data = array(
      array('name'=>'user1','weights'=>1),
      array('name'=>'user2','weights'=>2),
      array('name'=>'user3','weights'=>3),
      array('name'=>'user4','weights'=>4)
    );
    $weight = 0;
    $users = array();
    foreach ($data as $one) {
        $oneWeight = (int)$one['weights'] ? $one['weights'] : 1;
        $weight += $oneWeight;
        for ($i = 0; $i < $oneWeight; $i ++) {
            $users[] = $one;
        }
    }
    return $users[rand(0, $weight-1)];
}
@mingyun
Copy link
Owner Author

mingyun commented Dec 21, 2017

面试只是个线头, 线头扯开有很多东西
比如面试的时候闻到rabbitmq 我不会, 第二次面试就已经把它的原理和思想搞明白了,第三次就已经实操过了。 那么你和有经验的人还差点什么? 差的无非就是灵活应用和踩过的坑
google 搜索,前20条至少5条是应用场景, stackoverflow搜索, 按回复最多的排序, 前10条就基本是所有的坑,还有github上的isuse
那么说第4次面试, 你在这方面就算个小专家了

如果你用laravel tp yii这种重型框架 你只需要掌握一个单例 一个工厂(有3种) 一个适配模式就足够了
如果你用原生 用yaf这种轻量级框架 或者你的只能是预研、攻坚、指导 你还要掌握桥接 策略 等等…… 但最重要的是PHP自身的那些面向对象能力
明白一点,PHP本质还是函数语言,很多OO特性是PHP的一些取巧方法

另外记住一点,不分层不用设计模式,无应对强烈变化的需求不用设计模式
装B绝不是用设计模式的理由,甚至复用都不是用设计模式的理由
学设计模式最好办法就是用yaf 原生,或者自己做个简单框架
有分层需要,你就有用设计模式的动力
另外需求多变,你也会有用设计模式的动力哒

腾讯云互动 https://cloud.tencent.com/document/product/269/4029 https://cloud.tencent.com/document/product/268/7656

private function base64Encode($string) {
        static $replace = Array('+' => '*', '/' => '-', '=' => '_');
        $base64 = base64_encode($string);
        if ($base64 === false) {
            throw new Exception('base64_encode error');
        }
        return str_replace(array_keys($replace), array_values($replace), $base64);
    }
private function base64Decode($base64) {
        static $replace = Array('+' => '*', '/' => '-', '=' => '_');
        $string = str_replace(array_values($replace), array_keys($replace), $base64);
        $result = base64_decode($string);
        if ($result == false) {
            throw new Exception('base64_decode error');
        }
        return $result;
    }
private function sign($data) {
        $signature = '';
        if (!openssl_sign($data, $signature, $this->private_key, 'sha256')) {
            throw new Exception(openssl_error_string());
        }
        return $signature;
    }
private function verify($data, $sig) {
        $ret = openssl_verify($data, $sig, $this->public_key, 'sha256');
        if ($ret == -1) {
            throw new Exception(openssl_error_string());
        }
        return $ret;
    }
$this->private_key = openssl_pkey_get_private($private_key);
$this->public_key = openssl_pkey_get_public($public_key);//$public_key 公钥文件内容
异步导出处理逻辑
public static function asyncExport($id,$startDate ='',$endDate = '',$isMerge = false){
        $rsData = ['code'=>'200','msg'=>'生成中'];
        $status =RedisFacade::hget(self::WEBINARS_ATTACHED_INFO.$id,'async_export_status');
        if(1 == $status){
            $rsData = ['code'=>400,'msg'=>'已有一个导出任务正在生成中,请稍后'];
        }else{
            $exportAttributes = [
                'is_async_export'=>1,       //活动是否有异步导出
                'async_export_time'=>time(),//导出时间
                'async_export_status'=>1    //当前异步导出进度状态 1开始,2完成
            ];
            self::setWebinarsAttachedInfo($id,$exportAttributes);
            \Queue::push(new \App\Commands\WebinarTracksExport($id,$startDate,$endDate,$isMerge),null,'async_export');
        }
        return $rsData;
    }
public static function setWebinarsAttachedInfo($id,$data =[]){
        $key = self::WEBINARS_ATTACHED_INFO.$id;
        RedisFacade::hmset($key,$data);
    }
$position = Upload::appendToOSS($this->dir.'/'.date('Ymd').'_'.$this->webinar_id.'.csv', $title.PHP_EOL);
$position = Upload::appendToOSS($this->dir.'/'.date('Ymd').'_'.$this->webinar_id.'.csv', $str, $position);
/**
     * 结束导出处理
     * @param $webinar_id
     */
    private function endExportDeal($webinar_id){
        $data = ['async_export_status'=>2];
        \App\Services\WebinarTrackExport::setWebinarsAttachedInfo($webinar_id,$data);
        //活动id 计入集合
        $key = \App\Services\WebinarTrackExport::WEBINARS_EXPORT_LIST;
        RedisFacade::sadd($key,$webinar_id);
    }
/**
     * 删除观看数据导出前一天文件
     */
    private function webinarTracksExportDelete(){
        $key = WebinarTrackExport::WEBINARS_EXPORT_LIST;
        $count = RedisFacade::SCARD($key);
        if($count >0){
            $list = RedisFacade::SMEMBERS($key);
            if(!empty($list)){
                foreach($list as $row){
                    $file = 'exportFile/'.$row.'/'.date('Ymd',strtotime('-1 days')).'_'.$row.'.csv';
                    $exists = \Storage::disk('local_static')->exists($file);
                    if($exists){
                        \Storage::disk('local_static')->delete($file);
                        $key = WebinarTrackExport::WEBINARS_ATTACHED_INFO.$row;
                        RedisFacade::del($key);
                    }
                }
            }
        }
    }
$ret = RedisFacade::hget(WEBINARS_ATTACHED_INFO.$webinarId,'async_export_status');
        if($ret == 2){
            $file = env('UPLOAD_URL').'/exportFile/'.$webinarId.'/'.date('Ymd').'_webinarUserReg_'.$webinarId.'.csv';
            return response()->json(['code' => '200', 'msg' => '已完成,请尽快下载','data'=>['file'=>$file]]);
        }else{
            return response()->json(['code' => '500', 'msg' => '生成中,请稍后再来查看','data'=>[]]);
        }

@mingyun
Copy link
Owner Author

mingyun commented Dec 22, 2017

后端https://github.com/bitpay/bitcore-node 

API端https://github.com/bitpay/insight-api 

前端https://github.com/bitpay/insight 

预览https://insight.bitpay.com/
http://51.ruyo.net/3127.html 这里的接口不错,可以看vip视频
// http://cn.php.net/manual/zh/migration56.php
const ARR = ['a', 'b'];
echo 2 ** 3 ** 2;
function add($a, $b, $c) {
    return $a + $b + $c;
}
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
$aud_arr = [['a'=>'a','b'=>'b'],['a'=>'a','b'=>'b']];
$insertArr = array_unique($aud_arr, SORT_REGULAR);
echo "\u{9999}";
class A {private $x = 1;}
$getX = function() {return $this->x;};
echo $getX->call(new A);

$gen = (function() {
    yield 1;
    yield 2;

    return 3;
})();

foreach ($gen as $val) {
    echo $val, PHP_EOL;
}
// random_bytes() 和 random_int() 用来产生高安全级别的随机字符串和随机整数。
echo $gen->getReturn(), PHP_EOL;
var_dump(intdiv(10, 3));//3
$username = $_GET['user'] ?? 'nobody';//$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
$operators = [2, 3];
echo add(1, ...$operators);
function f($req, $opt = null, ...$params) {
    // $params 是一个包含了剩余参数的数组
    printf('$req: %d; $opt: %d; number of params: %d'."\n",
           $req, $opt, count($params));
}
f(1, 2, 3, 4, 5);
userRegister(1,2);
//  JSON 字面量 true,false 和 null,如果不采用小写格式,将会被 json_decode() 函数拒绝
// 不可以包含两个或多个同名的参数  ($foo->$bar)['baz']
 class C {}
$c =& new C;//error
$str = "0xffff";
$int = filter_var($str, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX);
if (false === $int) {
    throw new Exception("Invalid integer!");
}
var_dump($int); // int(65535) 含十六进制字符串不再被认为是数字。 可变变量不再能够与 global 关键字一起使用
var_dump("0x123" == "291");
var_dump(is_numeric("0x123"));
var_dump("0xe" + "0x1");
var_dump(substr("foo", "0x1"));

function foo($a, $b, $unused, $unused) {
    //
} 
$array = [0];
foreach ($array as &$val) {
    var_dump($val);
    $array[1] = 1;
}


curl -so /dev/null -w "%{time_namelookup} %{time_connect} %{time_redirect} %{time_pretransfer} \
%{time_starttransfer} %{time_total}\n" www.haiyun.me
curl -I --proxy 192.168.1.1:7070 www.haiyun.me
curl -I --socks5 192.168.1.1:7070 http://www.haiyun.me/archives/curl-ftp.html
curl -u user:passwd ftp://www.haiyun.me 列出FTP目录
curl -u user:passwd ftp://www.haiyun.me/file.rar -o file.rar 下载文件
curl -u user:passwd -T file.rar ftp://www.haiyun.me 上传文件
// PHP多进程同时写文件
function ffwrite($filename,$content) {
      $file = fopen("$filename","a");
      while(1) {
         if (flock($file,LOCK_EX))
         {
            fwrite($file,$content);
            flock($file,LOCK_UN);
            fclose($file);
            break;
            } else {
            usleep(1000);
         }
      }
   }
// 简单循环队列http://www.haiyun.me/archives/891.html
   function queue() {
      static $queue =  array(a,b,c,d);
      $a = array_shift($queue);
      $queue[] = $a;
      print_r($queue);
      echo $a;
   }
   queue();
   queue();
   queue();
   queue();

   function arr_foreach ($arr) 
   {
      static $tmp=array();  
      if (!is_array ($arr)) 
      {
         return false;
      }
      foreach ($arr as $val ) 
      {
         if (is_array ($val)) 
         {
            arr_foreach ($val);
         } 
         else
         {
            $tmp[]=$val;
         }
      }
      return $tmp;
   }
   $a = array(1,2=>array(3,4=>array(5,6)),7);
   print_r(arr_foreach($a));
// 随机汉字
   function genstr($num)
   {
      for($i=0;$i<=$num;$i++)
      {
         $str .= '&#'.rand(19968, 40869).';';
      }
 
      return mb_convert_encoding($str, "UTF-8", "HTML-ENTITIES");
   }
   echo genstr(mt_rand(1,8));
   function genstr2($num)
   {
      for($i=0;$i<=$num;$i++)
      {
         $str .= chr(rand(0xB0,0xF7)).chr(rand(0xA1,0xFE));
      }
 
      return $str;
   }
   echo genstr2(mt_rand(1,8));
function xor_enc($string, $operation, $key = 'abcdf') {
      $string = $operation == 'ENCODE' ? $string : base64_decode($string);
      $len1 = strlen($string);
      $len2 = strlen($key);
      if($len1 > $len2) $key = str_repeat($key, ceil($len1 / $len2));
      $string = $operation == 'ENCODE' ? base64_encode($string ^ $key) : $string ^ $key;
      return $string;
   }
   function xor_enc($string, $operation = 'ENCODE', $key = 'abcd') {
   $txt = $operation == 'ENCODE' ? $string : base64_decode($string);
   $len = strlen($key);
   $code = '';
   for ($i = 0; $i < strlen($string); $i ++) {
      $k = $i % $len;
      $code .= $string [$i] ^ $key [$k];
   }
   $code = $operation == 'ENCODE' ? base64_encode($code) : $code;
   return $code;
}
 

   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(true)); 
function strtr_words($str)  
   {  
      $words=array();  
      $content = file_get_contents('t.txt');
      $content = preg_split('/\r\n/', $content, -1, PREG_SPLIT_NO_EMPTY); //分割字符串为数组
      foreach($content as $key => $value)  
      {  
         //if ($key != '')  
         if (!empty($key))  
         {  
            $str_data = explode(',', $value); //分割同义词为k-v数组
            $str = str_replace($str_data[0], $str_data[1] , $str);
            //$words+=array("$str_data[0]"=>"$str_data[1]");  
         }  
      }  
      return $str;
      //return strtr($str,$words);
   }  
   echo strtr_words('村庄,一眼望不到边际')."\n";

git clone https://github.com/maxmind/geoip-api-php.git
http://dev.maxmind.com/geoip/legacy/geolite/
include("./src/geoip.inc");
$gi = geoip_open("/usr/share/GeoIP/GeoIP.dat", GEOIP_STANDARD);
echo geoip_country_code_by_name($gi, "www.haiyun.me") . "\n";
// http://www.haiyun.me/archives/973.html MySQL主从同步配置
在cmd窗口中set设置的环境变量为临时变量,如:
 
set PATH=%PATH%;D:\Program Files\
使用setx设置为永久环境变量:
 
// setx PATH "%PATH%;D:\Program Files\"
一致性hash
function get_hash($str, $num=10){
  $crc = crc32($str);
  $nu = $crc % $num;
  return $nu;
}

function genstr($num) {
  return substr(str_shuffle('abcdefghijklmnupqrstuvwxyz'), 0, $num);
}
 
for ($i=1; $i<10000000; $i++) {
  $str = genstr(5);
  $crc = crc32($str);
  $nu = get_hash($str);;
  if (isset($count[$nu])) {
    $count[$nu]++;
  } else {
    $count[$nu]=1;
  }
}
print_r($count);

function similarity(array $vec1, array $vec2) {
  return dotProduct($vec1, $vec2) / (absVector($vec1) * absVector($vec2));
}
 
function dotProduct(array $vec1, array $vec2) {
  $result = 0;
  foreach (array_keys($vec1) as $key1) {
    foreach (array_keys($vec2) as $key2) {
      if ($key1 === $key2) $result += $vec1[$key1] * $vec2[$key2];
    }
  }
  return $result;
}
// 计算词频,即分词后计算文章的总词数和每个词的出现次数,词数较多可取TOPk //$tf = 词出现次数 / 总词数

//$idf = log( 总文档数 / 包含词的文档数, 2); 
// $idf = log( $total_document_count / $documents_with_term, 2);
//计算TF-IDF,值越大分类能力越强:
// $tfidf = $tf * $idf
 // http://www.haiyun.me/archives/1046.html PHP TF-IDF与余弦相似性计算文章相似性
function absVector(array $vec) {
  $result = 0;
  foreach (array_values($vec) as $value) {
    $result += $value * $value;
  }
  return sqrt($result);
}
 
//文章词频向量
$v1 = array('我们' => 5, '设计' => 2,  '一个' => 1, '算法' =>0, '任意' => 0, '相似' => 1);
$v2 = array('我们' => 5, '设计' => 0,  '一个' => 3, '算法' =>0, '任意' => 0, '相似' => 1);
//计算相似度,值越大相似程度越高
$result1 = similarity($v1,$v2);
print_r($result1);
// 查老域名快照,看看是否是作弊,301等
// https://archive.org/web/
// http://www.screenshots.com/
// 使用PHP读取文件写入数据库遇到一个灵异的问题,第一行第一列内容插入后变成0,查看文件第一行开头为BOM格式:
// head -n 1 file | hexdump -Cef bb bf
// 删除BOM解决:sed -i '1 s/^\xef\xbb\xbf//' file

//方法1
function trim_array($input) {
  if (!is_array($input))
    return trim($input);
  return array_map('trim_array', $input);
}
$Array = trim_array($Array);
//方法2
function trim_value (& $value ) { 
  if (!is_array($value)) {
    $value  =  trim ( $value ); 
    return;
  }
  array_walk ( $value ,  'trim_value' );
}
array_walk ($Array,  'trim_value' );

@mingyun
Copy link
Owner Author

mingyun commented Dec 24, 2017

https://konghq.com/install/  kong(lua/nodejs) + swoole/workman
把验证前置到kong  把过滤前置到kong , 然后老的程序直接引入swoole或者workman把接口包装一下
然后慢慢拆分成微服务,解决通讯,一致性,健康检查的等等问题。 前期只是个适应性的微改造而已
curl http://api.example.com/profile -d "phone=123456789&name=Hwei" 
curl http://api.example.com/profile -F "image=@profile.jpg" -F "phone=123456789"
curl http://api.example.com/profile -F "image=@profile.jpg"
curl -F 'file=@email.png' http://api.happyocr.com/send
curl -i -X POST -H "Content-Type: multipart/form-data" 
-F "data=@test.mp3" http://mysuperserver/media/1234/upload/
curl -i -X POST -H "Content-Type: multipart/form-data" 
-F "data=@test.mp3;userid=1234" http://mysuperserver/media/upload/
curl -c cookie.txt  -d "username=admin&password=admin" "www.xxx.com/doLogin"  目录下生成一个cookie.txt文件
curl -L -b cookie.txt -d "key=value" "url"  携带登陆信息进行post请求需要使用-b选项
不能同时使用-d和-F,这2个选项在curl中是两种方式的请求,-d为application/x-www-url-encoded方式发送post请求,而-F为multipart/form-data方式,
        如果在一次curl中同时使用-d和-F选项会报Warning: You can only select one HTTP request!的警告,导致指令无法执行
curl -F "myfile2=@hellocurl2.zip" "www.xxx.com/upload?filename=hellocurl" http://man.linuxde.net/curl
https://www.cnblogs.com/gbyukg/p/3326825.html 
http://gad.qq.com/article/detail/37971 30 后的路该开向哪里
增加一列table_name
select posts_id,posts_name,posts_status,'users' as table_name from yy_posts
UNION
select user_id,user_nickname,user_status,'posts' as table_name from yy_user 
// 32位系统2038年问题 1、日期字符串转换为时间戳
$obj = new DateTime("2050-12-31 23:59:59");
echo $obj->format("U"); // 2556115199

// 2、时间戳转换为日期字符串
$obj = new DateTime("@2556115199"); // 这里时间戳前要写一个@符号
$timezone = timezone_open('Asia/HONG_KONG'); // 设置时区
$obj->setTimezone($timezone); 
echo $obj->format("Y-m-d H:i:s"); // 2050-12-31 23:59:59

// 而且DateTime还可以有其他玩法
$obj = new DateTime("2050-12-31 23:59:59");
echo $obj->format("Y/m/d H:i:s"); // 换种方式输入时间字符串2050/12/31 23:59:59

var_dump(strtotime("2050-12-31 23:59:59"));https://segmentfault.com/blog/yanying
Math.formatFloat = function(f, digit) {
    var m = Math.pow(10, digit);
    return parseInt(f * m, 10) / m;
}

var numA = 0.1;
var numB = 0.2;
alert(Math.formatFloat(numA + numB, 1) === 0.3);
alert( parseFloat((numA + numB).toFixed(2)) === 0.3 );

setInterval(function(){

        var end_time = '2017-02-11 12:23:32';
        var curent_time = new Date();
        var unix_end_time = Date.parse( new Date( end_time ) );
        var time_len = unix_end_time - curent_time.getTime();

        //计算出天数
        var days = Math.floor( time_len / ( 24 * 3600 * 1000 ) );

        //计算出小时数
        //计算除去天数后剩余的毫秒数
        var day_surplus = time_len % ( 24 * 3600 * 1000 );
        var hours = Math.floor( day_surplus / ( 3600 * 1000 ) );

        //计算相差分钟数
        //计算除去小时数后剩余的毫秒数
        var hours_surplus = day_surplus % ( 3600 * 1000 );
        var minutes = Math.floor( hours_surplus / ( 60 * 1000 ) );

        //计算相差秒数
        //计算除去分钟数后剩余的毫秒数
        var seconds_surplus = hours_surplus % ( 60 * 1000 );
        var seconds = Math.round( seconds_surplus / 1000 );

        $("#days").html(days);
        $("#hours").html(hours);
        $("#minutes").html(minutes);
        $("#seconds").html(seconds);

    },1000);
生成一个现在最常用的订单号
$order_number = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
去除Iphone/Android手机页面中手机号码、邮箱自动转为链接功能
<meta name="format-detection" content="telephone=no,email=no,adress=no">
手机WebApp开发、强制页面1:1显示、禁止放大缩小功能
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" />
js关闭网页,并且不带有任何的提示
window.opener=null;window.open('','_self');window.close();
var _log = console.log;
    console.log = function() {
        _log.call(console, '%c' + [].slice.call(arguments).join(' '), 'color:transparent;text-shadow:0 0 2px rgba(0,0,0,.5);');
    };
document.body.contentEditable='true';
data:text/html, <html contenteditable>
中文3个字节
$string = '我';
$length=strlen($string);
$result = array(); 
for($i=0;$i<$length;$i++){ 
if(ord($string[$i])>127){ 
$result[] = ord($string[$i]).' '.ord($string[++$i]).' '.ord($string[++$i]); 
} 
} 
var_dump($result); //"230 136 145"
$str = '';
foreach($result as $v){
    if(empty(strstr($v,' '))){
        $str .= chr($v);
    }else{
        list($a,$b,$c) = explode(' ',$v);
        $str .= chr($a).chr($b).chr($c);
    }
}
echo $str;
git log -p en.php > ~/en.php.log 查看en.php的所有历史记录及提交的各种信息https://www.lvtao.net/tool/git-log.html
function utf8_substr($str, $limit) { 
$restr = ''; 
for($i=0;$i< $limit-3;$i++) { 
$restr .= ord($str[$i])>127 ? $str[$i].$str[++$i].$str[++$i] : $str[$i]; 
} 
return $restr; 
} 
curl 度量 Web 站点的响应时间

curl -o /dev/null -s -w '%{time_connect}:%{time_starttransfer}:%{time_total}\n' 'https://www.lvtao.net'

0.081:0.272:0.779 https://www.lvtao.net/tool/1881.html

@mingyun
Copy link
Owner Author

mingyun commented Dec 24, 2017

 $count = \App\Models\WebinarRelationAdvs::count();

        echo '总行数---'.$count.PHP_EOL;
        $limit = 500;
        $sum = 0;
        $s     = floor($count/$limit);
        for ($i=0; $i<=$s; $i++) {
            $skip = $limit * $i;
            $list = \App\Models\WebinarRelationAdvs::orderBy('id','desc')
                ->skip($skip)
                ->take($limit)
                ->get()
                ->toArray();
            if(!empty($list)){
                foreach ($list as $row){
                    \App\Models\WebinarRelationAdvs::where(['id'=>$row['id']])->update(['order_num'=>$row['id']]);
                    $sum++;
                }
            }
        }
        echo '成功执行----'.$sum.PHP_EOL;

$redis->lpush(self::MESSAGE ,json_encode($arr));

public static function add($webinar_id,$member,$score =1){
        //参会id 计数+1
        $num = \RedisFacade::HINCRBY('test:webinar:hash:'.$webinar_id,$member,$score);
        $time = time();
        $score = ($num * 10000000000) + 9999999999 - $time;
        \RedisFacade::zAdd('test:webinar:rank:'.$webinar_id,$score,$member);
    }
public static function getMemberScore($webinar_id,$member){
        return RedisFacade::hget('test:webinar:hash:'.$webinar_id,$member);
    }public static function getList($webinar_id){
        $list = RedisFacade::ZREVRANGEBYSCORE('test:webinar:rank:'.$webinar_id, '+inf', '-inf', array('withscores' => TRUE, 'limit' => array(0, 10)));//\RedisFacade::zrevrange('test:webinar:rank:666666',0,-1,'withscores')
        dump($list);
        $arr = [];
        if(!empty($list)){
            foreach ($list as $key =>$row){
                $arr[$key] = self::getMemberScore($webinar_id,$key);
            }
        }
        return $arr;
    }
// 相同的 score 先加入的排前面 默认是排后面
       // self::add(666666,11);
        // self::add(666666,12,2);
        // self::add(666666,13);
        // self::add(666666,14,4);
        self::add(666666,15);
        dd(self::getList(666666));
array:5 [
  14 => "48487888014"
  12 => "28487888077"
  11 => "18487888101"
  13 => "18487888054"
  15 => "18487887989"
]
array:5 [
  14 => "4"
  12 => "2"
  11 => "1"
  13 => "1"
  15 => "1"
>>> \RedisFacade::hgetall('test:webinar:hash:666666')
=> [
       11 => "1",
       12 => "2",
       13 => "1",
       14 => "4",
       15 => "1"
   ]
>>> \RedisFacade::zrevrange('test:webinar:hash:888888',0,-1,'withscores')
=> [
       13 => "2",
       12 => "1",
       11 => "1"
   ]
>>> \RedisFacade::zRevrank('test:webinar:rank:666666',14)
=> 0

http://www.sojson.com/httpRequest/ 接口测试工具 https://getman.cn/X5dfz
http://www.imooc.com/learn/618 模板消息接口

function curlGet($url,$method='get',$data=''){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $temp = curl_exec($ch);
    return $temp;
}


$url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN';

$json = '{
"touser":"Openid", //用户Openid
"template_id":"TEMPLATE_ID", //模板消息ID
"url":"", //留空IOS点击显示空白 Android 无法点击 非空跳转至该URL
"topcolor":"#FF0000",
"data":{
    "first": {
    "value":"黄先生",
    "color":"yellow"
    },
    "product":{
    "value":"乐事薯片",
    "color":"pink"
    },
    "price":{
    "value":"4元",
    "color":"#173177"
    },
    "time":{
    "value":"2013年9月10日",
    "color":"#173177"
    },
    "remark":{
    "value":"祝您生活愉快!",
    "color":"#173177"
    }
}'
https://segmentfault.com/a/1190000000672340
{{first.DATA}} ----- >"first": {"value":"黄先生","color":"yellow"},
$res = curlGet($url,'post',$json);

算法大致如下:
openid = m('公众号APPID'+'用户真实ID')
unionid = m('开放平台AppId'+'用户真实ID')

同一个开放平台下绑定的所有公众号号,移动应用,小程序的unionid都不变
https://segmentfault.com/q/1010000010006978 php 的话除了 pcntl_fork 多个进程跑脚本,本身有批处理的模块,可以用 curl_multi_* 批量发送
https://www.kancloud.cn/wssshmily/wx_template/192483
https://www.wangwenxiao.com/182
http://docs.wechatpy.org/zh_CN/master/messages.html 推送消息
http://blog.hizmz.com/2016/09/13/mbqunfa/ 
https://www.kancloud.cn/abc663401/wechat_cloud/291001 
https://easywechat.org/zh-cn/docs/notice.html 
http://lanewechat.lanecn.com/doc/main/aid-7 

@mingyun
Copy link
Owner Author

mingyun commented Dec 25, 2017

$s='{"test":"	json 测试php解释	
"}';
print_r(json_decode(strip_control_characters($s),1));
print_r(json_decode($s,1));
print_r(json_last_error_msg());
>>> call_user_func_array('array_merge', [[1],[2]])
=> [
       1,
       2
   ]
// 如果是 PHP 版本在 5.6 以上,可以使用 ... 操作符:
http://blog.wpjam.com/m/wpjam_is_holiday
// $merged = array_merge(...$result);
 // PHP 中对于 URL 进行编码,可以使用 urlencode() 或者 rawurlencode(),二者的区别是 urlencode() 把空格编码为 ‘+’,而 rawurlencode() 把空格编码为 ‘%20’。

// 2. rawurlencode() 遵守是94年国际标准备忘录 RFC 1738,urlencode() 实现的是传统做法,推荐在 PHP 中使用用 rawurlencode(),弃用 urlencode()。
// php7.1 在使用 (+ – * / ** % << >> | & ^) 这些运算操作符时,例如 a+b,如果 a(123a) 和 b(b456) 包含非数字字符时,就会有 A non-numeric value encountered 警告 echo intval($a)+intval($b);

echo urldecode(json_encode(urlencode("我爱水煮鱼")));
echo json_encode("我爱水煮鱼", JSON_UNESCAPED_UNICODE);
function wpjam_hex2rgb($hex) {
   $hex = str_replace("#", "", $hex);

   if(strlen($hex) == 3) {
      $r = hexdec(substr($hex,0,1).substr($hex,0,1));
      $g = hexdec(substr($hex,1,1).substr($hex,1,1));
      $b = hexdec(substr($hex,2,1).substr($hex,2,1));
   } else {
      $r = hexdec(substr($hex,0,2));
      $g = hexdec(substr($hex,2,2));
      $b = hexdec(substr($hex,4,2));
   }

   return array($r, $g, $b);
}
function wpjam_rgb2hex($rgb) {
   $hex = "#";
   $hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT);
   $hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT);
   $hex .= str_pad(dechex($rgb[2]), 2, "0", STR_PAD_LEFT);

   return $hex; 
}
// /将 $data 插入关联数组 $array 的键名为 $key 的 Key 之前:
function wpjam_array_push($array, $data=null, $key=false){
	$data	= (array)$data;
	$offset	= ($key===false)?false:array_search($key, array_keys($array));
	$offset	= ($offset)?$offset:false;

	if($offset){
		return array_merge(
			array_slice($array, 0, $offset), 
			$data, 
			array_slice($array, $offset)
		);
	}else{	// 没指定 $key 或者找不到,就直接加到末尾
		return array_merge($array, $data);
	}
}
function data_uri($file, $mime) {
  $contents=file_get_contents($file);
  $base64=base64_encode($contents);
  echo "data:$mime;base64,$base64";
}
$html = file_get_contents('http://www.example.com');

$dom = new DOMDocument();
@$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
       $href = $hrefs->item($i);
       $url = $href->getAttribute('href');
       echo $url.'<br />';
}
/*
它们的第一个参数都是被调用的回调函数,call_user_func() 还可以有多个参数,它们都是回调函数的参数,call_user_func_array() 只有两个参数,第二个参数是要被传入回调函数的数组,这个数组得是索引数组。

所以它们最大的区别就是:http://blog.wpjam.com/m/call_user_func-vs-call_user_func_array/

如果传递一个数组给 call_user_func_array(),数组的每个元素的值都会当做一个参数传递给回调函数,数组的 key 回调掉。
如果传递一个数组给 call_user_func(),整个数组会当做一个参数传递给回调函数,数字的 key 还会保留住。
 */
function test_callback(){
	$args	= func_get_args();
	$num	= func_num_args();
	echo $num."个参数:";
	echo "<pre>";
	print_r($args);
	echo "</pre>";
}

$args = array (
	'foo'	=> 'bar',
	'hello'	=> 'world',
	0	=> 123
);

call_user_func('test_callback', $args);
call_user_func_array('test_callback', $args);

/*
1 个参数:
Array
(
    [0] => Array
        (
            [foo] => bar
            [hello] => world
            [0] => 123
        )
)

3个参数:
Array
(
    [0] => bar
    [1] => world
    [2] => 123
)*/

// if(isset($array[$i])){ echo "存在"; }
// if(array_key_exists($i, $array)) { echo "存在"; }
// 如果这个函数在页面中被调用3次,那么这个复杂的计算过程就会被执行3次。我们把 $var 定义成静态变量,就可以把这个过程优化
function get_some_var(){
	static $var;
	if(!isset($var)){
		$var = complex_calculation();
	}
	return $var;
}
echo strlen("你好ABC") . "";
# 输出 9
echo mb_strlen("你好ABC", 'UTF-8') . "";
# 输出 5
echo mb_strwidth("你好ABC") . "";
#输出 7  mb_strwidth 则把中文算成 2 个字节,所以 mb_strwidth 才是我们想要的:中文 2 个字节,英文 1 个字节
#截取字符串也建议使用 mb_strimwidth,也是按照 中文 2 个字节,英文 1 个字节 方式计算之后的,并且如果字数超过截取的要求,这个函数还可以在最后面自动添加‘…’。

mb_strimwidth('截取字符串也建议使用 mb_strimwidth',0,240,'...','utf-8');
function byteFormat($bytes, $unit = "", $decimals = 2) {
	$units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);

	$value = 0;
	if ($bytes > 0) {
		// Generate automatic prefix by bytes 
		// If wrong prefix given
		if (!array_key_exists($unit, $units)) {
			$pow = floor(log($bytes)/log(1024));
			$unit = array_search($pow, $units);
		}

		// Calculate byte value by prefix
		$value = ($bytes/pow(1024,floor($units[$unit])));
	}

	// If decimals is not numeric or decimals is less than 0 
	// then set default value
	if (!is_numeric($decimals) || $decimals < 0) {
		$decimals = 2;
	}

	// Format output
	return sprintf('%.' . $decimals . 'f '.$unit, $value);
}
echo byteFormat(4096, "B") ."\n";
echo byteFormat(8, "B", 2) . "\n";
echo byteFormat(1, "KB", 5) . "\n";
echo byteFormat(1073741824, "B", 0) . "\n";
echo byteFormat(1073741824, "KB", 0) . "\n";
echo byteFormat(1073741824, "MB") . "\n";
echo byteFormat(1073741824) . "\n";
echo byteFormat(1073741824, "TB", 10) . "\n";
echo byteFormat(1099511627776, "PB", 6) . "\n";
// 查老域名快照,看看是否是作弊,301等
// https://archive.org/web/
// http://www.screenshots.com/
// 使用PHP读取文件写入数据库遇到一个灵异的问题,第一行第一列内容插入后变成0,查看文件第一行开头为BOM格式:
// head -n 1 file | hexdump -Cef bb bf
// 删除BOM解决:sed -i '1 s/^\xef\xbb\xbf//' file
删除控制符echo (strlen('中文abc')+mb_strlen('中文abc'))/2;
function strip_control_characters($str){
	return preg_replace('/[\x00-\x1F\x7F-\x9F]/u', '', $str);
} 

@mingyun
Copy link
Owner Author

mingyun commented Dec 25, 2017

nginx.cof

include edu.conf

server {
        listen       80;
        server_name  edu.com;
        root   "D:/soft/wamp/WWW/edu/public";
        location / {
            index  index.html index.htm index.php;
try_files $uri $uri/ /index.php?$query_string;
            autoindex  off;
            #autoindex  on;
        }
        location ~ \.php(.*)$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_split_path_info  ^((?U).+\.php)(/?.+)$;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            fastcgi_param  PATH_INFO  $fastcgi_path_info;
            fastcgi_param  PATH_TRANSLATED  $document_root$fastcgi_path_info;
            include        fastcgi_params;
        }
}

MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error
redis 192.168.60.41:6379> config get stop-writes-on-bgsave-error
1) "stop-writes-on-bgsave-error"
2) "yes"

redis 192.168.60.41:6379> config set stop-writes-on-bgsave-error no
guzzle通过yield来实现单线程的并发请求。
贝叶斯过滤垃圾邮件PHP实现 http://www.haiyun.me/archives/1043.html
重温PHP手册 http://www.powerxing.com/php-review-oop/
A simple php router https://github.com/takashiki/cdo
MySQL入门教程 https://github.com/jaywcjlove/mysql-tutorial
极验验证码(Geetest)  https://cuiqingcai.com/2988.html
PHP 使用 QueryList 轻松采集 https://laravel-china.org/articles/6288/php-uses-querylist-to-easily-capture-javascript-dynamic-rendering-pages#reply3
写了一个从网上抓取代理IP,然后构建代理IP池的脚本,放在了这里:https://github.com/xiaosimao/IP_POOL
一条SQL语句查询出成绩名次排名 http://blog.csdn.net/clever027/article/details/7554213
https://cuiqingcai.com/4652.html  抓取微信公众号的所有文章
http://v2ex.com/t/299183#reply14  分享一下之前做的 《手把手教你简单妹子图爬虫》系列 - V2EX
http://www.kancloud.cn/luofei614/programmer_talk_life/107486 技术的三个阶段 - [ 内外兼修·程序员成长之路 ] 
 Select 无限级联动下拉菜单 https://linkagesel.xiaozhong.biz/
Clean Code concepts adapted for PHP https://github.com/yangweijie/clean-code-php
一个因number_format引起的bug http://yangguoqi.me/
PHP导出报表 https://www.jianshu.com/p/f4d2eb3cb7ba 
function foo(&$var) { }
 
foo($a); // $a is "created" and assigned to null
 
$b = array();
foo($b['b']);
var_dump(array_key_exists('b', $b)); // bool(true)
$a = 1;
$c = 2;
$b =& $a;   // $b points to 1
$a =& $c;   // $a points now to 2, but $b still to 1;引用总是指向变量的内容
echo $a, " ", $b;   // Output: 2 1
function foo(&$var)
{
    $var++;
}
 
$a=5;
foo($a);
 PHP5 中,返回新对象时,默认是返回引用,因此可以达到链式操作的效果:
class Foo {
    public function sayHi() {
        echo 'Hi, ';
        return $this;
    }
    public function sayHello() {
        echo 'Hello';
        return $this;
    }
 
}当 unset 一个引用,只是断开了变量名和变量内容之间的绑定。这并不意味着变量内容被销毁了。
$a = 1;
$b =& $a;
unset($a);
echo $b;    // 1 http://www.powerxing.com/php-review-reference/
// 两种定义是等价的
global $var;
$val =& GLOBALS['var']; unset($var) 不会 unset 全局变量。
// for 的写法:
<?php for ($i = 0; $i < 5; ++$i): ?>
    Hello, there!
<?php endfor; ?>
 
 
// while的写法:
<?php while ($i < 10): ?>
    Hi.
<?php endwhile; ?>
//*     -> 代码块正常运行
if ($foo) {
  echo $bar;
}
// */
 
 
/*      -> 只需要删掉一个斜杠,代码块就注释掉了
if ($foo) {
  echo $bar;
}
// */
 
 
/* 通过这种方式可以控制两个代码块间的切换 */
 
 
//*     -> 2个斜杠,第2个代码块被注释
if ($foo) {
  echo $bar;
}
/*/
if ($bar) {
  echo $foo;
}
// */
 
/*      -> 1个斜杠,第1个代码块被注释
if ($foo) {
  echo $bar;
}
/*/
if ($bar) {
  echo $foo;
}
// */
 echo (int) ( (0.1+0.7) * 10 ); // 显示 7! 永远不要相信浮点数结果精确到了最后一位,也永远不要直接比较两个浮点数是否相等
$a = 1.23456789;
$b = 1.23456780;
$epsilon = 0.00001; # 可以比较小数点后五位的浮点数
 
if(abs($a-$b) < $epsilon) {
    echo "true";
}// $values可能为NULL.
$combined = array_merge((array)$values, $other);
如果在$_POST数组(从form中传递过来)中使用字符串作为键名,键名中的小数点、空格会转换为下划线。程序中操作$_POST数组,则不会有这个情况。如下面点击submit后,输出结果为POST: Array ( [Windows3_1] => Sux, [Mac10.9] => Mavericks )。
$obj = (object) 'ciao';
echo $obj->scalar;      // outputs 'ciao'
 
$arrObj = (object) array('a' => 'aa', 'b'=> 'bb');
echo $arrObj->a;        // outpus 'aa'
echo $arrObj->{'a'}     // outpus 'aa'
$arrObj = (object) array('aa', 'bb');
var_dump($arrObj); // object(stdClass)#1 (2) { [0]=> string(2) "aa" [1]=> string(2) "bb" }
echo $arrObj->{0}; // Notice: Undefined property: stdClass::$0 in...
空数组的情况,空数组 == NULL 成立: http://www.powerxing.com/php-review-types/

@mingyun
Copy link
Owner Author

mingyun commented Dec 31, 2017

PHP 高性能 Excel 扩展,五百年配方无内存泄漏 https://laravel-china.org/topics/6888/php-high-performance-excel-extension-five-hundred-year-formula-no-memory-leak#reply37308
https://github.com/viest/php-excel-writer

单文件 https://github.com/mk-j/PHP_XLSXWriter

include_once("xlsxwriter.class.php");
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);

$filename = "example.xlsx";

for($index = 0 ; $index < 250000 ; $index++){
    $data[$index] = ['viest', 23, 666666666666666666, '银河市地球区程序村PHP组菜鸟湾66号', 15666666666];
}

$timeStart = microtime(true);

$writer = new XLSXWriter();
$writer->writeSheet($data);
$writer->writeToFile('example.xlsx');

$timeEnd = microtime(true);
$time = $timeEnd - $timeStart;

echo "导出Excel花费: $time seconds\n";
echo '#'.floor((memory_get_peak_usage())/1024/1024)."MB"."\n";

$start = microtime(true);
$writer->writeSheetHeader('Sheet1', array('c1'=>'integer','c2'=>'integer','c3'=>'integer','c4'=>'integer') );//optional
for($i=0; $i<250000; $i++)
{
    $writer->writeSheetRow('Sheet1', array(rand()%10000,rand()%10000,rand()%10000,rand()%10000) );
}
$writer->writeToFile('xlsx-numbers-250k.xlsx');//5.76MB
echo '#'.floor((memory_get_peak_usage())/1024/1024)."MB"."\n";
$end = microtime(true);
echo '耗时'.round($end-$start,3).'秒';//9.76

PDF、PPT、Excel、Word、视频等格式文件在线预览 https://laravel-china.org/articles/6891/pdf-ppt-excel-word-video-and-other-format-files-online-preview https://github.com/bean-du/excel
https://laravel-china.org/topics/5612/importing-excel-files-in-laravel-the-amount-of-data-is-too-large-the-server-often-500-how-to-do http://www.maatwebsite.nl/laravel-excel/docs/export#rows
https://laravel-china.org/topics/801/recommend-a-good-component-laravel-excel-excel-input-and-output var_dump($reader->toArray());//第一行内容为key,如果为中文,需要修改excel.php的 'to_ascii' => false, https://laravel-china.org/topics/1918/extension-how-to-deal-with-the-excel-file-in-the-laravel-project
https://laravel-china.org/topics/2029/laravel-excel-import-excel-file-incomplete-solution 'to_ascii' => true, 改为false,这下就算是中文标题也OK

$str = "时间,昵称,姓名,手机\n";
$filename = 'webinar_lottery_'.$id.'_'.date('YmdHi').'.csv'; //设置文件名
$this->common->export_csv($filename);
$lists = LotteryUser::where('lottery_id', $lottery->id)
->orderBy('id', 'desc')
->get()->toArray();
foreach($lists as $l){
$nick_name = empty($l['nick_name'])?'':$l['nick_name'];
$nick_name = Str::exportFilter($nick_name);
$start = ($lottery->created_at=='0000-00-00 00:00:00')?'':$lottery->created_at;
$name = empty($l['name'])?'':$l['name'];
$phone = empty($l['phone'])?'':$l['phone'];
$str .= "\t".$start.",".$nick_name.",".$name.",".$phone."\n";
}
$str = iconv('utf-8','GBK//IGNORE',$str);
echo $str;
public function export_csv($filename)
{
header("Content-type:text/csv");
header("Content-Disposition:attachment;filename=".$filename);
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');

}

大数字变成科学计数

如 11111111111 显示成 1.11111E+29
导出 excel 错误

PHPExcel_Calculation_Exception: Q5!A65 → Formula Error: An unexpected error occured in /application/www/web_git-pull/vendor/phpoffice/phpexcel/Classes/PHPExcel/Cell.php:291

在excel中一个单元格如果是以“=”开头,则说明这个单元格是根据其他单元格的值算出来的,“=”后面必须跟着一个合法的表达式

而那个字符串是用户的输入,很明显不应该是一个合法的表达式,所以应该在代码中过滤掉或者 $str = “\t”.$str;
https://segmentfault.com/q/1010000000509020
https://segmentfault.com/q/1010000000248717 只要0前加一小撇“'”(数字状态下的)就欧了。 也就是说:用简单的方法,Excel中的数字转文本就是加“'”,明白?!
SpartnerNL/Laravel-Excel#506

https://stackoverflow.com/questions/11189145/formula-error-in-phpexcel

win7 2038 年问题

var_dump(strtotime("2050-12-31 23:59:59"));//false
$obj = new DateTime("2050-12-31 23:59:59");
echo $obj->format("Y/m/d H:i:s"); // 2050/12/31 23:59:59
https://segmentfault.com/a/1190000011488841
https://segmentfault.com/a/1190000005366832
https://www.jianshu.com/p/6d8a99621e8b
for ($i=0; $i < 10000; $i++) {
echo "hello ".printf('%05s',$i).'
';
ob_flush();
flush();
} https://segmentfault.com/q/1010000000115282
https://gitee.com/xavier007/Xavxls

@mingyun
Copy link
Owner Author

mingyun commented Dec 31, 2017

SpartnerNL/Laravel-Excel#148
附adb工具下载(已包含cmd):http://pan.baidu.com/s/1mgGkNZM
https://github.com/wangshub/wechat_jump_game
JavaScript版本微信跳一跳"AI"脚本 https://github.com/hyb1996/WechatJumping.js

1.手机需安装证书:safari打开http://charlesproxy.com/getssl 可直接安装证书

2.pc端:在Charles的工具栏上点击设置按钮,选择Proxy Settings…

切换到SSL选项卡,选中Enable SSL Proxying

注:如果没有设置ssl的话,那么你看到的ssl的接口中,会有一个报错:SSL Proxying not enabled for this host: enable in Proxy Settings, SSL locations,这个时候,在左侧的域名上点右键:enable ssl,就OK了。

作者:af7f15573e1e
链接:https://www.jianshu.com/p/c47366ca3d49
教你在Mac+iPhone上用Python玩微信跳一跳
微信小游戏 https://m.weibo.cn/status/4192215624177208
https://1024ss.com/s#q=mysql%20redis

https://mp.weixin.qq.com/wxagame/wxagame_bottlereport
{
	"base_req": {
		"session_id": "Iv4xgn0ZqZBnsubuiER4xBGIZTd4giaNZofLxLE2iPOkcnNXZcMRDLyfPgURSOw6IdX1X5OmPBhXps78nDY0SyAmxiFiv4HnwMJHI+jtj0A5TAQ1YtkgqbRJZmb4n7eVs4v0D7P6k1jzXxrs7zQ7jA==",
		"fast": 1,
		"client_info": {
			"platform": "android",
			"brand": "Honor",
			"model": "CHM-TL00H",
			"system": "Android 4.4.2"
		}
	},
	"report_list": [{
		"ts": 1515060993,
		"type": 2,
		"score": 666,
		"best_score": 832,
		"break_record": 0,
		"duration": 176,
		"times": 237
	}]
}

{
	"base_resp": {
		"errcode": 0,
		"ts": "1515060995601"
	},
	"user_info": [{
		"nickname": "望月",
		"headimg": "http:\/\/wx.qlogo.cn\/mmhead\/vbazXibx6TdkVehyGIXXtcxSIgHPlvyGs6iaOVd78tsvY\/96",
		"score_info": [],
		"week_best_score": 349,
		"grade": 4,
		"hongbao_list": []
	}, {
		"nickname": "造数君",
		"headimg": "http:\/\/wx.qlogo.cn\/mmhead\/Iic9WLWEQMg1icGPXZ54MiaJ8Rus8IQrZP30CcXjvgVVmPZG6YFmFs9ow\/96",
		"score_info": [],
		"week_best_score": 22,
		"grade": 0,
		"hongbao_list": []
	}, {
		"nickname": "Durian",
		"headimg": "http:\/\/wx.qlogo.cn\/mmhead\/1CHHx9Yq4nHZSFxniarxXWrHIgKROpJtNqy0RJFibfDiantfsjbWAqejA\/96",
		"score_info": [],
		"week_best_score": 124,
		"grade": 2,
		"hongbao_list": []
	}, {
		"nickname": "稀文",
		"headimg": "http:\/\/wx.qlogo.cn\/mmhead\/1jsQWb6ybgpPe94RSVe5xbM3ofqYX3CwlEf9QxqGVaA\/96",
		"score_info": [],
		"week_best_score": 87,
		"grade": 1,
		"hongbao_list": []
	}, {
		"nickname": "小胡子哥",
		"headimg": "http:\/\/wx.qlogo.cn\/mmhead\/Q3auHgzwzM6lEgnnOXDyJTfp2DW4CJR1qmGXQKd4l2tYSiaibc1roJ2Q\/96",
		"score_info": [],
		"week_best_score": 53,
		"grade": 1,
		"hongbao_list": []
	}, {
		"nickname": "新青年(一个爱做发财梦的穷小哥)",
		"headimg": "http:\/\/wx.qlogo.cn\/mmhead\/K6CEv0Hv9DeszkMC7rtKAegJtvabue0hCD2uTObiarKWonQqhHnhypA\/96",
		"score_info": [],
		"week_best_score": 45,
		"grade": 0,
		"hongbao_list": []
	}, {
		"nickname": "justjavac",
		"headimg": "http:\/\/wx.qlogo.cn\/mmhead\/zZTzw65VTeib6DJxRdv4VQuEQwCOrlCPsPx9IXekJzJs\/96",
		"score_info": [],
		"week_best_score": 14,
		"grade": 2,
		"hongbao_list": []
	}, {
		"nickname": "尹喆",
		"headimg": "http:\/\/wx.qlogo.cn\/mmhead\/uhiaIOzbHYJOyYpqT3icIicBJKFCGlZiaET03fSLg324w4s\/96",
		"score_info": [],
		"week_best_score": 4,
		"grade": 0,
		"hongbao_list": []
	}, {
		"nickname": "逆水寒",
		"headimg": "http:\/\/wx.qlogo.cn\/mmhead\/ajNVdqHZLLCelhy6ktmibQFs6RaVniazlRAmIULUFBDRrv9Lick6CHWeQ\/96",
		"score_info": [],
		"week_best_score": 130,
		"grade": 2,
		"hongbao_list": []
	}],
	"my_user_info": {
		"nickname": "梦想旅程",
		"headimg": "http:\/\/wx.qlogo.cn\/mmhead\/6JJITcvPeqSChsZdXbAmE7kM4rrSeZ76nE3o1VicbIjc\/96",
		"score_info": [],
		"history_best_score": 832,
		"week_best_score": 832,
		"grade": 5,
		"times": 234,
		"hongbao_list": []
	}
}

http://java.zhaoxuyang.com/WxTyT/
https://zhaoxuyang.com/ios%E4%B8%8B%E6%8A%93%E5%8F%96%E5%BE%AE%E4%BF%A1%E8%B7%B3%E4%B8%80%E8%B7%B3%E5%B0%8F%E6%B8%B8%E6%88%8F%E7%9A%84session_id%E5%80%BC/  iOS下抓取微信跳一跳小游戏的session_id值
安卓抓包参考教程:http://t.cn/RH8hS0U
iOS抓包参考教程:http://t.cn/RH8hldu
Web刷分session_id提交链接:
主站 :http://java.zhaoxuyang.com/WxTyT/
备用:http://tyt.zhaoxuyang.com/WxTyT/
我的博客:https://zhaoxuyang.com
1.请不要随便将自己的session_id发到群里
https://www.jianshu.com/p/5539599c7a25
腾讯服务器返回的原始数据: 
{"base_resp":{"errcode":0,"ts":"1515065234933"}}
代表含义:改分成功,请结束微信进程重新进入等待分数刷新
https://www.jianshu.com/p/83e59181fd97  https://github.com/Erimus-Koo/wechat_jump_game 跳一跳外挂最简算法
http://fabiotoste.com/  
 
Failed to load http://t-api-class.e.vhall.com/edu/user/check-login 

: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8088' is therefore not allowed access. The response had HTTP status code 404.
Access-Control-Allow-Origin  * 不能设置 Access-Control-Allow-Credentials
Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:*
Access-Control-Allow-Origin:http://t-class.e.com #前面要加个http://

vue.com   跨域请求 t-api-class.e.vhall.com 
vue.com 访问前端代码
server {
        listen       80;
        server_name  vue.com;
        root   "D:/soft/WWW/public/dist";
        location / {
            index  index.html index.htm index.php;
        }
        location /api/ {
            proxy_pass http://edu.com/;
            proxy_set_header Host $host:$server_port;
        }
}
t-api-class.e.vhall.com 为本地接口域名 
server {
        listen       80;
        server_name  t-api-class.e.vhall.com;
        root   "D:/soft/WWW/edu/public";
        add_header Access-Control-Allow-Credentials true;
        add_header Access-Control-Allow-Methods *;
        add_header Access-Control-Allow-Origin http://vue.com;
        location / {
            index  index.html index.htm index.php;
            try_files $uri $uri/ /index.php?$query_string;
            autoindex  off;
            #autoindex  on;
        }
        location ~ \.php(.*)$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_split_path_info  ^((?U).+\.php)(/?.+)$;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            fastcgi_param  PATH_INFO  $fastcgi_path_info;
            fastcgi_param  PATH_TRANSLATED  $document_root$fastcgi_path_info;
            include        fastcgi_params;
        }
}

$data = ['limit' => ['start' => 0, 'end' => 5], 'table_name' => 'online_biz_id_1min_analysis_data', 'order_by' => 'biz_id', 'between_and_filter' => ['start' => '2018-01-04 17:00:00', 'end' => '2018-01-04 17:07:00','key' => 'timestamp_1min']];echo $url.'api/education?'.json_encode($data);
        $res =curlGetRequest($url.'api/?'.json_encode($data);// fail Malformed HTTP request line
$res =curlGetRequest($url.'api/?'.base64_encode(json_encode($data));
python get 没问题 
res = requests.get(url, params=_data, headers=headers)
https://blog.zhengxianjun.com/2015/05/javascript-crypto-js/ 
calculateSignature = function (toSign, key) {
        var hash, hex, signed;
        hash = CryptoJS.HmacSHA1(toSign, key);
        hex = hash.toString(CryptoJS.enc.Hex);
        signed = N.Base64.encodeBase64(hex);
        return signed;
    };
npm install crypto-js
var CryptoJS = require('crypto-js')
 
var hmacSHA1 = CryptoJS.HmacSHA1("Message", "Secret Passphrase").toString(CryptoJS.enc.Hex);
console.log(hmacSHA1) ;e90f713295ea4cc06c92c9248696ffafc5d01faf

$sign = base64_encode(hash_hmac('sha1', $toSign, $key)); 
$res =  curlRequest($url, json_encode($data), 5, ['Content-Type: application/json','Authorization: '.$header]);

@mingyun
Copy link
Owner Author

mingyun commented Jan 5, 2018

$ curl 'http://localhost:9001/res?data= test'
curl: (52) Empty reply from server
>>> s='eyJsaW1pdCI6eyJzdGFydCI6MCwiZW5kIjo1fSwidGFibGVfbmFtZSI6Im9ubGluZV91dl9hY
2NvdW50X2lkXzFob3VyX2FuYWx5c2lzX2RhdGEiLCJmaWx0ZXJfYXJncyI6eyJ2ZmlkIjoiMTQiLCJ0a
W1lc3RhbXBfMWhvdXIiOiIyMDE4LTAxLTA1IDIwOjA0OjI2In0sImJpel9kZXMwMSI6MCwib3JkZXJfY
nkiOiJ0aW1lc3RhbXBfMWhvdXIifQ'
>>> base64.b64decode(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "d:\python27\lib\base64.py", line 76, in b64decode
    raise TypeError(msg)
TypeError: Incorrect padding
>>> base64.b64decode(s+'===')
'{"limit":{"start":0,"end":5},"table_name":"online_uv_account_id_1hour_analysis_
data","filter_args":{"vfid":"14","timestamp_1hour":"2018-01-05 20:04:26"},"biz_d
es01":0,"order_by":"timestamp_1hour"}'
def decode_base64(data):
    """Decode base64, padding being optional.

    :param data: Base64 data as an ASCII byte string
    :returns: The decoded byte string.

    """
    missing_padding = len(data) % 4
    if missing_padding != 0:
        data += b'='* (4 - missing_padding)
    return base64.decodestring(data)
替换code后的链接复制到短链接 http://dwz.wailian.work/  
  https://www.jianshu.com/p/b599f85fdbef?from=timeline
免ROOT抓包  :  https://pan.baidu.com/s/1pLgfnqN 
    有的就不用下载了
再加一个刷分数的链接  :  http://java.zhaoxuyang.com/WxTyT/ 
第一步安装,抓包工具,切记,[安装的时候提示,证书什么的,一定要安装,]就这么简单

第二步,把其他的应用禁网,就留下,抓包工具和微信,

第三步,打开微信跳一跳,在点击开始游戏,然后打开抓包按钮并点击右上角开始抓包,

第四步,进游戏,跳几步,然后死掉,然后打开抓包工具,点击停止,然后打开这个包,找到一个,红色字样的  SSL  大写的,打开这一段 
复制,session_id  后面的内容,注意看图,

最后一不,打开链接,填入,session_id 在填入想要的分数,最后一个游戏次数,要比这个刷的分数大,比如你要刷 88  下面就填89

很多人反应SSL无数据,原因就是,证书没装好,好好看看我的,教程,还有就是这个版本的,抓包需要锁屏密码,这个我也不知道怎么回事。
教程视频在我快手:xiaohaoye200112
使用 GitHub Pages 搭建博客 http://gfwthesourceofevil.github.io/blog/2015/02/24/blogging-with-github-pages/
内网穿透 ngrok 服务器和客户端配置 https://xicheng412.github.io/2016/09/27/ngrok-config/#top
新建任意名字repo(非.github.io),比如project,新建gh-pages分支,一切更改在gh-pages上进行。对外访问链接为http://<username>.github.io/project 
https://simmin.github.io/2017/12/06/GitHub%20%E4%B8%8B%E5%A2%9E%E5%8A%A0%E9%A1%B9%E7%9B%AE%E4%B8%BB%E9%A1%B5/
在settings页面,找到GitHub Pages选项,点击 Source 下面的 None 选项,如下图示,选择master branch,最后点击 Save 按钮 
如何预览GitHub项目里面的网页或Demo https://gzyq.github.io/2017/04/07/read-github-html/

@mingyun
Copy link
Owner Author

mingyun commented Jan 21, 2018

php 替代函数递归方式的无限层级分类生成树方法 https://hanxv.cn/archives/98.html

/**
$data 节点list数据
$parent_index 父节点索引名,默认值parent_id
$data_index 各节点索引名,默认值id
$child_name 树状结构中子节点位存于父节点的属性值,默认值child
https://github.com/AxiosCros/tpr-composer/blob/master/src/helper.php 
根据节点id作为key值
单循环各节点,判断是否有父节点
若有父节点,则子节点绑定至父节点的child属性中
当出现a属于b,b属于c,c属于a这种死循环所属关系时,不会在$tree中体现
*/
 function tpr_infinite_tree($data,$parent_index='parent_id',$data_index='id',$child_name='child'){
        $items = [];
        foreach ($data as $d){
            $items[$d[$data_index]] = $d;
            if(!isset($d[$parent_index]) || !isset($d[$data_index]) || isset($d[$child_name])){
                return false;
            }
        }
        $tree = [];$n=0;
        foreach($items as $item){
            if(isset($items[$item[$parent_index]])){
                $items[$item[$parent_index]][$child_name][] = &$items[$item[$data_index]];
            }else{
                $tree[$n++] = &$items[$item[$data_index]];
            }
        }
        return $tree;
    }
echo '<pre>';
    $data = [
            ['id'=>1,'parent_id'=>0],
           ['id'=>2,'parent_id'=>3],
            ['id'=>3,'parent_id'=>1],
           ['id'=>4,'parent_id'=>2],
           ['id'=>5,'parent_id'=>6],
           ['id'=>6,'parent_id'=>7],
           ['id'=>7,'parent_id'=>5],
       ];
    print_r(tpr_infinite_tree($data));
Array
(
    [0] => Array
        (
            [id] => 1
            [parent_id] => 0
            [child] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [parent_id] => 1
                            [child] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 2
                                            [parent_id] => 3
                                            [child] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [id] => 4
                                                            [parent_id] => 2
                                                        )
                                                )
                                        )
                                )
                        )
                )
        )
)
php二维数组排序---支持单条件或多条件 https://hanxv.cn/archives/84.html
function arraySort($array,$sortRule,$order="asc"){
    if(is_array($sortRule)){
        /**
         * $sortRule = ['book'=>"asc",'version'=>"asc"]; 条件支持N多个
         */
        usort($array, function ($a, $b) use ($sortRule) {
            foreach($sortRule as $sortKey => $order){
                if($a[$sortKey] == $b[$sortKey]){continue;}
                return (($order == 'desc')?-1:1) * (($a[$sortKey] < $b[$sortKey]) ? -1 : 1);
            }
            return 0;
        });
    }else if(is_string($sortRule)){
        /**
         * $sortRule = "book";
         * $order = "asc";
         */
        usort($array,function ($a,$b) use ($sortRule,$order){
            if($a[$sortRule] == $b[$sortRule]){
              return 0;
            }
            return (($order == 'desc')?-1:1) * (($a[$sortRule] < $b[$sortRule]) ? -1 : 1);
        });
    }
    return $array;
}
$array = [
                 ["book"=>10,"version"=>10],
                 ["book"=>19,"version"=>30],
                 ["book"=>10,"version"=>30],
                 ["book"=>19,"version"=>10],
                 ["book"=>10,"version"=>20],
                 ["book"=>19,"version"=>20]
];
//单条件
$array = arraySort($array,'book','asc');
print_r($array);
Array
(
    [0] => Array
        (
            [book] => 10
            [version] => 10
        )
    [1] => Array
        (
            [book] => 10
            [version] => 30
        )
    [2] => Array
        (
            [book] => 10
            [version] => 20
        )
    [3] => Array
        (
            [book] => 19
            [version] => 30
        )
    [4] => Array
        (
            [book] => 19
            [version] => 10
        )
    [5] => Array
        (
            [book] => 19
            [version] => 20
        )
)
//多条件
arraySort($array,['book'=>"asc",'version'=>"asc"]);
print_r($array);
Array
(
    [0] => Array
        (
            [book] => 10
            [version] => 10
        )
    [1] => Array
        (
            [book] => 10
            [version] => 30
        )
    [2] => Array
        (
            [book] => 10
            [version] => 20
        )
    [3] => Array
        (
            [book] => 19
            [version] => 30
        )
    [4] => Array
        (
            [book] => 19
            [version] => 10
        )
    [5] => Array
        (
            [book] => 19
            [version] => 20
        )
)进制转换https://hanxv.cn/archives/111.html
$uuid = uniqid('code');
$resule = ConvertLogic::convert( $uuid, 16, 62);
//输出https://github.com/AxiosCros/tpr-cms/blob/master/library/logic/CodeLogic.php
//string(17) "5a5c5b182386"
//string(12) "7hoyVkRTi "
项目架构设计总结https://hanxv.cn/archives/81.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
@mingyun and others