php aes加密类

<?php
namespace app\common\lib;

/**
 * aes 加密 解密类库
 * @by singwa
 * Class Aes
 * @package app\common\lib
 */
class Aes {

    private $key = null;

    /**
     *
     * @param $key 		密钥
     * @return String
     */
    public function __construct() {
        // 需要小伙伴在配置文件app.php中定义aeskey
        $this->key = md5(config('app.aeskey'));
    }

    /**
     * 加密
     * @param String input 加密的字符串
     * @param String key   解密的key
     * @return HexString
     */
    public function encrypt($input = '') {

        if(version_compare(PHP_VERSION,'7.0.0','<'))
        {
            $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
            $input = $this->pkcs5_pad($input, $size);
            $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
            $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
            mcrypt_generic_init($td, $this->key, $iv);
            $data = mcrypt_generic($td, $input);
            mcrypt_generic_deinit($td);
            mcrypt_module_close($td);
        }else
        {
            $data =  openssl_encrypt($input, 'AES-256-ECB', $this->key, OPENSSL_RAW_DATA);
        }

        $data = base64_encode($data);

        return $data;
    }
    /**
     * 填充方式 pkcs5
     * @param String text 		 原始字符串
     * @param String blocksize   加密长度
     * @return String
     */
    private function pkcs5_pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    /**
     * 解密
     * @param String input 解密的字符串
     * @param String key   解密的key
     * @return String
     */
    public function decrypt($sStr) {
        if(version_compare(PHP_VERSION,'7.0.0','<')) {
            $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, base64_decode($sStr), MCRYPT_MODE_ECB);
            $dec_s = strlen($decrypted);
            $padding = ord($decrypted[$dec_s - 1]);
            $decrypted = substr($decrypted, 0, -$padding);
        }else{
            $encrypted = base64_decode($sStr);
            $decrypted = openssl_decrypt($encrypted, 'AES-256-ECB',$this->key, OPENSSL_RAW_DATA);
        }
        return $decrypted;
    }

}

nginx geoip 模块 使用

$ wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP.tar.gz
$ tar -zxvf GeoIP.tar.gz
$ cd GeoIP-1.4.8
$ ./configure
$ make
$ make install
$ ./configure --with-http_geoip_module 
    
$ make && make install

geoip_country /web/test/nginx/packbag/GeoIP.dat;

#location / {
        #       default_type ‘text/plain’;
        #       add_header Content-type ‘text/html;charset=utf-8’;
                #return 200 ‘$geoip_country_code’;
        #       content_by_lua_file conf/test1.lua;
                #return 200 ‘{“http_user_agent”:”$http_user_agent”,”remote_user”:”$remote_user”,”tcp”:”$tcpinfo_rtt, $tcpinfo_rttvar, $tcpinfo_snd_cwnd, $tcpinfo_rcv_space”,”content_type”:”$content_type”,”host”:”$host”,”remote_addr”:”$remote_addr”,”args”:”$args”}’;
        #}

python换脸

#!/usr/bin/python

# Copyright (c) 2015 Matthew Earl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
#     The above copyright notice and this permission notice shall be included
#     in all copies or substantial portions of the Software.
#
#     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
#     OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#     MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
#     NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
#     DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
#     OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
#     USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
This is the code behind the Switching Eds blog post:
    http://matthewearl.github.io/2015/07/28/switching-eds-with-python/
See the above for an explanation of the code below.
To run the script you'll need to install dlib (http://dlib.net) including its
Python bindings, and OpenCV. You'll also need to obtain the trained model from
sourceforge:
    http://sourceforge.net/projects/dclib/files/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2
Unzip with `bunzip2` and change `PREDICTOR_PATH` to refer to this file. The
script is run like so:
    ./faceswap.py <head image> <face image>
