text:
<?php

namespace Armd\NewsBundle\Controller;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Armd\NewsBundle\Entity\NewsManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Armd\ListBundle\Controller\ListController;
use Armd\MkCommentBundle\Entity\Thread;
use DateTime;
use Armd\UserBundle\Entity\Favorites;
use Armd\UserBundle\Entity\User;
use Armd\NewsBundle\Entity\News;
use Armd\LectureBundle\Entity\LectureManager;

class NewsController extends Controller {
    const DEFAULT_RELATED_LIMIT = 5;
    const PALETTE_COLOR_HEX = '#95BD59';
    const DEFAULT_LIST_LIMIT = 10;

    private $palette_color = 'palette-color-1';
    private $palette_background = 'palette-background-1';
    private $palette_favoritesIcon = 'palette-favoritesIcon-1';
    private $palette_favoritesIconAdded = 'palette-favoritesIconAdded-1';

    /**
     * @param $date
     * @Template("ArmdNewsBundle:News:mainpageWidget.html.twig")
     * @return array
     */
    public function mainpageWidgetAction($date = '') {
        $items = $this->getNewsRepository()->findForMainPage($date, 5);

        return array('items' => $items);
    }

    /**
     * @Route("/news-sidebar-widget", name="armd_news_sidebar_index_widget", options={"expose"=true})
     * @Template("ArmdNewsBundle:NewsNew:sidebarIndexWidget.html.twig")
     */
    public function sidebarIndexWidgetAction() {
        return array();
    }

    /**
     * @param $objects
     * @Template("ArmdNewsBundle:NewsNew:sidebarLinkedNewsWidget.html.twig")
     * @return array
     */
    public function sidebarLinkedNewsWidgetAction(array $objects) {
        return array('items' => $objects);
    }

    /**
     * @param $entity
     * @Template("ArmdNewsBundle:NewsNew:sidebarItemWidget.html.twig")
     * @return array
     */
    public function sidebarItemWidgetAction(News $entity) {
        $this->getTagManager()->loadTagging($entity);
        $tags = $entity->getTags();

        $commonTags = array();
        $techTags = array();
        foreach ($tags as $tag) {
            if (preg_match('/^[a-zA-Z]\d+$/', $tag->getName())) { //is technical tag
                $techTags[] = $tag->getName();
            }
            else {
                $commonTags[] = $tag->getName();
            }
        }

        $linkedObjects = array();
        $linkedObjectsQuantity = 0;
        if (count($techTags) > 0) {
            foreach ($techTags as $tagName) {
                $entityType = $tagName[0];
                $entityId = substr($tagName, 1);

                switch ($entityType) {
                    case "s": //special project
                        $linkedObjects['special_projects'][] = $entityId;
                        break;

                    case "n": //news
                        if ($entityId != $entity->getId()) { //if it's not the same entity
                            $linkedObjects['news'][] = $entityId;
                        }
                        break;

                    case "o": //atlas object
                        $linkedObjects['atlas_objects'][] = $entityId;
                        break;

                    case "l": //lecture
                        $linkedObjects['lectures'][] = $entityId;
                        break;

                    default:
                        //do nothing with unknown technical tag!
                }
            }

            //special projects
            //

            //news
            if (isset($linkedObjects['news']) AND (count($linkedObjects['news']) > 0)) {
                $linkedNews = $this->getNewsRepository()->findBy(array('id' => $linkedObjects['news']));
                $newsCount = count($linkedNews);
                if ($newsCount > 0) {
                    $linkedObjects['news'] = $linkedNews;
                    $linkedObjectsQuantity += $newsCount;
                }
            }

            //atlas objects
            if (isset($linkedObjects['atlas_objects']) AND (count($linkedObjects['atlas_objects']) > 0)) {
                $linkedAtlasObjects = $this->getDoctrine()->getRepository('ArmdAtlasBundle:Object')->findBy(array('id' => $linkedObjects['atlas_objects']));
                $atlasObjectsCount = count($linkedAtlasObjects);
                if ($atlasObjectsCount > 0) {
                    $linkedObjects['atlas_objects'] = $linkedAtlasObjects;
                    $linkedObjectsQuantity += $atlasObjectsCount;
                }
            }

            //lectures
            if (isset($linkedObjects['lectures']) AND (count($linkedObjects['lectures']) > 0)) {
                $linkedLectures = $this->getDoctrine()->getRepository('ArmdLectureBundle:Lecture')->findBy(array('id' => $linkedObjects['lectures']));
                $lecturesCount = count($linkedLectures);
                if ($lecturesCount > 0) {
                    $linkedObjects['lectures'] = $linkedLectures;
                    $linkedObjectsQuantity += $lecturesCount;
                }
            }
        }

        $relatedNews = array();
        $relatedObjectsLimit = NewsController::DEFAULT_RELATED_LIMIT - $linkedObjectsQuantity;
        if ($relatedObjectsLimit > 0) {
            $relatedNews = $this->getNewsManager()->findObjects(array(
                NewsManager::CRITERIA_LIMIT => $relatedObjectsLimit,
                NewsManager::CRITERIA_TAGS => $entity->getTags(),
                NewsManager::CRITERIA_RANDOM => true,
                NewsManager::CRITERIA_NOT_IDS => array($entity->getId())
            ));
        }

        $tagsString = implode(', ', $commonTags);
        $techTagsString = implode(', ', $techTags);

        return array(
            'tagsString' => $tagsString,
            'techTagsString' => $techTagsString,
            'linkedObjects' => $linkedObjects,
            'relatedNews' => $relatedNews
        );
    }

    /**
     * @Route("/{category}", name="armd_news_index_by_category", options={"expose"=true}, requirements={"category" = "[a-z]+"}, defaults={"category" = null})
     * @Route("/news-video", name="armd_lecture_news_index", options={"expose"=true}, defaults={"category" = "news-video"})
     * @Template("ArmdNewsBundle:NewsNew:index.html.twig")
     */
    function newsIndexAction($category = null) { //TODO: should be renamed to '$categorySlug'
        $request = $this->getRequest();
        $searchQuery = $request->get('search_query');

        $categoryRepository = $this->getDoctrine()->getRepository('ArmdNewsBundle:Category');
        $categories = $categoryRepository->findAll();

        return array(
            'category' => $category,
            'categories' => $categories,
            'currentCategory' => $category,
            'palette_color' => $this->palette_color,
            'palette_color_hex' => NewsController::PALETTE_COLOR_HEX,
            'searchQuery' => $searchQuery
        );
    }

    /**
     * @Route("/index-list/{category}", name="armd_news_index_list", options={"expose"=true}, requirements={"category" = "[a-z]+"}, defaults={"category" = null})
     * @Template("ArmdNewsBundle:NewsNew:indexList.html.twig")
     */
    function newsIndexListAction($category = null) {
        $request = $this->getRequest();

        $offset = $request->get('offset');
        $searchQuery = $request->get('searchQuery');

        //$category = $categorySlug ? $categoryRepository->findOneBySlug($categorySlug) : null;
        //$category = $category ? array($category) : array('news', 'interviews', 'reportages', 'articles'); //TODO: weird!

        //$newsByDate = array();

        //if ($request->query->has('to_date') || $request->query->has('from_date')) {
        //    $criteria = array(
        //        NewsManager::CRITERIA_LIMIT => 100
        //    );

        //    if ($request->query->has('from_date')) {
        //        $criteria[NewsManager::CRITERIA_NEWS_DATE_SINCE] = new \DateTime($request->get('from_date'));
        //    }
        //    if ($request->query->has('to_date')) {
        //        $criteria[NewsManager::CRITERIA_NEWS_DATE_TILL] = new \DateTime($request->get('to_date'));
        //    }

        //    $news = $newsManager->findObjects($criteria);
        //    $newsByDate = $this->getDateGroupedNews($category, $news);
        //}
        //else { //the default way
        //$firstLoadedDate = new \DateTime($request->get('first_loaded_date')); //at first get minimal date

        //if ($request->query->has('first_loaded_date')) {
        //    $firstLoadedDate->sub(new \DateInterval('P1D'))->setTime(0, 0);
        //}

        $criteria = array(
            NewsManager::CRITERIA_CATEGORY_SLUGS_OR => $category,
            //NewsManager::CRITERIA_NEWS_DATE_TILL => $firstLoadedDate,
            NewsManager::CRITERIA_LIMIT => self::DEFAULT_LIST_LIMIT,
            NewsManager::CRITERIA_OFFSET => $offset,
            NewsManager::CRITERIA_ORDER_BY => array('newsDate' => 'DESC')
        );

        if ($searchQuery) {
            $criteria[NewsManager::CRITERIA_SEARCH_STRING] = $searchQuery;
        }

        //if (count($news) > 0) {
        // this is low date
        //    $criteria[NewsManager::CRITERIA_NEWS_DATE_SINCE] = $news[count($news) - 1]->getNewsDate();

        // now get news
        //    unset($criteria[NewsManager::CRITERIA_LIMIT]);
        //    $news = $newsManager->findObjects($criteria);
        //    $newsByDate = $this->getDateGroupedNews($category, $news);
        //}
        //}

        $news = $this->getNewsManager()->findObjects($criteria);

        return array('news' => $news);
    }

    /**
     * @Route("/news-video/list", name="armd_lecture_news_list", options={"expose"=true})
     * @Template("ArmdNewsBundle:NewsNew:indexListVideos.html.twig")
     */
    public function newsIndexListVideosAction() {
        $request = $this->getRequest();
        $lecturesManager = $this->get('armd_lecture.manager.lecture');

        $offset = $request->get('offset');
        $searchQuery = $request->get('searchQuery');

        $criteria = array(
            LectureManager::CRITERIA_SUPER_TYPE_CODES_OR => array('LECTURE_SUPER_TYPE_NEWS'),
            LectureManager::CRITERIA_LIMIT => self::DEFAULT_LIST_LIMIT,
            LectureManager::CRITERIA_ORDER_BY => array('createdAt' => 'DESC')
        );

        if ($offset) {
            $criteria[LectureManager::CRITERIA_OFFSET] = $offset;
        }

        if ($searchQuery) {
            $criteria[LectureManager::CRITERIA_SEARCH_STRING] = $searchQuery;
        }

        $lectures = $lecturesManager->findObjects($criteria);

        $lecturesByMonth = array();
        foreach ($lectures as $entity) {
            $date = $entity->getCreatedAt()->format('Y-m');
            if (!isset($lecturesByMonth[$date])) {
                $lecturesByMonth[$date] = array();
            }
            $lecturesByMonth[$date][] = $entity;
        }

        return array('lecturesByMonth' => $lecturesByMonth);
    }

