text:
<?php
/**
 * Created by PhpStorm.
 * User : xin.zhang
 * Date : 15/4/29
 * Time : 下午2:05
 * Email: zhangxinmailvip@foxmail.com
 */

namespace app\modules\v1\models;

use app\components\Page;
use common\components\Code;
use app\modules\v1\entity\TravelTrip;
use app\modules\v1\entity\TravelTripApply;
use app\modules\v1\entity\TravelTripDetail;
use app\modules\v1\entity\TravelTripHighlight;
use app\modules\v1\entity\TravelTripPicture;
use app\modules\v1\entity\TravelTripPrice;
use app\modules\v1\entity\TravelTripPublisher;
use app\modules\v1\entity\TravelTripScenic;
use app\modules\v1\entity\TravelTripService;
use common\models\ProxyDb;
use yii\db\mssql\PDO;

class TravelTripDb extends ProxyDb
{

    public function getTripSelectInfo()
    {
        $selectInfo="t.tripId,t.createPublisherId,t.createTime,t.title,t.titleImg,t.countryId,t.cityId,t.lon,t.lat,
        ceil(t.basePrice*".Code::TRIP_SERVICE_PRICE.") AS basePrice,t.basePrice as oldPrice,
        t.basePriceType,t.maxUserCount,t.score,t.tripCount,t.startTime,t.endTime,t.travelTime,t.travelTimeType,t.intro,t.info,t.tags,
        t.commentCount,t.collectCount,t.isHot,t.type,t.status";

        return $selectInfo;
    }