If successful, a file `output.jpg` will be produced with the facial features
from `<head image>` replaced with the facial features from `<face image>`.
"""

import cv2
import dlib
import numpy

import sys

PREDICTOR_PATH = "shape_predictor_68_face_landmarks.dat"
SCALE_FACTOR = 1
FEATHER_AMOUNT = 11

FACE_POINTS = list(range(17, 68))
MOUTH_POINTS = list(range(48, 61))
RIGHT_BROW_POINTS = list(range(17, 22))
LEFT_BROW_POINTS = list(range(22, 27))
RIGHT_EYE_POINTS = list(range(36, 42))
LEFT_EYE_POINTS = list(range(42, 48))
NOSE_POINTS = list(range(27, 35))
JAW_POINTS = list(range(0, 17))

# Points used to line up the images.
ALIGN_POINTS = (LEFT_BROW_POINTS + RIGHT_EYE_POINTS + LEFT_EYE_POINTS +
                RIGHT_BROW_POINTS + NOSE_POINTS + MOUTH_POINTS)

# Points from the second image to overlay on the first. The convex hull of each
# element will be overlaid.
OVERLAY_POINTS = [
    LEFT_EYE_POINTS + RIGHT_EYE_POINTS + LEFT_BROW_POINTS + RIGHT_BROW_POINTS,
    NOSE_POINTS + MOUTH_POINTS,
]

# Amount of blur to use during colour correction, as a fraction of the
# pupillary distance.
COLOUR_CORRECT_BLUR_FRAC = 0.6

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(PREDICTOR_PATH)


class TooManyFaces(Exception):
    pass


class NoFaces(Exception):
    pass


def get_landmarks(im):
    rects = detector(im, 1)

    if len(rects) > 1:
        raise TooManyFaces
    if len(rects) == 0:
        raise NoFaces

    return numpy.matrix([[p.x, p.y] for p in predictor(im, rects[0]).parts()])


def annotate_landmarks(im, landmarks):
    im = im.copy()
    for idx, point in enumerate(landmarks):
        pos = (point[0, 0], point[0, 1])
        cv2.putText(im, str(idx), pos,
                    fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,
                    fontScale=0.4,
                    color=(0, 0, 255))
        cv2.circle(im, pos, 3, color=(0, 255, 255))
    return im


def draw_convex_hull(im, points, color):
    points = cv2.convexHull(points)
    cv2.fillConvexPoly(im, points, color=color)


def get_face_mask(im, landmarks):
    im = numpy.zeros(im.shape[:2], dtype=numpy.float64)

    for group in OVERLAY_POINTS:
        draw_convex_hull(im,
                         landmarks[group],
                         color=1)

    im = numpy.array([im, im, im]).transpose((1, 2, 0))

    im = (cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0) > 0) * 1.0
    im = cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0)

    return im


def transformation_from_points(points1, points2):
    """
    Return an affine transformation [s * R | T] such that:
        sum ||s*R*p1,i + T - p2,i||^2
    is minimized.
    """
    # Solve the procrustes problem by subtracting centroids, scaling by the
    # standard deviation, and then using the SVD to calculate the rotation. See
    # the following for more details:
    #   https://en.wikipedia.org/wiki/Orthogonal_Procrustes_problem

    points1 = points1.astype(numpy.float64)
    points2 = points2.astype(numpy.float64)

    c1 = numpy.mean(points1, axis=0)
    c2 = numpy.mean(points2, axis=0)
    points1 -= c1
    points2 -= c2

    s1 = numpy.std(points1)
    s2 = numpy.std(points2)
    points1 /= s1
    points2 /= s2

    U, S, Vt = numpy.linalg.svd(points1.T * points2)

    # The R we seek is in fact the transpose of the one given by U * Vt. This
    # is because the above formulation assumes the matrix goes on the right
    # (with row vectors) where as our solution requires the matrix to be on the
    # left (with column vectors).
    R = (U * Vt).T

    return numpy.vstack([numpy.hstack(((s2 / s1) * R,
                                       c2.T - (s2 / s1) * R * c1.T)),
                         numpy.matrix([0., 0., 1.])])


def read_im_and_landmarks(fname):
    im = cv2.imread(fname, cv2.IMREAD_COLOR)
    im = cv2.resize(im, (im.shape[1] * SCALE_FACTOR,
                         im.shape[0] * SCALE_FACTOR))
    s = get_landmarks(im)

    return im, s


def warp_im(im, M, dshape):
    output_im = numpy.zeros(dshape, dtype=im.dtype)
    cv2.warpAffine(im,
                   M[:2],
                   (dshape[1], dshape[0]),
                   dst=output_im,
                   borderMode=cv2.BORDER_TRANSPARENT,
                   flags=cv2.WARP_INVERSE_MAP)
    return output_im


def correct_colours(im1, im2, landmarks1):
    blur_amount = COLOUR_CORRECT_BLUR_FRAC * numpy.linalg.norm(
        numpy.mean(landmarks1[LEFT_EYE_POINTS], axis=0) -
        numpy.mean(landmarks1[RIGHT_EYE_POINTS], axis=0))
    blur_amount = int(blur_amount)
    if blur_amount % 2 == 0:
        blur_amount += 1
    im1_blur = cv2.GaussianBlur(im1, (blur_amount, blur_amount), 0)
    im2_blur = cv2.GaussianBlur(im2, (blur_amount, blur_amount), 0)

    # Avoid divide-by-zero errors.
    im2_blur += (128 * (im2_blur <= 1.0)).astype(im2_blur.dtype)

    return (im2.astype(numpy.float64) * im1_blur.astype(numpy.float64) /
            im2_blur.astype(numpy.float64))


im1, landmarks1 = read_im_and_landmarks('image/1.jpg')
im2, landmarks2 = read_im_and_landmarks('image/11.jpg')

M = transformation_from_points(landmarks1[ALIGN_POINTS],
                               landmarks2[ALIGN_POINTS])

mask = get_face_mask(im2, landmarks2)
warped_mask = warp_im(mask, M, im1.shape)
combined_mask = numpy.max([get_face_mask(im1, landmarks1), warped_mask],
                          axis=0)

warped_im2 = warp_im(im2, M, im1.shape)
warped_corrected_im2 = correct_colours(im1, warped_im2, landmarks1)

output_im = im1 * (1.0 - combined_mask) + warped_corrected_im2 * combined_mask

cv2.imwrite('output.jpg', output_im)

异步抓取网页 python aiohttp

    import asyncio
    import aiohttp
    
    async def get(url):
        try:
            async with aiohttp.ClientSession() as session:
                response = await session.get(url)
                result = await response.text()
                await session.close()
                return result
        except Exception as e:
            print("Fail:"+url)
            await session.close()
            return 0
    
    async def request(url):
        print('开始地址', url)
        res = await get(url)
        print('返回数据:', res)
    urls = [
        'http://csdn.com',
        'http://dev.dcloud.net.cn',
        'http://yigongla.com'
    ]
    tasks = []
    for url in urls:
        #把函数添加到task列表中
        tasks.append(request(url))
    
    try:
        loop = asyncio.get_event_loop()
        #asyncio.wait 接受一个task列表
        loop.run_until_complete(asyncio.wait(tasks))
    except Exception as e:
        print('fail')

hb + nginx_rtmp模块 + hls.js


<!DOCTYPE html>
<html>
	<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
	<title>Video Example</title>
	<script type="text/javascript">
var pusher = null;
// H5 plus事件处理
function plusReady(){
	// 创建直播推流控件
	pusher = new plus.video.LivePusher('pusher',{
		url:'rtmp://xxxx:1935/src/xxxx'
	});
	// 监听状态变化事件
	pusher.addEventListener('statechange', function(e){
		console.log('statechange: '+JSON.stringify(e));
	}, false);
}
document.addEventListener('plusready', plusReady, false);
// 开始推流
function startPusher() {
	pusher.start();
}
	</script>
	</head>
	<body style="margin:0;padding:0;text-align:center;">
		直播推流控件
		<br/><br/>
		<button onclick="startPusher()">开始</button>
		<br/><br/>
		<div id="pusher" style="width:100%;height:300px;background-color:#000000;margin:auto"></div>
	</body>
</html>

hb

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
		<video id="video"></video>
		<script>
		  var video = document.getElementById('video');
		  if(Hls.isSupported()) {
		    var hls = new Hls();
		    hls.loadSource('http://xxxx/360p/xxxx.m3u8');
		    hls.attachMedia(video);
		    hls.on(Hls.Events.MANIFEST_PARSED,function() {
		      video.play();
		  });
		 }
		  else if (video.canPlayType('application/vnd.apple.mpegurl')) {
		    video.src = 'http://xxxx/360p/xxxx.m3u8';
		    video.addEventListener('loadedmetadata',function() {
		      video.play();
		    });
		  }
		</script>

	</body>
	
</html>

html

nginx

server{
        listen 8887;
        server_name xxx.xxx.xxx;
        root /web/myMp4;
        location /{
                add_header Access-Control-Allow-Origin *;
                add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
                add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
        }

}
rtmp {

    server {

        listen 1935;  #监听的端口

        chunk_size 4000;

application src {
    live on;
    #exec_push ffmpeg -i rtmp://xxxxxxx:1935/src/$name -f flv rtmp://localhost/hls/$name 2>>/web/myMp4/ffmpeg-$name.log;
    #exec ffmpeg -re -i rtmp://localhost:1935/src/$name -vcodec flv -acodec copy -s 640x320 -f flv rtmp://localhost:1935/360p/$name 2>>/web/myMp4/ffmpeg-$name.log;
    exec ffmpeg -i rtmp://localhost:1935/src/$name -c:a copy -c:v libx264  -s 360x360 -f flv rtmp://localhost:1935/360p/$name 2>>/web/myMp4/ffmpeg-$name.log;
    hls on;
    hls_path /web/myMp4/allP;
    hls_fragment 5s;
}

application 360p {
    live on;
    hls on;
    hls_path /web/myMp4/360p;
    hls_fragment 5s;
}
    }
}

shadowsocks

pip install shadowsocks
sudo vim /etc/shadowsocks.json
//这里的json文件是自己创建的,不是系统自带

配置文件的内容大致如下:

{
    "server":"服务器的ip",
    "server_port":19175,
    "local_address":"127.0.0.1",
    "local_port":1080,
    "password":"密码",
    "timeout":300,
    "method":"aes-256-cfb",
    "fast_open":false
}

sssever -c shadowsocks.json

mongodb 东西整合

创建数据库

db.createDatabase("huxierong")

use huxierong

创建集合

db.createCollection("user")

添加

db.user.insert( {"title":"胡谢荣",age:"23",sex:"boy"} )

修改字符串类型

db.user.find().forEach(function(e){

     e.age = NumberInt(e.age);

     db.user.save(e)

})

修改

db.user.update({"title":"胡谢荣"},{$set:{"age":50}})

分页

db.user.find().skip(0).limit(15)

创建索引 (唯一索引)

db.user.createIndex({title:1},{unique:true})

聚合

group

db.user.aggregate( { $group: {_id:"$type",title:{$addToSet:"$title"} , age:{$sum:"$age"}  }  } )

管道

db.user.aggregate(

{

     $match:{age:{$gt:20}}

}

{

    $project:{_id:0,title:1}

}

)



db.user.aggregate(

{

     $match:{age:{$gt:20}}

}

{

    $group:{_id:null,age:{$sum:"$age"}}

}

)

lanp shell脚本下载安装

    #!bin/bash
    #
    
    #php 安装
    echo "php安装路径:"
    read php_name
    echo "php安装路径为:$php_name"
    echo `wget http://cn2.php.net/get/php-7.3.2.tar.bz2/from/this/mirror`
    echo `mv mirror php.tar.bz2`
    echo `tar -xvf php.tar.bz2`
    rm php.tar.bz2
    cd php-7.3.2
    pwd
    echo `./configure --prefix=/soft/php --with-openssl --with-config-file-path=/soft/php --enable-mbstring --enable-ftp --with-gd --with-jpeg-dir=/usr --with-png-dir=/usr --with-mysql=mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-pear --enable-sockets --with-freetype-dir=/usr --with-libxml-dir=/usr --with-xmlrpc --enable-fpm --enable-xml --enable-sockets --with-gd --with-iconv --with-freetype-dir=/usr/lib/ --enable-soap --enable-pcntl --enable-cli --with-curl
`
    echo `make && make install`
    echo `cp php.ini-production $php_name/php.ini`
    cd $php_name/etc
    mv php-fpm.conf.default php-fpm.conf
    cd $php_name/etc/php-fpm.d
    mv www.conf.default www.conf
    
    
    #mysql 下载
    echo "mysql安装路径:"
    read mysql_name
    echo "mysql安装路径:$mysql_name"
    echo `wget https://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-8.0.15-linux-glibc2.12-x86_64.tar.xz`
    mv mysql-8.0.15-linux-glibc2.12-x86_64.tar.xz $mysql_name/mysql.tar.xz
    cd $mysql_name
    echo `tar -xvf mysql.tar.xz`
    rm mysql.tar.xz
    mv mysql-8.0.15-linux-glibc2.12-x86_64/ mysql/
    echo `chown -R mysql:mysql mysql/`
    cd mysql/
    mkdir data
    
    cat>mysql.sock<<EOF
    EOF
    
    echo `chown -R mysql:mysql mysql.sock`
    
    cat>my.cnf<<EOF
    [mysqld]
    port=3406
    basedir=$mysql_name/mysql
    datadir=$mysql_name/mysql/data
    socket=$mysql_name/mysql/mysql.sock
    EOF
    groupadd mysql
	useradd -r -g mysql mysql
	chown -R mysql:mysql $mysql_name/
    
    cd bin
    echo `./mysqld --defaults-file=$mysql_name/mysql/my.cnf --initialize --user=mysql`
    echo `./mysqld_safe --user=mysql &`
    #nginx 安装
    echo "nginx安装路径:"
    read nginx_name
    echo "nginx安装路径为:$nginx_name"
    
    echo `wget http://nginx.org/download/nginx-1.14.2.tar.gz`
    echo `tar -xvf nginx-1.14.2.tar.gz`
    rm nginx-1.14.2.tar.gz
    cd nginx-1.14.2
    echo `./configure --prefix=$nginx_name --with-http_ssl_module`
    echo `make && make install`
    sed -i "s/\/scripts\$fastcgi_script_name/\$document_root\$fastcgi_script_name/g" $nginx_name/conf/nginx.conf