    /**
     * @Route("/{id}", requirements={"id" = "\d+"}, name="armd_news_item_by_category", options={"expose"=true})
     * @Template("ArmdNewsBundle:NewsNew:item.html.twig")
     */
    function newsItemAction($id) {
        $categoryRepository = $this->getDoctrine()->getRepository('ArmdNewsBundle:Category');
        $categories = $categoryRepository->findAll();

        $entityManager = $this->getDoctrine()->getManager();
        $entity = $entityManager->getRepository('ArmdNewsBundle:News')->findOneBy(array('id' => $id, 'published' => true));
        if (!$entity) {
            throw $this->createNotFoundException(sprintf('Unable to find record %d', $id));
        }
        $this->getTagManager()->loadTagging($entity);

        $favoritesManager = $this->get('armd_favorites_manager');
        $isInFavorites = $favoritesManager->entityIsInFavorites(Favorites::TYPE_MEDIA, $entity->getId());

        $commentsIntegrator = $this->get('armd_comments_integrator');
        $isCommentable = $commentsIntegrator->entityIsCommentable($entity);

        return array(
            'entity' => $entity,
            'isInFavorites' => $isInFavorites,
            'categories' => $categories,
            'palette_color_hex' => NewsController::PALETTE_COLOR_HEX,
            'palette_color' => $this->palette_color,
            'palette_favoritesIcon' => $this->palette_favoritesIcon,
            'palette_favoritesIconAdded' => $this->palette_favoritesIconAdded,
            'palette_background' => $this->palette_background,
            'isCommentable' => $isCommentable
        );
    }

    /**
     * @return \Armd\TagBundle\Entity\TagManager
     */
    private function getTagManager() {
        return $this->get('fpn_tag.tag_manager');
    }

    /**
     * @return \Armd\NewsBundle\Entity\NewsManager
     */
    private function getNewsManager() {
        return $this->get('armd_news.manager.news');
    }

    /**
     * @return \Armd\NewsBundle\Repository\NewsRepository
     */
    private function getNewsRepository() {
        return $this->getDoctrine()->getRepository('ArmdNewsBundle:News');
    }

    /**
     * @Route(
     *  "/text-search-result",
     *  name="armd_news_text_search_result",
     *  options={"expose"=true}
     * )
     * @Template("ArmdNewsBundle:News:text_search_result.html.twig")
     */
    public function textSearchResultAction() {
        $request = $this->getRequest();

        $criteria = array(
            NewsManager::CRITERIA_SEARCH_STRING => $request->get('search_query'),
            NewsManager::CRITERIA_CATEGORY_SLUGS_OR => array($request->get('category_slug')),
            NewsManager::CRITERIA_LIMIT => 20,
            NewsManager::CRITERIA_OFFSET => $request->get('offset')
        );

        $news = $this->getNewsManager()->findObjects($criteria);

        return array(
            'news' => $news
        );
    }

    /**
     * @Route("/two-column-news-list/{category}", name="armd_news_two_column_list", defaults={"category"=null}, options={"expose"=true})
     */
    function twoColumnNewsListAction($category = null, $limit = null) { //TODO: this thing is used by name alias and is now BROKEN!
        //
    }

    public function lastAnnounceAction() {
        $entity = $this->getDoctrine()->getManager()->getRepository('ArmdNewsBundle:News')->getLastAnnounce();

        return $this->render(
            'ArmdNewsBundle:Default:lastAnnounce.html.twig',
            array(
                'entity' => $entity
            )
        );
    }

    /**
     * @param int $count
     *
     * @return array
     */
    private function getNewsFeed($count = 30) {
        return $this->getNewsManager()->findObjects(
            array(
                NewsManager::CRITERIA_CATEGORY_SLUGS_OR => array('news', 'interviews', 'reportages', 'articles'),
                NewsManager::CRITERIA_LIMIT => $count
            )
        );
    }

    /**
     * @Route("/widget/", defaults={"_format"="js"}, name="armd_news_widget")
     */
    function widgetAction() {
        $count = $this->getRequest()->get('count', 3);

        // Validate...
        if (!in_array($count, array(1, 3, 5))) {
            $count = 3; // Default.
        }

        $news = $this->getNewsFeed($count);

        return $this->render('ArmdNewsBundle:News:widget.js.twig', array(
            'newsList' => $news
        ));
    }

    /**
     * @Route("/get-widget/", name="armd_news_get_widget")
     */
    function getWidgetAction() {
        return $this->render('ArmdNewsBundle:News:get_widget.html.twig');
    }

    /**
     * @Route("/rss/", defaults={"_format"="xml"}, name="armd_news_rss")
     */
    function rssAction() {
        $news = $this->getNewsFeed();

        return $this->render('ArmdNewsBundle:News:rss.xml.twig', array(
            'news' => $news
        ));
    }

    /**
     * @Route("/map/", name="armd_news_map")
     * @Template()
     */
    public function mapAction() {
        $em = $this->getDoctrine()->getManager();
        $regionsRepo = $em->getRepository('ArmdAtlasBundle:Region');
        $regions = $regionsRepo->findBy(array(), array('title'=>'ASC'));
        if (! $regions)
            throw new NotFoundHttpException("Regions not found");

        $categories = $this->getNewsManager()->getCategories();
        if (! $categories)
            throw new NotFoundHttpException("Categories not found");

        $lastNews = $this->getNewsManager()->findObjects(
            array(
                NewsManager::CRITERIA_LIMIT => 5
            )
        );
        $themes = $this->getNewsManager()->getThemes();
        if (! $themes)
            throw new NotFoundHttpException("Themes not found");

        $dateFrom = new \DateTime('-1 month');
        $dateTo   = new \DateTime('+13 month');
        $dateFromStr = $dateFrom->format('d.m.Y');
        $dateToStr   = $dateTo->format('d.m.Y');
        return array(
            'regions' => $regions,
            'categories' => $categories,
            'themes' => $themes,
            'lastNews' => $lastNews,
            'dateFrom' => $dateFromStr,
            'dateTo' => $dateToStr,
        );
    }

    /**
     * @Route("/map/filter", name="armd_news_filter", defaults={"_format"="json"})
     */
    public function filterAction() {
        try {
            $filter = $this->getRequest()->get('f');

            $criteria = array(
                NewsManager::CRITERIA_IS_ON_MAP => true,
                //NewsManager::CRITERIA_HAS_IMAGE => true,
                NewsManager::CRITERIA_EVENT_DATE_SINCE => empty($filter['date_from']) ? new DateTime : new DateTime($filter['date_from']),
                NewsManager::CRITERIA_EVENT_DATE_TILL  => empty($filter['date_to']) ? new DateTime : new DateTime($filter['date_to']),
            );

            if (!empty($filter['category'])) {
                $criteria[NewsManager::CRITERIA_CATEGORY_IDS_OR] = $filter['category'];
            }
            else {
                throw new \Exception('Выберите хотя бы один тип события.');
            }

            if (!empty($filter['theme']) && $filter['theme'][0] != '') {
                $criteria[NewsManager::CRITERIA_THEME_IDS_OR] = $filter['theme'];
            }

            $news = $this->getNewsManager()->findObjects($criteria);

            $data = array();
            foreach ($news as $article) {
                $imageUrl = $this->get('sonata.media.twig.extension')->path($article->getImage(), 'thumbnail');
                if ($article->getTheme()) {
                    $iconUrl = $this->get('sonata.media.twig.extension')->path($article->getTheme()->getIconMedia(), 'reference');
                }
                else {
                    $iconUrl = '';
                }
                $data[] = array(
                    'id' => $article->getId(),
                    'title' => $article->getTitle(),
                    //'dateFrom' => $row->getDate(),
                    //'dateTo' => $row->getEndDate(),
                    'lon' => $article->getLon(),
                    'lat' => $article->getLat(),
                    'imageUrl' => $imageUrl,
                    'iconUrl' => $iconUrl,
                    'categoryId' => $article->getCategory()->getId(),
                );
            }

            $filter['is_on_map'] = true;

            return array(
                'success' => true,
                'message' => 'OK',
                'result' => array(
                    'filter' => $filter,
                    'data' => $data,
                ),
            );
        }
        catch (\Exception $e) {
            return array(
                'success' => false,
                'message' => $e->getMessage(),
            );
        }
    }

    /**
     * @Route("/map/balloon", name="armd_news_map_balloon")
     * @Template()
     */
    public function balloonAction() {
        try {
            $id = (int) $this->getRequest()->get('id');
            $entity = $this->getDoctrine()->getManager()->getRepository('ArmdNewsBundle:News')->find($id);
            return array('entity' => $entity);
        }
        catch (\Exception $e) {
            print $e->getMessage();
        }
    }

    /**
     * @Route("/billboard-slider/", name="armd_news_billboard_slider")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    function billboardAction() {
        $newsManager = $this->getNewsManager();
        $entities = array();
        foreach ($newsManager->getCategories() as $category) {
            $news = $newsManager->findObjects(array(
                    NewsManager::CRITERIA_HAS_IMAGE => true,
                    NewsManager::CRITERIA_CATEGORY_IDS_OR => array($category->getId()),
                    NewsManager::CRITERIA_LIMIT => 1,
                    NewsManager::CRITERIA_ORDER_BY => array(
                        'showOnMain' => 'DESC',
                        'showOnMainOrd' => 'ASC',
                        'important' => 'DESC',
                        'newsDate' => 'DESC'
                    )
                ));

            if (!empty($news)) {
                $entities[] = $news[0];
            }
        }

        return $this->render('ArmdNewsBundle:News:billboard.html.twig', array(
            'entities' => $entities,
        ));
    }

    /**
     * @Route("/read-also-news/", name="armd_news_read_also_news")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function readAlsoNewsAction() {
        $request = $this->getRequest();
        $entityId = $request->get('id');
        $limit = $request->get('limit', 10);

        $entity = $this->getDoctrine()->getManager()->getRepository('ArmdNewsBundle:News')->find($entityId);

        $this->get('fpn_tag.tag_manager')->loadTagging($entity);

        $categories = array('news', 'articles', 'reportages', 'interviews');

//        $entities = array();
//        foreach ($categories as $category) {
//            $entitiesPart = $this->getNewsManager()->findObjects(
//                array(
//                    NewsManager::CRITERIA_LIMIT => $limit,
//                    NewsManager::CRITERIA_NOT_IDS => array($entity->getId()),
//                    NewsManager::CRITERIA_CATEGORY_SLUGS_OR => array($category),
//                    NewsManager::CRITERIA_TAGS => $entity->getTags(),
//                    NewsManager::CRITERIA_ORDER_BY => array('newsDate' => 'DESC')
//                )
//            );
//            $entities = array_merge($entities, $entitiesPart);
//        }

        $entities = $this->getNewsManager()->findObjects(
            array(
                NewsManager::CRITERIA_LIMIT => $limit,
                NewsManager::CRITERIA_NOT_IDS => array($entity->getId()),
                NewsManager::CRITERIA_CATEGORY_SLUGS_OR => $categories,
                NewsManager::CRITERIA_TAGS => $entity->getTags(),
                NewsManager::CRITERIA_ORDER_BY => array('newsDate' => 'DESC'),
                NewsManager::CRITERIA_TAGS_DONT_PAD_RESULT => true
            )
        );

        return $this->render('ArmdNewsBundle:News:read-also-news.html.twig', array(
            'entities' => $entities,
        ));
    }

    /**
     * @Route("/memorial-events/", name="armd_news_memorial_events")
     */
    function memorialEventsAction() {
        $news = $this->getNewsManager()->findObjects(
            array(
                NewsManager::CRITERIA_CATEGORY_SLUGS_OR => array('memorials'),
                NewsManager::CRITERIA_MEMORIAL_DATE => new \DateTime(),
                NewsManager::CRITERIA_LIMIT => 10
            )
        );

        return $this->render('ArmdNewsBundle:News:memorials.html.twig', array(
            'entities'      => $news
        ));
    }

