text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik\ReportRenderer;

use Piwik\Common;
use Piwik\Filesystem;
use Piwik\Piwik;
use Piwik\Plugins\API\API;
use Piwik\ReportRenderer;
use Piwik\TCPDF;

/**
 * @see libs/tcpdf
 */
require_once PIWIK_INCLUDE_PATH . '/plugins/ScheduledReports/config/tcpdf_config.php';
require_once PIWIK_INCLUDE_PATH . '/libs/tcpdf/config/lang/eng.php';
require_once PIWIK_INCLUDE_PATH . '/core/TCPDF.php';

/**
 *
 */
class Pdf extends ReportRenderer
{
    const IMAGE_GRAPH_WIDTH_LANDSCAPE = 1050;
    const IMAGE_GRAPH_WIDTH_PORTRAIT = 760;
    const IMAGE_GRAPH_HEIGHT = 220;

    const LANDSCAPE = 'L';
    const PORTRAIT = 'P';

    const MAX_ROW_COUNT = 28;
    const TABLE_HEADER_ROW_COUNT = 6;
    const NO_DATA_ROW_COUNT = 6;
    const MAX_GRAPH_REPORTS = 3;
    const MAX_2COL_TABLE_REPORTS = 2;

    const PDF_CONTENT_TYPE = 'pdf';

    private $reportFontStyle = '';
    private $reportSimpleFontSize = 9;
    private $reportHeaderFontSize = 16;
    private $cellHeight = 6;
    private $bottomMargin = 17;
    private $reportWidthPortrait = 195;
    private $reportWidthLandscape = 270;
    private $minWidthLabelCell = 100;
    private $maxColumnCountPortraitOrientation = 6;
    private $logoWidth = 16;
    private $logoHeight = 16;
    private $totalWidth;
    private $cellWidth;
    private $labelCellWidth;
    private $truncateAfter = 55;
    private $leftSpacesBeforeLogo = 7;
    private $logoImagePosition = array(10, 40);
    private $headerTextColor;
    private $reportTextColor;
    private $tableHeaderBackgroundColor;
    private $tableHeaderTextColor;
    private $tableCellBorderColor;
    private $tableBackgroundColor;
    private $rowTopBottomBorder = array(231, 231, 231);
    private $report;
    private $reportMetadata;
    private $displayGraph;
    private $evolutionGraph;
    private $displayTable;
    private $segment;
    private $reportColumns;
    private $reportRowsMetadata;
    private $currentPage = 0;
    private $reportFont = ReportRenderer::DEFAULT_REPORT_FONT;
    private $TCPDF;
    private $orientation = self::PORTRAIT;

    public function __construct()
    {
        $this->TCPDF = new TCPDF();
        $this->headerTextColor = preg_split("/,/", ReportRenderer::REPORT_TITLE_TEXT_COLOR);
        $this->reportTextColor = preg_split("/,/", ReportRenderer::REPORT_TEXT_COLOR);
        $this->tableHeaderBackgroundColor = preg_split("/,/", ReportRenderer::TABLE_HEADER_BG_COLOR);
        $this->tableHeaderTextColor = preg_split("/,/", ReportRenderer::TABLE_HEADER_TEXT_COLOR);
        $this->tableCellBorderColor = preg_split("/,/", ReportRenderer::TABLE_CELL_BORDER_COLOR);
        $this->tableBackgroundColor = preg_split("/,/", ReportRenderer::TABLE_BG_COLOR);
    }

    public function setLocale($locale)
    {
        switch ($locale) {
            case 'zh-tw':
                $reportFont = 'msungstdlight';
                break;

            case 'ja':
                $reportFont = 'kozgopromedium';
                break;

            case 'zh-cn':
                $reportFont = 'stsongstdlight';
                break;

            case 'ko':
                $reportFont = 'hysmyeongjostdmedium';
                break;

            case 'ar':
                $reportFont = 'almohanad';
                break;

            case 'en':
            default:
                $reportFont = ReportRenderer::DEFAULT_REPORT_FONT;
                break;
        }
        $this->reportFont = $reportFont;
    }

    public function sendToDisk($filename)
    {
        $filename = ReportRenderer::appendExtension($filename, self::PDF_CONTENT_TYPE);
        $outputFilename = ReportRenderer::getOutputPath($filename);

        $this->TCPDF->Output($outputFilename, 'F');

        return $outputFilename;
    }

    public function sendToBrowserDownload($filename)
    {
        $filename = ReportRenderer::appendExtension($filename, self::PDF_CONTENT_TYPE);
        $this->TCPDF->Output($filename, 'D');
    }

    public function sendToBrowserInline($filename)
    {
        $filename = ReportRenderer::appendExtension($filename, self::PDF_CONTENT_TYPE);
        $this->TCPDF->Output($filename, 'I');
    }

    public function getRenderedReport()
    {
        return $this->TCPDF->Output(null, 'S');
    }

    public function renderFrontPage($reportTitle, $prettyDate, $description, $reportMetadata, $segment)
    {
        $reportTitle = $this->formatText($reportTitle);
        $dateRange = $this->formatText(Piwik::translate('General_DateRange') . " " . $prettyDate);

        // footer
        $this->TCPDF->SetFooterFont(array($this->reportFont, $this->reportFontStyle, $this->reportSimpleFontSize));
        $this->TCPDF->SetFooterContent($reportTitle . " | " . $dateRange . " | ");

        // add first page
        $this->TCPDF->setPrintHeader(false);
        $this->TCPDF->AddPage(self::PORTRAIT);
        $this->TCPDF->AddFont($this->reportFont, '', '', false);
        $this->TCPDF->SetFont($this->reportFont, $this->reportFontStyle, $this->reportSimpleFontSize);
        $this->TCPDF->Bookmark(Piwik::translate('ScheduledReports_FrontPage'));

        // logo
        $this->TCPDF->Image(API::getInstance()->getLogoUrl(true), $this->logoImagePosition[0], $this->logoImagePosition[1], 180 / $factor = 2, 0, $type = '', $link = '', $align = '', $resize = false, $dpi = 300);
        $this->TCPDF->Ln(8);

        // report title
        $this->TCPDF->SetFont($this->reportFont, '', $this->reportHeaderFontSize + 5);
        $this->TCPDF->SetTextColor($this->headerTextColor[0], $this->headerTextColor[1], $this->headerTextColor[2]);
        $this->TCPDF->Cell(40, 210, $reportTitle);
        $this->TCPDF->Ln(8 * 4);

        // date and period
        $this->TCPDF->SetFont($this->reportFont, '', $this->reportHeaderFontSize);
        $this->TCPDF->SetTextColor($this->reportTextColor[0], $this->reportTextColor[1], $this->reportTextColor[2]);
        $this->TCPDF->Cell(40, 210, $dateRange);
        $this->TCPDF->Ln(8 * 20);

        // description
        $this->TCPDF->Write(1, $this->formatText($description));

        // segment
        if ($segment != null) {

            $this->TCPDF->Ln();
            $this->TCPDF->Ln();
            $this->TCPDF->SetFont($this->reportFont, '', $this->reportHeaderFontSize - 2);
            $this->TCPDF->SetTextColor($this->headerTextColor[0], $this->headerTextColor[1], $this->headerTextColor[2]);
            $this->TCPDF->Write(1, $this->formatText(Piwik::translate('ScheduledReports_CustomVisitorSegment') . ' ' . $segment['name']));
        }

        $this->TCPDF->Ln(8);
        $this->TCPDF->SetFont($this->reportFont, '', $this->reportHeaderFontSize);
        $this->TCPDF->Ln();
    }

    /**
     * Generate a header of page.
     */
    private function paintReportHeader()
    {
        $isAggregateReport = !empty($this->reportMetadata['dimension']);

        // Graph-only report
        static $graphOnlyReportCount = 0;
        $graphOnlyReport = $isAggregateReport && $this->displayGraph && !$this->displayTable;

        // Table-only report
        $tableOnlyReport = $isAggregateReport
            && !$this->displayGraph
            && $this->displayTable;

        $columnCount = count($this->reportColumns);

        // Table-only 2-column report
        static $tableOnly2ColumnReportCount = 0;
        $tableOnly2ColumnReport = $tableOnlyReport
            && $columnCount == 2;

        // Table-only report with more than 2 columns
        static $tableOnlyManyColumnReportRowCount = 0;
        $tableOnlyManyColumnReport = $tableOnlyReport
            && $columnCount > 3;

        $reportHasData = $this->reportHasData();

        $rowCount = $reportHasData ? $this->report->getRowsCount() + self::TABLE_HEADER_ROW_COUNT : self::NO_DATA_ROW_COUNT;

        // Only a page break before if the current report has some data
        if ($reportHasData &&
            // and
            (
                // it is the first report
                $this->currentPage == 0
                // or, it is a graph-only report and it is the first of a series of self::MAX_GRAPH_REPORTS
                || ($graphOnlyReport && $graphOnlyReportCount == 0)
                // or, it is a table-only 2-column report and it is the first of a series of self::MAX_2COL_TABLE_REPORTS
                || ($tableOnly2ColumnReport && $tableOnly2ColumnReportCount == 0)
                // or it is a table-only report with more than 2 columns and it is the first of its series or there isn't enough space left on the page
                || ($tableOnlyManyColumnReport && ($tableOnlyManyColumnReportRowCount == 0 || $tableOnlyManyColumnReportRowCount + $rowCount >= self::MAX_ROW_COUNT))
                // or it is a report with both a table and a graph
                || !$graphOnlyReport && !$tableOnlyReport
            )
        ) {
            $this->currentPage++;
            $this->TCPDF->AddPage();

            // Table-only reports with more than 2 columns are always landscape
            if ($tableOnlyManyColumnReport) {
                $tableOnlyManyColumnReportRowCount = 0;
                $this->orientation = self::LANDSCAPE;
            } else {
                // Graph-only reports are always portrait
                $this->orientation = $graphOnlyReport ? self::PORTRAIT : ($columnCount > $this->maxColumnCountPortraitOrientation ? self::LANDSCAPE : self::PORTRAIT);
            }

            $this->TCPDF->setPageOrientation($this->orientation, '', $this->bottomMargin);
        }

        $graphOnlyReportCount = ($graphOnlyReport && $reportHasData) ? ($graphOnlyReportCount + 1) % self::MAX_GRAPH_REPORTS : 0;
        $tableOnly2ColumnReportCount = ($tableOnly2ColumnReport && $reportHasData) ? ($tableOnly2ColumnReportCount + 1) % self::MAX_2COL_TABLE_REPORTS : 0;
        $tableOnlyManyColumnReportRowCount = $tableOnlyManyColumnReport ? ($tableOnlyManyColumnReportRowCount + $rowCount) : 0;

        $title = $this->formatText($this->reportMetadata['name']);
        $this->TCPDF->SetFont($this->reportFont, $this->reportFontStyle, $this->reportHeaderFontSize);
        $this->TCPDF->SetTextColor($this->headerTextColor[0], $this->headerTextColor[1], $this->headerTextColor[2]);
        $this->TCPDF->Bookmark($title);
        $this->TCPDF->Cell(40, 15, $title);
        $this->TCPDF->Ln();
        $this->TCPDF->SetFont($this->reportFont, '', $this->reportSimpleFontSize);
        $this->TCPDF->SetTextColor($this->reportTextColor[0], $this->reportTextColor[1], $this->reportTextColor[2]);
    }

    private function reportHasData()
    {
        return $this->report->getRowsCount() > 0;
    }