    /**
     * 获取推荐随游
     * @param $page
     * @param $countryId
     * @param $cityId
     * @return Page|null
     */
    public function getRelateRecommendTrip($page, $countryId, $cityId)
    {
        $sql = sprintf("
            FROM travel_trip
            WHERE 1=1
        ");
        $sql .= " AND status=:status";
        $this->setParam("status", TravelTrip::TRAVEL_TRIP_STATUS_NORMAL);
        if (!empty($countryId) && !empty($cityId)) {
            $sql .= " AND (countryId =:countryId or cityId=:cityId) ";
            $this->setParam("cityId", $cityId);
            $this->setParam("countryId", $countryId);
        } else if (!empty($countryId)) {

            $sql .= " AND countryId =:countryId";
            $this->setParam("countryId", $countryId);
        } else if (!empty($cityId)) {
            $sql .= " AND cityId =:cityId";
            $this->setParam("cityId", $cityId);
        }
        $this->setSelectInfo("tripId,title,titleImg,countryId,cityId,ceil(basePrice*".Code::TRIP_SERVICE_PRICE.") AS basePrice,
        basePriceType,score,tripCount,commentCount,collectCount,isHot,type,status ");
        $this->setSql($sql);
        return $this->find($page);

    }

    /**
     * 获取随游列表
     * @param $page
     * @param $title
     * @param $countryId
     * @param $cityId
     * @param $peopleCount
     * @param $startPrice
     * @param $endPrice
     * @param $tag
     * @param $isHot
     * @param $status
     * @param $typeArray
     * @return Page|null
     */
    public function getList($page, $title, $countryId, $cityId, $peopleCount, $startPrice, $endPrice, $tag, $isHot,$typeArray, $status)
    {

        $sql = sprintf("
            FROM travel_trip AS t
            LEFT JOIN user_publisher AS uo ON uo.userPublisherId=t.createPublisherId
            LEFT JOIN user_base AS u ON uo.userId=u.userSign
            LEFT JOIN country AS c ON c.id=t.countryId
            LEFT JOIN city AS ci ON ci.id=t.cityId
            WHERE 1=1
        ");
        $sql .= " AND t.status=:status";
        $this->setParam("status", $status);

        if (!empty($countryId) || !empty($cityId)) {
            if (!empty($countryId)) {
                $sql .= " AND t.countryId in(".$countryId.")";
            }
            if (!empty($cityId)) {
                $sql .= " AND t.cityId in(".$cityId.")";
            }
        } else {
            if (!empty($title)) {
                $sql .= " AND t.title like :title ";
                $this->setParam("title", "%" . $title . "%");
            }
        }
        if (!empty($peopleCount) && $peopleCount != 0) {
            $sql .= " AND t.maxUserCount>=:peopleCount ";
            $this->setParam("peopleCount", $peopleCount);
        }
        if (!empty($isHot) ) {
            $sql .= " AND t.isHot=:isHot ";
            $this->setParam("isHot", $isHot);
        }
        if (!empty($startPrice)) {
            $sql .= " AND t.basePrice>=:startPrice ";
            $this->setParam("startPrice", $startPrice);
        }
        if (!empty($endPrice)) {
            $sql .= " AND t.basePrice<=:endPrice ";
            $this->setParam("endPrice", $endPrice);
        }
        if (!empty($tag)) {
            $sql .= " AND t.tripId IN (";
            $sql .= $tag;
            $sql .= ")";
        }
        if(!empty($typeArray&&count($typeArray)>0)){
            $sql .= " AND t.type IN (";
            $sql .= implode(",",$typeArray);
            $sql .= ")";
        }
        $this->setSql($sql);
        $this->setSelectInfo("t.tripId,t.title,t.titleImg,t.countryId,t.cityId,ceil(t.basePrice*".Code::TRIP_SERVICE_PRICE.") AS basePrice,
        t.basePriceType,t.score,t.tripCount,t.commentCount,t.collectCount,t.isHot,t.type,t.status,
        u.nickname,u.headImg,c.cname,c.ename,ci.cname,ci.ename,u.userSign ");
        return $this->find($page);
    }

    /**
     * 全文检索根据列表
     * @param $page
     * @param $tripIds
     * @return \backend\components\Page|null
     */
    public function getListBySearch($page, $tripIds)
    {

        $sql = sprintf("
            FROM travel_trip AS t
            LEFT JOIN user_publisher AS uo ON uo.userPublisherId=t.createPublisherId
            LEFT JOIN user_base AS u ON uo.userId=u.userSign
            LEFT JOIN country AS c ON c.id=t.countryId
            LEFT JOIN city AS ci ON ci.id=t.cityId
            WHERE 1=1
        ");

        if(!empty($tripIds)){
            $sql .= " AND t.tripId in (" . $tripIds . ")";
        }

        $this->setSql($sql);
        $this->setSelectInfo(" t.tripId,t.title,t.titleImg,t.countryId,t.cityId,ceil(t.basePrice*".Code::TRIP_SERVICE_PRICE.") AS basePrice,
        t.basePriceType,t.score,t.tripCount,t.commentCount,t.collectCount,t.isHot,t.type,t.status,
        u.nickname,u.headImg,c.cname,c.ename,ci.cname,ci.ename ");

        return $this->find($page);
    }

    /**
     * 添加随游
     * @param TravelTrip $travelTrip
     * @throws \yii\db\Exception
     */
    public function addTravelTrip(TravelTrip $travelTrip)
    {
        $sql = sprintf("
            INSERT INTO travel_trip
            (
              createPublisherId,createTime,title,titleImg,countryId,cityId,lon,lat,basePrice,basePriceType,maxUserCount,
              isAirplane,isHotel,score,tripCount,startTime,endTime,travelTime,travelTimeType,intro,info,tags,status
            )
            VALUES
            (
              :createPublisherId,now(),:title,:titleImg,:countryId,:cityId,:lon,:lat,:basePrice,:basePriceType,:maxUserCount,
              :isAirplane,:isHotel,:score,0,:startTime,:endTime,:travelTime,:travelTimeType,:intro,:info,:tags,:status
            )
        ");

        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":createPublisherId", $travelTrip->createPublisherId, PDO::PARAM_INT);
        $command->bindParam(":title", $travelTrip->title, PDO::PARAM_STR);
        $command->bindParam(":titleImg", $travelTrip->titleImg, PDO::PARAM_STR);
        $command->bindParam(":countryId", $travelTrip->countryId, PDO::PARAM_INT);
        $command->bindParam(":cityId", $travelTrip->cityId, PDO::PARAM_INT);
        $command->bindParam(":lon", $travelTrip->lon, PDO::PARAM_STR);
        $command->bindParam(":lat", $travelTrip->lat, PDO::PARAM_STR);
        $command->bindParam(":basePrice", $travelTrip->basePrice, PDO::PARAM_STR);
        $command->bindParam(":basePriceType", $travelTrip->basePriceType, PDO::PARAM_INT);
        $command->bindParam(":maxUserCount", $travelTrip->maxUserCount, PDO::PARAM_INT);
        $command->bindParam(":isAirplane", $travelTrip->isAirplane, PDO::PARAM_INT);
        $command->bindParam(":isHotel", $travelTrip->isHotel, PDO::PARAM_INT);
        $command->bindParam(":score", $travelTrip->score, PDO::PARAM_STR);
        $command->bindParam(":startTime", $travelTrip->startTime, PDO::PARAM_STR);
        $command->bindParam(":endTime", $travelTrip->endTime, PDO::PARAM_STR);
        $command->bindParam(":travelTime", $travelTrip->travelTime, PDO::PARAM_STR);
        $command->bindParam(":travelTimeType", $travelTrip->travelTimeType, PDO::PARAM_INT);
        $command->bindParam(":intro", $travelTrip->intro, PDO::PARAM_STR);
        $command->bindParam(":info", $travelTrip->info, PDO::PARAM_STR);
        $command->bindParam(":tags", $travelTrip->tags, PDO::PARAM_STR);
        $command->bindParam(":status", $travelTrip->status, PDO::PARAM_INT);

        $command->execute();
    }

    /**
     * 修改随游
     * @param TravelTrip $travelTrip
     * @throws \yii\db\Exception
     */
    public function updateTravelTrip(TravelTrip $travelTrip)
    {
        $sql = sprintf("
            UPDATE travel_trip SET
            title=:title,titleImg=:titleImg,countryId=:countryId,cityId=:cityId,lon=:lon,lat=:lat,basePrice=:basePrice,
            basePriceType=:basePriceType,maxUserCount=:maxUserCount,isAirplane=:isAirplane,isHotel=:isHotel,score=:score,
            tripCount=:tripCount,startTime=:startTime,endTime=:endTime,travelTime=:travelTime,travelTimeType=:travelTimeType,
            intro=:intro,info=:info,tags=:tags,status=:status
            WHERE tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":title", $travelTrip->title, PDO::PARAM_STR);
        $command->bindParam(":titleImg", $travelTrip->titleImg, PDO::PARAM_STR);
        $command->bindParam(":countryId", $travelTrip->countryId, PDO::PARAM_INT);
        $command->bindParam(":cityId", $travelTrip->cityId, PDO::PARAM_INT);
        $command->bindParam(":lon", $travelTrip->lon, PDO::PARAM_STR);
        $command->bindParam(":lat", $travelTrip->lat, PDO::PARAM_STR);
        $command->bindParam(":basePrice", $travelTrip->basePrice, PDO::PARAM_STR);
        $command->bindParam(":basePriceType", $travelTrip->basePriceType, PDO::PARAM_INT);
        $command->bindParam(":maxUserCount", $travelTrip->maxUserCount, PDO::PARAM_INT);
        $command->bindParam(":isAirplane", $travelTrip->isAirplane, PDO::PARAM_INT);
        $command->bindParam(":isHotel", $travelTrip->isHotel, PDO::PARAM_INT);
        $command->bindParam(":score", $travelTrip->score, PDO::PARAM_STR);
        $command->bindParam(":tripCount", $travelTrip->tripCount, PDO::PARAM_INT);
        $command->bindParam(":startTime", $travelTrip->startTime, PDO::PARAM_STR);
        $command->bindParam(":endTime", $travelTrip->endTime, PDO::PARAM_STR);
        $command->bindParam(":travelTime", $travelTrip->travelTime, PDO::PARAM_STR);
        $command->bindParam(":travelTimeType", $travelTrip->travelTimeType, PDO::PARAM_INT);
        $command->bindParam(":intro", $travelTrip->intro, PDO::PARAM_STR);
        $command->bindParam(":info", $travelTrip->info, PDO::PARAM_STR);
        $command->bindParam(":tags", $travelTrip->tags, PDO::PARAM_STR);
        $command->bindParam(":status", $travelTrip->status, PDO::PARAM_INT);

        $command->bindParam(":tripId", $travelTrip->tripId, PDO::PARAM_INT);

        $command->execute();
    }

    /**
     * 改变随游状态
     * @param $tripId
     * @param $status
     * @throws \yii\db\Exception
     */
    public function changeTravelStatus($tripId, $status)
    {
        $sql = sprintf("
            UPDATE  travel_trip SET
            status=:status
            WHERE tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":status", $status, PDO::PARAM_INT);
        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->execute();
    }

    /**
     * 查看随游详情
     * @param $tripId
     * @return array|bool
     */
    public function findTravelTripById($tripId)
    {
        $sql = sprintf("
            SELECT %s,c.cname AS countryCname,c.ename AS countryEname,ci.cname AS cityCname,ci.ename AS cityEname FROM travel_trip AS t
            LEFT JOIN country AS c ON c.id=t.countryId
            LEFT JOIN city AS ci ON ci.id=t.cityId
            WHERE tripId=:tripId
        ",self::getTripSelectInfo());
        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);

        return $command->queryOne();
    }

    /**
     * 添加随游照片
     * @param TravelTripPicture $travelTripPicture
     * @throws \yii\db\Exception
     */
    public function addTravelTripPicture(TravelTripPicture $travelTripPicture)
    {
        $sql = sprintf("
            INSERT INTO travel_trip_picture
            (
              tripId,title,url
            )
            VALUES
            (
              :tripId,:title,:url
            )
        ");
        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $travelTripPicture->tripId, PDO::PARAM_INT);
        $command->bindParam(":title", $travelTripPicture->title, PDO::PARAM_STR);
        $command->bindParam(":url", $travelTripPicture->url, PDO::PARAM_STR);

        $command->execute();
    }

    /**
     * 根据随游批量删除照片
     * @param $tripId
     * @throws \yii\db\Exception
     */
    public function deleteTravelTripPicByTripId($tripId)
    {
        $sql = sprintf("
            DELETE FROM travel_trip_picture
            WHERE tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->execute();
    }

    /**
     * 查找随游照片
     * @param $tripId
     * @return array
     */
    public function getTravelTripPicList($tripId)
    {
        $sql = sprintf("
            SELECT picId,tripId,title,url FROM travel_trip_picture
            WHERE tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId);
        return $command->queryAll();
    }

    /**
     * 添加随游阶梯价格
     * @param TravelTripPrice $travelTripPrice
     * @throws \yii\db\Exception
     */
    public function addTravelTripPrice(TravelTripPrice $travelTripPrice)
    {
        $sql = sprintf("
            INSERT INTO travel_trip_price
            (
              tripId,minCount,maxCount,price
            )
            VALUES
            (
              :tripId,:minCount,:maxCount,:price
            )
        ");
        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $travelTripPrice->tripId, PDO::PARAM_INT);
        $command->bindParam(":minCount", $travelTripPrice->minCount, PDO::PARAM_INT);
        $command->bindParam(":maxCount", $travelTripPrice->maxCount, PDO::PARAM_INT);
        $command->bindParam(":price", $travelTripPrice->price, PDO::PARAM_STR);

        $command->execute();
    }

    /**
     * 根据随游批量删除阶梯价格
     * @param $tripId
     * @throws \yii\db\Exception
     */
    public function deleteTravelTripPriceByTripId($tripId)
    {
        $sql = sprintf("
            DELETE FROM travel_trip_price
            WHERE tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->execute();
    }

    /**
     * 查找随游阶梯价格
     * @param $tripId
     * @return array
     */
    public function getTravelTripPriceList($tripId)
    {
        $sql = sprintf("
            SELECT priceId,tripId,minCount,maxCount,ceil(price * ".Code::TRIP_SERVICE_PRICE.") AS price,price As oldPrice FROM travel_trip_price
            WHERE tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        return $command->queryAll();
    }

    /**
     * 添加随游中的随友关联
     * @param TravelTripPublisher $travelTripPublisher
     * @throws \yii\db\Exception
     */
    public function addTravelTripPublisher(TravelTripPublisher $travelTripPublisher)
    {
        $sql = sprintf("
            INSERT INTO travel_trip_publisher
            (
              tripId,publisherId
            )
            VALUES
            (
              :tripId,:publisherId
            )
        ");
        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $travelTripPublisher->tripId, PDO::PARAM_INT);
        $command->bindParam(":publisherId", $travelTripPublisher->publisherId, PDO::PARAM_INT);

        $command->execute();
    }

    /**
     * 根据随游批量删除随友关联
     * @param $tripId
     * @throws \yii\db\Exception
     */
    public function deleteTravelTripPublisherByTripId($tripId)
    {
        $sql = sprintf("
            DELETE FROM travel_trip_publisher
            WHERE tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->execute();
    }

    /**
     * 批量删除随游特殊亮点
     * @param $tripId
     * @throws \yii\db\Exception
     */
    public function deleteTravelTripSpecialByTripId($tripId)
    {
        $sql = sprintf("
            DELETE FROM travel_trip_special
            WHERE tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->execute();
    }

    /**
     * 获取随游特殊亮点列表
     * @param $tripId
     * @return array
     */
    public function getTravelTripSpecialList($tripId)
    {
        $sql = sprintf("
            SELECT specialId,tripId,title,info,picUrl FROM travel_trip_special
            WHERE tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        return $command->queryAll();
    }

    /**
     * 查找随游随友列表
     * @param $tripId
     * @return array
     */
    public function getTravelTripPublisherList($tripId)
    {
        $sql = sprintf("
            SELECT  ub.nickname,ub.phone,ub.areaCode,ub.email,ub.sex,ub.birthday,ub.headImg,ub.hobby,ub.countryId,ub.cityId,
            ub.profession,ub.school,ub.intro,ub.info,ub.travelCount,ub.userSign,t.tripPublisherId,t.tripId,t.publisherId,cit.cname as cityName,cty.cname as countryName
            FROM travel_trip_publisher t
            LEFT JOIN user_publisher up ON up.userPublisherId=t.publisherId
            LEFT JOIN user_base ub ON ub.userSign=up.userId
			LEFT JOIN city cit ON cit.id=ub.cityId
			LEFT JOIN country cty ON cty.id=ub.countryId
            WHERE t.tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        return $command->queryAll();
    }

    /**
     * 添加随游中景区
     * @param TravelTripScenic $travelTripScenic
     * @throws \yii\db\Exception
     */
    public function addTravelTripScenic(TravelTripScenic $travelTripScenic)
    {
        $sql = sprintf("
            INSERT INTO travel_trip_scenic
            (
              tripId,name,lon,lat
            )
            VALUES
            (
              :tripId,:name,:lon,:lat
            )
        ");
        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $travelTripScenic->tripId, PDO::PARAM_INT);
        $command->bindParam(":name", $travelTripScenic->name, PDO::PARAM_STR);
        $command->bindParam(":lon", $travelTripScenic->lon, PDO::PARAM_STR);
        $command->bindParam(":lat", $travelTripScenic->lat, PDO::PARAM_STR);

        $command->execute();
    }

    /**
     * 根据随游批量删除景区
     * @param $tripId
     * @throws \yii\db\Exception
     */
    public function deleteTravelTripScenicByTripId($tripId)
    {
        $sql = sprintf("
            DELETE FROM travel_trip_scenic
            WHERE tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->execute();
    }

    /**
     * 查找随游景区列表
     * @param $tripId
     * @return array
     */
    public function getTravelTripScenicList($tripId)
    {
        $sql = sprintf("
            SELECT scenicId,tripId,name,lon,lat FROM travel_trip_scenic
            WHERE tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        return $command->queryAll();
    }

    /**
     * 添加随游中的专项服务
     * @param TravelTripService $travelTripService
     * @throws \yii\db\Exception
     */
    public function addTravelTripService(TravelTripService $travelTripService)
    {
        $sql = sprintf("
            INSERT INTO travel_trip_service
            (
              tripId,title,money,type
            )
            VALUES
            (
              :tripId,:title,:money,:type
            )
        ");
        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $travelTripService->tripId, PDO::PARAM_INT);
        $command->bindParam(":title", $travelTripService->title, PDO::PARAM_STR);
        $command->bindParam(":money", $travelTripService->money, PDO::PARAM_STR);
        $command->bindParam(":type", $travelTripService->type, PDO::PARAM_INT);

        $command->execute();
    }

    /**
     * 根据随游批量删除专项服务
     * @param $tripId
     * @throws \yii\db\Exception
     */
    public function deleteTravelTripServiceByTripId($tripId)
    {
        $sql = sprintf("
            DELETE FROM travel_trip_service
            WHERE tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->execute();
    }

    /**
     * 查找随游专项服务列表
     * @param $tripId
     * @return array
     */
    public function getTravelTripServiceList($tripId)
    {
        $sql = sprintf("
            SELECT serviceId,tripId,title,money as oldMoney,ceil(money*".Code::TRIP_SERVICE_PRICE.") as money,type FROM travel_trip_service
            WHERE tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        return $command->queryAll();
    }

    /**
     * 添加随游申请
     * @param TravelTripApply $travelTripApply
     * @throws \yii\db\Exception
     */
    public function addTravelTripApply(TravelTripApply $travelTripApply)
    {
        $sql = sprintf("
            INSERT INTO travel_trip_apply
            (
              tripId,publisherId,sendTime,info,status
            )
            VALUES
            (
              :tripId,:publisherId,now(),:info,:status
            )
        ");
        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $travelTripApply->tripId, PDO::PARAM_INT);
        $command->bindParam(":publisherId", $travelTripApply->publisherId, PDO::PARAM_INT);
        $command->bindParam(":info", $travelTripApply->info, PDO::PARAM_STR);
        $command->bindParam(":status", $travelTripApply->status, PDO::PARAM_INT);

        $command->execute();

    }

    /**
     * 获取申请详情
     * @param $applyId
     * @return array|bool
     */
    public function findTravelTripApplyById($applyId)
    {
        $sql = sprintf("
            SELECT applyId,tripId,publisherId,sendTime,info,status FROM travel_trip_apply
            WHERE applyId=:applyId
        ");
        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":applyId", $applyId, PDO::PARAM_INT);
        return $command->queryOne();
    }

    /**
     * 改变申请加入随游状态
     * @param $applyId
     * @param $status
     * @throws \yii\db\Exception
     */
    public function changeTravelTripApplyStatus($applyId, $status)
    {
        $sql = sprintf("
            UPDATE travel_trip_apply SET
            status=:status
            WHERE applyId=:applyId
        ");

        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":applyId", $applyId, PDO::PARAM_INT);
        $command->bindParam(":status", $status, PDO::PARAM_INT);

        $command->execute();
    }

    /**
     * 获取随游申请列表(根据状态)
     * @param $tripId
     * @param $status
     */
    public function getTelTripApplyList($tripId, $status)
    {
        $sql = sprintf("
            FROM travel_trip_apply
            WHERE tripId=:tripId
        ");

        $this->setParam("tripId", $tripId);
        if (!empty($tripId)) {
            $this->setParam("status", $status);
            $sql .= " AND status=:status";
        }
        $this->setSelectInfo("applyId,tripId,publisherId,sendTime,info,status");
        $this->setSql($sql);
        $this->findListBySql();
    }

    /**
     * 删除随友关联
     * @param TravelTripPublisher $travelTripPublisher
     * @throws \yii\db\Exception
     */
    public function deleteTravelTripPublisher(TravelTripPublisher $travelTripPublisher)
    {
        $sql = sprintf("
            DELETE FROM travel_trip_publisher
            WHERE tripId=:tripId AND tripPublisherId=:tripPublisherId
        ");

        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $travelTripPublisher->tripId, PDO::PARAM_INT);
        $command->bindParam(":tripPublisherId", $travelTripPublisher->tripPublisherId, PDO::PARAM_INT);

        $command->execute();
    }

    /**
     * 获取我的随游列表
     * @param $createPublisherId
     * @return array
     */
    public function getMyTripList($createPublisherId)
    {
        $sql = sprintf("
            FROM travel_trip AS t
            LEFT JOIN user_publisher AS uo ON uo.userPublisherId=t.createPublisherId
            LEFT JOIN user_base AS u ON uo.userId=u.userSign
            LEFT JOIN
            (
                SELECT tta.tripId,COUNT(*) AS count FROM travel_trip_apply tta WHERE tta.status=:status GROUP BY tta.tripId
            ) AS apply
            ON apply.tripId=t.tripId
            LEFT JOIN
            (
                SELECT tts.tripId,GROUP_CONCAT(tts.title) as names FROM travel_trip_service tts GROUP BY tts.tripId
            )
            AS service
            ON service.tripId=t.tripId
            WHERE t.createPublisherId=:createPublisherId AND t.status!=:tripStatus
            ORDER BY t.status ASC
        ");
        $this->setParam("createPublisherId", $createPublisherId);
        $this->setParam("status", TravelTripApply::TRAVEL_TRIP_APPLY_STATUS_WAIT);
        $this->setParam("tripStatus", TravelTrip::TRAVEL_TRIP_STATUS_DELETE);

        $this->setSql($sql);
        $this->setSelectInfo(self::getTripSelectInfo().",u.nickname,u.headImg,apply.count,service.names,u.userSign");

        return $this->findListBySql();
    }

    /**
     * 获取某个随友加入的随游
     * @param $publisherId
     * @return array
     */
    public function getMyJoinTripList($publisherId)
    {
        $sql = sprintf("
            FROM travel_trip AS t
            LEFT JOIN user_publisher AS uo ON uo.userPublisherId=t.createPublisherId
            LEFT JOIN user_base AS u ON uo.userId=u.userSign
            LEFT JOIN
            (
                SELECT tta.tripId,COUNT(*) AS count FROM travel_trip_apply tta WHERE tta.status=:status GROUP BY tta.tripId
            ) AS apply
            ON apply.tripId=t.tripId
            LEFT JOIN
            (
                SELECT tts.tripId,GROUP_CONCAT(tts.title) as names FROM travel_trip_service tts GROUP BY tts.tripId
            )
            AS service
            ON service.tripId=t.tripId
            WHERE t.tripId in
			(
				SELECT tripId  FROM travel_trip_publisher
				WHERE publisherId =:publisherId
			)
			AND t.createPublisherId!=:publisherId  AND t.status=:tripStatus
        ");
        $this->setParam("publisherId", $publisherId);
        $this->setParam("status", TravelTripApply::TRAVEL_TRIP_APPLY_STATUS_WAIT);
        $this->setParam("tripStatus", TravelTrip::TRAVEL_TRIP_STATUS_NORMAL);

        $this->setSql($sql);
        $this->setSelectInfo(self::getTripSelectInfo().",u.nickname,u.headImg,apply.count,service.names");

        return $this->findListBySql();
    }

    /**
     * 获取随友申请加入列表
     * @param $tripId
     * @return array
     */
    public function getPublisherApplyList($tripId)
    {
        $sql = sprintf("
            SELECT  up.userId,up.countryId,up.cityId,up.lon,up.lat,up.idCard,up.idCardImg,up.kind,up.tripCount,up.leadCount,up.registerTime,up.lastUpdateTime,up.score,tta.applyId,tta.tripId,tta.publisherId,tta.sendTime,tta.info,tta.status,ub.nickname,ub.phone,ub.areaCode,ub.email,ub.sex,ub.birthday,ub.headImg,ub.hobby,ub.userSign,
            ub.profession,ub.school,ub.intro,ub.cityId,ub.countryId,ub.travelCount
            FROM user_publisher up
            LEFT JOIN user_base ub ON ub.userSign=up.userId
            LEFT JOIN travel_trip_apply tta ON tta.publisherId=up.userPublisherId
            WHERE tta.tripId=:tripId AND tta.status=:status
        ");

        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->bindValue(":status", TravelTripApply::TRAVEL_TRIP_APPLY_STATUS_WAIT, PDO::PARAM_INT);

        return $command->queryAll();
    }

    /**
     * 添加随游被参与次数
     * @param $tripId
     * @throws \yii\db\Exception
     */
    public function addTravelTripCount($tripId)
    {
        $sql = sprintf("
            UPDATE travel_trip SET
            tripCount=tripCount+1
            WHERE tripId=:tripId
        ");

        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);

        $command->execute();
    }

    /**
     * 添加评论次数
     * @param $tripId
     * @throws \yii\db\Exception
     */
    public function addCommentCount($tripId)
    {
        $sql = sprintf("
            UPDATE travel_trip SET
            commentCount=commentCount+1
            WHERE tripId=:tripId
        ");

        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->execute();
    }

    /**
     * 添加收藏次数
     * @param $tripId
     * @throws \yii\db\Exception
     */
    public function addCollectCount($tripId)
    {
        $sql = sprintf("
            UPDATE travel_trip SET
            collectCount=collectCount+1
            WHERE tripId=:tripId
        ");

        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->execute();
    }

    /**
     * 减少收藏次数
     * @param $tripId
     * @throws \yii\db\Exception
     */
    public function removeCollectCount($tripId)
    {

        $sql = sprintf("
            UPDATE travel_trip SET
            collectCount=collectCount-1
            WHERE tripId=:tripId
        ");

        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->execute();

    }

    /**
     * 获取是否有申请正在等待审核
     * @param $tripId
     * @param $publisherId
     * @return array|bool
     */
    public function findTravelTripApplyByTripIdAndUser($tripId, $publisherId)
    {
        $sql = sprintf("
            SELECT applyId,tripId,publisherId,sendTime,info,status FROM travel_trip_apply
            WHERE tripId=:tripId AND publisherId=:publisherId AND status=:status
        ");

        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->bindParam(":publisherId", $publisherId, PDO::PARAM_INT);
        $command->bindValue(":status", TravelTripApply::TRAVEL_TRIP_APPLY_STATUS_WAIT, PDO::PARAM_INT);

        return $command->queryOne();
    }

    /**
     * 更新随游封面图
     * @param $tripId
     * @param $titleImg
     * @throws \yii\db\Exception
     */
    public function updateTravelTripTitleImg($tripId, $titleImg)
    {
        $sql = sprintf("
            UPDATE travel_trip SET titleImg=:titleImg
            WHERE tripId=:tripId
        ");

        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->bindParam(":titleImg", $titleImg, PDO::PARAM_STR);

        $command->execute();
    }

    /**后台得到随游列表
     * @param $page
     * @param $search
     * @param $peopleCount
     * @param $startPrice
     * @param $endPrice
     * @param $status
     * @return Page|null
     */
    public function sysGetList($page, $search, $peopleCount, $startPrice, $endPrice, $status)
    {

        $sql = sprintf("
            FROM travel_trip AS t
            LEFT JOIN user_publisher AS uo ON uo.userPublisherId=t.createPublisherId
            LEFT JOIN user_base AS u ON uo.userId=u.userSign
            LEFT JOIN country AS c ON c.id=t.countryId
            LEFT JOIN city AS ci ON ci.id=t.cityId
            WHERE 1=1
        ");
        if (!empty($status)) {
            $sql .= " AND t.status=:status";
            $this->setParam("status", $status);
        }
        if (!empty($search)) {
            $sql .= " AND ( t.title like :search OR c.cname like :search OR ci.cname like :search OR u.nickname like :search ) ";
            $this->setParam("search", "%" . $search . "%");
        }
        if (!empty($peopleCount) && $peopleCount != 0) {
            $sql .= " AND t.maxUserCount>=:peopleCount ";
            $this->setParam("peopleCount", $peopleCount);
        }
        if (!empty($startPrice)) {
            $sql .= " AND t.basePrice>=:startPrice ";
            $this->setParam("startPrice", $startPrice);
        }
        if (!empty($endPrice)) {
            $sql .= " AND t.basePrice<=:endPrice ";
            $this->setParam("endPrice", $endPrice);
        }
        $this->setSql($sql);
        $this->setSelectInfo(self::getTripSelectInfo().",u.nickname,u.headImg,c.cname,c.ename,ci.cname as ctName,ci.ename as cteName ");

        return $this->find($page);
    }

    /**
     * 获取随游评论
     * @param $page
     * @param $search
     * @return Page|null
     */
    public function getComment($page, $search)
    {
        $sql = sprintf("
            FROM travel_trip_comment a
            LEFT JOIN travel_trip b ON a.tripId=b.tripId
            LEFT JOIN user_base c ON a.userSign = c.userSign
            WHERE 1=1
        ");
        if (!empty($search)) {
            $sql .= " AND ( b.title like :search OR c.nickname like :search OR a.content like :search ) ";
            $this->setParam("search", "%" . $search . "%");
        }
        $this->setSql($sql);
        $this->setSelectInfo("userSign,content,rTitle,replayCommentId,supportCount,opposeCount,cTime,tripId,isTravel,rUserSign,b.title,c.nickname");
        return $this->find($page);
    }

    /**
     * 删除随游评论
     * @param $id
     * @throws \yii\db\Exception
     */
    public function deleteComment($id)
    {
        $sql = sprintf("
            DELETE FROM travel_trip_comment
            WHERE commentId=:commentId
        ");
        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":commentId", $id, PDO::PARAM_INT);
        $command->execute();
    }

    /**
     * 添加随游明细
     * @param TravelTripDetail $travelTripDetail
     * @throws \yii\db\Exception
     */
    public function addTravelTripDetail(TravelTripDetail $travelTripDetail)
    {
        $sql = sprintf("
            INSERT INTO travel_trip_detail
            (
              tripId,name,type
            )
            VALUES
            (
              :tripId,:name,:type
            )
        ");

        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $travelTripDetail->tripId, PDO::PARAM_INT);
        $command->bindParam(":name", $travelTripDetail->name, PDO::PARAM_STR);
        $command->bindParam(":type", $travelTripDetail->type, PDO::PARAM_STR);

        $command->execute();
    }

    /**
     * 删除随游相关的明细
     * @param $tripId
     * @throws \yii\db\Exception
     */
    public function deleteTravelTripDetailByTripId($tripId)
    {
        $sql = sprintf("
            DELETE FROM travel_trip_detail
            WHERE tripId=:tripId
        ");

        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->execute();
    }

    /**
     * 添加随游亮点
     * @param TravelTripHighlight $travelTripHighlight
     * @throws \yii\db\Exception
     */
    public function addTravelTripHighLight(TravelTripHighlight $travelTripHighlight)
    {
        $sql = sprintf("
            INSERT INTO travel_trip_highlight
            (
              tripId,value
            )
            VALUES
            (
              :tripId,:value
            )
        ");

        $command = $this->getConnection()->createCommand($sql);

        $command->bindParam(":tripId", $travelTripHighlight->tripId, PDO::PARAM_INT);
        $command->bindParam(":value", $travelTripHighlight->value, PDO::PARAM_STR);

        $command->execute();
    }

    /**
     * 删除随游相关的亮点
     * @param $tripId
     * @throws \yii\db\Exception
     */
    public function deleteTravelTripHighLightByTripId($tripId)
    {
        $sql = sprintf("
            DELETE FROM travel_trip_highlight
            WHERE tripId=:tripId
        ");

        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->execute();
    }

    /**
     * 获取明细根据随游Id
     * @param $tripId
     * @return array
     */
    public function getTravelTripDetailList($tripId)
    {
        $sql = sprintf("
            SELECT detailId,tripId,name,type FROM travel_trip_detail
            WHERE tripId=:tripId
        ");

        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        return $command->queryAll();
    }

    /**
     * 获取亮点 根据随游Id
     * @param $tripId
     * @return array
     */
    public function getTravelTripHighlightList($tripId)
    {
        $sql = sprintf("
            SELECT hlId,tripId,value FROM travel_trip_highlight
            WHERE tripId=:tripId
        ");

        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        return $command->queryAll();
    }

    /**
     * 获取用户推荐信息
     * @param $tripId
     * @return array|bool
     */
    public function findTravelTripRecommendByTripId($tripId)
    {
        $sql = sprintf("
            SELECT ub.userSign,ub.nickname,ub.headImg,ttr.content FROM travel_trip_recommend ttr
            LEFT JOIN user_base ub ON ttr.userId=ub.userSign
            WHERE ttr.tripId=:tripId
        ");

        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);

        return $command->queryOne();
    }

    /**
     * 更新随游评分和随游次数
     * @param $tripId
     * @param $score
     * @param $tripCount
     * @param $isHot
     * @param $type
     * @return int
     * @throws \yii\db\Exception
     */
    public function updateTravelTripBase($tripId, $score, $tripCount,$isHot,$type)
    {
        $sql = sprintf("
            UPDATE travel_trip SET score=:score , tripCount=:tripCount,isHot=:isHot,type=:type
            WHERE tripId=:tripId
        ");
        $command = $this->getConnection()->createCommand($sql);
        $command->bindParam(":tripId", $tripId, PDO::PARAM_INT);
        $command->bindParam(":score", $score, PDO::PARAM_INT);
        $command->bindParam(":tripCount", $tripCount, PDO::PARAM_INT);
        $command->bindParam(":isHot", $isHot, PDO::PARAM_INT);
        $command->bindParam(":type", $type, PDO::PARAM_INT);

        return $command->execute();
    }

    /**
     * 获取随游目的地 和 目的地数量
     * @param Page $page
     * @param $search
     * @return Page|null
     */
    public function getTripDesSearchList(Page $page,$search)
    {
        $sql = sprintf("
            FROM
            (
                SELECT c.id,c.cname,c.ename,c.areaCode,t.count FROM  (SELECT countryId,COUNT(tripId) as count FROM travel_trip WHERE status=:status GROUP BY countryId HAVING count>0  ) t

                LEFT JOIN country c ON c.id=t.countryId

                UNION

                SELECT c.id,c.cname,c.ename,c.areaCode,t.count FROM  (SELECT cityId,COUNT(tripId) as count FROM travel_trip WHERE status=:status GROUP by cityId HAVING count>0  ) t

                LEFT JOIN city c ON c.id=t.cityId
            )  AS s
            WHERE 1=1 ORDER BY s.count
        ");
        $this->setParam("status", TravelTrip::TRAVEL_TRIP_STATUS_NORMAL);
        if (!empty($search)) {
            $sql .= " AND ( s.cname like :search OR  s.ename like :search) ";
            $this->setParam("search", "%" . $search . "%");
        }
        $this->setSql($sql);

        return $this->find($page);
    }

}


text:
from django.core.urlresolvers import reverse

# view imports
from django.views.generic import DetailView
from django.views.generic import RedirectView
from django.views.generic import UpdateView
from django.views.generic import ListView

# Only authenticated users can access views using this.
from braces.views import LoginRequiredMixin

# Import the form from users/forms.py
from .forms import UserForm

# Import the customized User model
from .models import User

class UserDetailView(LoginRequiredMixin, DetailView):
    model = User
    # These next two lines tell the view to index lookups by username
    slug_field = "username"
    slug_url_kwarg = "username"

class UserRedirectView(LoginRequiredMixin, RedirectView):
    permanent = False

    def get_redirect_url(self):
        return reverse("users:detail",
                       kwargs={"username": self.request.user.username})

class UserUpdateView(LoginRequiredMixin, UpdateView):

    form_class = UserForm

    # we already imported User in the view code above, remember?
    model = User

    # send the user back to their own page after a successful update
    def get_success_url(self):
        return reverse("users:detail",
                       kwargs={"username": self.request.user.username})

    def get_object(self):
        # Only get the User record for the user making the request
        return User.objects.get(username=self.request.user.username)

class UserListView(LoginRequiredMixin, ListView):
    model = User
    # These next two lines tell the view to index lookups by username
    slug_field = "username"
    slug_url_kwarg = "username"

    def get_context_data(self, **kwargs):
        import sys
        print >> sys.stderr, self.get_template_names()
        context = super(UserListView, self).get_context_data(**kwargs)
        return context

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Zodream\Service\Controller;
/**
 * 控制器基类
 *
 * @author Jason
 * @time 2015-12-19
 */
use Exception;
use Zodream\Service\Factory;
use Zodream\Infrastructure\Http\Request;
use Zodream\Infrastructure\Event\EventManger;
use Zodream\Infrastructure\Http\Response;

abstract class BaseController extends Action {

	protected $action = 'index';

	protected function actions() {
		return [];
	}

	/**
	 * 此方法主要是为了继承并附加规则
	 * @return array
	 */
	protected function rules() {
		return [];
	}

    /**
     * 执行方法
     * @param string $action
     * @param array $vars
     * @return string|Response
     * @throws \Exception
     */
	public function runMethod($action, array $vars = array()) {
        Factory::timer()->record('controllerStart');
		$this->action = $action;
		if (!$this->hasMethod($action)) {
			throw new Exception('URI ERROR!');
		}
		if (true !==
            ($arg = $this->beforeFilter($action))) {
			return $arg;
		}
		if (array_key_exists($action, $this->actions())) {
			return $this->runClassMethod($action);
		}
		$this->prepare();
		EventManger::getInstance()->run('runController', $vars);
		$result = $this->runActionMethod($this->getActionName($action), $vars);
		$this->finalize();
        Factory::timer()->record('controllerEnd');
		return $result;
	}

    /**
     * 获取
     * @param $action
     * @return string
     */
	protected function getActionName($action) {
	    return $action.APP_ACTION;
    }

	private function runClassMethod($action) {
		$class = $this->actions()[$action];
		if (is_callable($class)) {
			return call_user_func($class);
		}
		if (!class_exists($class)) {
			throw new Exception($action. ' CANNOT RUN CLASS!');
		}
		$instance = new $class;
		if (!$instance instanceof Action) {
			throw new Exception($action. ' IS NOT ACTION!');
		}
		$instance->init();
		$instance->prepare();
		$result = $instance->run();
		$instance->finalize();
		return $result;
	}

    /**
     * RUN THIS METHOD ACTION
     * @param string $action
     * @param array $vars
     * @return mixed
     */
	protected function runActionMethod($action, $vars = array()) {
		return call_user_func_array(
		    array($this, $action),
            $this->getActionArguments($action, $vars)
        );
	}

    /**
     * GET ACTION NEED ARGUMENTS
     * @param string $action
     * @param array $vars
     * @return array
     * @throws Exception
     */
	protected function getActionArguments($action, $vars = array()) {
        $reflectionObject = new \ReflectionObject($this);
        $method = $reflectionObject->getMethod($action);
        $parameters = $method->getParameters();
        $arguments = array();
        foreach ($parameters as $param) {
            $name = $param->getName();
            if (array_key_exists($name, $vars)) {
                $arguments[] = $vars[$name];
                continue;
            }
            $value = $this->setActionArguments($name);
            if (!is_null($value)){
                $arguments[] = $value;
                continue;
            }
            if ($param->isDefaultValueAvailable()) {
                $arguments[] = $param->getDefaultValue();
                continue;
            }
            throw new Exception($action.' ACTION`S '.$name, ' DOES NOT HAVE VALUE!');
        }
        return $arguments;
    }

    /**
     * 设置方法的注入值来源
     * @param $name
     * @return array|string  返回null时取默认值
     */
    protected function setActionArguments($name) {
        return Request::get($name);
    }

	/**
	 * 加载其他控制器的方法
	 * @param static|string $controller
	 * @param string $actionName
	 * @param array $parameters
	 */
	public function forward(
	    $controller,
        $actionName = 'index' ,
        $parameters = array()
    ) {
		if (is_string($controller)) {
			$controller = new $controller;
		}
		return $controller->runMethod($actionName, $parameters);
	}

	/**
	 * 判断是否存在方法
	 * @param string $action
	 * @return boolean
	 */
	public function hasMethod($action) {
		return array_key_exists($action, $this->actions())
        || method_exists($this, $action.APP_ACTION);
	}

    /**
     * 验证方法是否合法
     * @param $action
     * @return boolean|Response
     */
    abstract protected function beforeFilter($action);

}


text:
'use strict';

var path = require('path');
var gulp = require('gulp');
var runSequence = require('run-sequence');
var concat = require('gulp-concat');
var conf = require('./conf');

var $ = require('gulp-load-plugins')({
	pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});

gulp.task('partials', function() {
	return gulp.src([
    path.join(conf.paths.src, conf.paths.template),
    path.join(conf.paths.tmp, '/serve/app/**/*.html')
	])
    .pipe($.htmlmin({
    	removeEmptyAttributes: true,
    	removeAttributeQuotes: true,
    	collapseBooleanAttributes: true,
    	collapseWhitespace: true
    }))
    .pipe($.angularTemplatecache('templateCacheHtml.js', {
    	module: conf.names.module,
    	root: conf.paths.templateRoot,
    }))
    .pipe(gulp.dest(conf.paths.tmp + '/partials/'));
});

gulp.task('html', ['inject', 'partials'], function() {
	var partialsInjectFile = gulp.src(path.join(conf.paths.tmp, '/partials/templateCacheHtml.js'), { read: false });
	var partialsInjectOptions = {
		starttag: '<!-- inject:partials -->',
		ignorePath: path.join(conf.paths.tmp, '/partials'),
		addRootSlash: false
	};

	var htmlFilter = $.filter('*.html', { restore: true });
	var jsFilter = $.filter('**/*.js', { restore: true });
	var cssFilter = $.filter('**/*.css', { restore: true });

	return gulp.src(path.join(conf.paths.tmp, '/serve/*.html'))
    .pipe($.inject(partialsInjectFile, partialsInjectOptions))
    .pipe($.useref())
    .pipe(jsFilter)
    .pipe($.sourcemaps.init())
    .pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', conf.errorHandler('Uglify'))
    .pipe($.sourcemaps.write('maps'))
    .pipe(jsFilter.restore)
    .pipe(cssFilter)
    // .pipe($.sourcemaps.init())
    .pipe($.replace('../../bower_components/bootstrap-sass/assets/fonts/bootstrap/', '../fonts/'))
    .pipe($.cssnano())
    // .pipe($.sourcemaps.write('maps'))
    .pipe(cssFilter.restore)
    .pipe(htmlFilter)
    .pipe($.htmlmin({
    	removeEmptyAttributes: true,
    	removeAttributeQuotes: true,
    	collapseBooleanAttributes: true,
    	collapseWhitespace: true
    }))
    .pipe(htmlFilter.restore)
    .pipe(gulp.dest(path.join(conf.paths.dist, '/')))
    .pipe($.size({ title: path.join(conf.paths.dist, '/'), showFiles: true }));
});

// Only applies for fonts from bower dependencies
// Custom fonts are handled by the "other" task
gulp.task('fonts', function() {
	return gulp.src($.mainBowerFiles({
		paths: {
			bowerJson: 'bowerDocs.json'
		}
	}))
    .pipe($.filter('**/*.{eot,otf,svg,ttf,woff,woff2}'))
    .pipe($.flatten())
    .pipe(gulp.dest(path.join(conf.paths.dist, '/fonts/')));
});

gulp.task('other', function() {
	var fileFilter = $.filter(function(file) {
		return file.stat.isFile();
	});

	return gulp.src([
    path.join(conf.paths.src, '/**/*'),
    path.join('!' + conf.paths.src, '/**/*.{html,css,js,scss}')
	])
    .pipe(fileFilter)
    .pipe(gulp.dest(path.join(conf.paths.dist, '/')));
});

gulp.task('clean', function() {
	return $.del([path.join(conf.paths.dist, '/'), path.join(conf.paths.tmp, '/')]);
});

gulp.task('build', ['html', 'fonts', 'other']);

gulp.task('conf:component', function(cb) {
	conf.paths.src = 'src/app/component';
	conf.paths.dist = 'dist';
	conf.paths.template = '**/*.html';
	conf.paths.index = 'angularjs-dropdown-multiselect.module.js';
	conf.paths.templateRoot = 'app/component/';
	conf.paths.cssRoot = '';
	conf.paths.bowerJson = '../bower.json';
	conf.names.module = 'angularjs-dropdown-multiselect';
	conf.wiredep.bowerJson = require(conf.paths.bowerJson);
	cb();
});

gulp.task('clean:component', ['conf:component'], function() {
	return $.del([path.join(conf.paths.dist, '/'), path.join(conf.paths.tmp, '/')]);
});

gulp.task('compile:component', ['clean:component'], function(cb) {
	runSequence(['scripts', 'styles', 'partials'], cb);
});

gulp.task('build:component', ['compile:component'], function() {
	var jsFilter = $.filter('**/*.js', { restore: true });
	var cssFilter = $.filter('**/*.css', { restore: true });

	return gulp.src([
		path.join(conf.paths.tmp, 'serve/app/index.css'),
		path.join(conf.paths.tmp, 'serve/app/index.module.js'),
		path.join(conf.paths.tmp, 'partials/templateCacheHtml.js')
	])
		.pipe(jsFilter)
		.pipe(concat({ path: 'angularjs-dropdown-multiselect.min.js'}))
    .pipe($.sourcemaps.init())
    .pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', conf.errorHandler('Uglify'))
    .pipe($.sourcemaps.write('maps'))
		.pipe(jsFilter.restore)
		.pipe(cssFilter)
		.pipe($.cssnano())
		.pipe(cssFilter.restore)
		.pipe(gulp.dest(path.join(conf.paths.dist, '/')))
    .pipe($.size({ title: path.join(conf.paths.dist, '/'), showFiles: true }));
});


text:
package com.arenas.droidfan.profile.photoalbum;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.arenas.droidfan.R;
import com.arenas.droidfan.adapter.MyOnItemClickListener;
import com.arenas.droidfan.adapter.PhotoAlbumAdapter;
import com.arenas.droidfan.data.model.StatusModel;
import com.arenas.droidfan.main.hometimeline.HomeTimelineFragment;
import com.arenas.droidfan.photo.PhotoActivity;
import com.arenas.droidfan.profile.profilestatus.ProfileStatusFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

public class PhotoAlbumFragment extends ProfileStatusFragment {

    private static final String TAG = PhotoAlbumFragment.class.getSimpleName();

    private PhotoAlbumAdapter mAdapter;

    public PhotoAlbumFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_photos, container, false);
        init(view);
        return view;
    }

    @Override
    public void initAdapter() {
        mAdapter = new PhotoAlbumAdapter(getContext() , new ArrayList<StatusModel>() , listener);
    }

    public void init(View view){
        ButterKnife.bind(this , view);

        recyclerView.setLayoutManager(new GridLayoutManager(getContext() , 3));
        recyclerView.setPullRefreshEnabled(false);
        recyclerView.setLoadingListener(this);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    public void showStatus(List<StatusModel> status) {
        mAdapter.replaceData(status);
    }

    MyOnItemClickListener listener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(View view, StatusModel statusModel , int position) {
            PhotoActivity.start(getContext() , mAdapter.getPhotoData() , position);
        }

        @Override
        public void onItemLongClick(int id, int position) {

        }
    };
}


text:
<?php

namespace Champion\AccesBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ChampionAccesBundle extends Bundle
{
    public function getParent()
    {
        return 'FOSUserBundle';
    }
}


text:
/////////////////////////////////////////////////////////////////////////////
// Name:        wx/glcanvas.h
// Purpose:     wxGLCanvas base header
// Author:      Julian Smart
// Modified by:
// Created:
// Copyright:   (c) Julian Smart
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

#ifndef _WX_GLCANVAS_H_BASE_
#define _WX_GLCANVAS_H_BASE_

#include "wx/defs.h"

#if wxUSE_GLCANVAS

#include "wx/app.h"
#include "wx/palette.h"
#include "wx/window.h"

class WXDLLIMPEXP_FWD_GL wxGLCanvas;
class WXDLLIMPEXP_FWD_GL wxGLContext;

// ----------------------------------------------------------------------------
// Constants for attributes list
// ----------------------------------------------------------------------------

// Notice that not all implementation support options such as stereo, auxiliary
// buffers, alpha channel, and accumulator buffer, use IsDisplaySupported() to
// check for individual attributes support.
enum
{
    WX_GL_RGBA = 1,        // use true color palette (on if no attrs specified)
    WX_GL_BUFFER_SIZE,     // bits for buffer if not WX_GL_RGBA
    WX_GL_LEVEL,           // 0 for main buffer, >0 for overlay, <0 for underlay
    WX_GL_DOUBLEBUFFER,    // use double buffering (on if no attrs specified)
    WX_GL_STEREO,          // use stereoscopic display
    WX_GL_AUX_BUFFERS,     // number of auxiliary buffers
    WX_GL_MIN_RED,         // use red buffer with most bits (> MIN_RED bits)
    WX_GL_MIN_GREEN,       // use green buffer with most bits (> MIN_GREEN bits)
    WX_GL_MIN_BLUE,        // use blue buffer with most bits (> MIN_BLUE bits)
    WX_GL_MIN_ALPHA,       // use alpha buffer with most bits (> MIN_ALPHA bits)
    WX_GL_DEPTH_SIZE,      // bits for Z-buffer (0,16,32)
    WX_GL_STENCIL_SIZE,    // bits for stencil buffer
    WX_GL_MIN_ACCUM_RED,   // use red accum buffer with most bits (> MIN_ACCUM_RED bits)
    WX_GL_MIN_ACCUM_GREEN, // use green buffer with most bits (> MIN_ACCUM_GREEN bits)
    WX_GL_MIN_ACCUM_BLUE,  // use blue buffer with most bits (> MIN_ACCUM_BLUE bits)
    WX_GL_MIN_ACCUM_ALPHA, // use alpha buffer with most bits (> MIN_ACCUM_ALPHA bits)
    WX_GL_SAMPLE_BUFFERS,  // 1 for multisampling support (antialiasing)
    WX_GL_SAMPLES,         // 4 for 2x2 antialiasing supersampling on most graphics cards
    WX_GL_FRAMEBUFFER_SRGB,// capability for sRGB framebuffer
    // Context attributes
    WX_GL_CORE_PROFILE,    // use an OpenGL core profile
    WX_GL_MAJOR_VERSION,   // major OpenGL version of the core profile
    WX_GL_MINOR_VERSION,   // minor OpenGL version of the core profile
    wx_GL_COMPAT_PROFILE,  // use compatible profile (use all versions features)
    WX_GL_FORWARD_COMPAT,  // forward compatible context. OpenGL >= 3.0
    WX_GL_ES2,             // ES or ES2 context.
    WX_GL_DEBUG,           // create a debug context
    WX_GL_ROBUST_ACCESS,   // robustness.
    WX_GL_NO_RESET_NOTIFY, // never deliver notification of reset events
    WX_GL_LOSE_ON_RESET,   // if graphics reset, all context state is lost
    WX_GL_RESET_ISOLATION, // protect other apps or share contexts from reset side-effects
    WX_GL_RELEASE_FLUSH,   // on context release, flush pending commands
    WX_GL_RELEASE_NONE     // on context release, pending commands are not flushed
};

#define wxGLCanvasName wxT("GLCanvas")

// ----------------------------------------------------------------------------
// wxGLAttribsBase: OpenGL rendering attributes
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_GL wxGLAttribsBase
{
public:
    wxGLAttribsBase() { Reset(); }

    // Setters
    void AddAttribute(int attribute) { m_GLValues.push_back(attribute); }
    // Search for searchVal and combine the next value with combineVal
    void AddAttribBits(int searchVal, int combineVal);
    // ARB functions necessity
    void SetNeedsARB(bool needsARB = true) { m_needsARB = needsARB; }

    // Delete contents
    void Reset()
    {
        m_GLValues.clear();
        m_needsARB = false;
    }

    // Accessors
    const int* GetGLAttrs() const
    {
        return (m_GLValues.empty() || !m_GLValues[0]) ? NULL : &*m_GLValues.begin();
    }

    int GetSize() const { return (int)(m_GLValues.size()); }

    // ARB function (e.g. wglCreateContextAttribsARB) is needed
    bool NeedsARB() const { return m_needsARB; }

private:
    wxVector<int> m_GLValues;
    bool m_needsARB;
};

// ----------------------------------------------------------------------------
// wxGLContextAttrs: OpenGL rendering context attributes
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_GL wxGLContextAttrs : public wxGLAttribsBase
{
public:
    // Setters, allowing chained calls
    wxGLContextAttrs& CoreProfile();
    wxGLContextAttrs& MajorVersion(int val);
    wxGLContextAttrs& MinorVersion(int val);
    wxGLContextAttrs& OGLVersion(int vmayor, int vminor)
        { return MajorVersion(vmayor).MinorVersion(vminor); }
    wxGLContextAttrs& CompatibilityProfile();
    wxGLContextAttrs& ForwardCompatible();
    wxGLContextAttrs& ES2();
    wxGLContextAttrs& DebugCtx();
    wxGLContextAttrs& Robust();
    wxGLContextAttrs& NoResetNotify();
    wxGLContextAttrs& LoseOnReset();
    wxGLContextAttrs& ResetIsolation();
    wxGLContextAttrs& ReleaseFlush(int val = 1); //'int' allows future values
    wxGLContextAttrs& PlatformDefaults();
    void EndList(); // No more values can be chained

    // Currently only used for X11 context creation
    bool x11Direct; // X11 direct render
    bool renderTypeRGBA;
};

// ----------------------------------------------------------------------------
// wxGLAttributes: canvas configuration
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_GL wxGLAttributes : public wxGLAttribsBase
{
public:
    // Setters, allowing chained calls
    wxGLAttributes& RGBA();
    wxGLAttributes& BufferSize(int val);
    wxGLAttributes& Level(int val);
    wxGLAttributes& DoubleBuffer();
    wxGLAttributes& Stereo();
    wxGLAttributes& AuxBuffers(int val);
    wxGLAttributes& MinRGBA(int mRed, int mGreen, int mBlue, int mAlpha);
    wxGLAttributes& Depth(int val);
    wxGLAttributes& Stencil(int val);
    wxGLAttributes& MinAcumRGBA(int mRed, int mGreen, int mBlue, int mAlpha);
    wxGLAttributes& PlatformDefaults();
    wxGLAttributes& Defaults();
    wxGLAttributes& SampleBuffers(int val);
    wxGLAttributes& Samplers(int val);
    wxGLAttributes& FrameBuffersRGB();
    void EndList(); // No more values can be chained

    // This function is undocumented and can not be chained on purpose!
    // To keep backwards compatibility with versions before wx3.1 we add here
    // the default values used in those versions for the case of NULL list.
    void AddDefaultsForWXBefore31();
};

// ----------------------------------------------------------------------------
// wxGLContextBase: OpenGL rendering context
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_GL wxGLContextBase : public wxObject
{
public:

//  The derived class should provide a ctor with this signature:
//
//  wxGLContext(wxGLCanvas *win,
//              const wxGLContext *other = NULL,
//              const wxGLContextAttrs *ctxAttrs = NULL);

    // set this context as the current one
    virtual bool SetCurrent(const wxGLCanvas& win) const = 0;

    bool IsOK() const { return m_isOk; }

protected:
    bool m_isOk;
};

// ----------------------------------------------------------------------------
// wxGLCanvasBase: window which can be used for OpenGL rendering
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_GL wxGLCanvasBase : public wxWindow
{
public:
    // default ctor doesn't initialize the window, use Create() later
    wxGLCanvasBase();

    virtual ~wxGLCanvasBase();

    /*
       The derived class should provide a ctor with this signature:

    wxGLCanvas(wxWindow *parent,
               const wxGLAttributes& dispAttrs,
               wxWindowID id = wxID_ANY,
               const wxPoint& pos = wxDefaultPosition,
               const wxSize& size = wxDefaultSize,
               long style = 0,
               const wxString& name = wxGLCanvasName,
               const wxPalette& palette = wxNullPalette);
     */

    // operations
    // ----------

    // set the given context associated with this window as the current one
    bool SetCurrent(const wxGLContext& context) const;

    // flush the back buffer (if we have it)
    virtual bool SwapBuffers() = 0;

    // accessors
    // ---------

    // check if the given attributes are supported without creating a canvas
    static bool IsDisplaySupported(const wxGLAttributes& dispAttrs);
    static bool IsDisplaySupported(const int *attribList);

#if wxUSE_PALETTE
    const wxPalette *GetPalette() const { return &m_palette; }
#endif // wxUSE_PALETTE

    // miscellaneous helper functions
    // ------------------------------

    // call glcolor() for the colour with the given name, return false if
    // colour not found
    bool SetColour(const wxString& colour);

    // return true if the extension with given name is supported
    //
    // notice that while this function is implemented for all of GLX, WGL and
    // AGL the extensions names are usually not the same for different
    // platforms and so the code using it still usually uses conditional
    // compilation
    static bool IsExtensionSupported(const char *extension);

    // Get the wxGLContextAttrs object filled with the context-related values
    // of the list of attributes passed at ctor when no wxGLAttributes is used
    // as a parameter
    wxGLContextAttrs& GetGLCTXAttrs() { return m_GLCTXAttrs; }

    // deprecated methods using the implicit wxGLContext
#if WXWIN_COMPATIBILITY_2_8
    wxDEPRECATED( wxGLContext* GetContext() const );

    wxDEPRECATED( void SetCurrent() );

    wxDEPRECATED( void OnSize(wxSizeEvent& event) );
#endif // WXWIN_COMPATIBILITY_2_8

#ifdef __WXUNIVERSAL__
    // resolve the conflict with wxWindowUniv::SetCurrent()
    virtual bool SetCurrent(bool doit) { return wxWindow::SetCurrent(doit); }
#endif

protected:
    // override this to implement SetColour() in GL_INDEX_MODE
    // (currently only implemented in wxX11 and wxMotif ports)
    virtual int GetColourIndex(const wxColour& WXUNUSED(col)) { return -1; }

    // check if the given extension name is present in the space-separated list
    // of extensions supported by the current implementation such as returned
    // by glXQueryExtensionsString() or glGetString(GL_EXTENSIONS)
    static bool IsExtensionInList(const char *list, const char *extension);

    // For the case of "int* attribList" at ctor is != 0
    wxGLContextAttrs m_GLCTXAttrs;

    // Extract pixel format and context attributes.
    // Return false if an unknown attribute is found.
    static bool ParseAttribList(const int* attribList,
                                wxGLAttributes& dispAttrs,
                                wxGLContextAttrs* ctxAttrs = NULL);

#if wxUSE_PALETTE
    // create default palette if we're not using RGBA mode
    // (not supported in most ports)
    virtual wxPalette CreateDefaultPalette() { return wxNullPalette; }

    wxPalette m_palette;
#endif // wxUSE_PALETTE

#if WXWIN_COMPATIBILITY_2_8
    wxGLContext *m_glContext;
#endif // WXWIN_COMPATIBILITY_2_8
};

// ----------------------------------------------------------------------------
// wxGLApp: a special wxApp subclass for OpenGL applications which must be used
//          to select a visual compatible with the given attributes
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_GL wxGLAppBase : public wxApp
{
public:
    wxGLAppBase() : wxApp() { }

    // use this in the constructor of the user-derived wxGLApp class to
    // determine if an OpenGL rendering context with these attributes
    // is available - returns true if so, false if not.
    virtual bool InitGLVisual(const int *attribList) = 0;
};

#if defined(__WXMSW__)
    #include "wx/msw/glcanvas.h"
#elif defined(__WXMOTIF__) || defined(__WXX11__)
    #include "wx/x11/glcanvas.h"
#elif defined(__WXGTK20__)
    #include "wx/gtk/glcanvas.h"
#elif defined(__WXGTK__)
    #include "wx/gtk1/glcanvas.h"
#elif defined(__WXMAC__)
    #include "wx/osx/glcanvas.h"
#elif defined(__WXQT__)
    #include "wx/qt/glcanvas.h"
#else
    #error "wxGLCanvas not supported in this wxWidgets port"
#endif

// wxMac and wxMSW don't need anything extra in wxGLAppBase, so declare it here
#ifndef wxGL_APP_DEFINED

class WXDLLIMPEXP_GL wxGLApp : public wxGLAppBase
{
public:
    wxGLApp() : wxGLAppBase() { }

    virtual bool InitGLVisual(const int *attribList) wxOVERRIDE;

private:
    wxDECLARE_DYNAMIC_CLASS(wxGLApp);
};

#endif // !wxGL_APP_DEFINED

// ----------------------------------------------------------------------------
// wxGLAPI: an API wrapper that allows the use of 'old' APIs even on OpenGL
// platforms that don't support it natively anymore, if the APIs are available
// it's a mere redirect
// ----------------------------------------------------------------------------

#ifndef wxUSE_OPENGL_EMULATION
    #define wxUSE_OPENGL_EMULATION 0
#endif

class WXDLLIMPEXP_GL wxGLAPI : public wxObject
{
public:
    wxGLAPI();
    ~wxGLAPI();

    static void glFrustum(GLfloat left, GLfloat right, GLfloat bottom,
                            GLfloat top, GLfloat zNear, GLfloat zFar);
    static void glBegin(GLenum mode);
    static void glTexCoord2f(GLfloat s, GLfloat t);
    static void glVertex3f(GLfloat x, GLfloat y, GLfloat z);
    static void glNormal3f(GLfloat nx, GLfloat ny, GLfloat nz);
    static void glColor4f(GLfloat r, GLfloat g, GLfloat b, GLfloat a);
    static void glColor3f(GLfloat r, GLfloat g, GLfloat b);
    static void glEnd();
};

#endif // wxUSE_GLCANVAS

#endif // _WX_GLCANVAS_H_BASE_


text: var Handlebars = Y.Handlebars;


text:
namespace chromecast {
namespace media {

namespace {
const size_t kMaxFrameSize = 4 * 1024 * 1024;

class DecoderBufferFromMsg : public DecoderBufferBase {
 public:
  explicit DecoderBufferFromMsg(scoped_ptr<MediaMessage> msg);

  void Initialize();

  // DecoderBufferBase implementation.
  base::TimeDelta timestamp() const override;
  const uint8* data() const override;
  uint8* writable_data() const override;
  int data_size() const override;
  const ::media::DecryptConfig* decrypt_config() const override;
  bool end_of_stream() const override;

 private:
  ~DecoderBufferFromMsg() override;

  // Indicates whether this is an end of stream frame.
  bool is_eos_;

  // Frame timestamp.
  base::TimeDelta pts_;

  // CENC parameters.
  scoped_ptr< ::media::DecryptConfig> decrypt_config_;

  // Size of the frame.
  int data_size_;

  // Keeps the message since frame data is not copied.
  scoped_ptr<MediaMessage> msg_;
  uint8* data_;

  DISALLOW_COPY_AND_ASSIGN(DecoderBufferFromMsg);
};

DecoderBufferFromMsg::DecoderBufferFromMsg(
    scoped_ptr<MediaMessage> msg)
    : msg_(msg.Pass()),
      is_eos_(true),
      data_(NULL) {
  CHECK(msg_);
}

DecoderBufferFromMsg::~DecoderBufferFromMsg() {
}

void DecoderBufferFromMsg::Initialize() {
  CHECK_EQ(msg_->type(), FrameMediaMsg);

  CHECK(msg_->ReadPod(&is_eos_));
  if (is_eos_)
    return;

  int64 pts_internal = 0;
  CHECK(msg_->ReadPod(&pts_internal));
  pts_ = base::TimeDelta::FromInternalValue(pts_internal);

  bool has_decrypt_config = false;
  CHECK(msg_->ReadPod(&has_decrypt_config));
  if (has_decrypt_config)
    decrypt_config_.reset(DecryptConfigMarshaller::Read(msg_.get()).release());

  CHECK(msg_->ReadPod(&data_size_));
  CHECK_GT(data_size_, 0);
  CHECK_LT(data_size_, kMaxFrameSize);

  // Get a pointer to the frame data inside the message.
  // Avoid copying the frame data here.
  data_ = static_cast<uint8*>(msg_->GetWritableBuffer(data_size_));
  CHECK(data_);

  if (decrypt_config_) {
    uint32 subsample_total_size = 0;
    for (size_t k = 0; k < decrypt_config_->subsamples().size(); k++) {
      subsample_total_size += decrypt_config_->subsamples()[k].clear_bytes;
      subsample_total_size += decrypt_config_->subsamples()[k].cypher_bytes;
    }
    CHECK_EQ(subsample_total_size, data_size_);
  }
}

base::TimeDelta DecoderBufferFromMsg::timestamp() const {
  return pts_;
}

const uint8* DecoderBufferFromMsg::data() const {
  CHECK(msg_->IsSerializedMsgAvailable());
  return data_;
}

uint8* DecoderBufferFromMsg::writable_data() const {
  CHECK(msg_->IsSerializedMsgAvailable());
  return data_;
}

int DecoderBufferFromMsg::data_size() const {
  return data_size_;
}

const ::media::DecryptConfig* DecoderBufferFromMsg::decrypt_config() const {
  return decrypt_config_.get();
}

bool DecoderBufferFromMsg::end_of_stream() const {
  return is_eos_;
}

}  // namespace

// static
void DecoderBufferBaseMarshaller::Write(
    const scoped_refptr<DecoderBufferBase>& buffer,
    MediaMessage* msg) {
  CHECK(msg->WritePod(buffer->end_of_stream()));
  if (buffer->end_of_stream())
    return;

  CHECK(msg->WritePod(buffer->timestamp().ToInternalValue()));

  bool has_decrypt_config =
      (buffer->decrypt_config() != NULL &&
       buffer->decrypt_config()->iv().size() > 0);
  CHECK(msg->WritePod(has_decrypt_config));

  if (has_decrypt_config) {
    // DecryptConfig may contain 0 subsamples if all content is encrypted.
    // Map this case to a single fully-encrypted "subsample" for more consistent
    // backend handling.
    if (buffer->decrypt_config()->subsamples().empty()) {
      std::vector< ::media::SubsampleEntry> encrypted_subsample_list(1);
      encrypted_subsample_list[0].clear_bytes = 0;
      encrypted_subsample_list[0].cypher_bytes = buffer->data_size();
      ::media::DecryptConfig full_sample_config(
          buffer->decrypt_config()->key_id(),
          buffer->decrypt_config()->iv(),
          encrypted_subsample_list);
      DecryptConfigMarshaller::Write(full_sample_config, msg);
    } else {
      DecryptConfigMarshaller::Write(*buffer->decrypt_config(), msg);
    }
  }

  CHECK(msg->WritePod(buffer->data_size()));
  CHECK(msg->WriteBuffer(buffer->data(), buffer->data_size()));
}

// static
scoped_refptr<DecoderBufferBase> DecoderBufferBaseMarshaller::Read(
    scoped_ptr<MediaMessage> msg) {
  scoped_refptr<DecoderBufferFromMsg> buffer(
      new DecoderBufferFromMsg(msg.Pass()));
  buffer->Initialize();
  return buffer;
}

}  // namespace media
}  // namespace chromecast


text:
import { Question } from './question';
import { Achievement } from './achievement';

export interface Questionary {
  monumentId: string,
  name: string,
  questions: Question[],
  achievement: Achievement
}


text:
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <errno.h>

#include "gdbus/gdbus.h"

#include "src/plugin.h"
#include "hdp_manager.h"

static int hdp_init(void)
{
	return hdp_manager_init();
}

static void hdp_exit(void)
{
	hdp_manager_exit();
}

BLUETOOTH_PLUGIN_DEFINE(health, VERSION,
			BLUETOOTH_PLUGIN_PRIORITY_DEFAULT, hdp_init, hdp_exit)


text:
.. _getting_started:
Getting Started
===============

Installation
^^^^^^^^^^^^

Pfp can be installed via pip: ::

    pip install pfp

Introduction
^^^^^^^^^^^^

Pfp is an interpreter for 010 template scripts. 010 Template scripts
use a modified C syntax. Control-flow
statements are allowed within struct declarations, and type
checking is done dynamically, as statements are interpreted
instead of at compile time.

010 template scripts parse data from the input stream by declaring
variables. Each time a variable is declared, that much data is read
from the input stream and stored in the variable.

Variables are also allowed that do not cause data to be read from
the input stream. Prefixing a declaration with ``const`` or ``local``
will create a temporary variable that can be used in the script.

An example template script that parses TLV (type-length-value)
structures out of the input stream is shown below:

.. highlight:: c

::

    local int count = 0;
    const uint64 MAGIC = 0xaabbccddeeff0011;

    uint64 magic;

    if(magic != MAGIC) {
        Printf("Magic value is not valid, bailing");
        return 1;
    }

    while(!FEof()) {
        Printf("Parsing the %d-th TLV structure", ++count);
        struct {
            string type;
            int length;
            char value[length;
        } tlv;
    }

.. highlight:: python

Note that a return statement in the main body of the script will
cause the template to stop being executed. Also note that declaring
multiple variables of the same name (in this case, ``tlv``) will cause
that variable to be made into an array of the variable's type.

More about the 010 template script syntax can be read about
`on the 010 Editor website <http://www.sweetscape.com/010editor/templates.html>`_.

Parsing Data
^^^^^^^^^^^^

010 template scripts are interpreted from python using the ``pfp.parse``
function, as shown below: ::

    import pfp

    template = """
        local int count = 0;
        const uint64 MAGIC = 0xaabbccddeeff0011;

        uint64 magic;

        if(magic != MAGIC) {
            Printf("Magic value is not valid, bailing");
            return 1;
        }

        while(!FEof()) {
            Printf("Parsing the %d-th TLV structure", ++count);
            struct {
                string type;
                int length;
                char value[length];
            } tlvs;
        }
    """

    parsed_tlv = pfp.parse(
        template        = template,
        data_file       = "path/to/tlv.bin"
    )

The ``pfp.parse`` function returns a dom of the parsed data. Individual
fields may be accessed using standard dot-notation: ::

    for tlv in parsed_tlv.tlvs:
        print("type: {}, value: {}".format(tlv.type, tlv.value))

Manipulating Data
^^^^^^^^^^^^^^^^^

Parsed data contained within the dom can be manipulated and then
rebuilt: ::

    for tlv in parsed_tlv.tlvs:
        if tlv.type == "SOMETYPE":
            tlv.value = "a new value"

    new_data = parsed_tlv._pfp__build()

Printing Structures
^^^^^^^^^^^^^^^^^^^

The method :any:`pfp.fields.Field._pfp__show` will print data information
about the field. If called on a field that contains child fields, those
fields will also be printed: ::

    dom = pfp.parse(...)
    print(dom._pfp__show(include_offset=True))

Metadata
^^^^^^^^

010 template sytax supports adding "special attributes" (called
metadata in pfp). 010 editor's special attributes are largely
centered around how fields are displayed in the GUI; for this
reason, pfp currently ignores 010 editor's special attributes.

However, pfp also introduces new special attributes to help
manage relationships between fields, such as lengths, checksums,
and compressed data.

The template below has updated the TLV-parsing template from
above to add metadata to the length field:

.. highlight:: c
::

    local int count = 0;
    const uint64 MAGIC = 0xaabbccddeeff0011;

    uint64 magic;

    if(magic != MAGIC) {
        Printf("Magic value is not valid, bailing");
        return 1;
    }

    while(!FEof()) {
        Printf("Parsing the %d-th TLV structure", ++count);
        struct {
            string type;
            int length<watch=value, update=WatchLength>;
            char value[length];
        } tlvs;
    }
.. highlight:: python

With the metadata, if the ``value`` field of a tlv were changed,
the ``length`` field would be automatically updated to the
new length of the ``value`` field.

See :doc:`metadata` for detailed information.

Debugger
^^^^^^^^

Pfp comes with a built-in debugger, which can be dropped into
by calling the :any:`Int3() <pfp.native.dbg.int3>` function in a
template. ::

         23 //   length (4 bytes), chunk_type (4 bytes), data (length bytes), crc (4 bytes)
         24 //   CRC Does NOT include the length bytes.
         25 //--------------------------------------
         26
    -->  27 Int3();
         28
         29 BigEndian();                  // PNG files are in Network Byte order
         30
         31 const uint64 PNGMAGIC = 0x89504E470D0A1A0AL;
    pfp> peek
    89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 .PNG........IHDR
    pfp> help

    Documented commands (type help <topic>):
    ========================================
    EOF  continue  eval  help  list  next  peek  quit  s  show  step  x

    pfp> n
         25 //--------------------------------------
         26
         27 Int3();
         28
    -->  29 BigEndian();                  // PNG files are in Network Byte order
         30
         31 const uint64 PNGMAGIC = 0x89504E470D0A1A0AL;
         32
         33 // Chunk Type
    pfp>


text:
#ifndef _LINUX_RXRPC_PACKET_H
#define _LINUX_RXRPC_PACKET_H

typedef u32	rxrpc_seq_t;	/* Rx message sequence number */
typedef u32	rxrpc_serial_t;	/* Rx message serial number */
typedef __be32	rxrpc_seq_net_t; /* on-the-wire Rx message sequence number */
typedef __be32	rxrpc_serial_net_t; /* on-the-wire Rx message serial number */

/*****************************************************************************/
/*
 * on-the-wire Rx packet header
 * - all multibyte fields should be in network byte order
 */
struct rxrpc_header {
	__be32		epoch;		/* client boot timestamp */

	__be32		cid;		/* connection and channel ID */
#define RXRPC_MAXCALLS		4			/* max active calls per conn */
#define RXRPC_CHANNELMASK	(RXRPC_MAXCALLS-1)	/* mask for channel ID */
#define RXRPC_CIDMASK		(~RXRPC_CHANNELMASK)	/* mask for connection ID */
#define RXRPC_CIDSHIFT		ilog2(RXRPC_MAXCALLS)	/* shift for connection ID */
#define RXRPC_CID_INC		(1 << RXRPC_CIDSHIFT)	/* connection ID increment */

	__be32		callNumber;	/* call ID (0 for connection-level packets) */
#define RXRPC_PROCESS_MAXCALLS	(1<<2)	/* maximum number of active calls per conn (power of 2) */

	__be32		seq;		/* sequence number of pkt in call stream */
	__be32		serial;		/* serial number of pkt sent to network */

	uint8_t		type;		/* packet type */
#define RXRPC_PACKET_TYPE_DATA		1	/* data */
#define RXRPC_PACKET_TYPE_ACK		2	/* ACK */
#define RXRPC_PACKET_TYPE_BUSY		3	/* call reject */
#define RXRPC_PACKET_TYPE_ABORT		4	/* call/connection abort */
#define RXRPC_PACKET_TYPE_ACKALL	5	/* ACK all outstanding packets on call */
#define RXRPC_PACKET_TYPE_CHALLENGE	6	/* connection security challenge (SRVR->CLNT) */
#define RXRPC_PACKET_TYPE_RESPONSE	7	/* connection secutity response (CLNT->SRVR) */
#define RXRPC_PACKET_TYPE_DEBUG		8	/* debug info request */
#define RXRPC_PACKET_TYPE_VERSION	13	/* version string request */
#define RXRPC_N_PACKET_TYPES		14	/* number of packet types (incl type 0) */

	uint8_t		flags;		/* packet flags */
#define RXRPC_CLIENT_INITIATED	0x01		/* signifies a packet generated by a client */
#define RXRPC_REQUEST_ACK	0x02		/* request an unconditional ACK of this packet */
#define RXRPC_LAST_PACKET	0x04		/* the last packet from this side for this call */
#define RXRPC_MORE_PACKETS	0x08		/* more packets to come */
#define RXRPC_JUMBO_PACKET	0x20		/* [DATA] this is a jumbo packet */
#define RXRPC_SLOW_START_OK	0x20		/* [ACK] slow start supported */

	uint8_t		userStatus;	/* app-layer defined status */
	uint8_t		securityIndex;	/* security protocol ID */
	union {
		__be16	_rsvd;		/* reserved */
		__be16	cksum;		/* kerberos security checksum */
	};
	__be16		serviceId;	/* service ID */

} __packed;

#define __rxrpc_header_off(X) offsetof(struct rxrpc_header,X)

extern const char *rxrpc_pkts[];

/*****************************************************************************/
/*
 * jumbo packet secondary header
 * - can be mapped to read header by:
 *   - new_serial = serial + 1
 *   - new_seq = seq + 1
 *   - new_flags = j_flags
 *   - new__rsvd = j__rsvd
 *   - duplicating all other fields
 */
struct rxrpc_jumbo_header {
	uint8_t		flags;		/* packet flags (as per rxrpc_header) */
	uint8_t		pad;
	__be16		_rsvd;		/* reserved (used by kerberos security as cksum) */
};

#define RXRPC_JUMBO_DATALEN	1412	/* non-terminal jumbo packet data length */

/*****************************************************************************/
/*
 * on-the-wire Rx ACK packet data payload
 * - all multibyte fields should be in network byte order
 */
struct rxrpc_ackpacket {
	__be16		bufferSpace;	/* number of packet buffers available */
	__be16		maxSkew;	/* diff between serno being ACK'd and highest serial no
					 * received */
	__be32		firstPacket;	/* sequence no of first ACK'd packet in attached list */
	__be32		previousPacket;	/* sequence no of previous packet received */
	__be32		serial;		/* serial no of packet that prompted this ACK */

	uint8_t		reason;		/* reason for ACK */
#define RXRPC_ACK_REQUESTED		1	/* ACK was requested on packet */
#define RXRPC_ACK_DUPLICATE		2	/* duplicate packet received */
#define RXRPC_ACK_OUT_OF_SEQUENCE	3	/* out of sequence packet received */
#define RXRPC_ACK_EXCEEDS_WINDOW	4	/* packet received beyond end of ACK window */
#define RXRPC_ACK_NOSPACE		5	/* packet discarded due to lack of buffer space */
#define RXRPC_ACK_PING			6	/* keep alive ACK */
#define RXRPC_ACK_PING_RESPONSE		7	/* response to RXRPC_ACK_PING */
#define RXRPC_ACK_DELAY			8	/* nothing happened since received packet */
#define RXRPC_ACK_IDLE			9	/* ACK due to fully received ACK window */

	uint8_t		nAcks;		/* number of ACKs */
#define RXRPC_MAXACKS	255

	uint8_t		acks[0];	/* list of ACK/NAKs */
#define RXRPC_ACK_TYPE_NACK		0
#define RXRPC_ACK_TYPE_ACK		1

} __packed;

/*
 * ACK packets can have a further piece of information tagged on the end
 */
struct rxrpc_ackinfo {
	__be32		rxMTU;		/* maximum Rx MTU size (bytes) [AFS 3.3] */
	__be32		maxMTU;		/* maximum interface MTU size (bytes) [AFS 3.3] */
	__be32		rwind;		/* Rx window size (packets) [AFS 3.4] */
	__be32		jumbo_max;	/* max packets to stick into a jumbo packet [AFS 3.5] */
};

/*****************************************************************************/
/*
 * Kerberos security type-2 challenge packet
 */
struct rxkad_challenge {
	__be32		version;	/* version of this challenge type */
	__be32		nonce;		/* encrypted random number */
	__be32		min_level;	/* minimum security level */
	__be32		__padding;	/* padding to 8-byte boundary */
} __packed;

/*****************************************************************************/
/*
 * Kerberos security type-2 response packet
 */
struct rxkad_response {
	__be32		version;	/* version of this response type */
	__be32		__pad;

	/* encrypted bit of the response */
	struct {
		__be32		epoch;		/* current epoch */
		__be32		cid;		/* parent connection ID */
		__be32		checksum;	/* checksum */
		__be32		securityIndex;	/* security type */
		__be32		call_id[4];	/* encrypted call IDs */
		__be32		inc_nonce;	/* challenge nonce + 1 */
		__be32		level;		/* desired level */
	} encrypted;

	__be32		kvno;		/* Kerberos key version number */
	__be32		ticket_len;	/* Kerberos ticket length  */
} __packed;

/*****************************************************************************/
/*
 * RxRPC-level abort codes
 */
#define RX_CALL_DEAD		-1	/* call/conn has been inactive and is shut down */
#define RX_INVALID_OPERATION	-2	/* invalid operation requested / attempted */
#define RX_CALL_TIMEOUT		-3	/* call timeout exceeded */
#define RX_EOF			-4	/* unexpected end of data on read op */
#define RX_PROTOCOL_ERROR	-5	/* low-level protocol error */
#define RX_USER_ABORT		-6	/* generic user abort */
#define RX_ADDRINUSE		-7	/* UDP port in use */
#define RX_DEBUGI_BADTYPE	-8	/* bad debugging packet type */

/*
 * (un)marshalling abort codes (rxgen)
 */
#define	RXGEN_CC_MARSHAL    -450
#define	RXGEN_CC_UNMARSHAL  -451
#define	RXGEN_SS_MARSHAL    -452
#define	RXGEN_SS_UNMARSHAL  -453
#define	RXGEN_DECODE	    -454
#define	RXGEN_OPCODE	    -455
#define	RXGEN_SS_XDRFREE    -456
#define	RXGEN_CC_XDRFREE    -457

/*
 * Rx kerberos security abort codes
 * - unfortunately we have no generalised security abort codes to say things
 *   like "unsupported security", so we have to use these instead and hope the
 *   other side understands
 */
#define RXKADINCONSISTENCY	19270400	/* security module structure inconsistent */
#define RXKADPACKETSHORT	19270401	/* packet too short for security challenge */
#define RXKADLEVELFAIL		19270402	/* security level negotiation failed */
#define RXKADTICKETLEN		19270403	/* ticket length too short or too long */
#define RXKADOUTOFSEQUENCE	19270404	/* packet had bad sequence number */
#define RXKADNOAUTH		19270405	/* caller not authorised */
#define RXKADBADKEY		19270406	/* illegal key: bad parity or weak */
#define RXKADBADTICKET		19270407	/* security object was passed a bad ticket */
#define RXKADUNKNOWNKEY		19270408	/* ticket contained unknown key version number */
#define RXKADEXPIRED		19270409	/* authentication expired */
#define RXKADSEALEDINCON	19270410	/* sealed data inconsistent */
#define RXKADDATALEN		19270411	/* user data too long */
#define RXKADILLEGALLEVEL	19270412	/* caller not authorised to use encrypted conns */

#endif /* _LINUX_RXRPC_PACKET_H */


text:
package org.activiti.engine.impl.cmd;

import java.io.Serializable;
import java.util.Collection;

import org.activiti.engine.ActivitiIllegalArgumentException;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;

/**

 */
public class DeleteTaskCmd implements Command<Void>, Serializable {

  private static final long serialVersionUID = 1L;
  protected String taskId;
  protected Collection<String> taskIds;
  protected boolean cascade;
  protected String deleteReason;
  protected boolean cancel;

  public DeleteTaskCmd(String taskId, String deleteReason, boolean cascade) {
    this(taskId, deleteReason, cascade, false);

  }

  public DeleteTaskCmd(String taskId, String deleteReason, boolean cascade, boolean cancel) {
    this.taskId = taskId;
    this.cascade = cascade;
    this.deleteReason = deleteReason;
    this.cancel = cancel;
  }

  public DeleteTaskCmd(Collection<String> taskIds, String deleteReason, boolean cascade) {
      this(taskIds,deleteReason,cascade,false);
  }

  public DeleteTaskCmd(Collection<String> taskIds, String deleteReason, boolean cascade, boolean cancel) {
    this.taskIds = taskIds;
    this.cascade = cascade;
    this.deleteReason = deleteReason;
    this.cancel = cancel;
  }

  public Void execute(CommandContext commandContext) {
    if (taskId != null) {
      deleteTask(commandContext, taskId);
    } else if (taskIds != null) {
      for (String taskId : taskIds) {
        deleteTask(commandContext, taskId);
      }
    } else {
      throw new ActivitiIllegalArgumentException("taskId and taskIds are null");
    }

    return null;
  }

  protected void deleteTask(CommandContext commandContext, String taskId) {
    commandContext.getTaskEntityManager().deleteTask(taskId, deleteReason, cascade, cancel);
  }
}


text:
import os
from setuptools import find_packages, setup

# This reads the __version__ variable from cirq/_version.py
__version__ = ''
exec(open('cirq_web/_version.py').read())

name = 'cirq-web'

description = 'Web-based 3D visualization tools for Cirq.'

# README file as long_description.
long_description = open('README.rst', encoding='utf-8').read()

# If CIRQ_PRE_RELEASE_VERSION is set then we update the version to this value.
# It is assumed that it ends with one of `.devN`, `.aN`, `.bN`, `.rcN` and hence
# it will be a pre-release version on PyPi. See
# https://packaging.python.org/guides/distributing-packages-using-setuptools/#pre-release-versioning
# for more details.
if 'CIRQ_PRE_RELEASE_VERSION' in os.environ:
    __version__ = os.environ['CIRQ_PRE_RELEASE_VERSION']
    long_description = (
        "**This is a development version of cirq-web and may be "
        "unstable.**\n\n**For the latest stable release of cirq-web "
        "see**\n`here <https://pypi.org/project/cirq-web>`__.\n\n" + long_description
    )

# Read in requirements
requirements = open('requirements.txt').readlines()
requirements = [r.strip() for r in requirements]

# Sanity check
assert __version__, 'Version string cannot be empty'

requirements += [f'cirq-core=={__version__}']

# Gather all packages from cirq_web, and the dist/ folder from cirq_ts
# which contains all of the bundle files
packs = (
    ['cirq_web']
    + ['cirq_web.' + package for package in find_packages(where='cirq_web')]
    + ['cirq_ts']
)

setup(
    name=name,
    version=__version__,
    url='http://github.com/quantumlib/cirq',
    author='The Cirq Developers',
    author_email='cirq-dev@googlegroups.com',
    python_requires=('>=3.7.0'),
    install_requires=requirements,
    license='Apache 2',
    description=description,
    long_description=long_description,
    packages=packs,
    package_data={'cirq_web': ['dist/*'], 'cirq_ts': ['dist/*.bundle.js']},
)


text:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:title="@string/prefscreen_twitter">
    <PreferenceCategory android:title="@string/prefscreen_twitter_api_key">
        <EditTextPreference
            android:defaultValue=""
            android:key="@string/preference_twitter_consumer_key"
            android:title="@string/prefscreen_twitter_api_key_ck" />
        <EditTextPreference
            android:defaultValue=""
            android:key="@string/preference_twitter_consumer_secret"
            android:title="@string/prefscreen_twitter_api_key_cs" />
    </PreferenceCategory>
    <PreferenceCategory android:title="@string/prefscreen_twitter_account">
        <Preference
            android:key="@string/preference_twitter_accounts_delete"
            android:summary="@string/prefscreen_twitter_account_delete_summary"
            android:title="@string/prefscreen_twitter_account_delete" />
    </PreferenceCategory>
</PreferenceScreen>


text:
@interface ViewController : UIViewController<MKMapViewDelegate,CLLocationManagerDelegate>

@end


text:
namespace PS {
  class Unicode {
  public:
    // Get unicode string associated with glyph.  Set dingbats to true
    // if the font is Zapf Dingbats, or a clone thereof.
    // Returns empty string if the glyph name is undefined.
    static Glib::ustring chars_of_glyph(const std::string &glyph_name,
					bool dingbats = false);

    // Get space-separated list of PostScript glyph names mapping to
    // unicode character string (usually just one character, but
    // PostScript allows for the mapping of one glyph to a sequence of
    // characters).

    // NOTE: this returns an empty string if the chars are not defined
    // in the Adobe glyph list or in the dingbats list.  It does not
    // construct "uni" or "u" forms

    // NOTE ALSO: Glib::ustring's "==" operator is a bit too smart -
    // it considers e.g. "a" and "acircle" or "v" and "fiveroman" to
    // be the same character
    static std::string glyph_name_of_chars(Glib::ustring chars);

  private:
    static bool get_dingbat(const std::string &glyph, Glib::ustring &answer);
    static bool get_adobe(const std::string &glyph, Glib::ustring &answer);
    static bool get_uniform(const std::string &glyph, Glib::ustring &answer);
    static bool get_uform(const std::string &glyph, Glib::ustring &answer);

    // This is my solution to the problem of having a symmetric map
    // where values also can be used as keys for values of the
    // keys. There are probably better solutions, but this one is
    // mine.
    class Glyphs {
    public:
      Glyphs(bool dingbats);
      typedef std::map<std::string, const Glib::ustring*> NameMap;
      typedef std::multimap<Glib::ustring, const std::string*> CodeMap;
      NameMap namemap;
      CodeMap codemap;
    };
    static const Glyphs glyphlist, dingbats;
  };
};

#endif


text: I am an example of how CKEditorWidget should be used


text:
package com.intellij.openapi.projectRoots.impl;

import com.intellij.codeInspection.magicConstant.MagicConstantInspection;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.ProjectJdkTable;
import com.intellij.openapi.projectRoots.SdkType;
import com.intellij.openapi.roots.AnnotationOrderRootType;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.HeavyPlatformTestCase;
import org.intellij.lang.annotations.Language;
import org.jdom.Element;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class ProjectJdkTest extends HeavyPlatformTestCase {
  public void testDoesntCrashOnJdkRootDisappearance() throws Exception {
    VirtualFile nDir = Objects.requireNonNull(LocalFileSystem.getInstance().refreshAndFindFileByIoFile(createTempDir("nroot", true)));
    String nUrl = nDir.getUrl();
    ProjectJdkImpl jdk = WriteCommandAction.runWriteCommandAction(getProject(), (ThrowableComputable<ProjectJdkImpl, Exception>)()->{
      ProjectJdkImpl myJdk = (ProjectJdkImpl)ProjectJdkTable.getInstance().createSdk("my", JavaSdk.getInstance());
      @Language("XML")
      String s = "<jdk version=\"2\">\n" +
                 "  <name value=\"1.8\" />\n" +
                 "  <type value=\"JavaSDK\" />\n" +
                 "  <version value=\"java version "1.8.0_152-ea"\" />\n" +
                 "  <homePath value=\"I:/Java/jdk1.8\" />\n" +
                 "  <roots>\n" +
                 "    <classPath>\n" +
                 "      <root type=\"composite\">\n" +
                 "        <root url=\"" + nUrl + "\" type=\"simple\" />\n" +
                 "      </root>\n" +
                 "    </classPath>\n" +
                 "  </roots>\n" +
                 "  <additional />\n" +
                 "</jdk>\n";
      Element element = JDOMUtil.load(s);
      myJdk.readExternal(element);
      return myJdk;
    });

    try {
      List<String> urls = Arrays.stream(jdk.getRoots(OrderRootType.CLASSES)).peek(v -> assertTrue(v.isValid())).map(VirtualFile::getUrl).collect(Collectors.toList());
      assertOrderedEquals(urls, nUrl);

      delete(nDir);
      assertFalse(nDir.isValid());

      urls = Arrays.stream(jdk.getRoots(OrderRootType.CLASSES)).peek(v -> assertTrue(v.isValid())).map(VirtualFile::getUrl).collect(Collectors.toList());
      assertEmpty(urls);
    }
    finally {
      WriteCommandAction.runWriteCommandAction(getProject(), ()->ProjectJdkTable.getInstance().removeJdk(jdk));
    }
  }

  public void testJdkAnnotationsAttachedAutomaticallyOnJDKCreation() throws Exception {
    ProjectJdkImpl jdk = WriteCommandAction.runWriteCommandAction(getProject(), (ThrowableComputable<ProjectJdkImpl, Exception>)()->
      (ProjectJdkImpl)ProjectJdkTable.getInstance().createSdk("my", JavaSdk.getInstance()));
    ((SdkType)jdk.getSdkType()).setupSdkPaths(jdk);

    try {
      Runnable fix = MagicConstantInspection.getAttachAnnotationsJarFix(getProject());
      assertNull(fix);

      List<VirtualFile> annotations = Arrays.asList(jdk.getRoots(AnnotationOrderRootType.getInstance()));

      assertNotEmpty(annotations);

      VirtualFile internalAnnotationsPath = JavaSdkImpl.internalJdkAnnotationsPath(new ArrayList<>());
      assertContainsElements(annotations, internalAnnotationsPath);
    }
    finally {
      WriteCommandAction.runWriteCommandAction(getProject(), ()->ProjectJdkTable.getInstance().removeJdk(jdk));
    }
  }
}