    /**
     * @param \Armd\MkCommentBundle\Entity\Thread $thread
     * @return \Armd\MkCommentBundle\Entity\Comment
     */
    protected function getComments(Thread $thread = null) {
        if (empty($thread)) {
            return null;
        } else {
            return $this->container->get('fos_comment.manager.comment')->findCommentTreeByThread($thread);
        }
    }

    protected function getControllerName() {
        return 'ArmdNewsBundle:News';
    }

    public function getDateGroupedNews($categories, $news) {
        $newsManager = $this->getNewsManager();

        if (in_array('news', $categories) || 'news' === $categories) {
            $groupedNews = $newsManager->getNewsGroupedByNewsDate($news);
        } else {
            $groupedNews = $newsManager->getNewsGroupedByNewsMonth($news);
        }

        return $groupedNews;
    }

    /**
     * @param string $action
     * @param array $params
     * @return array
     */
    public function getItemsSitemap($action = null, $params = array()) {
        $items = array();

        switch ($action) {
            case 'newsIndexAction': {
                isset($params['category']) or $params['category'] = null;

                $criteria = array(
                    NewsManager::CRITERIA_CATEGORY_SLUGS_OR => $params['category'],
                    NewsManager::CRITERIA_NEWS_DATE_TILL => new \DateTime()
                );

                if ($news = $this->getNewsManager()->findObjects($criteria)) {
                    foreach ($news as $n) {
                        $items[] = array(
                            'loc' => $this->generateUrl('armd_news_item_by_category', array(
                                'id' => $n->getId(),
                                'category' => $n->getCategory()->getSlug()
                            )),
                            'lastmod' => $n->getPublishedAt()
                        );
                    }
                }

                break;
            }
        }

        return $items;
    }
}


text:
<?php

namespace common\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Category;

/**
 * CategorySearch represents the model behind the search form of `common\models\Category`.
 */
class CategorySearch extends Category
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['category_id'], 'integer'],
            [['title', 'parent_category_id', 'description', 'slug'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Category::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->joinWith('parentCategory');

        // grid filtering conditions
        $query->andFilterWhere([
            'category_id' => $this->category_id,
           ]);

        $query->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'description', $this->description])
            ->andFilterWhere(['like', 'slug', $this->slug])
            ->andFilterWhere(['like', 'main_category.title', $this->parent_category_id]);

        return $dataProvider;
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2020 The Tilt Brush Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using UnityEngine;

namespace TiltBrush {

public class LocalModelButton : ModelButton {
  // ReSharper disable once NotAccessedField.Local
  // Buttons in the prefab still have a "..." menu, but it's currently unused
  [SerializeField] private BaseButton m_MenuButton;

  override protected void RequestModelPreloadInternal(string reason) {
    StartCoroutine(m_Model.LoadFullyCoroutine(reason));
  }

  /// We don't want the preload any more; try to tear it down.
  override protected void CancelRequestModelPreload() {
    // Unlike Poly's loads, these loads aren't queued and so can't be just plucked from the queue.
    // So just let it keep going.
  }
}
}  // namespace TiltBrush


text:
layout: blank
---

          Cycle.js

          {% for chapter in site.tags.chapters %}

{% if page.id == chapter.id %}{{ chapter.title }}{% else %}{{ chapter.title }}{% endif %}

          {% endfor %}

{{ page.title }}

          {% if page.path %}
            Edit on GitHub
          {% endif %}

{{ content }}

            {% if page.next %}{% endif %}
            {% if page.previous %}{% endif %}

            {% if page.next %}{% endif %}
            {% if page.previous %}{% endif %}

{% include footer.html %}


text:
'use strict';

var grunt = require('grunt');

/**
 * Fake transport. Instead of sending an email, writes it down to a file...
 */
function FileStubTransport(){}

FileStubTransport.prototype.sendMail = function(emailMessage, callback) {

    var output = "";

    // sendmail strips this header line by itself
    emailMessage.options.keepBcc = true;

    emailMessage.on("data", function(data){
        output += (data || '').toString('utf-8');
    });

    emailMessage.on("error", function(err){
        callback(err);
    });

    emailMessage.on("end", function(){
        var result = {message: output, envelope: emailMessage.getEnvelope(), messageId: emailMessage._messageId};

        grunt.file.write('tmp/' + emailMessage._message.subject, JSON.stringify(result));

        callback(null, result);
    });

    emailMessage.streamMessage();

};

module.exports = FileStubTransport;


text:
using MS.Common.Content;
using MS.Common.Lang;
using MS.Common.System;
using System;
using System.IO;
using System.Reflection;

namespace MS.Common.Reflection
{
   //============================================================
   // <T>组件工具类。</T>
   //
   // @history MAOCY 140414
   //============================================================
   public class RAssembly
   {
      // 日志对象
      private static ILogger _logger = RLogger.Find(typeof(RAssembly));

      //============================================================
      // <T>加载组件资源。</T>
      //
      // @param assembly 组件对象
      // @param name 名称
      // @return 数据流
      //============================================================
      public static Stream LoadResource(Assembly assembly, string name) {
         string path = name.Replace('\\', '.').Replace('/', '.');
         path = assembly.GetName().Name + '.' + path;
         Stream stream = assembly.GetManifestResourceStream(path);
         if(null == stream) {
            throw new FFatalException("Can't load resource from {0}[{1}]", name, path);
         }
         if(_logger.DebugAble) {
            _logger.Debug(null, "LoadResource", "Load resource [{0}]", name);
         }
         return stream;
      }

      //============================================================
      // <T>加载类型资源。</T>
      //
      // @param type 类型对象
      // @return 数据流
      //============================================================
      public static Stream LoadTypeResource(Type type) {
         string resource = type.FullName + RXml.EXTENSION;
         Stream stream = type.Assembly.GetManifestResourceStream(resource);
         if(null == stream) {
            throw new FFatalException("Can't load resource from {0}[{1}]", type.Name, type.FullName);
         }
         if(_logger.DebugAble) {
            _logger.Debug(null, "LoadTypeResource", "Load type resource [{0}]", type.FullName);
         }
         return stream;
      }
   }
}


text:
<?php

namespace Org_Heigl\FileFinderTest\Service;

use Org_Heigl\FileFinder\Service\Tokenlist;
use PHPUnit\Framework\TestCase;

class TokenlistTest extends TestCase
{

    public function testInstantiation()
    {
        $list = new Tokenlist('<?php echo "Hello World";');
        $this->assertAttributeEquals(array(
            array(T_OPEN_TAG, '<?php ', 1),
            array(T_ECHO, 'echo', 1),
            array(T_WHITESPACE, ' ', 1),
            array(T_CONSTANT_ENCAPSED_STRING, '"Hello World"', 1),
            ';',
        ), 'tokenlist', $list);
    }

    public function testInstantiationOfIllegalString()
    {
        $list = new Tokenlist('FooBar Example');
    }

    public function testGettingNamespace()
    {
        $list = new Tokenlist('<?php namespace Foo\bar\baz;');
        $this->assertEquals(array('Foo', 'bar', 'baz'), $list->getNamespace());
    }

    public function testGEttingClassname()
    {
        $list = new Tokenlist('<?php class Foo');
        $this->assertEquals('Foo', $list->getClassName());
    }
}


text:
package com.calebgo.gitstats.generator

import scala.sys.process._
import com.calebgo.gitstats.Config
import org.joda.time.DateTime
import com.github.nscala_time.time.StaticDateTimeFormat

/**
 * Generator for calculating the number of lines in a program.
 */
class LineGenerator(implicit config: Config) extends NormalGenerator {
  override def header: Array[String] = Array("Lines", "Files")

  override def valueForDate(date: DateTime, repository: String): Array[String] = {
    // Get the data from the git repository.
    val formatter = StaticDateTimeFormat forPattern "yyyy-MM-dd HH:MM:SS"
    val dateString = formatter print date
    val hash = ("git -C " + repository + " hash-object -t tree /dev/null").!!.trim
    val dateHash = Seq("git", "-C", repository, "rev-list", "-n1", "--before=\"" + dateString + "\"", "master").!!.trim
    val diffOutput = (Seq("git", "-C", repository, "diff", "--stat", hash, dateHash) #| Seq("tail", "-1")).!!.trim

    val responseRegex = """(\d+).*, (\d+).*""".r
    try {
      val responseRegex(files, lines) = diffOutput

      Array(lines, files)
    }
    catch {
      case e: Exception => Array("0", "0") // There is no data for this day.
    }
  }
}


text:
namespace engine {

TargetHolderSystem::TargetHolderSystem()
    : mScene( Scene::Get() )
{
}

void TargetHolderSystem::Init()
{
    mRemovedActorsSystem = Engine::Get().GetSystem<RemovedActorsSystem>();
}

void TargetHolderSystem::Update( double DeltaTime )
{
    //     for( ActorList_t::iterator it = mScene.GetActors().begin(), e = mScene.GetActors().end(); it != e; ++it )
    //     {
    //        Actor& actor = **it;
    //        Opt<ITargetHolderComponent> targetHolderC=actor.Get<ITargetHolderComponent>();
    //        Opt<Actor> currentTarget(mScene.GetActor(targetHolderC->GetTargetId()));
    //        if (!targetHolderC.IsValid()||!currentTarget.IsValid())
    //        {
    //            continue;
    //        }
    //     }
}

} // namespace engine


text:
declare namespace Serenity {

    interface QuickFilterArgs<TWidget> {
        field?: string;
        widget?: TWidget;
        request?: ListRequest;
        equalityFilter?: any;
        value?: any;
        active?: boolean;
        handled?: boolean;
    }

    interface QuickFilter<TWidget extends Widget<TOptions>, TOptions> {
        field?: string;
        type?: new (element: JQuery, options: TOptions) => TWidget;
        handler?: (h: QuickFilterArgs<TWidget>) => void;
        title?: string;
        options?: TOptions;
        element?: (e: JQuery) => void;
        init?: (w: TWidget) => void;
        separator?: boolean;
        cssClass?: string;
        loadState?: (w: TWidget, state: any) => void;
        saveState?: (w: TWidget) => any;
        displayText?: (w: TWidget, label: string) => string;
    }
}


text:
<?php
namespace Concrete\Core\Package\ItemCategory;

use Concrete\Core\Entity\Package;
use Concrete\Controller\Element\Package\ThemeItemList;
use Concrete\Core\Page\Template;

defined('C5_EXECUTE') or die("Access Denied.");

class PageTemplate extends AbstractCategory
{

    public function getItemCategoryDisplayName()
    {
        return t('Page Templates');
    }

    public function getItemName($template)
    {
        return $template->getPageTemplateDisplayName();
    }

    public function getPackageItems(Package $package)
    {
        Template::getListByPackage($package);
    }

}


text: <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">


text:
package com.longwu.ijkplayer.utlis.permission;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * description:
 * <p/>
 * Created by 曾辉 on 2016/11/12.
 * QQ:240336124
 * Email: 240336124@qq.com
 * Version:1.0
 */
@Target(ElementType.METHOD)// 放在什么位置  ElementType.METHOD 方法上面
@Retention(RetentionPolicy.RUNTIME)// 是编译时检测 还是 运行时检测
public @interface PermissionFail {
    public int requestCode();// 请求码
}


text:
static void (*delay_callback)(int);

void ardno_register_delay_callback(void (*callback)(int)) {
    delay_callback = callback;
}

unsigned long millis() {
    return mc_get_time() / 1000;
}

unsigned long micros() {
    return mc_get_time();
}

void delay(unsigned long millis) {
    delayMicroseconds(millis * 1000);
}

void delayMicroseconds(unsigned int micros) {
    int start_time = mc_get_time();
    while (mc_get_time() < start_time + micros) {
        // Execute callback and then increment time.
        delay_callback(mc_get_time());
        mc_increment_time();
    }
}


text:
{{version}}

{{creator}}