    private function setBorderColor()
    {
        $this->TCPDF->SetDrawColor($this->tableCellBorderColor[0], $this->tableCellBorderColor[1], $this->tableCellBorderColor[2]);
    }

    public function renderReport($processedReport)
    {
        $this->reportMetadata = $processedReport['metadata'];
        $this->reportRowsMetadata = $processedReport['reportMetadata'];
        $this->displayGraph = $processedReport['displayGraph'];
        $this->evolutionGraph = $processedReport['evolutionGraph'];
        $this->displayTable = $processedReport['displayTable'];
        $this->segment = $processedReport['segment'];
        list($this->report, $this->reportColumns) = self::processTableFormat($this->reportMetadata, $processedReport['reportData'], $processedReport['columns']);

        $this->paintReportHeader();

        if (!$this->reportHasData()) {
            $this->paintMessage(Piwik::translate('CoreHome_ThereIsNoDataForThisReport'));
            return;
        }

        if ($this->displayGraph) {
            $this->paintGraph();
        }

        if ($this->displayGraph && $this->displayTable) {
            $this->TCPDF->Ln(5);
        }

        if ($this->displayTable) {
            $this->paintReportTableHeader();
            $this->paintReportTable();
        }
    }

    private function formatText($text)
    {
        return Common::unsanitizeInputValue($text);
    }

    private function paintReportTable()
    {
        //Color and font restoration
        $this->TCPDF->SetFillColor($this->tableBackgroundColor[0], $this->tableBackgroundColor[1], $this->tableBackgroundColor[2]);
        $this->TCPDF->SetTextColor($this->reportTextColor[0], $this->reportTextColor[1], $this->reportTextColor[2]);
        $this->TCPDF->SetFont('');

        $fill = false;
        $url = false;
        $leftSpacesBeforeLogo = str_repeat(' ', $this->leftSpacesBeforeLogo);

        $logoWidth = $this->logoWidth;
        $logoHeight = $this->logoHeight;

        $rowsMetadata = $this->reportRowsMetadata->getRows();

        // Draw a body of report table
        foreach ($this->report->getRows() as $rowId => $row) {
            $rowMetrics = $row->getColumns();
            $rowMetadata = isset($rowsMetadata[$rowId]) ? $rowsMetadata[$rowId]->getColumns() : array();
            if (isset($rowMetadata['url'])) {
                $url = $rowMetadata['url'];
            }
            foreach ($this->reportColumns as $columnId => $columnName) {
                // Label column
                if ($columnId == 'label') {
                    $isLogoDisplayable = isset($rowMetadata['logo']);
                    $text = '';
                    $posX = $this->TCPDF->GetX();
                    $posY = $this->TCPDF->GetY();
                    if (isset($rowMetrics[$columnId])) {
                        $text = substr($rowMetrics[$columnId], 0, $this->truncateAfter);
                        if ($isLogoDisplayable) {
                            $text = $leftSpacesBeforeLogo . $text;
                        }
                    }
                    $text = $this->formatText($text);

                    $this->TCPDF->Cell($this->labelCellWidth, $this->cellHeight, $text, 'LR', 0, 'L', $fill, $url);

                    if ($isLogoDisplayable) {
                        if (isset($rowMetadata['logoWidth'])) {
                            $logoWidth = $rowMetadata['logoWidth'];
                        }
                        if (isset($rowMetadata['logoHeight'])) {
                            $logoHeight = $rowMetadata['logoHeight'];
                        }
                        $restoreY = $this->TCPDF->getY();
                        $restoreX = $this->TCPDF->getX();
                        $this->TCPDF->SetY($posY);
                        $this->TCPDF->SetX($posX);
                        $topMargin = 1.3;
                        // Country flags are not very high, force a bigger top margin
                        if ($logoHeight < 16) {
                            $topMargin = 2;
                        }
                        $path = Filesystem::getPathToPiwikRoot() . "/" . $rowMetadata['logo'];
                        if (file_exists($path)) {
                            $this->TCPDF->Image($path, $posX + ($leftMargin = 2), $posY + $topMargin, $logoWidth / 4);
                        }
                        $this->TCPDF->SetXY($restoreX, $restoreY);
                    }
                } // metrics column
                else {
                    // No value means 0
                    if (empty($rowMetrics[$columnId])) {
                        $rowMetrics[$columnId] = 0;
                    }
                    $this->TCPDF->Cell($this->cellWidth, $this->cellHeight, $rowMetrics[$columnId], 'LR', 0, 'L', $fill);
                }
            }

            $this->TCPDF->Ln();

            // Top/Bottom grey border for all cells
            $this->TCPDF->SetDrawColor($this->rowTopBottomBorder[0], $this->rowTopBottomBorder[1], $this->rowTopBottomBorder[2]);
            $this->TCPDF->Cell($this->totalWidth, 0, '', 'T');
            $this->setBorderColor();
            $this->TCPDF->Ln(0.2);

            $fill = !$fill;
        }
    }

    private function paintGraph()
    {
        $imageGraph = parent::getStaticGraph(
            $this->reportMetadata,
            $this->orientation == self::PORTRAIT ? self::IMAGE_GRAPH_WIDTH_PORTRAIT : self::IMAGE_GRAPH_WIDTH_LANDSCAPE,
            self::IMAGE_GRAPH_HEIGHT,
            $this->evolutionGraph,
            $this->segment
        );

        $this->TCPDF->Image(
            '@' . $imageGraph,
            $x = '',
            $y = '',
            $w = 0,
            $h = 0,
            $type = '',
            $link = '',
            $align = 'N',
            $resize = false,
            $dpi = 72,
            $palign = '',
            $ismask = false,
            $imgmask = false,
            $order = 0,
            $fitbox = false,
            $hidden = false,
            $fitonpage = true,
            $alt = false,
            $altimgs = array()
        );

        unset($imageGraph);
    }

    /**
     * Draw the table header (first row)
     */
    private function paintReportTableHeader()
    {
        $initPosX = 10;

        // Get the longest column name
        $longestColumnName = '';
        foreach ($this->reportColumns as $columnName) {
            if (strlen($columnName) > strlen($longestColumnName)) {
                $longestColumnName = $columnName;
            }
        }

        $columnsCount = count($this->reportColumns);
        // Computes available column width
        if ($this->orientation == self::PORTRAIT
            && $columnsCount <= 3
        ) {
            $totalWidth = $this->reportWidthPortrait * 2 / 3;
        } else if ($this->orientation == self::LANDSCAPE) {
            $totalWidth = $this->reportWidthLandscape;
        } else {
            $totalWidth = $this->reportWidthPortrait;
        }
        $this->totalWidth = $totalWidth;
        $this->labelCellWidth = max(round(($this->totalWidth / $columnsCount)), $this->minWidthLabelCell);
        $this->cellWidth = round(($this->totalWidth - $this->labelCellWidth) / ($columnsCount - 1));
        $this->totalWidth = $this->labelCellWidth + ($columnsCount - 1) * $this->cellWidth;

        $this->TCPDF->SetFillColor($this->tableHeaderBackgroundColor[0], $this->tableHeaderBackgroundColor[1], $this->tableHeaderBackgroundColor[2]);
        $this->TCPDF->SetTextColor($this->tableHeaderTextColor[0], $this->tableHeaderTextColor[1], $this->tableHeaderTextColor[2]);
        $this->TCPDF->SetLineWidth(.3);
        $this->setBorderColor();
        $this->TCPDF->SetFont($this->reportFont, $this->reportFontStyle);
        $this->TCPDF->SetFillColor(255);
        $this->TCPDF->SetTextColor($this->tableHeaderBackgroundColor[0], $this->tableHeaderBackgroundColor[1], $this->tableHeaderBackgroundColor[2]);
        $this->TCPDF->SetDrawColor(255);

        $posY = $this->TCPDF->GetY();
        $this->TCPDF->MultiCell($this->cellWidth, $this->cellHeight, $longestColumnName, 1, 'C', true);
        $maxCellHeight = $this->TCPDF->GetY() - $posY;

        $this->TCPDF->SetFillColor($this->tableHeaderBackgroundColor[0], $this->tableHeaderBackgroundColor[1], $this->tableHeaderBackgroundColor[2]);
        $this->TCPDF->SetTextColor($this->tableHeaderTextColor[0], $this->tableHeaderTextColor[1], $this->tableHeaderTextColor[2]);
        $this->TCPDF->SetDrawColor($this->tableCellBorderColor[0], $this->tableCellBorderColor[1], $this->tableCellBorderColor[2]);

        $this->TCPDF->SetXY($initPosX, $posY);

        $countColumns = 0;
        $posX = $initPosX;
        foreach ($this->reportColumns as $columnName) {
            $columnName = $this->formatText($columnName);
            //Label column
            if ($countColumns == 0) {
                $this->TCPDF->MultiCell($this->labelCellWidth, $maxCellHeight, $columnName, 1, 'C', true);
                $this->TCPDF->SetXY($posX + $this->labelCellWidth, $posY);
            } else {
                $this->TCPDF->MultiCell($this->cellWidth, $maxCellHeight, $columnName, 1, 'C', true);
                $this->TCPDF->SetXY($posX + $this->cellWidth, $posY);
            }
            $countColumns++;
            $posX = $this->TCPDF->GetX();
        }
        $this->TCPDF->Ln();
        $this->TCPDF->SetXY($initPosX, $posY + $maxCellHeight);
    }

    /**
     * Prints a message
     *
     * @param string $message
     * @return void
     */
    private function paintMessage($message)
    {
        $this->TCPDF->SetFont($this->reportFont, $this->reportFontStyle, $this->reportSimpleFontSize);
        $this->TCPDF->SetTextColor($this->reportTextColor[0], $this->reportTextColor[1], $this->reportTextColor[2]);
        $message = $this->formatText($message);
        $this->TCPDF->Write("1em", $message);
        $this->TCPDF->Ln();
    }

    /**
     * Get report attachments, ex. graph images
     *
     * @param $report
     * @param $processedReports
     * @param $prettyDate
     * @return array
     */
    public function getAttachments($report, $processedReports, $prettyDate)
    {
        return array();
    }
}


text:
<?php

namespace common\tests\unit\lead;

use common\modules\lead\models\forms\AnswerForm;
use common\modules\lead\models\LeadQuestion;
use common\tests\_support\UnitModelTrait;
use common\tests\unit\Unit;
use yii\base\Model;

class AnswerFormTest extends Unit {

	use UnitModelTrait;

	private AnswerForm $model;
	private LeadQuestion $question;

	public function testEmptyAnswerWithRequiredQuestion(): void {
		$this->giveQuestion('Firstname', 'Input firstname');
		$this->question->is_required = true;
		$this->giveModel();
		$this->thenUnsuccessValidate();
		$this->thenSeeError('Firstname cannot be blank.', 'answer');
	}

	public function testRequiredWithAnswer(): void {
		$this->giveQuestion();
		$this->question->is_required = true;
		$this->giveModel();
		$this->model->answer = 'John';
		$this->thenSuccessValidate();
	}

	private function giveQuestion(string $name = 'Firstname', ?string $placeholder = null): void {
		$this->question = new LeadQuestion([
			'name' => $name,
			'placeholder' => $placeholder,
		]);
	}

	private function giveModel(): void {
		$this->model = new AnswerForm($this->question);
	}