    {{creationDate}}

        {{localize 'CORE.FORM.EDITORS.DOCUMENT.DOWNLOAD'}}


text:
"""Tradfri utility function tests."""
import pytest

from homeassistant.components.tradfri.fan import _from_fan_percentage, _from_fan_speed

@pytest.mark.parametrize(
    "fan_speed, expected_result",
    [
        (0, 0),
        (2, 2),
        (25, 49),
        (50, 100),
    ],
)
def test_from_fan_speed(fan_speed, expected_result):
    """Test that we can convert fan speed to percentage value."""
    assert _from_fan_speed(fan_speed) == expected_result

@pytest.mark.parametrize(
    "percentage, expected_result",
    [
        (1, 2),
        (100, 50),
        (50, 26),
    ],
)
def test_from_percentage(percentage, expected_result):
    """Test that we can convert percentage value to fan speed."""
    assert _from_fan_percentage(percentage) == expected_result


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta name="description" content="dodolan manuk responsive catalog themes built with twitter bootstrap">
    <meta name="keywords" content="responsive, catalog, cart, themes, twitter bootstrap, bootstrap">
    <meta name="author" content="afriq yasin ramadhan">
    <link rel="shortcut icon" href="../img/favicon.png">

    <title>Dodolan Manuk - Responsive catalog Template</title>

    <link href="../css/bootstrap.css" rel="stylesheet">

    <link href="../css/style.css" rel="stylesheet">
    <link href="../css/responsive.css" rel="stylesheet">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            Toggle navigation

          </button>
          Dodolan Manuk

Home

About

Profile

Contact

Price

Order

				Products

Canary

Emprit

					Doro

Doro Pos

Doro Kucir

Doro Belehan

Doro Sungut

Pitik

Cucak Rowo

				Blog

Blog 1

Blog 2

Single 1

Single 2

// blog

Home

Blog

								Lorem ipsum dolor sit amet

								 July 15, 2013
								 Aprik
								 5 Comments

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus quis lectus metus, at posuere neque. Sed pharetra nibh eget orci convallis at posuere leo convallis. Sed blandit augue vitae augue scelerisque bibendum. Vivamus sit amet libero turpis, non venenatis urna. In blandit, odio convallis suscipit venenatis, ante ipsum cursus augue.

Read more »

 Purcase, This, Theme

								Lorem ipsum dolor sit amet

								 July 15, 2013
								 Aprik
								 5 Comments

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus quis lectus metus, at posuere neque. Sed pharetra nibh eget orci convallis at posuere leo convallis. Sed blandit augue vitae augue scelerisque bibendum. Vivamus sit amet libero turpis, non venenatis urna. In blandit, odio convallis suscipit venenatis, ante ipsum cursus augue.

Read more »

 Purcase, This, Theme

								Lorem ipsum dolor sit amet

								 July 15, 2013
								 Aprik
								 5 Comments

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus quis lectus metus, at posuere neque. Sed pharetra nibh eget orci convallis at posuere leo convallis. Sed blandit augue vitae augue scelerisque bibendum. Vivamus sit amet libero turpis, non venenatis urna. In blandit, odio convallis suscipit venenatis, ante ipsum cursus augue.

Read more »

 Purcase, This, Theme

Page 1 of 2

«

1 (current)

2

3

4

5

»

Search

						          <input type="text" class="form-control" placeholder="Keywords :">

						            <button class="btn btn-warning" type="submit">Go!</button>

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus quis lectus metus, at posuere neque. Sed pharetra nibh eget orci convallis at posuere leo convallis. Sed blandit augue vitae augue scelerisque bibendum.

Recent post

												New Article

											 <time>02 May 2013</time>, Oleh admin

												New Article

											 <time>02 May 2013</time>, Oleh admin

												New Article

											 <time>02 May 2013</time>, Oleh admin

Tags

Design

Web

Photography

Graphics

Typography

Art

Film

Video

Text Widget

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus quis lectus metus, at posuere neque. Sed pharetra nibh eget orci convallis at posuere leo convallis. Sed blandit augue vitae augue scelerisque bibendum.

dodolan manuk

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus quis lectus metus,
Lorem ipsum dolor sit amet, consectetur adipiscing elit.

HOME

ABOUT

PROFILE

CONTACT

					Copyright © 2013 Dodolan Manuk All Right Reserved. Made With  by Afriq


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: android.graphics.YuvImage
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ANDROID_GRAPHICS_YUVIMAGE_HPP_DECL
#define J2CPP_ANDROID_GRAPHICS_YUVIMAGE_HPP_DECL

namespace j2cpp { namespace android { namespace graphics { class Rect; } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace io { class OutputStream; } } }

#include <android/graphics/Rect.hpp>
#include <java/io/OutputStream.hpp>
#include <java/lang/Object.hpp>

namespace j2cpp {

namespace android { namespace graphics {

	class YuvImage;
	class YuvImage
		: public object<YuvImage>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)
		J2CPP_DECLARE_METHOD(2)
		J2CPP_DECLARE_METHOD(3)
		J2CPP_DECLARE_METHOD(4)
		J2CPP_DECLARE_METHOD(5)
		J2CPP_DECLARE_METHOD(6)

		explicit YuvImage(jobject jobj)
		: object<YuvImage>(jobj)
		{
		}

		operator local_ref<java::lang::Object>() const;

		YuvImage(local_ref< array<jbyte,1> > const&, jint, jint, jint, local_ref< array<jint,1> > const&);
		jboolean compressToJpeg(local_ref< android::graphics::Rect >  const&, jint, local_ref< java::io::OutputStream >  const&);
		local_ref< array<jbyte,1> > getYuvData();
		jint getYuvFormat();
		local_ref< array<jint,1> > getStrides();
		jint getWidth();
		jint getHeight();
	}; //class YuvImage

} //namespace graphics
} //namespace android

} //namespace j2cpp

#endif //J2CPP_ANDROID_GRAPHICS_YUVIMAGE_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ANDROID_GRAPHICS_YUVIMAGE_HPP_IMPL
#define J2CPP_ANDROID_GRAPHICS_YUVIMAGE_HPP_IMPL

namespace j2cpp {

android::graphics::YuvImage::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

android::graphics::YuvImage::YuvImage(local_ref< array<jbyte,1> > const &a0, jint a1, jint a2, jint a3, local_ref< array<jint,1> > const &a4)
: object<android::graphics::YuvImage>(
	call_new_object<
		android::graphics::YuvImage::J2CPP_CLASS_NAME,
		android::graphics::YuvImage::J2CPP_METHOD_NAME(0),
		android::graphics::YuvImage::J2CPP_METHOD_SIGNATURE(0)
	>(a0, a1, a2, a3, a4)
)
{
}

jboolean android::graphics::YuvImage::compressToJpeg(local_ref< android::graphics::Rect > const &a0, jint a1, local_ref< java::io::OutputStream > const &a2)
{
	return call_method<
		android::graphics::YuvImage::J2CPP_CLASS_NAME,
		android::graphics::YuvImage::J2CPP_METHOD_NAME(1),
		android::graphics::YuvImage::J2CPP_METHOD_SIGNATURE(1),
		jboolean
	>(get_jobject(), a0, a1, a2);
}

local_ref< array<jbyte,1> > android::graphics::YuvImage::getYuvData()
{
	return call_method<
		android::graphics::YuvImage::J2CPP_CLASS_NAME,
		android::graphics::YuvImage::J2CPP_METHOD_NAME(2),
		android::graphics::YuvImage::J2CPP_METHOD_SIGNATURE(2),
		local_ref< array<jbyte,1> >
	>(get_jobject());
}

jint android::graphics::YuvImage::getYuvFormat()
{
	return call_method<
		android::graphics::YuvImage::J2CPP_CLASS_NAME,
		android::graphics::YuvImage::J2CPP_METHOD_NAME(3),
		android::graphics::YuvImage::J2CPP_METHOD_SIGNATURE(3),
		jint
	>(get_jobject());
}

local_ref< array<jint,1> > android::graphics::YuvImage::getStrides()
{
	return call_method<
		android::graphics::YuvImage::J2CPP_CLASS_NAME,
		android::graphics::YuvImage::J2CPP_METHOD_NAME(4),
		android::graphics::YuvImage::J2CPP_METHOD_SIGNATURE(4),
		local_ref< array<jint,1> >
	>(get_jobject());
}

jint android::graphics::YuvImage::getWidth()
{
	return call_method<
		android::graphics::YuvImage::J2CPP_CLASS_NAME,
		android::graphics::YuvImage::J2CPP_METHOD_NAME(5),
		android::graphics::YuvImage::J2CPP_METHOD_SIGNATURE(5),
		jint
	>(get_jobject());
}

jint android::graphics::YuvImage::getHeight()
{
	return call_method<
		android::graphics::YuvImage::J2CPP_CLASS_NAME,
		android::graphics::YuvImage::J2CPP_METHOD_NAME(6),
		android::graphics::YuvImage::J2CPP_METHOD_SIGNATURE(6),
		jint
	>(get_jobject());
}

J2CPP_DEFINE_CLASS(android::graphics::YuvImage,"android/graphics/YuvImage")
J2CPP_DEFINE_METHOD(android::graphics::YuvImage,0,"<init>","([BIII[I)V")
J2CPP_DEFINE_METHOD(android::graphics::YuvImage,1,"compressToJpeg","(Landroid/graphics/Rect;ILjava/io/OutputStream;)Z")
J2CPP_DEFINE_METHOD(android::graphics::YuvImage,2,"getYuvData","()[B")
J2CPP_DEFINE_METHOD(android::graphics::YuvImage,3,"getYuvFormat","()I")
J2CPP_DEFINE_METHOD(android::graphics::YuvImage,4,"getStrides","()[I")
J2CPP_DEFINE_METHOD(android::graphics::YuvImage,5,"getWidth","()I")
J2CPP_DEFINE_METHOD(android::graphics::YuvImage,6,"getHeight","()I")

} //namespace j2cpp

#endif //J2CPP_ANDROID_GRAPHICS_YUVIMAGE_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
#include <assert.h>
#include <cpprest/http_client.h>

#include "TriggerIterator.h"
#include "Collection.h"
#include "ConnectionHelper.h"
#include "DocumentDBConstants.h"
#include "exceptions.h"

using namespace documentdb;
using namespace std;
using namespace utility;
using namespace web::http;
using namespace web::json;
using namespace web::http::client;

TriggerIterator::TriggerIterator(
	const shared_ptr<const Collection>& collection,
	const string_t& original_query,
	const int page_size,
	const string_t& original_request_uri,
	const string_t& continuation_id,
	const value& buffer)
	: collection_(collection)
	, original_query_(original_query)
	, page_size_(page_size)
	, original_request_uri_(original_request_uri)
	, continuation_id_(continuation_id)
	, buffer_(buffer)
	, current_(0)
{}

TriggerIterator::~TriggerIterator()
{}

bool TriggerIterator::HasMore()
{
	if (current_ < buffer_.as_array().size())
	{
		return true;
	}

	if (continuation_id_.empty())
	{
		return false;
	}

	// Case where we have continuation, but we are not really sure do we have anything more, need to fetch it.
	//
	http_request request = CreateQueryRequest(
		original_query_,
		page_size_,
		RESOURCE_PATH_TRIGGERS,
		collection_->resource_id(),
		collection_->document_db_configuration()->master_key(),
		continuation_id_);
	request.set_request_uri(original_request_uri_);

	http_response response = collection_->document_db_configuration()->http_client().request(request).get();
	value json_response = response.extract_json().get();

	if (response.status_code() == status_codes::OK)
	{
		string_t new_continuation_id = response.headers()[HEADER_MS_CONTINUATION];
		int count = stoi(response.headers()[HEADER_MS_MAX_ITEM_COUNT]);

		buffer_ = json_response.at(RESPONSE_QUERY_TRIGGERS);
		continuation_id_ = new_continuation_id;
		current_ = 0;
		return count > 0;
	}

	ThrowExceptionFromResponse(response.status_code(), json_response);
}

shared_ptr<Trigger> TriggerIterator::Next()
{
	if (current_ < buffer_.as_array().size())
	{
		value trigger_json = buffer_.as_array().at(current_++);
		return collection_->TriggerFromJson(&trigger_json);
	}

	// Did you called hasMore()?
	//
	assert(false);
	throw DocumentDBRuntimeException(_XPLATSTR("Calling Next without checking HasMore before that."));
}


text:
package org.keycloak.broker.saml;

import org.jboss.logging.Logger;
import org.keycloak.broker.provider.AbstractIdentityProvider;
import org.keycloak.broker.provider.AuthenticationRequest;
import org.keycloak.broker.provider.BrokeredIdentityContext;
import org.keycloak.broker.provider.IdentityBrokerException;
import org.keycloak.broker.provider.IdentityProviderDataMarshaller;
import org.keycloak.broker.provider.IdentityProviderMapper;
import org.keycloak.broker.provider.util.SimpleHttp;
import org.keycloak.broker.saml.mappers.UserAttributeMapper;
import org.keycloak.common.util.PemUtils;
import org.keycloak.crypto.Algorithm;
import org.keycloak.crypto.KeyStatus;
import org.keycloak.crypto.KeyUse;
import org.keycloak.dom.saml.v2.assertion.AssertionType;
import org.keycloak.dom.saml.v2.assertion.AuthnStatementType;
import org.keycloak.dom.saml.v2.assertion.NameIDType;
import org.keycloak.dom.saml.v2.assertion.SubjectType;
import org.keycloak.dom.saml.v2.metadata.AttributeConsumingServiceType;
import org.keycloak.dom.saml.v2.metadata.EntityDescriptorType;
import org.keycloak.dom.saml.v2.metadata.LocalizedNameType;
import org.keycloak.dom.saml.v2.metadata.RequestedAttributeType;
import org.keycloak.dom.saml.v2.protocol.AuthnRequestType;
import org.keycloak.dom.saml.v2.protocol.LogoutRequestType;
import org.keycloak.dom.saml.v2.protocol.ResponseType;
import org.keycloak.events.EventBuilder;
import org.keycloak.models.FederatedIdentityModel;
import org.keycloak.models.IdentityProviderMapperModel;
import org.keycloak.models.KeyManager;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.saml.JaxrsSAML2BindingBuilder;
import org.keycloak.protocol.saml.SamlProtocol;
import org.keycloak.protocol.saml.SamlService;
import org.keycloak.protocol.saml.SamlSessionUtils;
import org.keycloak.protocol.saml.mappers.SamlMetadataDescriptorUpdater;
import org.keycloak.protocol.saml.preprocessor.SamlAuthenticationPreprocessor;
import org.keycloak.saml.SAML2AuthnRequestBuilder;
import org.keycloak.saml.SAML2LogoutRequestBuilder;
import org.keycloak.saml.SAML2NameIDPolicyBuilder;
import org.keycloak.saml.SAML2RequestedAuthnContextBuilder;
import org.keycloak.saml.SPMetadataDescriptor;
import org.keycloak.saml.SamlProtocolExtensionsAwareBuilder.NodeGenerator;
import org.keycloak.saml.SignatureAlgorithm;
import org.keycloak.saml.common.constants.GeneralConstants;
import org.keycloak.saml.common.constants.JBossSAMLURIConstants;
import org.keycloak.saml.common.exceptions.ConfigurationException;
import org.keycloak.saml.common.util.DocumentUtil;
import org.keycloak.saml.common.util.StaxUtil;
import org.keycloak.saml.processing.api.saml.v2.request.SAML2Request;
import org.keycloak.saml.processing.api.saml.v2.sig.SAML2Signature;
import org.keycloak.saml.processing.core.saml.v2.writers.SAMLMetadataWriter;
import org.keycloak.saml.processing.core.util.KeycloakKeySamlExtensionGenerator;
import org.keycloak.saml.validators.DestinationValidator;
import org.keycloak.sessions.AuthenticationSessionModel;
import org.keycloak.util.JsonSerialization;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.parsers.ParserConfigurationException;
import java.util.stream.Collectors;
import javax.xml.stream.XMLStreamWriter;

import java.io.StringWriter;
import java.net.URI;
import java.security.KeyPair;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;

/**
 * @author Pedro Igor
 */
public class SAMLIdentityProvider extends AbstractIdentityProvider<SAMLIdentityProviderConfig> {
    protected static final Logger logger = Logger.getLogger(SAMLIdentityProvider.class);

    private final DestinationValidator destinationValidator;
    public SAMLIdentityProvider(KeycloakSession session, SAMLIdentityProviderConfig config, DestinationValidator destinationValidator) {
        super(session, config);
        this.destinationValidator = destinationValidator;
    }

    @Override
    public Object callback(RealmModel realm, AuthenticationCallback callback, EventBuilder event) {
        return new SAMLEndpoint(realm, this, getConfig(), callback, destinationValidator);
    }

    @Override
    public Response performLogin(AuthenticationRequest request) {
        try {
            UriInfo uriInfo = request.getUriInfo();
            RealmModel realm = request.getRealm();
            String issuerURL = getEntityId(uriInfo, realm);
            String destinationUrl = getConfig().getSingleSignOnServiceUrl();
            String nameIDPolicyFormat = getConfig().getNameIDPolicyFormat();

            if (nameIDPolicyFormat == null) {
                nameIDPolicyFormat =  JBossSAMLURIConstants.NAMEID_FORMAT_PERSISTENT.get();
            }

            String protocolBinding = JBossSAMLURIConstants.SAML_HTTP_REDIRECT_BINDING.get();

            String assertionConsumerServiceUrl = request.getRedirectUri();

            if (getConfig().isPostBindingResponse()) {
                protocolBinding = JBossSAMLURIConstants.SAML_HTTP_POST_BINDING.get();
            }

            SAML2RequestedAuthnContextBuilder requestedAuthnContext =
                new SAML2RequestedAuthnContextBuilder()
                    .setComparison(getConfig().getAuthnContextComparisonType());

            for (String authnContextClassRef : getAuthnContextClassRefUris())
                requestedAuthnContext.addAuthnContextClassRef(authnContextClassRef);

            for (String authnContextDeclRef : getAuthnContextDeclRefUris())
                requestedAuthnContext.addAuthnContextDeclRef(authnContextDeclRef);

            Integer attributeConsumingServiceIndex = getConfig().getAttributeConsumingServiceIndex();

            String loginHint = getConfig().isLoginHint() ? request.getAuthenticationSession().getClientNote(OIDCLoginProtocol.LOGIN_HINT_PARAM) : null;
            Boolean allowCreate = null;
            if (getConfig().getConfig().get(SAMLIdentityProviderConfig.ALLOW_CREATE) == null || getConfig().isAllowCreate())
                allowCreate = Boolean.TRUE;
            SAML2AuthnRequestBuilder authnRequestBuilder = new SAML2AuthnRequestBuilder()
                    .assertionConsumerUrl(assertionConsumerServiceUrl)
                    .destination(destinationUrl)
                    .issuer(issuerURL)
                    .forceAuthn(getConfig().isForceAuthn())
                    .protocolBinding(protocolBinding)
                    .nameIdPolicy(SAML2NameIDPolicyBuilder
                        .format(nameIDPolicyFormat)
                        .setAllowCreate(allowCreate))
                    .attributeConsumingServiceIndex(attributeConsumingServiceIndex)
                    .requestedAuthnContext(requestedAuthnContext)
                    .subject(loginHint);

            JaxrsSAML2BindingBuilder binding = new JaxrsSAML2BindingBuilder(session)
                    .relayState(request.getState().getEncoded());
            boolean postBinding = getConfig().isPostBindingAuthnRequest();

            if (getConfig().isWantAuthnRequestsSigned()) {
                KeyManager.ActiveRsaKey keys = session.keys().getActiveRsaKey(realm);

                String keyName = getConfig().getXmlSigKeyInfoKeyNameTransformer().getKeyName(keys.getKid(), keys.getCertificate());
                binding.signWith(keyName, keys.getPrivateKey(), keys.getPublicKey(), keys.getCertificate())
                        .signatureAlgorithm(getSignatureAlgorithm())
                        .signDocument();
                if (! postBinding && getConfig().isAddExtensionsElementWithKeyInfo()) {    // Only include extension if REDIRECT binding and signing whole SAML protocol message
                    authnRequestBuilder.addExtension(new KeycloakKeySamlExtensionGenerator(keyName));
                }
            }

            AuthnRequestType authnRequest = authnRequestBuilder.createAuthnRequest();
            for(Iterator<SamlAuthenticationPreprocessor> it = SamlSessionUtils.getSamlAuthenticationPreprocessorIterator(session); it.hasNext(); ) {
                authnRequest = it.next().beforeSendingLoginRequest(authnRequest, request.getAuthenticationSession());
            }

            if (authnRequest.getDestination() != null) {
                destinationUrl = authnRequest.getDestination().toString();
            }

            // Save the current RequestID in the Auth Session as we need to verify it against the ID returned from the IdP
            request.getAuthenticationSession().setClientNote(SamlProtocol.SAML_REQUEST_ID_BROKER, authnRequest.getID());

            if (postBinding) {
                return binding.postBinding(authnRequestBuilder.toDocument()).request(destinationUrl);
            } else {
                return binding.redirectBinding(authnRequestBuilder.toDocument()).request(destinationUrl);
            }
        } catch (Exception e) {
            throw new IdentityBrokerException("Could not create authentication request.", e);
        }
    }

    private String getEntityId(UriInfo uriInfo, RealmModel realm) {
        String configEntityId = getConfig().getEntityId();

        if (configEntityId == null || configEntityId.isEmpty())
            return UriBuilder.fromUri(uriInfo.getBaseUri()).path("realms").path(realm.getName()).build().toString();
        else
            return configEntityId;
    }

    private List<String> getAuthnContextClassRefUris() {
        String authnContextClassRefs = getConfig().getAuthnContextClassRefs();
        if (authnContextClassRefs == null || authnContextClassRefs.isEmpty())
            return new LinkedList<String>();

        try {
            return Arrays.asList(JsonSerialization.readValue(authnContextClassRefs, String[].class));
        } catch (Exception e) {
            logger.warn("Could not json-deserialize AuthContextClassRefs config entry: " + authnContextClassRefs, e);
            return new LinkedList<String>();
        }
    }