	public function getModel(): Model {
		return $this->model;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.keycloak.storage.ldap.mappers;

import org.jboss.logging.Logger;
import org.keycloak.component.ComponentModel;
import org.keycloak.models.*;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.RoleUtils;
import org.keycloak.models.utils.UserModelDelegate;
import org.keycloak.storage.ldap.LDAPStorageProvider;
import org.keycloak.storage.ldap.idm.model.LDAPObject;
import org.keycloak.storage.ldap.idm.query.internal.LDAPQuery;

import java.util.stream.Stream;

/**
 * @author Jean-Loup Maillet
 */
public class HardcodedLDAPGroupStorageMapper extends AbstractLDAPStorageMapper {

    private static final Logger logger = Logger.getLogger(HardcodedLDAPGroupStorageMapper.class);

    public static final String GROUP = "group";

    public HardcodedLDAPGroupStorageMapper(ComponentModel mapperModel, LDAPStorageProvider ldapProvider) {
        super(mapperModel, ldapProvider);
    }

    @Override
    public void beforeLDAPQuery(LDAPQuery query) {
    }

    @Override
    public UserModel proxy(LDAPObject ldapUser, UserModel delegate, RealmModel realm) {
        return new UserModelDelegate(delegate) {

            @Override
            public Stream<GroupModel> getGroupsStream() {
                Stream<GroupModel> groups = super.getGroupsStream();

                GroupModel group = getGroup(realm);
                if (group != null) {
                    return Stream.concat(groups, Stream.of(group));
                }

                return groups;
            }

            @Override
            public boolean isMemberOf(GroupModel group) {
                GroupModel hardcodedGroup = getGroup(realm);
                return super.isMemberOf(group) || (hardcodedGroup != null && RoleUtils.isMember(Stream.of(hardcodedGroup), group));
            }

            @Override
            public void leaveGroup(GroupModel group) {
                if (group.equals(getGroup(realm))) {
                    throw new ModelException("Not possible to delete group. It's hardcoded by LDAP mapper");
                } else {
                    super.leaveGroup(group);
                }
            }

            @Override
            public boolean hasRole(RoleModel role) {
                GroupModel group = getGroup(realm);
                return super.hasRole(role) || (group != null && group.hasRole(role));
            }
        };
    }

    @Override
    public void onRegisterUserToLDAP(LDAPObject ldapUser, UserModel localUser, RealmModel realm) {

    }

    @Override
    public void onImportUserFromLDAP(LDAPObject ldapUser, UserModel user, RealmModel realm, boolean isCreate) {

    }

    private GroupModel getGroup(RealmModel realm) {
        String groupName = mapperModel.getConfig().getFirst(HardcodedLDAPGroupStorageMapper.GROUP);
        GroupModel group = KeycloakModelUtils.findGroupByPath(realm, groupName);
        if (group == null) {
            logger.warnf("Hardcoded group '%s' configured in mapper '%s' is not available anymore");
        }
        return group;
    }
}


text:
# Crumbs [![Build Status](https://travis-ci.org/coreplex/crumbs.svg?branch=master)](https://travis-ci.org/coreplex/crumbs) [![Coverage Status](https://coveralls.io/repos/coreplex/crumbs/badge.svg)](https://coveralls.io/r/coreplex/crumbs)
Framework agnostic breadcrumb container

Installation via composer
-------------------------

The package requires PHP 5.4+, includes a Laravel 5 Service Provider/Facade for quick integration, and abides the FIG standard PSR-4, allowing for a consistent codebase. All Coreplex packages follow these set standards. The repository is also fully unit tested through and continuously integrated through use of [Travis CI](https://travis-ci.org/coreplex/crumbs).

To install Crumbs via composer, simply add it to your composer.json file

```json
"require": {
    "coreplex/crumbs": "~1.0"
},
```

Then run `composer update` via the command line. To automatically add this into your composer json, you can simply run `composer require coreplex/crumbs`, and composer will handle this all for you

The Container
-------------

All breadcrumbs are held in a **Container** class. This allows you to prepare and render a set of breadcrumbs. A container has two dependencies. A `Contracts\Crumb` instance, and a `Contracts\Renderer` instance. We provide basic ones in the repository to be used

```php
$container = new Coreplex\Crumbs\Container(new Coreplex\Crumbs\Components\Crumb, new Coreplex\Crumbs\Renderers\Basic);
```

To add a few breadcrumbs to the container, you can either use the `append` method directly, like so

```php
$container->append('Homepage', '/home');
```

Or you can use a closure to group them into their own scope. To do this, just call the `prepare` method and use any of the container functions on the passed instance

```php
$container->prepare(function($crumbs)
{
    $crumbs->append('Homepage', '/home')
           ->append('Edit');
});
```

To add a breadcrumb to the start of the container rather than the end, use the alternative `prepend` method

```php
$container->prepend('The Website', '/');
```

Rendering The Breadcrumbs
-------------------------

The basic renderer provided will return a simple list-based navigation string. This can be invoked through the main container class by just calling the `render` method.

```php
echo $container->render();
```

The render method causes the last breadcrumb to be active by default. To disable this behaviour, pass false as the first parameter when calling render.

```php
echo $container->render(false);
```

The container can also be rendered by simply echoing out the class, as it will
be implicitly type-cast to a string.

```php
echo $container;
```

Retrieving The Breadcrumbs and the Crumb Component
--------------------------------------------------

If you are going to be handling breadcrumbs from the container, you will want to access the numerous properties on the class. To do this, you can use the fluent attribute methods

```php
$container->append('The Website', '//www.website.com');

foreach ($container->crumbs() as $crumb) {
    var_dump($crumb->label()); // returns 'The Website'
    var_dump($crumb->url()); // returns '//www.website.com'
    var_dump($crumb->current()); // returns true
}
```

There are also respective setters and isSetters for each of the attributes on the class

```php
// Append an empty breadcrumb to the container
$container->append();

foreach ($container->crumbs() as $crumb) {
    var_dump($crumb->label()); // returns null

    if ( ! $crumb->hasLabel()) {
        $crumb->setLabel('The Website')
    }

    var_dump($crumb->url()); // returns null

    if ( ! $crumb->hasUrl()) {
        $crumb->setUrl('//www.website.com')
    }

    var_dump($crumb->current()); // returns true

    if ( ! $crumb->current()) {
        $crumb->setCurrent();
    }

    $crumb->setNotCurrent();

    var_dump($crumb->current()); // returns false
}
```

Laravel 5 Support
-------------------------
Crumbs has support for Laravel 5 out of the box. Once installed via composer, simply add the service provider to your app.php file

```php
'providers' => [

    'Coreplex\Crumbs\CrumbsServiceProvider',

]
```

And also publish the config via command line, using the `php artisan vendor:publish` function. This allows the config to be published to the correct directory

Once these steps have been taken, Crumbs can be dependency injected into any controller constructs like so

```php
/**
 * Make a new controller instance
 *
 * @param \Coreplex\Crumbs\Contracts\Container $breadcrumbs
 * @return void
 */
public function __construct(\Coreplex\Crumbs\Contracts\Container $breadcrumbs)
{
    $this->breadcrumbs = $breadcrumbs;
}
```

Which will then allow access to the breadcrumbs container via the breadcrumbs class property on the controller

A facade is also provided to those who would opt using this over dependency injection. Simply add it to the aliases array in app.php

```php
'aliases' => [

    'Crumbs' => 'Coreplex\Crumbs\Facades\Crumbs',

],
```

Which would then allow you to do things like this in your controllers

```php
use Crumbs;

class DashboardController extends Controller {

    public function index()
    {
        Crumbs::prepare(function($crumbs)
        {
            $crumbs->append('Dashboard Home', route('dashboard.index'));
        });

        return view('dashboard.index')->with('breadcrumbs', Crumbs::render());
    }

}
```

Planned Features
----------------

- Laravel 4 Integration


text:
declare const angular: angular.IAngularStatic;
import { downgradeComponent } from '@angular/upgrade/static';

import { Component } from '@angular/core';

import { Phone, PhoneData } from '../core/phone/phone.service';
import { RouteParams } from '../ajs-upgraded-providers';

@Component({
  selector: 'phone-detail',
  templateUrl: './phone-detail.template.html',
})
export class PhoneDetailComponent {
  phone: PhoneData;
  mainImageUrl: string;

  constructor(routeParams: RouteParams, phone: Phone) {
    phone.get(routeParams.phoneId).subscribe(data => {
      this.phone = data;
      this.setImage(data.images[0]);
    });
  }

  setImage(imageUrl: string) {
    this.mainImageUrl = imageUrl;
  }
}

angular.module('phoneDetail')
  .directive(
    'phoneDetail',
    downgradeComponent({component: PhoneDetailComponent}) as angular.IDirectiveFactory
  );


text:
#include "StdAfx.h"

#ifndef _7ZIP_ST
#include "../../../Windows/System.h"
#endif

#include "../Common/ParseProperties.h"

#include "HandlerOut.h"

using namespace NWindows;

namespace NArchive {

static void SetMethodProp32(COneMethodInfo &m, PROPID propID, UInt32 value)
{
  if (m.FindProp(propID) < 0)
    m.AddProp32(propID, value);
}

void CMultiMethodProps::SetGlobalLevelAndThreads(COneMethodInfo &oneMethodInfo
    #ifndef _7ZIP_ST
    , UInt32 numThreads
    #endif
    )
{
  UInt32 level = _level;
  if (level != (UInt32)(UInt32)-1)
    SetMethodProp32(oneMethodInfo, NCoderPropID::kLevel, (UInt32)level);
  #ifndef _7ZIP_ST
  SetMethodProp32(oneMethodInfo, NCoderPropID::kNumThreads, numThreads);
  #endif
}

void CMultiMethodProps::Init()
{
  #ifndef _7ZIP_ST
  _numProcessors = _numThreads = NSystem::GetNumberOfProcessors();
  #endif

  _level = (UInt32)(UInt32)-1;
  _autoFilter = true;
  _crcSize = 4;
  _filterMethod.Clear();
  _methods.Clear();
}

HRESULT CMultiMethodProps::SetProperty(const wchar_t *nameSpec, const PROPVARIANT &value)
{
  UString name = nameSpec;
  name.MakeUpper();
  if (name.IsEmpty())
    return E_INVALIDARG;

  if (name[0] == 'X')
  {
    name.Delete(0);
    _level = 9;
    return ParsePropToUInt32(name, value, _level);
  }

  if (name == L"CRC")
  {
    name.Delete(0, 3);
    _crcSize = 4;
    return ParsePropToUInt32(name, value, _crcSize);
  }

  UInt32 number;
  int index = ParseStringToUInt32(name, number);
  UString realName = name.Mid(index);
  if (index == 0)
  {
    if (name.Left(2).CompareNoCase(L"MT") == 0)
    {
      #ifndef _7ZIP_ST
      RINOK(ParseMtProp(name.Mid(2), value, _numProcessors, _numThreads));
      #endif
      return S_OK;
    }
    if (name.CompareNoCase(L"F") == 0)
    {
      HRESULT res = PROPVARIANT_to_bool(value, _autoFilter);
      if (res == S_OK)
        return res;
      if (value.vt != VT_BSTR)
        return E_INVALIDARG;
      return _filterMethod.ParseMethodFromPROPVARIANT(L"", value);
    }
    number = 0;
  }
  if (number > 64)
    return E_FAIL;
  for (int j = _methods.Size(); j <= (int)number; j++)
    _methods.Add(COneMethodInfo());
  return _methods[number].ParseMethodFromPROPVARIANT(realName, value);
}

void CSingleMethodProps::Init()
{
  Clear();
  #ifndef _7ZIP_ST
  _numProcessors = _numThreads = NWindows::NSystem::GetNumberOfProcessors();
  AddNumThreadsProp(_numThreads);
  #endif
  _level = (UInt32)(UInt32)-1;
}

HRESULT CSingleMethodProps::SetProperties(const wchar_t **names, const PROPVARIANT *values, Int32 numProps)
{
  Init();
  for (int i = 0; i < numProps; i++)
  {
    UString name = names[i];
    name.MakeUpper();
    if (name.IsEmpty())
      return E_INVALIDARG;
    const PROPVARIANT &value = values[i];
    if (name[0] == L'X')
    {
      UInt32 a = 9;
      RINOK(ParsePropToUInt32(name.Mid(1), value, a));
      _level = a;
      AddLevelProp(a);
    }
    else if (name.Left(2).CompareNoCase(L"MT") == 0)
    {
      #ifndef _7ZIP_ST
      RINOK(ParseMtProp(name.Mid(2), value, _numProcessors, _numThreads));
      AddNumThreadsProp(_numThreads);
      #endif
    }
    else
      return ParseParamsFromPROPVARIANT(name, value);
  }
  return S_OK;
}

}


text:
cask "mini-program-studio" do
  version "1.13.7,bdb97283-1173-4185-aed0-fad47f7810ae"
  sha256 "391c72c8246048726829de9f218389e4d0dfd8ddf3fdab3a03a04791a7c57442"

  # gw.alipayobjects.com/ was verified as official when first introduced to the cask
  url "https://gw.alipayobjects.com/os/volans-demo/#{version.after_comma}/#{version.before_comma}/MiniProgramStudio-#{version.before_comma}.dmg"
  name "Mini Program Studio"
  name "小程序开发者工具"
  homepage "https://open.alipay.com/channel/miniIndex.htm"

  app "小程序开发者工具.app"

  zap trash: [
    "~/Library/Application Support/小程序开发者工具",
    "~/Library/Preferences/com.ant.miniprogram.plist",
    "~/Library/Saved Application State/com.ant.miniprogram.savedState",
  ]
end


text:
{% extends "base.html" %}
{% set active_page = "help" %}

{% block content %}

Privacy Policy

{% include ['custom/_privacy_policy.html', 'help/_privacy_policy.html'] ignore missing %}
{% endblock %}


text:
# Grind Framework

Grind is an opinionated Node web framework that utilizes popular packages in an easy to use framework to provide a solid foundation for you to build your apps on, without reinventing the wheel.

## Documentation

Full documentation for Grind is available on the [Grind website](https://grind.rocks/).

### Additional Resources

- [Example Web Project](https://github.com/grindjs/example-web)
- [Example API Project](https://github.com/grindjs/example-api)
- [Source for the Grind website](https://github.com/grindjs/site)
- [Grind Slack](https://chat.grind.rocks)

## License

Grind was created by [Shaun Harrison](https://github.com/shnhrrsn) and is made available under the [MIT license](LICENSE).


text:
import pytest
import numpy as np

from functools import reduce
import operator

from bluesky.utils import ensure_generator, Msg, merge_cycler, is_movable, CallbackRegistry
from cycler import cycler

def test_single_msg_to_gen():
    m = Msg('set', None, 0)

    m_list = [m for m in ensure_generator(m)]

    assert len(m_list) == 1
    assert m_list[0] == m

@pytest.mark.parametrize('traj',
                         ({'pseudo1': [10, 11, 12],
                           'pseudo2': [20, 21, 22]},
                          {'pseudo1': [10, 11, 12],
                           'pseudo2': [20, 21, 22],
                           'pseudo3': [30, 31, 32]},
                          )
                         )
def test_cycler_merge_pseudo(hw, traj):
    p3x3 = hw.pseudo3x3
    sig = hw.sig
    keys = traj.keys()
    tlen = len(next(iter(traj.values())))
    expected_merge = [{k: traj[k][j] for k in keys}
                      for j in range(tlen)]

    cyc = reduce(operator.add, (cycler(getattr(p3x3, k), v)
                                for k, v in traj.items()))

    mcyc = merge_cycler(cyc + cycler(sig, range(tlen)))

    assert mcyc.keys == {p3x3, sig}
    assert mcyc.by_key()[p3x3] == expected_merge
    assert mcyc.by_key()[sig] == list(range(tlen))

@pytest.mark.parametrize('children',
                         (
                             ['pseudo1', 'real1'],
                             ['pseudo1', 'pseudo2', 'real1']))
def test_cycler_merge_pseudo_real_clash(hw, children):
    p3x3 = hw.pseudo3x3
    cyc = reduce(operator.add, (cycler(getattr(p3x3, k), range(5))
                                for k in children))

    with pytest.raises(ValueError):
        merge_cycler(cyc)

@pytest.mark.parametrize('children',
                         (['pseudo1', ],
                          ['pseudo1', 'pseudo2'],
                          ['real1'],
                          ['real1', 'real2']))
def test_cycler_parent_and_parts_fail(hw, children):
    p3x3 = hw.pseudo3x3
    cyc = reduce(operator.add, (cycler(getattr(p3x3, k), range(5))
                                for k in children))
    cyc += cycler(p3x3, range(5))

    with pytest.raises(ValueError):
        merge_cycler(cyc)

@pytest.mark.parametrize('children',
                         (['sig', ],))
def test_cycler_parent_and_parts_succed(hw, children):
    p3x3 = hw.pseudo3x3
    cyc = reduce(operator.add, (cycler(getattr(p3x3, k), range(5))
                                for k in children))
    cyc += cycler(p3x3, range(5))
    mcyc = merge_cycler(cyc)

    assert mcyc.keys == cyc.keys
    assert mcyc.by_key() == cyc.by_key()

@pytest.mark.parametrize('children',
                         (
                             ['pseudo1'],
                             ['pseudo2', 'sig'],
                             ['real1'],
                             ['real1', 'real2'],
                             ['real1', 'real2', 'sig'],
                         ))
def test_cycler_merge_mixed(hw, children):
    p3x3 = hw.pseudo3x3
    cyc = reduce(operator.add, (cycler(getattr(p3x3, k), range(5))
                                for k in children))

    mcyc = merge_cycler(cyc)

    assert mcyc.keys == cyc.keys
    assert mcyc.by_key() == cyc.by_key()

def test_is_movable(hw):

    obj_list = [(10, False), (1.05, False), ("some_string", False),
                (hw.det, False), (hw.motor, True)]
    for obj, result in obj_list:
        assert is_movable(obj) == result, \
            f"The object {obj} is incorrectly recognized "\
            f"as {'' if result else 'not '}movable"

# Indicates if the step when all external references to callables are deleted is included.
@pytest.mark.parametrize("delete_objects", [True, False])
# Settings for the 'set_allowed_signals' parameter of the CallbackRegistry class.
@pytest.mark.parametrize("set_allowed_signals", [True, False])
# Callable type
@pytest.mark.parametrize("callable_type", ["bound_method",
                                           "function",
                                           "callable_object",
                                           "class_method",
                                           "static_method",
                                           "callable_object_class_method",
                                           "callable_object_static_method"])
def test_CallbackRegistry_1(delete_objects, set_allowed_signals, callable_type):
    """
    Basic tests for CallbackRegistry class. The tests verify the behavior
    of CallbackRegistry when connecting and disconnecting callback functions
    represented as the following types:
      - bound methods,
      - functions,
      - callable objects,
      - class methods,
      - static methods.
    The tests performed on callable objects with __call__ function being class or
    static method. The class needs to be instantiated: `a = A()` and the object `a`
    is used as a reference to the callback in the call to subscribe. (I don't know if anyone
    would do such a thing.)

    The callable objects are clearly separated into two groups:
      - GROUP 1 - callable objects;
      - GROUP 2 - functions, bound methods, class methods and static methods.

    The following behavior is expected when connecting callbacks to Callback Registry:

    GROUP 1 (bound methods) - weak reference is held internally (using proxy), deleting external
    references invalidates the weak reference and the respective callback is removed
    from the registry. Callback can be removed manually in a standard way by using `disconnect`
    function.

    GROUP 2 (the rest) - strong reference to the callable object is held internally,
    deleting all external references does not influence the callbacks in CB registry,
    callback can be used until they are removed by 'disconnect' function.

    The dictionaries of Callback registry: callbacks, _func_cid_map. Both dictionaries
    are using signal names as keys. In the current implementation, the entries in the two dictionaries
    are deleted if all callbacks for the respective signals are automatically disconnected
    (callbacks are bound methods and external references are deleted for a bound method).
    If all callbacks (actually the last callback) for a signal are manually disconnected,
    then the respective items in the dictionaries will remain in both dictionaries (they will
    hold ZERO callback references).
    """
    if set_allowed_signals:
        allowed_sigs = {"sig1", "sig2", "sig3"}
    else:
        allowed_sigs = None

    cb = CallbackRegistry(allowed_sigs=allowed_sigs)

    def _f_print(fn, kwarg_value):
        """Formatting of output"""
        return f"Function {fn}: kwarg_value {kwarg_value}"

    signals = {"sig1": 5, "sig2": 4, "sig3": 3}  # sig_name: num_of_created_objects

    # Lists to store data on the created objects
    obj_to_delete = []  # List of objects that will be explicitly deleted in the test
    obj_cid = []  # Object CID (returned by 'CallbackRegistyr.connect()' method
    obj_name = []  # Object Name (assigned to the object in order to identify it in the output
    obj_signal = []  # Name of the signal to which the object with respective index is subscribed.

    # Create objects of the selected type
    for sig_name, n_objects in signals.items():
        for _ in range(n_objects):
            n_callable = len(obj_to_delete)  # The index of the current callable

            if callable_type == "function":

                def _get_f(*, func_name):
                    def f(list_out, *, kwarg_value):
                        list_out.append(_f_print(f"{func_name}", kwarg_value))
                    return f

                o_name = f"f{n_callable}"
                f = _get_f(func_name=o_name)
                o_subscribe = f
                o_delete = f
                del f

            elif callable_type == "callable_object":
                def _get_class_instance(*, func_name):
                    class cl:
                        def __init__(self, func_name):
                            self._func_name = func_name

                        def __call__(self, list_out, *, kwarg_value):
                            list_out.append(_f_print(f"{self._func_name}", kwarg_value))

                    return cl(func_name)

                o_name = f"f{n_callable}"
                cl = _get_class_instance(func_name=o_name)
                o_subscribe = cl
                o_delete = cl
                del cl

            elif callable_type == "bound_method":
                def _get_class_instance(*, func_name):
                    class cl:
                        def __init__(self, func_name):
                            self._func_name = func_name

                        def func(self, list_out, *, kwarg_value):
                            list_out.append(_f_print(f"{self._func_name}", kwarg_value))

                    return cl(func_name)

                o_name = f"f{n_callable}"
                cl_inst = _get_class_instance(func_name=o_name)
                o_subscribe = cl_inst.func
                o_delete = cl_inst
                del cl_inst

            elif callable_type == "class_method":
                def _get_class_instance(*, func_name):
                    class cl:
                        @classmethod
                        def func(cls, list_out, *, kwarg_value):
                            list_out.append(_f_print(f"{func_name}", kwarg_value))

                    return cl()

                o_name = f"f{n_callable}"
                cl = _get_class_instance(func_name=o_name)
                o_subscribe = cl.func
                o_delete = cl
                del cl

            elif callable_type == "static_method":
                def _get_class_instance(*, func_name):
                    class cl:
                        @staticmethod
                        def func(list_out, *, kwarg_value):
                            list_out.append(_f_print(f"{func_name}", kwarg_value))

                    return cl()

                o_name = f"f{n_callable}"
                cl = _get_class_instance(func_name=o_name)
                o_subscribe = cl.func
                o_delete = cl
                del cl

            elif callable_type == "callable_object_class_method":
                def _get_class_instance(*, func_name):
                    class cl:
                        @classmethod
                        def __call__(cls, list_out, *, kwarg_value):
                            list_out.append(_f_print(f"{func_name}", kwarg_value))

                    return cl()

                o_name = f"f{n_callable}"
                cl_inst = _get_class_instance(func_name=o_name)
                o_subscribe = cl_inst
                o_delete = cl_inst
                del cl_inst

            elif callable_type == "callable_object_static_method":
                def _get_class_instance(*, func_name):
                    class cl:
                        @staticmethod
                        def __call__(list_out, *, kwarg_value):
                            list_out.append(_f_print(f"{func_name}", kwarg_value))

                    return cl()

                o_name = f"f{n_callable}"
                cl_inst = _get_class_instance(func_name=o_name)
                o_subscribe = cl_inst
                o_delete = cl_inst
                del cl_inst

            else:
                raise RuntimeError(f"Unknown type of the callable: {callable_type}")

            obj_to_delete.append(o_delete)
            obj_signal.append(sig_name)
            obj_name.append(o_name)
            cid = cb.connect(sig_name, o_subscribe)
            obj_cid.append(cid)
            del o_subscribe, o_delete

    # Verify that the right number of callbacks was initially set
    assert len(cb._func_cid_map) == len(signals), "Incorrect number of signals"
    assert len(cb.callbacks) == len(signals), "Incorrect number of signals"
    for sig_name, n_objects in signals.items():
        assert len(cb._func_cid_map[sig_name]) == n_objects, \
            f"Incorrect number of callbacks for '{sig_name}'"
        assert len(cb.callbacks[sig_name]) == n_objects, \
            f"Incorrect number of callbacks for '{sig_name}'"

    def _process_each_signal(n_start_check=0):
        """Process each signal, check callback output starting from index `n_start_check`"""
        # Try calling each signal
        for sig_name in signals.keys():
            # The list of indices for the entries related to 'signal_name' signal
            i_sig = [_ for _ in range(len(obj_signal)) if (obj_signal[_] == sig_name)]

            list_out = []
            rand_value = np.random.rand()  # Some value that is expected to be part of the function output
            cb.process(sig_name, list_out, kwarg_value=rand_value)

            assert len(list_out) == len([_ for _ in i_sig if _ >= n_start_check]), \
                "Output list has incorrect number of entries"
            for n in i_sig:
                if n >= n_start_check:
                    expected_substr = _f_print(obj_name[n], rand_value)
                    assert list_out.count(expected_substr) == 1, \
                        f"Signal '{sig_name}' was processed incorrectly: entry '{expected_substr}' " \
                        f"was not found in the output '{list_out}'"

    _process_each_signal()

    if delete_objects:
        # Now delete all the callable objects one by one
        for n in range(len(obj_to_delete)):
            obj_to_delete[n] = None  # Overwriting the reference deletes the object

            # Check the function composition
            if callable_type in ["function", "callable_object", "class_method", "static_method",
                                 "callable_object_class_method", "callable_object_static_method"]:
                # Deleting objects should change nothing
                assert len(cb._func_cid_map) == len(signals), "Incorrect number of signals"
                assert len(cb.callbacks) == len(signals), "Incorrect number of signals"
                for sig_name, n_objects in signals.items():
                    assert len(cb._func_cid_map[sig_name]) == n_objects, \
                        f"Incorrect number of callbacks for '{sig_name}'"
                    assert len(cb.callbacks[sig_name]) == n_objects, \
                        f"Incorrect number of callbacks for '{sig_name}'"

                _process_each_signal()

            elif callable_type == "bound_method":
                # Callbacks should be removed as they get deleted
                sigs_remaining = list(set(obj_signal[n+1:]))
                assert len(cb._func_cid_map) == len(sigs_remaining), "Incorrect number of signals"
                assert len(cb.callbacks) == len(sigs_remaining), "Incorrect number of signals"
                for sig_name, n_objects in signals.items():
                    if sig_name in sigs_remaining:
                        assert len(cb._func_cid_map[sig_name]) == obj_signal[n+1:].count(sig_name), \
                            f"Incorrect number of callbacks for '{sig_name}'"
                        assert len(cb.callbacks[sig_name]) == obj_signal[n+1:].count(sig_name), \
                            f"Incorrect number of callbacks for '{sig_name}'"

                _process_each_signal(n_start_check=n + 1)

            else:
                assert False, f"Unknown callable type: {callable_type}"

    if delete_objects and callable_type == "bound_method":
        # Dictionary entries for signals are deleted when the objects are deleted
        #   and callbacks are unsubscribed
        assert len(cb._func_cid_map) == 0, "Not all callbacks were automatically unsubscribed"
        assert len(cb.callbacks) == 0, "Not all callbacks were automatically unsubscribed"
    else:
        # Now disconnect the callbacks one by one and verify dictionary content
        for n in range(len(obj_to_delete)):
            cb.disconnect(obj_cid[n])
            # NOTE: as the objects are deleted, the dictionary entries for the signals still remain
            assert len(cb._func_cid_map) == len(signals), "Incorrect number of signals"
            assert len(cb.callbacks) == len(signals), "Incorrect number of signals"
            for sig_name, n_objects in signals.items():
                assert len(cb._func_cid_map[sig_name]) == obj_signal[n+1:].count(sig_name), \
                    f"Incorrect number of callbacks for '{sig_name}'"
                assert len(cb.callbacks[sig_name]) == obj_signal[n+1:].count(sig_name), \
                    f"Incorrect number of callbacks for '{sig_name}'"
            _process_each_signal(n_start_check=n + 1)

def test_CallbackRegistry_2():
    """
    The following features were tested:
    - connect the same callback to the same signal (repeated connections are ignored);
    - connecting the same callback to different signals (works noramlly);
    - connecting a callback to a signals that are not in allowed list (exception raised);
    - attempting to process a signals that are not in allowed list (exception raised;
    - processing signals that have no callback assigned (nothing happens).
    """

    allowed_sigs = {"sig1", "sig2", "sig3"}
    cb = CallbackRegistry(allowed_sigs=allowed_sigs)

    def f():
        pass

    # Signal not allowed
    with pytest.raises(ValueError, match=f"Allowed signals are {allowed_sigs}"):
        cb.connect("some_sig", f)

    # Connect callback to allowed signal
    sig_name = "sig2"
    cb.connect(sig_name, f)
    assert len(cb.callbacks[sig_name]) == 1, "Incorrect number of assigned callbacks"

    # Attempt to connect the same callback to the same signal are ignored
    cb.connect(sig_name, f)
    assert len(cb.callbacks[sig_name]) == 1, "Incorrect number of assigned callbacks"

    # Connect the same callback to a different signal
    sig_name2 = "sig3"
    cb.connect(sig_name2, f)
    assert len(cb.callbacks[sig_name]) == 1, "Incorrect number of assigned callbacks"
    assert len(cb.callbacks[sig_name2]) == 1, "Incorrect number of assigned callbacks"

    # Process the allowed signal with assigned callback
    cb.process(sig_name)

    # Process the allowed signal with unassigned callback (no callbacks called,
    #   but it still works.
    cb.process("sig1")

    # Process the signal that is not allowed
    with pytest.raises(ValueError, match=f"Allowed signals are {allowed_sigs}"):
        cb.process("some_signal")


text:
[![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT)
[![Build Status](https://travis-ci.org/nhejazi/stat215a-journal-review.svg?branch=master)](https://travis-ci.org/nhejazi/stat215a-journal-review?branch=master)
[![Coverage Status](https://coveralls.io/repos/nhejazi/stat215a-journal-review/badge.svg?branch=master)](https://coveralls.io/r/nhejazi/stat215a-journal-review?branch=master)
[![Join the chat at https://gitter.im/stat215a-journal-review/Lobby](https://badges.gitter.im/stat215a-journal-review/Lobby.svg)](https://gitter.im/stat215a-journal-review/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

_**Team members:**_ [Nima Hejazi](https://github.com/nhejazi), [Courtney
Schiffman](https://github.com/courtneyschiffman), [Xiaonan
Zhou](https://github.com/GiannaJo)

This project consists in a full, reproducible review of the scientific paper:

* [JH Pitt and HZ Hill. "Statistical analysis of numerical preclinical
    radiobiological data." _ScienceOpen Research_,
    2016.](https://www.scienceopen.com/document?20&vid=8aa0f248-2bad-44c6-adfd-42816c14c272)

---

## Directions/Roadmap

The workflow for reproducing all results discussed in the published review is
described below:

---

## License

© 2016 [Nima Hejazi](http://nimahejazi.org), Courtney Schiffman, Xiaonan
Zhou

This repository is licensed under the MIT license. See `LICENSE` for details.


text:
// Plato.NET
// Copyright (c) 2017 ReflectSoftware Inc.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using MsgPack;
using MsgPack.Serialization;
using Plato.Redis.Interfaces;
using StackExchange.Redis;
using System;
using System.IO;

namespace Plato.Redis.Serializers
{
    /// <summary>
    ///
    /// </summary>
    /// <seealso cref="Plato.Redis.Interfaces.IRedisSerializer" />
    public class MsgPackRedisSerializer : IRedisSerializer
    {
        /// <summary>
        /// Serializes the specified data.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public RedisValue Serialize(object data)
        {
            if (data != null)
            {
                using (var ms = new MemoryStream())
                {
                    MessagePackSerializer.Get(data.GetType()).Pack(ms, data);
                    return ms.ToArray();
                }
            }

            return RedisValue.EmptyString;
        }

        /// <summary>
        /// Deserializes the specified data.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public T Deserialize<T>(RedisValue data)
        {
            if (data.HasValue)
            {
                using (var ms = new MemoryStream(data))
                {
                    return MessagePackSerializer.Get<T>().Unpack(ms);
                }
            }

            return default(T);
        }

        /// <summary>
        /// Deserializes the specified data.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public T Deserialize<T>(object data)
        {
            return MessagePackSerializer.Get<T>().FromMessagePackObject((MessagePackObject)data);
        }

        /// <summary>
        /// Deserializes the specified data.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public object Deserialize(object data, Type type)
        {
            return MessagePackSerializer.Get(type).FromMessagePackObject((MessagePackObject)data);
        }
    }
}


text:
package org.springframework.core.annotation;

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

import org.springframework.core.Ordered;

/**
 * {@code @Order} defines the sort order for an annotated component.
 *
 *
The {@link #value} is optional and represents an order value as defined
 * in the {@link Ordered} interface. Lower values have higher priority. The
 * default value is {@code Ordered.LOWEST_PRECEDENCE}, indicating
 * lowest priority (losing to any other specified order value).
 *
 *
Since Spring 4.1, the standard {@link javax.annotation.Priority}
 * annotation can be used as a drop-in replacement for this annotation.
 *
 *
NOTE: Annotation-based ordering is supported for specific kinds
 * of components only — for example, for annotation-based AspectJ
 * aspects. Ordering strategies within the Spring container, on the other
 * hand, are typically based on the {@link Ordered} interface in order to
 * allow for programmatically configurable ordering of each instance.
 *
 *
Consult the Javadoc for {@link org.springframework.core.OrderComparator
 * OrderComparator} for details on the sort semantics for non-ordered objects.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @since 2.0
 * @see org.springframework.core.Ordered
 * @see AnnotationAwareOrderComparator
 * @see OrderUtils
 * @see javax.annotation.Priority
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order {

	/**
	 * The order value.
	 *
Default is {@link Ordered#LOWEST_PRECEDENCE}.
	 * @see Ordered#getOrder()
	 */
	int value() default Ordered.LOWEST_PRECEDENCE;

}


text:
FROM ubuntu:16.04
MAINTAINER Sébastien Han "seb@redhat.com"

ENV ETCDCTL_VERSION v2.3.7
ENV ETCDCTL_ARCH linux-amd64
ENV CEPH_VERSION infernalis

ENV KVIATOR_VERSION 0.0.7
ENV CONFD_VERSION 0.10.0
ENV KUBECTL_VERSION v1.4.0

# Install prerequisites
RUN apt-get update && apt-get install -y wget unzip uuid-runtime runit python3

# Install Ceph
RUN wget -q -O- 'https://download.ceph.com/keys/release.asc' | apt-key add -
RUN echo deb http://download.ceph.com/debian-${CEPH_VERSION}/ xenial main | tee /etc/apt/sources.list.d/ceph-${CEPH_VERSION}.list
RUN apt-get update && apt-get install -y --force-yes ceph radosgw && \
apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Install etcdctl
RUN wget -q -O- "https://github.com/coreos/etcd/releases/download/${ETCDCTL_VERSION}/etcd-${ETCDCTL_VERSION}-${ETCDCTL_ARCH}.tar.gz" |tar xfz - -C/tmp/ etcd-${ETCDCTL_VERSION}-${ETCDCTL_ARCH}/etcdctl
RUN mv /tmp/etcd-${ETCDCTL_VERSION}-${ETCDCTL_ARCH}/etcdctl /usr/local/bin/etcdctl

#install kviator
ADD https://github.com/AcalephStorage/kviator/releases/download/v${KVIATOR_VERSION}/kviator-${KVIATOR_VERSION}-linux-amd64.zip /tmp/kviator.zip
RUN cd /usr/local/bin && unzip /tmp/kviator.zip && chmod +x /usr/local/bin/kviator && rm /tmp/kviator.zip

# Install confd
ADD https://github.com/kelseyhightower/confd/releases/download/v${CONFD_VERSION}/confd-${CONFD_VERSION}-linux-amd64 /usr/local/bin/confd
RUN chmod +x /usr/local/bin/confd && mkdir -p /etc/confd/conf.d && mkdir -p /etc/confd/templates

# Install kubectl
ADD https://storage.googleapis.com/kubernetes-release/release/${KUBECTL_VERSION}/bin/linux/amd64/kubectl /usr/local/bin/kubectl
RUN chmod +x /usr/local/bin/kubectl

ADD https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64 /usr/local/bin/jq
RUN chmod +x /usr/local/bin/jq

ADD entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe Service do

  describe "service instance" do

    it { should belong_to :service_category }
    it { should scope_sorted }
    it { should scope_active }
    it { should scope_sorted_id }

    describe "named scope" do
      describe "identity_services" do
        before do
          @service = Factory(:service, :use_for => 'identity')
          @service_not = Factory(:service, :use_for => 'not')
        end
        it "should find services that have use_for=='identity_services'" do
          Service.identity_services.should include(@service)
        end
        it "should not find services that where use_for!='identity_services'" do
          Service.identity_services.should_not include(@service_not)
        end
      end
      describe "tag_services" do
        before do
          @service = Factory(:service, :use_for => 'tags')
          @service_not = Factory(:service, :use_for => 'not')
        end
        it "should find services that have use_for=='tags'" do
          Service.tag_services.should include(@service)
        end
        it "should not find services that where use_for!='tags'" do
          Service.tag_services.should_not include(@service_not)
        end
      end
      describe "sorted_id" do
        before do
          Service.delete_all
          @first = Factory(:service)
          @second = Factory(:service)
        end
        it "should sort by 'sort' field" do
          Service.sorted_id[0].should == @first
          Service.sorted_id[1].should == @second
        end
      end
      describe "photo_services" do
        before do
          @service_category = Factory(:service_category, :name => 'Photos')
          @service = Factory(:service, :service_category => @service_category)
          @service_not = Factory(:service)
        end
        it "should find services that have 'Photos' for a service category" do
          Service.photo_services.should include(@service)
        end
        it "should not find services that don't have 'Photos' for a service category" do
          Service.photo_services.should_not include(@service_not)
        end
      end
    end

    describe "photos" do
      before do
        service_category = Factory(:service_category, :name => 'Photos')
        @service = Factory(:service, :service_category_id => service_category.id)
      end
      it "should be a photo service" do
        @service.photo?(true).should be_true
      end
    end

    describe "videos" do
      before do
        service_category = Factory(:service_category, :name => 'Videos')
        @service = Factory(:service, :service_category_id => service_category.id)
      end
      it "should be a video service" do
        @service.video?(true).should be_true
      end
    end

    describe "bookmarks" do
      before do
        service_category = Factory(:service_category, :name => 'Bookmarks')
        @service = Factory(:service, :service_category_id => service_category.id)
      end
      it "should be a bookmark service" do
        @service.bookmark?(true).should be_true
      end
    end

    describe "music" do
      before do
        service_category = Factory(:service_category, :name => 'Music')
        @service = Factory(:service, :service_category_id => service_category.id)
      end
      it "should be a music service" do
        @service.music?(true).should be_true
      end
    end

    describe "news" do
      before do
        service_category = Factory(:service_category, :name => 'News')
        @service = Factory(:service, :service_category_id => service_category.id)
      end
      it "should be a news service" do
        @service.news?(true).should be_true
      end
    end

    describe "blog" do
      before do
        service_category = Factory(:service_category, :name => 'Blogging')
        @service = Factory(:service, :service_category_id => service_category.id)
      end
      it "should be a blog service" do
        @service.blog?(true).should be_true
      end
    end

    describe "search" do
      before do
        service_category = Factory(:service_category, :name => 'Search')
        @service = Factory(:service, :service_category_id => service_category.id)
      end
      it "should be a search service" do
        @service.search?(true).should be_true
      end
    end

    describe "general" do
      before do
        service_category = Factory(:service_category, :name => 'RSS')
        @service = Factory(:service, :service_category_id => service_category.id)
      end
      it "should be a general service" do
        @service.general?(true).should be_true
      end
    end

  end

  describe "identity services" do
    it "should generate uri using blog url" do
      service = Factory(:service)
      uris = service.generate_uris('', '', TEST_URI)
      uris.map(&:url).include?(TEST_RSS_URI).should be_true
    end
    it "should generate uri using username" do
      service = Factory(:service, :uri_data_template => TEST_USERNAME_TEMPLATE)
      uris = service.generate_uris('jbasdf', '', '')
      uris.map(&:url).include?(TEST_USERNAME_TEMPLATE.sub('{username}', 'jbasdf')).should be_true
    end
    it "should get twitter uri from username" do
      service = Factory(:service, :uri_data_template => "http://www.twitter.com/{username}")
      uris = service.generate_uris('jbasdf', '', '')
      uris.map(&:url).include?("http://twitter.com/statuses/user_timeline/7219042.rss").should be_true
    end
  end

  describe "tag services" do
    before do
      @user = Factory(:user)
      @template = "http://example.com/{tag}.rss"
      @uri_template = "http://example.com/{tag}"
      @service = Factory(:service, :uri_data_template => @template, :uri_template => @uri_template,  :use_for => 'tags')
    end
    it "should generate urls for tag" do
      tag = 'rails'
      uris = Service.generate_tag_uris(tag)
      uris.should include(@template.sub('{tag}', tag))
    end
    it "should set display uri when building a feed" do
      tag = 'identity'
      feeds = Service.build_tag_feeds(tag, @user, nil, true)
      feeds.any?{|feed| feed.display_uri == (@uri_template.sub('{tag}', tag))}.should be_true
    end
    it "should build a feed for every tag service" do
      tag = 'cycling'
      feeds = Service.build_tag_feeds(tag, @user, nil, true)
      feeds.length.should == Service.tag_services.length
      feeds.any?{|feed| feed.uri == (@template.sub('{tag}', tag))}.should be_true
    end
    it "should build a limited number of feeds for tag" do
      tag = 'ruby'
      feeds = Service.build_tag_feeds(tag, @user, [@service.id], true)
      feeds.length.should == 1
      feeds.any?{|feed| feed.uri == (@template.sub('{tag}', tag))}.should be_true
    end
    it "should create a feed for every tag service" do
      tag = 'physics'
      feeds = Service.create_tag_feeds(tag, @user, nil, true)
      feeds.length.should == Service.tag_services.length
      feeds.any?{|feed| feed.uri == (@template.sub('{tag}', tag))}.should be_true
    end
    it "should create a limited number of feeds for tag" do
      tag = 'math'
      feeds = Service.create_tag_feeds(tag, @user, [@service.id], true)
      feeds.length.should == 1
      feeds.any?{|feed| feed.uri.should == (@template.sub('{tag}', tag))}
    end
  end

  describe "Create feed from service" do
    before do
      @login = 'jbasdf'
      @password = ''
      @uri_data_template = TEST_USERNAME_TEMPLATE
      @service = Factory(:service, :uri_data_template => @uri_data_template)
      @user = Factory(:user)
    end
    it "should create feed from service" do
      feeds = Service.create_tag_feeds_for_service(@service, '', @login, @password, @user)
      feed = feeds[0]
      feed.uri.should == @uri_data_template.sub("{username}", @login)
      feed.login.should == @login
      feed.password.should == @password
      feed.service_id.should == @service.id
    end
    it "should create feed from service even with nil template" do
      feeds = Service.create_tag_feeds_for_service(@service, '', @login, @password, @user)
      feed = feeds[0]
      feed.uri.should == @uri_data_template.sub("{username}", @login)
      feed.login.should == @login
      feed.password.should == @password
      feed.service_id.should == @service.id
    end
  end

  describe "Find service by uri" do
    before do
      Service.delete_all
    end
    after do
      bootstrap_services
    end
    it "should find service when uri is shorter" do
      foo_service = Factory(:service, :uri => 'http://www.foo.com')
      service = Service.find_service_by_uri('foo.com', true)
      service.should == foo_service
    end
    it "should find service uri is longer" do
      example_service = Factory(:service, :uri => 'http://www.example.com')
      service = Service.find_service_by_uri('http://www.example.com/other_stuff', true)
      service.should == example_service
    end
  end

  describe "build" do
    before do
      @terms = "ruby"
      @user = Factory(:user)
    end
    describe "photo feeds" do
      before do
        @feeds = Service.build_photo_feeds(@terms, @user.id)
      end
      it "should only create photo feeds" do
        assert @feeds.length > 0
        @feeds.all? { |feed| feed.service.service_category.name == "Photos" }.should be_true
      end
    end
    describe "video feeds" do
      before do
        @feeds = Service.build_video_feeds(@terms, @user.id)
      end
      it "should only create video feeds" do
        assert @feeds.length > 0
        @feeds.all? { |feed| feed.service.service_category.name == "Videos" }.should be_true
      end
    end
    describe "bookmark feeds" do
      before do
        @feeds = Service.build_bookmark_feeds(@terms, @user.id)
      end
      it "should only create bookmark feeds" do
        assert @feeds.length > 0
        @feeds.all? { |feed| feed.service.service_category.name == "Bookmarks" }.should be_true
      end
    end
    describe "music feeds" do
      before do
        build_music_service
        @feeds = Service.build_music_feeds(@terms, @user.id, nil, true) # We build the music service above so we have to force a cache refresh
      end
      it "should only create music feeds" do
        assert @feeds.length > 0
        @feeds.all? { |feed| feed.service.service_category.name == "Music" }.should be_true
      end
    end
    describe "news feeds" do
      before do
        @feeds = Service.build_news_feeds(@terms, @user.id, nil, true) # We build the news service above so we have to force a cache refresh
      end
      it "should only create news feeds" do
        assert @feeds.length > 0
        @feeds.all? { |feed| feed.service.service_category.name == "News" }.should be_true
      end
    end
    describe "blog feeds" do
      before do
        @feeds = Service.build_blog_feeds(@terms, @user.id, nil, true) # We build the blog service above so we have to force a cache refresh
      end
      it "should only create blog feeds" do
        assert @feeds.length > 0
        @feeds.all? { |feed| feed.service.service_category.name == "Blogging" }.should be_true
      end
    end
    describe "search feeds" do
      before do
        @feeds = Service.build_search_feeds(@terms, @user.id, nil, true) # We build the search service above so we have to force a cache refresh
      end
      it "should only create search feeds" do
        assert @feeds.length > 0
        @feeds.all? { |feed| feed.service.service_category.name == "Search" }.should be_true
      end
    end
  end

  describe "service types" do
    before do
      build_music_service
    end
    it "should get photo services" do
      assert Service.get_photo_tag_services(true).length > 0
      Service.get_photo_tag_services.all? { |service| service.service_category.name == "Photos" }.should be_true
    end
    it "should get video services" do
      assert Service.get_video_tag_services(true).length > 0
      Service.get_video_tag_services.all? { |service| service.service_category.name == "Videos" }.should be_true
    end
    it "should get bookmark services" do
      assert Service.get_bookmark_tag_services(true).length > 0
      Service.get_bookmark_tag_services.all? { |service| service.service_category.name == "Bookmarks" }.should be_true
    end
    it "should get music services" do
      assert Service.get_music_tag_services(true).length > 0
      Service.get_music_tag_services.all? { |service| service.service_category.name == "Music" }.should be_true
    end
    it "should get news services" do
      assert Service.get_news_tag_services(true).length > 0
      Service.get_news_tag_services.all? { |service| service.service_category.name == "News" }.should be_true
    end
    it "should get blog services" do
      assert Service.get_blog_tag_services(true).length > 0
      Service.get_blog_tag_services.all? { |service| service.service_category.name == "Blogging" }.should be_true
    end
    it "should get search services" do
      assert Service.get_search_tag_services(true).length > 0
      Service.get_search_tag_services.all? { |service| service.service_category.name == "Search" }.should be_true
    end
    it "should get general services" do
      assert Service.get_general_tag_services(true).length > 0
      Service.get_general_tag_services.any? { |service| service.service_category.name == "Photos" }.should_not be_true
      Service.get_general_tag_services.any? { |service| service.service_category.name == "Videos" }.should_not be_true
      Service.get_general_tag_services.any? { |service| service.service_category.name == "Bookmarks" }.should_not be_true
      Service.get_general_tag_services.any? { |service| service.service_category.name == "Music" }.should_not be_true
    end
  end

end


text:
export default class GeneratorSeedIterator<T> implements Iterator<T> {
    private prevItem: T;

    constructor(private readonly seed: T,
                private readonly nextFunction: (value: T) => T | null | undefined) {
    }

    next(value?: any): IteratorResult<T> {
        if (this.prevItem == null) {
            this.prevItem = this.seed;
            return {done: false, value: this.seed};
        }
        const nextItem = this.nextFunction(this.prevItem);
        if (nextItem == null) {
            return {done: true, value: undefined as any};
        }
        this.prevItem = nextItem;
        return {
            done: false,
            value: nextItem!
        };
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Aust. Syst. Bot. 5(5): 601 (1992)

#### Original name
Dingleya geometrica Trappe, Castellano & Malajczuk

### Remarks
null


text:
package boofcv.alg.distort.impl;

import boofcv.alg.distort.ImageDistortCache_SB;
import boofcv.alg.interpolate.InterpolatePixelS;
import boofcv.struct.image.GrayS32;
import boofcv.struct.image.ImageGray;

/**
 * Implementation of {@link ImageDistortCache_SB} for {@link GrayS32}.
 *
 * @author Peter Abeles
 */
public class ImplImageDistortCache_S32<Input extends ImageGray>
		extends ImageDistortCache_SB<Input,GrayS32> {
	public ImplImageDistortCache_S32(InterpolatePixelS<Input> interp)
	{
		super( interp );
	}

	@Override
	protected void assign(int indexDst, float value) {
		dstImg.data[indexDst] = (int)value;
	}
}


text:
import lombok.Value;
final @lombok.Value class Value1 {
  private final int x;
  private final String name;
  public @java.lang.SuppressWarnings("all") int getX() {
    return this.x;
  }
  public @java.lang.SuppressWarnings("all") String getName() {
    return this.name;
  }
  public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) {
    if ((o == this))
        return true;
    if ((! (o instanceof Value1)))
        return false;
    final @java.lang.SuppressWarnings("all") Value1 other = (Value1) o;
    if ((this.getX() != other.getX()))
        return false;
    final java.lang.Object this$name = this.getName();
    final java.lang.Object other$name = other.getName();
    if (((this$name == null) ? (other$name != null) : (! this$name.equals(other$name))))
        return false;
    return true;
  }
  public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() {
    final int PRIME = 59;
    int result = 1;
    result = ((result * PRIME) + this.getX());
    final java.lang.Object $name = this.getName();
    result = ((result * PRIME) + (($name == null) ? 0 : $name.hashCode()));
    return result;
  }
  public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() {
    return (((("Value1(x=" + this.getX()) + ", name=") + this.getName()) + ")");
  }
  public @java.beans.ConstructorProperties({"x", "name"}) @java.lang.SuppressWarnings("all") Value1(final int x, final String name) {
    super();
    this.x = x;
    this.name = name;
  }
}
@Value @lombok.experimental.NonFinal class Value2 {
  public final int x;
  private final String name;
  public @java.lang.SuppressWarnings("all") int getX() {
    return this.x;
  }
  public @java.lang.SuppressWarnings("all") String getName() {
    return this.name;
  }
  public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) {
    if ((o == this))
        return true;
    if ((! (o instanceof Value2)))
        return false;
    final @java.lang.SuppressWarnings("all") Value2 other = (Value2) o;
    if ((! other.canEqual((java.lang.Object) this)))
        return false;
    if ((this.getX() != other.getX()))
        return false;
    final java.lang.Object this$name = this.getName();
    final java.lang.Object other$name = other.getName();
    if (((this$name == null) ? (other$name != null) : (! this$name.equals(other$name))))
        return false;
    return true;
  }
  protected @java.lang.SuppressWarnings("all") boolean canEqual(final java.lang.Object other) {
    return (other instanceof Value2);
  }
  public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() {
    final int PRIME = 59;
    int result = 1;
    result = ((result * PRIME) + this.getX());
    final java.lang.Object $name = this.getName();
    result = ((result * PRIME) + (($name == null) ? 0 : $name.hashCode()));
    return result;
  }
  public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() {
    return (((("Value2(x=" + this.getX()) + ", name=") + this.getName()) + ")");
  }
  public @java.beans.ConstructorProperties({"x", "name"}) @java.lang.SuppressWarnings("all") Value2(final int x, final String name) {
    super();
    this.x = x;
    this.name = name;
  }
}
final @Value class Value3 {
  private @lombok.experimental.NonFinal int x;
  private final int y;
  public @java.lang.SuppressWarnings("all") int getX() {
    return this.x;
  }
  public @java.lang.SuppressWarnings("all") int getY() {
    return this.y;
  }
  public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) {
    if ((o == this))
        return true;
    if ((! (o instanceof Value3)))
        return false;
    final @java.lang.SuppressWarnings("all") Value3 other = (Value3) o;
    if ((this.getX() != other.getX()))
        return false;
    if ((this.getY() != other.getY()))
        return false;
    return true;
  }
  public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() {
    final int PRIME = 59;
    int result = 1;
    result = ((result * PRIME) + this.getX());
    result = ((result * PRIME) + this.getY());
    return result;
  }
  public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() {
    return (((("Value3(x=" + this.getX()) + ", y=") + this.getY()) + ")");
  }
  public @java.beans.ConstructorProperties({"x", "y"}) @java.lang.SuppressWarnings("all") Value3(final int x, final int y) {
    super();
    this.x = x;
    this.y = y;
  }
}


text:
package mud.objects;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import mud.ObjectFlag;
import mud.MUDObject;
import mud.TypeFlag;
import mud.events.EventSource;
import mud.events.SayEvent;
import mud.events.SayEventListener;
import mud.interfaces.Instance;
import mud.misc.Direction;
import mud.misc.Trigger;
import mud.misc.TriggerType;
import mud.misc.Zone;
import mud.objects.Thing;
import mud.objects.exits.Door;
import mud.utils.Utils;
import mud.weather.Weather;

/**
 * Room Class
 *
 * @author Jeremy N. Harton
 *
 */
public class Room extends MUDObject implements EventSource, Instance
{
	//public static final String DAY = "DAY";
	//public static final String NIGHT = "NIGHT";

	// NOTE: for room, location and "parent" are the same
	private RoomType roomType = RoomType.NONE;              // the type of room (I = Inside, O = Outside, P = Protected, N = None)
	private Terrain terrain = Terrain.NONE;                 // terrain type of the room (affects movement speed?)

	// x, y - size of the room ( 10x10 default )
	// z - height of room ( 10 default )
	private int x = 10, y = 10, z = 10;

	private transient Zone zone = null;                     // the zone this room belongs to

	private transient List<Exit> exits;                     // the exits leading away from the room
	private transient String exitNames;                     // formatted string containing the usable exit names

	private transient List<Thing> things;                   // the objects the room contains (things)
	private transient List<Item> items;                     // the objects the room contains (items)

	public String music;                                    // the ambient background music for this room (filename, probably a wav file)
	//public String timeOfDay = DAY;                        // replace this with an enum with one type per each or a hashmap string, boolean?
	// DAY or NIGHT

	private Weather weather;                                // the weather in this room

	private Integer instance_id = -1;                       // instance_id (transient?)

	public transient char[] tiles;

	private transient List<Player> listeners;               // Player(s) in the Room listening to what is being said
	private transient List<SayEventListener> _listeners;    // Other things listening to say events?

	private transient Map<TriggerType, List<Trigger>> triggers; //

	// initialize trigger lists
	/*{
		this.triggers.put(TriggerType.onEnter, new LinkedList<Trigger>());
		this.triggers.put(TriggerType.onLeave, new LinkedList<Trigger>());
	}*/

	private Exit[] dirMap = new Exit[9]; // dirMap[Direction.NORTH]

	// misc note: parent == location

	/**
	 * Construct a room using only default parameter
	 */
	public Room() {
		super(-1);

		this.name = "room";
		this.desc = "You see nothing.";
		this.flags = EnumSet.of(ObjectFlag.SILENT);
		this.location = 0;

		this.type = TypeFlag.ROOM;

		this.exits = new ArrayList<Exit>();

		this.tiles = new char[x * y];
		Arrays.fill(tiles, 'X');

		this.items = new ArrayList<Item>();
		this.things = new ArrayList<Thing>();

		this.listeners = new ArrayList<Player>();
		this._listeners = new ArrayList<SayEventListener>();

		this.triggers = new HashMap<TriggerType, List<Trigger>>();

		this.triggers.put(TriggerType.onEnter, new LinkedList<Trigger>());
		this.triggers.put(TriggerType.onLeave, new LinkedList<Trigger>());
	}

	/**
	 * Copy Constructor
	 *
	 * @param toCopy
	 */
	public Room(final Room toCopy)
	{
		super(toCopy.getDBRef());

		this.name = toCopy.getName();         // Set the name
		this.desc = toCopy.getDesc();         // Set the description to the default
		this.flags = toCopy.getFlags();       // Set the flags
		this.location = toCopy.getLocation(); // Set the location

		this.type = TypeFlag.ROOM;

		this.exits = new ArrayList<Exit>();

		this.tiles = new char[x * y];
		Arrays.fill(tiles, 'X');

		this.items = new ArrayList<Item>();
		this.things = new ArrayList<Thing>();

		this.listeners = new ArrayList<Player>();
		this._listeners = new ArrayList<SayEventListener>();

		this.triggers = new HashMap<TriggerType, List<Trigger>>();

		this.triggers.put(TriggerType.onEnter, new LinkedList<Trigger>());
		this.triggers.put(TriggerType.onLeave, new LinkedList<Trigger>());
	}

	/**
	 * Loading Constructor
	 *
	 * @param tempDBREF
	 * @param tempName
	 * @param tempFlags
	 * @param tempDesc
	 * @param tempLocation
	 */
	public Room(int tempDBREF, String tempName, final EnumSet<ObjectFlag> tempFlags, String tempDesc, int tempLocation)
	{
		super(tempDBREF);

		this.name = tempName;         // Set the name
		this.desc = tempDesc;         // Set the description
		this.flags = tempFlags;       // Set room flags
		this.location = tempLocation; // Set the location

		this.type = TypeFlag.ROOM;

		this.exits = new ArrayList<Exit>();

		this.tiles = new char[x * y];
		Arrays.fill(tiles, 'X');

		this.items = new ArrayList<Item>();
		this.things = new ArrayList<Thing>();

		this.listeners = new ArrayList<Player>();
		this._listeners = new ArrayList<SayEventListener>();

		this.triggers = new HashMap<TriggerType, List<Trigger>>();
		this.triggers.put(TriggerType.onEnter, new LinkedList<Trigger>());
		this.triggers.put(TriggerType.onLeave, new LinkedList<Trigger>());
	}

	/**
	 * Set parent room.
	 *
	 * @param parentRoomId
	 */
	public void setParent(int parentRoomId) {
		this.setLocation(parentRoomId);
	}

	/**
	 * Get parent room.
	 *
	 * @return int parent room dbref number
	 */
	public int getParent() {
		return this.getLocation();
	}

	/**
	 * Set the type of room.
	 *
	 * @param newRoomType
	 */
	public void setRoomType(final RoomType newRoomType) {
		this.roomType = newRoomType;
	}

	/**
	 * Get the type of room.
	 *
	 * @return
	 */
	public RoomType getRoomType() {
		return this.roomType;
	}

	public Weather getWeather() {
		return this.weather;
	}

	public void setWeather(Weather weather) {
		this.weather = weather;
	}

	public Exit getExit(final Direction dir) {
		return this.dirMap[dir.getValue()];
	}
	/**
	 * getExits
	 *
	 * NOTE: the returned list /should/ be unmodifiable. that is, the
	 * return here is not for modifying the list the exits
	 *
	 * @return the exits
	 */
	public List<Exit> getExits() {
		return Collections.unmodifiableList(exits);
	}

	// TODO excise method
	public String getExitNames() {
		if( exits.size() > 0 ) {
			final StringBuilder buf = new StringBuilder();

			for (final Exit e : exits) {
				if( e instanceof Door ) {
					Door d = (Door) e;

					if( getDBRef() == d.getLocation() ) {
						if( d.isLocked() ) buf.append(", ").append(d.getName().split("/")[0] + " (locked)");
						else               buf.append(", ").append(d.getName().split("/")[0]);
					}
					else if( getDBRef() == d.getDestination() ) {
						if( d.isLocked() ) buf.append(", ").append(d.getName().split("/")[1] + " (locked)");
						else               buf.append(", ").append(d.getName().split("/")[1]);
					}
				}
				else buf.append(", ").append(e.getName());
			}

			return buf.toString().substring(2); // clip off the initial, unnecessary " ,"
		}
		else return "";
	}

	public String getExitNames(boolean visible) {
		return "";
	}

	// TODO excise method
	public String getVisibleExitNames() {
		final StringBuilder buf = new StringBuilder();
		for (final Exit e : exits) {
			if (!e.getFlags().contains("D")) {
				if( e instanceof Door ) {
					Door d = (Door) e;

					if( getDBRef() == d.getLocation() ) {
						if( d.isLocked() ) buf.append(", ").append(d.getName().split("/")[0] + " (locked)");
						else buf.append(", ").append(d.getName().split("/")[0]);
					}
					else if( getDBRef() == d.getDestination() ) {
						if( d.isLocked() ) buf.append(", ").append(d.getName().split("/")[1] + " (locked)");
						else buf.append(", ").append(d.getName().split("/")[1]);
					}
				}
				else buf.append(", ").append(e.getName());
			}
		}
		return buf.toString().substring(2); // clip off the initial, unecessary " ,"
	}

	/**
	 * setExits
	 *
	 * Make this room have the exits specified
	 *
	 * @param exits the exits to set
	 */
	public void setExits(final List<Exit> exits) {
		this.exits.clear();
		this.exits.addAll( exits );
	}

	public void addExit(final Exit exit) {
		this.exits.add(exit);
	}

	public void removeExit(final Exit exit) {
		this.exits.remove(exit);
	}

	public void setDimension(final String dim, final int size) {
		switch( dim.toLowerCase() ) {
		case "x": this.x = size; break;
		case "y": this.y = size; break;
		case "z": this.z = size; break;
		default:  break;
		}
	}

	public int getDimension(final String dim) {
		int m = 0; // magnitude?

		switch( dim.toLowerCase() ) {
		case "x": m = this.x; break;
		case "y": m = this.y; break;
		case "z": m = this.z; break;
		default:  m = -1;     break;
		}

		return m;
	}

	// adjustDimensions with just change data? does this render set/get redundant?
	public void setDimensions(int xSize, int ySize, int zSize) {
		this.x = xSize;
		this.y = ySize;
		this.z = zSize;
	}

	public List<Player> getListeners() {
		return this.listeners;
	}

	public void addListener(Player player) {
		this.listeners.add(player);
	}

	public void removeListener(Player player) {
		this.listeners.remove(player);
	}

	/* Say Event Stuff */
	public synchronized void addSayEventListener(SayEventListener listener)  {
		this._listeners.add(listener);
	}

	public synchronized void removeSayEventListener(SayEventListener listener)   {
		this._listeners.remove(listener);
	}

	/**
	 * Add an Item to the room.
	 *
	 * @param item
	 */
	public void addItem(final Item item) {
		this.items.add(item);
	}

	/**
	 * Add multiple items to the room at the same time.
	 *
	 * @param items List of Item(s)
	 */
	public void addItems(final List<Item> items) {
		this.items.addAll(items);
	}

	/**
	 * Remove an Item from the room.
	 * @param item
	 */
	public void removeItem(final Item item) {
		this.items.remove(item);
	}

	public void removeItems(final List<Item> items) {
		this.items.removeAll(items);
	}

	/**
	 * Get a List of the Item(s) in the Room.
	 *
	 * @return an unmodifiable list
	 */
	public List<Item> getItems() {
		return Collections.unmodifiableList(this.items);
	}

	/**
	 * Add a Thing to the room
	 *
	 * @param thing the Thing to add
	 */
	public void addThing(final Thing thing) {
		this.things.add(thing);
	}

	/**
	 * Add multiple Thing(s) to the room at the same time.
	 *
	 * @param things List of Thing(s) to add
	 */
	public void addThings(final List<Thing> things) {
		this.things.addAll( things );
	}

	/**
	 * Remove a Thing from the room
	 *
	 * @param thing
	 */
	public void removeThing(final Thing thing) {
		this.things.remove(thing);
	}

	public void removeThings(final List<Thing> things) {
		this.things.removeAll( things );
	}

	public List<Thing> getThings() {
		return this.things;
	}

	/* Triggers & Scripting */
	public void setTrigger(TriggerType type, Trigger trigger) {
		this.triggers.get(type).add(trigger);
	}

	public List<Trigger> getTriggers(TriggerType triggerType) {
		return Collections.unmodifiableList(this.triggers.get(triggerType));
	}

	public void setTerrain(final Terrain newTerrain) {
		this.terrain = newTerrain;
	}

	public Terrain getTerrain() {
		return this.terrain;
	}

	public void setZone(final Zone zone) {
		this.zone = zone;
	}

	public Zone getZone() {
		return this.zone;
	}

	public void setDirectionExit(final Integer direction, final Exit exit) {
		this.dirMap[direction] = exit;
	}

	// call this method whenever you want to notify the event listeners
	@Override
	public synchronized void fireEvent(String message) {
		final SayEvent sayEvent = new SayEvent(this, message);

		for(final SayEventListener sl : this._listeners) {
			sl.handleSayEvent(sayEvent);
		}
	}

	// instancing stuff

	// implements
	public Boolean isInstance() {
		if( this.instance_id > 0 ) {
			return true;
		}

		return false;
	}

	// implements
	public Integer getInstanceId() {
		return this.instance_id;
	}

	/**
	 * Translate the persistent aspects of the room into the string
	 * format used by the database
	 */
	public String toDB() {
		String[] output = new String[9];
		output[0] = "" + this.getDBRef();                         // database reference number
		output[1] = this.getName();                               // name
		output[2] = "" + TypeFlag.asLetter(this.type);            // flags
		output[2] = output[2] + getFlagsAsString();
		output[3] = this.getDesc();                               // description
		output[4] = "" + this.getLocation();                      // location (a.k.a parent)
		output[5] = "" + this.getRoomType().toString().charAt(0); // room type
		output[6] = this.x + "," + this.y + "," + this.z;         // room dimensions (x,y,z)
		output[7] = "-1";                                         // room terrain
		output[8] = (zone != null) ? "" + zone.getId() : "-1";    // zone data

		return Utils.join(output, "#");
	}

	// TODO remove?
	public String toJSON() {
		final StringBuilder sb = new StringBuilder();

		int count = 0;

		sb.append("{\n");

		sb.append("\t\"dbref\"" + ": \"" + getDBRef() + "\",\n");
		sb.append("\t\"name\"" + ": \"" + getName() + "\",\n");
		sb.append("\t\"flags\"" + ": \"" + TypeFlag.asLetter(this.type) + getFlagsAsString() + "\",\n");
		sb.append("\t\"desc\"" + ": \"" + getDesc() + "\",\n");
		sb.append("\t\"location\"" + ": \"" + getLocation() + "\",\n");

		/*sb.append("\n");

		sb.append("\t\"names\"" + ":\n");

		sb.append("\t{\n");

		int numNames = names.size();
		count = 0;

		for(final String name : names) {
			sb.append("\t\t\"name\"" + ": \"" + name + "\"");
			if( count < numNames ) sb.append(",\n");
			else                   sb.append("\n");
			count++;
		}

		sb.append("\t},\n");*/

		sb.append("}\n");

		return sb.toString();
	}

	public String toString() {
		return getName() + " (#" + getDBRef() + ")";
	}
}


text:
package com.solar.ikfa.http.body;

public interface ProgressListener {

    void onProgress(long bytesRead, long contentLength, boolean done);
}