    private List<String> getAuthnContextDeclRefUris() {
        String authnContextDeclRefs = getConfig().getAuthnContextDeclRefs();
        if (authnContextDeclRefs == null || authnContextDeclRefs.isEmpty())
            return new LinkedList<String>();

        try {
            return Arrays.asList(JsonSerialization.readValue(authnContextDeclRefs, String[].class));
        } catch (Exception e) {
            logger.warn("Could not json-deserialize AuthContextDeclRefs config entry: " + authnContextDeclRefs, e);
            return new LinkedList<String>();
        }
    }

    @Override
    public void authenticationFinished(AuthenticationSessionModel authSession, BrokeredIdentityContext context)  {
        ResponseType responseType = (ResponseType)context.getContextData().get(SAMLEndpoint.SAML_LOGIN_RESPONSE);
        AssertionType assertion = (AssertionType)context.getContextData().get(SAMLEndpoint.SAML_ASSERTION);
        SubjectType subject = assertion.getSubject();
        SubjectType.STSubType subType = subject.getSubType();
        if (subType != null) {
            NameIDType subjectNameID = (NameIDType) subType.getBaseID();
            authSession.setUserSessionNote(SAMLEndpoint.SAML_FEDERATED_SUBJECT_NAMEID, subjectNameID.serializeAsString());
        }
        AuthnStatementType authn =  (AuthnStatementType)context.getContextData().get(SAMLEndpoint.SAML_AUTHN_STATEMENT);
        if (authn != null && authn.getSessionIndex() != null) {
            authSession.setUserSessionNote(SAMLEndpoint.SAML_FEDERATED_SESSION_INDEX, authn.getSessionIndex());

        }
    }

    @Override
    public Response retrieveToken(KeycloakSession session, FederatedIdentityModel identity) {
        return Response.ok(identity.getToken()).build();
    }

    @Override
    public void backchannelLogout(KeycloakSession session, UserSessionModel userSession, UriInfo uriInfo, RealmModel realm) {
        String singleLogoutServiceUrl = getConfig().getSingleLogoutServiceUrl();
        if (singleLogoutServiceUrl == null || singleLogoutServiceUrl.trim().equals("") || !getConfig().isBackchannelSupported()) return;
        JaxrsSAML2BindingBuilder binding = buildLogoutBinding(session, userSession, realm);
        try {
            LogoutRequestType logoutRequest = buildLogoutRequest(userSession, uriInfo, realm, singleLogoutServiceUrl);
            if (logoutRequest.getDestination() != null) {
                singleLogoutServiceUrl = logoutRequest.getDestination().toString();
            }
            int status = SimpleHttp.doPost(singleLogoutServiceUrl, session)
                    .param(GeneralConstants.SAML_REQUEST_KEY, binding.postBinding(SAML2Request.convert(logoutRequest)).encoded())
                    .param(GeneralConstants.RELAY_STATE, userSession.getId()).asStatus();
            boolean success = status >=200 && status < 400;
            if (!success) {
                logger.warn("Failed saml backchannel broker logout to: " + singleLogoutServiceUrl);
            }
        } catch (Exception e) {
            logger.warn("Failed saml backchannel broker logout to: " + singleLogoutServiceUrl, e);
        }

    }

    @Override
    public Response keycloakInitiatedBrowserLogout(KeycloakSession session, UserSessionModel userSession, UriInfo uriInfo, RealmModel realm) {
        String singleLogoutServiceUrl = getConfig().getSingleLogoutServiceUrl();
        if (singleLogoutServiceUrl == null || singleLogoutServiceUrl.trim().equals("")) return null;

        if (getConfig().isBackchannelSupported()) {
            backchannelLogout(session, userSession, uriInfo, realm);
            return null;
       } else {
            try {
                LogoutRequestType logoutRequest = buildLogoutRequest(userSession, uriInfo, realm, singleLogoutServiceUrl);
                if (logoutRequest.getDestination() != null) {
                    singleLogoutServiceUrl = logoutRequest.getDestination().toString();
                }
                JaxrsSAML2BindingBuilder binding = buildLogoutBinding(session, userSession, realm);
                if (getConfig().isPostBindingLogout()) {
                    return binding.postBinding(SAML2Request.convert(logoutRequest)).request(singleLogoutServiceUrl);
                } else {
                    return binding.redirectBinding(SAML2Request.convert(logoutRequest)).request(singleLogoutServiceUrl);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    protected LogoutRequestType buildLogoutRequest(UserSessionModel userSession, UriInfo uriInfo, RealmModel realm, String singleLogoutServiceUrl, NodeGenerator... extensions) throws ConfigurationException {
        SAML2LogoutRequestBuilder logoutBuilder = new SAML2LogoutRequestBuilder()
                .assertionExpiration(realm.getAccessCodeLifespan())
                .issuer(getEntityId(uriInfo, realm))
                .sessionIndex(userSession.getNote(SAMLEndpoint.SAML_FEDERATED_SESSION_INDEX))
                .nameId(NameIDType.deserializeFromString(userSession.getNote(SAMLEndpoint.SAML_FEDERATED_SUBJECT_NAMEID)))
                .destination(singleLogoutServiceUrl);
        LogoutRequestType logoutRequest = logoutBuilder.createLogoutRequest();
        for (NodeGenerator extension : extensions) {
            logoutBuilder.addExtension(extension);
        }
        for (Iterator<SamlAuthenticationPreprocessor> it = SamlSessionUtils.getSamlAuthenticationPreprocessorIterator(session); it.hasNext();) {
            logoutRequest = it.next().beforeSendingLogoutRequest(logoutRequest, userSession, null);
        }
        return logoutRequest;
    }

    private JaxrsSAML2BindingBuilder buildLogoutBinding(KeycloakSession session, UserSessionModel userSession, RealmModel realm) {
        JaxrsSAML2BindingBuilder binding = new JaxrsSAML2BindingBuilder(session)
                .relayState(userSession.getId());
        if (getConfig().isWantAuthnRequestsSigned()) {
            KeyManager.ActiveRsaKey keys = session.keys().getActiveRsaKey(realm);
            String keyName = getConfig().getXmlSigKeyInfoKeyNameTransformer().getKeyName(keys.getKid(), keys.getCertificate());
            binding.signWith(keyName, keys.getPrivateKey(), keys.getPublicKey(), keys.getCertificate())
                    .signatureAlgorithm(getSignatureAlgorithm())
                    .signDocument();
        }
        return binding;
    }

    @Override
    public Response export(UriInfo uriInfo, RealmModel realm, String format) {
        try
        {
            URI authnBinding = JBossSAMLURIConstants.SAML_HTTP_REDIRECT_BINDING.getUri();

            if (getConfig().isPostBindingAuthnRequest()) {
                authnBinding = JBossSAMLURIConstants.SAML_HTTP_POST_BINDING.getUri();
            }

            URI endpoint = uriInfo.getBaseUriBuilder()
                    .path("realms").path(realm.getName())
                    .path("broker")
                    .path(getConfig().getAlias())
                    .path("endpoint")
                    .build();

            boolean wantAuthnRequestsSigned = getConfig().isWantAuthnRequestsSigned();
            boolean wantAssertionsSigned = getConfig().isWantAssertionsSigned();
            boolean wantAssertionsEncrypted = getConfig().isWantAssertionsEncrypted();
            String entityId = getEntityId(uriInfo, realm);
            String nameIDPolicyFormat = getConfig().getNameIDPolicyFormat();

            List<Element> signingKeys = new LinkedList<>();
            List<Element> encryptionKeys = new LinkedList<>();

            session.keys().getKeysStream(realm, KeyUse.SIG, Algorithm.RS256)
                    .filter(Objects::nonNull)
                    .filter(key -> key.getCertificate() != null)
                    .sorted(SamlService::compareKeys)
                    .forEach(key -> {
                        try {
                            Element element = SPMetadataDescriptor
                                    .buildKeyInfoElement(key.getKid(), PemUtils.encodeCertificate(key.getCertificate()));
                            signingKeys.add(element);

                            if (key.getStatus() == KeyStatus.ACTIVE) {
                                encryptionKeys.add(element);
                            }
                        } catch (ParserConfigurationException e) {
                            logger.warn("Failed to export SAML SP Metadata!", e);
                            throw new RuntimeException(e);
                        }
                    });

            // Prepare the metadata descriptor model
            StringWriter sw = new StringWriter();
            XMLStreamWriter writer = StaxUtil.getXMLStreamWriter(sw);
            SAMLMetadataWriter metadataWriter = new SAMLMetadataWriter(writer);

            EntityDescriptorType entityDescriptor = SPMetadataDescriptor.buildSPdescriptor(
                authnBinding, authnBinding, endpoint, endpoint,
                wantAuthnRequestsSigned, wantAssertionsSigned, wantAssertionsEncrypted,
                entityId, nameIDPolicyFormat, signingKeys, encryptionKeys);

            // Create the AttributeConsumingService if at least one attribute importer mapper exists
            List<Entry<IdentityProviderMapperModel, SamlMetadataDescriptorUpdater>> metadataAttrProviders = new ArrayList<>();
            realm.getIdentityProviderMappersByAliasStream(getConfig().getAlias())
                .forEach(mapper -> {
                    IdentityProviderMapper target = (IdentityProviderMapper) session.getKeycloakSessionFactory().getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
                    if (target instanceof SamlMetadataDescriptorUpdater)
                        metadataAttrProviders.add(new java.util.AbstractMap.SimpleEntry<>(mapper, (SamlMetadataDescriptorUpdater)target));
                });

            if (!metadataAttrProviders.isEmpty()) {
                int attributeConsumingServiceIndex = getConfig().getAttributeConsumingServiceIndex() != null ? getConfig().getAttributeConsumingServiceIndex() : 1;
                String attributeConsumingServiceName = getConfig().getAttributeConsumingServiceName();
                //default value for attributeConsumingServiceName
                if (attributeConsumingServiceName == null)
                    attributeConsumingServiceName = realm.getDisplayName() != null ? realm.getDisplayName() : realm.getName() ;
                AttributeConsumingServiceType attributeConsumingService = new AttributeConsumingServiceType(attributeConsumingServiceIndex);
                attributeConsumingService.setIsDefault(true);

                String currentLocale = realm.getDefaultLocale() == null ? "en" : realm.getDefaultLocale();
                LocalizedNameType attributeConsumingServiceNameElement = new LocalizedNameType(currentLocale);
                attributeConsumingServiceNameElement.setValue(attributeConsumingServiceName);
                attributeConsumingService.addServiceName(attributeConsumingServiceNameElement);

                // Look for the SP descriptor and add the attribute consuming service
                for (EntityDescriptorType.EDTChoiceType choiceType : entityDescriptor.getChoiceType()) {
                    List<EntityDescriptorType.EDTDescriptorChoiceType> descriptors = choiceType.getDescriptors();
                    for (EntityDescriptorType.EDTDescriptorChoiceType descriptor : descriptors) {
                        descriptor.getSpDescriptor().addAttributeConsumerService(attributeConsumingService);
                    }
                }

                // Add the attribute mappers
                metadataAttrProviders.forEach(mapper -> {
                    SamlMetadataDescriptorUpdater metadataAttrProvider = mapper.getValue();
                    metadataAttrProvider.updateMetadata(mapper.getKey(), entityDescriptor);
                });
            }

            // Write the metadata and export it to a string
            metadataWriter.writeEntityDescriptor(entityDescriptor);

            String descriptor = sw.toString();

            // Metadata signing
            if (getConfig().isSignSpMetadata())
            {
                KeyManager.ActiveRsaKey activeKey = session.keys().getActiveRsaKey(realm);
                String keyName = getConfig().getXmlSigKeyInfoKeyNameTransformer().getKeyName(activeKey.getKid(), activeKey.getCertificate());
                KeyPair keyPair = new KeyPair(activeKey.getPublicKey(), activeKey.getPrivateKey());

                Document metadataDocument = DocumentUtil.getDocument(descriptor);
                SAML2Signature signatureHelper = new SAML2Signature();
                signatureHelper.setSignatureMethod(getSignatureAlgorithm().getXmlSignatureMethod());
                signatureHelper.setDigestMethod(getSignatureAlgorithm().getXmlSignatureDigestMethod());

                Node nextSibling = metadataDocument.getDocumentElement().getFirstChild();
                signatureHelper.setNextSibling(nextSibling);

                signatureHelper.signSAMLDocument(metadataDocument, keyName, keyPair, CanonicalizationMethod.EXCLUSIVE);

                descriptor = DocumentUtil.getDocumentAsString(metadataDocument);
            }

            return Response.ok(descriptor, MediaType.APPLICATION_XML_TYPE).build();
        } catch (Exception e) {
            logger.warn("Failed to export SAML SP Metadata!", e);
            throw new RuntimeException(e);
        }
    }

    public SignatureAlgorithm getSignatureAlgorithm() {
        String alg = getConfig().getSignatureAlgorithm();
        if (alg != null) {
            SignatureAlgorithm algorithm = SignatureAlgorithm.valueOf(alg);
            if (algorithm != null) return algorithm;
        }
        return SignatureAlgorithm.RSA_SHA256;
    }

    @Override
    public IdentityProviderDataMarshaller getMarshaller() {
        return new SAMLDataMarshaller();
    }
}


text:
package cn.ctodb.push.server.test;

import cn.ctodb.push.server.UserManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.ctodb.push.server.PushServerApp;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = PushServerApp.class)
public class TestUser {
    private Logger logger = LoggerFactory.getLogger(TestRedis.class);

    @Autowired
    private UserManager userManager;

    @Test
    public void before() throws Exception {
        userManager.clearUserOnlineData();
        logger.debug("清理缓存");
    }

    @Test
    public void test() throws Exception {
        logger.debug("模拟添加用户");
//        userManager.on("user001");
//        userManager.on("user002");
//        userManager.on("user003");
//        userManager.on("user004");
//        userManager.on("user005");
//        userManager.on("user001");
//        userManager.on("user001");
    }

    @Test
    public void count() {
        logger.debug("在线人数 : {}", userManager.getOnlineUserNum());
    }

}


text:
"use strict";

var ApplicationController = require('../../../base/ApplicationController');
var workbenchConfig = require('../../../services/workbenchConfig');

module.exports = ApplicationController.extend({

    viewControl: null,

    modelConstructor: ApplicationController.prototype.modelConstructor.extend({
        session: {
            applicationName: {
                type:'string',
                required:true,
                default: 'RuntimeImportExport'
            }
        }
    }),

    events: {
        'click [data-hook="import"]': onClickImport,
        'click [data-hook="export"]': onClickExport
    },

    initialize: function() {
        ApplicationController.prototype.initialize.apply(this, arguments);
        if (this.view) {
            this.viewControl = this.view.viewControl;
            this.model.on('Application:unregister', function() {
                if (this.view) {
                    this.viewControl.itemControl.items.off(null, null, this);
                    this.viewControl.views.off(null, null, this);
                    this.applicationControl.off(null,null, this);
                }
                workbenchConfig.off(null, null, this);
            }, this);
            this.applicationControl.on('register', onRefresh, this);
            this.applicationControl.on('unregister', onRefresh, this);
            this.viewControl.views.on('add', onRefresh, this);
            this.viewControl.views.on('remove', onRefresh, this);
            workbenchConfig.on('change', onRefresh, this);
            onRefresh.bind(this)();
        }
        fileReaderSetup(this);

        this.fileEl = this.queryByHook('import').querySelector('[type="file"]');
        this.fileEl.addEventListener('change', onFileChange.bind(this));
    }

});

function onRefresh() {
    console.log('refresh');
    this.queryByHook('applications').innerHTML = this.applicationControl.applications.length;
    this.queryByHook('views').innerHTML = this.viewControl.views.length;
}

function onClickImport() {}

function onClickExport() {
    generateExport(this);
}

function onFileChange() {
    var scope = this;
    scope.reader.readAsText(scope.fileEl.files.item(0), "UTF-8");
}

function generateExport(scope) {
    var data = {};
    // config
    data.config = workbenchConfig.data;
    // icons
    data.icons = [];
    scope.viewControl.itemControl.items.forEach(function(itemModel) {
        data.icons.push(itemModel.toJSON());
        // data.views.push({
        //     url: viewModel.url,
        //     options: {
        //         scroll: viewModel.scroll,
        //         bounds: {
        //             min: {
        //                 x: viewModel.bounds.min.x,
        //                 y: viewModel.bounds.min.y
        //             },
        //             max: {
        //                 x: viewModel.bounds.max.x,
        //                 y: viewModel.bounds.max.y
        //             }
        //         }
        //     }
        // });
    });
    // views
    data.views = [];
    scope.viewControl.views.forEach(function(viewModel) {
        // ignore view with itemControl (Folder)
        if (!viewModel.itemControl) {
            data.views.push({
                url: viewModel.url,
                options: {
                    scroll: viewModel.scroll,
                    bounds: {
                        min: {
                            x: viewModel.bounds.min.x,
                            y: viewModel.bounds.min.y
                        },
                        max: {
                            x: viewModel.bounds.max.x,
                            y: viewModel.bounds.max.y
                        }
                    }
                }
            });
        }
    });
    data = JSON.stringify(data);
    var url = 'data:application/json;charset=utf8,' + encodeURIComponent(data);
    window.open(url, '_blank');
    window.focus();
    console.log(data);
}

function fileReaderSetup(scope) {
    scope.reader = new FileReader();
    scope.reader.addEventListener('load', function(evt) {
        var data = {
            views: [],
            icons: []
        };
        try {
            data = JSON.parse(evt.target.result);
        } catch (e) {
            console.error('can\'t parse json file');
        }
        workbenchConfig.set(data.config);
        console.log('data.icons', data.icons);
        scope.viewControl.itemControl.items.add(data.icons);
        data.views.forEach(function(viewModel) {
            var options = viewModel.options;
            options.dimension = {
                x: options.bounds.max.x - options.bounds.min.x,
                y: options.bounds.max.y - options.bounds.min.y
            };
            scope.viewControl.openView(viewModel.url, options);
        });
        scope.fileEl.value = null;

    });
    scope.reader.addEventListener('error', function() {
        console.log("error reading file");
    });
}


text:
<?php

namespace Oro\Bundle\UserBundle\Security;

use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface as SecurityUserInterface;

use Oro\Bundle\UserBundle\Entity\User;
use Oro\Bundle\UserBundle\Entity\UserManager;

class UserProvider implements UserProviderInterface
{
    /**
     * @var UserManager
     */
    protected $userManager;

    /**
     * Constructor.
     *
     * @param UserManager $userManager
     */
    public function __construct(UserManager $userManager)
    {
        $this->userManager = $userManager;
    }

    /**
     * {@inheritDoc}
     */
    public function loadUserByUsername($username)
    {
        $user = $this->findUser($username);

        if (!$user) {
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
        }

        return $user;
    }

    /**
     * {@inheritDoc}
     */
    public function refreshUser(SecurityUserInterface $user)
    {
        if (!$user instanceof User) {
            throw new UnsupportedUserException(sprintf('Expected an instance of Oro\Bundle\UserBundle\Entity\User, but got "%s".', get_class($user)));
        }

        if (null === $reloadedUser = $this->userManager->findUserBy(array('id' => $user->getId()))) {
            throw new UsernameNotFoundException(sprintf('User with ID "%d" could not be reloaded.', $user->getId()));
        }

        return $reloadedUser;
    }

    /**
     * {@inheritDoc}
     */
    public function supportsClass($class)
    {
        $userClass = $this->userManager->getClass();

        return $userClass === $class || is_subclass_of($class, $userClass);
    }

    /**
     * Finds a user by username.
     * This method is meant to be an extension point for possible child classes.
     *
     * @param  string    $username
     * @return User|null
     */
    protected function findUser($username)
    {
        return $this->userManager->findUserByUsernameOrEmail($username);
    }
}


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1">
    <meta charset="utf-8">

    <link rel="stylesheet" href="style/style.css">

washing machine

            <svg viewBox="0 0 162 162">
                <circle id="duration-circle" r="71" cy="81" cx="81" />
            </svg>

                idle

                0
                H
                0
                M

            left

        <svg viewBox="0 0 120 120" id="icon-stop">
            <rect x="20" y="20" width="80" height="80" />
        </svg>


text:
#ifndef ALEXA_CLIENT_SDK_CAPABILITYAGENTS_SYSTEM_INCLUDE_SYSTEM_STATEREPORTGENERATOR_H_
#define ALEXA_CLIENT_SDK_CAPABILITYAGENTS_SYSTEM_INCLUDE_SYSTEM_STATEREPORTGENERATOR_H_

#include <array>
#include <memory>
#include <string>

#include <AVSCommon/Utils/PlatformDefinitions.h>
#include <AVSCommon/Utils/Optional.h>
#include <Settings/SettingEventMetadata.h>
#include <Settings/SettingStringConversion.h>
#include <Settings/SettingsManagerBuilderBase.h>

namespace alexaClientSDK {
namespace capabilityAgents {
namespace system {

/**
 * This class is responsible for generating a state report for every setting available in a given @c SettingsManager.
 *
 * @note This class is not thread safe.
 */
class StateReportGenerator {
public:
    /// Alias for the @c SettingsConfigurations of a given @c SettingsManager.
    /// @tparam SettingsManagerT The target settings manager type.
    template <class SettingsManagerT>
    using SettingConfigurations =
        typename settings::SettingsManagerBuilderBase<SettingsManagerT>::SettingConfigurations;

    /**
     * Create a StateReportGenerator for the given manager with the provided configurations.
     *
     * @tparam SettingsManagerT The type of the SettingManager.
     * @param settingManager The manager that exposes the setting states.
     * @param configurations The configurations which hold the metadata to generate the report.
     * @return An optional with a valid StateReportGenerator if it succeeds; an empty optional otherwise.
     */
    template <class SettingsManagerT>
    static avsCommon::utils::Optional<StateReportGenerator> create(
        std::shared_ptr<SettingsManagerT> settingManager,
        const SettingConfigurations<SettingsManagerT>& configurations);

    /**
     * Generate a report for each setting.
     *
     * @return The generated reports.
     */
    std::vector<std::string> generateReport();

    /**
     * Default constructor. This should only be used by optional.
     */
    StateReportGenerator() = default;

protected:
    /**
     * Constructor (protected for unit tests).
     *
     * @param reportFunctions The collection of report functions used to generate the entire report.
     */
    explicit StateReportGenerator(const std::vector<std::function<std::string()>>& reportFunctions);

private:
    /**
     * Utility structure used to wrap each setting into a report generation function.
     *
     * @tparam SettingsManagerT The type of the settings manager.
     * @tparam index The index of the setting being wrapped.
     */
    template <class SettingsManagerT, ssize_t index = SettingsManagerT::NUMBER_OF_SETTINGS - 1>
    struct StringFunctionWrapper {
        /**
         * The operator() which will subscribe the generation function to @c reportFunctions.
         *
         * @param manager The target setting manager.
         * @param configurations The settings configuration for the setting manager.
         * @param reportFunctions Collection of report functions.
         */
        void operator()(
            const std::shared_ptr<SettingsManagerT>& manager,
            const SettingConfigurations<SettingsManagerT>& configurations,
            std::vector<std::function<std::string()>>& reportFunctions);
    };

    /**
     * Specialization of the @c StringFunctionWrapper which will stop the recursive setting addition.
     *
     * @tparam SettingsManagerT The type of the settings manager.
     */
    template <class SettingsManagerT>
    struct StringFunctionWrapper<SettingsManagerT, -1> {
        /**
         * The operator() which will subscribe the generation function to @c reportFunctions.
         *
         * @param manager The target setting manager.
         * @param configurations The settings configuration for the setting manager.
         * @param reportFunctions Collection of report functions.
         */
        void operator()(
            const std::shared_ptr<SettingsManagerT>& manager,
            const SettingConfigurations<SettingsManagerT>& configurations,
            std::vector<std::function<std::string()>>& reportFunctions);
    };

    /**
     * The function that generates the report of one setting.
     *
     * @param metadata The metadata with the information need to generate the report.
     * @param value The current value of the setting.
     * @return The state report of a given setting.
     */
    static std::string generateSettingStateReport(
        const settings::SettingEventMetadata& metadata,
        const std::string& value);

    /// The report functions.
    std::vector<std::function<std::string()>> m_reportFunctions;
};

template <class SettingsManagerT>
avsCommon::utils::Optional<StateReportGenerator> StateReportGenerator::create(
    std::shared_ptr<SettingsManagerT> manager,
    const SettingConfigurations<SettingsManagerT>& configurations) {
    if (!manager) {
        avsCommon::utils::logger::acsdkError(
            avsCommon::utils::logger::LogEntry("StateReportGenerator", "createFailed").d("reason", "nullManager"));
        return avsCommon::utils::Optional<StateReportGenerator>();
    }
    std::vector<std::function<std::string()>> reportFunctions;
    StringFunctionWrapper<SettingsManagerT> wrapper;
    wrapper(manager, configurations, reportFunctions);
    return avsCommon::utils::Optional<StateReportGenerator>(StateReportGenerator{reportFunctions});
}

template <class SettingsManagerT, ssize_t index>
void StateReportGenerator::StringFunctionWrapper<SettingsManagerT, index>::operator()(
    const std::shared_ptr<SettingsManagerT>& settingsManager,
    const SettingConfigurations<SettingsManagerT>& configurations,
    std::vector<std::function<std::string()>>& reportFunctions) {
    if (std::get<index>(configurations).metadata.hasValue()) {
        auto metadata = std::get<index>(configurations).metadata.value();
        reportFunctions.push_back([settingsManager, metadata] {
            return generateSettingStateReport(metadata, settingsManager->template getJsonValue<index>());
        });
    }

    StringFunctionWrapper<SettingsManagerT, index - 1> wrapper;
    wrapper(settingsManager, configurations, reportFunctions);
}

template <class SettingsManagerT>
void StateReportGenerator::StringFunctionWrapper<SettingsManagerT, -1>::operator()(
    const std::shared_ptr<SettingsManagerT>& settingsManager,
    const SettingConfigurations<SettingsManagerT>& configurations,
    std::vector<std::function<std::string()>>& reportFunctions) {
    // Do nothing. This is the end of the loop.
}

}  // namespace system
}  // namespace capabilityAgents
}  // namespace alexaClientSDK

#endif  // ALEXA_CLIENT_SDK_CAPABILITYAGENTS_SYSTEM_INCLUDE_SYSTEM_STATEREPORTGENERATOR_H_


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>Name Property</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Nini Library API Reference - http://nini.sourceforge.net/

IConfig.Name Property

 Gets or sets the IConfig name. If set then it renames this config with the parent source.

        string Name {get; set;}

See Also

        IConfig Interface | Nini.Config Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="Name property">
        </param>
        <param name="Keyword" value="Name property, IConfig interface">
        </param>
        <param name="Keyword" value="IConfig.Name property">
        </param>
      </object>

          Copyright (c) 2006 Brent R. Matzelle


text:
layout: post
title: "Iowa Liqour Sales"
date: 2016-10-12
excerpt: "Exploratory Data Analysis"
tags: [EDA, GA]
comments: false
---

Problem Statement

Given 2015 and 2016 Iowa liquor sales data, determine the best locations for a new storefront.

Risks and Assumptions

The team assumed that the best place to build a new store would be near stores that are performing well, but a store can perform well for several different reasons. They can have very high advertising budgets, could have monopolies on certain areas (maybe a University only allows 2 liquor stores near campus), great supply chain management, etc. To determine which location in Iowa we looked at County for the main predictor. This is because we wanted to start broad and then hone in on a specific city. All of subsequent information is dependent upon data form 2015 and Q1 2016, which is assumed to be representative of the larger data set of 2.7 million transactions. There were also several errors in the original dataset, but a majority of the data was able to be cleaned up.

Data Analysis

First, the current information was evaluated to see which stores had the highest sales and where they were located.

To determine where the client should build a new store, 'Profit per Store' was evaluated (the top 10 counties shown in graph). Johnson county had the highest profit per store followed by Polk, Scott, Dallas, Woodbury, Cerro Gordo, Dickinson, Howard, Kossuth, and Linn. To make sure the recommendation was not too risky, building a store in a county that had very few stores was prioritized. For example, if a county only had 1 store but a high average profit per store then it may indicated there wasn't a big enough market.

Des Moines had the two highest performing stores (2633 and 4829) which had total sales of $407,000 and $363,000 respectively. There is over a 50% drop off to the next best store which was in Iowa City and had sales of $177,000 dollars.

A linear regression model was created to predict where sales would be highest in the future based on 'County', 'State Bottle Retail' and 'Bottles Sold'. 2015 data was used as training data to predict what sales would be like in 2016.

In order to achieve our main goal of determining where the best performing stores are, we plotted the top 10 counties with the highest sales.

Taking it one step further, the sales were evaluated to show average sales were per store in those counties. After correcting to show the results per store, we found that sales per store did not vary nearly as much as sales per county.

The top 10 counties with the highest total of stores are Polk (207), Linn (101), Black Hawk (73), Scott (66), Johnson (53), Pottawattamie (53), Dubuque (40), Story (38), Woodbury (38), and Des Moines(21). So while Dallas had the 3rd highest profit per store, we'd be reluctant to build there since they don't have many stores (17).

Conclusion

Polk seems like a great place to build a new store since there are already 207 stores and it still has 2nd highest profit per store. If we built the 208th store, we'd expect for their to be a minimal decrease on the profit per store average in the county whereas if we built in Dallas we'd expect a more significant decline. Other counties that appear to be great locations to build a new store are Johnson ($130,000/store, 53 stores) and Scott ($125,000/store, 66 stores).

Find Jupyter Notebook for this project here


text:
<?php

namespace yiiunit\framework\di\stubs;

use yii\base\BaseObject;

class Kappa extends BaseObject
{
    public function __construct(Unknown $unknown)
    {
    }
}


text:
<?php

namespace Ups\Entity;

use DOMDocument;
use DOMElement;
use Ups\NodeInterface;

class FreightCharges implements NodeInterface
{
    protected $monetaryValue;

    public function __construct($response = null)
    {
        if (null !== $response) {
            if (isset($response->MonetaryValue)) {
                $this->setMonetaryValue($response->MonetaryValue);
            }
        }
    }

    /**
     * @param null|DOMDocument $document
     *
     * @return DOMElement
     */
    public function toNode(DOMDocument $document = null)
    {
        if (null === $document) {
            $document = new DOMDocument();
        }

        $node = $document->createElement('FreightCharges');
        $node->appendChild($document->createElement('MonetaryValue', $this->getMonetaryValue()));

        return $node;
    }

    /**
     * @return mixed
     */
    public function getMonetaryValue()
    {
        return $this->monetaryValue;
    }

    /**
     * @param $var
     *
     * @throws \Exception
     *
     * @return $this
     */
    public function setMonetaryValue($var)
    {
        $this->monetaryValue = round($var, 2); // Max 2 decimals places

        if ($this->monetaryValue < 0) {
            throw new \Exception('Freight charges cannot be negative');
        }

        if (strlen((string)$this->monetaryValue) > 15) {
            throw new \Exception('Value too long');
        }

        return $this;
    }
}


text:
package edu.nju.util.enums;

/**
 * state of a reservation
 * @author cuihao
 */
public enum ReserveState {
    reserve,checkIn
}


text: SELECT * FROM t5


text:
package com.github.ffpojo.metadata.delimited.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface DelimitedRecord {
	String delimiter() default ",";
}


text:
#include "config.h"
#include "JavaScriptTest.h"
#include "PlatformUtilities.h"
#include "PlatformWebView.h"
#include "Test.h"

namespace TestWebKitAPI {

static bool didFinishLoad;

static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef, const void*)
{
    didFinishLoad = true;
}

static void setPageLoaderClient(WKPageRef page)
{
    WKPageLoaderClient loaderClient;
    memset(&loaderClient, 0, sizeof(loaderClient));
    loaderClient.version = 0;
    loaderClient.didFinishLoadForFrame = didFinishLoadForFrame;

    WKPageSetPageLoaderClient(page, &loaderClient);
}

static WKRetainPtr<WKDataRef> createSessionStateContainingFormData(WKContextRef context)
{
    PlatformWebView webView(context);
    setPageLoaderClient(webView.page());

    WKPageLoadURL(webView.page(), adoptWK(Util::createURLForResource("simple-form", "html")).get());
    Util::run(&didFinishLoad);
    didFinishLoad = false;

    EXPECT_JS_EQ(webView.page(), "submitForm()", "undefined");
    Util::run(&didFinishLoad);
    didFinishLoad = false;

    return adoptWK(WKPageCopySessionState(webView.page(), 0, 0));
}

TEST(WebKit2, RestoreSessionStateContainingFormData)
{
    WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate());

    // FIXME: Once <rdar://problem/8708435> is fixed, we can move the creation of this
    // PlatformWebView after the call to createSessionStaetContainingFormData. Until then, it must
    // remain here to avoid a race condition between the UI and web processes.
    PlatformWebView webView(context.get());
    setPageLoaderClient(webView.page());

    WKRetainPtr<WKDataRef> data = createSessionStateContainingFormData(context.get());
    EXPECT_NOT_NULL(data);

    WKPageRestoreFromSessionState(webView.page(), data.get());
    Util::run(&didFinishLoad);

    EXPECT_TRUE(WKPageCanGoBack(webView.page()));
}

} // namespace TestWebKitAPI