code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use ArrayObject;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
use PhpOffice\PhpSpreadsheet\Chart\Chart;
use PhpOffice\PhpSpreadsheet\Collection\Cells;
use PhpOffice\PhpSpreadsheet\Collection\CellsFactory;
use PhpOffice\PhpSpreadsheet\Comment;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\IComparable;
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\Style;
class Worksheet implements IComparable
{
// Break types
const BREAK_NONE = 0;
const BREAK_ROW = 1;
const BREAK_COLUMN = 2;
// Sheet state
const SHEETSTATE_VISIBLE = 'visible';
const SHEETSTATE_HIDDEN = 'hidden';
const SHEETSTATE_VERYHIDDEN = 'veryHidden';
/**
* Maximum 31 characters allowed for sheet title.
*
* @var int
*/
const SHEET_TITLE_MAXIMUM_LENGTH = 31;
/**
* Invalid characters in sheet title.
*
* @var array
*/
private static $invalidCharacters = ['*', ':', '/', '\\', '?', '[', ']'];
/**
* Parent spreadsheet.
*
* @var Spreadsheet
*/
private $parent;
/**
* Collection of cells.
*
* @var Cells
*/
private $cellCollection;
/**
* Collection of row dimensions.
*
* @var RowDimension[]
*/
private $rowDimensions = [];
/**
* Default row dimension.
*
* @var RowDimension
*/
private $defaultRowDimension;
/**
* Collection of column dimensions.
*
* @var ColumnDimension[]
*/
private $columnDimensions = [];
/**
* Default column dimension.
*
* @var ColumnDimension
*/
private $defaultColumnDimension;
/**
* Collection of drawings.
*
* @var ArrayObject<int, BaseDrawing>
*/
private $drawingCollection;
/**
* Collection of Chart objects.
*
* @var ArrayObject<int, Chart>
*/
private $chartCollection;
/**
* Worksheet title.
*
* @var string
*/
private $title;
/**
* Sheet state.
*
* @var string
*/
private $sheetState;
/**
* Page setup.
*
* @var PageSetup
*/
private $pageSetup;
/**
* Page margins.
*
* @var PageMargins
*/
private $pageMargins;
/**
* Page header/footer.
*
* @var HeaderFooter
*/
private $headerFooter;
/**
* Sheet view.
*
* @var SheetView
*/
private $sheetView;
/**
* Protection.
*
* @var Protection
*/
private $protection;
/**
* Collection of styles.
*
* @var Style[]
*/
private $styles = [];
/**
* Conditional styles. Indexed by cell coordinate, e.g. 'A1'.
*
* @var array
*/
private $conditionalStylesCollection = [];
/**
* Is the current cell collection sorted already?
*
* @var bool
*/
private $cellCollectionIsSorted = false;
/**
* Collection of breaks.
*
* @var int[]
*/
private $breaks = [];
/**
* Collection of merged cell ranges.
*
* @var string[]
*/
private $mergeCells = [];
/**
* Collection of protected cell ranges.
*
* @var string[]
*/
private $protectedCells = [];
/**
* Autofilter Range and selection.
*
* @var AutoFilter
*/
private $autoFilter;
/**
* Freeze pane.
*
* @var null|string
*/
private $freezePane;
/**
* Default position of the right bottom pane.
*
* @var null|string
*/
private $topLeftCell;
/**
* Show gridlines?
*
* @var bool
*/
private $showGridlines = true;
/**
* Print gridlines?
*
* @var bool
*/
private $printGridlines = false;
/**
* Show row and column headers?
*
* @var bool
*/
private $showRowColHeaders = true;
/**
* Show summary below? (Row/Column outline).
*
* @var bool
*/
private $showSummaryBelow = true;
/**
* Show summary right? (Row/Column outline).
*
* @var bool
*/
private $showSummaryRight = true;
/**
* Collection of comments.
*
* @var Comment[]
*/
private $comments = [];
/**
* Active cell. (Only one!).
*
* @var string
*/
private $activeCell = 'A1';
/**
* Selected cells.
*
* @var string
*/
private $selectedCells = 'A1';
/**
* Cached highest column.
*
* @var int
*/
private $cachedHighestColumn = 1;
/**
* Cached highest row.
*
* @var int
*/
private $cachedHighestRow = 1;
/**
* Right-to-left?
*
* @var bool
*/
private $rightToLeft = false;
/**
* Hyperlinks. Indexed by cell coordinate, e.g. 'A1'.
*
* @var array
*/
private $hyperlinkCollection = [];
/**
* Data validation objects. Indexed by cell coordinate, e.g. 'A1'.
*
* @var array
*/
private $dataValidationCollection = [];
/**
* Tab color.
*
* @var null|Color
*/
private $tabColor;
/**
* Dirty flag.
*
* @var bool
*/
private $dirty = true;
/**
* Hash.
*
* @var string
*/
private $hash;
/**
* CodeName.
*
* @var string
*/
private $codeName;
/**
* Create a new worksheet.
*
* @param string $title
*/
public function __construct(?Spreadsheet $parent = null, $title = 'Worksheet')
{
// Set parent and title
$this->parent = $parent;
$this->setTitle($title, false);
// setTitle can change $pTitle
$this->setCodeName($this->getTitle());
$this->setSheetState(self::SHEETSTATE_VISIBLE);
$this->cellCollection = CellsFactory::getInstance($this);
// Set page setup
$this->pageSetup = new PageSetup();
// Set page margins
$this->pageMargins = new PageMargins();
// Set page header/footer
$this->headerFooter = new HeaderFooter();
// Set sheet view
$this->sheetView = new SheetView();
// Drawing collection
$this->drawingCollection = new ArrayObject();
// Chart collection
$this->chartCollection = new ArrayObject();
// Protection
$this->protection = new Protection();
// Default row dimension
$this->defaultRowDimension = new RowDimension(null);
// Default column dimension
$this->defaultColumnDimension = new ColumnDimension(null);
$this->autoFilter = new AutoFilter(null, $this);
}
/**
* Disconnect all cells from this Worksheet object,
* typically so that the worksheet object can be unset.
*/
public function disconnectCells(): void
{
if ($this->cellCollection !== null) {
$this->cellCollection->unsetWorksheetCells();
// @phpstan-ignore-next-line
$this->cellCollection = null;
}
// detach ourself from the workbook, so that it can then delete this worksheet successfully
// @phpstan-ignore-next-line
$this->parent = null;
}
/**
* Code to execute when this worksheet is unset().
*/
public function __destruct()
{
Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title);
$this->disconnectCells();
$this->rowDimensions = [];
}
/**
* Return the cell collection.
*
* @return Cells
*/
public function getCellCollection()
{
return $this->cellCollection;
}
/**
* Get array of invalid characters for sheet title.
*
* @return array
*/
public static function getInvalidCharacters()
{
return self::$invalidCharacters;
}
/**
* Check sheet code name for valid Excel syntax.
*
* @param string $sheetCodeName The string to check
*
* @return string The valid string
*/
private static function checkSheetCodeName($sheetCodeName)
{
$charCount = Shared\StringHelper::countCharacters($sheetCodeName);
if ($charCount == 0) {
throw new Exception('Sheet code name cannot be empty.');
}
// Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'"
if (
(str_replace(self::$invalidCharacters, '', $sheetCodeName) !== $sheetCodeName) ||
(Shared\StringHelper::substring($sheetCodeName, -1, 1) == '\'') ||
(Shared\StringHelper::substring($sheetCodeName, 0, 1) == '\'')
) {
throw new Exception('Invalid character found in sheet code name');
}
// Enforce maximum characters allowed for sheet title
if ($charCount > self::SHEET_TITLE_MAXIMUM_LENGTH) {
throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.');
}
return $sheetCodeName;
}
/**
* Check sheet title for valid Excel syntax.
*
* @param string $sheetTitle The string to check
*
* @return string The valid string
*/
private static function checkSheetTitle($sheetTitle)
{
// Some of the printable ASCII characters are invalid: * : / \ ? [ ]
if (str_replace(self::$invalidCharacters, '', $sheetTitle) !== $sheetTitle) {
throw new Exception('Invalid character found in sheet title');
}
// Enforce maximum characters allowed for sheet title
if (Shared\StringHelper::countCharacters($sheetTitle) > self::SHEET_TITLE_MAXIMUM_LENGTH) {
throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet title.');
}
return $sheetTitle;
}
/**
* Get a sorted list of all cell coordinates currently held in the collection by row and column.
*
* @param bool $sorted Also sort the cell collection?
*
* @return string[]
*/
public function getCoordinates($sorted = true)
{
if ($this->cellCollection == null) {
return [];
}
if ($sorted) {
return $this->cellCollection->getSortedCoordinates();
}
return $this->cellCollection->getCoordinates();
}
/**
* Get collection of row dimensions.
*
* @return RowDimension[]
*/
public function getRowDimensions()
{
return $this->rowDimensions;
}
/**
* Get default row dimension.
*
* @return RowDimension
*/
public function getDefaultRowDimension()
{
return $this->defaultRowDimension;
}
/**
* Get collection of column dimensions.
*
* @return ColumnDimension[]
*/
public function getColumnDimensions()
{
return $this->columnDimensions;
}
/**
* Get default column dimension.
*
* @return ColumnDimension
*/
public function getDefaultColumnDimension()
{
return $this->defaultColumnDimension;
}
/**
* Get collection of drawings.
*
* @return ArrayObject<int, BaseDrawing>
*/
public function getDrawingCollection()
{
return $this->drawingCollection;
}
/**
* Get collection of charts.
*
* @return ArrayObject<int, Chart>
*/
public function getChartCollection()
{
return $this->chartCollection;
}
/**
* Add chart.
*
* @param null|int $chartIndex Index where chart should go (0,1,..., or null for last)
*
* @return Chart
*/
public function addChart(Chart $chart, $chartIndex = null)
{
$chart->setWorksheet($this);
if ($chartIndex === null) {
$this->chartCollection[] = $chart;
} else {
// Insert the chart at the requested index
array_splice($this->chartCollection, $chartIndex, 0, [$chart]);
}
return $chart;
}
/**
* Return the count of charts on this worksheet.
*
* @return int The number of charts
*/
public function getChartCount()
{
return count($this->chartCollection);
}
/**
* Get a chart by its index position.
*
* @param string $index Chart index position
*
* @return Chart|false
*/
public function getChartByIndex($index)
{
$chartCount = count($this->chartCollection);
if ($chartCount == 0) {
return false;
}
if ($index === null) {
$index = --$chartCount;
}
if (!isset($this->chartCollection[$index])) {
return false;
}
return $this->chartCollection[$index];
}
/**
* Return an array of the names of charts on this worksheet.
*
* @return string[] The names of charts
*/
public function getChartNames()
{
$chartNames = [];
foreach ($this->chartCollection as $chart) {
$chartNames[] = $chart->getName();
}
return $chartNames;
}
/**
* Get a chart by name.
*
* @param string $chartName Chart name
*
* @return Chart|false
*/
public function getChartByName($chartName)
{
$chartCount = count($this->chartCollection);
if ($chartCount == 0) {
return false;
}
foreach ($this->chartCollection as $index => $chart) {
if ($chart->getName() == $chartName) {
return $this->chartCollection[$index];
}
}
return false;
}
/**
* Refresh column dimensions.
*
* @return $this
*/
public function refreshColumnDimensions()
{
$currentColumnDimensions = $this->getColumnDimensions();
$newColumnDimensions = [];
foreach ($currentColumnDimensions as $objColumnDimension) {
$newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension;
}
$this->columnDimensions = $newColumnDimensions;
return $this;
}
/**
* Refresh row dimensions.
*
* @return $this
*/
public function refreshRowDimensions()
{
$currentRowDimensions = $this->getRowDimensions();
$newRowDimensions = [];
foreach ($currentRowDimensions as $objRowDimension) {
$newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension;
}
$this->rowDimensions = $newRowDimensions;
return $this;
}
/**
* Calculate worksheet dimension.
*
* @return string String containing the dimension of this worksheet
*/
public function calculateWorksheetDimension()
{
// Return
return 'A1:' . $this->getHighestColumn() . $this->getHighestRow();
}
/**
* Calculate worksheet data dimension.
*
* @return string String containing the dimension of this worksheet that actually contain data
*/
public function calculateWorksheetDataDimension()
{
// Return
return 'A1:' . $this->getHighestDataColumn() . $this->getHighestDataRow();
}
/**
* Calculate widths for auto-size columns.
*
* @return $this
*/
public function calculateColumnWidths()
{
// initialize $autoSizes array
$autoSizes = [];
foreach ($this->getColumnDimensions() as $colDimension) {
if ($colDimension->getAutoSize()) {
$autoSizes[$colDimension->getColumnIndex()] = -1;
}
}
// There is only something to do if there are some auto-size columns
if (!empty($autoSizes)) {
// build list of cells references that participate in a merge
$isMergeCell = [];
foreach ($this->getMergeCells() as $cells) {
foreach (Coordinate::extractAllCellReferencesInRange($cells) as $cellReference) {
$isMergeCell[$cellReference] = true;
}
}
// loop through all cells in the worksheet
foreach ($this->getCoordinates(false) as $coordinate) {
$cell = $this->getCellOrNull($coordinate);
if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) {
//Determine if cell is in merge range
$isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]);
//By default merged cells should be ignored
$isMergedButProceed = false;
//The only exception is if it's a merge range value cell of a 'vertical' randge (1 column wide)
if ($isMerged && $cell->isMergeRangeValueCell()) {
$range = $cell->getMergeRange();
$rangeBoundaries = Coordinate::rangeDimension($range);
if ($rangeBoundaries[0] == 1) {
$isMergedButProceed = true;
}
}
// Determine width if cell does not participate in a merge or does and is a value cell of 1-column wide range
if (!$isMerged || $isMergedButProceed) {
// Calculated value
// To formatted string
$cellValue = NumberFormat::toFormattedString(
$cell->getCalculatedValue(),
$this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode()
);
if ($cellValue !== null && $cellValue !== '') {
$autoSizes[$this->cellCollection->getCurrentColumn()] = max(
(float) $autoSizes[$this->cellCollection->getCurrentColumn()],
(float) Shared\Font::calculateColumnWidth(
$this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(),
$cellValue,
$this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(),
$this->getParent()->getDefaultStyle()->getFont()
)
);
}
}
}
}
// adjust column widths
foreach ($autoSizes as $columnIndex => $width) {
if ($width == -1) {
$width = $this->getDefaultColumnDimension()->getWidth();
}
$this->getColumnDimension($columnIndex)->setWidth($width);
}
}
return $this;
}
/**
* Get parent.
*
* @return Spreadsheet
*/
public function getParent()
{
return $this->parent;
}
/**
* Re-bind parent.
*
* @return $this
*/
public function rebindParent(Spreadsheet $parent)
{
if ($this->parent !== null) {
$definedNames = $this->parent->getDefinedNames();
foreach ($definedNames as $definedName) {
$parent->addDefinedName($definedName);
}
$this->parent->removeSheetByIndex(
$this->parent->getIndex($this)
);
}
$this->parent = $parent;
return $this;
}
/**
* Get title.
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set title.
*
* @param string $title String containing the dimension of this worksheet
* @param bool $updateFormulaCellReferences Flag indicating whether cell references in formulae should
* be updated to reflect the new sheet name.
* This should be left as the default true, unless you are
* certain that no formula cells on any worksheet contain
* references to this worksheet
* @param bool $validate False to skip validation of new title. WARNING: This should only be set
* at parse time (by Readers), where titles can be assumed to be valid.
*
* @return $this
*/
public function setTitle($title, $updateFormulaCellReferences = true, $validate = true)
{
// Is this a 'rename' or not?
if ($this->getTitle() == $title) {
return $this;
}
// Old title
$oldTitle = $this->getTitle();
if ($validate) {
// Syntax check
self::checkSheetTitle($title);
if ($this->parent) {
// Is there already such sheet name?
if ($this->parent->sheetNameExists($title)) {
// Use name, but append with lowest possible integer
if (Shared\StringHelper::countCharacters($title) > 29) {
$title = Shared\StringHelper::substring($title, 0, 29);
}
$i = 1;
while ($this->parent->sheetNameExists($title . ' ' . $i)) {
++$i;
if ($i == 10) {
if (Shared\StringHelper::countCharacters($title) > 28) {
$title = Shared\StringHelper::substring($title, 0, 28);
}
} elseif ($i == 100) {
if (Shared\StringHelper::countCharacters($title) > 27) {
$title = Shared\StringHelper::substring($title, 0, 27);
}
}
}
$title .= " $i";
}
}
}
// Set title
$this->title = $title;
$this->dirty = true;
if ($this->parent && $this->parent->getCalculationEngine()) {
// New title
$newTitle = $this->getTitle();
$this->parent->getCalculationEngine()
->renameCalculationCacheForWorksheet($oldTitle, $newTitle);
if ($updateFormulaCellReferences) {
ReferenceHelper::getInstance()->updateNamedFormulas($this->parent, $oldTitle, $newTitle);
}
}
return $this;
}
/**
* Get sheet state.
*
* @return string Sheet state (visible, hidden, veryHidden)
*/
public function getSheetState()
{
return $this->sheetState;
}
/**
* Set sheet state.
*
* @param string $value Sheet state (visible, hidden, veryHidden)
*
* @return $this
*/
public function setSheetState($value)
{
$this->sheetState = $value;
return $this;
}
/**
* Get page setup.
*
* @return PageSetup
*/
public function getPageSetup()
{
return $this->pageSetup;
}
/**
* Set page setup.
*
* @return $this
*/
public function setPageSetup(PageSetup $pageSetup)
{
$this->pageSetup = $pageSetup;
return $this;
}
/**
* Get page margins.
*
* @return PageMargins
*/
public function getPageMargins()
{
return $this->pageMargins;
}
/**
* Set page margins.
*
* @return $this
*/
public function setPageMargins(PageMargins $pageMargins)
{
$this->pageMargins = $pageMargins;
return $this;
}
/**
* Get page header/footer.
*
* @return HeaderFooter
*/
public function getHeaderFooter()
{
return $this->headerFooter;
}
/**
* Set page header/footer.
*
* @return $this
*/
public function setHeaderFooter(HeaderFooter $headerFooter)
{
$this->headerFooter = $headerFooter;
return $this;
}
/**
* Get sheet view.
*
* @return SheetView
*/
public function getSheetView()
{
return $this->sheetView;
}
/**
* Set sheet view.
*
* @return $this
*/
public function setSheetView(SheetView $sheetView)
{
$this->sheetView = $sheetView;
return $this;
}
/**
* Get Protection.
*
* @return Protection
*/
public function getProtection()
{
return $this->protection;
}
/**
* Set Protection.
*
* @return $this
*/
public function setProtection(Protection $protection)
{
$this->protection = $protection;
$this->dirty = true;
return $this;
}
/**
* Get highest worksheet column.
*
* @param null|int|string $row Return the data highest column for the specified row,
* or the highest column of any row if no row number is passed
*
* @return string Highest column name
*/
public function getHighestColumn($row = null)
{
if (empty($row)) {
return Coordinate::stringFromColumnIndex($this->cachedHighestColumn);
}
return $this->getHighestDataColumn($row);
}
/**
* Get highest worksheet column that contains data.
*
* @param null|int|string $row Return the highest data column for the specified row,
* or the highest data column of any row if no row number is passed
*
* @return string Highest column name that contains data
*/
public function getHighestDataColumn($row = null)
{
return $this->cellCollection->getHighestColumn($row);
}
/**
* Get highest worksheet row.
*
* @param null|string $column Return the highest data row for the specified column,
* or the highest row of any column if no column letter is passed
*
* @return int Highest row number
*/
public function getHighestRow($column = null)
{
if ($column == null) {
return $this->cachedHighestRow;
}
return $this->getHighestDataRow($column);
}
/**
* Get highest worksheet row that contains data.
*
* @param null|string $column Return the highest data row for the specified column,
* or the highest data row of any column if no column letter is passed
*
* @return int Highest row number that contains data
*/
public function getHighestDataRow($column = null)
{
return $this->cellCollection->getHighestRow($column);
}
/**
* Get highest worksheet column and highest row that have cell records.
*
* @return array Highest column name and highest row number
*/
public function getHighestRowAndColumn()
{
return $this->cellCollection->getHighestRowAndColumn();
}
/**
* Set a cell value.
*
* @param string $coordinate Coordinate of the cell, eg: 'A1'
* @param mixed $value Value of the cell
*
* @return $this
*/
public function setCellValue($coordinate, $value)
{
$this->getCell($coordinate)->setValue($value);
return $this;
}
/**
* Set a cell value by using numeric cell coordinates.
*
* @param int $columnIndex Numeric column coordinate of the cell
* @param int $row Numeric row coordinate of the cell
* @param mixed $value Value of the cell
*
* @return $this
*/
public function setCellValueByColumnAndRow($columnIndex, $row, $value)
{
$this->getCellByColumnAndRow($columnIndex, $row)->setValue($value);
return $this;
}
/**
* Set a cell value.
*
* @param string $coordinate Coordinate of the cell, eg: 'A1'
* @param mixed $value Value of the cell
* @param string $dataType Explicit data type, see DataType::TYPE_*
*
* @return $this
*/
public function setCellValueExplicit($coordinate, $value, $dataType)
{
// Set value
$this->getCell($coordinate)->setValueExplicit($value, $dataType);
return $this;
}
/**
* Set a cell value by using numeric cell coordinates.
*
* @param int $columnIndex Numeric column coordinate of the cell
* @param int $row Numeric row coordinate of the cell
* @param mixed $value Value of the cell
* @param string $dataType Explicit data type, see DataType::TYPE_*
*
* @return $this
*/
public function setCellValueExplicitByColumnAndRow($columnIndex, $row, $value, $dataType)
{
$this->getCellByColumnAndRow($columnIndex, $row)->setValueExplicit($value, $dataType);
return $this;
}
/**
* Get cell at a specific coordinate.
*
* @param string $coordinate Coordinate of the cell, eg: 'A1'
*
* @return Cell Cell that was found or created
*/
public function getCell(string $coordinate): Cell
{
// Shortcut for increased performance for the vast majority of simple cases
if ($this->cellCollection->has($coordinate)) {
/** @var Cell $cell */
$cell = $this->cellCollection->get($coordinate);
return $cell;
}
/** @var Worksheet $sheet */
[$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($coordinate);
$cell = $sheet->cellCollection->get($finalCoordinate);
return $cell ?? $sheet->createNewCell($finalCoordinate);
}
/**
* Get the correct Worksheet and coordinate from a coordinate that may
* contains reference to another sheet or a named range.
*
* @return array{0: Worksheet, 1: string}
*/
private function getWorksheetAndCoordinate(string $coordinate): array
{
$sheet = null;
$finalCoordinate = null;
// Worksheet reference?
if (strpos($coordinate, '!') !== false) {
$worksheetReference = self::extractSheetTitle($coordinate, true);
$sheet = $this->parent->getSheetByName($worksheetReference[0]);
$finalCoordinate = strtoupper($worksheetReference[1]);
if (!$sheet) {
throw new Exception('Sheet not found for name: ' . $worksheetReference[0]);
}
} elseif (
!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $coordinate) &&
preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/i', $coordinate)
) {
// Named range?
$namedRange = $this->validateNamedRange($coordinate, true);
if ($namedRange !== null) {
$sheet = $namedRange->getWorksheet();
if (!$sheet) {
throw new Exception('Sheet not found for named range: ' . $namedRange->getName());
}
$cellCoordinate = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!');
$finalCoordinate = str_replace('$', '', $cellCoordinate);
}
}
if (!$sheet || !$finalCoordinate) {
$sheet = $this;
$finalCoordinate = strtoupper($coordinate);
}
if (Coordinate::coordinateIsRange($finalCoordinate)) {
throw new Exception('Cell coordinate string can not be a range of cells.');
} elseif (strpos($finalCoordinate, '$') !== false) {
throw new Exception('Cell coordinate must not be absolute.');
}
return [$sheet, $finalCoordinate];
}
/**
* Get an existing cell at a specific coordinate, or null.
*
* @param string $coordinate Coordinate of the cell, eg: 'A1'
*
* @return null|Cell Cell that was found or null
*/
private function getCellOrNull($coordinate): ?Cell
{
// Check cell collection
if ($this->cellCollection->has($coordinate)) {
return $this->cellCollection->get($coordinate);
}
return null;
}
/**
* Get cell at a specific coordinate by using numeric cell coordinates.
*
* @param int $columnIndex Numeric column coordinate of the cell
* @param int $row Numeric row coordinate of the cell
*
* @return Cell Cell that was found/created or null
*/
public function getCellByColumnAndRow($columnIndex, $row): Cell
{
$columnLetter = Coordinate::stringFromColumnIndex($columnIndex);
$coordinate = $columnLetter . $row;
if ($this->cellCollection->has($coordinate)) {
/** @var Cell $cell */
$cell = $this->cellCollection->get($coordinate);
return $cell;
}
// Create new cell object, if required
return $this->createNewCell($coordinate);
}
/**
* Create a new cell at the specified coordinate.
*
* @param string $coordinate Coordinate of the cell
*
* @return Cell Cell that was created
*/
private function createNewCell($coordinate)
{
$cell = new Cell(null, DataType::TYPE_NULL, $this);
$this->cellCollection->add($coordinate, $cell);
$this->cellCollectionIsSorted = false;
// Coordinates
[$column, $row] = Coordinate::coordinateFromString($coordinate);
$aIndexes = Coordinate::indexesFromString($coordinate);
if ($this->cachedHighestColumn < $aIndexes[0]) {
$this->cachedHighestColumn = $aIndexes[0];
}
if ($aIndexes[1] > $this->cachedHighestRow) {
$this->cachedHighestRow = $aIndexes[1];
}
// Cell needs appropriate xfIndex from dimensions records
// but don't create dimension records if they don't already exist
$rowDimension = $this->rowDimensions[$row] ?? null;
$columnDimension = $this->columnDimensions[$column] ?? null;
if ($rowDimension !== null && $rowDimension->getXfIndex() > 0) {
// then there is a row dimension with explicit style, assign it to the cell
$cell->setXfIndex($rowDimension->getXfIndex());
} elseif ($columnDimension !== null && $columnDimension->getXfIndex() > 0) {
// then there is a column dimension, assign it to the cell
$cell->setXfIndex($columnDimension->getXfIndex());
}
return $cell;
}
/**
* Does the cell at a specific coordinate exist?
*
* @param string $coordinate Coordinate of the cell eg: 'A1'
*
* @return bool
*/
public function cellExists($coordinate)
{
/** @var Worksheet $sheet */
[$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($coordinate);
return $sheet->cellCollection->has($finalCoordinate);
}
/**
* Cell at a specific coordinate by using numeric cell coordinates exists?
*
* @param int $columnIndex Numeric column coordinate of the cell
* @param int $row Numeric row coordinate of the cell
*
* @return bool
*/
public function cellExistsByColumnAndRow($columnIndex, $row)
{
return $this->cellExists(Coordinate::stringFromColumnIndex($columnIndex) . $row);
}
/**
* Get row dimension at a specific row.
*
* @param int $row Numeric index of the row
*/
public function getRowDimension(int $row): RowDimension
{
// Get row dimension
if (!isset($this->rowDimensions[$row])) {
$this->rowDimensions[$row] = new RowDimension($row);
$this->cachedHighestRow = max($this->cachedHighestRow, $row);
}
return $this->rowDimensions[$row];
}
/**
* Get column dimension at a specific column.
*
* @param string $column String index of the column eg: 'A'
*/
public function getColumnDimension(string $column): ColumnDimension
{
// Uppercase coordinate
$column = strtoupper($column);
// Fetch dimensions
if (!isset($this->columnDimensions[$column])) {
$this->columnDimensions[$column] = new ColumnDimension($column);
$columnIndex = Coordinate::columnIndexFromString($column);
if ($this->cachedHighestColumn < $columnIndex) {
$this->cachedHighestColumn = $columnIndex;
}
}
return $this->columnDimensions[$column];
}
/**
* Get column dimension at a specific column by using numeric cell coordinates.
*
* @param int $columnIndex Numeric column coordinate of the cell
*/
public function getColumnDimensionByColumn(int $columnIndex): ColumnDimension
{
return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex));
}
/**
* Get styles.
*
* @return Style[]
*/
public function getStyles()
{
return $this->styles;
}
/**
* Get style for cell.
*
* @param string $cellCoordinate Cell coordinate (or range) to get style for, eg: 'A1'
*
* @return Style
*/
public function getStyle($cellCoordinate)
{
// set this sheet as active
$this->parent->setActiveSheetIndex($this->parent->getIndex($this));
// set cell coordinate as active
$this->setSelectedCells($cellCoordinate);
return $this->parent->getCellXfSupervisor();
}
/**
* Get conditional styles for a cell.
*
* @param string $coordinate eg: 'A1'
*
* @return Conditional[]
*/
public function getConditionalStyles($coordinate)
{
$coordinate = strtoupper($coordinate);
if (!isset($this->conditionalStylesCollection[$coordinate])) {
$this->conditionalStylesCollection[$coordinate] = [];
}
return $this->conditionalStylesCollection[$coordinate];
}
/**
* Do conditional styles exist for this cell?
*
* @param string $coordinate eg: 'A1'
*
* @return bool
*/
public function conditionalStylesExists($coordinate)
{
return isset($this->conditionalStylesCollection[strtoupper($coordinate)]);
}
/**
* Removes conditional styles for a cell.
*
* @param string $coordinate eg: 'A1'
*
* @return $this
*/
public function removeConditionalStyles($coordinate)
{
unset($this->conditionalStylesCollection[strtoupper($coordinate)]);
return $this;
}
/**
* Get collection of conditional styles.
*
* @return array
*/
public function getConditionalStylesCollection()
{
return $this->conditionalStylesCollection;
}
/**
* Set conditional styles.
*
* @param string $coordinate eg: 'A1'
* @param Conditional[] $styles
*
* @return $this
*/
public function setConditionalStyles($coordinate, $styles)
{
$this->conditionalStylesCollection[strtoupper($coordinate)] = $styles;
return $this;
}
/**
* Get style for cell by using numeric cell coordinates.
*
* @param int $columnIndex1 Numeric column coordinate of the cell
* @param int $row1 Numeric row coordinate of the cell
* @param null|int $columnIndex2 Numeric column coordinate of the range cell
* @param null|int $row2 Numeric row coordinate of the range cell
*
* @return Style
*/
public function getStyleByColumnAndRow($columnIndex1, $row1, $columnIndex2 = null, $row2 = null)
{
if ($columnIndex2 !== null && $row2 !== null) {
$cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
return $this->getStyle($cellRange);
}
return $this->getStyle(Coordinate::stringFromColumnIndex($columnIndex1) . $row1);
}
/**
* Duplicate cell style to a range of cells.
*
* Please note that this will overwrite existing cell styles for cells in range!
*
* @param Style $style Cell style to duplicate
* @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
*
* @return $this
*/
public function duplicateStyle(Style $style, $range)
{
// Add the style to the workbook if necessary
$workbook = $this->parent;
if ($existingStyle = $this->parent->getCellXfByHashCode($style->getHashCode())) {
// there is already such cell Xf in our collection
$xfIndex = $existingStyle->getIndex();
} else {
// we don't have such a cell Xf, need to add
$workbook->addCellXf($style);
$xfIndex = $style->getIndex();
}
// Calculate range outer borders
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range);
// Make sure we can loop upwards on rows and columns
if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
$tmp = $rangeStart;
$rangeStart = $rangeEnd;
$rangeEnd = $tmp;
}
// Loop through cells and apply styles
for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
$this->getCell(Coordinate::stringFromColumnIndex($col) . $row)->setXfIndex($xfIndex);
}
}
return $this;
}
/**
* Duplicate conditional style to a range of cells.
*
* Please note that this will overwrite existing cell styles for cells in range!
*
* @param Conditional[] $styles Cell style to duplicate
* @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
*
* @return $this
*/
public function duplicateConditionalStyle(array $styles, $range = '')
{
foreach ($styles as $cellStyle) {
if (!($cellStyle instanceof Conditional)) {
throw new Exception('Style is not a conditional style');
}
}
// Calculate range outer borders
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range);
// Make sure we can loop upwards on rows and columns
if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) {
$tmp = $rangeStart;
$rangeStart = $rangeEnd;
$rangeEnd = $tmp;
}
// Loop through cells and apply styles
for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
$this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $styles);
}
}
return $this;
}
/**
* Set break on a cell.
*
* @param string $coordinate Cell coordinate (e.g. A1)
* @param int $break Break type (type of Worksheet::BREAK_*)
*
* @return $this
*/
public function setBreak($coordinate, $break)
{
// Uppercase coordinate
$coordinate = strtoupper($coordinate);
if ($coordinate != '') {
if ($break == self::BREAK_NONE) {
if (isset($this->breaks[$coordinate])) {
unset($this->breaks[$coordinate]);
}
} else {
$this->breaks[$coordinate] = $break;
}
} else {
throw new Exception('No cell coordinate specified.');
}
return $this;
}
/**
* Set break on a cell by using numeric cell coordinates.
*
* @param int $columnIndex Numeric column coordinate of the cell
* @param int $row Numeric row coordinate of the cell
* @param int $break Break type (type of Worksheet::BREAK_*)
*
* @return $this
*/
public function setBreakByColumnAndRow($columnIndex, $row, $break)
{
return $this->setBreak(Coordinate::stringFromColumnIndex($columnIndex) . $row, $break);
}
/**
* Get breaks.
*
* @return int[]
*/
public function getBreaks()
{
return $this->breaks;
}
/**
* Set merge on a cell range.
*
* @param string $range Cell range (e.g. A1:E1)
*
* @return $this
*/
public function mergeCells($range)
{
// Uppercase coordinate
$range = strtoupper($range);
if (strpos($range, ':') !== false) {
$this->mergeCells[$range] = $range;
// make sure cells are created
// get the cells in the range
$aReferences = Coordinate::extractAllCellReferencesInRange($range);
// create upper left cell if it does not already exist
$upperLeft = $aReferences[0];
if (!$this->cellExists($upperLeft)) {
$this->getCell($upperLeft)->setValueExplicit(null, DataType::TYPE_NULL);
}
// Blank out the rest of the cells in the range (if they exist)
$count = count($aReferences);
for ($i = 1; $i < $count; ++$i) {
if ($this->cellExists($aReferences[$i])) {
$this->getCell($aReferences[$i])->setValueExplicit(null, DataType::TYPE_NULL);
}
}
} else {
throw new Exception('Merge must be set on a range of cells.');
}
return $this;
}
/**
* Set merge on a cell range by using numeric cell coordinates.
*
* @param int $columnIndex1 Numeric column coordinate of the first cell
* @param int $row1 Numeric row coordinate of the first cell
* @param int $columnIndex2 Numeric column coordinate of the last cell
* @param int $row2 Numeric row coordinate of the last cell
*
* @return $this
*/
public function mergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
{
$cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
return $this->mergeCells($cellRange);
}
/**
* Remove merge on a cell range.
*
* @param string $range Cell range (e.g. A1:E1)
*
* @return $this
*/
public function unmergeCells($range)
{
// Uppercase coordinate
$range = strtoupper($range);
if (strpos($range, ':') !== false) {
if (isset($this->mergeCells[$range])) {
unset($this->mergeCells[$range]);
} else {
throw new Exception('Cell range ' . $range . ' not known as merged.');
}
} else {
throw new Exception('Merge can only be removed from a range of cells.');
}
return $this;
}
/**
* Remove merge on a cell range by using numeric cell coordinates.
*
* @param int $columnIndex1 Numeric column coordinate of the first cell
* @param int $row1 Numeric row coordinate of the first cell
* @param int $columnIndex2 Numeric column coordinate of the last cell
* @param int $row2 Numeric row coordinate of the last cell
*
* @return $this
*/
public function unmergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
{
$cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
return $this->unmergeCells($cellRange);
}
/**
* Get merge cells array.
*
* @return string[]
*/
public function getMergeCells()
{
return $this->mergeCells;
}
/**
* Set merge cells array for the entire sheet. Use instead mergeCells() to merge
* a single cell range.
*
* @param string[] $mergeCells
*
* @return $this
*/
public function setMergeCells(array $mergeCells)
{
$this->mergeCells = $mergeCells;
return $this;
}
/**
* Set protection on a cell range.
*
* @param string $range Cell (e.g. A1) or cell range (e.g. A1:E1)
* @param string $password Password to unlock the protection
* @param bool $alreadyHashed If the password has already been hashed, set this to true
*
* @return $this
*/
public function protectCells($range, $password, $alreadyHashed = false)
{
// Uppercase coordinate
$range = strtoupper($range);
if (!$alreadyHashed) {
$password = Shared\PasswordHasher::hashPassword($password);
}
$this->protectedCells[$range] = $password;
return $this;
}
/**
* Set protection on a cell range by using numeric cell coordinates.
*
* @param int $columnIndex1 Numeric column coordinate of the first cell
* @param int $row1 Numeric row coordinate of the first cell
* @param int $columnIndex2 Numeric column coordinate of the last cell
* @param int $row2 Numeric row coordinate of the last cell
* @param string $password Password to unlock the protection
* @param bool $alreadyHashed If the password has already been hashed, set this to true
*
* @return $this
*/
public function protectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2, $password, $alreadyHashed = false)
{
$cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
return $this->protectCells($cellRange, $password, $alreadyHashed);
}
/**
* Remove protection on a cell range.
*
* @param string $range Cell (e.g. A1) or cell range (e.g. A1:E1)
*
* @return $this
*/
public function unprotectCells($range)
{
// Uppercase coordinate
$range = strtoupper($range);
if (isset($this->protectedCells[$range])) {
unset($this->protectedCells[$range]);
} else {
throw new Exception('Cell range ' . $range . ' not known as protected.');
}
return $this;
}
/**
* Remove protection on a cell range by using numeric cell coordinates.
*
* @param int $columnIndex1 Numeric column coordinate of the first cell
* @param int $row1 Numeric row coordinate of the first cell
* @param int $columnIndex2 Numeric column coordinate of the last cell
* @param int $row2 Numeric row coordinate of the last cell
*
* @return $this
*/
public function unprotectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
{
$cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2;
return $this->unprotectCells($cellRange);
}
/**
* Get protected cells.
*
* @return string[]
*/
public function getProtectedCells()
{
return $this->protectedCells;
}
/**
* Get Autofilter.
*
* @return AutoFilter
*/
public function getAutoFilter()
{
return $this->autoFilter;
}
/**
* Set AutoFilter.
*
* @param AutoFilter|string $autoFilterOrRange
* A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility
*
* @return $this
*/
public function setAutoFilter($autoFilterOrRange)
{
if (is_string($autoFilterOrRange)) {
$this->autoFilter->setRange($autoFilterOrRange);
} elseif (is_object($autoFilterOrRange) && ($autoFilterOrRange instanceof AutoFilter)) {
$this->autoFilter = $autoFilterOrRange;
}
return $this;
}
/**
* Set Autofilter Range by using numeric cell coordinates.
*
* @param int $columnIndex1 Numeric column coordinate of the first cell
* @param int $row1 Numeric row coordinate of the first cell
* @param int $columnIndex2 Numeric column coordinate of the second cell
* @param int $row2 Numeric row coordinate of the second cell
*
* @return $this
*/
public function setAutoFilterByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2)
{
return $this->setAutoFilter(
Coordinate::stringFromColumnIndex($columnIndex1) . $row1
. ':' .
Coordinate::stringFromColumnIndex($columnIndex2) . $row2
);
}
/**
* Remove autofilter.
*
* @return $this
*/
public function removeAutoFilter()
{
$this->autoFilter->setRange(null);
return $this;
}
/**
* Get Freeze Pane.
*
* @return null|string
*/
public function getFreezePane()
{
return $this->freezePane;
}
/**
* Freeze Pane.
*
* Examples:
*
* - A2 will freeze the rows above cell A2 (i.e row 1)
* - B1 will freeze the columns to the left of cell B1 (i.e column A)
* - B2 will freeze the rows above and to the left of cell B2 (i.e row 1 and column A)
*
* @param null|string $cell Position of the split
* @param null|string $topLeftCell default position of the right bottom pane
*
* @return $this
*/
public function freezePane($cell, $topLeftCell = null)
{
if (is_string($cell) && Coordinate::coordinateIsRange($cell)) {
throw new Exception('Freeze pane can not be set on a range of cells.');
}
if ($cell !== null && $topLeftCell === null) {
$coordinate = Coordinate::coordinateFromString($cell);
$topLeftCell = $coordinate[0] . $coordinate[1];
}
$this->freezePane = $cell;
$this->topLeftCell = $topLeftCell;
return $this;
}
public function setTopLeftCell(string $topLeftCell): self
{
$this->topLeftCell = $topLeftCell;
return $this;
}
/**
* Freeze Pane by using numeric cell coordinates.
*
* @param int $columnIndex Numeric column coordinate of the cell
* @param int $row Numeric row coordinate of the cell
*
* @return $this
*/
public function freezePaneByColumnAndRow($columnIndex, $row)
{
return $this->freezePane(Coordinate::stringFromColumnIndex($columnIndex) . $row);
}
/**
* Unfreeze Pane.
*
* @return $this
*/
public function unfreezePane()
{
return $this->freezePane(null);
}
/**
* Get the default position of the right bottom pane.
*
* @return null|string
*/
public function getTopLeftCell()
{
return $this->topLeftCell;
}
/**
* Insert a new row, updating all possible related data.
*
* @param int $before Insert before this one
* @param int $numberOfRows Number of rows to insert
*
* @return $this
*/
public function insertNewRowBefore($before, $numberOfRows = 1)
{
if ($before >= 1) {
$objReferenceHelper = ReferenceHelper::getInstance();
$objReferenceHelper->insertNewBefore('A' . $before, 0, $numberOfRows, $this);
} else {
throw new Exception('Rows can only be inserted before at least row 1.');
}
return $this;
}
/**
* Insert a new column, updating all possible related data.
*
* @param string $before Insert before this one, eg: 'A'
* @param int $numberOfColumns Number of columns to insert
*
* @return $this
*/
public function insertNewColumnBefore($before, $numberOfColumns = 1)
{
if (!is_numeric($before)) {
$objReferenceHelper = ReferenceHelper::getInstance();
$objReferenceHelper->insertNewBefore($before . '1', $numberOfColumns, 0, $this);
} else {
throw new Exception('Column references should not be numeric.');
}
return $this;
}
/**
* Insert a new column, updating all possible related data.
*
* @param int $beforeColumnIndex Insert before this one (numeric column coordinate of the cell)
* @param int $numberOfColumns Number of columns to insert
*
* @return $this
*/
public function insertNewColumnBeforeByIndex($beforeColumnIndex, $numberOfColumns = 1)
{
if ($beforeColumnIndex >= 1) {
return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $numberOfColumns);
}
throw new Exception('Columns can only be inserted before at least column A (1).');
}
/**
* Delete a row, updating all possible related data.
*
* @param int $row Remove starting with this one
* @param int $numberOfRows Number of rows to remove
*
* @return $this
*/
public function removeRow($row, $numberOfRows = 1)
{
if ($row < 1) {
throw new Exception('Rows to be deleted should at least start from row 1.');
}
$highestRow = $this->getHighestDataRow();
$removedRowsCounter = 0;
for ($r = 0; $r < $numberOfRows; ++$r) {
if ($row + $r <= $highestRow) {
$this->getCellCollection()->removeRow($row + $r);
++$removedRowsCounter;
}
}
$objReferenceHelper = ReferenceHelper::getInstance();
$objReferenceHelper->insertNewBefore('A' . ($row + $numberOfRows), 0, -$numberOfRows, $this);
for ($r = 0; $r < $removedRowsCounter; ++$r) {
$this->getCellCollection()->removeRow($highestRow);
--$highestRow;
}
return $this;
}
/**
* Remove a column, updating all possible related data.
*
* @param string $column Remove starting with this one, eg: 'A'
* @param int $numberOfColumns Number of columns to remove
*
* @return $this
*/
public function removeColumn($column, $numberOfColumns = 1)
{
if (is_numeric($column)) {
throw new Exception('Column references should not be numeric.');
}
$highestColumn = $this->getHighestDataColumn();
$highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
$pColumnIndex = Coordinate::columnIndexFromString($column);
if ($pColumnIndex > $highestColumnIndex) {
return $this;
}
$column = Coordinate::stringFromColumnIndex($pColumnIndex + $numberOfColumns);
$objReferenceHelper = ReferenceHelper::getInstance();
$objReferenceHelper->insertNewBefore($column . '1', -$numberOfColumns, 0, $this);
$maxPossibleColumnsToBeRemoved = $highestColumnIndex - $pColumnIndex + 1;
for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $numberOfColumns); $c < $n; ++$c) {
$this->getCellCollection()->removeColumn($highestColumn);
$highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1);
}
$this->garbageCollect();
return $this;
}
/**
* Remove a column, updating all possible related data.
*
* @param int $columnIndex Remove starting with this one (numeric column coordinate of the cell)
* @param int $numColumns Number of columns to remove
*
* @return $this
*/
public function removeColumnByIndex($columnIndex, $numColumns = 1)
{
if ($columnIndex >= 1) {
return $this->removeColumn(Coordinate::stringFromColumnIndex($columnIndex), $numColumns);
}
throw new Exception('Columns to be deleted should at least start from column A (1)');
}
/**
* Show gridlines?
*
* @return bool
*/
public function getShowGridlines()
{
return $this->showGridlines;
}
/**
* Set show gridlines.
*
* @param bool $showGridLines Show gridlines (true/false)
*
* @return $this
*/
public function setShowGridlines($showGridLines)
{
$this->showGridlines = $showGridLines;
return $this;
}
/**
* Print gridlines?
*
* @return bool
*/
public function getPrintGridlines()
{
return $this->printGridlines;
}
/**
* Set print gridlines.
*
* @param bool $printGridLines Print gridlines (true/false)
*
* @return $this
*/
public function setPrintGridlines($printGridLines)
{
$this->printGridlines = $printGridLines;
return $this;
}
/**
* Show row and column headers?
*
* @return bool
*/
public function getShowRowColHeaders()
{
return $this->showRowColHeaders;
}
/**
* Set show row and column headers.
*
* @param bool $showRowColHeaders Show row and column headers (true/false)
*
* @return $this
*/
public function setShowRowColHeaders($showRowColHeaders)
{
$this->showRowColHeaders = $showRowColHeaders;
return $this;
}
/**
* Show summary below? (Row/Column outlining).
*
* @return bool
*/
public function getShowSummaryBelow()
{
return $this->showSummaryBelow;
}
/**
* Set show summary below.
*
* @param bool $showSummaryBelow Show summary below (true/false)
*
* @return $this
*/
public function setShowSummaryBelow($showSummaryBelow)
{
$this->showSummaryBelow = $showSummaryBelow;
return $this;
}
/**
* Show summary right? (Row/Column outlining).
*
* @return bool
*/
public function getShowSummaryRight()
{
return $this->showSummaryRight;
}
/**
* Set show summary right.
*
* @param bool $showSummaryRight Show summary right (true/false)
*
* @return $this
*/
public function setShowSummaryRight($showSummaryRight)
{
$this->showSummaryRight = $showSummaryRight;
return $this;
}
/**
* Get comments.
*
* @return Comment[]
*/
public function getComments()
{
return $this->comments;
}
/**
* Set comments array for the entire sheet.
*
* @param Comment[] $comments
*
* @return $this
*/
public function setComments(array $comments)
{
$this->comments = $comments;
return $this;
}
/**
* Get comment for cell.
*
* @param string $cellCoordinate Cell coordinate to get comment for, eg: 'A1'
*
* @return Comment
*/
public function getComment($cellCoordinate)
{
// Uppercase coordinate
$cellCoordinate = strtoupper($cellCoordinate);
if (Coordinate::coordinateIsRange($cellCoordinate)) {
throw new Exception('Cell coordinate string can not be a range of cells.');
} elseif (strpos($cellCoordinate, '$') !== false) {
throw new Exception('Cell coordinate string must not be absolute.');
} elseif ($cellCoordinate == '') {
throw new Exception('Cell coordinate can not be zero-length string.');
}
// Check if we already have a comment for this cell.
if (isset($this->comments[$cellCoordinate])) {
return $this->comments[$cellCoordinate];
}
// If not, create a new comment.
$newComment = new Comment();
$this->comments[$cellCoordinate] = $newComment;
return $newComment;
}
/**
* Get comment for cell by using numeric cell coordinates.
*
* @param int $columnIndex Numeric column coordinate of the cell
* @param int $row Numeric row coordinate of the cell
*
* @return Comment
*/
public function getCommentByColumnAndRow($columnIndex, $row)
{
return $this->getComment(Coordinate::stringFromColumnIndex($columnIndex) . $row);
}
/**
* Get active cell.
*
* @return string Example: 'A1'
*/
public function getActiveCell()
{
return $this->activeCell;
}
/**
* Get selected cells.
*
* @return string
*/
public function getSelectedCells()
{
return $this->selectedCells;
}
/**
* Selected cell.
*
* @param string $coordinate Cell (i.e. A1)
*
* @return $this
*/
public function setSelectedCell($coordinate)
{
return $this->setSelectedCells($coordinate);
}
/**
* Sigh - Phpstan thinks, correctly, that preg_replace can return null.
* But Scrutinizer doesn't. Try to satisfy both.
*
* @param mixed $str
*/
private static function ensureString($str): string
{
return is_string($str) ? $str : '';
}
public static function pregReplace(string $pattern, string $replacement, string $subject): string
{
return self::ensureString(preg_replace($pattern, $replacement, $subject));
}
private function tryDefinedName(string $coordinate): string
{
// Uppercase coordinate
$coordinate = strtoupper($coordinate);
// Eliminate leading equal sign
$coordinate = self::pregReplace('/^=/', '', $coordinate);
$defined = $this->parent->getDefinedName($coordinate, $this);
if ($defined !== null) {
if ($defined->getWorksheet() === $this && !$defined->isFormula()) {
$coordinate = self::pregReplace('/^=/', '', $defined->getValue());
}
}
return $coordinate;
}
/**
* Select a range of cells.
*
* @param string $coordinate Cell range, examples: 'A1', 'B2:G5', 'A:C', '3:6'
*
* @return $this
*/
public function setSelectedCells($coordinate)
{
$originalCoordinate = $coordinate;
$coordinate = $this->tryDefinedName($coordinate);
// Convert 'A' to 'A:A'
$coordinate = self::pregReplace('/^([A-Z]+)$/', '${1}:${1}', $coordinate);
// Convert '1' to '1:1'
$coordinate = self::pregReplace('/^(\d+)$/', '${1}:${1}', $coordinate);
// Convert 'A:C' to 'A1:C1048576'
$coordinate = self::pregReplace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $coordinate);
// Convert '1:3' to 'A1:XFD3'
$coordinate = self::pregReplace('/^(\d+):(\d+)$/', 'A${1}:XFD${2}', $coordinate);
if (preg_match('/^\\$?[A-Z]{1,3}\\$?\d{1,7}(:\\$?[A-Z]{1,3}\\$?\d{1,7})?$/', $coordinate) !== 1) {
throw new Exception("Invalid setSelectedCells $originalCoordinate $coordinate");
}
if (Coordinate::coordinateIsRange($coordinate)) {
[$first] = Coordinate::splitRange($coordinate);
$this->activeCell = $first[0];
} else {
$this->activeCell = $coordinate;
}
$this->selectedCells = $coordinate;
return $this;
}
/**
* Selected cell by using numeric cell coordinates.
*
* @param int $columnIndex Numeric column coordinate of the cell
* @param int $row Numeric row coordinate of the cell
*
* @return $this
*/
public function setSelectedCellByColumnAndRow($columnIndex, $row)
{
return $this->setSelectedCells(Coordinate::stringFromColumnIndex($columnIndex) . $row);
}
/**
* Get right-to-left.
*
* @return bool
*/
public function getRightToLeft()
{
return $this->rightToLeft;
}
/**
* Set right-to-left.
*
* @param bool $value Right-to-left true/false
*
* @return $this
*/
public function setRightToLeft($value)
{
$this->rightToLeft = $value;
return $this;
}
/**
* Fill worksheet from values in array.
*
* @param array $source Source array
* @param mixed $nullValue Value in source array that stands for blank cell
* @param string $startCell Insert array starting from this cell address as the top left coordinate
* @param bool $strictNullComparison Apply strict comparison when testing for null values in the array
*
* @return $this
*/
public function fromArray(array $source, $nullValue = null, $startCell = 'A1', $strictNullComparison = false)
{
// Convert a 1-D array to 2-D (for ease of looping)
if (!is_array(end($source))) {
$source = [$source];
}
// start coordinate
[$startColumn, $startRow] = Coordinate::coordinateFromString($startCell);
// Loop through $source
foreach ($source as $rowData) {
$currentColumn = $startColumn;
foreach ($rowData as $cellValue) {
if ($strictNullComparison) {
if ($cellValue !== $nullValue) {
// Set cell value
$this->getCell($currentColumn . $startRow)->setValue($cellValue);
}
} else {
if ($cellValue != $nullValue) {
// Set cell value
$this->getCell($currentColumn . $startRow)->setValue($cellValue);
}
}
++$currentColumn;
}
++$startRow;
}
return $this;
}
/**
* Create array from a range of cells.
*
* @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
* @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
* @param bool $calculateFormulas Should formulas be calculated?
* @param bool $formatData Should formatting be applied to cell values?
* @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
* True - Return rows and columns indexed by their actual row and column IDs
*
* @return array
*/
public function rangeToArray($range, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
{
// Returnvalue
$returnValue = [];
// Identify the range that we need to extract from the worksheet
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
$minCol = Coordinate::stringFromColumnIndex($rangeStart[0]);
$minRow = $rangeStart[1];
$maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]);
$maxRow = $rangeEnd[1];
++$maxCol;
// Loop through rows
$r = -1;
for ($row = $minRow; $row <= $maxRow; ++$row) {
$rRef = $returnCellRef ? $row : ++$r;
$c = -1;
// Loop through columns in the current row
for ($col = $minCol; $col != $maxCol; ++$col) {
$cRef = $returnCellRef ? $col : ++$c;
// Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen
// so we test and retrieve directly against cellCollection
if ($this->cellCollection->has($col . $row)) {
// Cell exists
$cell = $this->cellCollection->get($col . $row);
if ($cell->getValue() !== null) {
if ($cell->getValue() instanceof RichText) {
$returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText();
} else {
if ($calculateFormulas) {
$returnValue[$rRef][$cRef] = $cell->getCalculatedValue();
} else {
$returnValue[$rRef][$cRef] = $cell->getValue();
}
}
if ($formatData) {
$style = $this->parent->getCellXfByIndex($cell->getXfIndex());
$returnValue[$rRef][$cRef] = NumberFormat::toFormattedString(
$returnValue[$rRef][$cRef],
($style && $style->getNumberFormat()) ? $style->getNumberFormat()->getFormatCode() : NumberFormat::FORMAT_GENERAL
);
}
} else {
// Cell holds a NULL
$returnValue[$rRef][$cRef] = $nullValue;
}
} else {
// Cell doesn't exist
$returnValue[$rRef][$cRef] = $nullValue;
}
}
}
// Return
return $returnValue;
}
private function validateNamedRange(string $definedName, bool $returnNullIfInvalid = false): ?DefinedName
{
$namedRange = DefinedName::resolveName($definedName, $this);
if ($namedRange === null) {
if ($returnNullIfInvalid) {
return null;
}
throw new Exception('Named Range ' . $definedName . ' does not exist.');
}
if ($namedRange->isFormula()) {
if ($returnNullIfInvalid) {
return null;
}
throw new Exception('Defined Named ' . $definedName . ' is a formula, not a range or cell.');
}
if ($namedRange->getLocalOnly() && $this->getHashCode() !== $namedRange->getWorksheet()->getHashCode()) {
if ($returnNullIfInvalid) {
return null;
}
throw new Exception(
'Named range ' . $definedName . ' is not accessible from within sheet ' . $this->getTitle()
);
}
return $namedRange;
}
/**
* Create array from a range of cells.
*
* @param string $definedName The Named Range that should be returned
* @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
* @param bool $calculateFormulas Should formulas be calculated?
* @param bool $formatData Should formatting be applied to cell values?
* @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
* True - Return rows and columns indexed by their actual row and column IDs
*
* @return array
*/
public function namedRangeToArray(string $definedName, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
{
$namedRange = $this->validateNamedRange($definedName);
$workSheet = $namedRange->getWorksheet();
$cellRange = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!');
$cellRange = str_replace('$', '', $cellRange);
return $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef);
}
/**
* Create array from worksheet.
*
* @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
* @param bool $calculateFormulas Should formulas be calculated?
* @param bool $formatData Should formatting be applied to cell values?
* @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
* True - Return rows and columns indexed by their actual row and column IDs
*
* @return array
*/
public function toArray($nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
{
// Garbage collect...
$this->garbageCollect();
// Identify the range that we need to extract from the worksheet
$maxCol = $this->getHighestColumn();
$maxRow = $this->getHighestRow();
// Return
return $this->rangeToArray('A1:' . $maxCol . $maxRow, $nullValue, $calculateFormulas, $formatData, $returnCellRef);
}
/**
* Get row iterator.
*
* @param int $startRow The row number at which to start iterating
* @param int $endRow The row number at which to stop iterating
*
* @return RowIterator
*/
public function getRowIterator($startRow = 1, $endRow = null)
{
return new RowIterator($this, $startRow, $endRow);
}
/**
* Get column iterator.
*
* @param string $startColumn The column address at which to start iterating
* @param string $endColumn The column address at which to stop iterating
*
* @return ColumnIterator
*/
public function getColumnIterator($startColumn = 'A', $endColumn = null)
{
return new ColumnIterator($this, $startColumn, $endColumn);
}
/**
* Run PhpSpreadsheet garbage collector.
*
* @return $this
*/
public function garbageCollect()
{
// Flush cache
$this->cellCollection->get('A1');
// Lookup highest column and highest row if cells are cleaned
$colRow = $this->cellCollection->getHighestRowAndColumn();
$highestRow = $colRow['row'];
$highestColumn = Coordinate::columnIndexFromString($colRow['column']);
// Loop through column dimensions
foreach ($this->columnDimensions as $dimension) {
$highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex()));
}
// Loop through row dimensions
foreach ($this->rowDimensions as $dimension) {
$highestRow = max($highestRow, $dimension->getRowIndex());
}
// Cache values
if ($highestColumn < 1) {
$this->cachedHighestColumn = 1;
} else {
$this->cachedHighestColumn = $highestColumn;
}
$this->cachedHighestRow = $highestRow;
// Return
return $this;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode()
{
if ($this->dirty) {
$this->hash = md5($this->title . $this->autoFilter . ($this->protection->isProtectionEnabled() ? 't' : 'f') . __CLASS__);
$this->dirty = false;
}
return $this->hash;
}
/**
* Extract worksheet title from range.
*
* Example: extractSheetTitle("testSheet!A1") ==> 'A1'
* Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1'];
*
* @param string $range Range to extract title from
* @param bool $returnRange Return range? (see example)
*
* @return mixed
*/
public static function extractSheetTitle($range, $returnRange = false)
{
// Sheet title included?
if (($sep = strrpos($range, '!')) === false) {
return $returnRange ? ['', $range] : '';
}
if ($returnRange) {
return [substr($range, 0, $sep), substr($range, $sep + 1)];
}
return substr($range, $sep + 1);
}
/**
* Get hyperlink.
*
* @param string $cellCoordinate Cell coordinate to get hyperlink for, eg: 'A1'
*
* @return Hyperlink
*/
public function getHyperlink($cellCoordinate)
{
// return hyperlink if we already have one
if (isset($this->hyperlinkCollection[$cellCoordinate])) {
return $this->hyperlinkCollection[$cellCoordinate];
}
// else create hyperlink
$this->hyperlinkCollection[$cellCoordinate] = new Hyperlink();
return $this->hyperlinkCollection[$cellCoordinate];
}
/**
* Set hyperlink.
*
* @param string $cellCoordinate Cell coordinate to insert hyperlink, eg: 'A1'
*
* @return $this
*/
public function setHyperlink($cellCoordinate, ?Hyperlink $hyperlink = null)
{
if ($hyperlink === null) {
unset($this->hyperlinkCollection[$cellCoordinate]);
} else {
$this->hyperlinkCollection[$cellCoordinate] = $hyperlink;
}
return $this;
}
/**
* Hyperlink at a specific coordinate exists?
*
* @param string $coordinate eg: 'A1'
*
* @return bool
*/
public function hyperlinkExists($coordinate)
{
return isset($this->hyperlinkCollection[$coordinate]);
}
/**
* Get collection of hyperlinks.
*
* @return Hyperlink[]
*/
public function getHyperlinkCollection()
{
return $this->hyperlinkCollection;
}
/**
* Get data validation.
*
* @param string $cellCoordinate Cell coordinate to get data validation for, eg: 'A1'
*
* @return DataValidation
*/
public function getDataValidation($cellCoordinate)
{
// return data validation if we already have one
if (isset($this->dataValidationCollection[$cellCoordinate])) {
return $this->dataValidationCollection[$cellCoordinate];
}
// else create data validation
$this->dataValidationCollection[$cellCoordinate] = new DataValidation();
return $this->dataValidationCollection[$cellCoordinate];
}
/**
* Set data validation.
*
* @param string $cellCoordinate Cell coordinate to insert data validation, eg: 'A1'
*
* @return $this
*/
public function setDataValidation($cellCoordinate, ?DataValidation $dataValidation = null)
{
if ($dataValidation === null) {
unset($this->dataValidationCollection[$cellCoordinate]);
} else {
$this->dataValidationCollection[$cellCoordinate] = $dataValidation;
}
return $this;
}
/**
* Data validation at a specific coordinate exists?
*
* @param string $coordinate eg: 'A1'
*
* @return bool
*/
public function dataValidationExists($coordinate)
{
return isset($this->dataValidationCollection[$coordinate]);
}
/**
* Get collection of data validations.
*
* @return DataValidation[]
*/
public function getDataValidationCollection()
{
return $this->dataValidationCollection;
}
/**
* Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet.
*
* @param string $range
*
* @return string Adjusted range value
*/
public function shrinkRangeToFit($range)
{
$maxCol = $this->getHighestColumn();
$maxRow = $this->getHighestRow();
$maxCol = Coordinate::columnIndexFromString($maxCol);
$rangeBlocks = explode(' ', $range);
foreach ($rangeBlocks as &$rangeSet) {
$rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet);
if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) {
$rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol);
}
if ($rangeBoundaries[0][1] > $maxRow) {
$rangeBoundaries[0][1] = $maxRow;
}
if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) {
$rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol);
}
if ($rangeBoundaries[1][1] > $maxRow) {
$rangeBoundaries[1][1] = $maxRow;
}
$rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1];
}
unset($rangeSet);
return implode(' ', $rangeBlocks);
}
/**
* Get tab color.
*
* @return Color
*/
public function getTabColor()
{
if ($this->tabColor === null) {
$this->tabColor = new Color();
}
return $this->tabColor;
}
/**
* Reset tab color.
*
* @return $this
*/
public function resetTabColor()
{
$this->tabColor = null;
return $this;
}
/**
* Tab color set?
*
* @return bool
*/
public function isTabColorSet()
{
return $this->tabColor !== null;
}
/**
* Copy worksheet (!= clone!).
*
* @return static
*/
public function copy()
{
return clone $this;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
// @phpstan-ignore-next-line
foreach ($this as $key => $val) {
if ($key == 'parent') {
continue;
}
if (is_object($val) || (is_array($val))) {
if ($key == 'cellCollection') {
$newCollection = $this->cellCollection->cloneCellCollection($this);
$this->cellCollection = $newCollection;
} elseif ($key == 'drawingCollection') {
$currentCollection = $this->drawingCollection;
$this->drawingCollection = new ArrayObject();
foreach ($currentCollection as $item) {
if (is_object($item)) {
$newDrawing = clone $item;
$newDrawing->setWorksheet($this);
}
}
} elseif (($key == 'autoFilter') && ($this->autoFilter instanceof AutoFilter)) {
$newAutoFilter = clone $this->autoFilter;
$this->autoFilter = $newAutoFilter;
$this->autoFilter->setParent($this);
} else {
$this->{$key} = unserialize(serialize($val));
}
}
}
}
/**
* Define the code name of the sheet.
*
* @param string $codeName Same rule as Title minus space not allowed (but, like Excel, change
* silently space to underscore)
* @param bool $validate False to skip validation of new title. WARNING: This should only be set
* at parse time (by Readers), where titles can be assumed to be valid.
*
* @return $this
*/
public function setCodeName($codeName, $validate = true)
{
// Is this a 'rename' or not?
if ($this->getCodeName() == $codeName) {
return $this;
}
if ($validate) {
$codeName = str_replace(' ', '_', $codeName); //Excel does this automatically without flinching, we are doing the same
// Syntax check
// throw an exception if not valid
self::checkSheetCodeName($codeName);
// We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_'
if ($this->getParent()) {
// Is there already such sheet name?
if ($this->getParent()->sheetCodeNameExists($codeName)) {
// Use name, but append with lowest possible integer
if (Shared\StringHelper::countCharacters($codeName) > 29) {
$codeName = Shared\StringHelper::substring($codeName, 0, 29);
}
$i = 1;
while ($this->getParent()->sheetCodeNameExists($codeName . '_' . $i)) {
++$i;
if ($i == 10) {
if (Shared\StringHelper::countCharacters($codeName) > 28) {
$codeName = Shared\StringHelper::substring($codeName, 0, 28);
}
} elseif ($i == 100) {
if (Shared\StringHelper::countCharacters($codeName) > 27) {
$codeName = Shared\StringHelper::substring($codeName, 0, 27);
}
}
}
$codeName .= '_' . $i; // ok, we have a valid name
}
}
}
$this->codeName = $codeName;
return $this;
}
/**
* Return the code name of the sheet.
*
* @return null|string
*/
public function getCodeName()
{
return $this->codeName;
}
/**
* Sheet has a code name ?
*
* @return bool
*/
public function hasCodeName()
{
return $this->codeName !== null;
}
}
| collectiveaccess/pawtucket2 | vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php | PHP | gpl-3.0 | 89,151 |
function InstrumentSelector(list) {
this.instruments = list;
this.currentInstrument;
this.updateInstrumentView();
}
InstrumentSelector.prototype.addInstrument = function (type, url, colorCode) {
var l = this.instruments.push(new Instrument(type, url, colorCode));
this.createInstrumentView(l-1);
}
InstrumentSelector.prototype.removeInstrument = function (type, url, colorCode) {
this.instruments.push(new Instrument(type, url, colorCode));
this.updateInstrumentView();
}
InstrumentSelector.prototype.createInstrumentView = function (index) {
var bar = document.getElementById("instrumentBar");
var img = document.createElement("span");
img.className = "instrumentContainer";
img.id = this.instruments[index].instrumentName;
img.style.backgroundImage = "url(" + this.instruments[index].imgURL + ")";
img.style.backgroundColor = this.instruments[index].color;
// img.style.backgroundImage = "url(images/"+this.instruments[index]+".png)";
bar.appendChild(img);
}
InstrumentSelector.prototype.updateInstrumentView = function () {
var bar = document.getElementById("instrumentBar");
// first clear all the children.
var len = bar.children.length;
for (var a=0; a<len; a++) {
bar.removeChild(bar.children[a]);
}
// then add all
for (var i=0; i < this.instruments.length; i++) {
this.createInstrumentView(i);
}
}
InstrumentSelector.prototype.setActiveInstrument = function (instrumentName) {
this.currentInstrument = this.getInstrument(instrumentName);
this.updateSelected();
}
InstrumentSelector.prototype.getInstrument = function (instrumentName) {
for (var i=0; i<this.instruments.length; i++) {
// alert(this.instruments[i].instrumentName + " " + instrumentName);
if (this.instruments[i].instrumentName == instrumentName) {
return this.instruments[i];
}
}
return null;
}
InstrumentSelector.prototype.updateSelected = function () {
for (var i=0; i<this.instruments.length; i++) {
var sel = document.getElementById(this.instruments[i].instrumentName);
sel.className = sel.className.replace(" instrumentSelected","");
}
var sel = document.getElementById(this.currentInstrument.instrumentName);
sel.className = sel.className + " instrumentSelected";
}
| mqtlam/cloud-composer | release/beta_0.3/include/InstrumentSelector.js | JavaScript | gpl-3.0 | 2,208 |
<?php
/**
* OpenCart 1.5.2.1 Polskie Tłumaczenie
*
* This script is protected by copyright. It's use, copying, modification
* and distribution without written consent of the author is prohibited.
*
* @category OpenCart
* @package OpenCart
* @author Andrzej Kłopotowski <aklopot@gmail.com>
* @author Krzysztof Kardasz <krzysztof.kardasz@gmail.com>
* @copyright Copyright (c) 2012 Andrzej Kłopotowski
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU Lesser General Public
* @version 1.5.2.1 $Id: forgotten.php 88 2012-04-23 14:42:06Z krzysztof.kardasz $
* @link http://opencart-polish.googlecode.com
* @link http://opencart-polish.googlecode.com/svn/branches/1.5.2.1/
*/
// Heading
$_['heading_title'] = 'Zapomniałeś hasła?';
// Text
$_['text_account'] = 'Konto';
$_['text_forgotten'] = 'Zapomniane hasło';
$_['text_your_email'] = 'Adres E-Mail';
$_['text_email'] = 'Podaj adres E-Mail, który użyłeś podczas rejestracji.';
$_['text_success'] = 'Sukces: Nowe hasło zostało wysłane na podany adres E-Mail.';
// Entry
$_['entry_email'] = 'Adres E-Mail:';
// Error
$_['error_email'] = 'Uwaga: Podany adres E-Mail nie istnieje, prosimy spróbować ponownie!';
| kzawner/andreaherbaty.pl | upload/catalog/language/polski/account/forgotten.php | PHP | gpl-3.0 | 1,273 |
from __future__ import unicode_literals
from __future__ import absolute_import
from django.views.generic.base import TemplateResponseMixin
from wiki.core.plugins import registry
from wiki.conf import settings
class ArticleMixin(TemplateResponseMixin):
"""A mixin that receives an article object as a parameter (usually from a wiki
decorator) and puts this information as an instance attribute and in the
template context."""
def dispatch(self, request, article, *args, **kwargs):
self.urlpath = kwargs.pop('urlpath', None)
self.article = article
self.children_slice = []
if settings.SHOW_MAX_CHILDREN > 0:
try:
for child in self.article.get_children(
max_num=settings.SHOW_MAX_CHILDREN +
1,
articles__article__current_revision__deleted=False,
user_can_read=request.user):
self.children_slice.append(child)
except AttributeError as e:
raise Exception(
"Attribute error most likely caused by wrong MPTT version. Use 0.5.3+.\n\n" +
str(e))
return super(ArticleMixin, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
kwargs['urlpath'] = self.urlpath
kwargs['article'] = self.article
kwargs['article_tabs'] = registry.get_article_tabs()
kwargs['children_slice'] = self.children_slice[:20]
kwargs['children_slice_more'] = len(self.children_slice) > 20
kwargs['plugins'] = registry.get_plugins()
return kwargs
| Infernion/django-wiki | wiki/views/mixins.py | Python | gpl-3.0 | 1,668 |
import game as game
import pytest
import sys
sys.path.insert(0, '..')
def trim_board(ascii_board):
return '\n'.join([i.strip() for i in ascii_board.splitlines()])
t = trim_board
def test_new_board():
game.Board(3,3).ascii() == t("""
...
...
...
""")
game.Board(4,3).ascii() == t("""
....
....
....
""")
game.Board(3,4).ascii() == t("""
...
...
...
...
""")
def test_game():
board = game.Board(3,3,win=3)
assert board.count_tokens == 0
assert board.game_status == 'active'
assert board.turn_color == None
# drop first token
token = board.drop('x',0)
assert board.game_status == 'active'
assert token.position == (0,0)
assert token.color == 'x'
assert board.ascii() == t("""
...
...
x..
""")
assert board.count_tokens == 1
assert board.turn_color == 'o'
# drop second token
token = board.drop('o',0)
assert board.game_status == 'active'
assert token.position == (0,1)
assert token.color == 'o'
assert board.ascii() == t("""
...
o..
x..
""")
assert board.count_tokens == 2
assert board.turn_color == 'x'
# dropping the wrong color should raise an error
with pytest.raises(Exception):
token = board.drop('o',1)
# drop third token
token = board.drop('x',1)
assert board.game_status == 'active'
assert token.position == (1,0)
assert token.color == 'x'
board.ascii() == t("""
...
o..
xx.
""")
assert board.count_tokens == 3
assert board.turn_color == 'o'
# drop fourth token
token = board.drop('o',0)
assert board.game_status == 'active'
assert token.position == (0,2)
assert token.color == 'o'
board.ascii() == t("""
o..
o..
xx.
""")
assert board.count_tokens == 4
# drop fifth token
token = board.drop('x',2)
assert board.game_status == 'over'
assert board.won_by == 'x'
assert token.position == (2,0)
assert token.color == 'x'
board.ascii() == t("""
o..
o..
xxx
""")
assert board.count_tokens == 5
def test_load_board():
"""
The Board class should provide a load method to load a predefined board.
the load method should be implemented as a static method like this:
>>> class Test:
>>> @staticmethod
>>> def a_static_factory():
>>> t = Test()
>>> # do something with t and return it
>>> return t
the load function accepts a board layout. It retrieves the dimensions of the board
and loads the provided data into the board.
"""
board = game.Board.load(t("""
o..
o..
xxx
"""))
def test_axis_strings():
board = game.Board.load(t("""
o..
o..
xxx
"""))
# get the axis strings in this order: | \ / -
axis_strings = board.axis_strings(0,0)
assert axis_strings[0] == 'xoo'
assert axis_strings[1] == 'x'
assert axis_strings[2] == 'x..'
assert axis_strings[3] == 'xxx' # the winner :-)
assert board.won_by == 'x'
| fweidemann14/x-gewinnt | game/test_game.py | Python | gpl-3.0 | 3,095 |
#!/usr/bin/env ruby
#
# Usage: ruby load_data.rb *txt
#
require File.dirname(__FILE__) + '/../../../config/environment'
require File.dirname(__FILE__) + '/../../load_utils'
# First get hold of the region
region = Region.find_or_initialize_by_region("Denmark")
region.lat = 56.2639
region.lng = 9.5018
region.country = "Denmark"
region.country_code = 'DK'
region.current_year = 2006
region.stats_name = "Danmarks Statstik"
region.stats_url = "http://www.dst.dk/"
region.stats_desc = "Top 50 baby names given by gender."
region.save
# ************* JUST TO FIX MY FSCKED INITIAL LOAD **************
Stat.delete_all(["region_id = ?", region.id])
CurrentStat.delete_all(["region_id = ?", region.id])
# Now parse every text file that was provided.
for filename in ARGV
filename =~ /^[0-9]{4}/
year = Integer($&) # Get year from previous regexp on filename
if filename =~ /boy/i
gender = "MALE"
else
gender = "FEMALE"
end
File.open(filename) do | file |
while line = file.gets
for pair in line.scan(/([^\d]+)(\d+)/)
#puts pair[0].strip + " (" + pair[1] + ")"
load_stat(pair[0].strip, Integer(pair[1]), year, gender, region)
end
end
end
if (year == region.current_year)
calc_popularity(gender, region)
end
puts "Finished " + filename
end
| guydavis/babynamemap | stats/europe/denmark/load_stats.rb | Ruby | gpl-3.0 | 1,307 |
/*************************************************************************
*
* The Contents of this file are made available subject to the terms of
* the BSD license.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Sun Microsystems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*************************************************************************/
import java.awt.Component;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
public class UnoTreeRenderer extends DefaultTreeCellRenderer{
private Icon m_oMethodIcon;
private Icon m_oPropertyIcon;
private Icon m_oContainerIcon;
private Icon m_oContentIcon;
private Icon m_oServiceIcon;
private Icon m_oInterfaceIcon;
private Icon m_oPropertyValueIcon;
private boolean bSelected;
private int nWidth = 0;
/** Creates a new instance of UnoTreeRenderer */
public UnoTreeRenderer(){
super();
try {
final ClassLoader loader = ClassLoader.getSystemClassLoader();
m_oMethodIcon = new ImageIcon(loader.getResource("images/methods_16.png"));
m_oPropertyIcon = new ImageIcon("images/properties_16.png");
m_oPropertyValueIcon = new ImageIcon("images/properties_16.png");
m_oContainerIcon = new ImageIcon("images/containers_16.png");
m_oServiceIcon = new ImageIcon("images/services_16.png");
m_oInterfaceIcon = new ImageIcon("images/interfaces_16.png");
m_oContentIcon = new ImageIcon("images/content_16.png");
} catch (RuntimeException e) {
System.out.println("Sorry, could not locate resourecs, treecell icons will not be displayed.");
}
}
public synchronized Component getTreeCellRendererComponent(JTree tree,Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus){
try{
bSelected = sel;
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
Component rc = super.getTreeCellRendererComponent( tree, value, sel,expanded, leaf, row,hasFocus);
String sLabelText = (String)node.getUserObject();
if (sLabelText != null){
if (sLabelText.equals(XUnoFacetteNode.SCONTAINERDESCRIPTION)){
// setIcon(m_oContainerIcon);
} else if (sLabelText.equals(XUnoFacetteNode.SCONTENTDESCRIPTION)){
// setIcon(m_oContentIcon);
} else if (sLabelText.equals(XUnoFacetteNode.SINTERFACEDESCRIPTION)){
// setIcon(m_oInterfaceIcon);
} else if (sLabelText.equals(XUnoFacetteNode.SMETHODDESCRIPTION)){
// setIcon(m_oMethodIcon);
} else if (sLabelText.equals(XUnoFacetteNode.SPROPERTYDESCRIPTION)){
// setIcon(m_oPropertyIcon);
} else if (sLabelText.startsWith(XUnoFacetteNode.SPROPERTYINFODESCRIPTION)){
// setIcon(m_oPropertyIcon);
} else if (sLabelText.equals(XUnoFacetteNode.SPROPERTYVALUEDESCRIPTION)){
// setIcon(m_oPropertyValueIcon);
} else if (sLabelText.equals(XUnoFacetteNode.SSERVICEDESCRIPTION)){
// setIcon(m_oServiceIcon);
} else{
setText(sLabelText);
rc.validate();
}
setSize(getPreferredSize()); //fm.stringWidth(sLabelText), (int) getSize().getHeight());
rc.validate();
// nWidth = (int) rc.getPreferredSize().getWidth();
doLayout();
}
} catch (RuntimeException e) {
System.out.println("Sorry, icon for treecell could not be displayed.");
}
return this;
}
public void paintComponent(Graphics g) {
FontMetrics fm = getFontMetrics(getFont());
int x, y;
y = fm.getAscent() + 2;
if(getIcon() == null) {
x = 0;
} else {
x = getIcon().getIconWidth() + getIconTextGap();
}
g.setColor(getForeground());
// g.fillRect(x,y,x + fm.stringWidth(getText()),y);
// System.out.println("Text: " + getText());
super.paintComponent(g);
}
}
| qt-haiku/LibreOffice | odk/examples/java/Inspector/UnoTreeRenderer.java | Java | gpl-3.0 | 5,903 |
package antlr;
/* ANTLR Translator Generator
* Project led by Terence Parr at http://www.cs.usfca.edu
* Software rights: http://www.antlr.org/license.html
*
* $Id: //depot/code/org.antlr/release/antlr-2.7.7/antlr/TreeBlockContext.java#2 $
*/
/**The context needed to add root,child elements to a Tree. There
* is only one alternative (i.e., a list of children). We subclass to
* specialize. MakeGrammar.addElementToCurrentAlt will work correctly
* now for either a block of alts or a Tree child list.
*
* The first time addAlternativeElement is called, it sets the root element
* rather than adding it to one of the alternative lists. Rather than have
* the grammar duplicate the rules for grammar atoms etc... we use the same
* grammar and same refToken behavior etc... We have to special case somewhere
* and here is where we do it.
*/
class TreeBlockContext extends BlockContext {
protected boolean nextElementIsRoot = true;
public void addAlternativeElement(AlternativeElement e) {
TreeElement tree = (TreeElement)block;
if (nextElementIsRoot) {
tree.root = (GrammarAtom)e;
nextElementIsRoot = false;
}
else {
super.addAlternativeElement(e);
}
}
}
| salcedonia/acide-0-8-release-2010-2011 | acide/antlr/TreeBlockContext.java | Java | gpl-3.0 | 1,263 |
"""
A mode for working with Circuit Python boards.
Copyright (c) 2015-2017 Nicholas H.Tollervey and others (see the AUTHORS file).
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import ctypes
import logging
from subprocess import check_output
from mu.modes.base import MicroPythonMode
from mu.modes.api import ADAFRUIT_APIS, SHARED_APIS
from mu.interface.panes import CHARTS
from mu.logic import Device
from adafruit_board_toolkit import circuitpython_serial
logger = logging.getLogger(__name__)
class CircuitPythonMode(MicroPythonMode):
"""
Represents the functionality required by the CircuitPython mode.
"""
name = _("CircuitPython")
short_name = "circuitpython"
description = _("Write code for boards running CircuitPython.")
icon = "circuitpython"
save_timeout = 0 #: No auto-save on CP boards. Will restart.
connected = True #: is the board connected.
force_interrupt = False #: NO keyboard interrupt on serial connection.
# Modules built into CircuitPython which mustn't be used as file names
# for source code.
module_names = {
"_bleio",
"_eve",
"_pew",
"_pixelbuf",
"_stage",
"_typing",
"adafruit_bus_device",
"aesio",
"alarm",
"array",
"analogio",
"audiobusio",
"audiocore",
"audioio",
"audiomixer",
"audiomp3",
"audiopwmio",
"binascii",
"bitbangio",
"bitmaptools",
"bitops",
"board",
"builtins",
"busio",
"camera",
"canio",
"collections",
"countio",
"digitalio",
"displayio",
"dualbank",
"errno",
"fontio",
"framebufferio",
"frequencyio",
"gamepad",
"gamepadshift",
"gc",
"gnss",
"hashlib",
"i2cperipheral",
"io",
"ipaddress",
"json",
"math",
"memorymonitor",
"microcontroller",
"msgpack",
"multiterminal",
"neopixel_write",
"network",
"nvm",
"os",
"ps2io",
"pulseio",
"pwmio",
"random",
"re",
"rgbmatrix",
"rotaryio",
"rtc",
"sdcardio",
"sdioio",
"sharpdisplay",
"socket",
"socketpool",
"ssl",
"storage",
"struct",
"supervisor",
"sys",
"terminalio",
"time",
"touchio",
"uheap",
"usb_cdc",
"usb_hid",
"usb_midi",
"ustack",
"vectorio",
"watchdog",
"wifi",
"wiznet",
"zlib",
}
def actions(self):
"""
Return an ordered list of actions provided by this module. An action
is a name (also used to identify the icon) , description, and handler.
"""
buttons = [
{
"name": "serial",
"display_name": _("Serial"),
"description": _("Open a serial connection to your device."),
"handler": self.toggle_repl,
"shortcut": "CTRL+Shift+U",
}
]
if CHARTS:
buttons.append(
{
"name": "plotter",
"display_name": _("Plotter"),
"description": _("Plot incoming REPL data."),
"handler": self.toggle_plotter,
"shortcut": "CTRL+Shift+P",
}
)
return buttons
def workspace_dir(self):
"""
Return the default location on the filesystem for opening and closing
files.
"""
device_dir = None
# Attempts to find the path on the filesystem that represents the
# plugged in CIRCUITPY board.
if os.name == "posix":
# We're on Linux or OSX
for mount_command in ["mount", "/sbin/mount"]:
try:
mount_output = check_output(mount_command).splitlines()
mounted_volumes = [x.split()[2] for x in mount_output]
for volume in mounted_volumes:
tail = os.path.split(volume)[-1]
if tail.startswith(b"CIRCUITPY") or tail.startswith(
b"PYBFLASH"
):
device_dir = volume.decode("utf-8")
break
except FileNotFoundError:
pass
except PermissionError as e:
logger.error(
"Received '{}' running command: {}".format(
repr(e), mount_command
)
)
m = _("Permission error running mount command")
info = _(
'The mount command ("{}") returned an error: '
"{}. Mu will continue as if a device isn't "
"plugged in."
).format(mount_command, repr(e))
self.view.show_message(m, info)
# Avoid crashing Mu, the workspace dir will be set to default
except Exception as e:
logger.error(
"Received '{}' running command: {}".format(
repr(e), mount_command
)
)
elif os.name == "nt":
# We're on Windows.
def get_volume_name(disk_name):
"""
Each disk or external device connected to windows has an
attribute called "volume name". This function returns the
volume name for the given disk/device.
Code from http://stackoverflow.com/a/12056414
"""
vol_name_buf = ctypes.create_unicode_buffer(1024)
ctypes.windll.kernel32.GetVolumeInformationW(
ctypes.c_wchar_p(disk_name),
vol_name_buf,
ctypes.sizeof(vol_name_buf),
None,
None,
None,
None,
0,
)
return vol_name_buf.value
#
# In certain circumstances, volumes are allocated to USB
# storage devices which cause a Windows popup to raise if their
# volume contains no media. Wrapping the check in SetErrorMode
# with SEM_FAILCRITICALERRORS (1) prevents this popup.
#
old_mode = ctypes.windll.kernel32.SetErrorMode(1)
try:
for disk in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
path = "{}:\\".format(disk)
if (
os.path.exists(path)
and get_volume_name(path) == "CIRCUITPY"
):
return path
finally:
ctypes.windll.kernel32.SetErrorMode(old_mode)
else:
# No support for unknown operating systems.
raise NotImplementedError('OS "{}" not supported.'.format(os.name))
if device_dir:
# Found it!
self.connected = True
return device_dir
else:
# Not plugged in? Just return Mu's regular workspace directory
# after warning the user.
wd = super().workspace_dir()
if self.connected:
m = _("Could not find an attached CircuitPython device.")
info = _(
"Python files for CircuitPython devices"
" are stored on the device. Therefore, to edit"
" these files you need to have the device plugged in."
" Until you plug in a device, Mu will use the"
" directory found here:\n\n"
" {}\n\n...to store your code."
)
self.view.show_message(m, info.format(wd))
self.connected = False
return wd
def compatible_board(self, port):
"""Use adafruit_board_toolkit to find out whether a board is running
CircuitPython. The toolkit sees if the CDC Interface name is appropriate.
"""
pid = port.productIdentifier()
vid = port.vendorIdentifier()
manufacturer = port.manufacturer()
serial_number = port.serialNumber()
port_name = self.port_path(port.portName())
# Find all the CircuitPython REPL comports,
# and see if any of their device names match the one passed in.
for comport in circuitpython_serial.repl_comports():
if comport.device == port_name:
return Device(
vid,
pid,
port_name,
serial_number,
manufacturer,
self.name,
self.short_name,
"CircuitPython board",
)
# No match.
return None
def api(self):
"""
Return a list of API specifications to be used by auto-suggest and call
tips.
"""
return SHARED_APIS + ADAFRUIT_APIS
| carlosperate/mu | mu/modes/circuitpython.py | Python | gpl-3.0 | 10,028 |
import os
from collections import defaultdict
from django.conf import settings
from django.contrib import messages
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.db.models import Count, Q
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.shortcuts import render, get_object_or_404
from django.utils.translation import ugettext_lazy as _
from haystack.query import SearchQuerySet
from orb.forms import (ResourceStep1Form, ResourceStep2Form, SearchForm,
ResourceRejectForm, AdvancedSearchForm)
from orb.models import Collection
from orb.models import home_resources
from orb.models import ResourceFile, ResourceTag, ResourceCriteria, ResourceRating
from orb.models import ReviewerRole
from orb.models import Tag, Resource, ResourceURL, Category, TagOwner, SearchTracker
from orb.signals import (resource_viewed, resource_url_viewed, resource_file_viewed,
search, resource_workflow, resource_submitted, tag_viewed)
from orb.tags.forms import TagPageForm
def home_view(request):
topics = []
organized_topics = defaultdict(list)
for tag in Tag.tags.public().top_level():
child_tags = tag.children.values_list('id')
resource_count = Resource.objects.filter(status=Resource.APPROVED).filter(
Q(resourcetag__tag__pk__in=child_tags) | Q(resourcetag__tag=tag)).distinct().count()
for category_slug in ["health-domain"]:
if tag.category.slug == category_slug:
organized_topics[category_slug.replace("-", "_")].append({
'resource_count': resource_count,
'tag': tag,
})
topics.append({
'resource_count': resource_count,
'tag': tag,
})
return render(request, 'orb/home.html', {
'topics': topics,
'organized_topics': home_resources(),
'page_title': _(u'ORB by mPowering'),
})
def partner_view(request):
PARTNERS = ['jhu-ccp', 'digital-campus', 'digital-green',
'global-health-media-project', 'medical-aid-films', 'zinc-ors']
partners = Tag.objects.filter(
category__slug='organisation', slug__in=PARTNERS).order_by('name')
return render(request, 'orb/partners.html', {'partners': partners})
def tag_view(request, tag_slug):
"""
Renders a tag detail page.
Allows the user to paginate resultes and sort by preselected options.
Args:
request: HttpRequest
tag_slug: the identifier for the tag
Returns:
Rendered response with a tag's resource list
"""
tag = get_object_or_404(Tag, slug=tag_slug)
filter_params = {
'page': 1,
'order': TagPageForm.CREATED,
}
params_form = TagPageForm(data=request.GET)
if params_form.is_valid():
filter_params.update(params_form.cleaned_data)
order_by = filter_params['order']
if order_by == TagPageForm.RATING:
data = Resource.resources.approved().with_ratings(tag).order_by(order_by)
else:
data = Resource.resources.approved().for_tag(tag).order_by(order_by)
paginator = Paginator(data, settings.ORB_PAGINATOR_DEFAULT)
try:
resources = paginator.page(filter_params['page'])
except (EmptyPage, InvalidPage):
resources = paginator.page(paginator.num_pages)
show_filter_link = tag.category.slug in [slug for name, slug in settings.ADVANCED_SEARCH_CATEGORIES]
tag_viewed.send(sender=tag, tag=tag, request=request)
is_geo_tag = tag.category.name == "Geography"
return render(request, 'orb/tag.html', {
'tag': tag,
'page': resources,
'params_form': params_form,
'show_filter_link': show_filter_link,
'is_geo_tag': is_geo_tag,
})
def taxonomy_view(request):
return render(request, 'orb/taxonomy.html')
def resource_permalink_view(request, id):
resource = get_object_or_404(Resource, pk=id)
return resource_view(request, resource.slug)
def resource_view(request, resource_slug):
resource = get_object_or_404(
Resource.objects.approved(user=request.user), slug=resource_slug)
if resource.status == Resource.ARCHIVED:
messages.error(request, _(
u"This resource has been archived by the ORB Content"
u" Review Team, so is not available for users to view"))
elif resource.status != Resource.APPROVED:
messages.error(request, _(
u"This resource is not yet approved by the ORB Content"
u" Review Team, so is not yet available for all users to view"))
options_menu = []
if resource_can_edit(resource, request.user):
om = {}
om['title'] = _(u'Edit')
om['url'] = reverse('orb_resource_edit', args=[resource.id])
options_menu.append(om)
if request.user.is_staff and resource.status == Resource.PENDING:
om = {}
om['title'] = _(u'Reject')
om['url'] = reverse('orb_resource_reject', args=[resource.id])
options_menu.append(om)
om = {}
om['title'] = _(u'Approve')
om['url'] = reverse('orb_resource_approve', args=[resource.id])
options_menu.append(om)
resource_viewed.send(sender=resource, resource=resource, request=request)
user_rating = 0
if request.user.is_authenticated():
try:
user_rating = ResourceRating.objects.get(
resource=resource, user=request.user).rating
except ResourceRating.DoesNotExist:
pass
# get the collections for this resource
collections = Collection.objects.filter(
collectionresource__resource=resource, visibility=Collection.PUBLIC)
# See if bookmarked
bookmarks = Collection.objects.filter(collectionresource__resource=resource,
visibility=Collection.PRIVATE, collectionuser__user__id=request.user.id).count()
if bookmarks > 0:
bookmarked = True
else:
bookmarked = False
return render(request, 'orb/resource/view.html', {
'resource': resource,
'options_menu': options_menu,
'user_rating': user_rating,
'collections': collections,
'bookmarked': bookmarked,
})
def resource_create_step1_view(request):
if request.user.is_anonymous():
return render(request, 'orb/login_required.html', {
'message': _(u'You need to be logged in to add a resource.'),
})
if request.method == 'POST':
form = ResourceStep1Form(request.POST, request.FILES, request=request)
resource_form_set_choices(form)
if form.is_valid():
# save resource
resource = Resource(status=Resource.PENDING,
create_user=request.user, update_user=request.user)
resource.title = form.cleaned_data.get("title")
resource.description = form.cleaned_data.get("description")
if form.cleaned_data.get("study_time_number") and form.cleaned_data.get("study_time_unit"):
resource.study_time_number = form.cleaned_data.get(
"study_time_number")
resource.study_time_unit = form.cleaned_data.get(
"study_time_unit")
if request.FILES.has_key('image'):
resource.image = request.FILES["image"]
resource.attribution = form.cleaned_data.get("attribution")
resource.save()
# add organisation(s)/geography and other tags
resource_add_free_text_tags(
resource, form.cleaned_data.get('organisations'), request.user, 'organisation')
resource_add_free_text_tags(
resource, form.cleaned_data.get('geography'), request.user, 'geography')
resource_add_free_text_tags(
resource, form.cleaned_data.get('languages'), request.user, 'language')
resource_add_free_text_tags(
resource, form.cleaned_data.get('other_tags'), request.user, 'other')
# add tags
resource_add_tags(request, form, resource)
# see if email needs to be sent
resource_workflow.send(sender=resource, resource=resource, request=request,
status=Resource.PENDING, notes="")
resource_submitted.send(sender=resource, resource=resource, request=request)
# redirect to step 2
# Redirect after POST
return HttpResponseRedirect(reverse('orb_resource_create2', args=[resource.id]))
else:
if request.user.userprofile.organisation:
user_org = request.user.userprofile.organisation.name
initial = {'organisations': user_org, }
else:
initial = {}
form = ResourceStep1Form(initial=initial, request=request)
resource_form_set_choices(form)
return render(request, 'orb/resource/create_step1.html', {'form': form})
def resource_create_step2_view(request, id):
if request.user.is_anonymous():
# TODO use contrib.messages
return render(request, 'orb/login_required.html', {
'message': _(u'You need to be logged in to add a resource.'),
})
resource = get_object_or_404(Resource, pk=id)
# check if owner of this resource
if not resource_can_edit(resource, request.user):
raise Http404()
if request.method == 'POST':
form = ResourceStep2Form(request.POST, request.FILES, request=request)
if form.is_valid():
title = form.cleaned_data.get("title")
# add file and url
if request.FILES.has_key('file'):
rf = ResourceFile(
resource=resource, create_user=request.user, update_user=request.user)
rf.file = request.FILES["file"]
if title:
rf.title = title
rf.save()
url = form.cleaned_data.get("url")
if url:
ru = ResourceURL(
resource=resource, create_user=request.user, update_user=request.user)
ru.url = url
if title:
ru.title = title
ru.save()
initial = {}
form = ResourceStep2Form(initial=initial, request=request)
resource_files = ResourceFile.objects.filter(resource=resource)
resource_urls = ResourceURL.objects.filter(resource=resource)
return render(request, 'orb/resource/create_step2.html', {
'form': form,
'resource': resource,
'resource_files': resource_files,
'resource_urls': resource_urls,
})
def resource_create_file_delete_view(request, id, file_id):
# check ownership
resource = get_object_or_404(Resource, pk=id)
if not resource_can_edit(resource, request.user):
raise Http404()
try:
ResourceFile.objects.get(resource=resource, pk=file_id).delete()
except ResourceFile.DoesNotExist:
pass
return HttpResponseRedirect(reverse('orb_resource_create2', args=[id]))
def resource_create_url_delete_view(request, id, url_id):
# check ownership
resource = get_object_or_404(Resource, pk=id)
if not resource_can_edit(resource, request.user):
raise Http404()
try:
ResourceURL.objects.get(resource=resource, pk=url_id).delete()
except ResourceURL.DoesNotExist:
pass
return HttpResponseRedirect(reverse('orb_resource_create2', args=[id]))
def resource_edit_file_delete_view(request, id, file_id):
# check ownership
resource = get_object_or_404(Resource, pk=id)
if not resource_can_edit(resource, request.user):
raise Http404()
try:
ResourceFile.objects.get(resource=resource, pk=file_id).delete()
except ResourceFile.DoesNotExist:
pass
return HttpResponseRedirect(reverse('orb_resource_edit2', args=[id]))
def resource_edit_url_delete_view(request, id, url_id):
# check ownership
resource = get_object_or_404(Resource, pk=id)
if not resource_can_edit(resource, request.user):
raise Http404()
try:
ResourceURL.objects.get(resource=resource, pk=url_id).delete()
except ResourceURL.DoesNotExist:
pass
return HttpResponseRedirect(reverse('orb_resource_edit2', args=[id]))
def resource_create_thanks_view(request, id):
resource = get_object_or_404(Resource, pk=id)
if not resource_can_edit(resource, request.user):
raise Http404()
return render(request, 'orb/resource/create_thanks.html', {'resource': resource})
def resource_guidelines_view(request):
criteria = []
# get the general criteria
criteria_general = ResourceCriteria.objects.filter(role=None).order_by('order_by')
obj = {}
obj['category'] = _("General")
obj['criteria'] = criteria_general
criteria.append(obj)
for k in ReviewerRole.objects.all():
obj = {}
cat = ResourceCriteria.objects.filter(role=k).order_by('order_by')
obj['category'] = k
obj['criteria'] = cat
criteria.append(obj)
return render(request, 'orb/resource/guidelines.html', {'criteria_categories': criteria})
def resource_approve_view(request, id):
if not request.user.is_staff:
return HttpResponse(status=401, content="Not Authorized")
resource = Resource.objects.get(pk=id)
resource.status = Resource.APPROVED
resource.save()
resource_workflow.send(sender=resource, resource=resource,
request=request, status=Resource.APPROVED, notes="")
return render(request, 'orb/resource/status_updated.html', {'resource': resource})
def resource_reject_view(request, id):
if not request.user.is_staff:
return HttpResponse(status=401, content="Not Authorized")
resource = Resource.objects.get(pk=id)
if request.method == 'POST':
form = ResourceRejectForm(data=request.POST)
form.fields['criteria'].choices = [(t.id, t.description) for t in ResourceCriteria.objects.all(
).order_by('category_order_by', 'order_by')]
if form.is_valid():
resource.status = Resource.REJECTED
resource.save()
notes = form.cleaned_data.get("notes")
criteria = form.cleaned_data.get("criteria")
resource_workflow.send(sender=resource, resource=resource, request=request,
status=Resource.REJECTED, notes=notes, criteria=criteria)
return HttpResponseRedirect(reverse('orb_resource_reject_sent', args=[resource.id]))
else:
form = ResourceRejectForm()
form.fields['criteria'].choices = [(t.id, t.description) for t in ResourceCriteria.objects.all(
).order_by('category_order_by', 'order_by')]
return render(request, 'orb/resource/reject_form.html', {
'resource': resource,
'form': form,
})
def resource_reject_sent_view(request, id):
if not request.user.is_staff:
return HttpResponse(status=401, content="Not Authorized")
resource = Resource.objects.get(pk=id)
return render(request, 'orb/resource/status_updated.html', {'resource': resource, })
def resource_pending_mep_view(request, id):
if not request.user.is_staff:
return HttpResponse(status=401, content="Not Authorized")
resource = Resource.objects.get(pk=id)
resource.status = Resource.PENDING
resource.save()
resource_workflow.send(sender=resource, resource=resource, request=request,
status=Resource.PENDING, notes="")
return render(request, 'orb/resource/status_updated.html', {'resource': resource})
def resource_edit_view(request, resource_id):
resource = get_object_or_404(Resource, pk=resource_id)
if not resource_can_edit(resource, request.user):
raise Http404()
if request.method == 'POST':
form = ResourceStep1Form(data=request.POST, files=request.FILES)
resource_form_set_choices(form)
if form.is_valid():
resource.update_user = request.user
resource.title = form.cleaned_data.get("title")
resource.description = form.cleaned_data.get("description")
if form.cleaned_data.get("study_time_number") and form.cleaned_data.get("study_time_unit"):
resource.study_time_number = form.cleaned_data.get(
"study_time_number")
resource.study_time_unit = form.cleaned_data.get(
"study_time_unit")
resource.attribution = form.cleaned_data.get("attribution")
resource.save()
# update image
image = form.cleaned_data.get("image")
if image == False:
resource.image = None
resource.save()
if request.FILES.has_key('image'):
resource.image = request.FILES["image"]
resource.save()
# update tags - remove all current tags first
ResourceTag.objects.filter(resource=resource).delete()
resource_add_tags(request, form, resource)
resource_add_free_text_tags(
resource, form.cleaned_data.get('organisations'), request.user, 'organisation')
resource_add_free_text_tags(
resource, form.cleaned_data.get('geography'), request.user, 'geography')
resource_add_free_text_tags(
resource, form.cleaned_data.get('languages'), request.user, 'language')
resource_add_free_text_tags(
resource, form.cleaned_data.get('other_tags'), request.user, 'other')
# All successful - now redirect
# Redirect after POST
return HttpResponseRedirect(reverse('orb_resource_edit2', args=[resource.id]))
else:
initial = request.POST.copy()
initial['image'] = resource.image
files = ResourceFile.objects.filter(resource=resource)[:1]
if files:
initial['file'] = files[0].file
form = ResourceStep1Form(
initial=initial, data=request.POST, files=request.FILES)
resource_form_set_choices(form)
else:
data = {}
data['title'] = resource.title
organisations = Tag.objects.filter(
category__slug='organisation', resourcetag__resource=resource).values_list('name', flat=True)
data['organisations'] = ', '.join(organisations)
data['description'] = resource.description
data['image'] = resource.image
data['study_time_number'] = resource.study_time_number
data['study_time_unit'] = resource.study_time_unit
data['attribution'] = resource.attribution
files = ResourceFile.objects.filter(resource=resource)[:1]
if files:
data['file'] = files[0].file
urls = ResourceURL.objects.filter(resource=resource)[:1]
if urls:
data['url'] = urls[0].url
health_topic = Tag.objects.filter(
category__top_level=True, resourcetag__resource=resource).values_list('id', flat=True)
data['health_topic'] = health_topic
resource_type = Tag.objects.filter(
category__slug='type', resourcetag__resource=resource).values_list('id', flat=True)
data['resource_type'] = resource_type
audience = Tag.objects.filter(
category__slug='audience', resourcetag__resource=resource).values_list('id', flat=True)
data['audience'] = audience
geography = Tag.objects.filter(
category__slug='geography', resourcetag__resource=resource).values_list('name', flat=True)
data['geography'] = ', '.join(geography)
languages = Tag.objects.filter(
category__slug='language', resourcetag__resource=resource).values_list('name', flat=True)
data['languages'] = ', '.join(languages)
device = Tag.objects.filter(
category__slug='device', resourcetag__resource=resource).values_list('id', flat=True)
data['device'] = device
license = Tag.objects.filter(
category__slug='license', resourcetag__resource=resource).values_list('id', flat=True)
if license:
data['license'] = license[0]
other_tags = Tag.objects.filter(
resourcetag__resource=resource, category__slug='other').values_list('name', flat=True)
data['other_tags'] = ', '.join(other_tags)
form = ResourceStep1Form(initial=data)
resource_form_set_choices(form)
return render(request, 'orb/resource/edit.html', {'form': form})
def resource_edit_step2_view(request, resource_id):
if request.user.is_anonymous():
# TODO use contrib.messages
return render(request, 'orb/login_required.html', {
'message': _(u'You need to be logged in to add a resource.'),
})
resource = get_object_or_404(Resource, pk=resource_id)
# check if owner of this resource
if not resource_can_edit(resource, request.user):
raise Http404()
if request.method == 'POST':
form = ResourceStep2Form(request.POST, request.FILES, request=request)
if form.is_valid():
title = form.cleaned_data.get("title")
# add file and url
if request.FILES.has_key('file'):
rf = ResourceFile(
resource=resource, create_user=request.user, update_user=request.user)
rf.file = request.FILES["file"]
if title:
rf.title = title
rf.save()
url = form.cleaned_data.get("url")
if url:
ru = ResourceURL(
resource=resource, create_user=request.user, update_user=request.user)
ru.url = url
if title:
ru.title = title
ru.save()
initial = {}
form = ResourceStep2Form(initial=initial, request=request)
resource_files = ResourceFile.objects.filter(resource=resource)
resource_urls = ResourceURL.objects.filter(resource=resource)
return render(request, 'orb/resource/edit_step2.html', {
'form': form,
'resource': resource,
'resource_files': resource_files,
'resource_urls': resource_urls,
})
def resource_edit_thanks_view(request, id):
resource = get_object_or_404(Resource, pk=id)
if not resource_can_edit(resource, request.user):
raise Http404()
return render(request, 'orb/resource/edit_thanks.html', {'resource': resource})
def search_view(request):
search_query = request.GET.get('q', '')
if search_query:
search_results = SearchQuerySet().filter(content=search_query)
else:
search_results = []
data = {}
data['q'] = search_query
form = SearchForm(initial=data)
paginator = Paginator(search_results, settings.ORB_PAGINATOR_DEFAULT)
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
results = paginator.page(page)
except (EmptyPage, InvalidPage):
results = paginator.page(paginator.num_pages)
if search_query:
search.send(sender=search_results, query=search_query,
no_results=search_results.count(), request=request, page=page)
return render(request, 'orb/search.html', {
'form': form,
'query': search_query,
'page': results,
'total_results': paginator.count,
})
def search_advanced_view(request, tag_id=None):
if request.method == 'POST':
form = AdvancedSearchForm(request.POST)
if form.is_valid():
urlparams = request.POST.copy()
# delete these from params as not required
del urlparams['csrfmiddlewaretoken']
del urlparams['submit']
return HttpResponseRedirect(reverse('orb_search_advanced_results') + "?" + urlparams.urlencode())
else:
form = AdvancedSearchForm()
return render(request, 'orb/search_advanced.html', {'form': form})
def search_advanced_results_view(request):
form = AdvancedSearchForm(request.GET)
if form.is_valid():
q = form.cleaned_data.get('q')
results, filter_tags = form.search()
if q:
search_results = SearchQuerySet().filter(content=q).models(Resource).values_list('pk', flat=True)
results = results.filter(pk__in=search_results)
paginator = Paginator(results, settings.ORB_PAGINATOR_DEFAULT)
try:
page = int(request.GET.get('page', 1))
except ValueError:
page = 1
try:
resources = paginator.page(page)
except (EmptyPage, InvalidPage):
resources = paginator.page(paginator.num_pages)
search.send(sender=results, query=q, no_results=results.count(),
request=request, type=SearchTracker.SEARCH_ADV, page=page)
license_tags = form.cleaned_data['license']
else:
filter_tags = Tag.objects.filter(pk=None)
license_tags = []
resources = Resource.objects.filter(pk=None)
paginator = Paginator(resources, settings.ORB_PAGINATOR_DEFAULT)
return render(request, 'orb/search_advanced_results.html', {
'filter_tags': filter_tags,
'license_tags': license_tags,
'q': form.cleaned_data.get('q'),
'page': resources,
'total_results': paginator.count,
})
def collection_view(request, collection_slug):
collection = get_object_or_404(Collection,
slug=collection_slug, visibility=Collection.PUBLIC)
data = Resource.objects.filter(collectionresource__collection=collection,
status=Resource.APPROVED).order_by('collectionresource__order_by')
paginator = Paginator(data, settings.ORB_PAGINATOR_DEFAULT)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
resources = paginator.page(page)
except (EmptyPage, InvalidPage):
resources = paginator.page(paginator.num_pages)
return render(request, 'orb/collection/view.html', {
'collection': collection,
'page': resources,
'total_results': paginator.count,
})
# Helper functions
def resource_form_set_choices(form):
form.fields['health_topic'].choices = [(t.id, t.name) for t in Tag.objects.filter(
category__top_level=True).order_by('order_by', 'name')]
form.fields['resource_type'].choices = [(t.id, t.name) for t in Tag.objects.filter(
category__slug='type').order_by('order_by', 'name')]
form.fields['audience'].choices = [(t.id, t.name) for t in Tag.objects.filter(
category__slug='audience').order_by('order_by', 'name')]
form.fields['device'].choices = [(t.id, t.name) for t in Tag.objects.filter(
category__slug='device').order_by('order_by', 'name')]
form.fields['license'].choices = [(t.id, t.name) for t in Tag.objects.filter(
category__slug='license').order_by('order_by', 'name')]
return form
def advanced_search_form_set_choices(form):
for name, slug in settings.ADVANCED_SEARCH_CATEGORIES:
form.fields[name].choices = [(t.id, t.name) for t in Tag.objects.filter(
category__slug=slug, resourcetag__resource__status=Resource.APPROVED).distinct().order_by('order_by', 'name')]
form.fields['license'].choices = [
('ND', _(u'Derivatives allowed')), ('NC', _(u'Commercial use allowed'))]
return form
def resource_can_edit(resource, user):
if user.is_staff or user == resource.create_user or user == resource.update_user:
return True
else:
return TagOwner.objects.filter(user__pk=user.id, tag__resourcetag__resource=resource).exists()
def resource_add_free_text_tags(resource, tag_text, user, category_slug):
"""
Adds tags to a resource based on free text and category slugs
Args:
resource: a Resource object
tag_text: string of text including multiple comma separated tags
user: the User object to use for the tags
category_slug: the slug of the related Category
Returns:
None
"""
free_text_tags = [x.strip() for x in tag_text.split(',') if x.strip()]
category = Category.objects.get(slug=category_slug)
for tag_name in free_text_tags:
try:
tag = Tag.tags.rewrite(False).get(name=tag_name)
except Tag.DoesNotExist:
try:
tag = Tag.tags.get(name=tag_name)
except Tag.DoesNotExist:
tag = Tag.tags.create(
name=tag_name,
category=category,
create_user=user,
update_user=user,
)
ResourceTag.objects.get_or_create(
tag=tag, resource=resource, defaults={'create_user': user})
def resource_add_tags(request, form, resource):
"""
Adds structured tags to the resource
Args:
request: the HttpRequest
form: Resource add/edit form that has the tag data
resource: the resource to add the tags
Returns:
None
"""
tag_categories = ["health_topic", "resource_type", "audience", "device"]
for tc in tag_categories:
tag_category = form.cleaned_data.get(tc)
for ht in tag_category:
tag = Tag.objects.get(pk=ht)
ResourceTag.objects.get_or_create(
tag=tag, resource=resource, defaults={'create_user': request.user})
# add license
license = form.cleaned_data.get("license")
tag = Tag.objects.get(pk=license)
ResourceTag(tag=tag, resource=resource, create_user=request.user).save()
| mPowering/django-orb | orb/views.py | Python | gpl-3.0 | 30,008 |
<?php
/*
* Starting player: Take the Starting player token and all the Food that has
* accumulated on this Action space. Additionally, take 2 Ore (in games with 1
* to 3 players) or 1 Ruby (in games with 4 to 7 players) from the general
* supply. (1 Food is added to this Action space every round.) */
namespace Caverna\CoreBundle\Entity\ActionSpace;
use Doctrine\ORM\Mapping as ORM;
use Caverna\CoreBundle\Entity\ActionSpace\ActionSpace;
use Caverna\CoreBundle\Entity\Player;
/**
* @ORM\Entity;
*/
class StartingPlayerActionSpace extends ActionSpace {
const KEY = 'StartingPlayer';
const INITIAL_FOOD = 1;
const REPLENISH_FOOD = 1;
const ORE = 2;
const RUBY = 1;
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="integer")
*/
private $food;
public function isImitableForPlayer(Player $player) {
return false;
}
public function getOre() {
if ($this->getGame()->getNumPlayers() < 4) {
return self::ORE;
}
return 0;
}
public function getRuby() {
if ($this->getGame()->getNumPlayers() >= 4) {
return self::RUBY;
}
return 0;
}
public function getKey() {
return self::KEY;
}
public function getDescription() {
$description = "Jugador Inicial\nComida: 1(1)\n";
if ($this->getGame()->getNumPlayers() < 4) {
$description .= "Mineral: +2\n";
}
if ($this->getGame()->getNumPlayers() >= 4) {
$description .= "Ruby: +1\n";
}
return $description;
}
public function getState() {
return $this->getDescription();
}
public function __toString() {
return parent::__toString() . ' (' . $this->getFood() . 'F)';
}
public function __construct() {
parent::__construct();
$this->setName('Jugador Inicial');
$this->food = 0;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set food
*
* @param integer $food
*
* @return StartingPlayerActionSpace
*/
public function setFood($food)
{
$this->food = $food;
return $this;
}
/**
* Get food
*
* @return integer
*/
public function getFood()
{
return $this->food;
}
}
| nanomuelle/caverna | src/Caverna/CoreBundle/Entity/ActionSpace/StartingPlayerActionSpace.php | PHP | gpl-3.0 | 2,605 |
package get_cocoa
import (
"log"
"github.com/gonum/plot"
"github.com/gonum/plot/plotter"
"github.com/gonum/plot/plotutil"
"github.com/gonum/plot/vg"
)
type PlotStruct struct {
X float64
Y float64
}
func Plot(series plotter.XYs) {
p, err := plot.New()
if err != nil {
log.Fatal(err)
}
p.Title.Text = "Time Series"
p.X.Label.Text = "Day #"
p.Y.Label.Text = "Price"
err = plotutil.AddLinePoints(p,
"Close", series,
)
if err != nil {
log.Fatal(err)
}
if err := p.Save(12*vg.Inch, 6*vg.Inch, "price.png"); err != nil {
log.Fatal(err)
}
}
| tchitchikov/instant_cocoa | src/get_cocoa/plotting.go | GO | gpl-3.0 | 566 |
require "rails_helper"
RSpec.describe User::TeamsController, type: :controller do
describe "GET #index" do
context "when user is logged in" do
login_user
before(:each) do
FactoryBot.create_list(:team_basis, 3, owner: @user)
end
it "returns http success" do
get :index
expect(assigns(:teams)).to eq Team::Base.where(owner: @user)
expect(response).to have_http_status(:success)
end
end
context "when user is not logged in" do
it "redirects to login screen" do
get :index
expect(assigns(:teams)).to eq nil
expect(response).to redirect_to(new_user_session_path)
end
end
end
end
| tsolar/bp-tourneys | spec/controllers/user/teams_controller_spec.rb | Ruby | gpl-3.0 | 697 |
/*
* Copyright (c) 2017 SamuelGjk <samuel.alva@outlook.com>
*
* This file is part of DiyCode
*
* DiyCode is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DiyCode is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with DiyCode. If not, see <http://www.gnu.org/licenses/>.
*/
package moe.yukinoneko.diycode.module.about;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.webkit.WebView;
import java.util.Locale;
import butterknife.BindView;
import butterknife.OnClick;
import moe.yukinoneko.diycode.R;
import moe.yukinoneko.diycode.base.BaseActivity;
import moe.yukinoneko.diycode.tool.Tools;
/**
* MVPPlugin
* 邮箱 784787081@qq.com
*/
public class AboutActivity extends BaseActivity {
@BindView(R.id.text_app_version) AppCompatTextView textAppVersion;
@Override
protected int provideContentViewId() {
return R.layout.activity_about;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
textAppVersion.setText(String.format(Locale.getDefault(), "Version %s", Tools.getVersionName(this)));
}
@OnClick(R.id.card_open_source_licenses)
public void onViewClicked() {
WebView v = new WebView(this);
v.loadUrl("file:///android_asset/licenses.html");
new AlertDialog.Builder(this)
.setView(v)
.setNegativeButton(R.string.close, null)
.show();
}
}
| SamuelGjk/DiyCode | app/src/main/java/moe/yukinoneko/diycode/module/about/AboutActivity.java | Java | gpl-3.0 | 1,987 |
/**
* \file IMP/atom/Selection.cpp
* \brief Select a subset of a hierarchy.
*
* Copyright 2007-2017 IMP Inventors. All rights reserved.
*
*/
#include "IMP/atom/hierarchy_tools.h"
#include <IMP/SingletonContainer.h>
#include <IMP/algebra/vector_generators.h>
#include <IMP/atom/Atom.h>
#include <IMP/atom/Chain.h>
#include <IMP/atom/Copy.h>
#include <IMP/atom/Domain.h>
#include <IMP/atom/Fragment.h>
#include <IMP/atom/Mass.h>
#include <IMP/atom/Molecule.h>
#include <IMP/atom/Residue.h>
#include <IMP/atom/Representation.h>
#include <IMP/atom/State.h>
#include <IMP/atom/bond_decorators.h>
#include <IMP/atom/distance.h>
#include <IMP/atom/estimates.h>
#include <IMP/constants.h>
#include <IMP/container/AllBipartitePairContainer.h>
#include <IMP/container/ConnectingPairContainer.h>
#include <IMP/container/ListSingletonContainer.h>
#include <IMP/container/generic.h>
#include <IMP/core/ClosePairsPairScore.h>
#include <IMP/core/ConnectivityRestraint.h>
#include <IMP/core/CoverRefined.h>
#include <IMP/core/DistancePairScore.h>
#include <IMP/core/ExcludedVolumeRestraint.h>
#include <IMP/core/Harmonic.h>
#include <IMP/core/PairRestraint.h>
#include <IMP/core/SphereDistancePairScore.h>
#include <IMP/core/TableRefiner.h>
#include <IMP/generic.h>
#include <algorithm>
#include <boost/unordered_set.hpp>
IMPATOM_BEGIN_NAMESPACE
namespace {
inline std::ostream &show_predicate(internal::SelectionPredicate *p,
std::ostream &out = std::cout) {
IMP_PRINT_TREE(out, internal::SelectionPredicate*, p,
n->get_number_of_children(), n->get_child, n->show(out));
return out;
}
internal::SelectionPredicate::MatchType get_match_return(bool v) {
if (v) return internal::SelectionPredicate::MATCH_WITH_CHILDREN;
else return internal::SelectionPredicate::MISMATCH;
}
//! Reverse a match
class NotSelectionPredicate : public internal::SelectionPredicate {
Pointer<SelectionPredicate> predicate_;
public:
NotSelectionPredicate(SelectionPredicate *predicate,
std::string name = "NotSelectionPredicate%1%")
: internal::SelectionPredicate(name), predicate_(predicate) {}
virtual unsigned get_number_of_children() const IMP_OVERRIDE {
return 1;
}
virtual SelectionPredicate *get_child(unsigned) const IMP_OVERRIDE {
return predicate_;
}
virtual SelectionPredicate *clone(bool) IMP_OVERRIDE {
set_was_used(true);
return new NotSelectionPredicate(predicate_->clone(false));
}
virtual int setup_bitset(int index) IMP_OVERRIDE {
index = internal::SelectionPredicate::setup_bitset(index);
/* Set index for subpredicate */
index = predicate_->setup_bitset(index);
return index;
}
virtual ModelObjectsTemp do_get_inputs(
Model *m, const ParticleIndexes &pis) const
IMP_OVERRIDE {
return IMP::get_particles(m, pis);
}
virtual MatchType do_get_value_index(Model *m, ParticleIndex pi,
boost::dynamic_bitset<> &bs)
const IMP_OVERRIDE {
MatchType v = predicate_->get_value_index(m, pi, bs);
switch(v) {
case NO_MATCH:
/* If the subpredicate doesn't match, we do... but we don't want to
cache this result, since child particles may match */
return MATCH_SELF_ONLY;
case MATCH_WITH_CHILDREN:
return MISMATCH;
case MISMATCH:
return MATCH_WITH_CHILDREN;
default:
/* The opposite of a non-cached match (MATCH_SELF_ONLY)
is a "no match" */
return NO_MATCH;
}
}
IMP_OBJECT_METHODS(NotSelectionPredicate);
};
//! Match only if every subpredicate matches (or there are no subpredicates)
class AndSelectionPredicate : public internal::ListSelectionPredicate {
public:
AndSelectionPredicate(std::string name = "AndSelectionPredicate%1%")
: internal::ListSelectionPredicate(name) {}
virtual SelectionPredicate *clone(bool toplevel) IMP_OVERRIDE {
set_was_used(true);
// If only one predicate and we're not the top level,
// no need to keep ourself around
if (!toplevel && predicates_.size() == 1) {
return predicates_[0]->clone(false);
} else {
Pointer<ListSelectionPredicate> a = new AndSelectionPredicate();
clone_predicates(a);
return a.release();
}
}
virtual MatchType do_get_value_index(Model *m, ParticleIndex pi,
boost::dynamic_bitset<> &bs)
const IMP_OVERRIDE {
// Empty list matches everything
if (predicates_.size() == 0) {
return MATCH_WITH_CHILDREN;
}
bool no_match = false, cached_match = true;
IMP_FOREACH(internal::SelectionPredicate *p, predicates_) {
MatchType v = p->get_value_index(m, pi, bs);
if (v == MISMATCH) {
return MISMATCH;
} else if (v == NO_MATCH) {
no_match = true;
} else if (v == MATCH_SELF_ONLY) {
cached_match = false;
}
}
if (no_match) {
return NO_MATCH;
} else if (cached_match) {
return MATCH_WITH_CHILDREN;
} else {
return MATCH_SELF_ONLY;
}
}
IMP_OBJECT_METHODS(AndSelectionPredicate);
};
//! Match if any subpredicate matches (or there are no subpredicates)
class OrSelectionPredicate : public internal::ListSelectionPredicate {
public:
OrSelectionPredicate(std::string name = "OrSelectionPredicate%1%")
: internal::ListSelectionPredicate(name) {}
virtual SelectionPredicate *clone(bool) IMP_OVERRIDE {
set_was_used(true);
Pointer<ListSelectionPredicate> a = new OrSelectionPredicate();
clone_predicates(a);
return a.release();
}
virtual MatchType do_get_value_index(Model *m, ParticleIndex pi,
boost::dynamic_bitset<> &bs)
const IMP_OVERRIDE {
// Empty list matches everything
if (predicates_.size() == 0) {
return MATCH_WITH_CHILDREN;
}
bool no_match = false, no_cached_match = false;
IMP_FOREACH(internal::SelectionPredicate *p, predicates_) {
MatchType v = p->get_value_index(m, pi, bs);
if (v == MATCH_WITH_CHILDREN) {
return MATCH_WITH_CHILDREN;
} else if (v == NO_MATCH) {
no_match = true;
} else if (v == MATCH_SELF_ONLY) {
no_cached_match = true;
}
}
if (no_cached_match) {
return MATCH_SELF_ONLY;
} else if (no_match) {
return NO_MATCH;
} else {
return MISMATCH;
}
}
IMP_OBJECT_METHODS(OrSelectionPredicate);
};
//! Match if an odd number of subpredicates match (or there are none)
class XorSelectionPredicate : public internal::ListSelectionPredicate {
public:
XorSelectionPredicate(std::string name = "XorSelectionPredicate%1%")
: internal::ListSelectionPredicate(name) {}
virtual SelectionPredicate *clone(bool) IMP_OVERRIDE {
set_was_used(true);
Pointer<ListSelectionPredicate> a = new XorSelectionPredicate();
clone_predicates(a);
return a.release();
}
virtual MatchType do_get_value_index(Model *m, ParticleIndex pi,
boost::dynamic_bitset<> &bs)
const IMP_OVERRIDE {
// Empty list matches everything
if (predicates_.size() == 0) {
return MATCH_WITH_CHILDREN;
}
bool no_match = false, match = false;
IMP_FOREACH(internal::SelectionPredicate *p, predicates_) {
MatchType v = p->get_value_index(m, pi, bs);
if (v == MATCH_WITH_CHILDREN || v == MATCH_SELF_ONLY) {
match = !match;
}
if (v == NO_MATCH || v == MATCH_SELF_ONLY) {
no_match = true;
}
}
if (match) {
/* Note that we *don't* want to cache matches from this predicate,
since a child might match another subpredicate and so flip this
predicate's match bit */
return MATCH_SELF_ONLY;
} else if (no_match) {
return NO_MATCH;
} else {
return MISMATCH;
}
}
IMP_OBJECT_METHODS(XorSelectionPredicate);
};
}
void Selection::init_predicate() {
and_predicate_ = new AndSelectionPredicate();
and_predicate_->set_was_used(true);
predicate_ = and_predicate_;
}
Selection::Selection() : resolution_(0),representation_type_(BALLS) {
init_predicate();
m_ = nullptr;
}
Selection Selection::create_clone() {
Selection s;
s.m_ = m_;
s.h_ = h_;
s.resolution_ = resolution_;
s.representation_type_ = representation_type_;
s.predicate_ = dynamic_cast<internal::ListSelectionPredicate*>
(predicate_->clone(true));
IMP_INTERNAL_CHECK(s.predicate_, "Clone failed");
s.and_predicate_ = nullptr;
return s;
}
Selection::Selection(Particle *h) : resolution_(0),representation_type_(BALLS) {
init_predicate();
set_hierarchies(h->get_model(), ParticleIndexes(1, h->get_index()));
}
Selection::Selection(Hierarchy h) : resolution_(0),representation_type_(BALLS) {
init_predicate();
set_hierarchies(h.get_model(),
ParticleIndexes(1, h.get_particle_index()));
}
Selection::Selection(Model *m, const ParticleIndexes &pis)
: resolution_(0),representation_type_(BALLS) {
init_predicate();
set_hierarchies(m, pis);
}
Selection::Selection(const Hierarchies &h) :
resolution_(0),representation_type_(BALLS) {
init_predicate();
if (h.empty()) {
m_ = nullptr;
return;
} else {
set_hierarchies(h[0].get_model(), IMP::internal::get_index(h));
}
}
Selection::Selection(const ParticlesTemp &h) :
resolution_(0),representation_type_(BALLS) {
init_predicate();
if (h.empty()) {
m_ = nullptr;
return;
} else {
set_hierarchies(h[0]->get_model(), IMP::get_indexes(h));
}
}
// for C++
Selection::Selection(Hierarchy h, std::string molname, int residue_index)
: resolution_(0),representation_type_(BALLS) {
init_predicate();
set_hierarchies(h.get_model(),
ParticleIndexes(1, h.get_particle_index()));
set_molecules(Strings(1, molname));
set_residue_indexes(Ints(1, residue_index));
}
void Selection::set_hierarchies(Model *m,
const ParticleIndexes &pi) {
m_ = m;
h_ = pi;
for (unsigned int i = 0; i < pi.size(); ++i) {
Hierarchy h(m_, pi[i]);
IMP_USAGE_CHECK(h.get_is_valid(true), "Hierarchy " << h
<< " is not valid.");
}
}
namespace {
#define IMP_ATOM_SELECTION_PRED(Name, DataType, check) \
class Name##SelectionPredicate : public internal::SelectionPredicate { \
DataType data_; \
\
public: \
Name##SelectionPredicate(const DataType &data, \
std::string name = #Name "SelectionPredicate%1%") \
: internal::SelectionPredicate(name), data_(data) {} \
virtual MatchType do_get_value_index(Model *m, \
ParticleIndex pi, \
boost::dynamic_bitset<> &) \
const IMP_OVERRIDE { \
check; \
} \
virtual ModelObjectsTemp do_get_inputs( \
Model *m, const ParticleIndexes &pis) const \
IMP_OVERRIDE { \
return IMP::get_particles(m, pis); \
} \
IMP_OBJECT_METHODS(Name##SelectionPredicate); \
};
bool get_is_residue_index_match(const Ints &data, Model *m,
ParticleIndex pi) {
if (Residue::get_is_setup(m, pi)) {
return std::binary_search(data.begin(), data.end(),
Residue(m, pi).get_index());
}
if (Fragment::get_is_setup(m, pi)) {
Ints cur = Fragment(m, pi).get_residue_indexes();
Ints si;
std::set_intersection(data.begin(), data.end(), cur.begin(), cur.end(),
std::back_inserter(si));
return !si.empty();
} else if (Domain::get_is_setup(m, pi)) {
IntRange ir = Domain(m, pi).get_index_range();
return std::lower_bound(data.begin(), data.end(), ir.first) !=
std::lower_bound(data.begin(), data.end(), ir.second);
}
return false;
}
IMP_ATOM_SELECTION_PRED(ResidueIndex, Ints, {
bool this_matches = get_is_residue_index_match(data_, m, pi);
if (!this_matches)
return NO_MATCH;
if (Hierarchy(m, pi).get_number_of_children() > 0) {
// if any children match, push it until then
for (unsigned int i = 0; i < Hierarchy(m, pi).get_number_of_children();
++i) {
ParticleIndex cpi =
Hierarchy(m, pi).get_child(i).get_particle_index();
bool cur = get_is_residue_index_match(data_, m, cpi);
if (cur) {
return NO_MATCH;
}
}
}
return MATCH_WITH_CHILDREN;
});
IMP_ATOM_SELECTION_PRED(MoleculeName, Strings, {
if (Molecule::get_is_setup(m, pi)) {
return get_match_return(std::binary_search(data_.begin(), data_.end(),
m->get_particle_name(pi)));
}
return NO_MATCH;
});
IMP_ATOM_SELECTION_PRED(ResidueType, ResidueTypes, {
if (Residue::get_is_setup(m, pi)) {
return get_match_return(std::binary_search(
data_.begin(), data_.end(), Residue(m, pi).get_residue_type()));
}
return NO_MATCH;
});
IMP_ATOM_SELECTION_PRED(Element, Element, {
if (Atom::get_is_setup(m, pi)) {
return get_match_return(data_ == Atom(m, pi).get_element());
}
return NO_MATCH;
});
IMP_ATOM_SELECTION_PRED(ChainID, Strings, {
if (Chain::get_is_setup(m, pi)) {
return get_match_return(
std::binary_search(data_.begin(), data_.end(), Chain(m, pi).get_id()));
}
return NO_MATCH;
});
IMP_ATOM_SELECTION_PRED(AtomType, AtomTypes, {
if (Atom::get_is_setup(m, pi)) {
return get_match_return(std::binary_search(data_.begin(), data_.end(),
Atom(m, pi).get_atom_type()));
}
return NO_MATCH;
});
IMP_ATOM_SELECTION_PRED(DomainName, Strings, {
if (Domain::get_is_setup(m, pi)) {
return get_match_return(std::binary_search(data_.begin(), data_.end(),
m->get_particle_name(pi)));
}
return NO_MATCH;
});
IMP_ATOM_SELECTION_PRED(CopyIndex, Ints, {
if (Copy::get_is_setup(m, pi)) {
return get_match_return(std::binary_search(data_.begin(), data_.end(),
Copy(m, pi).get_copy_index()));
}
return NO_MATCH;
});
IMP_ATOM_SELECTION_PRED(StateIndex, Ints, {
if (State::get_is_setup(m, pi)) {
return get_match_return(std::binary_search(data_.begin(), data_.end(),
State(m, pi).get_state_index()));
}
return NO_MATCH;
});
IMP_ATOM_SELECTION_PRED(Type, core::ParticleTypes, {
if (core::Typed::get_is_setup(m, pi)) {
if( std::binary_search(data_.begin(), data_.end(),
core::Typed(m, pi).get_type())) {
return MATCH_WITH_CHILDREN;
}
}
return NO_MATCH;
});
#define IMP_ATOM_SELECTION_MATCH_TYPE(Type, type, UCTYPE) \
if (Type::get_is_setup(m, pi)) { \
if (std::binary_search(data_.begin(), data_.end(), UCTYPE)) \
return MATCH_WITH_CHILDREN; \
else \
return NO_MATCH; \
}
IMP_ATOM_SELECTION_PRED(HierarchyType, Ints, {
IMP_ATOM_FOREACH_HIERARCHY_TYPE_STATEMENTS(IMP_ATOM_SELECTION_MATCH_TYPE);
return NO_MATCH;
});
bool get_is_terminus(Model *m, ParticleIndex pi, int t) {
if (Atom::get_is_setup(m, pi)) {
// Atoms can only be termini if the type matches
Atom a(m, pi);
if (t == Selection::C && a.get_atom_type() != AT_C) {
return false;
}
if (t == Selection::N && a.get_atom_type() != AT_N) {
return false;
}
}
Hierarchy cur(m, pi);
Hierarchy p = cur.get_parent();
if (!p) return true;
// e.g. the terminal residue in a non-terminal fragment is *not* a terminus
if (!IMP::atom::Chain::get_is_setup(p) &&
!IMP::atom::Molecule::get_is_setup(p) &&
!get_is_terminus(m, p.get_particle_index(), t)) {
return false;
}
// Ignore order with atoms
if (!Atom::get_is_setup(m, pi)) {
unsigned int i = cur.get_child_index();
IMP_INTERNAL_CHECK(p.get_child(i) == cur, "Cur isn't the ith child");
if (t == Selection::C && i + 1 != p.get_number_of_children()) {
return false;
}
if (t == Selection::N && i != 0) {
return false;
}
}
return true;
}
IMP_ATOM_SELECTION_PRED(Terminus, Int, {
Hierarchy cur(m, pi);
if (cur.get_number_of_children() > 0) {
return NO_MATCH;
} else if (get_is_terminus(m, pi, data_)) {
return MATCH_WITH_CHILDREN;
} else {
return NO_MATCH;
}
});
IMP_NAMED_TUPLE_2(ExpandResult, ExpandResults, bool, from_rep,
ParticleIndexes, indexes, );
ExpandResult expand_search(Model *m,
ParticleIndex pi,
double resolution,
RepresentationType representation_type) {
// to handle representations
ParticleIndexes idxs;
bool from_rep = false;
if (Representation::get_is_setup(m, pi)) {
from_rep = true;
if (resolution == ALL_RESOLUTIONS) {
idxs = Representation(m, pi).get_representations(representation_type);
}
else {
Hierarchy tmp = Representation(m, pi).get_representation(resolution,
representation_type);
if (tmp) idxs.push_back(tmp);
}
}
else {
idxs.push_back(pi);
}
return ExpandResult(from_rep,idxs);
}
ExpandResults expand_children_search(Model *m,
ParticleIndex pi,
double resolution,
RepresentationType representation_type) {
Hierarchy h(m, pi);
ExpandResults ret;
IMP_FOREACH(Hierarchy c, h.get_children()) {
ExpandResult r = expand_search(m, c, resolution, representation_type);
if (r.get_indexes().size()>0) ret.push_back(r);
}
return ret;
}
}
Selection::SearchResult Selection::search(
Model *m, ParticleIndex pi,
boost::dynamic_bitset<> parent, bool with_representation,
bool found_rep_node) const {
IMP_FUNCTION_LOG;
IMP_LOG_VERBOSE("Searching " << m->get_particle_name(pi) << std::endl);
internal::SelectionPredicate::MatchType val
= predicate_->get_value_index(m, pi, parent);
if (val == internal::SelectionPredicate::MISMATCH) {
// nothing can match in this subtree
return SearchResult(false, ParticleIndexes());
} else if (val == internal::SelectionPredicate::MATCH_WITH_CHILDREN
&& !with_representation) {
// terminate search without considering children, if we got a sure match
// BUT make sure non-BALLS only acceptable if you found a rep in subtree
if (representation_type_==BALLS || found_rep_node){
return SearchResult(true, ParticleIndexes(1, pi));
}
else return SearchResult(false, ParticleIndexes());
}
Hierarchy cur(m, pi);
ParticleIndexes children;
ExpandResults cur_children =
expand_children_search(m, pi, resolution_, representation_type_);
bool children_covered = true;
bool matched = (val == internal::SelectionPredicate::MATCH_WITH_CHILDREN
|| val == internal::SelectionPredicate::MATCH_SELF_ONLY);
IMP_FOREACH(ExpandResult chlist, cur_children) {
found_rep_node |= chlist.get_from_rep();
IMP_FOREACH(ParticleIndex ch, chlist.get_indexes()) {
SearchResult curr = search(m, ch, parent, with_representation, found_rep_node);
matched |= curr.get_match();
if (curr.get_match()) {
if (curr.get_indexes().empty()) {
children_covered = false;
} else {
children += curr.get_indexes();
}
}
}
}
if (matched) {
IMP_LOG_VERBOSE("Matched " << m->get_particle_name(pi) << " with "
<< children << " and " << children_covered
<<" found rep node: "<<found_rep_node
<< std::endl);
if (children_covered && !children.empty()) {
return SearchResult(true, children);
}
else {
if (representation_type_==BALLS || found_rep_node){
return SearchResult(true, ParticleIndexes(1, pi));
}
else return SearchResult(false, ParticleIndexes());
}
}
return SearchResult(false, ParticleIndexes());
}
ParticlesTemp
Selection::get_selected_particles(bool with_representation) const {
return IMP::get_particles(m_,
get_selected_particle_indexes(with_representation));
}
ParticleIndexes
Selection::get_selected_particle_indexes(bool with_representation) const {
if (h_.empty()) return ParticleIndexes();
ParticleIndexes ret;
// Dynamic bitsets support .none(), but not .all(), so start with all
// true
int sz = predicate_->setup_bitset(0);
boost::dynamic_bitset<> base(sz);
base.set();
IMP_LOG_TERSE("Processing selection on " << h_ << " with predicates "
<< std::endl);
IMP_LOG_WRITE(VERBOSE, show_predicate(predicate_, IMP_STREAM));
IMP_FOREACH(ParticleIndex pi, h_) {
ExpandResult res = expand_search(m_, pi, resolution_,
representation_type_);
IMP_FOREACH(ParticleIndex rpi, res.get_indexes()) {
ret += search(m_, rpi, base, with_representation, res.get_from_rep()).get_indexes();
}
}
return ret;
}
Hierarchies Selection::get_hierarchies() const {
Hierarchies ret(h_.size());
for (unsigned int i = 0; i < h_.size(); ++i) {
ret[i] = Hierarchy(m_, h_[i]);
}
return ret;
}
void Selection::set_molecules(Strings mols) {
std::sort(mols.begin(), mols.end());
add_predicate(new MoleculeNameSelectionPredicate(mols));
}
void Selection::set_terminus(Terminus t) {
add_predicate(new TerminusSelectionPredicate(t));
}
void Selection::set_element(Element e) {
add_predicate(new ElementSelectionPredicate(e));
}
void Selection::set_chain_ids(Strings chains) {
std::sort(chains.begin(), chains.end());
add_predicate(new ChainIDSelectionPredicate(chains));
}
void Selection::set_residue_indexes(Ints indexes) {
std::sort(indexes.begin(), indexes.end());
add_predicate(new ResidueIndexSelectionPredicate(indexes));
}
void Selection::set_atom_types(AtomTypes types) {
std::sort(types.begin(), types.end());
add_predicate(new AtomTypeSelectionPredicate(types));
}
void Selection::set_residue_types(ResidueTypes types) {
std::sort(types.begin(), types.end());
add_predicate(new ResidueTypeSelectionPredicate(types));
}
void Selection::set_domains(Strings names) {
std::sort(names.begin(), names.end());
add_predicate(new DomainNameSelectionPredicate(names));
}
void Selection::set_molecule(std::string mol) {
set_molecules(Strings(1, mol));
}
void Selection::set_chain_id(std::string c) { set_chain_ids(Strings(1, c)); }
void Selection::set_residue_index(int i) { set_residue_indexes(Ints(1, i)); }
void Selection::set_atom_type(AtomType types) {
set_atom_types(AtomTypes(1, types));
}
void Selection::set_residue_type(ResidueType type) {
set_residue_types(ResidueTypes(1, type));
}
void Selection::set_domain(std::string name) { set_domains(Strings(1, name)); }
void Selection::set_copy_index(unsigned int copy) {
set_copy_indexes(Ints(1, copy));
}
void Selection::set_copy_indexes(Ints copies) {
std::sort(copies.begin(), copies.end());
add_predicate(new CopyIndexSelectionPredicate(copies));
}
void Selection::set_state_indexes(Ints copies) {
std::sort(copies.begin(), copies.end());
add_predicate(new StateIndexSelectionPredicate(copies));
}
void Selection::set_particle_type(core::ParticleType t) {
set_particle_types(core::ParticleTypes(1, t));
}
void Selection::set_particle_types(core::ParticleTypes t) {
std::sort(t.begin(), t.end());
add_predicate(new TypeSelectionPredicate(t));
}
void Selection::set_hierarchy_types(Ints types) {
std::sort(types.begin(), types.end());
add_predicate(new HierarchyTypeSelectionPredicate(types));
}
void Selection::set_intersection(const Selection &s) {
IMP_USAGE_CHECK(h_ == s.h_,
"Both Selections must be on the same Hierarchy or Hierarchies");
if (!dynamic_cast<AndSelectionPredicate*>(predicate_.get())) {
// Replace top-level predicate with a new AndSelectionPredicate, and make
// both the existing top-level predicate and the other selection's predicate
// children of it
Pointer<internal::ListSelectionPredicate> p
= new AndSelectionPredicate();
p->add_predicate(predicate_);
predicate_ = p;
}
predicate_->add_predicate(s.predicate_->clone(false));
}
void Selection::set_union(const Selection &s) {
IMP_USAGE_CHECK(h_ == s.h_,
"Both Selections must be on the same Hierarchy or Hierarchies");
if (!dynamic_cast<OrSelectionPredicate*>(predicate_.get())) {
// Replace top-level predicate with a new OrSelectionPredicate, and make
// both the existing top-level predicate and the other selection's predicate
// children of it
Pointer<internal::ListSelectionPredicate> p
= new OrSelectionPredicate();
p->add_predicate(predicate_);
predicate_ = p;
}
predicate_->add_predicate(s.predicate_->clone(false));
}
void Selection::set_symmetric_difference(const Selection &s) {
IMP_USAGE_CHECK(h_ == s.h_,
"Both Selections must be on the same Hierarchy or Hierarchies");
if (!dynamic_cast<XorSelectionPredicate*>(predicate_.get())) {
// Replace top-level predicate with a new XorSelectionPredicate, and make
// both the existing top-level predicate and the other selection's predicate
// children of it
Pointer<internal::ListSelectionPredicate> p
= new XorSelectionPredicate();
p->add_predicate(predicate_);
predicate_ = p;
}
predicate_->add_predicate(s.predicate_->clone(false));
}
void Selection::set_difference(const Selection &s) {
IMP_USAGE_CHECK(h_ == s.h_,
"Both Selections must be on the same Hierarchy or Hierarchies");
if (!dynamic_cast<AndSelectionPredicate*>(predicate_.get())) {
// Replace top-level predicate with a new AndSelectionPredicate, and make
// both the existing top-level predicate and the other selection's predicate
// (wrapped with a NotSelectionPredicate) children of it
Pointer<internal::ListSelectionPredicate> p
= new AndSelectionPredicate();
p->add_predicate(predicate_);
predicate_ = p;
}
predicate_->add_predicate(new NotSelectionPredicate
(s.predicate_->clone(false)));
}
void Selection::add_predicate(internal::SelectionPredicate *p)
{
// Take a reference to p so it gets freed if the usage check fails
Pointer<internal::SelectionPredicate> pp(p);
IMP_USAGE_CHECK(and_predicate_, "Cannot add predicates to Selection copies");
and_predicate_->add_predicate(p);
}
void Selection::show(std::ostream &out) const { out << "Selection on " << h_; }
namespace {
template <class PS>
Restraint *create_distance_restraint(const Selection &n0, const Selection &n1,
PS *ps, std::string name) {
ParticlesTemp p0 = n0.get_selected_particles();
ParticlesTemp p1 = n1.get_selected_particles();
IMP_IF_CHECK(USAGE) {
boost::unordered_set<Particle *> all(p0.begin(), p0.end());
all.insert(p1.begin(), p1.end());
IMP_USAGE_CHECK(all.size() == p0.size() + p1.size(),
"The two selections cannot overlap.");
}
Pointer<Restraint> ret;
IMP_USAGE_CHECK(!p0.empty(),
"Selection " << n0 << " does not refer to any particles.");
IMP_USAGE_CHECK(!p1.empty(),
"Selection " << n1 << " does not refer to any particles.");
if (p1.size() == 1 && p0.size() == 1) {
IMP_LOG_TERSE("Creating distance restraint between "
<< p0[0]->get_name() << " and " << p1[0]->get_name()
<< std::endl);
ret = IMP::create_restraint(ps, ParticlePair(p0[0], p1[0]), name);
} else {
IMP_LOG_TERSE("Creating distance restraint between " << n0 << " and " << n1
<< std::endl);
/*if (p0.size()+p1.size() < 100) {
ret=new core::KClosePairsRestraint(ps,
p0, p1, 1,
"Atom k distance restraint %1%");
} else {*/
Pointer<core::TableRefiner> r = new core::TableRefiner();
r->add_particle(p0[0], p0);
r->add_particle(p1[0], p1);
IMP_NEW(core::KClosePairsPairScore, nps, (ps, r, 1));
ret = IMP::create_restraint(
nps.get(), ParticlePair(p0[0], p1[0]), name);
//}
}
return ret.release();
}
}
Restraint *create_distance_restraint(const Selection &n0, const Selection &n1,
double x0, double k, std::string name) {
IMP_NEW(core::HarmonicSphereDistancePairScore, ps, (x0, k));
return create_distance_restraint(n0, n1, ps.get(), name);
}
Restraint *create_connectivity_restraint(const Selections &s, double x0,
double k, std::string name) {
IMP_IF_CHECK(USAGE) {
boost::unordered_set<ParticleIndex> used;
IMP_FOREACH(const Selection & sel, s) {
ParticleIndexes cur = sel.get_selected_particle_indexes();
int old = used.size();
IMP_UNUSED(old);
used.insert(cur.begin(), cur.end());
IMP_USAGE_CHECK(used.size() == old + cur.size(),
"Input selections are not disjoint. This won't work.");
}
}
if (s.size() < 2) return nullptr;
if (s.size() == 2) {
IMP_NEW(core::HarmonicUpperBoundSphereDistancePairScore, ps, (x0, k));
Restraint *r =
create_distance_restraint(s[0], s[1], ps.get(), name);
return r;
} else {
unsigned int max = 0;
for (unsigned int i = 0; i < s.size(); ++i) {
max = std::max(
static_cast<unsigned int>(s[i].get_selected_particles().size()), max);
}
if (max == 1) {
// special case all singletons
ParticlesTemp particles;
for (unsigned int i = 0; i < s.size(); ++i) {
IMP_USAGE_CHECK(!s[i].get_selected_particles().empty(),
"No particles selected");
particles.push_back(s[i].get_selected_particles()[0]);
}
IMP_NEW(core::HarmonicUpperBoundSphereDistancePairScore, hdps, (x0, k));
IMP_NEW(container::ListSingletonContainer, lsc,
(particles[0]->get_model(), IMP::get_indexes(particles)));
IMP_NEW(container::ConnectingPairContainer, cpc, (lsc, 0));
Pointer<Restraint> cr =
container::create_restraint(hdps.get(), cpc.get(), name);
return cr.release();
} else {
IMP_NEW(core::TableRefiner, tr, ());
ParticlesTemp rps;
for (unsigned int i = 0; i < s.size(); ++i) {
ParticlesTemp ps = s[i].get_selected_particles();
IMP_USAGE_CHECK(!ps.empty(), "Selection "
<< s[i]
<< " does not contain any particles.");
tr->add_particle(ps[0], ps);
rps.push_back(ps[0]);
}
IMP_NEW(core::HarmonicUpperBoundSphereDistancePairScore, hdps, (x0, k));
Pointer<PairScore> ps;
IMP_LOG_TERSE("Using closest pair score." << std::endl);
ps = new core::KClosePairsPairScore(hdps, tr);
IMP_NEW(IMP::internal::StaticListContainer<SingletonContainer>,
lsc, (rps[0]->get_model(), "Connectivity particles"));
lsc->set(IMP::internal::get_index(rps));
IMP_NEW(core::ConnectivityRestraint, cr, (ps, lsc));
cr->set_name(name);
return cr.release();
}
}
}
Restraint *create_connectivity_restraint(const Selections &s, double k,
std::string name) {
return create_connectivity_restraint(s, 0, k, name);
}
Restraint *create_internal_connectivity_restraint(const Selection &ss,
double x0, double k,
std::string name) {
ParticleIndexes s = ss.get_selected_particle_indexes();
if (s.size() < 2) return nullptr;
Hierarchies h = ss.get_hierarchies();
Model *m = h[0].get_model();
if (s.size() == 2) {
IMP_NEW(core::HarmonicUpperBoundSphereDistancePairScore, ps, (x0, k));
IMP_NEW(core::PairRestraint, r,
(m, ps, ParticleIndexPair(s[0], s[1]), name));
return r.release();
} else {
IMP_NEW(core::HarmonicUpperBoundSphereDistancePairScore, hdps, (x0, k));
IMP_NEW(container::ListSingletonContainer, lsc, (m, s));
IMP_NEW(container::ConnectingPairContainer, cpc, (lsc, 0));
Pointer<Restraint> cr =
container::create_restraint(hdps.get(), cpc.get(), name);
return cr.release();
}
}
Restraint *create_internal_connectivity_restraint(const Selection &s, double k,
std::string name) {
return create_internal_connectivity_restraint(s, 0, k, name);
}
Restraint *create_excluded_volume_restraint(const Selections &ss) {
ParticlesTemp ps;
for (unsigned int i = 0; i < ss.size(); ++i) {
ParticlesTemp cps = ss[i].get_selected_particles();
IMP_IF_LOG(TERSE) {
IMP_LOG_TERSE("Found ");
for (unsigned int i = 0; i < cps.size(); ++i) {
IMP_LOG_TERSE(cps[i]->get_name() << " ");
}
IMP_LOG_TERSE(std::endl);
}
ps.insert(ps.end(), cps.begin(), cps.end());
}
IMP_NEW(IMP::internal::StaticListContainer<SingletonContainer>,
lsc, (ps[0]->get_model(), "Hierarchy EV particles"));
lsc->set(IMP::internal::get_index(ps));
IMP_NEW(core::ExcludedVolumeRestraint, evr, (lsc));
evr->set_name("Hierarchy EV");
return evr.release();
}
Restraint *create_excluded_volume_restraint(const Hierarchies &hs,
double resolution) {
Selections ss;
for (unsigned int i = 0; i < hs.size(); ++i) {
Selection s(hs[i]);
s.set_resolution(resolution);
ss.push_back(s);
}
return create_excluded_volume_restraint(ss);
}
core::XYZR create_cover(const Selection &s, std::string name) {
if (name.empty()) {
name = "atom cover";
}
ParticlesTemp ps = s.get_selected_particles();
IMP_USAGE_CHECK(!ps.empty(), "No particles selected.");
Particle *p = new Particle(ps[0]->get_model());
p->set_name(name);
core::RigidBody rb;
for (unsigned int i = 0; i < ps.size(); ++i) {
if (core::RigidMember::get_is_setup(ps[i])) {
if (!rb) {
rb = core::RigidMember(ps[i]).get_rigid_body();
} else {
if (rb != core::RigidMember(ps[i]).get_rigid_body()) {
rb = core::RigidBody();
break;
}
}
}
}
if (rb) {
algebra::Sphere3Ds ss;
for (unsigned int i = 0; i < ps.size(); ++i) {
ss.push_back(core::XYZR(ps[i]).get_sphere());
}
algebra::Sphere3D s = algebra::get_enclosing_sphere(ss);
core::XYZR d = core::XYZR::setup_particle(p, s);
rb.add_member(d);
return d;
} else {
core::Cover c = core::Cover::setup_particle(p, core::XYZRs(ps));
return c;
}
}
double get_mass(const Selection &h) {
IMP_FUNCTION_LOG;
double ret = 0;
ParticlesTemp ps = h.get_selected_particles();
for (unsigned int i = 0; i < ps.size(); ++i) {
ret += Mass(ps[i]).get_mass();
}
return ret;
}
#ifdef IMP_ALGEBRA_USE_IMP_CGAL
namespace {
algebra::Sphere3Ds get_representation(Selection h) {
ParticlesTemp leaves = h.get_selected_particles();
algebra::Sphere3Ds ret(leaves.size());
for (unsigned int i = 0; i < leaves.size(); ++i) {
ret[i] = core::XYZR(leaves[i]).get_sphere();
}
return ret;
}
}
double get_volume(const Selection &h) {
IMP_FUNCTION_LOG;
IMP_USAGE_CHECK(!h.get_selected_particles().empty(),
"No particles selected.");
return algebra::get_surface_area_and_volume(get_representation(h)).second;
}
double get_surface_area(const Selection &h) {
IMP_FUNCTION_LOG;
IMP_USAGE_CHECK(!h.get_selected_particles().empty(),
"No particles selected.");
return algebra::get_surface_area_and_volume(get_representation(h)).first;
}
#endif
double get_radius_of_gyration(const Selection &h) {
IMP_FUNCTION_LOG;
IMP_USAGE_CHECK(!h.get_selected_particles().empty(),
"No particles selected.");
return get_radius_of_gyration(h.get_selected_particles());
}
HierarchyTree get_hierarchy_tree(Hierarchy h) {
HierarchyTree ret;
typedef boost::property_map<HierarchyTree, boost::vertex_name_t>::type VM;
VM vm = boost::get(boost::vertex_name, ret);
Vector<std::pair<int, Hierarchy> > queue;
int v = boost::add_vertex(ret);
vm[v] = h;
queue.push_back(std::make_pair(v, h));
do {
int v = queue.back().first;
Hierarchy c = queue.back().second;
queue.pop_back();
for (unsigned int i = 0; i < c.get_number_of_children(); ++i) {
int vc = boost::add_vertex(ret);
vm[vc] = c.get_child(i);
boost::add_edge(v, vc, ret);
queue.push_back(std::make_pair(vc, c.get_child(i)));
}
} while (!queue.empty());
return ret;
}
display::Geometries SelectionGeometry::get_components() const {
display::Geometries ret;
ParticlesTemp ps = res_.get_selected_particles();
for (unsigned int i = 0; i < ps.size(); ++i) {
if (components_.find(ps[i]) == components_.end()) {
IMP_NEW(HierarchyGeometry, g, (atom::Hierarchy(ps[i])));
components_[ps[i]] = g;
g->set_name(get_name());
if (get_has_color()) {
components_[ps[i]]->set_color(get_color());
}
}
ret.push_back(components_.find(ps[i])->second);
}
return ret;
}
Hierarchies get_leaves(const Selection &h) {
Hierarchies ret;
ParticlesTemp ps = h.get_selected_particles();
for (unsigned int i = 0; i < ps.size(); ++i) {
ret += get_leaves(Hierarchy(ps[i]));
}
return ret;
}
namespace {
Ints get_tree_residue_indexes(Hierarchy h) {
if (Residue::get_is_setup(h)) {
return Ints(1, Residue(h).get_index());
}
Ints ret;
if (Domain::get_is_setup(h)) {
IntRange ir = Domain(h).get_index_range();
for (int i = ir.first; i < ir.second; ++i) {
ret.push_back(i);
}
} else if (Fragment::get_is_setup(h)) {
Ints cur = Fragment(h).get_residue_indexes();
ret.insert(ret.end(), cur.begin(), cur.end());
}
if (ret.empty()) {
if (h.get_number_of_children() > 0) {
for (unsigned int i = 0; i < h.get_number_of_children(); ++i) {
Ints cur = get_tree_residue_indexes(h.get_child(0));
ret.insert(ret.end(), cur.begin(), cur.end());
}
}
}
return ret;
}
}
Ints get_residue_indexes(Hierarchy h) {
do {
Ints ret = get_tree_residue_indexes(h);
if (!ret.empty()) return ret;
} while ((h = h.get_parent()));
IMP_THROW("Hierarchy " << h << " has no residue index.", ValueException);
}
ResidueType get_residue_type(Hierarchy h) {
do {
if (Residue::get_is_setup(h)) {
return Residue(h).get_residue_type();
}
} while ((h = h.get_parent()));
IMP_THROW("Hierarchy " << h << " has no residue type.", ValueException);
}
std::string get_chain_id(Hierarchy h) {
Chain c = get_chain(h);
if (!c) {
IMP_THROW("Hierarchy " << h << " has no chain.", ValueException);
} else {
return c.get_id();
}
}
AtomType get_atom_type(Hierarchy h) {
do {
if (Atom::get_is_setup(h)) {
return Atom(h).get_atom_type();
}
} while ((h = h.get_parent()));
IMP_THROW("Hierarchy " << h << " has no atom type.", ValueException);
}
std::string get_domain_name(Hierarchy h) {
do {
if (Domain::get_is_setup(h)) {
return Domain(h)->get_name();
}
} while ((h = h.get_parent()));
IMP_THROW("Hierarchy " << h << " has no domain name.", ValueException);
}
std::string get_molecule_name(Hierarchy h) {
do {
if (Molecule::get_is_setup(h)) {
return h->get_name();
}
} while ((h = get_parent_representation(h)));
IMP_THROW("Hierarchy " << h << " has no molecule name.", ValueException);
}
IMPATOM_END_NAMESPACE
| shanot/imp | modules/atom/src/Selection.cpp | C++ | gpl-3.0 | 41,273 |
<?php
/**
* The template for displaying the footer.
*
* Contains the closing of the #content div and all content after
*
* @package Bristol Big Youth Vote
*/
?>
</div><!-- #content -->
<footer id="colophon" class="site-footer" role="contentinfo">
<ul class="acknowledgements">
<li><img src="<?php bloginfo('template_directory'); ?>/img/bristol-city-council.png" alt="Bristol City Council"></li>
<li><img src="<?php bloginfo('template_directory'); ?>/img/bristol-city-youth-council.png" alt="Bristol City Youth Council"></li>
<li><img src="<?php bloginfo('template_directory'); ?>/img/bristol-youth-links.png" alt="Bristol Youth Links"></li>
<li><img src="<?php bloginfo('template_directory'); ?>/img/knowle-west-media-centre.jpg" alt="Knowle West Media Centre"></li>
</ul>
<div class="site-info">
<a href="<?php echo esc_url( __( 'http://wordpress.org/', 'bristolbigyouthvote' ) ); ?>"><?php printf( __( 'Proudly powered by %s', 'bristolbigyouthvote' ), 'WordPress' ); ?></a>
<span class="sep"> | </span>
<?php printf( __( 'Theme: %1$s by %2$s.', 'bristolbigyouthvote' ), 'Bristol Big Youth Vote', '<a href="http://davidbiddle.co.uk" rel="designer" title="David Biddle - Bristol Web Developer">David Biddle</a>' ); ?>
</div><!-- .site-info -->
</footer><!-- #colophon -->
</div><!-- #page -->
<?php wp_footer(); ?>
</body>
</html>
| DavidBiddle/bbyv-theme | footer.php | PHP | gpl-3.0 | 1,408 |
<?php
/**
Copyright 2011-2015 Nick Korbel
This file is part of Booked Scheduler.
Booked Scheduler is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Booked Scheduler is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Booked Scheduler. If not, see <http://www.gnu.org/licenses/>.
*/
require_once('Language.php');
require_once('en_us.php');
//Spanish language
class es extends en_us
{
public function __construct()
{
parent::__construct();
}
protected function _LoadDates()
{
$dates = parent::_LoadDates();
$dates['general_date'] = 'd/m/Y';
$dates['general_datetime'] = 'd/m/Y H:i:s';
$dates['schedule_daily'] = 'l, d/m/Y';
$dates['reservation_email'] = 'd/m/Y @ g:i A (e)';
$dates['res_popup'] = 'd/m/Y g:i A';
$dates['dashboard'] = 'd/m/Y g:i A';
$dates['period_time'] = "g:i A";
$dates['general_date_js'] = "dd/mm/yy";
$this->Dates = $dates;
}
protected function _LoadStrings()
{
$strings = parent::_LoadStrings();
$strings['FirstName'] = 'Nombre';
$strings['LastName'] = 'Apellido';
$strings['Timezone'] = 'Zona Horaria';
$strings['Edit'] = 'Editar';
$strings['Change'] = 'Cambiar';
$strings['Rename'] = 'Renombrar';
$strings['Remove'] = 'Eliminar';
$strings['Delete'] = 'Borrar';
$strings['Update'] = 'Actualizar';
$strings['Cancel'] = 'Cancelar';
$strings['Add'] = 'Añadir';
$strings['Name'] = 'Nombre';
$strings['Yes'] = 'Sí';
$strings['No'] = 'No';
$strings['FirstNameRequired'] = 'Se requiere un Nombre.';
$strings['LastNameRequired'] = 'Se requiere un Apellido.';
$strings['PwMustMatch'] = 'La contraseña de confirmación debe coincidir.';
$strings['PwComplexity'] = 'La contraseña debe tener por lo menos 6 carácteres.';
$strings['PwRequired'] = 'Se requiere una contraseña.';
$strings['ValidEmailRequired'] = 'Se requiere una dirección válida de correo.';
$strings['UniqueEmailRequired'] = 'Esa dirección de correo ya está registrada.';
$strings['UniqueUsernameRequired'] = 'Ese Nombre de Usuario ya está registrado.';
$strings['UserNameRequired'] = 'Se requiere un Nombre de Usuario.';
$strings['CaptchaMustMatch'] = 'Por favor, introduce los carácteres de seguridad tal como aparecen.';
$strings['Today'] = 'Hoy';
$strings['Week'] = 'Semana';
$strings['Month'] = 'Mes';
$strings['BackToCalendar'] = 'Regreso al calendario';
$strings['BeginDate'] = 'Inicio';
$strings['EndDate'] = 'Fin';
$strings['Username'] = 'Nombre de Usuario';
$strings['Password'] = 'Contraseña';
$strings['PasswordConfirmation'] = 'Confirmar Contraseña';
$strings['DefaultPage'] = 'Página de Inicio predeterminada';
$strings['MyCalendar'] = 'Mi Calendario';
$strings['ScheduleCalendar'] = 'Calendario de Reservas';
$strings['Registration'] = 'Registro';
$strings['NoAnnouncements'] = 'No hay Anuncios';
$strings['Announcements'] = 'Anuncios';
$strings['NoUpcomingReservations'] = 'No tienes Reservas próximas';
$strings['UpcomingReservations'] = 'Próximas Reservas';
$strings['ShowHide'] = 'Mostrar/Ocultar';
$strings['Error'] = 'Error';
$strings['ReturnToPreviousPage'] = 'Volver a la última página en la que estabas';
$strings['UnknownError'] = 'Error Desconocido';
$strings['InsufficientPermissionsError'] = 'No tienes permiso para acceder a este Recurso';
$strings['MissingReservationResourceError'] = 'No se ha seleccionado un Recurso';
$strings['MissingReservationScheduleError'] = 'No se ha seleccionado una Planificación';
$strings['DoesNotRepeat'] = 'No Se Repite';
$strings['Daily'] = 'Diario';
$strings['Weekly'] = 'Semanal';
$strings['Monthly'] = 'Mensual';
$strings['Yearly'] = 'Anual';
$strings['RepeatPrompt'] = 'Repetir';
$strings['hours'] = 'Horas';
$strings['days'] = 'días';
$strings['weeks'] = 'semanas';
$strings['months'] = 'meses';
$strings['years'] = 'años';
$strings['day'] = 'Día';
$strings['week'] = 'Semana';
$strings['month'] = 'Mes';
$strings['year'] = 'Año';
$strings['repeatDayOfMonth'] = 'día del mes';
$strings['repeatDayOfWeek'] = 'día de la semana';
$strings['RepeatUntilPrompt'] = 'Hasta';
$strings['RepeatEveryPrompt'] = 'Cada';
$strings['RepeatDaysPrompt'] = 'En';
$strings['CreateReservationHeading'] = 'Crear una nueva reserva';
$strings['EditReservationHeading'] = 'Editando reserva %s';
$strings['ViewReservationHeading'] = 'Viendo reserva %s';
$strings['ReservationErrors'] = 'Cambiar Reserva';
$strings['Create'] = 'Crear';
$strings['ThisInstance'] = 'Sólo Esta Instancia';
$strings['AllInstances'] = 'Todas Las Instancias';
$strings['FutureInstances'] = 'Instancias Futuras';
$strings['Print'] = 'Imprimir';
$strings['ShowHideNavigation'] = 'Mostrar/Ocultar Navegación';
$strings['ReferenceNumber'] = 'Número de Referencia';
$strings['Tomorrow'] = 'Mañana';
$strings['LaterThisWeek'] = 'Más Tarde Esta Semana';
$strings['NextWeek'] = 'Siguiente Semana';
$strings['SignOut'] = 'Cerrar';
$strings['LayoutDescription'] = 'Empieza en %s, mostrando %s días cada vez';
$strings['AllResources'] = 'Todos Los Recursos';
$strings['TakeOffline'] = 'Deshabilitar';
$strings['BringOnline'] = 'Habilitar';
$strings['AddImage'] = 'Añadir Imágen';
$strings['NoImage'] = 'Sin Imágen Asignada';
$strings['Move'] = 'Mover';
$strings['AppearsOn'] = 'Aparece En %s';
$strings['Location'] = 'Localización';
$strings['NoLocationLabel'] = '(no se ha fijado una localización)';
$strings['Contact'] = 'Contacto';
$strings['NoContactLabel'] = '(sin información de contacto';
$strings['Description'] = 'Descripción';
$strings['NoDescriptionLabel'] = '(sin descripción)';
$strings['Notes'] = 'Notas';
$strings['NoNotesLabel'] = '(sin notas)';
$strings['NoTitleLabel'] = '(sin título)';
$strings['UsageConfiguration'] = 'Configuración De Uso';
$strings['ChangeConfiguration'] = 'Cambiar Configuración';
$strings['ResourceMinLength'] = 'Las reservas deben durar por lo menos %s';
$strings['ResourceMinLengthNone'] = 'No hay duración mínima de reserva';
$strings['ResourceMaxLength'] = 'Las reservas no pueden durar más de %s';
$strings['ResourceMaxLengthNone'] = 'No hay duración máxima de reserva';
$strings['ResourceRequiresApproval'] = 'Las reservas deben ser aprobadas';
$strings['ResourceRequiresApprovalNone'] = 'Las reservas no requieren ser aprobadas';
$strings['ResourcePermissionAutoGranted'] = 'El permiso es automáticamente concedido';
$strings['ResourcePermissionNotAutoGranted'] = 'El permiso no es automáticamente concedido';
$strings['ResourceMinNotice'] = 'Las reservas deben ser realizadas por lo menos %s antés del tiempo de inicio';
$strings['ResourceMinNoticeNone'] = 'Las reservas se pueden realizar hasta el tiempo actual';
$strings['ResourceMaxNotice'] = 'Las reservas no deben durar más de %s desde el tiempo actual';
$strings['ResourceMaxNoticeNone'] = 'Las reservas pueden terminar en cualquier momento futuro';
$strings['ResourceBufferTime'] = 'Debe de haber %s entre reservas';
$strings['ResourceBufferTimeNone'] = 'No hay tiempo entre reservas';
$strings['ResourceAllowMultiDay'] = 'Las reservas pueden extenderse a lo largo de días';
$strings['ResourceNotAllowMultiDay'] = 'Las reservas no pueden extenderse a lo largo de días';
$strings['ResourceCapacity'] = 'Este recurso tiene una capacidad de %s personas';
$strings['ResourceCapacityNone'] = 'Este recurso tiene capacidad ilimitada';
$strings['AddNewResource'] = 'Añadir Nuevo Recurso';
$strings['AddNewUser'] = 'Añadir Nuevo Usuario';
$strings['AddUser'] = 'Añadir Usuario';
$strings['Schedule'] = 'Planificación';
$strings['AddResource'] = 'Añadir Recurso';
$strings['Capacity'] = 'Capacidad';
$strings['Access'] = 'Acceso';
$strings['Duration'] = 'Duración';
$strings['Active'] = 'Activo';
$strings['Inactive'] = 'Inactivo';
$strings['ResetPassword'] = 'Reiniciar Contraseñ';
$strings['LastLogin'] = 'Último Inicio de Sesión';
$strings['Search'] = 'Buscar';
$strings['ResourcePermissions'] = 'Permisos del Recurso';
$strings['Reservations'] = 'Reservas';
$strings['Groups'] = 'Grupos';
$strings['ResetPassword'] = 'Reiniciar Contraseñ';
$strings['AllUsers'] = 'Todos Los Usuarios';
$strings['AllGroups'] = 'Todos Los Grupos';
$strings['AllSchedules'] = 'Todas Las Planificaciones';
$strings['UsernameOrEmail'] = 'Nombre de Usuario o correo electrónico';
$strings['Members'] = 'Miembros';
$strings['QuickSlotCreation'] = 'Crear un intervalo de tiempo cada %s minutos entre %s y %s';
$strings['ApplyUpdatesTo'] = 'Aplicar Actualizaciones A';
$strings['CancelParticipation'] = 'Cancelar Participación';
$strings['Attending'] = 'Asistencia';
$strings['QuotaConfiguration'] = '%s Para %s usuarios del grupo %s están limitados a %s %s por cada %s';
$strings['reservations'] = 'reservas';
$strings['ChangeCalendar'] = 'Cambiar Calendario';
$strings['AddQuota'] = 'Añadir Cuota';
$strings['FindUser'] = 'Encontrar Usuario';
$strings['Created'] = 'Creado';
$strings['LastModified'] = 'Última Modificación';
$strings['GroupName'] = 'Nombre de Grupo';
$strings['GroupMembers'] = 'Miembros del Grupo';
$strings['GroupRoles'] = 'Roles del Grupo';
$strings['GroupAdmin'] = 'Administrador del Grupo';
$strings['Actions'] = 'Acciones';
$strings['CurrentPassword'] = 'Contraseña Actual';
$strings['NewPassword'] = 'Nueva Contraseña';
$strings['InvalidPassword'] = 'La Contraseña actual es incorrecta';
$strings['PasswordChangedSuccessfully'] = 'Tu Contraseña ha sido modificada con éxito';
$strings['SignedInAs'] = 'Sesión iniciada por ';
$strings['NotSignedIn'] = 'No has iniciado sesión';
$strings['ReservationTitle'] = 'Título de la reserva';
$strings['ReservationDescription'] = 'Descripción de la reserva';
$strings['ResourceList'] = 'Recursos a reservar';
$strings['Accessories'] = 'Accesorios';
$strings['Add'] = 'Añadir';
$strings['ParticipantList'] = 'Participantes';
$strings['InvitationList'] = 'Invitados';
$strings['AccessoryName'] = 'Nombre de Accesorio';
$strings['QuantityAvailable'] = 'Cantidad Disponible';
$strings['Resources'] = 'Recursos';
$strings['Participants'] = 'Participantes';
$strings['User'] = 'Usuario';
$strings['Resource'] = 'Recurso';
$strings['Status'] = 'Estado';
$strings['Approve'] = 'Aprobado';
$strings['Page'] = 'Página';
$strings['Rows'] = 'Filas';
$strings['Unlimited'] = 'Ilimitado';
$strings['Email'] = 'Correo';
$strings['EmailAddress'] = 'Direción de Correo';
$strings['Phone'] = 'Teléfono';
$strings['Organization'] = 'Organización';
$strings['Position'] = 'Nº de Socio';
$strings['Language'] = 'Lenguaje';
$strings['Permissions'] = 'Permisos';
$strings['Reset'] = 'Reiniciar';
$strings['FindGroup'] = 'Encontrar Grupo';
$strings['Manage'] = 'Gestionar';
$strings['None'] = 'Ninguno';
$strings['AddToOutlook'] = 'Añadir a Outlook';
$strings['Done'] = 'Hecho';
$strings['RememberMe'] = 'Recuérdame';
$strings['FirstTimeUser?'] = '¿Eres un usuario nuevo?';
$strings['CreateAnAccount'] = 'Crear Cuenta';
$strings['ViewSchedule'] = 'Ver Planificación';
$strings['ForgotMyPassword'] = 'He Olvidado Mi Contraseña';
$strings['YouWillBeEmailedANewPassword'] = 'Se te enviará una contraseña generada aleatoriamente.';
$strings['Close'] = 'Cerrar';
$strings['ExportToCSV'] = 'Exportar a CSV';
$strings['OK'] = 'OK';
$strings['Working'] = 'Funcionando...';
$strings['Login'] = 'Iniciar Sesión';
$strings['AdditionalInformation'] = 'Información Adicional';
$strings['AllFieldsAreRequired'] = 'Se requieren todos los campos';
$strings['Optional'] = 'opcional';
$strings['YourProfileWasUpdated'] = 'Tu perfil fue actualizado';
$strings['YourSettingsWereUpdated'] = 'Tus ajustes fueron actualizados';
$strings['Register'] = 'Registrar';
$strings['SecurityCode'] = 'Código de Seguridad';
$strings['ReservationCreatedPreference'] = 'Cuando yo creo una reserva o una reserva es creada en mi nombre';
$strings['ReservationUpdatedPreference'] = 'Cuando yo actualizado una reserva o una reserva es actualizada en mi nombre';
$strings['ReservationApprovalPreference'] = 'Cuando mi reserva pendiente ha sido aprobada';
$strings['PreferenceSendEmail'] = 'Envíame un correo';
$strings['PreferenceNoEmail'] = 'No me notifiques';
$strings['ReservationCreated'] = '¡Tu reserva ha sido creada con éxito!';
$strings['ReservationUpdated'] = 'Tu reserva ha sido actualizada con éxito!';
$strings['ReservationRemoved'] = 'Tu reserva ha sido eliminada';
$strings['YourReferenceNumber'] = 'Tu número de referencia es %s';
$strings['UpdatingReservation'] = 'Actualizando reserva';
$strings['ChangeUser'] = 'Cambiar Usuario';
$strings['MoreResources'] = 'Más Recursos';
$strings['ReservationLength'] = 'Duración de la Reserva';
$strings['ParticipantList'] = 'Lista de Participantes';
$strings['AddParticipants'] = 'Añadir Participantes';
$strings['InviteOthers'] = 'Invitar A Otros';
$strings['AddResources'] = 'Añadir Resources';
$strings['AddAccessories'] = 'Añadir Accesorios';
$strings['Accessory'] = 'Accesorio';
$strings['QuantityRequested'] = 'Cantidad Requerida';
$strings['CreatingReservation'] = 'Creando Reserva';
$strings['UpdatingReservation'] = 'Actualizado Reserva';
$strings['DeleteWarning'] = '¡Esta acción es permanente e irrecuperable!';
$strings['DeleteAccessoryWarning'] = 'Al borrar este accesorio se eliminará de todas las reservas.';
$strings['AddAccessory'] = 'Añadir Accesorio';
$strings['AddBlackout'] = 'Añadir No Disponibilidad';
$strings['AllResourcesOn'] = 'Todos los Recursos Habilitados';
$strings['Reason'] = 'Razón';
$strings['BlackoutShowMe'] = 'Muéstrame reservas en conflicto';
$strings['BlackoutDeleteConflicts'] = 'Borrar las reservas en conflicto';
$strings['Filter'] = 'Filtrar';
$strings['Between'] = 'Entre';
$strings['CreatedBy'] = 'Creada Por';
$strings['BlackoutCreated'] = 'No Disponibilidad Creada';
$strings['BlackoutNotCreated'] = 'No se ha podido crear la No Dispinibilidad';
$strings['BlackoutConflicts'] = 'Hay conflictos en la temporización de No Disponibilidad';
$strings['BlackoutUpdated'] = 'No Disponibilidad actualizada';
$strings['BlackoutNotUpdated'] = 'La No Disponibilidad no pudo ser actualizada';
$strings['BlackoutConflicts'] = 'There are conflicting blackout times';
$strings['ReservationConflicts'] = 'Hay tiempos de reserva en conflicto';
$strings['UsersInGroup'] = 'Usuarios en este grupo';
$strings['Browse'] = 'Navegar';
$strings['DeleteGroupWarning'] = 'Al borrar este grupo se eliminarán todos los permisos de los recursos asociados. Los usuarios en este grupo pueden perder acceso a los recursos.';
$strings['WhatRolesApplyToThisGroup'] = '¿Qué roles aplican a este grupo?';
$strings['WhoCanManageThisGroup'] = '¿Quién puede gestionar este grupo?';
$strings['AddGroup'] = 'Añadir Grupo';
$strings['AllQuotas'] = 'Todas Las Cuotas';
$strings['QuotaReminder'] = 'Recordar: Las cuotas se fijan basándose en la zona horaria de las planificaciones.';
$strings['AllReservations'] = 'Todas Las Reservas';
$strings['PendingReservations'] = 'Reservas Pendientes';
$strings['Approving'] = 'Aprobando';
$strings['MoveToSchedule'] = 'Mover a planificación';
$strings['DeleteResourceWarning'] = 'Al borrar este recurso se eliminarán todos los datos asociados, incluyendo';
$strings['DeleteResourceWarningReservations'] = 'todos las reservas pasadas, actuales y futuras asociadas';
$strings['DeleteResourceWarningPermissions'] = 'todas las asignaciones de permisos';
$strings['DeleteResourceWarningReassign'] = 'Por favor reasigna todo lo que no quieras que sea borrado antes de continuar';
$strings['ScheduleLayout'] = 'Distribución horaria (todas las veces %s)';
$strings['ReservableTimeSlots'] = 'Intervalos de Tiempo Reservables';
$strings['BlockedTimeSlots'] = 'Intervalos de Tiempo Bloqueados';
$strings['ThisIsTheDefaultSchedule'] = 'Esta es la planificación predeterminada';
$strings['DefaultScheduleCannotBeDeleted'] = 'La planificación predeterminada no se puede eliminar';
$strings['MakeDefault'] = 'Hacer Predeterminada';
$strings['BringDown'] = 'Deshabilitar';
$strings['ChangeLayout'] = 'Cambiar Distribución horaria';
$strings['AddSchedule'] = 'Añadir Planificación';
$strings['StartsOn'] = 'Comienza en';
$strings['NumberOfDaysVisible'] = 'Números de Días Visibles';
$strings['UseSameLayoutAs'] = 'Usar la misma Distribución horaria que';
$strings['Format'] = 'Formato';
$strings['OptionalLabel'] = 'Etiqueta Opcional';
$strings['LayoutInstructions'] = 'Introduce un intervalo de tiempo por línea. Se deben proporcionar intervarlos de tiempo para las 24 horas del día comenzando y terminando a las 12:00 AM.';
$strings['AddUser'] = 'Añadir Usuario';
$strings['UserPermissionInfo'] = 'El acceso real a los recursos puede ser diferente dependiendo de los roles del usuario, permisos de grupo, o ajustes externos de permisos';
$strings['DeleteUserWarning'] = 'Al borrar este usuario se eliminarán todas sus reservas actuales, futuras y pasadas.';
$strings['AddAnnouncement'] = 'Añadir Anuncio';
$strings['Announcement'] = 'Anuncio';
$strings['Priority'] = 'Prioridad';
$strings['Reservable'] = 'Reservable';
$strings['Unreservable'] = 'No Reservable';
$strings['Reserved'] = 'Reservado';
$strings['MyReservation'] = 'Mi Reserva';
$strings['Pending'] = 'Pendiente';
$strings['Past'] = 'Pasado';
$strings['Restricted'] = 'Restringido';
$strings['ViewAll'] = 'View All';
$strings['MoveResourcesAndReservations'] = 'Mover recursos y reservas a';
$strings['WeekOf'] = 'Semana de';
$strings['Of']='de';
// Errors
$strings['LoginError'] = 'No se ha encontrado una correspondencia para tu Nombre de Usuario (Identificador) y contraseña';
$strings['ReservationFailed'] = 'Tu reserva no se ha podido realizar';
$strings['MinNoticeError'] = 'Esta reserva se debe realizar por anticipado. La fecha más temprana que puede ser reservada %s.';
$strings['MaxNoticeError'] = 'Esta reserva no se puede alargar tan lejos en el futuro. La última fecha en la que se puede reservar es %s.';
$strings['MinDurationError'] = 'Esta reserva debe durar al menos %s.';
$strings['MaxDurationError'] = 'Esta reserva no puede durar más de %s.';
$strings['ConflictingAccessoryDates'] = 'No hay suficientes de los siguientes accesorios:';
$strings['NoResourcePermission'] = 'No tienes permisos para acceder uno o más de los recursos requeridos';
$strings['ConflictingReservationDates'] = 'Hay conflictos en las reservas de las siguientes fechas:';
$strings['StartDateBeforeEndDateRule'] = 'La fecha de inicio debe ser anterior a la fecha final';
$strings['StartIsInPast'] = 'La fecha inicial no puede ser pasada';
$strings['EmailDisabled'] = 'El administrador ha desactivado las notificaciones por correo';
$strings['ValidLayoutRequired'] = 'Se deben proporcionar intervalos de tiempo para las 24 horas del día comenzando y terminando a las 12:00 AM.';
$strings['CustomAttributeErrors'] = 'Hay problemas con los atributos adicionales que proporcionaste:';
$strings['CustomAttributeRequired'] = '%s es un campo requerido.';
$strings['CustomAttributeInvalid'] = 'El valor proporcionado para %s no es válido.';
$strings['AttachmentLoadingError'] = 'Lo siento, hubo un problema con el fichero solicitado.';
$strings['InvalidAttachmentExtension'] = 'Solamente puedes subir ficheros de tipo: %s';
$strings['InvalidStartSlot'] = 'La fecha y hora de comienzo solicitada no es válida.';
$strings['InvalidEndSlot'] = 'La fecha y hora de finalización solicitada no es válido.';
$strings['MaxParticipantsError'] = '%s puede soportar %s participantes solamente.';
$strings['ReservationCriticalError'] = 'Hubo un error crítico guardando tu reserva. Si continúa, contacta con el administrador del sistema.';
$strings['InvalidStartReminderTime'] = 'La hora de comienzo del recordatorio no es válida.';
$strings['InvalidEndReminderTime'] = 'La hora de finalización del recordatorio no es válida.';
$strings['QuotaExceeded'] = 'Límite de cuota excedido.';
$strings['MultiDayRule'] = '%s no permite reservar a través de días.';
$strings['InvalidReservationData'] = 'Hubo problemas con tu solicitud de reserva.';
$strings['PasswordError'] = 'La contraseña debe contener al menos %s letras y al menos %s números.';
$strings['PasswordErrorRequirements'] = 'La contraseña debe contener una combinación de al menos %s letras mayúsculas y minusculas y %s números.';
$strings['NoReservationAccess'] = 'No estas permitido para cambiar esta reserva.';
// End Errors
// Page Titles
$strings['CreateReservation'] = 'Crear Reserva';
$strings['EditReservation'] = 'Editar Reserva';
$strings['LogIn'] = 'Iniciar Sesión';
$strings['ManageReservations'] = 'Gestionar Reservas';
$strings['AwaitingActivation'] = 'Esperando Activación';
$strings['PendingApproval'] = 'Pendiente De Aprobación';
$strings['ManageSchedules'] = 'Planificaciones';
$strings['ManageResources'] = 'Recursos';
$strings['ManageAccessories'] = 'Accesorios';
$strings['ManageUsers'] = 'Usuarios';
$strings['ManageGroups'] = 'Grupos';
$strings['ManageQuotas'] = 'Cuotas';
$strings['ManageBlackouts'] = 'Agenda de No Disponibilidad';
$strings['MyDashboard'] = 'Mi Tablón';
$strings['ServerSettings'] = 'Ajustes De Servidor';
$strings['Dashboard'] = 'Tablón';
$strings['Help'] = 'Ayuda';
$strings['Bookings'] = 'Reservas';
$strings['Schedule'] = 'Planificación';
$strings['Reservations'] = 'Reservas';
$strings['Account'] = 'Cuenta';
$strings['EditProfile'] = 'Editar Mi Perfil';
$strings['FindAnOpening'] = 'Encontrar Un Hueco';
$strings['OpenInvitations'] = 'Invitaciones Pendientes';
$strings['MyCalendar'] = 'Mi Calendario';
$strings['ResourceCalendar'] = 'Calendario de Recursos';
$strings['Reservation'] = 'Nueva Reserva';
$strings['Install'] = 'Instalación';
$strings['ChangePassword'] = 'Cambiar Contraseña';
$strings['MyAccount'] = 'Mi Cuenta';
$strings['Profile'] = 'Perfil';
$strings['ApplicationManagement'] = 'Gestión de la Aplicación';
$strings['ForgotPassword'] = 'Contraseña Olvidada';
$strings['NotificationPreferences'] = 'Preferencias de Notificación';
$strings['ManageAnnouncements'] = 'Anuncios';
//
// Day representations
$strings['DaySundaySingle'] = 'D';
$strings['DayMondaySingle'] = 'L';
$strings['DayTuesdaySingle'] = 'M';
$strings['DayWednesdaySingle'] = 'X';
$strings['DayThursdaySingle'] = 'J';
$strings['DayFridaySingle'] = 'V';
$strings['DaySaturdaySingle'] = 'S';
$strings['DaySundayAbbr'] = 'Dom';
$strings['DayMondayAbbr'] = 'Lun';
$strings['DayTuesdayAbbr'] = 'Mar';
$strings['DayWednesdayAbbr'] = 'Mié';
$strings['DayThursdayAbbr'] = 'Jue';
$strings['DayFridayAbbr'] = 'Vie';
$strings['DaySaturdayAbbr'] = 'Sáb';
// Email Subjects
$strings['ReservationApprovedSubject'] = 'Se ha aprobado tu reserva';
$strings['ReservationCreatedSubject'] = 'Se ha creado tu reserva';
$strings['ReservationUpdatedSubject'] = 'Se ha actualizado tu reserva';
$strings['ReservationCreatedAdminSubject'] = 'Notificación: Se ha creado una reserva';
$strings['ReservationUpdatedAdminSubject'] = 'Notificación: Se ha actualizado una reserva';
$strings['ParticipantAddedSubject'] = 'Notificación de participación en reserva';
$strings['InviteeAddedSubject'] = 'Invitación a reserva';
$strings['ResetPassword'] = 'Petición de reinicio de contraseña';
$strings['ForgotPasswordEmailSent'] = 'Se ha enviado un correo a la dirección proporcionada con instrucciones para reiniciar la contraseña';
$strings['ActivationEmailSent'] = 'Recibirás un correo de activación en breve.';
$strings['AccountActivationError'] = 'Lo sentimos, no podemos activar tu cuenta.';
//
// Adapting Booked: missing strings
$strings['Responsibilities'] = 'Administración';
$strings['GroupReservations'] = 'Gestionar Reservas';
$strings['ResourceReservations'] = 'Reservas por recursos';
$strings['Customization'] = 'Personalización';
$strings['ScheduleReservations'] = 'Historial de Reservas';
$strings['Reports'] = 'Informes';
$strings['GenerateReport'] = 'Crear nuevo informe';
$strings['MySavedReports'] = 'Mis informes';
$strings['CommonReports'] = 'Informes comunes';
$strings['BulkResourceUpdate'] = 'Ver toda la configuración del recurso';
$strings['ResourceType'] = 'Tipo de Recurso';
$strings['AppliesTo'] = 'Aplicar a';
$strings['UniquePerInstance'] = 'Único por instancia';
$strings['AddResourceType'] = 'Añadir Tipo de Recurso';
$strings['NoResourceTypeLabel'] = '(no hay tipo de recurso configurado)';
$strings['ClearFilter'] = 'Limpiar Filtro';
$strings['MinimumCapacity'] = 'Capacidad Mínima';
$strings['Color'] = 'Color';
$strings['Available'] = 'Disponible';
$strings['Unavailable'] = 'No disponible';
$strings['Hidden'] = 'Oculto';
$strings['ResourceStatus'] = 'Estado del Recurso';
$strings['CurrentStatus'] = 'Estado actual';
$strings['File'] = 'Fichero';
$strings['Unchanged'] = 'Sin cambios';
$strings['Common'] = 'Común';
$strings['AdvancedFilter'] = 'Filtro Avanzado';
$strings['SortOrder'] = 'Orden';
$strings['TurnOffSubscription'] = 'Desactivar suscripciones en Calendario';
$strings['TurnOnSubscription'] = 'Activar suscripciones en Calendario';
$strings['SubscribeToCalendar'] = 'Subscribirse a este Calendario';
$strings['SubscriptionsAreDisabled'] = 'El administrador ha deshabilitado las suscripciones a este calendario';
$strings['NoResourceAdministratorLabel'] = '(No hay administrador de Recurso)';
$strings['WhoCanManageThisResource'] = '¿Quién puede administrar este Recurso?';
$strings['ResourceAdministrator'] = 'Administrador de Recurso';
$strings['Private'] = 'Privado';
$strings['Accept'] = 'Aceptar';
$strings['Decline'] = 'Rechazar';
$strings['ShowFullWeek'] = 'Mostrar semana completa';
$strings['CustomAttributes'] = 'Personalizar atributos';
$strings['AddAttribute'] = 'Añadir un atributo';
$strings['EditAttribute'] = 'Editar un atributo';
$strings['DisplayLabel'] = 'Etiqueta visible';
$strings['Type'] = 'Tipo';
$strings['Required'] = 'Requerido';
$strings['ValidationExpression'] = 'Expresión de validación';
$strings['PossibleValues'] = 'Posibles valores';
$strings['SingleLineTextbox'] = 'Caja de texto de una sola línea';
$strings['MultiLineTextbox'] = 'Caja de texto de múltiples líneas';
$strings['Checkbox'] = 'Casilla de verificación';
$strings['Title'] = 'Título';
$strings['AdditionalAttributes'] = 'Atributos adicionales';
$strings['True'] = 'Verdadero';
$strings['False'] = 'Falso';
$strings['Attachments'] = 'Adjuntos';
$strings['AttachFile'] = 'Adjuntar fichero';
$strings['Maximum'] = 'máximo';
$strings['NoScheduleAdministratorLabel'] = 'No hay Administrador de calendario';
$strings['ScheduleAdministrator'] = 'Administrador de calendario';
$strings['Total'] = 'Total';
$strings['QuantityReserved'] = 'Cantidad Reservada';
$strings['AllAccessories'] = 'Todos los Accesorios';
$strings['GetReport'] = 'Generar Informe';
$strings['NoResultsFound'] = 'No hemos encontrado coincidencias';
$strings['SaveThisReport'] = 'Guardar este informe';
$strings['ReportSaved'] = '¡Informe guardado!';
$strings['EmailReport'] = 'Enviar informe por correo';
$strings['ReportSent'] = '¡Informe enviado!';
$strings['RunReport'] = 'Generar informe';
$strings['NoSavedReports'] = 'No has guardado el informe.';
$strings['CurrentWeek'] = 'Semana actual';
$strings['CurrentMonth'] = 'Mes actual';
$strings['AllTime'] = 'Todo el tiempo';
$strings['FilterBy'] = 'Filtrar por';
$strings['Select'] = 'Seleccionar';
$strings['List'] = 'Lista';
$strings['TotalTime'] = 'Tiempo Total';
$strings['Count'] = 'Cuenta';
$strings['Usage'] = 'Uso';
$strings['AggregateBy'] = 'Agregar por';
$strings['Range'] = 'Rango';
$strings['Choose'] = 'Elegir';
$strings['All'] = 'Todo';
$strings['ViewAsChart'] = 'Ver como gráfico';
$strings['ReservedResources'] = 'Recurso Reservado';
$strings['ReservedAccessories'] = 'Accesorio Reservado';
$strings['ResourceUsageTimeBooked'] = 'Uso de recurso - Tiempo Reservado';
$strings['ResourceUsageReservationCount'] = 'Uso de recursos - Número de Reservas';
$strings['Top20UsersTimeBooked'] = 'Top 20 - Tiempo reservado';
$strings['Top20UsersReservationCount'] = 'Top 20 - Número de Reservas';
$strings['ConfigurationUpdated'] = 'Se actualizó el fichero de configuración';
$strings['ConfigurationUiNotEnabled'] = 'No se puede acceder a esta página porque $conf[\'settings\'][\'pages\'][\'enable.configuration\'] es configurado a Falso.';
$strings['ConfigurationFileNotWritable'] = 'El fichero de configuración no es editable. Por favor compruebe los permisos de este fichero e inténtelo de nuevo.';
$strings['ConfigurationUpdateHelp'] = 'Vaya a la sección de Configuración del <a target=_blank href=%s>Archivo de ayuda</a> para documentación sobre estas opciones.';
$strings['GeneralConfigSettings'] = 'opciones';
$strings['UseSameLayoutForAllDays'] = 'Usar la misma Distribución horaria para todos los días';
$strings['LayoutVariesByDay'] = 'La Distribución horaria varía por días';
$strings['Administration'] = 'Administración';
$strings['About'] = 'Acerca de';
$strings['Private'] = 'Privado';
$strings['Participant'] = 'Participantes';
$strings['MakeDefaultSchedule'] = 'Hacer esta planificación mi Planificación predeterminada';
$strings['DefaultScheduleSet'] = 'Ahora ésta es tu planificación predeterminada';
$strings['FlipSchedule'] = 'Girar la distribución de la planificación';
$strings['StandardScheduleDisplay'] = 'Use la vista de programación estandar';
$strings['TallScheduleDisplay'] = 'Use la vista de programación alargada';
$strings['WideScheduleDisplay'] = 'Use la vista de programación ancha';
$strings['CondensedWeekScheduleDisplay'] = 'Use la vista de programación de semana condensada';
$strings['ResourceGroupHelp1'] = 'Arrastre los grupos de recursos a organizar.';
$strings['ResourceGroupHelp2'] = 'Haga clic con el botón derecho sobre el nombre de un grupo de recursos para acciones adicionales.';
$strings['ResourceGroupHelp3'] = 'Arrastre los recursos para añadirlos a los grupos.';
$strings['ResourceGroupWarning'] = 'Si usa los grupos de recursos, cada recurso debe estar asignado al menos a un grupo. Los recursos no asignados no estarán disponibles para ser reservados.';
$strings['ManageConfiguration'] = 'Configuración de la aplicación';
$strings['LookAndFeel'] = 'Apariencia';
$strings['ManageResourceGroups'] = 'Grupos de recursos';
$strings['ManageResourceTypes'] = 'Tipos de recursos';
$strings['ManageResourceStatus'] = 'Estados de recursos';
$strings['Group'] = 'Grupo';
$strings['Address'] = 'Dirección';
$strings['Province'] = 'Provincia';
$strings['CIF'] = 'CIF/NIF';
$strings['Date_effective'] = 'Fecha de renovación';
$strings['acceptTerm1'] = 'Acepto los ';
$strings['acceptTerm2'] = 'Términos y condiciones de uso';
$strings['Insurances'] = 'Aseguradoras';
$strings['Specialties'] = 'Especialidades';
$strings['FirstTimeProfesional?'] = '¿Eres un profesional nuevo?';
$strings['LoginError2'] = 'Tu suscripción ha caducado, debes ponerte en contacto con el administrador.';
//Enhance
//Calendario
$strings['Day'] = 'Dia';
$strings['Colors'] = 'Colores';
$strings['TimeTable'] = 'Horarios';
$strings['TimeTableBoundaries'] = 'Seleccione las opciones de visualización';
$strings['Export'] = 'Fichero .ics';
$strings['DeleteReservation'] = '¿Estas seguro de que deseas borrar este elemento?';
$strings['Download'] = 'Descargar';
$strings['Subscribe'] = '¿Exportar datos?';
$strings['Subscription'] = 'Exportar como...';
$strings['checkAll'] = 'Marcar todos';
$strings['uncheckAll'] = 'Desmarcar todos';
$strings['selectOptions'] = 'Selección de recursos';
$strings['selectText'] = 'seleccionados';
$strings['GoDay'] = 'Ir al día';
$strings['Calendar'] = 'Calendario';
$strings['Period'] = 'Período';
$strings['Until'] = 'hasta';
$strings['Pending'] = 'Pendiente de confirmación';
//Informes
$strings['ViewAsList'] = 'Ver como lista';
$strings['Columns'] = 'Columnas';
//Cuotas
$strings['Amount'] = 'Cantidad';
$strings['Unit'] = 'Unidad';
//Recursos
$strings['Roles'] = 'Roles';
$strings['RequiresApproval'] = 'Requiere aprobación';
$strings['WhoApproves'] = '¿Quién aprueba?';
$strings['FieldWarning'] = 'Opciones inválidas';
$strings['Permissions2'] = 'Acceso a recursos';
$strings['Fullname'] = 'Nombre completo';
$strings['Reserved'] = 'Reservado para recurrencia';
$strings['Superuser'] = 'Superusuario';
$strings['AllSelected'] = 'Todos seleccionados';
$strings['NoneSelected'] = 'Ninguno seleccionado';
//Configuracion
$strings['AppTitle'] = 'Título de la aplicación';
$strings['DefaultTimezone'] = 'Zona horaria';
$strings['DefaultPageSize'] = 'Tamaño de página';
$strings['EnableEmail'] = 'Habilitar emails';
$strings['AdminEmail'] = 'Email de la aplicación';
$strings['DefaultLanguage'] = 'Idioma por defecto';
$strings['ScriptUrl'] = 'URL de la aplicación';
$strings['InactivityTimeout'] = 'Temporizador de inactividad';
$strings['NameFormat'] = 'Formato de nombre';
$strings['LogoutUrl'] = 'URL de cierre de sesión';
$strings['Host'] = 'Dirección';
$strings['Port'] = 'Puerto';
$strings['Version'] = 'Versión';
$strings['StartTLS'] = 'Comenzar TLS';
$strings['BindDN'] = 'BindDN';
$strings['BindPW'] = 'Contraseña';
$strings['BaseDN'] = 'BaseDN';
$strings['AttributeMapping'] = 'Mapeo de atributos';
$strings['UserIdAttribute'] = 'Identificador de usuario';
//Roles
$strings['ResAdmin'] = 'Administrador de recurso';
$strings['AppAdmin'] = 'Administrador del sistema';
//Otros
$strings['ViewReservations'] = 'Ver reservas';
$strings['Blackout'] = 'No disponibilidad';
$strings['CheckReservation'] = 'Comprobar reserva';
$strings['Monday'] = 'Lunes';
$strings['Tuesday'] = 'Martes';
$strings['Wednesday'] = 'Miércoles';
$strings['Thursday'] = 'Jueves';
$strings['Friday'] = 'Viernes';
$strings['Saturday'] = 'Sábado';
$strings['Sunday'] = 'Domingo';
$strings['Weekends'] = 'Mostrar fines de semana';
$strings['FirstDay'] = 'Primer día de la semana';
$strings['Format12'] = 'Formato 12 horas';
$strings['Format24'] = 'Formato 24 horas';
$strings['NotAvailable'] = 'No disponible';
$strings['NoActions'] = 'No hay acciones disponibles';
$strings['WorkSchedule'] = 'Horario de Trabajo';
$strings['Configuration'] = 'Configuración';
$strings['PermissionsAll'] = 'Todos pueden reservarlo por defecto';
$strings['PermissionsNone'] = 'Nadie puede reservarlo por defecto';
$strings['Reason'] = 'Razón';
$strings['Stop'] = 'Parar';
$strings['Hide'] = 'Mostrar / Ocultar';
//Ayuda
$strings['Help2'] = 'Guía de usuario';
$strings['Help3'] = 'Guía de administración';
$strings['AboutBookedScheduler'] = 'Acerca de Booked Scheduler';
$strings['Support'] = 'Soporte y colaboración';
$strings['Credits'] = 'Créditos';
$strings['OriginalAuthors'] = 'Autores originales';
$strings['ExtendedBy'] = 'Extendida por';
$strings['ThankYou'] = 'Gracias a los siguientes proyectos';
$strings['License'] = 'Licencia';
$strings['License2'] = 'Booked Scheduler es gratis y de código libre, bajo licencia GNU General Public License. Por favor comprueben el archivo de licencia incluido para más detalles.';
//Instalación
$strings['InstallApplication'] = 'Instalar Booked Scheduler (solo MySQL)';
$strings['IncorrectInstallPassword'] = 'La contraseña no es correcta.';
$strings['SetInstallPassword'] = 'Es necesario establecer una contraseña antes de comenzar la instalación.';
$strings['InstallPasswordInstructions'] = 'En %s por favor establezca %s con una contraseña seguro, después regrese a esta página.<br/>Puede usar %s';
$strings['NoUpgradeNeeded'] = 'El proceso de instalación borrará todos los datos contenidos en la base de datos de Booked Scheduler';
$strings['ProvideInstallPassword'] = 'Introduzca la contraseña de instalación.';
$strings['InstallPasswordLocation'] = 'La puede encontrar en el fichero %s en la directiva %s.';
$strings['VerifyInstallSettings'] = 'Verifique las siguienets opciones antes de continuar, o las puede cambiar en el fichero %s.';
$strings['DatabaseName'] = 'Nombre de la base de datos';
$strings['DatabaseUser'] = 'Usuario de la base de datos';
$strings['DatabaseHost'] = 'Host de la base de datos';
$strings['DatabaseCredentials'] = 'Es necesario otorgar credenciales de la base de datos con permisos de creación de tablas. Sino, contacte a un administrador.';
$strings['MySQLUser'] = 'Usuario MySQL';
$strings['InstallOptionsWarning'] = 'Las siguientes opciones pueden no funcionar en todos los entornos. Si fuera necesario, use el asistente de MySQL para completar estos pasos.';
$strings['CreateDatabase'] = 'Crear la base de datos';
$strings['CreateDatabaseUser'] = 'Crear el usuario de la base de datos';
$strings['PopulateExampleData'] = 'Importar datos de ejemplo. Crea los siguientes usuarios: admin/password y user/password';
$strings['DataWipeWarning'] = 'Atención: Se borrará cualquier información existente';
$strings['RunInstallation'] = 'Comenzar instalación';
$strings['UpgradeNotice'] = 'Está actualizando desde la versión <b>%s</b> hacia la versión <b>%s</b>';
$strings['RunUpgrade'] = 'Comenzar actualización';
$strings['Executing'] = 'Ejecutando';
$strings['StatementFailed'] = 'Fallo. Detalles:';
$strings['SQLStatement'] = 'Sentencia SQL:';
$strings['ErrorCode'] = 'Código de error:';
$strings['ErrorText'] = 'Mensaje de error:';
$strings['InstallationSuccess'] = 'La instalación se completó con éxito.';
$strings['RegisterAdminUser'] = 'Registre su cuenta de administrador. Esto es requerido si no se importaron los datos de ejemplo. Asegurese de que la opción $conf[\'settings\'][\'allow.self.registration\'] = \'true\' está configurada en el fichero %s.';
$strings['LoginWithSampleAccounts'] = 'Si ha importado los datos de ejemplo, puede autenticarse con las credenciales admin/password para el modo administración o user/password para un usuario básico.';
$strings['InstalledVersion'] = 'Actualmente está ejecutando la versión %s de Booked Scheduler';
$strings['InstallUpgradeConfig'] = 'Se recomienza actualizar el fichero de configuración';
$strings['InstallationFailure'] = 'Hubo problemas con la instalación. Por favor corrijalos y ejecute de nuevo.';
$strings['ConfigureApplication'] = 'Configurar Booked Scheduler';
$strings['ConfigUpdateSuccess'] = 'Su archivo de configuración ha sido actualizado.';
$strings['ConfigUpdateFailure'] = 'No se pudo actualizar el fichero de configuración. Por favor sobreescriba el contenido del fichero config.php con lo siguiente:';
$strings['SelectUser'] = 'Seleccione usuario';
// End Install
$this->Strings = $strings;
}
protected function _LoadDays()
{
$days = parent::_LoadDays();
/***
DAY NAMES
All of these arrays MUST start with Sunday as the first element
and go through the seven day week, ending on Saturday
***/
// The full day name
$days['full'] = array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado');
// The three letter abbreviation
$days['abbr'] = array('Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb');
// The two letter abbreviation
$days['two'] = array('Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa');
// The one letter abbreviation
$days['letter'] = array('D', 'L', 'M', 'X', 'J', 'V', 'S');
$this->Days = $days;
}
protected function _LoadMonths()
{
$months = parent::_LoadMonths();
/***
MONTH NAMES
All of these arrays MUST start with January as the first element
and go through the twelve months of the year, ending on December
***/
// The full month name
$months['full'] = array('Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Deciembre');
// The three letter month name
$months['abbr'] = array('Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic');
$this->Months = $months;
}
protected function _LoadLetters()
{
$this->Letters = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'Ñ', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
}
protected function _GetHtmlLangCode()
{
return 'es';
}
}
?> | JoseTfg/booked3 | lang/es.php | PHP | gpl-3.0 | 45,501 |
module ApplicationEnvironment
protected
def get_setting(key)
@setting = Setting.find(:first, :conditions => ["key = ?", key], :limit => 1 )
return @setting.value
end
def path_for_thumbnail(thumbnail_name, username)
path = Rails.root.join(
get_setting('public_pictures_directory'),
get_setting('thumb_path_prefix'),
username
)
FileUtils.mkdir_p(path) if !File.exist?(path)
path + thumbnail_name
end
def path_for_picture(picture_name, username)
path = Rails.root.join(
get_setting('public_pictures_directory'),
username
)
FileUtils.mkdir_p(path) if !File.exist?(path)
path + picture_name
end
def path_to_thumbnail(thumbnail_name)
Rails.root.join(
get_setting('public_pictures_directory'),
get_setting('thumb_path_prefix'),
self.user.login,
thumbnail_name
)
end
def path_to_picture(picture_name)
Rails.root.join(
get_setting('public_pictures_directory'),
self.user.login,
picture_name
)
end
end
| khanku/raillery | lib/application_environment.rb | Ruby | gpl-3.0 | 1,125 |
package madsdf.ardrone.controller.neuralnet;
import com.google.common.eventbus.EventBus;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.ListIterator;
import madsdf.shimmer.gui.AccelGyro;
/**
* Movement model implementing the abstract MovementModel and implementing the
* processFeatures methods with only three features. This movement model
* is a specific implementation for the networks which need only the mean,
* difference and median features.
*
* Java version : JDK 1.6.0_21
* IDE : Netbeans 7.1.1
*
* @author Gregoire Aubert
* @version 1.0
*/
public class MeanDifferenceMedianMovement extends MovementModel {
// Number of line and number of features
private final static int NB_FEATURES = 3;
private final static int NB_LINES = 6;
// Constants for the normalization
private static final float COL_MAX = 4100;
private static final float COL_MIN = 0;
private static final float NORM_MAX = 0.95f;
private static final float NORM_MIN = -0.95f;
public MeanDifferenceMedianMovement(EventBus ebus, int[] windowSize, int[] movementSize){
super(ebus, windowSize, movementSize);
}
/**
* Process all the three feature, normalize them and return them.
* @param iterator the iterator used to process the features
*/
@Override
protected float[] processFeatures(AccelGyro.UncalibratedSample[] window) {
// Verify the feature array
float[] features = new float[NB_FEATURES * NB_LINES];
// Copy all the sample values
LinkedList<Float>[] sampleCopy = new LinkedList[NB_LINES];
for(int i = 0; i < sampleCopy.length; i++)
sampleCopy[i] = new LinkedList<Float>();
// Initialisation of the features array
AccelGyro.UncalibratedSample sample = window[0];
// The maximum values
float[] maxValue = new float[NB_LINES];
// The minimum values
float[] minValue = new float[NB_LINES];
// For each value of the first AccelGyroSample, initialise the features
for(int i = 0; i < NB_LINES; i++){
// Copy the sample
sampleCopy[i].add((float)getVal(sample, i+1));
// Initialize the mean, min and max
features[NB_FEATURES * i] = getVal(sample, i+1);
minValue[i] = getVal(sample, i+1);
maxValue[i] = getVal(sample, i+1);
}
// For each sample
for (int j = 1; j < window.length; ++j) {
sample = window[j];
// For each value of the AccelGyroSample
for(int i = 0; i < NB_LINES; i++){
// Copy
sampleCopy[i].add((float)getVal(sample, i+1));
// Mean
features[NB_FEATURES * i] += getVal(sample, i+1);
// Min
minValue[i] = Math.min(getVal(sample, i+1), minValue[i]);
// Max
maxValue[i] = Math.max(getVal(sample, i+1), maxValue[i]);
}
}
// For each value of the AccelGyroSample, process the remaining features
for(int i = 0; i < NB_LINES; i++){
// Mean
features[NB_FEATURES * i] /= sampleCopy[i].size();
// Difference
features[1+NB_FEATURES * i] = maxValue[i] - minValue[i];
// Median
Float[] med = sampleCopy[i].toArray(new Float[0]);
Arrays.sort(med);
if(med.length % 2 == 0)
features[2+NB_FEATURES * i] = (med[med.length / 2] + med[med.length / 2 + 1]) / 2.f;
else
features[2+NB_FEATURES * i] = med[med.length / 2 + 1];
}
// Normalize the features
for(int i = 0; i < features.length; i++)
features[i] = (NORM_MAX - NORM_MIN) * ((features[i] - COL_MIN) / (COL_MAX - COL_MIN)) + NORM_MIN;
return features;
}
}
| heig-iict-ida/ardrone_gesture | src/madsdf/ardrone/controller/neuralnet/MeanDifferenceMedianMovement.java | Java | gpl-3.0 | 4,036 |
package edu.osu.cse5236.group9.dieta;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class DetailedResultsActivity extends FragmentActivity implements View.OnClickListener{
private static final String ACTIVITYNAME = "DetailedResultsActivity";
private Meal mMeal;
private int currentIndex;
private int mealSize;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(ACTIVITYNAME, "onCreate(Bundle) called");
setContentView(R.layout.activity_detailed_results);
// TODO: get meal from prior class
mMeal=getIntent().getParcelableExtra("mMeal");
mealSize=mMeal.getFoods().size();
if(savedInstanceState!=null) {
currentIndex = savedInstanceState.getInt("curIndex");
} else {
currentIndex=0;
}
ResultsFragment resultsFragment= new ResultsFragment();
if (mealSize > 0) {
resultsFragment.passFood(mMeal.getFoods().get(currentIndex));
}
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.detailedresults_nfacts,resultsFragment);
fragmentTransaction.commit();
View buttonLeft=findViewById(R.id.detailedresults_left);
View buttonRight=findViewById(R.id.detailedresults_right);
View buttonFinish=findViewById(R.id.detailedresults_finish);
mTextView=(TextView) findViewById(R.id.textView_foodname);
buttonLeft.setOnClickListener(this);
buttonRight.setOnClickListener(this);
buttonFinish.setOnClickListener(this);
if (mealSize>0) {
mTextView.setText(mMeal.getFoods().get(currentIndex).getName());
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("curIndex",currentIndex);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.detailedresults_left:
if (currentIndex>0) {
currentIndex--;
if(getSupportFragmentManager().findFragmentById(R.id.detailedresults_nfacts) != null) {
ResultsFragment resultsFragment= new ResultsFragment();
resultsFragment.passFood(mMeal.getFoods().get(currentIndex));
mTextView.setText(mMeal.getFoods().get(currentIndex).getName());
getSupportFragmentManager().beginTransaction().replace(R.id.detailedresults_nfacts,resultsFragment).commit();
}
}
break;
case R.id.detailedresults_right:
if (currentIndex<mealSize-1) {
currentIndex++;
if(getSupportFragmentManager().findFragmentById(R.id.detailedresults_nfacts) != null) {
ResultsFragment resultsFragment= new ResultsFragment();
resultsFragment.passFood(mMeal.getFoods().get(currentIndex));
mTextView.setText(mMeal.getFoods().get(currentIndex).getName());
getSupportFragmentManager().beginTransaction().replace(R.id.detailedresults_nfacts,resultsFragment).commit();
}
}
break;
case R.id.detailedresults_finish:
startActivity(new Intent(this,NewFoodActivity.class));
break;
}
}
@Override
public void onStart() {
super.onStart();
Log.d(ACTIVITYNAME, "onStart() called");
}
@Override
public void onPause() {
super.onPause();
Log.d(ACTIVITYNAME, "onPause() called");
}
@Override
public void onResume() {
super.onResume();
Log.d(ACTIVITYNAME, "onResume() called");
}
@Override
public void onStop() {
super.onStop();
Log.d(ACTIVITYNAME, "onStop() called");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(ACTIVITYNAME, "onDestroy() called");
}
}
| lisiyuan656/dieta | src/Dieta/app/src/main/java/edu/osu/cse5236/group9/dieta/DetailedResultsActivity.java | Java | gpl-3.0 | 4,468 |
class SiteController < ApplicationController
skip_before_filter :authenticate_user!, only: [:index, :weixin, :weixin_mobile]
layout :action_layout
def index
end
def main
@notices=General::Notice.where("date<=? AND e_date>=?", Date.today, Date.today )
end
def presentation
end
def weixin
end
def weixin_mobile
end
private
def action_layout
case action_name
when "index"
"index"
when "weixin"
"index_no_menu"
when "weixin_mobile"
"index_no_menu"
else
"application"
end
end
end
| ImJayQiu/ssics | app/controllers/site_controller.rb | Ruby | gpl-3.0 | 533 |
function glitch_frame(frame)
{
// bail out if we have no motion vectors
let mvs = frame["mv"];
if ( !mvs )
return;
// bail out if we have no forward motion vectors
let fwd_mvs = mvs["forward"];
if ( !fwd_mvs )
return;
// clear horizontal element of all motion vectors
for ( let i = 0; i < fwd_mvs.length; i++ )
{
// loop through all rows
let row = fwd_mvs[i];
for ( let j = 0; j < row.length; j++ )
{
// loop through all macroblocks
let mv = row[j];
// THIS IS WHERE THE MAGIC HAPPENS
mv[0] = 0; // this sets the horizontal motion vector to zero
// mv[1] = 0; // you could also change the vertical motion vector
}
}
}
| JC-Morph/alghemy | lib/alghemy/scripts/mv_sink.js | JavaScript | gpl-3.0 | 805 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cz.webarchiv.webanalyzer.dictionary;
/**
*
* @author praso
*/
class Word implements java.lang.Comparable<Word> {
private String word;
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
@Override
public boolean equals(Object o) {
if (o instanceof Word) {
Word w = (Word) o;
return getWord().equals(w.getWord());
} else {
return false;
}
}
@Override
public int hashCode() {
return this.getWord().hashCode();
}
public int compareTo(Word o) {
return this.word.compareTo(o.getWord());
}
}
| WebArchivCZ/webanalyzer | src/cz/webarchiv/webanalyzer/dictionary/Word.java | Java | gpl-3.0 | 800 |
<?php
namespace OceanApplications\Postmen\Models;
class Model
{
protected $acceptedCountries = ['ABW', 'AFG', 'AGO', 'AIA', 'ALA', 'ALB', 'AND', 'ARE', 'ARG', 'ARM', 'ASM', 'ATA', 'ATF', 'ATG', 'AUS',
'AUT', 'AZE', 'BDI', 'BEL', 'BEN', 'BES', 'BFA', 'BGD', 'BGR', 'BHR', 'BHS', 'BIH', 'BLM', 'BLR', 'BLZ', 'BMU', 'BOL', 'BRA',
'BRB', 'BRN', 'BTN', 'BVT', 'BWA', 'CAF', 'CAN', 'CCK', 'CHE', 'CHL', 'CHN', 'CIV', 'CMR', 'COD', 'COG', 'COK', 'COL', 'COM',
'CPV', 'CRI', 'CUB', 'CUW', 'CXR', 'CYM', 'CYP', 'CZE', 'DEU', 'DJI', 'DMA', 'DNK', 'DOM', 'DZA', 'ECU', 'EGY', 'ERI', 'ESH',
'ESP', 'EST', 'ETH', 'FIN', 'FJI', 'FLK', 'FRA', 'FRO', 'FSM', 'GAB', 'GBR', 'GEO', 'GGY', 'GHA', 'GIB', 'GIN', 'GLP', 'GMB',
'GNB', 'GNQ', 'GRC', 'GRD', 'GRL', 'GTM', 'GUF', 'GUM', 'GUY', 'HKG', 'HMD', 'HND', 'HRV', 'HTI', 'HUN', 'IDN', 'IMN', 'IND',
'IOT', 'IRL', 'IRN', 'IRQ', 'ISL', 'ISR', 'ITA', 'JAM', 'JEY', 'JOR', 'JPN', 'KAZ', 'KEN', 'KGZ', 'KHM', 'KIR', 'KNA', 'KOR',
'KWT', 'LAO', 'LBN', 'LBR', 'LBY', 'LCA', 'LIE', 'LKA', 'LSO', 'LTU', 'LUX', 'LVA', 'MAC', 'MAF', 'MAR', 'MCO', 'MDA', 'MDG',
'MDV', 'MEX', 'MHL', 'MKD', 'MLI', 'MLT', 'MMR', 'MNE', 'MNG', 'MNP', 'MOZ', 'MRT', 'MSR', 'MTQ', 'MUS', 'MWI', 'MYS', 'MYT',
'NAM', 'NCL', 'NER', 'NFK', 'NGA', 'NIC', 'NIU', 'NLD', 'NOR', 'NPL', 'NRU', 'NZL', 'OMN', 'PAK', 'PAN', 'PCN', 'PER', 'PHL',
'PLW', 'PNG', 'POL', 'PRI', 'PRK', 'PRT', 'PRY', 'PSE', 'PYF', 'QAT', 'REU', 'ROU', 'RUS', 'RWA', 'SAU', 'SDN', 'SEN', 'SGP',
'SGS', 'SHN', 'SJM', 'SLB', 'SLE', 'SLV', 'SMR', 'SOM', 'SPM', 'SRB', 'SSD', 'STP', 'SUR', 'SVK', 'SVN', 'SWE', 'SWZ', 'SXM',
'SYC', 'SYR', 'TCA', 'TCD', 'TGO', 'THA', 'TJK', 'TKL', 'TKM', 'TLS', 'TON', 'TTO', 'TUN', 'TUR', 'TUV', 'TWN', 'TZA', 'UGA',
'UKR', 'UMI', 'URY', 'USA', 'UZB', 'VAT', 'VCT', 'VEN', 'VGB', 'VIR', 'VNM', 'VUT', 'WLF', 'WSM', 'YEM', 'ZAF', 'ZMB', 'ZWE', ];
}
| oceanapplications/postmen | src/Models/Model.php | PHP | gpl-3.0 | 1,954 |
<?php
/* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2005-2014 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2005-2010 Regis Houssin <regis.houssin@capnetworks.com>
* Copyright (C) 2010-2013 Juanjo Menent <jmenent@2byte.es>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/admin/prelevement.php
* \ingroup prelevement
* \brief Page configuration des prelevements
*/
require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
$langs->load("admin");
$langs->load("withdrawals");
// Security check
if (!$user->admin) accessforbidden();
$action = GETPOST('action','alpha');
/*
* Actions
*/
if ($action == "set")
{
$db->begin();
for ($i = 0 ; $i < 2 ; $i++)
{
$res = dolibarr_set_const($db, GETPOST("nom$i",'alpha'), GETPOST("value$i",'alpha'),'chaine',0,'',$conf->entity);
if (! $res > 0) $error++;
}
$res = dolibarr_set_const($db, "PRELEVEMENT_ICS", GETPOST("PRELEVEMENT_ICS"),'chaine',0,'',$conf->entity);
if (! $res > 0) $error++;
$id=GETPOST('PRELEVEMENT_ID_BANKACCOUNT','int');
$account = new Account($db);
if($account->fetch($id)>0)
{
$res = dolibarr_set_const($db, "PRELEVEMENT_ID_BANKACCOUNT", $id,'chaine',0,'',$conf->entity);
if (! $res > 0) $error++;
$res = dolibarr_set_const($db, "PRELEVEMENT_CODE_BANQUE", $account->code_banque,'chaine',0,'',$conf->entity);
if (! $res > 0) $error++;
$res = dolibarr_set_const($db, "PRELEVEMENT_CODE_GUICHET", $account->code_guichet,'chaine',0,'',$conf->entity);
if (! $res > 0) $error++;
$res = dolibarr_set_const($db, "PRELEVEMENT_NUMERO_COMPTE", $account->number,'chaine',0,'',$conf->entity);
if (! $res > 0) $error++;
$res = dolibarr_set_const($db, "PRELEVEMENT_NUMBER_KEY", $account->cle_rib,'chaine',0,'',$conf->entity);
if (! $res > 0) $error++;
$res = dolibarr_set_const($db, "PRELEVEMENT_IBAN", $account->iban,'chaine',0,'',$conf->entity);
if (! $res > 0) $error++;
$res = dolibarr_set_const($db, "PRELEVEMENT_BIC", $account->bic,'chaine',0,'',$conf->entity);
if (! $res > 0) $error++;
$res = dolibarr_set_const($db, "PRELEVEMENT_RAISON_SOCIALE", $account->proprio,'chaine',0,'',$conf->entity);
if (! $res > 0) $error++;
}
else $error++;
if (! $error)
{
$db->commit();
setEventMessage($langs->trans("SetupSaved"));
}
else
{
$db->rollback();
setEventMessage($langs->trans("Error"),'errors');
}
}
if ($action == "addnotif")
{
$bon = new BonPrelevement($db);
$bon->AddNotification($db,GETPOST('user','int'),$action);
header("Location: prelevement.php");
exit;
}
if ($action == "deletenotif")
{
$bon = new BonPrelevement($db);
$bon->DeleteNotificationById(GETPOST('notif','int'));
header("Location: prelevement.php");
exit;
}
/*
* View
*/
$form=new Form($db);
llxHeader('',$langs->trans("WithdrawalsSetup"));
$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php">'.$langs->trans("BackToModuleList").'</a>';
print_fiche_titre($langs->trans("WithdrawalsSetup"),$linkback,'setup');
print '<br>';
print '<form method="post" action="prelevement.php?action=set">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre">';
print '<td width="30%">'.$langs->trans("Parameter").'</td>';
print '<td width="40%">'.$langs->trans("Value").'</td>';
print "</tr>";
//User
print '<tr class="impair"><td>'.$langs->trans("ResponsibleUser").'</td>';
print '<td align="left">';
print '<input type="hidden" name="nom0" value="PRELEVEMENT_USER">';
print $form->select_dolusers($conf->global->PRELEVEMENT_USER,'value0',1);
print '</td>';
print '</tr>';
//Profid1 of Transmitter
print '<tr class="pair"><td>'.$langs->trans("NumeroNationalEmetter").' - '.$langs->transcountry('ProfId1',$mysoc->country_code).'</td>';
print '<td align="left">';
print '<input type="hidden" name="nom1" value="PRELEVEMENT_NUMERO_NATIONAL_EMETTEUR">';
print '<input type="text" name="value1" value="'.$conf->global->PRELEVEMENT_NUMERO_NATIONAL_EMETTEUR.'" size="9" ></td>';
print '</tr>';
// Bank account (from Banks module)
print '<tr class="impair"><td>'.$langs->trans("BankToReceiveWithdraw").'</td>';
print '<td align="left">';
$form->select_comptes($conf->global->PRELEVEMENT_ID_BANKACCOUNT,'PRELEVEMENT_ID_BANKACCOUNT',0,"courant=1",1);
print '</td></tr>';
// ICS
print '<tr class="pair"><td>'.$langs->trans("ICS").'</td>';
print '<td align="left">';
print '<input type="text" name="PRELEVEMENT_ICS" value="'.$conf->global->PRELEVEMENT_ICS.'" size="9" ></td>';
print '</td></tr>';
print '</table>';
print '<br>';
print '<div class="center"><input type="submit" class="button" value="'.$langs->trans("Save").'"></div>';
print '</form>';
dol_fiche_end();
print '<br>';
/*
* Notifications
*/
/* Disable this, there is no trigger with elementtype 'withdraw'
if (! empty($conf->global->MAIN_MODULE_NOTIFICATION))
{
$langs->load("mails");
print_titre($langs->trans("Notifications"));
$sql = "SELECT u.rowid, u.lastname, u.firstname, u.fk_societe, u.email";
$sql.= " FROM ".MAIN_DB_PREFIX."user as u";
$sql.= " WHERE entity IN (0,".$conf->entity.")";
$resql=$db->query($sql);
if ($resql)
{
$num = $db->num_rows($resql);
$var = true;
$i = 0;
while ($i < $num)
{
$obj = $db->fetch_object($resql);
$var=!$var;
if (!$obj->fk_societe)
{
$username=dolGetFirstLastname($obj->firstname,$obj->lastname);
$internalusers[$obj->rowid] = $username;
}
$i++;
}
$db->free($resql);
}
// Get list of triggers for module withdraw
$sql = "SELECT rowid, code, label";
$sql.= " FROM ".MAIN_DB_PREFIX."c_action_trigger";
$sql.= " WHERE elementtype = 'withdraw'";
$sql.= " ORDER BY rang ASC";
$resql = $db->query($sql);
if ($resql)
{
$num = $db->num_rows($resql);
$i = 0;
$var = false;
while ($i < $num)
{
$obj = $db->fetch_object($resql);
$label=($langs->trans("Notify_".$obj->code)!="Notify_".$obj->code?$langs->trans("Notify_".$obj->code):$obj->label);
$actions[$obj->rowid]=$label;
$i++;
}
$db->free($resql);
}
print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?action=addnotif">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre">';
print '<td>'.$langs->trans("User").'</td>';
print '<td>'.$langs->trans("Value").'</td>';
print '<td align="right">'.$langs->trans("Action").'</td>';
print "</tr>\n";
print '<tr class="impair"><td align="left">';
print $form->selectarray('user',$internalusers);// select_users(0,'user',0);
print '</td>';
print '<td>';
print $form->selectarray('action',$actions);// select_users(0,'user',0);
print '</td>';
print '<td align="right"><input type="submit" class="button" value="'.$langs->trans("Add").'"></td></tr>';
// List of current notifications for objet_type='withdraw'
$sql = "SELECT u.lastname, u.firstname,";
$sql.= " nd.rowid, ad.code, ad.label";
$sql.= " FROM ".MAIN_DB_PREFIX."user as u,";
$sql.= " ".MAIN_DB_PREFIX."notify_def as nd,";
$sql.= " ".MAIN_DB_PREFIX."c_action_trigger as ad";
$sql.= " WHERE u.rowid = nd.fk_user";
$sql.= " AND nd.fk_action = ad.rowid";
$sql.= " AND u.entity IN (0,".$conf->entity.")";
$resql = $db->query($sql);
if ($resql)
{
$num = $db->num_rows($resql);
$i = 0;
$var = false;
while ($i < $num)
{
$obj = $db->fetch_object($resql);
$var=!$var;
print "<tr ".$bc[$var].">";
print '<td>'.dolGetFirstLastname($obj->firstname,$obj->lastname).'</td>';
$label=($langs->trans("Notify_".$obj->code)!="Notify_".$obj->code?$langs->trans("Notify_".$obj->code):$obj->label);
print '<td>'.$label.'</td>';
print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=deletenotif&notif='.$obj->rowid.'">'.img_delete().'</a></td>';
print '</tr>';
$i++;
}
$db->free($resql);
}
print '</table>';
print '</form>';
}
*/
$db->close();
llxFooter();
| ozit/dolibarr | htdocs/admin/prelevement.php | PHP | gpl-3.0 | 9,338 |
package com.a4server.gameserver.network.packets.clientpackets;
import com.a4server.gameserver.model.GameLock;
import com.a4server.gameserver.model.GameObject;
import com.a4server.gameserver.model.Hand;
import com.a4server.gameserver.model.Player;
import com.a4server.gameserver.model.inventory.AbstractItem;
import com.a4server.gameserver.model.inventory.Inventory;
import com.a4server.gameserver.model.inventory.InventoryItem;
import com.a4server.gameserver.network.packets.serverpackets.InventoryUpdate;
import com.a4server.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.a4server.gameserver.model.GameObject.WAIT_LOCK;
/**
* клик по объекту в инвентаре
* Created by arksu on 26.02.15.
*/
public class InventoryClick extends GameClientPacket
{
private static final Logger _log = LoggerFactory.getLogger(InventoryClick.class.getName());
private int _inventoryId;
private int _objectId;
private int _btn;
private int _mod;
/**
* отступ в пикселах внутри вещи где произошел клик
*/
private int _offsetX;
private int _offsetY;
/**
* слот в который тыкнули
*/
private int _x;
private int _y;
@Override
public void readImpl()
{
_inventoryId = readD();
_objectId = readD();
_btn = readC();
_mod = readC();
_offsetX = readC();
_offsetY = readC();
_x = readC();
_y = readC();
}
@Override
public void run()
{
_log.debug("obj=" + _objectId + " inv=" + _inventoryId + " (" + _x + ", " + _y + ")" + " offset=" + _offsetX + ", " + _offsetY + " mod=" + _mod);
Player player = client.getPlayer();
if (player != null && _btn == 0)
{
try (GameLock ignored = player.lock())
{
// держим в руке что-то?
if (player.getHand() == null)
{
// в руке ничего нет. возьмем из инвентаря
InventoryItem item = null;
if (player.getInventory() != null)
{
item = player.getInventory().findItem(_objectId);
}
// не нашли эту вещь у себя в инвентаре
// попробуем найти в объекте с которым взаимодействуем
if (item == null && player.isInteractive())
{
for (GameObject object : player.getInteractWith())
{
item = object.getInventory() != null ? object.getInventory().findItem(_objectId) : null;
if (item != null)
{
break;
}
}
}
// пробуем взять вещь из инвентаря
if (item != null)
{
GameObject object = item.getParentInventory().getObject();
try (GameLock ignored2 = object.lock())
{
InventoryItem taked = item.getParentInventory().takeItem(item);
// взяли вещь из инвентаря
if (taked != null)
{
object.sendInteractPacket(new InventoryUpdate(item.getParentInventory()));
// какая кнопка была зажата
switch (_mod)
{
case Utils.MOD_ALT:
// сразу перекинем вещь в инвентарь
if (!putItem(player, taked, -1, -1))
{
setHand(player, taked);
}
break;
default:
// ничего не нажато. пихаем в руку
setHand(player, taked);
break;
}
}
}
}
else
{
// возможно какой-то баг или ошибка. привлечем внимание
_log.error("InventoryClick: item=null");
}
}
else
{
// положим в инвентарь то что держим в руке
Hand hand = player.getHand();
if (putItem(player, hand.getItem(), _x - hand.getOffsetX(), _y - hand.getOffsetY()))
{
player.setHand(null);
}
}
}
}
}
/**
* положить вещь в инвентарь
* @param item вещь которую кладем
*/
public boolean putItem(Player player, AbstractItem item, int x, int y)
{
Inventory to = null;
// ищем нужный инвентарь у себя
if (player.getInventory() != null)
{
to = player.getInventory().findInventory(_inventoryId);
}
// а потом в объектах с которыми взаимодействую
if (to == null && player.isInteractive())
{
for (GameObject object : player.getInteractWith())
{
to = object.getInventory() != null ? object.getInventory().findInventory(_inventoryId) : null;
if (to != null)
{
break;
}
}
}
// положим в инвентарь
if (to != null)
{
if (to.getObject().tryLock(WAIT_LOCK))
{
try
{
InventoryItem putItem = to.putItem(item, x, y);
if (putItem != null)
{
to.getObject().sendInteractPacket(new InventoryUpdate(to));
return true;
}
}
finally
{
to.getObject().unlock();
}
}
}
return false;
}
private void setHand(Player player, InventoryItem taked)
{
player.setHand(new Hand(player, taked,
_x - taked.getX(),
_y - taked.getY(),
_offsetX, _offsetY
));
}
}
| arksu/origin | server/src/com/a4server/gameserver/network/packets/clientpackets/InventoryClick.java | Java | gpl-3.0 | 5,303 |
#include "qtreversimenudialog.h"
#include <QKeyEvent>
#include <QApplication>
#include <QDesktopWidget>
#include "reversimenudialog.h"
#include "qtaboutdialog.h"
#include "qtreversimaindialog.h"
#include "reversimenudialog.h"
#include "ui_qtreversimenudialog.h"
ribi::reversi::QtReversiMenuDialog::QtReversiMenuDialog(QWidget *parent) noexcept
: QtHideAndShowDialog(parent),
ui(new Ui::QtReversiMenuDialog)
{
ui->setupUi(this);
}
ribi::reversi::QtReversiMenuDialog::~QtReversiMenuDialog() noexcept
{
delete ui;
}
void ribi::reversi::QtReversiMenuDialog::keyPressEvent(QKeyEvent * e)
{
if (e->key() == Qt::Key_Escape) { close(); }
}
void ribi::reversi::QtReversiMenuDialog::on_button_start_clicked() noexcept
{
QtReversiMainDialog d;
this->ShowChild(&d);
}
void ribi::reversi::QtReversiMenuDialog::on_button_about_clicked() noexcept
{
QtAboutDialog d(MenuDialog().GetAbout());
d.setWindowIcon(windowIcon());
d.setStyleSheet(styleSheet());
ShowChild(&d);
}
void ribi::reversi::QtReversiMenuDialog::on_button_quit_clicked() noexcept
{
close();
}
| richelbilderbeek/Reversi | qtreversimenudialog.cpp | C++ | gpl-3.0 | 1,084 |
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Auxiliary
include Msf::Exploit::Remote::Tcp
include Msf::Auxiliary::Dos
def initialize(info = {})
super(update_info(info,
'Name' => 'Node.js HTTP Pipelining Denial of Service',
'Description' => %q{
This module exploits a Denial of Service (DoS) condition in the HTTP parser of Node.js versions
released before 0.10.21 and 0.8.26. The attack sends many pipelined
HTTP requests on a single connection, which causes unbounded memory
allocation when the client does not read the responses.
},
'Author' =>
[
'Marek Majkowski', # Vulnerability discovery
'titanous', # Metasploit module
'joev' # Metasploit module
],
'License' => MSF_LICENSE,
'References' =>
[
[ 'CVE', '2013-4450' ],
[ 'OSVDB', '98724' ],
[ 'BID' , '63229' ],
[ 'URL', 'http://blog.nodejs.org/2013/10/22/cve-2013-4450-http-server-pipeline-flood-dos' ]
],
'DisclosureDate' => 'Oct 18 2013'))
register_options(
[
Opt::RPORT(80),
OptInt.new('RLIMIT', [true, "Number of requests to send", 100000])
],
self.class)
end
def check
# http://blog.nodejs.org/2013/08/21/node-v0-10-17-stable/
# check if we are < 0.10.17 by seeing if a malformed HTTP request is accepted
status = Exploit::CheckCode::Safe
connect
sock.put(http_request("GEM"))
begin
response = sock.get_once
status = Exploit::CheckCode::Appears if response =~ /HTTP/
rescue EOFError
# checking against >= 0.10.17 raises EOFError because there is no
# response to GEM requests
vprint_error("Failed to determine the vulnerable state due to an EOFError (no response)")
return Msf::Exploit::CheckCode::Unknown
ensure
disconnect
end
status
end
def host
host = datastore['RHOST']
host += ":" + datastore['RPORT'].to_s if datastore['RPORT'] != 80
host
end
def http_request(method='GET')
"#{method} / HTTP/1.1\r\nHost: #{host}\r\n\r\n"
end
def run
payload = http_request
begin
print_status("Stressing the target memory...")
connect
datastore['RLIMIT'].times { sock.put(payload) }
print_status("Attack finished. If you read it, it wasn't enough to trigger an Out Of Memory condition.")
rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout
print_status("Unable to connect to #{host}.")
rescue ::Errno::ECONNRESET, ::Errno::EPIPE, ::Timeout::Error
print_good("DoS successful. #{host} not responding. Out Of Memory condition probably reached")
ensure
disconnect
end
end
end
| cSploit/android.MSF | modules/auxiliary/dos/http/nodejs_pipelining.rb | Ruby | gpl-3.0 | 2,959 |
/**
*
* Copyright (c) 2013-2014, Openflexo
* Copyright (c) 2011-2012, AgileBirds
*
* This file is part of Gina-core, a component of the software infrastructure
* developed at Openflexo.
*
*
* Openflexo is dual-licensed under the European Union Public License (EUPL, either
* version 1.1 of the License, or any later version ), which is available at
* https://joinup.ec.europa.eu/software/page/eupl/licence-eupl
* and the GNU General Public License (GPL, either version 3 of the License, or any
* later version), which is available at http://www.gnu.org/licenses/gpl.html .
*
* You can redistribute it and/or modify under the terms of either of these licenses
*
* If you choose to redistribute it and/or modify under the terms of the GNU GPL, you
* must include the following additional permission.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with software containing parts covered by the terms
* of EPL 1.0, the licensors of this Program grant you additional permission
* to convey the resulting work. *
*
* This software is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE.
*
* See http://www.openflexo.org/license.html for details.
*
*
* Please contact Openflexo (openflexo-contacts@openflexo.org)
* or visit www.openflexo.org if you need additional information.
*
*/
package org.openflexo.gina.model.widget;
import java.util.logging.Logger;
import org.openflexo.connie.BindingModel;
import org.openflexo.connie.DataBinding;
import org.openflexo.gina.model.FIBComponent.LocalizationEntryRetriever;
import org.openflexo.gina.model.FIBModelObject;
import org.openflexo.pamela.annotations.CloningStrategy;
import org.openflexo.pamela.annotations.CloningStrategy.StrategyType;
import org.openflexo.pamela.annotations.DefineValidationRule;
import org.openflexo.pamela.annotations.DeserializationFinalizer;
import org.openflexo.pamela.annotations.Getter;
import org.openflexo.pamela.annotations.ImplementationClass;
import org.openflexo.pamela.annotations.Import;
import org.openflexo.pamela.annotations.Imports;
import org.openflexo.pamela.annotations.ModelEntity;
import org.openflexo.pamela.annotations.PropertyIdentifier;
import org.openflexo.pamela.annotations.Setter;
import org.openflexo.pamela.annotations.XMLAttribute;
import org.openflexo.pamela.annotations.XMLElement;
@ModelEntity(isAbstract = true)
@ImplementationClass(FIBTableAction.FIBTableActionImpl.class)
@Imports({ @Import(FIBTableAction.FIBAddAction.class), @Import(FIBTableAction.FIBRemoveAction.class),
@Import(FIBTableAction.FIBCustomAction.class) })
public abstract interface FIBTableAction extends FIBModelObject {
public static enum ActionType {
Add, Delete, Custom
}
@PropertyIdentifier(type = FIBTable.class)
public static final String OWNER_KEY = "owner";
@PropertyIdentifier(type = DataBinding.class)
public static final String METHOD_KEY = "method";
@PropertyIdentifier(type = DataBinding.class)
public static final String IS_AVAILABLE_KEY = "isAvailable";
@PropertyIdentifier(type = Boolean.class)
public static final String ALLOWS_BATCH_EXECUTION_KEY = "allowsBatchExecution";
@Getter(value = OWNER_KEY /*, inverse = FIBTable.ACTIONS_KEY*/)
@CloningStrategy(StrategyType.IGNORE)
public FIBTable getOwner();
@Setter(OWNER_KEY)
public void setOwner(FIBTable table);
@Getter(value = METHOD_KEY)
@XMLAttribute
public DataBinding<Object> getMethod();
@Setter(METHOD_KEY)
public void setMethod(DataBinding<Object> method);
@Getter(value = IS_AVAILABLE_KEY)
@XMLAttribute
public DataBinding<Boolean> getIsAvailable();
@Setter(IS_AVAILABLE_KEY)
public void setIsAvailable(DataBinding<Boolean> isAvailable);
public abstract ActionType getActionType();
@DeserializationFinalizer
public void finalizeDeserialization();
public void searchLocalized(LocalizationEntryRetriever retriever);
@Getter(value = ALLOWS_BATCH_EXECUTION_KEY, defaultValue = "true")
@XMLAttribute
public boolean getAllowsBatchExecution();
@Setter(ALLOWS_BATCH_EXECUTION_KEY)
public void setAllowsBatchExecution(boolean allowsBatchExecution);
public static abstract class FIBTableActionImpl extends FIBModelObjectImpl implements FIBTableAction {
private static final Logger logger = Logger.getLogger(FIBTableAction.class.getPackage().getName());
private DataBinding<Object> method;
private DataBinding<Boolean> isAvailable;
@Override
public FIBTable getComponent() {
return getOwner();
}
@Override
public void setOwner(FIBTable ownerTable) {
// BindingModel oldBindingModel = getBindingModel();
performSuperSetter(OWNER_KEY, ownerTable);
}
@Override
public DataBinding<Object> getMethod() {
if (method == null) {
method = new DataBinding<>(this, Object.class, DataBinding.BindingDefinitionType.EXECUTE);
method.setBindingName("method");
}
return method;
}
@Override
public void setMethod(DataBinding<Object> method) {
if (method != null) {
method.setOwner(this);
method.setDeclaredType(Object.class);
method.setBindingDefinitionType(DataBinding.BindingDefinitionType.EXECUTE);
method.setBindingName("method");
}
this.method = method;
}
@Override
public DataBinding<Boolean> getIsAvailable() {
if (isAvailable == null) {
isAvailable = new DataBinding<>(this, Boolean.class, DataBinding.BindingDefinitionType.GET);
isAvailable.setBindingName("isAvailable");
}
return isAvailable;
}
@Override
public void setIsAvailable(DataBinding<Boolean> isAvailable) {
if (isAvailable != null) {
isAvailable.setOwner(this);
isAvailable.setDeclaredType(Boolean.class);
isAvailable.setBindingDefinitionType(DataBinding.BindingDefinitionType.GET);
isAvailable.setBindingName("isAvailable");
}
this.isAvailable = isAvailable;
}
@Override
public BindingModel getBindingModel() {
if (getOwner() != null) {
return getOwner().getActionBindingModel();
}
return null;
}
@Override
public void finalizeDeserialization() {
logger.fine("finalizeDeserialization() for FIBTableAction " + getName());
if (method != null) {
method.decode();
}
}
@Override
public abstract ActionType getActionType();
@Override
public void searchLocalized(LocalizationEntryRetriever retriever) {
retriever.foundLocalized(getName());
}
@Override
public String getPresentationName() {
return getName();
}
}
@ModelEntity
@ImplementationClass(FIBAddAction.FIBAddActionImpl.class)
@XMLElement(xmlTag = "AddAction")
public static interface FIBAddAction extends FIBTableAction {
public static abstract class FIBAddActionImpl extends FIBTableActionImpl implements FIBAddAction {
@Override
public ActionType getActionType() {
return ActionType.Add;
}
}
}
@ModelEntity
@ImplementationClass(FIBRemoveAction.FIBRemoveActionImpl.class)
@XMLElement(xmlTag = "RemoveAction")
public static interface FIBRemoveAction extends FIBTableAction {
public static abstract class FIBRemoveActionImpl extends FIBTableActionImpl implements FIBRemoveAction {
@Override
public ActionType getActionType() {
return ActionType.Delete;
}
}
}
@ModelEntity
@ImplementationClass(FIBCustomAction.FIBCustomActionImpl.class)
@XMLElement(xmlTag = "CustomAction")
public static interface FIBCustomAction extends FIBTableAction {
@PropertyIdentifier(type = boolean.class)
public static final String IS_STATIC_KEY = "isStatic";
@Getter(value = IS_STATIC_KEY, defaultValue = "false")
@XMLAttribute
public boolean isStatic();
@Setter(IS_STATIC_KEY)
public void setStatic(boolean isStatic);
public static abstract class FIBCustomActionImpl extends FIBTableActionImpl implements FIBCustomAction {
@Override
public ActionType getActionType() {
return ActionType.Custom;
}
}
}
@DefineValidationRule
public static class MethodBindingMustBeValid extends BindingMustBeValid<FIBTableAction> {
public MethodBindingMustBeValid() {
super("'method'_binding_is_not_valid", FIBTableAction.class);
}
@Override
public DataBinding<?> getBinding(FIBTableAction object) {
return object.getMethod();
}
}
@DefineValidationRule
public static class IsAvailableBindingMustBeValid extends BindingMustBeValid<FIBTableAction> {
public IsAvailableBindingMustBeValid() {
super("'is_available'_binding_is_not_valid", FIBTableAction.class);
}
@Override
public DataBinding<?> getBinding(FIBTableAction object) {
return object.getIsAvailable();
}
}
}
| openflexo-team/gina | gina-api/src/main/java/org/openflexo/gina/model/widget/FIBTableAction.java | Java | gpl-3.0 | 8,774 |
<?php
/***************************************************************************\
* SPIP, Systeme de publication pour l'internet *
* *
* Copyright (c) 2001-2019 *
* Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James *
* *
* Ce programme est un logiciel libre distribue sous licence GNU/GPL. *
* Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. *
\***************************************************************************/
/**
* Gestion d'affichage de la page de réparation de la base de données
*
* ## REMARQUE IMPORTANTE : SÉCURITÉ
*
* Ce systeme de réparation doit pouvoir fonctionner même si
* la table spip_auteurs est en panne : index.php n'appelle donc pas
* inc_auth ; seule l'authentification FTP est exigée.
*
* @package SPIP\Core\Exec
*/
if (!defined('_ECRIRE_INC_VERSION')) {
return;
}
/**
* Réparer la base de données
*/
function exec_base_repair_dist() {
$ok = false;
if (!spip_connect()) {
$message = _T('titre_probleme_technique');
} else {
$version_sql = sql_version();
if (!$version_sql) {
$message = _T('avis_erreur_connexion_mysql');
} else {
$message = _T('texte_requetes_echouent');
$ok = true;
}
$action = _T('texte_tenter_reparation');
}
if ($ok) {
$admin = charger_fonction('admin', 'inc');
echo $admin('repair', $action, $message, true);
} else {
include_spip('inc/minipres');
echo minipres(_T('titre_reparation'), "<p>$message</p>");
}
}
| JLuc/SPIP | ecrire/exec/base_repair.php | PHP | gpl-3.0 | 1,706 |
<?php
class ModelOpenbayAmazonPatch extends Model {
public function runPatch($manual = true) {
$this->load->model('setting/setting');
$settings = $this->model_setting_setting->getSetting('openbay_amazon');
if ($settings) {
$this->db->query("
CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "amazon_product_search` (
`product_id` int(11) NOT NULL,
`marketplace` enum('uk','de','es','it','fr') NOT NULL,
`status` enum('searching','finished') NOT NULL,
`matches` int(11) DEFAULT NULL,
`data` text,
PRIMARY KEY (`product_id`,`marketplace`)
) DEFAULT COLLATE=utf8_general_ci;"
);
$this->db->query("
CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "amazon_listing_report` (
`marketplace` enum('uk','de','fr','es','it') NOT NULL,
`sku` varchar(255) NOT NULL,
`quantity` int(10) unsigned NOT NULL,
`asin` varchar(255) NOT NULL,
`price` decimal(10,4) NOT NULL,
PRIMARY KEY (`marketplace`,`sku`)
) DEFAULT COLLATE=utf8_general_ci;"
);
if (!$this->config->get('openbay_amazon_processing_listing_reports')) {
$settings['openbay_amazon_processing_listing_reports'] = array();
}
$this->model_setting_setting->editSetting('openbay_amazon', $settings);
}
return true;
}
}
| villagedefrance/OpenCart-Overclocked | upload/admin/model/openbay/amazon_patch.php | PHP | gpl-3.0 | 1,268 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2012 Tuukka Turto
#
# This file is part of satin-python.
#
# pyherc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyherc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with satin-python. If not, see <http://www.gnu.org/licenses/>.
"""
Module for testing labels
"""
from hamcrest.core.base_matcher import BaseMatcher
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
from .enumerators import all_widgets
class LabelMatcher(BaseMatcher):
"""
Check if Widget has label with given text
"""
def __init__(self, text):
"""
Default constructor
"""
super(LabelMatcher, self).__init__()
if hasattr(text, 'matches'):
self.text = text
else:
self.text = wrap_matcher(text)
def _matches(self, item):
"""
Check if matcher matches item
:param item: object to match against
:returns: True if matching, otherwise False
:rtype: Boolean
"""
widgets = all_widgets(item)
for widget in widgets:
if hasattr(widget, 'text') and self.text.matches(widget.text()):
return True
return False
def describe_to(self, description):
"""
Describe this matcher
"""
description.append('Control with label {0}'.format(self.text))
def describe_mismatch(self, item, mismatch_description):
"""
Describe this mismatch
"""
mismatch_description.append(
'QLabel with text {0} was not found'.format(self.text))
def has_label(text):
"""
Check if Widget has label with given text
"""
return LabelMatcher(text)
| tuturto/satin-python | satin/label.py | Python | gpl-3.0 | 2,211 |
'use strict';
const {Application} = require('backbone.marionette');
const Geppetto = require('backbone.geppetto');
const debug = require( 'debug' )( 'dpac:app', '[Context]' );
const eventLog = require( 'debug' )( 'dpac:core.events', '\u2709' );
const app = module.exports = new Application();
const AppContext = Geppetto.Context.extend( {
initialize: function( config ){
debug( "#initialize" );
Geppetto.setDebug( true );
this.vent.on( 'all', function( eventName,
event ){
eventLog( eventName );
} );
this.wireValue( 'appContext', this );
this.wireValue( 'app', app );
this.wireCommand( "app:startup:requested", require( './controllers/BootstrapModule' ) );
}
} );
app.on( 'start', function(){
debug( 'App#start' );
const app = this;
app.context = new AppContext();
app.context.dispatch( 'app:startup:requested' );
} );
| d-pac/d-pac.client | src/scripts/core/App.js | JavaScript | gpl-3.0 | 957 |
package eiko.collections;
public class CircularQueue<E extends Comparable<? super E>>
extends AbstractCircularArray<E> {
@SuppressWarnings("unchecked")
public CircularQueue() {
elements = (E[]) new Comparable[START_SIZE];
size = 0;
start = 0;
stop = 0;
}
public void enqueue(E element) {
check_size(size+1);
elements[stop] = element;
stop = (stop+1) % elements.length;
size++;
}
public E dequeue() {
E element = elements[start];
elements[start] = null;
start = (start+1) % elements.length;
size--;
return element;
}
}
| thelasteiko/practice | algorithms/src/eiko/collections/CircularQueue.java | Java | gpl-3.0 | 587 |
/***
* Copyright 2013, 2014 Moises J. Bonilla Caraballo (Neodivert)
*
* This file is part of COMO.
*
* COMO is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License v3 as published by
* the Free Software Foundation.
*
* COMO is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with COMO. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef LIGHT_DATA_HPP
#define LIGHT_DATA_HPP
#include <glm/vec3.hpp>
namespace como {
const glm::vec3 DEFAULT_LIGHT_COLOR( 1.0f );
const float DEFAULT_LIGHT_AMBIENT_COEFFICIENT = 0.3f;
struct LightData {
glm::vec3 color;
float ambientCoefficient;
/***
* 1. Construction
***/
LightData() :
color( DEFAULT_LIGHT_COLOR ),
ambientCoefficient( DEFAULT_LIGHT_AMBIENT_COEFFICIENT ){}
};
} // namespace como
#endif // LIGHT_DATA_HPP
| moisesjbc/como | src/common/3d/light_data.hpp | C++ | gpl-3.0 | 1,137 |
<?php
/*
* Copyright (c) 2011-2021 Lp Digital
*
* This file is part of BackBee Standalone.
*
* BackBee is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with BackBee Standalone. If not, see <https://www.gnu.org/licenses/>.
*/
namespace BackBee\Rest\Controller\Annotations;
/**
* Pagination properties annotation.
*
* @Annotation
*
* @category BackBee
*
* @copyright Lp digital system
* @author k.golovin
*/
class Pagination
{
/**
* @var integer
*/
public $default_start = 0;
/**
* @var integer
*/
public $default_count = 100;
/**
* @var integer
*/
public $max_count = 1000;
/**
* @var integer
*/
public $min_count = 1;
}
| backbee/backbee-php | Rest/Controller/Annotations/Pagination.php | PHP | gpl-3.0 | 1,222 |
jQuery(document).ready(function(jQuery){
jQuery('.smile-upload-media').click(function(e) {
_wpPluploadSettings['defaults']['multipart_params']['admin_page']= 'customizer';
var button = jQuery(this);
var id = 'smile_'+button.attr('id');
var uid = button.data('uid');
var rmv_btn = 'remove_'+button.attr('id');
var img_container = button.attr('id')+'_container';
//Extend wp.media object
var uploader = wp.media.frames.file_frame = wp.media({
title: 'Select or Upload Image',
button: {
text: 'Choose Image'
},
library: {
type: 'image'
},
multiple: false,
});
uploader.on('select', function(props, attachment){
attachment = uploader.state().get('selection').first().toJSON();
var data = attachment.id+"|"+attachment.url;
var sz = jQuery(".cp-media-"+uid).val();
var alt = attachment.alt;//console.log(id);
var val = attachment.id+"|"+sz+"|"+alt;
var a = jQuery("#"+id);
var name = jQuery("#"+id).attr('name');
a.val(val);
a.attr('value',val);
jQuery(".cp-media-"+uid).attr('data-id',attachment.id);
jQuery(".cp-media-"+uid).attr('data-alt',attachment.alt);
jQuery(".cp-media-"+uid).parents(".cp-media-sizes").removeClass("hide-for-default");
jQuery("."+img_container).html('<img src="'+attachment.url+'"/>');
jQuery("#"+rmv_btn).show();
button.text('Change Image');
// Partial Refresh
// - Apply background, background-color, color etc.
var css_preview = a.attr('data-css-preview') || '';
var selector = a.attr('data-css-selector') || '';
var property = a.attr('data-css-property') || '';
var unit = a.attr('data-unit') || 'px';
var url = attachment.url;
partial_refresh_image( css_preview, selector, property, unit, url );
jQuery(document).trigger('cp-image-change', [name,url, val] );
jQuery("#"+id).trigger('change');
});
uploader.open(button);
return false;
});
jQuery('.smile-remove-media').on('click', function(e){
e.preventDefault();
var button = jQuery(this);
var id = button.attr('id').replace("remove_","smile_");
var upload = button.attr('id').replace("remove_","");
var img_container = button.attr('id').replace("remove_","")+'_container';
jQuery("#"+id).attr('value','');
// Partial Refresh
// - Apply background, background-color, color etc.
var a = jQuery("#"+id);
var css_preview = a.attr('data-css-preview') || '';
var selector = a.attr('data-css-selector') || '';
var property = a.attr('data-css-property') || '';
var unit = a.attr('data-unit') || 'px';
var value = ''; // Empty the background image
var name = jQuery("#"+id).attr('name');
partial_refresh_image( css_preview, selector, property, unit, value );
var html = '<p class="description">No Image Selected</p>';
jQuery("."+img_container).html(html);
button.hide();
jQuery("#"+upload).text('Select Image');
jQuery(document).trigger('cp-image-remove', [name,value] );
jQuery("#"+id).trigger('change');
});
jQuery('.smile-default-media').on('click', function(e){
e.preventDefault();
var button = jQuery(this);
var id = button.attr('id').replace("default_","smile_");
var upload = button.attr('id').replace("default_","");
var img_container = button.attr('id').replace("default_","")+'_container';
var container = jQuery(this).parents('.content');
var default_img = jQuery(this).data('default');
jQuery("#"+id).attr('value',default_img);
// Partial Refresh
// - Apply background, background-color, color etc.
var a = jQuery("#"+id);
var css_preview = a.attr('data-css-preview') || '';
var selector = a.attr('data-css-selector') || '';
var property = a.attr('data-css-property') || '';
var unit = a.attr('data-unit') || 'px';
var value = default_img; // Empty the background image
var name = jQuery("#"+id).attr('name');
partial_refresh_image( css_preview, selector, property, unit, value );
var html = '<p class="description">No Image Selected</p>';
jQuery("."+img_container).html('<img src="'+default_img+'"/>');
jQuery(document).trigger('cp-image-default', [name,value] );
jQuery("#"+id).trigger('change');
container.find(".cp-media-sizes").hide().addClass('hide-for-default');
});
jQuery(".cp-media-size").on("change", function(e){
var img_id = jQuery(this).attr('data-id');
var alt = jQuery(this).attr('data-alt');
var input = 'smile_'+jQuery(this).parents('.cp-media-sizes').data('name');
var val = "";
if( img_id !== '' ) {
val = img_id+"|"+jQuery(this).val();
}
if( alt !== '' ) {
val = val+"|"+alt;
}
jQuery("#"+input).val(val);
jQuery("#"+input).attr('value',val);
});
function partial_refresh_image( css_preview, selector, property, unit, value ) {
// apply css by - inline
if( css_preview != 1 || null == css_preview || 'undefined' == css_preview ) {
var frame = jQuery("#smile_design_iframe").contents();
switch( property ) {
case 'src': frame.find( selector ).attr( 'src' , value );
break;
default:
frame.find( selector ).css( property , 'url(' + value + ')' );
break;
}
}
// apply css by - after css generation
jQuery(document).trigger('updated', [css_preview, selector, property, value, unit]);
}
});
| emergugue/emergugue_wp_theme | wp-content/plugins/convertplug/framework/lib/fields/media/media.js | JavaScript | gpl-3.0 | 5,553 |
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
from base.models import ModelloSemplice
from base.tratti import ConMarcaTemporale
class Giudizio(ModelloSemplice, ConMarcaTemporale):
"""
Rappresenta un giudizio sociale ad un oggetto generico.
Utilizzare tramite il tratto ConGiudizio ed i suoi metodi.
"""
class Meta:
verbose_name_plural = "Giudizi"
permissions = (
("view_giudizio", "Can view giudizio"),
)
autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="giudizi", on_delete=models.CASCADE)
positivo = models.BooleanField("Positivo", db_index=True, default=True)
oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True)
oggetto_id = models.PositiveIntegerField(db_index=True)
oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id')
class Commento(ModelloSemplice, ConMarcaTemporale):
"""
Rappresenta un commento sociale ad un oggetto generico.
Utilizzare tramite il tratto ConCommento ed i suoi metodi.
"""
class Meta:
verbose_name_plural = "Commenti"
app_label = "social"
abstract = False
permissions = (
("view_commento", "Can view commento"),
)
autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE)
commento = models.TextField("Testo del commento")
oggetto_tipo = models.ForeignKey(ContentType, db_index=True, on_delete=models.SET_NULL, null=True)
oggetto_id = models.PositiveIntegerField(db_index=True)
oggetto = GenericForeignKey('oggetto_tipo', 'oggetto_id')
LUNGHEZZA_MASSIMA = 1024
class ConGiudizio():
"""
Aggiunge le funzionalita' di giudizio, stile social,
positivi o negativi.
"""
class Meta:
abstract = True
giudizi = GenericRelation(
Giudizio,
related_query_name='giudizi',
content_type_field='oggetto_tipo',
object_id_field='oggetto_id'
)
def giudizio_positivo(self, autore):
"""
Registra un giudizio positivo
:param autore: Autore del giudizio
"""
self._giudizio(autore, True)
def giudizio_negativo(self, autore):
"""
Registra un giudizio negativo
:param autore: Autore del giudizio
"""
self._giudizio(autore, False)
def _giudizio(self, autore, positivo):
"""
Registra un giudizio
:param autore: Autore del giudizio
:param positivo: Vero se positivo, falso se negativo
"""
g = self.giudizio_cerca(autore)
if g: # Se gia' esiste un giudizio, modifico il tipo
g.positivo = positivo
else: # Altrimenti, ne registro uno nuovo
g = Giudizio(
oggetto=self,
positivo=positivo,
autore=autore
)
g.save()
@property
def giudizi_positivi(self):
"""
Restituisce il numero di giudizi positivi associati all'oggetto.
"""
return self._giudizi(self, True)
@property
def giudizi_negativi(self):
"""
Restituisce il numero di giudizi negativi associati all'oggetto.
"""
return self._giudizi(self, False)
def _giudizi(self, positivo):
"""
Restituisce il numero di giudizi positivi o negativi associati all'oggetto.
"""
return self.giudizi.filter(positivo=positivo).count()
def giudizio_cerca(self, autore):
"""
Cerca il giudizio di un autore sull'oggetto. Se non presente,
ritorna None.
"""
g = self.giudizi.filter(autore=autore)[:1]
if g:
return g
return None
class ConCommenti(models.Model):
"""
Aggiunge la possibilita' di aggiungere commenti ad
un oggetto.
"""
class Meta:
abstract = True
commenti = GenericRelation(
Commento,
related_query_name='%(class)s',
content_type_field='oggetto_tipo',
object_id_field='oggetto_id'
)
def commento_notifica_destinatari(self, mittente):
"""
SOVRASCRIVIMI!
Ritorna il queryset di persone che devono ricevere
una notifica ogni volta che un commento viene aggiunto
da un dato mittente.
"""
from anagrafica.models import Persona
return Persona.objects.none()
| CroceRossaItaliana/jorvik | social/models.py | Python | gpl-3.0 | 4,591 |
import {Component, Input, OnInit, ViewChild} from '@angular/core';
import {Messages} from "../../models/message";
import {Threadz} from "../../models/threadz";
import {HttpClient} from "@angular/common/http";
import {MatRipple} from "@angular/material";
import {FormBuilder, FormGroup} from "@angular/forms";
@Component({
selector: 'app-content',
templateUrl: './content.component.html',
styleUrls: ['./content.component.css']
})
export class ContentComponent implements OnInit {
@Input() selectedThread: Threadz;
@Input() messageList: Messages[];
@ViewChild(MatRipple) ripple: MatRipple;
form: FormGroup;
constructor(private http: HttpClient, private fb: FormBuilder) {
}
ngOnInit() {
this.form = this.fb.group({
msg: '',
});
}
sendMessage(b) {
console.log(this.form.get('msg').value);
}
}
| whiteshadoww/smsWpc | src/app/components/content/content.component.ts | TypeScript | gpl-3.0 | 897 |
<?php
namespace App\Repositories\Implementation\Cms;
use App\Repositories\Contracts\Cms\Industry as IndustryInterface;
use App\Repositories\Implementation\BaseImplementation;
use App\Models\Industri as IndustryModels;
use App\Models\IndustriTrans as IndustryTransModels;
use App\Services\Transformation\Cms\Industry as IndustryTransformation;
use App\Custom\DataHelper;
use LaravelLocalization;
use Carbon\Carbon;
use Cache;
use Auth;
use Session;
use DB;
class Industry extends BaseImplementation implements IndustryInterface
{
protected $industry;
protected $industryTrans;
protected $industryTransformation;
protected $message;
protected $lastInsertId;
protected $uniqueIdImagePrefix = '';
const PREFIX_IMAGE_NAME = 'industry__lintas__ebtke';
function __construct(IndustryModels $industry, IndustryTransModels $industryTrans, IndustryTransformation $industryTransformation)
{
$this->industry = $industry;
$this->industryTrans = $industryTrans;
$this->industryTransformation = $industryTransformation;
$this->uniqueIdImagePrefix = uniqid(self::PREFIX_IMAGE_NAME);
}
/**
* Get Data
* @param $data
* @return array
*/
public function getData($data)
{
$params = [
"order_by" => 'order',
];
$industryData = $this->industry($params, 'asc', 'array', false);
return $this->industryTransformation->getIndustryCmsTransform($industryData);
}
/**
* Store Data
* @param $data
* @return array
*/
public function store($data)
{
try {
DB::beginTransaction();
if(!$this->storeData($data) == true)
{
DB::rollBack();
return $this->setResponse($this->message, false);
}
if(!$this->storeDatTranslation($data) == true)
{
DB::rollBack();
return $this->setResponse($this->message, false);
}
//TODO: THUMBNAIL UPLOAD
if ($this->uploadThumbnail($data) != true) {
DB::rollBack();
return $this->setResponse($this->message, false);
}
DB::commit();
return $this->setResponse(trans('message.cms_success_store_data_general'), true);
} catch (\Exception $e) {
return $this->setResponse($e->getMessage(), false);
}
}
/**
* Store Data into Database
* @param $data
*/
protected function storeData($data)
{
try {
$store = $this->industry;
if ($this->isEditMode($data)) {
$store = $this->industry->find($data['id']);
if (!empty($data['thumbnail'])) {
$store->thumbnail = $this->uniqueIdImagePrefix . '_' .$data['thumbnail']->getClientOriginalName();
}
$store->updated_at = $this->mysqlDateTimeFormat();
} else {
$store->is_active = true;
$store->order = $this->industry->max('order')+1;
$store->created_at = $this->mysqlDateTimeFormat();
$store->created_by = DataHelper::userId();
}
$store->thumbnail = isset($data['thumbnail']) ? $this->uniqueIdImagePrefix . '_' .$data['thumbnail']->getClientOriginalName() : '';
if($save = $store->save())
{
$this->lastInsertId = $store->id;
}
return $save;
} catch (\Exception $e) {
$this->message = $e->getMessage();
return false;
}
}
/**
* Store Data Translation into Database
* @param $data
*/
protected function storeDatTranslation($data)
{
if ($this->isEditMode($data)) {
$this->removeDatTranslation($data['id']);
}
$finalData = $this->industryTransformation->getDataTranslation($data, $this->lastInsertId, $this->isEditMode($data));
return $this->industryTrans->insert($finalData);
}
/**
* Remove Data Translation by ID
* @param $eventId
* @return bool
*/
protected function removeDatTranslation($industryId)
{
if (empty($industryId))
return false;
return $this->industryTrans->where('industri_id', $industryId)->delete();
}
/**
* Upload Thumbnail
* @param $data
* @return bool
*/
protected function uploadThumbnail($data)
{
try {
if (!$this->isEditMode($data)) {
if ( !$this->thumbnailUploader($data)) {
return false;
}
} else {
//TODO: Edit Mode
if (isset($data['thumbnail']) && !empty($data['thumbnail'])) {
if (!$this->thumbnailUploader($data)) {
return false;
}
}
}
return true;
} catch (\Exception $e) {
$this->message = $e->getMessage();
return false;
}
}
/**
* Thumbnail Uploader
* @param $data
* @return bool
*/
protected function thumbnailUploader($data)
{
if ($data['thumbnail']->isValid()) {
$filename = $this->uniqueIdImagePrefix . '_' .$data['thumbnail']->getClientOriginalName();
if (! $data['thumbnail']->move('./' . INDUSTRI_PAGES_DIRECTORY, $filename)) {
$this->message = trans('message.cms_upload_thumbnail_failed');
return false;
}
return true;
} else {
$this->message = $data['thumbnail']->getErrorMessage();
return false;
}
}
/**
* Get Data For Edit
* @param $data
*/
public function edit($data)
{
$params = [
"id" => isset($data['id']) ? $data['id'] : '',
];
$singleData = $this->industry($params, 'asc', 'array', true);
return $this->setResponse(trans('message.cms_success_get_data'), true, $this->industryTransformation->getSingleForEditIndustryTransform($singleData));
}
/**
* Change Status
* @param $params
* @return mixed
*/
public function changeStatus($data)
{
try {
if (!isset($data['id']) && empty($data['id']))
return $this->setResponse(trans('message.cms_required_id'), false);
DB::beginTransaction();
$oldData = $this->industry
->id($data['id'])
->first()->toArray();
$updatedData = [
'is_active' => $oldData['is_active'] ? false : true,
];
$changeStatus = $this->industry
->id($data['id'])
->update($updatedData);
if($changeStatus) {
DB::commit();
return $this->setResponse(trans('message.cms_success_update_status_general'), true);
}
DB::rollBack();
return $this->setResponse(trans('message.cms_failed_update_status_general'), false);
} catch (\Exception $e) {
return $this->setResponse($e->getMessage(), false);
}
}
/**
* Order Data
* @param $data
*/
public function order($data)
{
try {
DB::beginTransaction();
if ($this->orderData($data)) {
DB::commit();
return $this->setResponse(trans('message.cms_success_ordering'), true);
}
DB::rollBack();
return $this->setResponse(trans('message.cms_failed_ordering'), false);
} catch (\Exception $e) {
DB::rollBack();
return $this->setResponse($e->getMessage(), false);
}
}
/**
* Order List Data
* @param $data
*/
protected function orderData($data)
{
try {
$i = 1 ;
foreach ($data as $key => $val) {
$orderValue = $i++;
$industry = IndustryModels::find($val);
$industry->order = $orderValue;
$industry->save();
}
return true;
} catch (Exception $e) {
$this->message = $e->getMessage();
return false;
}
}
/**
* Delete Data
* @param $params
* @return mixed
*/
public function delete($data)
{
try {
if (!isset($data['id']) && empty($data['id']))
return $this->setResponse(trans('message.cms_required_id'), false);
DB::beginTransaction();
$params = [
"id" => $data['id']
];
if (!$this->removeData($params)) {
DB::rollback();
return $this->setResponse($this->message, false);
}
DB::commit();
return $this->setResponse(trans('message.cms_success_delete_data_general'), true);
} catch (\Exception $e) {
DB::rollback();
return $this->setResponse($e->getMessage(), false);
}
}
/**
* Remove Data From Database
* @param $data
* @return bool
*/
protected function removeData($data)
{
try {
$delete = $this->industry
->id($data['id'])
->forceDelete();
if ($delete)
return true;
$this->message = trans('message.cms_failed_delete_data_general');
return false;
} catch (\Exception $e) {
$this->message = $e->getMessage();
return false;
}
}
/**
* Get All Data
* Warning: this function doesn't redis cache
* @param array $params
* @return array
*/
protected function industry($params = array(), $orderType = 'asc', $returnType = 'array', $returnSingle = false)
{
$industry = $this->industry->with(['translation', 'translations']);
if(isset($params['limit_data'])) {
$industry->take($params['limit_data']);
}
if(isset($params['id'])) {
$industry->id($params['id']);
}
if(isset($params['is_active'])) {
$industry->isActive($params['is_active']);
}
if(isset($params['order_by'])) {
$industry->orderBy($params['order_by'], $orderType);
}
if(!$industry->count())
return array();
switch ($returnType) {
case 'array':
if(!$returnSingle)
{
return $industry->get()->toArray();
}
else
{
return $industry->first()->toArray();
}
break;
}
}
/**
* Check need edit Mode or No
* @param $data
* @return bool
*/
protected function isEditMode($data)
{
return isset($data['id']) && !empty($data['id']) ? true : false;
}
} | kiki091/LintasEbtke | app/Repositories/Implementation/Cms/Industry.php | PHP | gpl-3.0 | 11,280 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 Taifxx
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
########## LI2 (JSP):
### Import modules ...
from base import *
DETVIDEXT = False
### Items ...
currentItemPos = lambda : inte(xbmc.getInfoLabel('Container.CurrentItem'))
itemsCount = lambda : inte(xbmc.getInfoLabel('Container.NumItems'))
### Container info ...
getCpath = lambda : xbmc.getInfoLabel('Container.FolderPath')
getCname = lambda : xbmc.getInfoLabel('Container.FolderName')
getCplug = lambda : xbmc.getInfoLabel('Container.PluginName')
### Listitem info ...
getLi = lambda infolabel, idx=currentItemPos() : xbmc.getInfoLabel('ListitemNoWrap(%s).%s' % (str(idx-currentItemPos()), infolabel))
getIcn = lambda idx=currentItemPos() : getLi('Icon', idx)
getTbn = lambda idx=currentItemPos() : getLi('Thumb', idx)
getLink = lambda idx=currentItemPos() : getLi('FileNameAndPath', idx)
getPath = lambda idx=currentItemPos() : getLi('Path', idx)
getFname = lambda idx=currentItemPos() : getLi('FileName', idx)
getFolpath = lambda idx=currentItemPos() : getLi('FolderPath', idx)
getTitle = lambda idx=currentItemPos() : getLi('Label', idx)
getTitleF = lambda idx=currentItemPos() : getLi('Label', idx)
# def getTitleF (idx=currentItemPos()):
# tmpTitle = getTitle(idx)
# tmpFname = getFname(idx)
# return tmpFname if tmpFname else tmpTitle
def isFolder (idx=currentItemPos()):
if DETVIDEXT and isVidExt(getTitle(idx)) : return False
return True if getLi('Property(IsPlayable)',idx) in ('false', Empty) and not getFname(idx) else False
def isVidExt(name):
for itm in TAG_PAR_VIDEOSEXT:
if name.endswith(itm) : return True
return False
### JSP functions ...
_listdircmd = '{"jsonrpc": "2.0", "method": "Files.GetDirectory", "params": {"properties": ["file", "title"], "directory":"%s", "media":"files"}, "id": "1"}'
def getJsp(dirPath, srcName):
_itmList = eval(xbmc.executeJSONRPC(_listdircmd % (dirPath)))['result']['files']
_jsp = struct()
_jsp.link = dirPath
_jsp.name = srcName
_jsp.itmList = _itmList
_jsp.count = len(_itmList)
return _jsp
jsp_getLabel = lambda jsp, idx=0 : jsp.itmList[idx]['label']
jsp_getLink = lambda jsp, idx=0 : jsp.itmList[idx]['file']
def jsp_isFolder(jsp, idx):
if jsp.itmList[idx]['filetype'] != 'folder' : return False
return True
### Listitems Object ...
class vidItems:
def __init__(self, dirPath=Empty, srcName=Empty):
if not dirPath : self.norm_init()
else : self.jsp_init (dirPath, srcName)
def jsp_init(self, dirPath, srcName):
jsp = getJsp(dirPath, srcName)
#import resources.lib.gui as GUI
#GUI.dlgOk(str( jsp.count ))
## Current jsp data ...
self.vidFolderNameDef = Empty
self.vidCPath = jsp.link
self.vidCName = jsp.name
self.vidIsEmpty = True
self.vidFolCount = jsp.count
## Local items list...
self.vidListItems = []
self.vidListItemsRaw = []
## Create items list ...
for idx in range(0, self.vidFolCount):
self.vidListItemsRaw.append([jsp_getLabel(jsp, idx), jsp_getLink(jsp, idx)])
if jsp_isFolder(jsp, idx) : continue
self.vidListItems.append([jsp_getLabel(jsp, idx), jsp_getLink(jsp, idx)])
if self.vidListItems :
self.vidIsEmpty = False
## Set as default first nofolder item ...
self.vidFolderNameDef = self.vidListItems[0][0]
def norm_init(self):
## Current listitem data ...
self.vidFolderNameDef = Empty
self.vidCurr = getTitleF()
self.vidPath = getPath()
self.vidIsFolder = isFolder()
self.vidFPath = getFolpath()
self.vidLink = getLink()
self.vidCPath = getCpath()
self.vidCName = getCname()
self.vidCPlug = getCplug()
self.vidIsEmpty = True
self.vidFolCount = itemsCount()
## Local items list...
self.vidListItems = []
self.vidListItemsRaw = []
## If current item is not a folder, set it as default ...
if not self.vidIsFolder : self.vidFolderNameDef = self.vidCurr
## Create items list ...
for idx in range(1, self.vidFolCount+1):
self.vidListItemsRaw.append([getTitleF(idx), getLink(idx)])
if isFolder(idx) : continue
self.vidListItems.append([getTitleF(idx), getLink(idx)])
if self.vidListItems :
self.vidIsEmpty = False
## Set as default first nofolder item, if current item is a folder ...
if self.vidFolderNameDef == Empty : self.vidFolderNameDef = self.vidListItems[0][0]
def setmanually(self, manlist):
self.vidListItems = [itm for idx, itm in enumerate(self.vidListItemsRaw) if idx in manlist]
def reverse(self):
self.vidListItems.reverse()
self.vidListItemsRaw.reverse()
def getOnlyNexts(self):
nexts = False
retList = []
for itm in self.vidListItems:
if itm[0] == self.vidCurr : nexts = True; continue
if not nexts : continue
retList.append(itm[1])
return retList
| Taifxx/xxtrep | context.addtolib/resources/lib/ext/li2_.py | Python | gpl-3.0 | 6,356 |
<?php
/**
* Mahara: Electronic portfolio, weblog, resume builder and social networking
* Copyright (C) 2006-2009 Catalyst IT Ltd and others; see:
* http://wiki.mahara.org/Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package mahara
* @subpackage auth
* @author Catalyst IT Ltd
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL
* @copyright (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
*
*/
defined('INTERNAL') || die();
require('session.php');
require(get_config('docroot') . 'auth/user.php');
require_once(get_config('docroot') . '/lib/htmloutput.php');
/**
* Unknown user exception
*/
class AuthUnknownUserException extends UserException {}
/**
* An instance of an auth plugin failed during execution
* e.g. LDAP auth failed to connect to a directory
* Developers can use this to fail an individual auth
* instance, but not kill all from being tried.
* If appropriate - the 'message' of the exception will be used
* as the display message, so don't forget to language translate it
*/
class AuthInstanceException extends UserException {
public function strings() {
return array_merge(parent::strings(),
array('title' => $this->get_sitename() . ': Authentication problem'));
}
}
/**
* We tried to call a method on an auth plugin that hasn't been init'ed
* successfully
*/
class UninitialisedAuthException extends SystemException {}
/**
* We tried creating automatically creating an account for a user but
* it failed for a reason that the user might want to know about
* (e.g. they used an email address that's already used on the site)
*/
class AccountAutoCreationException extends AuthInstanceException {
public function strings() {
return array_merge(parent::strings(),
array('message' => 'The automatic creation of your user account failed.'
. "\nDetails if any, follow:"));
}
}
/**
* Base authentication class. Provides a common interface with which
* authentication can be carried out for system users.
*
* @todo for authentication:
* - inactivity: each institution has inactivity timeout times, this needs
* to be supported
* - this means the lastlogin field needs to be updated on the usr table
* - warnings are handled by cron
*/
abstract class Auth {
protected $instanceid;
protected $institution;
protected $instancename;
protected $priority;
protected $authname;
protected $config;
protected $has_instance_config;
protected $type;
protected $ready;
/**
* Given an id, create the auth object and retrieve the config settings
* If an instance ID is provided, get all the *instance* config settings
*
* @param int $id The unique ID of the auth instance
* @return bool Whether the create was successful
*/
public function __construct($id = null) {
$this->ready = false;
}
/**
* Instantiate the plugin by pulling the config data for an instance from
* the database
*
* @param int $id The unique ID of the auth instance
* @return bool Whether the create was successful
*/
public function init($id) {
if (!is_numeric($id) || intval($id) != $id) {
throw new UserNotFoundException();
}
$instance = get_record('auth_instance', 'id', $id);
if (empty($instance)) {
throw new UserNotFoundException();
}
$this->instanceid = $id;
$this->institution = $instance->institution;
$this->instancename = $instance->instancename;
$this->priority = $instance->priority;
$this->authname = $instance->authname;
// Return now if the plugin type doesn't require any config
// (e.g. internal)
if ($this->has_instance_config == false) {
return true;
}
$records = get_records_array('auth_instance_config', 'instance', $this->instanceid);
if ($records == false) {
return false;
}
foreach($records as $record) {
$this->config[$record->field] = $record->value;
}
return true;
}
/**
* The __get overloader is invoked when the requested member is private or
* protected, or just doesn't exist.
*
* @param string $name The name of the value to fetch
* @return mixed The value
*/
public function __get($name) {
$approved_members = array('instanceid', 'institution', 'instancename', 'priority', 'authname', 'type');
if (in_array($name, $approved_members)) {
return $this->{$name};
}
if (isset($this->config[$name])) {
return $this->config[$name];
}
return null;
}
/**
* The __set overloader is invoked when the specified member is private or
* protected, or just doesn't exist.
*
* @param string $name The name of the value to set
* @param mixed $value The value to assign
* @return void
*/
public function __set($name, $value) {
/*
if (property_exists($this, $name)) {
$this->{$name} = $value;
return;
}
*/
throw new SystemException('It\'s forbidden to set values on Auth objects');
}
/**
* Check that the plugin has been initialised before we try to use it.
*
* @throws UninitialisedAuthException
* @return bool
*/
protected function must_be_ready() {
if ($this->ready == false) {
throw new UninitialisedAuthException('This Auth plugin has not been initialised');
}
return true;
}
/**
* Fetch the URL that users can visit to change their passwords. This might
* be a Moodle installation, for example.
*
* @return mixed URL to change password or false if there is none
*/
public function changepasswordurl() {
$this->must_be_ready();
if (empty($this->config['changepasswordurl'])) {
return false;
}
return $this->config['changepasswordurl'];
}
/**
* Given a username and password, attempts to log the user in.
*
* @param object $user An object with username member (at least)
* @param string $password The password to use for the attempt
* @return bool Whether the authentication was successful
* @throws AuthUnknownUserException If the user is unknown to the
* authentication method
*/
public function authenticate_user_account($user, $password) {
$this->must_be_ready();
return false;
}
/**
* Given a username, returns whether the user exists in the usr table
*
* @param string $username The username to attempt to identify
* @return bool Whether the username exists
*/
public function user_exists($username) {
$this->must_be_ready();
if (record_exists_select('usr', 'LOWER(username) = ?', array(strtolower($username)))) {
return true;
}
throw new AuthUnknownUserException("\"$username\" is not known to Auth");
}
/**
* Returns whether the authentication instance can automatically create a
* user record.
*
* Auto creating users means that the authentication plugin can say that
* users who don't exist yet in Mahara's usr table are allowed, and Mahara
* should create a user account for them. Example: the first time a user logs
* in, when authenticating against an ldap store or similar).
*
* However, if a plugin says a user can be authenticated, then it must
* implement the get_user_info() method which will be called to find out
* information about the user so a record in the usr table _can_ be created
* for the new user.
*
* Authentication methods must implement this method. Some may choose to
* implement it by returning an instance config value that the admin user
* can set.
*
* @return bool
*/
public abstract function can_auto_create_users();
/**
* Given a username, returns a hash of information about a user from the
* external data source.
*
* @param string $username The username to look up information for
* @return array The information for the user
* @throws AuthUnknownUserException If the user is unknown to the
* authentication method
*/
public function get_user_info($username) {
return false;
}
/**
* Given a password, returns whether it is in a valid format for this
* authentication method.
*
* This only needs to be defined by subclasses if:
* - They implement the change_password method, which means that the
* system can use the <kbd>passwordchange</kbd> flag on the <kbd>usr</kbd>
* table to control whether the user's password needs changing.
* - The password that a user can set must be in a certain format.
*
* The default behaviour is to assume that the password is in a valid form,
* so make sure to implement this method if this is not the case!
*
* This method is defined to be empty, so that authentication methods do
* not have to specify a format if they do not need to.
*
* @param string $password The password to check
* @return bool Whether the username is in valid form.
*/
public function is_password_valid($password) {
return true;
}
/**
* Called when a user is being logged in, after the main authentication routines.
*
* You can use $USER->login() to perform any additional tasks, for example
* to set a cookie that another application can read, or pull some data
* from somewhere.
*
* This method has no parameters and needs no return value
*/
public function login() {
}
/**
* Called when a user is being logged out, either by clicking a logout
* link, their session timing out or some other method where their session
* is explicitly being ended with no more processing to take place on this
* page load.
*
* You can use $USER->logout() to log a user out but continue page
* processing if necessary. register.php is an example of such a place
* where this happens.
*
* If you define this hook, you can call $USER->logout() in it if you need
* to before redirecting. Otherwise, it will be called for you once your
* hook has run.
*
* If you do not explicitly redirect yourself, once this hook is finished
* the user will be redirected to the homepage with a message saying they
* have been logged out successfully.
*
* This method has no parameters and needs no return value
*/
public function logout() {
}
}
/******************************************************************************/
// End of Auth base-class
/******************************************************************************/
/**
* Handles authentication by setting up a session for a user if they are logged
* in.
*
* This function combined with the Session class is smart - if the user is not
* logged in then they do not get a session, which prevents simple curl hits
* or search engine crawls to a page from getting sessions they won't use.
*
* Once the user has a session, they keep it even if the log out, so it can
* be reused. The session does expire, but the expiry time is typically a week
* or more.
*
* If the user is not authenticated for this page, then this function will
* exit, printing the login page. Therefore, after including init.php, you can
* be sure that the user is logged in, or has a valid guest key. However, no
* testing is done to make sure the user has the required permissions to see
* the page.
*
*/
function auth_setup () {
global $SESSION, $USER;
// If the system is not installed, let the user through in the hope that
// they can fix this little problem :)
if (!get_config('installed')) {
$USER->logout();
return;
}
// Lock the site until core upgrades are done
require(get_config('libroot') . 'version.php');
$siteclosed = $config->version > get_config('version');
$disablelogin = $config->disablelogin;
if (!$siteclosed && get_config('forcelocalupgrades')) {
require(get_config('docroot') . 'local/version.php');
$siteclosed = $config->version > get_config('localversion');
}
$cfgsiteclosed = get_config('siteclosed');
if ($siteclosed && !$cfgsiteclosed || !$siteclosed && $cfgsiteclosed) {
// If the admin closed the site manually, open it automatically
// when an upgrade is successful.
if ($cfgsiteclosed && get_config('siteclosedbyadmin')) {
set_config('siteclosedbyadmin', false);
}
set_config('siteclosed', $siteclosed);
set_config('disablelogin', $disablelogin);
}
// Check the time that the session is set to log out. If the user does
// not have a session, this time will be 0.
$sessionlogouttime = $USER->get('logout_time');
if ($sessionlogouttime && isset($_GET['logout'])) {
// Call the authinstance' logout hook
$authinstance = $SESSION->get('authinstance');
if ($authinstance) {
$authobj = AuthFactory::create($authinstance);
$authobj->logout();
}
else {
log_debug("Strange: user " . $USER->get('username') . " had no authinstance set in their session");
}
if (function_exists('local_logout')) {
local_logout();
}
$USER->logout();
$SESSION->add_ok_msg(get_string('loggedoutok'));
redirect();
}
if ($sessionlogouttime > time()) {
// The session is still active, so continue it.
// Make sure that if a user's admin status has changed, they're kicked
// out of the admin section
if (in_admin_section()) {
// Reload site admin/staff permissions
$realuser = get_record('usr', 'id', $USER->id, null, null, null, null, 'admin,staff');
if (!$USER->get('admin') && $realuser->admin) {
// The user has been made into an admin
$USER->admin = 1;
}
else if ($USER->get('admin') && !$realuser->admin) {
// The user's admin rights have been taken away
$USER->admin = 0;
}
if (!$USER->get('staff') && $realuser->staff) {
$USER->staff = 1;
}
else if ($USER->get('staff') && !$realuser->staff) {
$USER->staff = 0;
}
// Reload institutional admin/staff permissions
$USER->reset_institutions();
auth_check_admin_section();
}
$USER->renew();
auth_check_required_fields();
}
else if ($sessionlogouttime > 0) {
// The session timed out
$authinstance = $SESSION->get('authinstance');
if ($authinstance) {
$authobj = AuthFactory::create($authinstance);
$mnetuser = 0;
if ($SESSION->get('mnetuser') && $authobj->parent) {
// We wish to remember that the user is an MNET user - even though
// they're using the local login form
$mnetuser = $USER->get('id');
}
$authobj->logout();
$USER->logout();
if ($mnetuser != 0) {
$SESSION->set('mnetuser', $mnetuser);
$SESSION->set('authinstance', $authinstance);
}
}
else {
log_debug("Strange: user " . $USER->get('username') . " had no authinstance set in their session");
}
if (defined('JSON')) {
json_reply('global', get_string('sessiontimedoutreload'), 1);
}
if (defined('IFRAME')) {
header('Content-type: text/html');
print_auth_frame();
exit;
}
// If the page the user is viewing is public, inform them that they can
// log in again
if (defined('PUBLIC')) {
// @todo this links to ?login - later it should do magic to make
// sure that whatever GET string is made it includes the old data
// correctly
$loginurl = $_SERVER['REQUEST_URI'];
$loginurl .= (false === strpos($loginurl, '?')) ? '?' : '&';
$loginurl .= 'login';
$SESSION->add_info_msg(get_string('sessiontimedoutpublic', 'mahara', hsc($loginurl)), false);
return;
}
auth_draw_login_page(get_string('sessiontimedout'));
}
else {
// There is no session, so we check to see if one needs to be started.
// Build login form. If the form is submitted it will be handled here,
// and set $USER for us (this will happen when users hit a page and
// specify login data immediately
require_once('pieforms/pieform.php');
$form = new Pieform(auth_get_login_form());
if ($USER->is_logged_in()) {
return;
}
// Check if the page is public or the site is configured to be public.
if (defined('PUBLIC') && !isset($_GET['login'])) {
if ($lang = param_alphanumext('lang', null)) {
$SESSION->set('lang', $lang);
}
return;
}
// No session and a json request
if (defined('JSON')) {
json_reply('global', get_string('nosessionreload'), 1);
}
auth_draw_login_page(null, $form);
exit;
}
}
/**
*
* Returns all auth instances
*
* @return array Array of auth instance records
*/
function auth_get_auth_instances() {
static $cache = array();
if (count($cache) > 0) {
return $cache;
}
$sql ='
SELECT DISTINCT
i.id,
inst.name,
inst.displayname,
i.instancename,
i.authname
FROM
{institution} inst,
{auth_instance} i
WHERE
i.institution = inst.name
ORDER BY
inst.displayname,
i.instancename';
$cache = get_records_sql_array($sql, array());
if (empty($cache)) {
return array();
}
return $cache;
}
/**
*
* Given a list of institutions, returns all auth instances associated with them
*
* @return array Array of auth instance records
*/
function auth_get_auth_instances_for_institutions($institutions) {
if (empty($institutions)) {
return array();
}
$sql ='
SELECT DISTINCT
i.id,
inst.name,
inst.displayname,
i.instancename,
i.authname
FROM
{institution} inst,
{auth_instance} i
WHERE
i.institution = inst.name AND
inst.name IN (' . join(',', array_map('db_quote',$institutions)) . ')
ORDER BY
inst.displayname,
i.instancename';
return get_records_sql_array($sql, array());
}
/**
* Given an institution, returns the authentication methods used by it, sorted
* by priority.
*
* @param string $institution Name of the institution
* @return array Array of auth instance records
*/
function auth_get_auth_instances_for_institution($institution=null) {
static $cache = array();
if (null == $institution) {
return array();
}
if (!isset($cache[$institution])) {
// Get auth instances in order of priority
// DO NOT CHANGE THE SORT ORDER OF THIS RESULT SET
// YEAH EINSTEIN - THAT MEANS YOU!!!
// TODO: work out why this won't accept a placeholder - had to use db_quote
$sql ='
SELECT DISTINCT
i.id,
i.instancename,
i.priority,
i.authname,
a.requires_config,
a.requires_parent
FROM
{auth_instance} i,
{auth_installed} a
WHERE
a.name = i.authname AND
i.institution = '. db_quote($institution).'
ORDER BY
i.priority,
i.instancename';
$cache[$institution] = get_records_sql_array($sql, array());
if (empty($cache[$institution])) {
return false;
}
}
return $cache[$institution];
}
/**
* Given a wwwroot, find any auth instances that can come from that host
*
* @param string wwwroot of the host that is connecting to us
* @return array array of record objects
*/
function auth_get_auth_instances_for_wwwroot($wwwroot) {
// TODO: we just need ai.id and ai.authname... rewrite query, or
// just drop this function
$query = " SELECT
ai.*,
aic.*,
i.*
FROM
{auth_instance} ai,
{auth_instance_config} aic,
{institution} i
WHERE
aic.field = 'wwwroot' AND
aic.value = ? AND
aic.instance = ai.id AND
i.name = ai.institution";
return get_records_sql_array($query, array('value' => $wwwroot));
}
/**
* Given an institution, get all the auth types EXCEPT those that are already
* enabled AND do not require configuration.
*
* @param string $institution Name of the institution
* @return array Array of auth instance records
*/
function auth_get_available_auth_types($institution=null) {
if (!is_null($institution) && (!is_string($institution) || strlen($institution) > 255)) {
return array();
}
// TODO: work out why this won't accept a placeholder - had to use db_quote
$sql ='
SELECT DISTINCT
a.name,
a.requires_config
FROM
{auth_installed} a
LEFT JOIN
{auth_instance} i
ON
a.name = i.authname AND
i.institution = '. db_quote($institution).'
WHERE
(a.requires_config = 1 OR
i.id IS NULL) AND
a.active = 1
ORDER BY
a.name';
if (is_null($institution)) {
$result = get_records_array('auth_installed', '','','name','name, requires_config');
} else {
$result = get_records_sql_array($sql, array());
}
if (empty($result)) {
return array();
}
foreach ($result as &$row) {
$row->title = get_string('title', 'auth.' . $row->name);
safe_require('auth', $row->name);
if ($row->is_usable = call_static_method('PluginAuth' . $row->name, 'is_usable')) {
$row->description = get_string('description', 'auth.' . $row->name);
}
else {
$row->description = get_string('notusable', 'auth.' . $row->name);
}
}
usort($result, create_function('$a, $b', 'if ($a->is_usable != $b->is_usable) return $b->is_usable; return strnatcasecmp($a->title, $b->title);'));
return $result;
}
/**
* Checks that all the required fields are set, and handles setting them if required.
*
* Checks whether the current user needs to change their password, and handles
* the password changing if it's required.
*/
function auth_check_required_fields() {
global $USER, $SESSION;
if (defined('NOCHECKREQUIREDFIELDS')) {
return;
}
$changepassword = true;
$elements = array();
if (
!$USER->get('passwordchange') // User doesn't need to change their password
|| ($USER->get('parentuser') && $USER->get('loginanyway')) // User is masquerading and wants to log in anyway
|| defined('NOCHECKPASSWORDCHANGE') // The page wants to skip this hassle
) {
$changepassword = false;
}
// Check if the user wants to log in anyway
if ($USER->get('passwordchange') && $USER->get('parentuser') && isset($_GET['loginanyway'])) {
$USER->loginanyway = true;
$changepassword = false;
}
if ($changepassword) {
$authobj = AuthFactory::create($USER->authinstance);
if ($authobj->changepasswordurl) {
redirect($authobj->changepasswordurl);
exit;
}
if (method_exists($authobj, 'change_password')) {
if ($SESSION->get('resetusername')) {
$elements['username'] = array(
'type' => 'text',
'defaultvalue' => $USER->get('username'),
'title' => get_string('changeusername', 'account'),
'description' => get_string('changeusernamedesc', 'account', hsc(get_config('sitename'))),
);
}
$elements['password1'] = array(
'type' => 'password',
'title' => get_string('newpassword') . ':',
'description' => get_string('yournewpassword'),
'rules' => array(
'required' => true
)
);
$elements['password2'] = array(
'type' => 'password',
'title' => get_string('confirmpassword') . ':',
'description' => get_string('yournewpasswordagain'),
'rules' => array(
'required' => true,
),
);
$elements['email'] = array(
'type' => 'text',
'title' => get_string('principalemailaddress', 'artefact.internal'),
'ignore' => (trim($USER->get('email')) != '' && !preg_match('/@example\.org$/', $USER->get('email'))),
'rules' => array(
'required' => true,
'email' => true,
),
);
}
}
else if (defined('JSON')) {
// Don't need to check this for json requests
return;
}
safe_require('artefact', 'internal');
require_once('pieforms/pieform.php');
$alwaysmandatoryfields = array_keys(ArtefactTypeProfile::get_always_mandatory_fields());
foreach(ArtefactTypeProfile::get_mandatory_fields() as $field => $type) {
// Always mandatory fields are stored in the usr table, so are part of
// the user session object. We can save a query by grabbing them from
// the session.
if (in_array($field, $alwaysmandatoryfields) && $USER->get($field) != null) {
continue;
}
// Not cached? Get value the standard way.
if (get_profile_field($USER->get('id'), $field) != null) {
continue;
}
if ($field == 'email') {
if (isset($elements['email'])) {
continue;
}
// Use a text field for their first e-mail address, not the
// emaillist element
$type = 'text';
}
$elements[$field] = array(
'type' => $type,
'title' => get_string($field, 'artefact.internal'),
'rules' => array('required' => true)
);
// @todo ruthlessly stolen from artefact/internal/index.php, could be merged
if ($type == 'wysiwyg') {
$elements[$field]['rows'] = 10;
$elements[$field]['cols'] = 60;
}
if ($type == 'textarea') {
$elements[$field]['rows'] = 4;
$elements[$field]['cols'] = 60;
}
if ($field == 'country') {
$elements[$field]['options'] = getoptions_country();
$elements[$field]['defaultvalue'] = get_config('country');
}
if ($field == 'email') {
$elements[$field]['rules']['email'] = true;
}
}
if (empty($elements)) { // No mandatory fields that aren't set
return;
}
$elements['submit'] = array(
'type' => 'submit',
'value' => get_string('submit')
);
$form = pieform(array(
'name' => 'requiredfields',
'method' => 'post',
'action' => '',
'elements' => $elements
));
$smarty = smarty();
if ($USER->get('parentuser')) {
$smarty->assign('loginasoverridepasswordchange',
get_string('loginasoverridepasswordchange', 'admin',
'<a href="' . get_config('wwwroot') . '?loginanyway">', '</a>'));
}
$smarty->assign('changepassword', $changepassword);
$smarty->assign('changeusername', $SESSION->get('resetusername'));
$smarty->assign('form', $form);
$smarty->display('requiredfields.tpl');
exit;
}
function requiredfields_validate(Pieform $form, $values) {
global $USER;
if (!isset($values['password1'])) {
return true;
}
// Get the authentication type for the user, and
// use the information to validate the password
$authobj = AuthFactory::create($USER->authinstance);
// @todo this could be done by a custom form rule... 'password' => $user
password_validate($form, $values, $USER);
// The password cannot be the same as the old one
try {
if (!$form->get_error('password1')
&& $authobj->authenticate_user_account($USER, $values['password1'])) {
$form->set_error('password1', get_string('passwordnotchanged'));
}
}
// propagate error up as the collective error AuthUnknownUserException
catch (AuthInstanceException $e) {
$form->set_error('password1', $e->getMessage());
}
if ($authobj->authname == 'internal' && isset($values['username']) && $values['username'] != $USER->get('username')) {
if (!AuthInternal::is_username_valid($values['username'])) {
$form->set_error('username', get_string('usernameinvalidform', 'auth.internal'));
}
if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', strtolower($values['username']))) {
$form->set_error('username', get_string('usernamealreadytaken', 'auth.internal'));
}
}
}
function requiredfields_submit(Pieform $form, $values) {
global $USER, $SESSION;
if (isset($values['password1'])) {
$authobj = AuthFactory::create($USER->authinstance);
// This method should exist, because if it did not then the change
// password form would not have been shown.
if ($password = $authobj->change_password($USER, $values['password1'])) {
$SESSION->add_ok_msg(get_string('passwordsaved'));
}
else {
throw new SystemException('Attempt by "' . $USER->get('username') . '@'
. $USER->get('institution') . 'to change their password failed');
}
}
if (isset($values['username'])) {
$SESSION->set('resetusername', false);
if ($values['username'] != $USER->get('username')) {
$USER->username = $values['username'];
$USER->commit();
$otherfield = true;
}
}
foreach ($values as $field => $value) {
if (in_array($field, array('submit', 'sesskey', 'password1', 'password2', 'username'))) {
continue;
}
if ($field == 'email') {
$USER->email = $values['email'];
$USER->commit();
}
set_profile_field($USER->get('id'), $field, $value);
$otherfield = true;
}
if (isset($otherfield)) {
$SESSION->add_ok_msg(get_string('requiredfieldsset', 'auth'));
}
redirect();
}
/**
* Creates and displays the transient login page.
*
* This login page remembers all GET/POST data and passes it on. This way,
* users can have their sessions time out, and then can log in again without
* losing any of their data.
*
* As this function builds and validates a login form, it is possible that
* calling this may validate a user to be logged in.
*
* @param Pieform $form If specified, just build this form to get the HTML
* required. Otherwise, this function will build and
* validate the form itself.
* @access private
*/
function auth_draw_login_page($message=null, Pieform $form=null) {
global $USER, $SESSION;
if ($form != null) {
$loginform = get_login_form_js($form->build());
}
else {
require_once('pieforms/pieform.php');
$loginform = get_login_form_js(pieform(auth_get_login_form()));
/*
* If $USER is set, the form was submitted even before being built.
* This happens when a user's session times out and they resend post
* data. The request should just continue if so.
*/
if ($USER->is_logged_in()) {
return;
}
}
$externallogin = get_config('externallogin');
if ($externallogin) {
$externallogin = preg_replace('/{shorturlencoded}/', urlencode(get_relative_script_path()), $externallogin);
$externallogin = preg_replace('/{wwwroot}/', get_config('wwwroot'), $externallogin);
redirect($externallogin);
}
if ($message) {
$SESSION->add_info_msg($message);
}
$smarty = smarty(array(), array(), array(), array('pagehelp' => false, 'sidebars' => false));
$smarty->assign('login_form', $loginform);
$smarty->assign('PAGEHEADING', get_string('loginto', 'mahara', get_config('sitename')));
$smarty->assign('LOGINPAGE', true);
$smarty->display('login.tpl');
exit;
}
/**
* Returns the definition of the login form.
*
* @return array The login form definition array.
* @access private
*/
function auth_get_login_form() {
$elements = auth_get_login_form_elements();
$elements['login']['elements']['login_submitted'] = array(
'type' => 'hidden',
'value' => 1
);
// Change login redirection for clean urls
$url = get_relative_script_path();
$getstart = strrpos($url, '?');
if ($getstart !== false) {
$getpart = substr($url, $getstart + 1);
$url = substr($url, 0, $getstart);
}
if (!file_exists(get_config('docroot') . $url)) {
// clean url, treat get string differently
$get = array();
if (isset($getpart)) {
$getarr = split('&', $getpart);
if ($getarr) {
foreach ($getarr as $data) {
$arr = split('=', $data);
$get[$arr[0]] = isset($arr[1]) ? $arr[1] : null;
}
}
}
}
else {
$get = $_GET;
}
// The login page is completely transient, and it is smart because it
// remembers the GET and POST data sent to it and resends that on
// afterwards.
$action = '';
if ($get) {
if (isset($get['logout'])) {
// You can log the user out on any particular page by appending
// ?logout to the URL. In this case, we don't want the "action"
// of the url to include that, or be blank, else the next time
// the user logs in they will be logged out again.
$action = hsc(substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')));
}
else {
$action .= '?';
foreach ($get as $key => $value) {
if ($key != 'login') {
$action .= hsc($key) . '=' . hsc($value) . '&';
}
}
$action = substr($action, 0, -1);
}
}
if ($_POST) {
foreach ($_POST as $key => $value) {
if (!isset($elements[$key]) && !isset($elements['login']['elements'][$key])) {
$elements[$key] = array(
'type' => 'hidden',
'value' => $value
);
}
}
}
$form = array(
'name' => 'login',
'renderer' => 'div',
'method' => 'post',
'action' => $action,
'plugintype' => 'auth',
'pluginname' => 'internal',
'elements' => $elements,
'dieaftersubmit' => false,
'iscancellable' => false
);
return $form;
}
/**
* Returns the definition of the login form elements.
*
* @return array The login form elements array.
* @access private
*/
function auth_get_login_form_elements() {
// See if user can register
if (count_records('institution', 'registerallowed', 1, 'suspended', 0)) {
$registerlink = '<a href="' . get_config('wwwroot') . 'register.php" tabindex="2">' . get_string('register') . '</a><br>';
}
else {
$registerlink = '';
}
$elements = array(
'login_username' => array(
'type' => 'text',
'title' => get_string('username') . ':',
'description' => get_string('usernamedescription'),
'defaultvalue' => (isset($_POST['login_username'])) ? $_POST['login_username'] : '',
'rules' => array(
'required' => true
)
),
'login_password' => array(
'type' => 'password',
'title' => get_string('password') . ':',
'description' => get_string('passworddescription'),
'defaultvalue' => '',
'rules' => array(
'required' => true
)
),
'submit' => array(
'type' => 'submit',
'value' => get_string('login')
),
'register' => array(
'type' => 'markup',
'value' => '<div id="login-helplinks">' . $registerlink
. '<a href="' . get_config('wwwroot') . 'forgotpass.php" tabindex="2">' . get_string('lostusernamepassword') . '</a></div>'
),
);
$elements = array(
'login' => array(
'type' => 'container',
'class' => 'login',
'elements' => $elements
)
);
// Get any extra elements from the enabled auth plugins
$extraelements = array();
$showbasicform = false;
$authplugins = auth_get_enabled_auth_plugins();
foreach ($authplugins as $plugin) {
$classname = 'PluginAuth' . ucfirst(strtolower($plugin));
$pluginelements = call_static_method($classname, 'login_form_elements');
if (!empty($pluginelements)) {
$extraelements = array_merge($extraelements, $pluginelements);
}
if (call_static_method($classname, 'need_basic_login_form')) {
$showbasicform = true;
}
}
if (!empty($extraelements) && $showbasicform) {
$loginlabel = array(
'type' => 'markup',
'value' => '<label>'.get_string('orloginvia') . '</label>'
);
$extraelements = array_merge(array('label' => $loginlabel), $extraelements);
$keys = array_keys($extraelements);
if (!empty($keys)) {
$key = $keys[count($keys) - 1];
$extraelements[$key]['value'] .= '<div class="cb"></div>';
}
}
if (count($extraelements)) {
$extraelements = array(
'login_extra' => array(
'type' => 'container',
'class' => 'login_extra',
'elements' => $extraelements
)
);
}
// Replace or supplement the standard login form elements
if ($showbasicform) {
$elements = array_merge($elements, $extraelements);
}
else {
$elements = $extraelements;
}
return $elements;
}
/**
* Returns javascript to assist with the rendering of the login forms. The
* javascript is used to detect whether cookies are enabled, and not show the
* login form if they are not.
*
* @param string $form A rendered login form
* @return string The form with extra javascript added for cookie detection
* @private
*/
function get_login_form_js($form) {
$form = json_encode($form);
$strcookiesnotenabled = json_encode(get_string('cookiesnotenabled'));
$cookiename = get_config('cookieprefix') . 'ctest';
$js = <<< EOF
<script type="text/javascript">
var loginbox = $('loginform_container');
document.cookie = "$cookiename=1";
if (document.cookie) {
loginbox.innerHTML = $form;
document.cookie = '$cookiename=1;expires=1/1/1990 00:00:00';
}
else {
replaceChildNodes(loginbox, P(null, $strcookiesnotenabled));
}
</script>
EOF;
$authplugins = auth_get_enabled_auth_plugins();
foreach ($authplugins as $plugin) {
$classname = 'PluginAuth' . ucfirst(strtolower($plugin));
$pluginjs = call_static_method($classname, 'login_form_js');
if (!empty($pluginjs)) {
$js .= $pluginjs;
}
}
return $js;
}
/**
* Return a list of all enabled and usable auth plugins.
*/
function auth_get_enabled_auth_plugins() {
static $cached_plugins = null;
if ($cached_plugins !== null) {
return $cached_plugins;
}
$sql = 'SELECT
DISTINCT(authname)
FROM
{auth_instance} ai
JOIN
{institution} i ON ai.institution = i.name
JOIN
{auth_installed} inst ON inst.name = ai.authname
WHERE
i.suspended = 0 AND
inst.active = 1
ORDER BY authname';
$authplugins = get_column_sql($sql);
$usableplugins = array();
foreach ($authplugins as $plugin) {
safe_require('auth', strtolower($plugin));
$classname = 'PluginAuth' . ucfirst(strtolower($plugin));
if (call_static_method($classname, 'is_usable')) {
$usableplugins[] = $plugin;
}
}
$cached_plugins = $usableplugins;
return $cached_plugins;
}
/**
* Class to build and cache instances of auth objects
*/
class AuthFactory {
static $authcache = array();
/**
* Take an instanceid and create an auth object for that instance.
*
* @param int $id The id of the auth instance
* @return mixed An intialised auth object or false, if the
* instance doesn't exist (Should never happen)
*/
public static function create($id) {
if (is_object($id) && isset($id->id)) {
$id = $id->id;
}
if (isset(self::$authcache[$id]) && is_object(self::$authcache[$id])) {
return self::$authcache[$id];
}
$authinstance = get_record('auth_instance', 'id', $id, null, null, null, null, 'authname');
if (!empty($authinstance)) {
$authclassname = 'Auth' . ucfirst($authinstance->authname);
safe_require('auth', $authinstance->authname);
self::$authcache[$id] = new $authclassname($id);
return self::$authcache[$id];
}
return false;
}
}
/**
* Called when the login form is submitted. Validates the user and password, and
* if they are valid, starts a new session for the user.
*
* @param object $form The Pieform form object
* @param array $values The submitted values
* @access private
*/
function login_submit(Pieform $form, $values) {
global $SESSION, $USER;
$username = trim($values['login_username']);
$password = $values['login_password'];
$authenticated = false;
try {
$authenticated = $USER->login($username, $password);
if (empty($authenticated)) {
$SESSION->add_error_msg(get_string('loginfailed'));
return;
}
}
catch (AuthUnknownUserException $e) {
// If the user doesn't exist, check for institutions that
// want to create users automatically.
try {
// Reset the LiveUser object, since we are attempting to create a
// new user
$SESSION->destroy_session();
$USER = new LiveUser();
$authinstances = get_records_sql_array("
SELECT a.id, a.instancename, a.priority, a.authname, a.institution, i.suspended, i.displayname
FROM {institution} i JOIN {auth_instance} a ON a.institution = i.name
WHERE a.authname != 'internal'
ORDER BY a.institution, a.priority, a.instancename", null);
if ($authinstances == false) {
throw new AuthUnknownUserException("\"$username\" is not known");
}
$USER->username = $username;
reset($authinstances);
while ((list(, $authinstance) = each($authinstances)) && false == $authenticated) {
$auth = AuthFactory::create($authinstance->id);
if (!$auth->can_auto_create_users()) {
continue;
}
// catch semi-fatal auth errors, but allow next auth instance to be
// tried
try {
if ($auth->authenticate_user_account($USER, $password)) {
$authenticated = true;
}
else {
continue;
}
} catch (AuthInstanceException $e) {
continue;
}
// Check now to see if the institution has its maximum quota of users
require_once('institution.php');
$institution = new Institution($authinstance->institution);
if ($institution->isFull()) {
throw new AuthUnknownUserException('Institution has too many users');
}
$USER->authinstance = $authinstance->id;
$userdata = $auth->get_user_info($username);
if (empty($userdata)) {
throw new AuthUnknownUserException("\"$username\" is not known");
}
// Check for a suspended institution
if ($authinstance->suspended) {
$sitename = get_config('sitename');
throw new AccessTotallyDeniedException(get_string('accesstotallydenied_institutionsuspended', 'mahara', $authinstance->displayname, $sitename));
}
// We have the data - create the user
$USER->lastlogin = db_format_timestamp(time());
if (isset($userdata->firstname)) {
$USER->firstname = sanitize_firstname($userdata->firstname);
}
if (isset($userdata->lastname)) {
$USER->lastname = sanitize_firstname($userdata->lastname);
}
if (isset($userdata->email)) {
$USER->email = sanitize_email($userdata->email);
}
else {
// The user will be asked to populate this when they log in.
$USER->email = null;
}
$profilefields = array();
foreach (array('studentid', 'preferredname') as $pf) {
if (isset($userdata->$pf)) {
$sanitize = 'sanitize_' . $pf;
if (($USER->$pf = $sanitize($userdata->$pf)) !== '') {
$profilefields[$pf] = $USER->$pf;
}
}
}
try {
// If this authinstance is a parent auth for some xmlrpc authinstance, pass it along to create_user
// so that this username also gets recorded as the username for sso from the remote sites.
$remoteauth = count_records('auth_instance_config', 'field', 'parent', 'value', $authinstance->id) ? $authinstance : null;
create_user($USER, $profilefields, $institution, $remoteauth);
$USER->reanimate($USER->id, $authinstance->id);
}
catch (Exception $e) {
db_rollback();
throw $e;
}
}
if (!$authenticated) {
$SESSION->add_error_msg(get_string('loginfailed'));
return;
}
}
catch (AuthUnknownUserException $e) {
// We weren't able to authenticate the user for some reason that
// probably isn't their fault (e.g. ldap extension not available
// when using ldap authentication)
log_info($e->getMessage());
$SESSION->add_error_msg(get_string('loginfailed'));
return;
}
}
auth_check_admin_section();
ensure_user_account_is_active();
// User is allowed to log in
//$USER->login($userdata);
auth_check_required_fields();
}
/**
* Redirect to the home page if the user is trying to access the admin
* area without permission
*/
function auth_check_admin_section() {
global $USER, $SESSION;
if (defined('ADMIN')) {
$allowed = $USER->get('admin');
}
else if (defined('STAFF')) {
$allowed = $USER->get('admin') || $USER->get('staff');
}
else if (defined('INSTITUTIONALADMIN')) {
$allowed = $USER->get('admin') || $USER->is_institutional_admin();
}
else if (defined('INSTITUTIONALSTAFF')) {
$allowed = $USER->get('admin') || $USER->get('staff') || $USER->is_institutional_admin() || $USER->is_institutional_staff();
}
else {
return;
}
if (!$allowed) {
$SESSION->add_error_msg(get_string('accessforbiddentoadminsection'));
redirect();
}
}
/**
* Die and log the user out if their account is not active.
*
* @param $user The user object to check or null for the currently logged in user.
*/
function ensure_user_account_is_active($user=null) {
$dologout = false;
if (!$user) {
global $USER;
$user = $USER;
$dologout = true;
}
// Check if the user's account has been deleted
if ($user->deleted) {
if ($dologout) {
$user->logout();
}
die_info(get_string('accountdeleted'));
}
// Check if the user's account has expired
if ($user->expiry > 0 && time() > $user->expiry) {
if ($dologout) {
$user->logout();
}
die_info(get_string('accountexpired'));
}
// Check if the user's account has been suspended
if ($user->suspendedcusr) {
$suspendedctime = strftime(get_string('strftimedaydate'), $user->suspendedctime);
$suspendedreason = $user->suspendedreason;
if ($dologout) {
$user->logout();
}
die_info(get_string('accountsuspended', 'mahara', $suspendedctime, $suspendedreason));
}
}
/**
* Removes registration requests that were not completed in the allowed amount of time
*/
function auth_clean_partial_registrations() {
delete_records_sql('DELETE FROM {usr_registration}
WHERE expiry < ?', array(db_format_timestamp(time())));
}
function _email_or_notify($user, $subject, $bodytext, $bodyhtml) {
try {
email_user($user, null, $subject, $bodytext, $bodyhtml);
}
catch (EmailException $e) {
// Send a notification instead - email is invalid or disabled for this user
$message = new StdClass;
$message->users = array($user->id);
$message->subject = $subject;
$message->message = $bodytext;
require_once('activity.php');
activity_occurred('maharamessage', $message);
}
}
/**
* Sends notification e-mails to users in two situations:
*
* - Their account is about to expire. This is controlled by the 'expiry'
* field of the usr table. Once that time has passed, the user may not
* log in.
* - They have not logged in for close to a certain amount of time. If that
* amount of time has passed, the user may not log in.
*
* The actual prevention of users logging in is handled by the authentication
* code. This cron job sends e-mails to notify users that these events will
* happen soon.
*/
function auth_handle_account_expiries() {
// The 'expiry' flag on the usr table
$sitename = get_config('sitename');
$wwwroot = get_config('wwwroot');
$expire = get_config('defaultaccountinactiveexpire');
$warn = get_config('defaultaccountinactivewarn');
$daystoexpire = ceil($warn / 86400) . ' ';
$daystoexpire .= ($daystoexpire == 1) ? get_string('day') : get_string('days');
// Expiry warning messages
if ($users = get_records_sql_array('SELECT u.id, u.username, u.firstname, u.lastname, u.preferredname, u.email, u.admin, u.staff
FROM {usr} u
WHERE ' . db_format_tsfield('u.expiry', false) . ' < ?
AND expirymailsent = 0 AND deleted = 0', array(time() + $warn))) {
foreach ($users as $user) {
$displayname = display_name($user);
_email_or_notify($user, get_string('accountexpirywarning'),
get_string('accountexpirywarningtext', 'mahara', $displayname, $sitename, $daystoexpire, $wwwroot . 'contact.php', $sitename),
get_string('accountexpirywarninghtml', 'mahara', $displayname, $sitename, $daystoexpire, $wwwroot . 'contact.php', $sitename)
);
set_field('usr', 'expirymailsent', 1, 'id', $user->id);
}
}
// Actual expired users
if ($users = get_records_sql_array('SELECT id
FROM {usr}
WHERE ' . db_format_tsfield('expiry', false) . ' < ?', array(time()))) {
// Users have expired!
foreach ($users as $user) {
expire_user($user->id);
}
}
if ($expire) {
// Inactivity (lastlogin is too old)
// MySQL doesn't want to compare intervals, so when editing the where clauses below, make sure
// the intervals are always added to datetimes first.
$dbexpire = db_interval($expire);
$dbwarn = db_interval($warn);
$installationtime = get_config('installation_time');
$lastactive = "COALESCE(u.lastaccess, u.lastlogin, u.ctime, ?)";
// Actual inactive users
if ($users = get_records_sql_array("
SELECT u.id
FROM {usr} u
WHERE $lastactive + $dbexpire < current_timestamp
AND (u.expiry IS NULL OR u.expiry > current_timestamp) AND id > 0", array($installationtime))) {
// Users have become inactive!
foreach ($users as $user) {
deactivate_user($user->id);
}
}
// Inactivity warning emails
if ($users = get_records_sql_array("
SELECT u.id, u.username, u.firstname, u.lastname, u.preferredname, u.email, u.admin, u.staff
FROM {usr} u
WHERE $lastactive + $dbexpire < current_timestamp + $dbwarn
AND (u.expiry IS NULL OR u.expiry > current_timestamp)
AND inactivemailsent = 0 AND deleted = 0 AND id > 0", array($installationtime))) {
foreach ($users as $user) {
$displayname = display_name($user);
_email_or_notify($user, get_string('accountinactivewarning'),
get_string('accountinactivewarningtext', 'mahara', $displayname, $sitename, $daystoexpire, $sitename),
get_string('accountinactivewarninghtml', 'mahara', $displayname, $sitename, $daystoexpire, $sitename)
);
set_field('usr', 'inactivemailsent', 1, 'id', $user->id);
}
}
}
// Institution membership expiry
delete_records_sql('DELETE FROM {usr_institution}
WHERE ' . db_format_tsfield('expiry', false) . ' < ? AND expirymailsent = 1', array(time()));
// Institution membership expiry warnings
if ($users = get_records_sql_array('
SELECT
u.id, u.username, u.firstname, u.lastname, u.preferredname, u.email, u.admin, u.staff,
ui.institution, ui.expiry, i.displayname as institutionname
FROM {usr} u
INNER JOIN {usr_institution} ui ON u.id = ui.usr
INNER JOIN {institution} i ON ui.institution = i.name
WHERE ' . db_format_tsfield('ui.expiry', false) . ' < ?
AND ui.expirymailsent = 0 AND u.deleted = 0', array(time() + $warn))) {
foreach ($users as $user) {
$displayname = display_name($user);
_email_or_notify($user, get_string('institutionmembershipexpirywarning'),
get_string('institutionmembershipexpirywarningtext', 'mahara', $displayname, $user->institutionname,
$sitename, $daystoexpire, $wwwroot . 'contact.php', $sitename),
get_string('institutionmembershipexpirywarninghtml', 'mahara', $displayname, $user->institutionname,
$sitename, $daystoexpire, $wwwroot . 'contact.php', $sitename)
);
set_field('usr_institution', 'expirymailsent', 1, 'usr', $user->id,
'institution', $user->institution);
}
}
}
/**
* Sends notification e-mails to site and institutional admins when:
*
* - An institution is expiring within the institution expiry warning
* period, set in site options.
*
* The actual prevention of users logging in is handled by the authentication
* code. This cron job sends e-mails to notify users that these events will
* happen soon.
*/
function auth_handle_institution_expiries() {
// The 'expiry' flag on the usr table
$sitename = get_config('sitename');
$wwwroot = get_config('wwwroot');
$expire = get_config('institutionautosuspend');
$warn = get_config('institutionexpirynotification');
$daystoexpire = ceil($warn / 86400) . ' ';
$daystoexpire .= ($daystoexpire == 1) ? get_string('day') : get_string('days');
// Get site administrators
$siteadmins = get_records_sql_array('SELECT u.id, u.username, u.firstname, u.lastname, u.preferredname, u.email, u.admin, u.staff FROM {usr} u WHERE u.admin = 1', array());
// Expiry warning messages
if ($institutions = get_records_sql_array(
'SELECT i.name, i.displayname FROM {institution} i ' .
'WHERE ' . db_format_tsfield('i.expiry', false) . ' < ? AND suspended != 1 AND expirymailsent != 1',
array(time() + $warn))) {
foreach ($institutions as $institution) {
$institution_displayname = $institution->displayname;
// Email site administrators
foreach ($siteadmins as $user) {
$user_displayname = display_name($user);
_email_or_notify($user, get_string('institutionexpirywarning'),
get_string('institutionexpirywarningtext_site', 'mahara', $user_displayname, $institution_displayname, $daystoexpire, $sitename, $sitename),
get_string('institutionexpirywarninghtml_site', 'mahara', $user_displayname, $institution_displayname, $daystoexpire, $sitename, $sitename)
);
}
// Email institutional administrators
$institutionaladmins = get_records_sql_array(
'SELECT u.id, u.username, u.expiry, u.staff, u.admin AS siteadmin, ui.admin AS institutionadmin, u.firstname, u.lastname, u.email ' .
'FROM {usr_institution} ui JOIN {usr} u ON (ui.usr = u.id) WHERE ui.admin = 1', array()
);
foreach ($institutionaladmins as $user) {
$user_displayname = display_name($user);
_email_or_notify($user, get_string('institutionexpirywarning'),
get_string('institutionexpirywarningtext_institution', 'mahara', $user_displayname, $institution_displayname, $sitename, $daystoexpire, $wwwroot . 'contact.php', $sitename),
get_string('institutionexpirywarninghtml_institution', 'mahara', $user_displayname, $institution_displayname, $sitename, $daystoexpire, $wwwroot . 'contact.php', $sitename)
);
}
set_field('institution', 'expirymailsent', 1, 'name', $institution->name);
}
}
// If we can automatically suspend expired institutions
$autosuspend = get_config('institutionautosuspend');
if ($autosuspend) {
// Actual expired institutions
if ($institutions = get_records_sql_array(
'SELECT name FROM {institution} ' .
'WHERE ' . db_format_tsfield('expiry', false) . ' < ?', array(time()))) {
// Institutions have expired!
foreach ($institutions as $institution) {
set_field('institution', 'suspended', 1, 'name', $institution->name);
}
}
}
}
/**
* Clears out old session files
*
* This should be run once every now and then (once a day is good), to clean
* out session files of users whose sessions have timed out.
*/
function auth_remove_old_session_files() {
$basedir = get_config('dataroot') . 'sessions/';
// delete sessions older than the session timeout plus 2 days
$mintime = time() - get_config('session_timeout') - 2 * 24 * 60 * 60;
// Session files are stored in a three tier md5sum layout
// The actual files are stored in the third directory
// This loops through all three directories, then checks the files for age
$iter1 = new DirectoryIterator($basedir);
foreach ($iter1 as $dir1) {
if ($dir1->isDot()) continue;
$dir1path = $dir1->getPath() . '/' . $dir1->getFilename();
$iter2 = new DirectoryIterator($dir1path);
foreach ($iter2 as $dir2) {
if ($dir2->isDot()) continue;
$dir2path = $dir2->getPath() . '/' . $dir2->getFilename();
$iter3 = new DirectoryIterator($dir2path);
foreach ($iter3 as $dir3) {
if ($dir3->isDot()) continue;
$dir3path = $dir3->getPath() . '/' . $dir3->getFilename();
$fileiter = new DirectoryIterator($dir3path);
foreach ($fileiter as $file) {
if ($file->isFile() && $file->getCTime() < $mintime) {
unlink($file->getPath() . '/' . $file->getFilename());
}
}
}
}
}
// Throw away records of old login sessions. Should check whether any are still alive.
delete_records_select('usr_session', 'ctime < ?', array(db_format_timestamp(time() - 86400 * 30)));
}
/**
* Generates the login form for the sideblock
*
* {@internal{Not sure why this form definition doesn't use
* auth_get_login_form, but keep that in mind when making changes.}}
*/
function auth_generate_login_form() {
require_once('pieforms/pieform.php');
if (!get_config('installed')) {
return;
}
$elements = auth_get_login_form_elements();
$loginform = get_login_form_js(pieform(array(
'name' => 'login',
'renderer' => 'div',
'submit' => false,
'plugintype' => 'auth',
'pluginname' => 'internal',
'autofocus' => false,
'elements' => $elements,
)));
return $loginform;
}
/**
* Given a form, an array of values with 'password1' and 'password2'
* indices and a user, validate that the user can change their password to
* the one in $values.
*
* This provides one place where validation of passwords can be done. This is
* used by:
* - registration
* - user forgot password
* - user changing password on their account page
* - user forced to change their password by the <kbd>passwordchange</kbd>
* flag on the <kbd>usr</kbd> table.
*
* The password is checked for:
* - Being in valid form according to the rules of the authentication method
* for the user
* - Not being an easy password (a blacklist of strings, NOT a length check or
* similar), including being the user's username
* - Both values being equal
*
* @param Pieform $form The form to validate
* @param array $values The values passed through
* @param string $authplugin The authentication plugin that the user uses
*/
function password_validate(Pieform $form, $values, $user) {
$authobj = AuthFactory::create($user->authinstance);
if (!$form->get_error('password1') && !$authobj->is_password_valid($values['password1'])) {
$form->set_error('password1', get_string('passwordinvalidform', "auth.$authobj->type"));
}
$suckypasswords = array(
'mahara', 'password', $user->username, 'abc123'
);
if (!$form->get_error('password1') && in_array($values['password1'], $suckypasswords)) {
$form->set_error('password1', get_string('passwordtooeasy'));
}
if (!$form->get_error('password1') && $values['password1'] != $values['password2']) {
$form->set_error('password2', get_string('passwordsdonotmatch'));
}
}
function auth_get_random_salt() {
return substr(md5(rand(1000000, 9999999)), 2, 8);
}
// Add salt and encrypt the pw for a user, if their auth instance allows for it
function reset_password($user, $resetpasswordchange=true, $quickhash=false) {
$userobj = new User();
$userobj->find_by_id($user->id);
$authobj = AuthFactory::create($user->authinstance);
if (isset($user->password) && $user->password != '' && method_exists($authobj, 'change_password')) {
$authobj->change_password($userobj, $user->password, $resetpasswordchange, $quickhash);
}
else {
$userobj->password = '';
$userobj->salt = auth_get_random_salt();
$userobj->commit();
}
}
function user_login_tries_to_zero() {
execute_sql('UPDATE {usr} SET logintries = 0 WHERE logintries > 0');
}
function auth_generate_registration_form($formname, $authname='internal', $goto) {
require_once(get_config('libroot').'antispam.php');
$elements = array(
'firstname' => array(
'type' => 'text',
'title' => get_string('firstname'),
'rules' => array(
'required' => true
)
),
'lastname' => array(
'type' => 'text',
'title' => get_string('lastname'),
'rules' => array(
'required' => true
)
),
'email' => array(
'type' => 'text',
'title' => get_string('emailaddress'),
'rules' => array(
'required' => true,
'email' => true
)
)
);
$sql = 'SELECT
i.*
FROM
{institution} i,
{auth_instance} ai
WHERE
ai.authname = ? AND
ai.institution = i.name AND
i.registerallowed = 1';
$institutions = get_records_sql_array($sql, array($authname));
$registerconfirm = array();
$reason = false;
if (count($institutions) > 0) {
$options = array();
foreach ($institutions as $institution) {
$options[$institution->name] = $institution->displayname;
if ($registerconfirm[$institution->name] = $institution->registerconfirm) {
if ($authname != 'internal') {
$authinstance = get_record('auth_instance', 'institution', $institution->name, 'authname', $authname);
$auth = AuthFactory::create($authinstance->id);
$registerconfirm[$institution->name] = !$auth->weautocreateusers;
}
if ($registerconfirm[$institution->name]) {
$options[$institution->name] .= ' (' . get_string('approvalrequired') . ')';
$reason = true;
}
}
}
natcasesort($options);
if (count($institutions) > 1) {
array_unshift($options, get_string('chooseinstitution', 'mahara'));
}
$elements['institution'] = array(
'type' => 'select',
'title' => get_string('institution'),
'options' => $options,
'rules' => array(
'required' => true
)
);
}
else {
return;
}
if ($reason) {
$elements['reason'] = array(
'type' => 'textarea',
'title' => get_string('registrationreason', 'auth.internal'),
'description' => get_string('registrationreasondesc1', 'auth.internal'),
'class' => 'js-hidden',
'rows' => 4,
'cols' => 60,
);
}
$registerterms = get_config('registerterms');
if ($registerterms) {
$elements['tandc'] = array(
'type' => 'radio',
'title' => get_string('iagreetothetermsandconditions', 'auth.internal'),
'options' => array(
'yes' => get_string('yes'),
'no' => get_string('no')
),
'defaultvalue' => 'no',
'rules' => array(
'required' => true
),
'separator' => ' '
);
}
$elements['submit'] = array(
'type' => 'submit',
'value' => get_string('register'),
);
$elements['goto'] = array(
'type' => 'hidden',
'value' => $goto,
);
// swap the name and email fields at random
if (rand(0,1)) {
$emailelement = $elements['email'];
unset($elements['email']);
$elements = array('email' => $emailelement) + $elements;
}
$form = array(
'name' => $formname,
'validatecallback' => 'auth_' . $formname . '_validate',
'successcallback' => 'auth_' . $formname . '_submit',
'method' => 'post',
'action' => '',
'showdescriptiononerror' => false,
'renderer' => 'table',
'elements' => $elements,
'spam' => array(
'secret' => get_config('formsecret'),
'mintime' => 5,
'hash' => array('firstname', 'lastname', 'email', 'institution', 'reason', 'tandc', 'submit'),
),
);
if ($authname == 'internal') {
$form['plugintype'] = 'core';
$form['pluginname'] = 'register';
}
return array($form, $registerconfirm);
}
function auth_generate_registration_form_js($aform, $registerconfirm) {
// The javascript needs to refer to field names, but they are obfuscated in this form,
// so construct and build the form in separate steps, so we can get the field names.
$form = new Pieform($aform);
$institutionid = $form->get_name() . '_' . $form->hashedfields['institution'];
$reasonid = $form->get_name() . '_' . $form->hashedfields['reason'];
$formhtml = $form->build();
if (count($registerconfirm) == 1) {
$js = '
$j(function() {
$j("#' . $reasonid . '_container").removeClass("js-hidden");
$j("#' . $reasonid . '_container textarea").removeClass("js-hidden");
$j("#' . $reasonid . '_container").next("tr.textarea").removeClass("js-hidden");
});
';
}
else {
$js = '
var registerconfirm = ' . json_encode($registerconfirm) . ';
$j(function() {
$j("#' . $institutionid . '").change(function() {
if (this.value && registerconfirm[this.value] == 1) {
$j("#' . $reasonid . '_container").removeClass("js-hidden");
$j("#' . $reasonid . '_container textarea").removeClass("js-hidden");
$j("#' . $reasonid . '_container").next("tr.textarea").removeClass("js-hidden");
}
else {
$j("#' . $reasonid . '_container").addClass("js-hidden");
$j("#' . $reasonid . '_container textarea").addClass("js-hidden");
$j("#' . $reasonid . '_container").next("tr.textarea").addClass("js-hidden");
}
});
});
';
}
return array($formhtml, $js);
}
/**
* @todo add note: because the form select thing will eventually enforce
* that the result for $values['institution'] was in the original lot,
* and because that only allows authmethods that use 'internal' auth, we
* can guarantee that the auth method is internal
*/
function auth_register_validate(Pieform $form, $values) {
global $SESSION;
$registerterms = get_config('registerterms');
$spamtrap = new_spam_trap(array(
array(
'type' => 'name',
'value' => $values['firstname'],
),
array(
'type' => 'name',
'value' => $values['lastname'],
),
array(
'type' => 'email',
'value' => $values['email'],
),
));
if ($form->spam_error() || $spamtrap->is_spam()) {
$msg = get_string('formerror');
$emailcontact = get_config('emailcontact');
if (!empty($emailcontact)) {
$msg .= ' ' . get_string('formerroremail', 'mahara', $emailcontact, $emailcontact);
}
$form->set_error(null, $msg);
return;
}
$institution = $values['institution'];
safe_require('auth', 'internal');
// First name and last name must contain at least one non whitespace
// character, so that there's something to read
if (!$form->get_error('firstname') && !preg_match('/\S/', $values['firstname'])) {
$form->set_error('firstname', $form->i18n('required'));
}
if (!$form->get_error('lastname') && !preg_match('/\S/', $values['lastname'])) {
$form->set_error('lastname', $form->i18n('required'));
}
// The e-mail address cannot already be in the system
if (!$form->get_error('email')
&& (record_exists('usr', 'email', $values['email'])
|| record_exists('artefact_internal_profile_email', 'email', $values['email']))) {
$form->set_error('email', get_string('emailalreadytaken', 'auth.internal'));
}
// If the user hasn't agreed to the terms and conditions, don't bother
if ($registerterms && $values['tandc'] != 'yes') {
$form->set_error('tandc', get_string('youmaynotregisterwithouttandc', 'auth.internal'));
}
$institution = get_record_sql('
SELECT
i.name, i.maxuseraccounts, i.registerallowed, COUNT(u.id)
FROM {institution} i
LEFT OUTER JOIN {usr_institution} ui ON ui.institution = i.name
LEFT OUTER JOIN {usr} u ON (ui.usr = u.id AND u.deleted = 0)
WHERE
i.name = ?
GROUP BY
i.name, i.maxuseraccounts, i.registerallowed', array($institution));
if (!empty($institution->maxuseraccounts) && $institution->count >= $institution->maxuseraccounts) {
$form->set_error($hashed['institution'], get_string('institutionfull'));
}
if (!$institution || !$institution->registerallowed) {
$form->set_error('institution', get_string('registrationnotallowed'));
}
}
function auth_register_submit(Pieform $form, $values) {
global $SESSION;
safe_require('auth', 'internal');
$values['key'] = get_random_key();
$values['lang'] = $SESSION->get('lang');
// If the institution requires approval, mark the record as pending
// @todo the expiry date should be configurable
if ($confirm = get_field('institution', 'registerconfirm', 'name', $values['institution'])) {
if (isset($values['authtype']) && $values['authtype'] != 'internal') {
$authinstance = get_record('auth_instance', 'institution', $values['institution'], 'authname', $values['authtype'] ? $values['authtype'] : 'internal');
$auth = AuthFactory::create($authinstance->id);
$confirm = !$auth->weautocreateusers;
}
if ($confirm) {
$values['pending'] = 1;
$values['expiry'] = db_format_timestamp(time() + (86400 * 14)); // now + 2 weeks
}
else {
$values['pending'] = 0;
$values['expiry'] = db_format_timestamp(time() + 86400);
}
}
else {
$values['pending'] = 0;
$values['expiry'] = db_format_timestamp(time() + 86400);
}
if (function_exists('local_register_submit')) {
local_register_submit($values);
}
try {
if (!record_exists('usr_registration', 'email', $values['email'])) {
insert_record('usr_registration', $values);
}
else {
update_record('usr_registration', $values, array('email' => $values['email']));
}
$user =(object) $values;
$user->admin = 0;
$user->staff = 0;
// If the institution requires approval, notify institutional admins.
if ($confirm) {
$fullname = sprintf("%s %s", trim($user->firstname), trim($user->lastname));
$institution = new Institution($values['institution']);
$pendingregistrationslink = sprintf("%sadmin/users/pendingregistrations.php?institution=%s", get_config('wwwroot'), $values['institution']);
// list of admins for this institution
if (count($institution->admins()) > 0) {
$admins = $institution->admins();
}
else {
// use site admins if the institution doesn't have any
$admins = get_column('usr', 'id', 'admin', 1, 'deleted', 0);
}
// email each admin
// @TODO Respect the notification preferences of the admins.
foreach ($admins as $admin) {
$adminuser = new User();
$adminuser->find_by_id($admin);
email_user($adminuser, null,
get_string('pendingregistrationadminemailsubject', 'auth.internal', $institution->displayname, get_config('sitename')),
get_string('pendingregistrationadminemailtext', 'auth.internal',
$adminuser->firstname, $institution->displayname, $pendingregistrationslink,
$fullname, $values['email'], $values['reason'], get_config('sitename')),
get_string('pendingregistrationadminemailhtml', 'auth.internal',
$adminuser->firstname, $institution->displayname, $pendingregistrationslink, $pendingregistrationslink,
$fullname, $values['email'], $values['reason'], get_config('sitename'))
);
}
email_user($user, null,
get_string('approvalemailsubject', 'auth.internal', get_config('sitename')),
get_string('approvalemailmessagetext', 'auth.internal', $values['firstname'], get_config('sitename'), get_config('sitename')),
get_string('approvalemailmessagehtml', 'auth.internal', $values['firstname'], get_config('sitename'), get_config('sitename')));
$_SESSION['registeredokawaiting'] = true;
}
else {
if (isset($values['authtype']) && $values['authtype'] == 'browserid') {
redirect('/register.php?key='.$values['key']);
}
else {
email_user($user, null,
get_string('registeredemailsubject', 'auth.internal', get_config('sitename')),
get_string('registeredemailmessagetext', 'auth.internal', $values['firstname'], get_config('sitename'), get_config('wwwroot'), $values['key'], get_config('sitename')),
get_string('registeredemailmessagehtml', 'auth.internal', $values['firstname'], get_config('sitename'), get_config('wwwroot'), $values['key'], get_config('wwwroot'), $values['key'], get_config('sitename')));
}
// Add a marker in the session to say that the user has registered
$_SESSION['registered'] = true;
}
}
catch (EmailException $e) {
log_warn($e);
die_info(get_string('registrationunsuccessful', 'auth.internal'));
}
catch (SQLException $e) {
log_warn($e);
die_info(get_string('registrationunsuccessful', 'auth.internal'));
}
redirect($values['goto']);
}
class PluginAuth extends Plugin {
public static function get_event_subscriptions() {
$subscriptions = array();
$activecheck = new StdClass;
$activecheck->plugin = 'internal';
$activecheck->event = 'suspenduser';
$activecheck->callfunction = 'update_active_flag';
$subscriptions[] = clone $activecheck;
$activecheck->event = 'unsuspenduser';
$subscriptions[] = clone $activecheck;
$activecheck->event = 'deleteuser';
$subscriptions[] = clone $activecheck;
$activecheck->event = 'undeleteuser';
$subscriptions[] = clone $activecheck;
$activecheck->event = 'expireuser';
$subscriptions[] = clone $activecheck;
$activecheck->event = 'unexpireuser';
$subscriptions[] = clone $activecheck;
$activecheck->event = 'deactivateuser';
$subscriptions[] = clone $activecheck;
$activecheck->event = 'activateuser';
$subscriptions[] = clone $activecheck;
return $subscriptions;
}
/**
* Can be overridden by plugins to assert when they are able to be used.
* For example, a plugin might check that a certain PHP extension is loaded
*/
public static function is_usable() {
return true;
}
public static function update_active_flag($event, $user) {
if (!isset($user['id'])) {
log_warn("update_active_flag called without a user id");
}
if ($user['id'] === 0 || $user['id'] === '0') {
return;
}
$active = true;
// ensure we have everything we need
$user = get_user($user['id']);
$inactivetime = get_config('defaultaccountinactiveexpire');
if ($user->suspendedcusr) {
$active = false;
}
else if ($user->expiry && $user->expiry < time()) {
$active = false;
}
else if ($inactivetime) {
$lastactive = max($user->lastlogin, $user->lastaccess, $user->ctime);
if ($lastactive && ($lastactive + $inactivetime < time())) {
$active = false;
}
}
else if ($user->deleted) {
$active = false;
}
if ($active != $user->active) {
set_field('usr', 'active', (int)$active, 'id', $user->id);
}
}
public static function can_be_disabled() {
return false;
}
/**
* Can be overridden by plugins that need to inject more
* pieform elements into the login form.
*/
public static function login_form_elements() {
return false;
}
/**
* Can be overridden by plugins that need to inject more
* Javascript to make the login form work.
*/
public static function login_form_js() {
return false;
}
/**
* Can be overridden by plugins that inject the things they need
* in the login form and don't need the standard elements.
*/
public static function need_basic_login_form() {
return true;
}
}
| universityofglasgow/mahara | htdocs/auth/lib.php | PHP | gpl-3.0 | 84,268 |
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.uirendering.cts.testclasses;
import android.annotation.ColorInt;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.MediumTest;
import android.uirendering.cts.bitmapverifiers.ColorVerifier;
import android.uirendering.cts.testinfrastructure.ActivityTestBase;
import android.uirendering.cts.testinfrastructure.ViewInitializer;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.uirendering.cts.R;
import android.widget.FrameLayout;
import org.junit.Test;
import org.junit.runner.RunWith;
@MediumTest
@RunWith(AndroidJUnit4.class)
public class LayerTests extends ActivityTestBase {
@Test
public void testLayerPaintAlpha() {
// red channel full strength, other channels 75% strength
// (since 25% alpha red subtracts from them)
@ColorInt
final int expectedColor = Color.rgb(255, 191, 191);
createTest()
.addLayout(R.layout.simple_red_layout, (ViewInitializer) view -> {
// reduce alpha by 50%
Paint paint = new Paint();
paint.setAlpha(128);
view.setLayerType(View.LAYER_TYPE_HARDWARE, paint);
// reduce alpha by another 50% (ensuring two alphas combine correctly)
view.setAlpha(0.5f);
})
.runWithVerifier(new ColorVerifier(expectedColor));
}
@Test
public void testLayerPaintColorFilter() {
// Red, fully desaturated. Note that it's not 255/3 in each channel.
// See ColorMatrix#setSaturation()
@ColorInt
final int expectedColor = Color.rgb(54, 54, 54);
createTest()
.addLayout(R.layout.simple_red_layout, (ViewInitializer) view -> {
Paint paint = new Paint();
ColorMatrix desatMatrix = new ColorMatrix();
desatMatrix.setSaturation(0.0f);
paint.setColorFilter(new ColorMatrixColorFilter(desatMatrix));
view.setLayerType(View.LAYER_TYPE_HARDWARE, paint);
})
.runWithVerifier(new ColorVerifier(expectedColor));
}
@Test
public void testLayerPaintBlend() {
// Red, drawn underneath opaque white, so output should be white.
// TODO: consider doing more interesting blending test here
@ColorInt
final int expectedColor = Color.WHITE;
createTest()
.addLayout(R.layout.simple_red_layout, (ViewInitializer) view -> {
Paint paint = new Paint();
/* Note that when drawing in SW, we're blending within an otherwise empty
* SW layer, as opposed to in the frame buffer (which has a white
* background).
*
* For this reason we use just use DST, which just throws out the SRC
* content, regardless of the DST alpha channel.
*/
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST));
view.setLayerType(View.LAYER_TYPE_HARDWARE, paint);
})
.runWithVerifier(new ColorVerifier(expectedColor));
}
@Test
public void testLayerInitialSizeZero() {
createTest()
.addLayout(R.layout.frame_layout, view -> {
FrameLayout root = (FrameLayout) view.findViewById(R.id.frame_layout);
// disable clipChildren, to ensure children aren't rejected by bounds
root.setClipChildren(false);
for (int i = 0; i < 2; i++) {
View child = new View(view.getContext());
child.setLayerType(View.LAYER_TYPE_HARDWARE, null);
// add rendering content, so View isn't skipped at render time
child.setBackgroundColor(Color.RED);
// add one with width=0, one with height=0
root.addView(child, new FrameLayout.LayoutParams(
i == 0 ? 0 : 90,
i == 0 ? 90 : 0,
Gravity.TOP | Gravity.LEFT));
}
}, true)
.runWithVerifier(new ColorVerifier(Color.WHITE, 0 /* zero tolerance */));
}
@Test
public void testLayerResizeZero() {
createTest()
.addLayout(R.layout.frame_layout, view -> {
FrameLayout root = (FrameLayout) view.findViewById(R.id.frame_layout);
// disable clipChildren, to ensure child isn't rejected by bounds
root.setClipChildren(false);
for (int i = 0; i < 2; i++) {
View child = new View(view.getContext());
child.setLayerType(View.LAYER_TYPE_HARDWARE, null);
// add rendering content, so View isn't skipped at render time
child.setBackgroundColor(Color.BLUE);
root.addView(child, new FrameLayout.LayoutParams(90, 90,
Gravity.TOP | Gravity.LEFT));
}
// post invalid dimensions a few frames in, so initial layer allocation succeeds
// NOTE: this must execute before capture, or verification will fail
root.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
int mDrawCount = 0;
@Override
public boolean onPreDraw() {
if (mDrawCount++ == 5) {
root.getChildAt(0).getLayoutParams().width = 0;
root.getChildAt(0).requestLayout();
root.getChildAt(1).getLayoutParams().height = 0;
root.getChildAt(1).requestLayout();
}
return true;
}
});
}, true)
.runWithVerifier(new ColorVerifier(Color.WHITE, 0 /* zero tolerance */));
}
}
| wiki2014/Learning-Summary | alps/cts/tests/tests/uirendering/src/android/uirendering/cts/testclasses/LayerTests.java | Java | gpl-3.0 | 7,246 |
// Copyright © 2016 Gary W. Hudson Esq.
// Released under GNU GPL 3.0
var lzwh = (function() {var z={
Decode:function(p)
{function f(){--h?k>>=1:(k=p.charCodeAt(q++)-32,h=15);return k&1}var h=1,q=0,k=0,e=[""],l=[],g=0,m=0,c="",d,a=0,n,b;
do{m&&(e[g-1]=c.charAt(0));m=a;l.push(c);d=0;for(a=g++;d!=a;)f()?d=(d+a>>1)+1:a=d+a>>1;if(d)c=l[d]+e[d],e[g]=c.charAt(0)
else{b=1;do for(n=8;n--;b*=2)d+=b*f();while(f());d&&(c=String.fromCharCode(d-1),e[g]="")}}while(d);return l.join("")},
Encode:function(p)
{function f(b){b&&(k|=e);16384==e?(q.push(String.fromCharCode(k+32)),e=1,k=0):e<<=1}function h(b,d){for(var a=0,e,c=l++;a!=c;)
e=a+c>>1,b>e?(a=e+1,f(1)):(c=e,f(0));if(!a){-1!=b&&(a=d+1);do{for(c=8;c--;a=(a-a%2)/2)f(a%2);f(a)}while(a)}}for(var q=[],k=0,
e=1,l=0,g=[],m=[],c=0,d=p.length,a,n,b=0;c<d;)a=p.charCodeAt(c++),g[b]?(n=g[b].indexOf(a),-1==n?(g[b].push(a),m[b].push(l+1),
c-=b?1:0,h(b,a),b=0):b=m[b][n]):(g[b]=[a],m[b]=[l+1],c-=b?1:0,h(b,a),b=0);b&&h(b,0);for(h(-1,0);1!=e;)f(0);return q.join("")}
};return z})();
if(typeof define==='function'&&define.amd)define(function(){return lzw})
else if(typeof module!=='undefined'&&module!=null)module.exports=lzw;
| GWHudson/lzwh | lzwhutf16-min.js | JavaScript | gpl-3.0 | 1,186 |
<?php
class ModelDefinitionForumCategory extends Model {
public function addCategory($data) {
$this->db->query("INSERT INTO " . DB_PREFIX . "forum_category SET parent_id = '" . (int)$data['parent_id'] . "', `top` = '" . (isset($data['top']) ? (int)$data['top'] : 0) . "', `column` = '" . (int)$data['column'] . "', sort_order = '" . (int)$data['sort_order'] . "', status = '" . (int)$data['status'] . "', date_modified = NOW(), date_added = NOW()");
$forum_category_id = $this->db->getLastId();
if (isset($data['image'])) {
$this->db->query("UPDATE " . DB_PREFIX . "forum_category SET image = '" . $this->db->escape($data['image']) . "' WHERE forum_category_id = '" . (int)$forum_category_id . "'");
}
foreach ($data['category_description'] as $language_id => $value) {
$this->db->query("INSERT INTO " . DB_PREFIX . "forum_category_description SET forum_category_id = '" . (int)$forum_category_id . "', language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "', description = '" . $this->db->escape($value['description']) . "', meta_title = '" . $this->db->escape($value['meta_title']) . "', meta_description = '" . $this->db->escape($value['meta_description']) . "', meta_keyword = '" . $this->db->escape($value['meta_keyword']) . "'");
}
$level = 0;
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "forum_category_path` WHERE forum_category_id = '" . (int)$data['parent_id'] . "' ORDER BY `level` ASC");
foreach ($query->rows as $result) {
$this->db->query("INSERT INTO `" . DB_PREFIX . "forum_category_path` SET `forum_category_id` = '" . (int)$forum_category_id . "', `path_id` = '" . (int)$result['path_id'] . "', `level` = '" . (int)$level . "'");
$level++;
}
$this->cache->delete('category');
return $forum_category_id;
}
public function editCategory($forum_category_id, $data) {
$this->db->query("UPDATE " . DB_PREFIX . "forum_category SET parent_id = '" . (int)$data['parent_id'] . "', `top` = '" . (isset($data['top']) ? (int)$data['top'] : 0) . "', `column` = '" . (int)$data['column'] . "', sort_order = '" . (int)$data['sort_order'] . "', status = '" . (int)$data['status'] . "', date_modified = NOW() WHERE forum_category_id = '" . (int)$forum_category_id . "'");
if (isset($data['image'])) {
$this->db->query("UPDATE " . DB_PREFIX . "forum_category SET image = '" . $this->db->escape($data['image']) . "' WHERE forum_category_id = '" . (int)$forum_category_id . "'");
}
$this->db->query("DELETE FROM " . DB_PREFIX . "forum_category_description WHERE forum_category_id = '" . (int)$forum_category_id . "'");
foreach ($data['category_description'] as $language_id => $value) {
$this->db->query("INSERT INTO " . DB_PREFIX . "forum_category_description SET forum_category_id = '" . (int)$forum_category_id . "', language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "', description = '" . $this->db->escape($value['description']) . "', meta_title = '" . $this->db->escape($value['meta_title']) . "', meta_description = '" . $this->db->escape($value['meta_description']) . "', meta_keyword = '" . $this->db->escape($value['meta_keyword']) . "'");
}
// MySQL Hierarchical Data Closure Table Pattern
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "forum_category_path` WHERE path_id = '" . (int)$forum_category_id . "' ORDER BY level ASC");
if ($query->rows) {
foreach ($query->rows as $category_path) {
// Delete the path below the current one
$this->db->query("DELETE FROM `" . DB_PREFIX . "forum_category_path` WHERE forum_category_id = '" . (int)$category_path['forum_category_id'] . "' AND level < '" . (int)$category_path['level'] . "'");
$path = array();
// Get the nodes new parents
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "forum_category_path` WHERE forum_category_id = '" . (int)$data['parent_id'] . "' ORDER BY level ASC");
foreach ($query->rows as $result) {
$path[] = $result['path_id'];
}
// Get whats left of the nodes current path
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "forum_category_path` WHERE forum_category_id = '" . (int)$category_path['forum_category_id'] . "' ORDER BY level ASC");
foreach ($query->rows as $result) {
$path[] = $result['path_id'];
}
// Combine the paths with a new level
$level = 0;
foreach ($path as $path_id) {
$this->db->query("REPLACE INTO `" . DB_PREFIX . "forum_category_path` SET forum_category_id = '" . (int)$category_path['forum_category_id'] . "', `path_id` = '" . (int)$path_id . "', level = '" . (int)$level . "'");
$level++;
}
}
} else {
// Delete the path below the current one
$this->db->query("DELETE FROM `" . DB_PREFIX . "forum_category_path` WHERE forum_category_id = '" . (int)$forum_category_id . "'");
// Fix for records with no paths
$level = 0;
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "forum_category_path` WHERE forum_category_id = '" . (int)$data['parent_id'] . "' ORDER BY level ASC");
foreach ($query->rows as $result) {
$this->db->query("INSERT INTO `" . DB_PREFIX . "forum_category_path` SET forum_category_id = '" . (int)$forum_category_id . "', `path_id` = '" . (int)$result['path_id'] . "', level = '" . (int)$level . "'");
$level++;
}
$this->db->query("REPLACE INTO `" . DB_PREFIX . "forum_category_path` SET forum_category_id = '" . (int)$forum_category_id . "', `path_id` = '" . (int)$forum_category_id . "', level = '" . (int)$level . "'");
}
$this->cache->delete('category');
}
public function deleteCategory($forum_category_id) {
$this->db->query("DELETE FROM " . DB_PREFIX . "forum_category_path WHERE forum_category_id = '" . (int)$forum_category_id . "'");
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "forum_category_path WHERE path_id = '" . (int)$forum_category_id . "'");
foreach ($query->rows as $result) {
$this->deleteCategory($result['forum_category_id']);
}
$this->db->query("DELETE FROM " . DB_PREFIX . "forum_category WHERE forum_category_id = '" . (int)$forum_category_id . "'");
$this->db->query("DELETE FROM " . DB_PREFIX . "forum_category_description WHERE forum_category_id = '" . (int)$forum_category_id . "'");
$this->cache->delete('category');
}
public function repairCategories($parent_id = 0) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "forum_category WHERE parent_id = '" . (int)$parent_id . "'");
foreach ($query->rows as $category) {
// Delete the path below the current one
$this->db->query("DELETE FROM `" . DB_PREFIX . "forum_category_path` WHERE forum_category_id = '" . (int)$category['forum_category_id'] . "'");
// Fix for records with no paths
$level = 0;
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "forum_category_path` WHERE forum_category_id = '" . (int)$parent_id . "' ORDER BY level ASC");
foreach ($query->rows as $result) {
$this->db->query("INSERT INTO `" . DB_PREFIX . "forum_category_path` SET forum_category_id = '" . (int)$category['forum_category_id'] . "', `path_id` = '" . (int)$result['path_id'] . "', level = '" . (int)$level . "'");
$level++;
}
$this->db->query("REPLACE INTO `" . DB_PREFIX . "forum_category_path` SET forum_category_id = '" . (int)$category['forum_category_id'] . "', `path_id` = '" . (int)$category['forum_category_id'] . "', level = '" . (int)$level . "'");
$this->repairCategories($category['forum_category_id']);
}
}
public function getCategory($forum_category_id) {
$query = $this->db->query("SELECT DISTINCT *, (SELECT GROUP_CONCAT(cd1.name ORDER BY level SEPARATOR ' > ') FROM " . DB_PREFIX . "forum_category_path cp LEFT JOIN " . DB_PREFIX . "forum_category_description cd1 ON (cp.path_id = cd1.forum_category_id AND cp.forum_category_id != cp.path_id) WHERE cp.forum_category_id = c.forum_category_id AND cd1.language_id = '" . (int)$this->config->get('config_language_id') . "' GROUP BY cp.forum_category_id) AS path, FROM " . DB_PREFIX . "forum_category c LEFT JOIN " . DB_PREFIX . "forum_category_description cd2 ON (c.forum_category_id = cd2.forum_category_id) WHERE c.forum_category_id = '" . (int)$forum_category_id . "' AND cd2.language_id = '" . (int)$this->config->get('config_language_id') . "'");
return $query->row;
}
public function getCategories($data = array()) {
$sql = "SELECT cp.forum_category_id AS forum_category_id, GROUP_CONCAT(cd1.name ORDER BY cp.level SEPARATOR ' > ') AS name, c1.parent_id, c1.sort_order FROM " . DB_PREFIX . "forum_category_path cp LEFT JOIN " . DB_PREFIX . "forum_category c1 ON (cp.forum_category_id = c1.forum_category_id) LEFT JOIN " . DB_PREFIX . "forum_category c2 ON (cp.path_id = c2.forum_category_id) LEFT JOIN " . DB_PREFIX . "forum_category_description cd1 ON (cp.path_id = cd1.forum_category_id) LEFT JOIN " . DB_PREFIX . "forum_category_description cd2 ON (cp.forum_category_id = cd2.forum_category_id) WHERE cd1.language_id = '" . (int)$this->config->get('config_language_id') . "' AND cd2.language_id = '" . (int)$this->config->get('config_language_id') . "'";
if (!empty($data['filter_name'])) {
$sql .= " AND cd2.name LIKE '%" . $this->db->escape($data['filter_name']) . "%'";
}
$sql .= " GROUP BY cp.forum_category_id";
$sort_data = array(
'name',
'sort_order'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY sort_order";
}
if (isset($data['order']) && ($data['order'] == 'DESC')) {
$sql .= " DESC";
} else {
$sql .= " ASC";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->rows;
}
public function getCategoryDescriptions($forum_category_id) {
$category_description_data = array();
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "forum_category_description WHERE forum_category_id = '" . (int)$forum_category_id . "'");
foreach ($query->rows as $result) {
$category_description_data[$result['language_id']] = array(
'name' => $result['name'],
'meta_title' => $result['meta_title'],
'meta_description' => $result['meta_description'],
'meta_keyword' => $result['meta_keyword'],
'description' => $result['description']
);
}
return $category_description_data;
}
public function getCategoryPath($forum_category_id) {
$query = $this->db->query("SELECT forum_category_id, path_id, level FROM " . DB_PREFIX . "forum_category_path WHERE forum_category_id = '" . (int)$forum_category_id . "'");
return $query->rows;
}
public function getTotalCategories() {
$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "forum_category");
return $query->row['total'];
}
} | fahrettinaksoy/anet-support-center | public_html/admin/model/definition/forum_category.php | PHP | gpl-3.0 | 11,068 |
#include "../../../corpuslib_headers.h"
#include "ClassifyLayer.h"
namespace Corpus
{
namespace Tokenisation
{
namespace Layers
{
boost::shared_ptr<SPretoken> CClassifyLayer::GetNext()
{
// fetch next
boost::shared_ptr<SPretoken> current(lower->GetNext());
// try to classify only uknown pretokens (i.e. of ign class)
if(current && current->flexClass == cf_ign)
{
if(!GetCore()->Classify(*current))
{
// if the regexes fail, assume it's a symbol
current->flexClass = cf_tsym;
current->attrValues = gc_none;
}
}
return current;
} // GetNext
} // namespace Layers
} // namespace Tokenisation
} // namespace Corpus
| accek/pantera-tagger | third_party/TaKIPI18/Linux/Corpus/Corpus/Tokenisation/Layers/ClassifyLayer.cpp | C++ | gpl-3.0 | 726 |
#!/usr/bin/env python
import argparse
from . import core
from . import gui
def main():
parser = argparse.ArgumentParser(
description="Track opponent's mulligan in the game of Hearthstone.")
parser.add_argument('--gui', action='store_true')
args = parser.parse_args()
if args.gui:
gui.main()
else:
core.main()
if __name__ == '__main__':
main()
| xor7486/mully | mully/__main__.py | Python | gpl-3.0 | 396 |
namespace WindowsFormsApplication4
{
partial class TimeLinerSub
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.mHScrollBar = new System.Windows.Forms.HScrollBar();
this.trackBar1 = new System.Windows.Forms.TrackBar();
this.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.vScrollBar1 = new System.Windows.Forms.VScrollBar();
this.headerDraw = new NPEditor.TimeDraw();
this.gradDraw = new NPEditor.TimeDraw();
this.mainDraw = new NPEditor.TimeDraw();
this.button2 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
this.SuspendLayout();
//
// mHScrollBar
//
this.mHScrollBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.mHScrollBar.LargeChange = 50;
this.mHScrollBar.Location = new System.Drawing.Point(0, 323);
this.mHScrollBar.Name = "mHScrollBar";
this.mHScrollBar.Size = new System.Drawing.Size(1076, 17);
this.mHScrollBar.TabIndex = 0;
//
// trackBar1
//
this.trackBar1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.trackBar1.AutoSize = false;
this.trackBar1.Location = new System.Drawing.Point(923, 10);
this.trackBar1.Name = "trackBar1";
this.trackBar1.Size = new System.Drawing.Size(104, 32);
this.trackBar1.TabIndex = 2;
this.trackBar1.Value = 6;
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.Location = new System.Drawing.Point(1033, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(23, 23);
this.button1.TabIndex = 4;
this.button1.Text = "1";
this.button1.UseVisualStyleBackColor = true;
//
// label1
//
this.label1.Location = new System.Drawing.Point(-2, 48);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(199, 18);
this.label1.TabIndex = 5;
this.label1.Text = "未选中";
//
// vScrollBar1
//
this.vScrollBar1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Right)));
this.vScrollBar1.LargeChange = 1;
this.vScrollBar1.Location = new System.Drawing.Point(1059, 82);
this.vScrollBar1.Name = "vScrollBar1";
this.vScrollBar1.Size = new System.Drawing.Size(17, 238);
this.vScrollBar1.TabIndex = 6;
//
// headerDraw
//
this.headerDraw.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.headerDraw.BackColor = System.Drawing.SystemColors.ControlDarkDark;
this.headerDraw.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.headerDraw.ForeColor = System.Drawing.Color.White;
this.headerDraw.Location = new System.Drawing.Point(0, 82);
this.headerDraw.Name = "headerDraw";
this.headerDraw.Size = new System.Drawing.Size(200, 238);
this.headerDraw.TabIndex = 11;
//
// gradDraw
//
this.gradDraw.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.gradDraw.BackColor = System.Drawing.SystemColors.ControlDarkDark;
this.gradDraw.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.gradDraw.ForeColor = System.Drawing.Color.White;
this.gradDraw.Location = new System.Drawing.Point(203, 48);
this.gradDraw.Name = "gradDraw";
this.gradDraw.Size = new System.Drawing.Size(853, 28);
this.gradDraw.TabIndex = 3;
//
// mainDraw
//
this.mainDraw.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.mainDraw.BackColor = System.Drawing.SystemColors.ControlDarkDark;
this.mainDraw.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.mainDraw.ForeColor = System.Drawing.Color.White;
this.mainDraw.Location = new System.Drawing.Point(203, 82);
this.mainDraw.Name = "mainDraw";
this.mainDraw.Size = new System.Drawing.Size(853, 238);
this.mainDraw.TabIndex = 1;
//
// button2
//
this.button2.Location = new System.Drawing.Point(292, 13);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 12;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1076, 340);
this.Controls.Add(this.button2);
this.Controls.Add(this.headerDraw);
this.Controls.Add(this.vScrollBar1);
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.Controls.Add(this.gradDraw);
this.Controls.Add(this.trackBar1);
this.Controls.Add(this.mainDraw);
this.Controls.Add(this.mHScrollBar);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.HScrollBar mHScrollBar;
private NPEditor.TimeDraw mainDraw;
private System.Windows.Forms.TrackBar trackBar1;
private NPEditor.TimeDraw gradDraw;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.VScrollBar vScrollBar1;
private NPEditor.TimeDraw headerDraw;
private System.Windows.Forms.Button button2;
}
}
| lyn0328/Timeliner | Timeliner/TimeLinerSub.Designer.cs | C# | gpl-3.0 | 8,189 |
from api.callers.api_caller import ApiCaller
from exceptions import ResponseTextContentTypeError
from colors import Color
import os
from cli.arguments_builders.default_cli_arguments import DefaultCliArguments
import datetime
from cli.cli_file_writer import CliFileWriter
from cli.formatter.cli_json_formatter import CliJsonFormatter
from constants import CALLED_SCRIPT
class CliCaller:
api_object = None
action_name = None
help_description = ''
given_args = {}
result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).'
result_msg_for_json = '{}'
cli_output_folder = ''
args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet']
def __init__(self, api_object: ApiCaller, action_name: str):
self.api_object = api_object
self.action_name = action_name
self.help_description = self.help_description.format(self.api_object.endpoint_url)
def init_verbose_mode(self):
self.result_msg_for_json = 'JSON:\n\n{}'
def build_argument_builder(self, child_parser):
return DefaultCliArguments(child_parser)
def add_parser_args(self, child_parser):
parser_argument_builder = self.build_argument_builder(child_parser)
parser_argument_builder.add_verbose_arg()
parser_argument_builder.add_help_opt()
parser_argument_builder.add_quiet_opt()
return parser_argument_builder
def attach_args(self, args):
self.given_args = args.copy()
args_to_send = args.copy()
for arg_to_remove in self.args_to_prevent_from_being_send:
if arg_to_remove in args_to_send:
del args_to_send[arg_to_remove]
if 'output' in args:
self.cli_output_folder = args['output']
del args_to_send['output']
args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary
if 'file' in args:
del args_to_send['file'] # attaching file is handled by separated method
if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET:
self.api_object.attach_params(args_to_send)
else: # POST
self.api_object.attach_data(args_to_send)
def attach_file(self, file):
if isinstance(file, str):
file = open(file, 'rb')
self.api_object.attach_files({'file': file}) # it's already stored as file handler
def get_colored_response_status_code(self):
response_code = self.api_object.get_response_status_code()
return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code)
def get_colored_prepared_response_msg(self):
response_msg = self.api_object.get_prepared_response_msg()
return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg)
def get_result_msg(self):
if self.api_object.api_response.headers['Content-Type'] == 'text/html':
raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type))
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON:
return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json()))
elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE:
if self.api_object.if_request_success() is True:
return self.get_result_msg_for_files()
else:
error_msg = 'Error has occurred and your files were not saved.'
if self.given_args['verbose'] is False:
error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')'
return error_msg
def get_processed_output_path(self):
output_path = self.cli_output_folder
if output_path.startswith('/') is True: # Given path is absolute
final_output_path = output_path
else:
path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2]
called_script_dir = os.path.dirname(CALLED_SCRIPT)
# It's about a case when user is calling script from not root directory.€
if called_script_dir != 'vxapi.py':
new_path_parts = []
bad_parts = called_script_dir.split('/')
for part in reversed(path_parts):
if part in bad_parts:
bad_parts.remove(part)
continue
new_path_parts.append(part)
new_path_parts.reverse()
path_parts = new_path_parts
prepared_file_path = path_parts + [self.cli_output_folder]
final_output_path = '/'.join(prepared_file_path)
if not final_output_path.startswith('/'):
final_output_path = '/' + final_output_path
return final_output_path
def get_result_msg_for_files(self):
return self.result_msg_for_files.format(self.get_processed_output_path())
def do_post_processing(self):
if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True:
self.save_files()
def get_date_string(self):
now = datetime.datetime.now()
return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second)
def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'):
with args[file_arg] as file:
hashes = file.read().splitlines()
if not hashes:
raise Exception('Given file does not contain any data.')
for key, value in enumerate(hashes):
args['{}[{}]'.format(key_of_array_arg, key)] = value
del args[file_arg]
return args
def save_files(self):
api_response = self.api_object.api_response
identifier = None
if 'id' in self.given_args:
identifier = self.given_args['id']
elif 'sha256' in self.given_args:
identifier = self.given_args['sha256']
filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename'])
return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content)
| PayloadSecurity/VxAPI | cli/wrappers/cli_caller.py | Python | gpl-3.0 | 6,741 |
/* First created by JCasGen Wed Sep 07 16:18:03 EDT 2016 */
package edu.pitt.dbmi.xmeso.model.Model;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.JCasRegistry;
import org.apache.uima.cas.impl.CASImpl;
import org.apache.uima.cas.impl.FSGenerator;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.cas.impl.TypeImpl;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.impl.FeatureImpl;
import org.apache.uima.cas.Feature;
import org.apache.uima.jcas.tcas.Annotation_Type;
/** Type defined in edu.pitt.dbmi.xmeso.model.Model
* Updated by JCasGen Wed Sep 07 16:18:03 EDT 2016
* @generated */
public class XmesoSentence_Type extends Annotation_Type {
/** @generated
* @return the generator for this type
*/
@Override
protected FSGenerator getFSGenerator() {return fsGenerator;}
/** @generated */
private final FSGenerator fsGenerator =
new FSGenerator() {
public FeatureStructure createFS(int addr, CASImpl cas) {
if (XmesoSentence_Type.this.useExistingInstance) {
// Return eq fs instance if already created
FeatureStructure fs = XmesoSentence_Type.this.jcas.getJfsFromCaddr(addr);
if (null == fs) {
fs = new XmesoSentence(addr, XmesoSentence_Type.this);
XmesoSentence_Type.this.jcas.putJfsFromCaddr(addr, fs);
return fs;
}
return fs;
} else return new XmesoSentence(addr, XmesoSentence_Type.this);
}
};
/** @generated */
@SuppressWarnings ("hiding")
public final static int typeIndexID = XmesoSentence.typeIndexID;
/** @generated
@modifiable */
@SuppressWarnings ("hiding")
public final static boolean featOkTst = JCasRegistry.getFeatOkTst("edu.pitt.dbmi.xmeso.model.Model.XmesoSentence");
/** @generated */
final Feature casFeat_sectionName;
/** @generated */
final int casFeatCode_sectionName;
/** @generated
* @param addr low level Feature Structure reference
* @return the feature value
*/
public String getSectionName(int addr) {
if (featOkTst && casFeat_sectionName == null)
jcas.throwFeatMissing("sectionName", "edu.pitt.dbmi.xmeso.model.Model.XmesoSentence");
return ll_cas.ll_getStringValue(addr, casFeatCode_sectionName);
}
/** @generated
* @param addr low level Feature Structure reference
* @param v value to set
*/
public void setSectionName(int addr, String v) {
if (featOkTst && casFeat_sectionName == null)
jcas.throwFeatMissing("sectionName", "edu.pitt.dbmi.xmeso.model.Model.XmesoSentence");
ll_cas.ll_setStringValue(addr, casFeatCode_sectionName, v);}
/** @generated */
final Feature casFeat_partNumber;
/** @generated */
final int casFeatCode_partNumber;
/** @generated
* @param addr low level Feature Structure reference
* @return the feature value
*/
public int getPartNumber(int addr) {
if (featOkTst && casFeat_partNumber == null)
jcas.throwFeatMissing("partNumber", "edu.pitt.dbmi.xmeso.model.Model.XmesoSentence");
return ll_cas.ll_getIntValue(addr, casFeatCode_partNumber);
}
/** @generated
* @param addr low level Feature Structure reference
* @param v value to set
*/
public void setPartNumber(int addr, int v) {
if (featOkTst && casFeat_partNumber == null)
jcas.throwFeatMissing("partNumber", "edu.pitt.dbmi.xmeso.model.Model.XmesoSentence");
ll_cas.ll_setIntValue(addr, casFeatCode_partNumber, v);}
/** @generated */
final Feature casFeat_sentenceNumber;
/** @generated */
final int casFeatCode_sentenceNumber;
/** @generated
* @param addr low level Feature Structure reference
* @return the feature value
*/
public int getSentenceNumber(int addr) {
if (featOkTst && casFeat_sentenceNumber == null)
jcas.throwFeatMissing("sentenceNumber", "edu.pitt.dbmi.xmeso.model.Model.XmesoSentence");
return ll_cas.ll_getIntValue(addr, casFeatCode_sentenceNumber);
}
/** @generated
* @param addr low level Feature Structure reference
* @param v value to set
*/
public void setSentenceNumber(int addr, int v) {
if (featOkTst && casFeat_sentenceNumber == null)
jcas.throwFeatMissing("sentenceNumber", "edu.pitt.dbmi.xmeso.model.Model.XmesoSentence");
ll_cas.ll_setIntValue(addr, casFeatCode_sentenceNumber, v);}
/** initialize variables to correspond with Cas Type and Features
* @generated
* @param jcas JCas
* @param casType Type
*/
public XmesoSentence_Type(JCas jcas, Type casType) {
super(jcas, casType);
casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator());
casFeat_sectionName = jcas.getRequiredFeatureDE(casType, "sectionName", "uima.cas.String", featOkTst);
casFeatCode_sectionName = (null == casFeat_sectionName) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_sectionName).getCode();
casFeat_partNumber = jcas.getRequiredFeatureDE(casType, "partNumber", "uima.cas.Integer", featOkTst);
casFeatCode_partNumber = (null == casFeat_partNumber) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_partNumber).getCode();
casFeat_sentenceNumber = jcas.getRequiredFeatureDE(casType, "sentenceNumber", "uima.cas.Integer", featOkTst);
casFeatCode_sentenceNumber = (null == casFeat_sentenceNumber) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_sentenceNumber).getCode();
}
}
| dbmi-pitt/xmeso | src/main/java/edu/pitt/dbmi/xmeso/model/Model/XmesoSentence_Type.java | Java | gpl-3.0 | 5,475 |
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
try:
import json
except ImportError:
from django.utils import simplejson as json
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.views.decorators.http import require_POST
from django.shortcuts import get_object_or_404
from django.conf import settings
from django.contrib.auth import get_user_model
from geonode.utils import resolve_object
from geonode.base.models import ResourceBase
from geonode.layers.models import Layer
from geonode.people.models import Profile
if "notification" in settings.INSTALLED_APPS:
from notification import models as notification
def _perms_info(obj):
info = obj.get_all_level_info()
return info
def _perms_info_json(obj):
info = _perms_info(obj)
info['users'] = dict([(u.username, perms)
for u, perms in info['users'].items()])
info['groups'] = dict([(g.name, perms)
for g, perms in info['groups'].items()])
return json.dumps(info)
def resource_permissions(request, resource_id):
try:
resource = resolve_object(
request, ResourceBase, {
'id': resource_id}, 'base.change_resourcebase_permissions')
except PermissionDenied:
# we are handling this in a non-standard way
return HttpResponse(
'You are not allowed to change permissions for this resource',
status=401,
content_type='text/plain')
if request.method == 'POST':
success = True
message = "Permissions successfully updated!"
try:
permission_spec = json.loads(request.body)
resource.set_permissions(permission_spec)
# Check Users Permissions Consistency
view_any = False
info = _perms_info(resource)
info_users = dict([(u.username, perms) for u, perms in info['users'].items()])
for user, perms in info_users.items():
if user == 'AnonymousUser':
view_any = ('view_resourcebase' in perms)
break
for user, perms in info_users.items():
if 'download_resourcebase' in perms and 'view_resourcebase' not in perms and not view_any:
success = False
message = 'User ' + str(user) + ' has Download permissions but ' \
'cannot access the resource. ' \
'Please update permissions consistently!'
return HttpResponse(
json.dumps({'success': success, 'message': message}),
status=200,
content_type='text/plain'
)
except BaseException:
success = False
message = "Error updating permissions :("
return HttpResponse(
json.dumps({'success': success, 'message': message}),
status=500,
content_type='text/plain'
)
elif request.method == 'GET':
permission_spec = _perms_info_json(resource)
return HttpResponse(
json.dumps({'success': True, 'permissions': permission_spec}),
status=200,
content_type='text/plain'
)
else:
return HttpResponse(
'No methods other than get and post are allowed',
status=401,
content_type='text/plain')
@require_POST
def invalidate_permissions_cache(request):
from .utils import sync_resources_with_guardian
uuid = request.POST['uuid']
resource = get_object_or_404(ResourceBase, uuid=uuid)
can_change_permissions = request.user.has_perm(
'change_resourcebase_permissions',
resource)
if can_change_permissions:
# Push Security Rules
sync_resources_with_guardian(resource)
return HttpResponse(
json.dumps({'success': 'ok', 'message': 'Security Rules Cache Refreshed!'}),
status=200,
content_type='text/plain'
)
else:
return HttpResponse(
json.dumps({'success': 'false', 'message': 'You cannot modify this resource!'}),
status=200,
content_type='text/plain'
)
@require_POST
def attributes_sats_refresh(request):
from geonode.geoserver.helpers import set_attributes_from_geoserver
uuid = request.POST['uuid']
resource = get_object_or_404(ResourceBase, uuid=uuid)
can_change_data = request.user.has_perm(
'change_resourcebase',
resource)
layer = Layer.objects.get(id=resource.id)
if layer and can_change_data:
# recalculate the layer statistics
set_attributes_from_geoserver(layer, overwrite=True)
return HttpResponse(
json.dumps({'success': 'ok', 'message': 'Attributes/Stats Refreshed Successfully!'}),
status=200,
content_type='text/plain'
)
else:
return HttpResponse(
json.dumps({'success': 'false', 'message': 'You cannot modify this resource!'}),
status=200,
content_type='text/plain'
)
@require_POST
def invalidate_tiledlayer_cache(request):
from .utils import set_geowebcache_invalidate_cache
uuid = request.POST['uuid']
resource = get_object_or_404(ResourceBase, uuid=uuid)
can_change_data = request.user.has_perm(
'change_resourcebase',
resource)
layer = Layer.objects.get(id=resource.id)
if layer and can_change_data:
set_geowebcache_invalidate_cache(layer.alternate)
return HttpResponse(
json.dumps({'success': 'ok', 'message': 'GeoWebCache Tiled Layer Emptied!'}),
status=200,
content_type='text/plain'
)
else:
return HttpResponse(
json.dumps({'success': 'false', 'message': 'You cannot modify this resource!'}),
status=200,
content_type='text/plain'
)
@require_POST
def set_bulk_permissions(request):
permission_spec = json.loads(request.POST.get('permissions', None))
resource_ids = request.POST.getlist('resources', [])
if permission_spec is not None:
not_permitted = []
for resource_id in resource_ids:
try:
resource = resolve_object(
request, ResourceBase, {
'id': resource_id
},
'base.change_resourcebase_permissions')
resource.set_permissions(permission_spec)
except PermissionDenied:
not_permitted.append(ResourceBase.objects.get(id=resource_id).title)
return HttpResponse(
json.dumps({'success': 'ok', 'not_changed': not_permitted}),
status=200,
content_type='text/plain'
)
else:
return HttpResponse(
json.dumps({'error': 'Wrong permissions specification'}),
status=400,
content_type='text/plain')
@require_POST
def request_permissions(request):
""" Request permission to download a resource.
"""
uuid = request.POST['uuid']
resource = get_object_or_404(ResourceBase, uuid=uuid)
try:
notification.send(
[resource.owner],
'request_download_resourcebase',
{'from_user': request.user, 'resource': resource}
)
return HttpResponse(
json.dumps({'success': 'ok', }),
status=200,
content_type='text/plain')
except BaseException:
return HttpResponse(
json.dumps({'error': 'error delivering notification'}),
status=400,
content_type='text/plain')
def send_email_consumer(layer_uuid, user_id):
resource = get_object_or_404(ResourceBase, uuid=layer_uuid)
user = Profile.objects.get(id=user_id)
notification.send(
[resource.owner],
'request_download_resourcebase',
{'from_user': user, 'resource': resource}
)
def send_email_owner_on_view(owner, viewer, layer_id, geonode_email="email@geo.node"):
# get owner and viewer emails
owner_email = get_user_model().objects.get(username=owner).email
layer = Layer.objects.get(id=layer_id)
# check if those values are empty
if owner_email and geonode_email:
from django.core.mail import EmailMessage
# TODO: Copy edit message.
subject_email = "Your Layer has been seen."
msg = ("Your layer called {0} with uuid={1}"
" was seen by {2}").format(layer.name, layer.uuid, viewer)
try:
email = EmailMessage(
subject=subject_email,
body=msg,
from_email=geonode_email,
to=[owner_email, ],
reply_to=[geonode_email, ])
email.content_subtype = "html"
email.send()
except BaseException:
pass
| mcldev/geonode | geonode/security/views.py | Python | gpl-3.0 | 9,784 |
# Alternative during matching. Contains a list of symbols where each is tried.
# Since we are parsing a CFG, there is no precedence to the alternatives. Only
# fails if all alternatives fail.
#
# Example:
#
# str('a') | str('b') # matches either 'a' or 'b'
#
class Marpa::Atoms::Alternative < Marpa::Atoms::Base
attr_reader :alternatives
# Constructs an Alternative instance using all given symbols in the order
# given. This is what happens if you call '|' on existing symbols, like this:
#
# lex(/a/) | lex(/b/)
#
def initialize(*alternatives)
super()
@alternatives = alternatives
end
# Build the sub-grammar for this rule: multiple productions for the same LHS
# symbol.
def build(parser)
if (id = parser.sym_id(self))
return id
end
finish_priorities
sym = parser.create_symbol(self)
alt_pairs = alternatives.map {|aa| [aa, asym = aa.build(parser)]}
alt_pairs.each do |alt_atom, alt_sym|
parser.create_rule(sym, alt_sym, alt_atom.priority)
end
# two-stage construction groups the alternative rules together; doesn't
# affect machine operation, but easier for people to debug
return sym
end
# Finish calculating the alternative priorities. The DSL marks
# lower-priority alternatives with a priority of -1. This method accumulates
# and shifts these values to a non-negative, monotone decreasing sequence of
# priorities.
def finish_priorities
#old:hi_pri = - alternatives.inject(0) {|s,alt| s + alt.priority}
#old:alternatives.inject(hi_pri) {|s,alt| alt.priority += s}
#old:# this last inject has significant, intended side-effects
hi_pri = -alternatives.map(&:priority).min
alternatives.each {|alt| alt.priority += hi_pri}
# sanity check
pri = nil
alternatives.each do |alt|
if pri
raise ArgumentError, "Unexpected priority sequence." \
unless (pri == alt.priority) || (pri-1 == alt.priority)
end
pri = alt.priority
end
end
# Don't construct a hanging tree of {Alternative} atoms, instead store them
# all in one {Alternative} object. This reduces the number of symbols in the
# grammar (though it creates a bunch of extra objects while building the
# DSL).
def |(rule)
# may have higher-priority alternatives buried in rule
new_rules = rule.alternatives rescue [rule]
pri = alternatives.last.priority
new_rules.each {|alt| alt.priority += pri}
new_rule = self.class.new(*@alternatives + new_rules)
new_rule
end
# Similar to the previous, override prioritized alternative DSL operator to
# collect the options in a single object instead of a dangling tree.
def /(rule)
rule.priority = alternatives.last.priority - 1
new_rule = self.class.new(*@alternatives + [rule])
new_rule
end
def to_s_inner
pri = nil
alternatives.map do |alt|
#tmp:str = alt.to_s
str = "#{alt} p#{alt.priority}"
if pri.nil?
str # first item, no separator
elsif pri == alt.priority
str = ' | ' + str
elsif pri > alt.priority
str = ' / ' + str
else
raise RuntimeError, 'Unexpected priority increase'
end
pri = alt.priority
str
end.join('') # alternatives.map
end # to_s_inner method
end # class Marpa::Atoms::Alternative
| rhinton/libmarpa-bindings | ruby/marpa/atoms/alternative.rb | Ruby | gpl-3.0 | 3,452 |
#ifndef ATOOLS_Math_MathTools_H
#define ATOOLS_Math_MathTools_H
/* Declarations for discrete functions */
#ifdef __GNUC__
// GNU C++ Compiler
#include <cmath>
#include <cstdlib>
/*
if __GNUC__ == 3 && __GNUC_MINOR__ == 0.
if defined __GNUC__ && defined __cplusplus && __GNUC_MINOR__ >= 8
if !defined __GNUC__ || __GNUC__ < 2 || __GNUC_MINOR__ < 7
#define GCC_VERSION (__GNUC__ * 10000 \
+ __GNUC_MINOR__ * 100 \
+ __GNUC_PATCHLEVEL__)
...
Test for GCC > 3.2.0
#if GCC_VERSION > 30200
*/
#endif
#if defined(__sgi) && !defined(__GNUC__)
// SGI IRIX C++ Compiler, complex but not double methods need "std::", e.g. Abs() exp()
#include <iostream>
#include <math.h>
#endif
#include "ATOOLS/Math/MyComplex.H"
namespace ATOOLS {
template <class Type> const Type &Min(const Type &a,const Type &b)
{ return a<b?a:b; }
template <class Type> const Type &Max(const Type &a,const Type &b)
{ return a>b?a:b; }
template <class Type> Type &Min(Type &a,Type &b)
{ return a<b?a:b; }
template <class Type> Type &Max(Type &a,Type &b)
{ return a>b?a:b; }
inline double Accu() {return 1.e-12;}
inline double SqrtAccu() {return 1.e-6;}
inline int Sign(const int& a) { return a<0?-1:1; }
inline double Sign(const double& a) { return a<0.0?-1.0:1.0; }
inline double Theta(const double &a) { return a<0.0?0.0:1.0; }
inline int iabs(const int& a) { return a<0?-a:a; }
inline double dabs(const double& a) { return a<0.0?-a:a; }
template <typename Scalar>
inline Scalar sqr(const Scalar &x) { return x*x; }
template <typename Scalar> inline std::complex<Scalar>
csqr(const std::complex<Scalar> &x) { return x*x; }
inline int IsZero(const double &a,const double &crit)
{ return dabs(a)<crit?1:0; }
inline int IsZero(const Complex &a,const double &crit)
{ return std::abs(a)<crit?1:0; }
inline int IsEqual(const double &a,const double &b)
{
if (a==0. && b==0.) return 1;
return (dabs(a-b)/(dabs(a)+dabs(b))<Accu()) ? 1 : 0;
}
inline int IsEqual(const double &a,const double &b,const double &crit)
{
if (a==0. && b==0.) return 1;
return (dabs(a-b)/(dabs(a)+dabs(b))<crit) ? 1 : 0;
}
inline int IsEqual(const Complex &a,const Complex &b)
{
if (a==Complex(0.,0.) && b==Complex(0.,0.)) return 1;
return (std::abs(a-b)/(std::abs(a)+std::abs(b))<Accu()) ? 1 : 0;
}
inline Complex csqrt(const double &d)
{
if (d<0) return Complex(0.,sqrt(-d));
return sqrt(d);
}
#define GAMMA_E 0.5772156649015328606
double Gammln(double xx);
double ReIncompleteGamma0(double x,double prec=1.e-6);
double DiLog(double x);
Complex DiLog(const Complex& x);
int Factorial(const int n);
double ExpIntegral(int n, double x);
template<typename Scalar> inline bool IsNan(const Scalar& x);
template<typename Scalar> inline bool IsBad(const Scalar& x);
template<typename Scalar> inline bool IsZero(const Scalar& x);
template<typename Scalar> inline Scalar Abs(const Scalar& x);
template<typename Scalar> inline Scalar Abs(const std::complex<Scalar>& x);
template<> inline bool IsNan<double>(const double& x) {
return std::isnan(x)||std::isnan(-x);
}
template<> inline bool IsBad<double>(const double& x) {
return IsNan(x)||std::isinf(x)||std::isinf(-x);
}
template<> inline bool IsZero<double>(const double& x) {
return dabs(x)<Accu()?1:0;
}
template<> inline double Abs<double>(const double& x) {
return x>0.0?x:-x;
}
template<> inline bool IsNan<long double>(const long double& x) {
return std::isnan(x)||std::isnan(-x);
}
template<> inline bool IsBad<long double>(const long double& x) {
return IsNan(x)||std::isinf(x)||std::isinf(-x);
}
template<> inline bool IsZero<long double>(const long double& x) {
return dabs(x)<Accu()?1:0;
}
template<> inline long double Abs<long double>(const long double& x) {
return x>0.0?x:-x;
}
template<> inline bool IsNan<Complex>(const Complex& x) {
return (std::isnan(real(x)) || std::isnan(imag(x)) ||
std::isnan(-real(x)) || std::isnan(-imag(x)));
}
template<> inline bool IsBad<Complex>(const Complex& x) {
return IsNan(x)||std::isinf(real(x))||std::isinf(imag(x))
||std::isinf(-real(x))||std::isinf(-imag(x));
}
template<> inline bool IsZero<Complex>(const Complex& x) {
return std::abs(x)<Accu()?1:0;
}
template<> inline double Abs<double>(const Complex& x) {
return std::abs(x);
}
template<> inline bool IsNan<std::complex<long double> >
(const std::complex<long double>& x) {
return (std::isnan(real(x)) || std::isnan(imag(x)) ||
std::isnan(-real(x)) || std::isnan(-imag(x)));
}
template<> inline bool IsBad<std::complex<long double> >
(const std::complex<long double>& x) {
return IsNan(x)||std::isinf(real(x))||std::isinf(imag(x))
||std::isinf(-real(x))||std::isinf(-imag(x));
}
template<> inline bool IsZero<std::complex<long double> >
(const std::complex<long double>& x) {
return std::abs(x)<Accu()?1:0;
}
template<> inline long double Abs<long double>
(const std::complex<long double>& x) {
return std::abs(x);
}
template<class T1, class T2>
struct promote_trait {
};
#define DECLARE_PROMOTE(A,B,C) \
template<> struct promote_trait<A,B> { \
typedef C T_promote; \
}
DECLARE_PROMOTE(double,Complex,Complex);
DECLARE_PROMOTE(Complex,double,Complex);
DECLARE_PROMOTE(int,double,double);
DECLARE_PROMOTE(double,int,double);
DECLARE_PROMOTE(int,Complex,Complex);
DECLARE_PROMOTE(Complex,int,Complex);
DECLARE_PROMOTE(double,double,double);
DECLARE_PROMOTE(Complex,Complex,Complex);
DECLARE_PROMOTE(long double,std::complex<long double>,
std::complex<long double>);
DECLARE_PROMOTE(std::complex<long double>,long double,
std::complex<long double>);
DECLARE_PROMOTE(int,long double,long double);
DECLARE_PROMOTE(long double,int,long double);
DECLARE_PROMOTE(int,std::complex<long double>,std::complex<long double>);
DECLARE_PROMOTE(std::complex<long double>,int,std::complex<long double>);
DECLARE_PROMOTE(long double,long double,long double);
DECLARE_PROMOTE(std::complex<long double>,std::complex<long double>,
std::complex<long double>);
#define PROMOTE(TYPE1,TYPE2) typename promote_trait<TYPE1,TYPE2>::T_promote
/*!
\file
\brief contains a collection of simple mathematical functions
*/
/*!
\fn inline Type Min(Type a, Type b)
\brief returns the minimum of two numbers
*/
/*!
\fn inline Type Max(Type a, Type b)
\brief returns the maximum of two numbers
*/
/*!
\fn inline int Sign(const int& a) {return (a<0) ? -1 : 1;}
\brief returns the sign of the argument
*/
/*!
\fn inline int iabs(const int& a) {return a>0 ? a : -a;}
\brief returns the absolute value of the argument
*/
/*!
\fn inline double dabs(const double& a) {return a>0 ? a : -a;}
\brief returns the absolute value of the argument
*/
/*!
\fn inline double sqr(double x) {return x*x;}
\brief returns the argument squared
*/
/*!
\fn inline double Accu() {return 1.e-12;};
\brief returns a (platform dependent) precission, default is \f$1^{-12}\f$
*/
/*!
\fn inline int IsZero(const double a)
\brief returns \em true if argument is smaller than Accu()
*/
/*!
\fn inline int IsZero(const Complex& a)
\brief returns \em true if argument is smaller than Accu()
*/
/*!
\fn inline int IsEqual(const double a,const double b)
\brief returns \em true if arguments are equal (compared to Accu())
*/
/*!
\fn inline int IsEqual(const Complex& a,const Complex& b)
\brief returns \em true if arguments are equal (compared to Accu())
*/
/*!
\fn inline Complex csqrt(const double d)
\brief returns the complex root of a (possibly negative) float or double variable
*/
/*!
\fn inline Complex csqr(Complex x)
\brief returns the argument squared
*/
/*!
\fn double Gammln(double xx)
\brief calculates the logarithm of the Gammafunction
*/
/*!
\fn double ReIncomplietGamma0(double xx)
\brief calculates the real part of the incomplete Gammafunction.
*/
/*!
\fn double DiLog(double x)
\brief calculates the real part of Li_2(x).
*/
}
#endif
| cms-externals/sherpa | ATOOLS/Math/MathTools.H | C++ | gpl-3.0 | 8,456 |
ManageIndexes = {
GridPanel : function(config) {
config.autoExpandColumn = 'columns';
config.viewConfig = { forceFit: true };
ManageIndexes.GridPanel.superclass.constructor.call(this, config);
},
gridPanelStore : function(data) {
var store = new Ext.data.SimpleStore( {
fields : data.fields
});
store.loadData(data.data);
return store;
},
gridPanelColumnModel : function(data) {
for ( var i = 0; i < data.models.length; i++) {
var curr = data.models[i];
if (curr.id == 'unique' || curr.id == 'fullText') {
curr.renderer = function(v) {
//return '<div class="x-grid3-check-col' + (v ? '-on' : '') + '"> </div>';
return '<input type="checkbox" '+(v?'checked="checked"':'')+' disabled="disabled" />';
};
}
}
var cm = new Ext.grid.ColumnModel( {
columns : data.models
});
return cm;
},
closeManageIndexesWindow : function() {
Ext.getCmp('manage_indexes_window').close();
},
showDeleteIndexConfirmation : function() {
// Get the selected row(s)
var indexesGrid = Ext.getCmp('manage_indexes_grid');
var selModel = indexesGrid.getSelectionModel();
var rows = selModel.getSelections();
// If no rows are selected, alert the user.
if (!rows.length) {
var msg = "Please select index(s) to delete!";
Dbl.Utils.showErrorMsg(msg, '');
// Ext.MessageBox.alert('No Index(es) Selected',
// 'Please select the index(es) to delete');
return;
}
ManageIndexes.indexesForDeletion = [];
for ( var i = 0; i < rows.length; i++) {
ManageIndexes.indexesForDeletion.push(rows[i].data.indexName);
}
// Get confirmation from the user
var title = 'Are you sure?';
var message = 'Are you sure you want to delete the selected index(es)?';
var handleConfirmation = function(btn) {
if (btn == "yes") {
// Send the delete index command to server
Server.sendCommand('delete_indexes', {
indexes : ManageIndexes.indexesForDeletion,
table : Explorer.selectedDbTable
}, function(data) {
// var msg = "Index(s) deleted successfully";
Dbl.Utils.showInfoMsg(Messages.getMsg('index_deletion_success'));
// Ext.MessageBox.alert('Success!!',
// 'Index(es) deleted successfully');
ManageIndexes.refreshGrid();
// Server.sendCommand('get_min_table_indexes', {
// parent_database : Explorer.selectedDatabase,
// table : Explorer.selectedDbTable
// }, function(data) {
// var store = ManageIndexes.gridPanelStore(data);
// var cm = ManageIndexes.gridPanelColumnModel(data);
// Ext.getCmp('manage_indexes_grid')
// .reconfigure(store, cm);
//
// });
});
}
};
Ext.MessageBox.confirm(title, message, handleConfirmation);
},
indexesForDeletion : [],
refreshGrid: function()
{
Server.sendCommand('get_min_table_indexes', {
parent_database : Explorer.selectedDatabase,
table : Explorer.selectedDbTable
}, function(data) {
var store = ManageIndexes.gridPanelStore(data);
var cm = ManageIndexes.gridPanelColumnModel(data);
Ext.getCmp('manage_indexes_grid').reconfigure(store, cm);
});
},
showEditIndexWindow: function()
{
var selectionCount = Ext.getCmp('manage_indexes_grid').getSelectionModel().getCount();
if(!selectionCount) {
// var msg = "Please select an index to edit!";
Dbl.Utils.showErrorMsg(Messages.getMsg('edit_index_required'));
} else if(selectionCount > 1) {
// var msg = "Please select a single index to edit!";
Dbl.Utils.showErrorMsg(Messages.getMsg('edit_index_single'));
} else {
Server.sendCommand('get_min_table_columns', {
table : Explorer.selectedDbTable
}, function(data) {
data.editMode = true;
ManageIndexes.addIndexWin = new ManageIndexes.AddIndexWindow(data);
ManageIndexes.addIndexWin.show();
});
}
},
showAddIndexWindow : function(editMode) {
Server.sendCommand('get_min_table_columns', {
table : Explorer.selectedDbTable
}, function(data) {
ManageIndexes.addIndexWin = new ManageIndexes.AddIndexWindow(data);
ManageIndexes.addIndexWin.show();
});
},
AddIndexWindow : function(data) {
var gridPanel = new ManageIndexes.AddIndexGrid(data);
var form = new ManageIndexes.AddIndexForm();
if(data.editMode)
{
var index = Ext.getCmp('manage_indexes_grid').getSelectionModel().getSelected().data;
var indexName = index.indexName;
var formObj = form.getForm();
formObj.findField('add_index_form_index_name').setValue(indexName);
formObj.findField('add_index_form_original_name').setValue(indexName);
//form.originalIndexName = indexName;
var indexType;
if(indexName == 'PRIMARY')
indexType = 'primary';
else if(index.unique == true)
indexType = 'unique';
else if(index.fullText == true)
indexType = 'fullText';
else
indexType = 'none';
var cmpId = 'add_index_form_index_type_'+indexType;
Ext.getCmp('options_group').setValue(cmpId,true);
var columns = index.columns.split(',').reverse();
for(var i=0; i<columns.length; i++)
{
var recIndex = gridPanel.getStore().find('Name',columns[i]);
var rec = gridPanel.getStore().getAt(recIndex);
rec.set('included', true);
gridPanel.getStore().remove(rec);
gridPanel.getStore().insert(0, rec);
}
}
ManageIndexes.AddIndexWindow.superclass.constructor.call(this, {
title : "Add New Index",
id : "add_index_window",
headerAsText : true,
width : 350,
resizable : false,
modal : true,
plain : true,
stateful : true,
shadow : false,
onEsc : function() {
},
closeAction : 'destroy',
items : [ form, gridPanel ],
buttons : [
{
text: data.editMode ? 'submit' : 'add',
handler: data.editMode?ManageIndexes.editIndex:ManageIndexes.createAndAddIndex
},
{
text: 'cancel',
handler: ManageIndexes.closeAddIndexWindow
}]
});
},
AddIndexGrid : function(data) {
var includedModel = new Ext.ux.CheckColumn({
header: ' ',
checkOnly: true,
dataIndex: 'included',
width: 20});
for(var i=0; i<data.fields.length; i++)
{
if(data.fields[i] == "included") {
data.fields[i].type = 'bool';
data.models[i] = includedModel;
}
}
ManageIndexes.AddIndexGrid.superclass.constructor.call(this, {
fields : data.fields,
data : data.data,
models : data.models,
autoExpandColumn: 'Name',
viewConfig: { forceFit: true },
id : 'add_index_grid',
height: 180,
//width: 333,
autoScroll: true,
fbar: [Messages.getMsg('edit_index_footer')],
enableDragDrop: true,
ddGroup: 'mygridDD',
plugins: [includedModel],
listeners: {
"render": {
scope: this,
fn: function(grid) {
var ddrow = new Ext.dd.DropTarget(grid.container, {
ddGroup : 'mygridDD',
copy: false,
notifyDrop : function(dd, e, data){
//Ext.getCmp('reorder_columns_window').reorderButton.enable();
var ds = grid.store;
var sm = grid.getSelectionModel();
var rows = sm.getSelections();
//var rows = this.currentRowEl;
if(dd.getDragData(e)) {
var cindex=dd.getDragData(e).rowIndex;
if(typeof(cindex) != "undefined") {
for(i = 0; i < rows.length; i++) {
ds.remove(ds.getById(rows[i].id));
}
ds.insert(cindex,data.selections);
sm.clearSelections();
}
}
}
});
}
}
}
});
},
AddIndexForm: function(data) {
var radioGroupItems = [
{
boxLabel: 'Unique',
name: 'add_index_form_index_type',
id: 'add_index_form_index_type_unique',
inputValue: 'unique'
},
{
boxLabel: 'Full Text',
name: 'add_index_form_index_type',
id: 'add_index_form_index_type_fullText',
inputValue: 'fullText'
},
{
boxLabel: 'Primary',
name: 'add_index_form_index_type',
id: 'add_index_form_index_type_primary',
inputValue: 'primary',
listeners:
{
'check': {
fn: function()
{
var form = Ext.getCmp('add_index_form').getForm().getValues(false);
var indexName = Ext.getCmp('add_index_form_index_name');
if(form.add_index_form_index_type == 'primary')
{
indexName.prevValue = form.add_index_form_index_name;
indexName.setValue('PRIMARY');
indexName.disable();
}
else
{
indexName.setValue(indexName.prevValue);
indexName.enable();
}
}
}
}
},
{
boxLabel: 'None',
name: 'add_index_form_index_type',
id: 'add_index_form_index_type_none',
inputValue: 'none',
checked: true
}];
ManageIndexes.AddIndexForm.superclass.constructor.call(this, {
id: 'add_index_form',
labelAlign: 'top',
frame: true,
bodyStyle: "padding: 5px",
defaults: {
anchor: '100%'
},
items:[
{
xtype: 'textfield',
fieldLabel: 'Index Name',
name: 'add_index_form_index_name',
id: 'add_index_form_index_name',
blankText: 'Index name is required',
allowBlank: false
},
{
xtype: 'hidden',
name: 'add_index_form_original_name',
id: 'add_index_form_original_name'
},
{
xtype: 'radiogroup',
rows: 1,
id: 'options_group',
defaults: {
anchor: '100%'
},
bodyStyle: "padding: 0px; margin: 0px",
items: radioGroupItems,
fieldLabel: 'Index Options'
}]
});
},
editIndex: function()
{
ManageIndexes.createAndAddIndex(true);
},
createAndAddIndex: function(editMode)
{
var form = Ext.getCmp('add_index_form').getForm();
if(!form.isValid())
{
return;
}
var values = form.getValues();
var store = Ext.getCmp('add_index_grid').getStore();
var indexes = [];
var selectedRows = 0;
for(var i=0; i<store.getCount(); i++)
{
var record = store.getAt(i);
if(record.get('included') == true)
{
indexes.push(record.get('Name'));
selectedRows++;
}
}
if(selectedRows < 1)
{
// var msg = 'Please select at least one column';
Dbl.Utils.showErrorMsg(Messages.getMsg('add_index_column_req'));
//Ext.MessageBox.alert('No Columns Selected', 'Please Select atleast one column');
return;
}
Server.sendCommand(
'create_indexes',
{
table: Explorer.selectedDbTable,
type: values.add_index_form_index_type,
name: values.add_index_form_index_name,
indexes: indexes,
originalName: values.add_index_form_original_name
},
function(data) {
if(data.success) {
ManageIndexes.refreshGrid();
ManageIndexes.closeAddIndexWindow();
// var msg = 'Index added successfully';
Dbl.Utils.showInfoMsg(Messages.getMsg('index_addition_success'));
} else if(!data.success) {
var msg = data.msg ? data.msg : data;
Dbl.Utils.showErrorMsg(data.msg, '');
}
}, function(data){
Dbl.Utils.showErrorMsg(data.msg, '');
});
},
closeAddIndexWindow: function() {
Ext.getCmp('add_index_window').close();
}
};
Ext.onReady(function() {
Ext.extend(ManageIndexes.GridPanel, Dbl.ListViewPanel, {
hello : function(str) {
}
});
Ext.extend(ManageIndexes.AddIndexWindow, Ext.Window, {
});
Ext.extend(ManageIndexes.AddIndexGrid, Dbl.ListViewPanel, {});
Ext.extend(ManageIndexes.AddIndexForm, Ext.FormPanel, {});
});
| manusis/dblite | app/js/dblite/manageindexes.js | JavaScript | gpl-3.0 | 11,797 |
require 'package'
class Kubectl < Package
description 'Kubernetes command line tool'
homepage 'https://kubernetes.io'
version '1.7.0'
source_url 'https://github.com/kubernetes/kubernetes/archive/v1.7.0.tar.gz'
source_sha256 '0fe34180a4bb61384894616b1d348cc6350d1ebcbc071c67748864ffd2deb026'
binary_url ({
aarch64: 'https://dl.bintray.com/chromebrew/chromebrew/kubectl-1.7.0-chromeos-armv7l.tar.xz',
armv7l: 'https://dl.bintray.com/chromebrew/chromebrew/kubectl-1.7.0-chromeos-armv7l.tar.xz',
i686: 'https://dl.bintray.com/chromebrew/chromebrew/kubectl-1.7.0-chromeos-i686.tar.xz',
x86_64: 'https://dl.bintray.com/chromebrew/chromebrew/kubectl-1.7.0-chromeos-x86_64.tar.xz',
})
binary_sha256 ({
aarch64: '9743623318ffeeaf659364297d5d8f81c9eaa8d78e9319308fc01dfb6b0ec724',
armv7l: '9743623318ffeeaf659364297d5d8f81c9eaa8d78e9319308fc01dfb6b0ec724',
i686: 'd9a2c48ab4fee90e1ff681bf73842f1896ed1e82344dc1e3bd0d81bb6010e590',
x86_64: '0c8d84f6d8802892d6cea9e238fd8fe132cb8db117467d85ba5e94dcaae30de4',
})
depends_on "go" => :build
depends_on "rsync" => :build
def self.build
ENV['TMPDIR'] = "#{CREW_PREFIX}/tmp"
# Override the -j$NPROC set by crew with -j1 to workaround a race issue
system "make", "-j1", "generated_files"
system "make", "kubectl"
end
def self.install
system "install", "-D", "-m", "755", "_output/bin/kubectl", "#{CREW_DEST_PREFIX}/bin/kubectl"
end
end
| chromebrew/chromebrew-test | packages/kubectl.rb | Ruby | gpl-3.0 | 1,464 |
#include <string>
#include <vector>
#include <stdio.h>
#include "graphics.h"
#include "engine.h"
#include "Lib/BufferedFile.h"
#include "Lib/getvar.h"
using namespace std;
using namespace sf;
int GraphicResources::GetGraphicCount()
{
return Graphics.size() - 1;
}
GraphicData& GraphicResources::GetGraphic(int Index)
{
return Graphics[Index];
}
void GraphicResources::LoadAll()
{
LoadGraphicData();
LoadTextures();
LoadAnimations();
}
void GraphicResources::LoadTextures()
{
int GraphicCount = GetGraphicCount();
for (int I = 1; I <= GraphicCount; I++)
{
GraphicData& Graphic = GetGraphic(I);
if (Textures.count(Graphic.FileID) == 0)
{
Textures[Graphic.FileID] = Texture();
Textures[Graphic.FileID].loadFromFile("Resources/Graphics/" + to_string(Graphic.FileID) + ".png");
}
}
}
int GraphicResources::GetAnimation(int BodyPart, int AnimIndex, int Heading)
{
return Animations[BodyPart][AnimIndex][Heading];
}
void GraphicResources::LoadGraphicData()
{
BufferedFile File = BufferedFile("Resources/Graficos.ind", "rb");
int FileVersion = File.Read(&FileVersion);
unsigned int GraphicCount = File.Read(&GraphicCount);
printf("GrhCount %u\n", GraphicCount);
Graphics.resize(GraphicCount + 1);
while(true)
{
GraphicData Graphic;
unsigned int Index = File.Read(&Index);
if (Index != 0)
{
Graphic.FrameCount = File.Read(&Graphic.FrameCount);
if (Graphic.FrameCount > 1)
{
for (int I = 0; I < Graphic.FrameCount; I++)
{
Graphic.Frames[I] = File.Read(&Graphic.Frames[I]);
if (Graphic.Frames[I] <= 0 || Graphic.Frames[I] > GraphicCount)
return;
}
Graphic.Speed = File.Read(&Graphic.Speed);
if (Graphic.Speed <= 0)
return;
Graphic.StartX = Graphics[Graphic.Frames[0]].StartX;
if (Graphic.StartX < 0)
return;
Graphic.StartY = Graphics[Graphic.Frames[0]].StartY;
if (Graphic.StartY < 0)
return;
Graphic.TileWidth = Graphics[Graphic.Frames[0]].TileWidth;
Graphic.TileHeight = Graphics[Graphic.Frames[0]].TileHeight;
}
else
{
Graphic.FileID = File.Read(&Graphic.FileID);
if (Graphic.FileID <= 0)
return;
Graphic.StartX = File.Read(&Graphic.StartX);
if (Graphic.StartX < 0)
return;
Graphic.StartY = File.Read(&Graphic.StartY);
if (Graphic.StartY < 0)
return;
Graphic.PixelWidth = File.Read(&Graphic.PixelWidth);
if (Graphic.PixelWidth <= 0)
return;
Graphic.PixelHeight = File.Read(&Graphic.PixelHeight);
if (Graphic.PixelHeight <= 0)
return;
Graphic.TileWidth = Graphic.PixelWidth / 32;
Graphic.TileHeight = Graphic.PixelHeight / 32;
Graphic.Frames[0] = Index;
}
Graphics[Index] = Graphic;
}
if (Index == GraphicCount)
break;
}
}
void GraphicResources::LoadAnimations()
{
printf("Loading animations\n");
Animations.resize(5);
int Count = GetVarInt("Resources/Cabezas.ini", "INIT", "NumHeads");
printf("Head count: %u\n", Count);
for (int I = 0; I < Count; ++I)
{
vector<int> Anim;
Anim.push_back(GetVarInt("Resources/Cabezas.ini", "HEAD" + to_string(I), "Head1"));
Anim.push_back(GetVarInt("Resources/Cabezas.ini", "HEAD" + to_string(I), "Head2"));
Anim.push_back(GetVarInt("Resources/Cabezas.ini", "HEAD" + to_string(I), "Head3"));
Anim.push_back(GetVarInt("Resources/Cabezas.ini", "HEAD" + to_string(I), "Head4"));
Animations[0].push_back(Anim);
}
Count = GetVarInt("Resources/Cuerpos.ini", "INIT", "NumBodies");
printf("Torso count: %u\n", Count);
for (int I = 0; I < Count; ++I)
{
vector<int> Anim;
Anim.push_back(GetVarInt("Resources/Cuerpos.ini", "BODY" + to_string(I), "WALK1"));
Anim.push_back(GetVarInt("Resources/Cuerpos.ini", "BODY" + to_string(I), "WALK2"));
Anim.push_back(GetVarInt("Resources/Cuerpos.ini", "BODY" + to_string(I), "WALK3"));
Anim.push_back(GetVarInt("Resources/Cuerpos.ini", "BODY" + to_string(I), "WALK4"));
Animations[1].push_back(Anim);
}
Count = GetVarInt("Resources/Cascos.ini", "INIT", "NumCascos");
printf("Helmet count: %u\n", Count);
for (int I = 0; I < Count; ++I)
{
vector<int> Anim;
Anim.push_back(GetVarInt("Resources/Cascos.ini", "CASCO" + to_string(I), "Head1"));
Anim.push_back(GetVarInt("Resources/Cascos.ini", "CASCO" + to_string(I), "Head2"));
Anim.push_back(GetVarInt("Resources/Cascos.ini", "CASCO" + to_string(I), "Head3"));
Anim.push_back(GetVarInt("Resources/Cascos.ini", "CASCO" + to_string(I), "Head4"));
Animations[2].push_back(Anim);
}
Count = GetVarInt("Resources/Armas.ini", "INIT", "NumArmas");
printf("Weapon count: %u\n", Count);
for (int I = 0; I < Count; ++I)
{
vector<int> Anim;
Anim.push_back(GetVarInt("Resources/Armas.ini", "Arma" + to_string(I), "Dir1"));
Anim.push_back(GetVarInt("Resources/Armas.ini", "Arma" + to_string(I), "Dir2"));
Anim.push_back(GetVarInt("Resources/Armas.ini", "Arma" + to_string(I), "Dir3"));
Anim.push_back(GetVarInt("Resources/Armas.ini", "Arma" + to_string(I), "Dir4"));
Animations[3].push_back(Anim);
}
Count = GetVarInt("Resources/Escudos.ini", "INIT", "NumEscudos");
printf("Shield count: %u\n", Count);
for (int I = 0; I < Count; ++I)
{
vector<int> Anim;
Anim.push_back(GetVarInt("Resources/Escudos.ini", "ESC" + to_string(I), "Dir1"));
Anim.push_back(GetVarInt("Resources/Escudos.ini", "ESC" + to_string(I), "Dir2"));
Anim.push_back(GetVarInt("Resources/Escudos.ini", "ESC" + to_string(I), "Dir3"));
Anim.push_back(GetVarInt("Resources/Escudos.ini", "ESC" + to_string(I), "Dir4"));
Animations[4].push_back(Anim);
}
}
Sprite GraphicResources::GenerateSpriteFromGrhIndex(int GrhIndex, bool Centered)
{
Sprite Sprite;
GraphicData& Frame = GetGraphic(GetGraphic(GrhIndex).Frames[0]);
Sprite.setTexture(Textures[Frame.FileID]);
Sprite.setTextureRect(IntRect(Frame.StartX, Frame.StartY, Frame.PixelWidth, Frame.PixelHeight));
if (Centered)
{
int OriginX = (int)(((int)Frame.TileWidth) * 16) + 16;
int OriginY = (int)((((int)Frame.TileHeight) * 32) + 32);
Sprite.setOrigin(OriginX, OriginY);
}
return Sprite;
}
| Nvreformat/Argentum-Engine | Source/graphics.cpp | C++ | gpl-3.0 | 6,132 |
/* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/. */
package com.db4o.io;
import com.db4o.ext.*;
import com.db4o.internal.fileheader.*;
/**
* CachedIoAdapter is an IOAdapter for random access files, which caches data
* for IO access. Its functionality is similar to OS cache.<br>
* Example:<br>
* <code>delegateAdapter = new RandomAccessFileAdapter();</code><br>
* <code>Db4o.configure().io(new CachedIoAdapter(delegateAdapter));</code><br>
* @deprecated Use {@link CachingStorage} instead.
*/
public class CachedIoAdapter extends IoAdapter {
private Page _head;
private Page _tail;
private long _position;
private int _pageSize;
private int _pageCount;
private long _fileLength;
private long _filePointer;
private IoAdapter _io;
private boolean _readOnly;
private static int DEFAULT_PAGE_SIZE = 1024;
private static int DEFAULT_PAGE_COUNT = 64;
// private Hashtable4 _posPageMap = new Hashtable4(PAGE_COUNT);
/**
* Creates an instance of CachedIoAdapter with the default page size and
* page count.
*
* @param ioAdapter
* delegate IO adapter (RandomAccessFileAdapter by default)
*/
public CachedIoAdapter(IoAdapter ioAdapter) {
this(ioAdapter, DEFAULT_PAGE_SIZE, DEFAULT_PAGE_COUNT);
}
/**
* Creates an instance of CachedIoAdapter with a custom page size and page
* count.<br>
*
* @param ioAdapter
* delegate IO adapter (RandomAccessFileAdapter by default)
* @param pageSize
* cache page size
* @param pageCount
* allocated amount of pages
*/
public CachedIoAdapter(IoAdapter ioAdapter, int pageSize, int pageCount) {
_io = ioAdapter;
_pageSize = pageSize;
_pageCount = pageCount;
}
/**
* Creates an instance of CachedIoAdapter with extended parameters.<br>
*
* @param path
* database file path
* @param lockFile
* determines if the file should be locked
* @param initialLength
* initial file length, new writes will start from this point
* @param readOnly
* if the file should be used in read-onlyt mode.
* @param io
* delegate IO adapter (RandomAccessFileAdapter by default)
* @param pageSize
* cache page size
* @param pageCount
* allocated amount of pages
*/
public CachedIoAdapter(String path, boolean lockFile, long initialLength,
boolean readOnly, IoAdapter io, int pageSize, int pageCount)
throws Db4oIOException {
_readOnly = readOnly;
_pageSize = pageSize;
_pageCount = pageCount;
initCache();
initIOAdaptor(path, lockFile, initialLength, readOnly, io);
_position = initialLength;
_filePointer = initialLength;
_fileLength = _io.getLength();
}
/**
* Creates and returns a new CachedIoAdapter <br>
*
* @param path
* database file path
* @param lockFile
* determines if the file should be locked
* @param initialLength
* initial file length, new writes will start from this point
*/
public IoAdapter open(String path, boolean lockFile, long initialLength, boolean readOnly)
throws Db4oIOException {
return new CachedIoAdapter(path, lockFile, initialLength, readOnly, _io,
_pageSize, _pageCount);
}
/**
* Deletes the database file
*
* @param path
* file path
*/
public void delete(String path) {
_io.delete(path);
}
/**
* Checks if the file exists
*
* @param path
* file path
*/
public boolean exists(String path) {
return _io.exists(path);
}
private void initIOAdaptor(String path, boolean lockFile, long initialLength, boolean readOnly, IoAdapter io)
throws Db4oIOException {
_io = io.open(path, lockFile, initialLength, readOnly);
}
private void initCache() {
_head = new Page(_pageSize);
_head._prev = null;
Page page = _head;
Page next = _head;
for (int i = 0; i < _pageCount - 1; ++i) {
next = new Page(_pageSize);
page._next = next;
next._prev = page;
page = next;
}
_tail = next;
}
/**
* Reads the file into the buffer using pages from cache. If the next page
* is not cached it will be read from the file.
*
* @param buffer
* destination buffer
* @param length
* how many bytes to read
*/
public int read(byte[] buffer, int length) throws Db4oIOException {
long startAddress = _position;
int bytesToRead = length;
int totalRead = 0;
while (bytesToRead > 0) {
final Page page = getPage(startAddress, true);
final int readBytes = page.read(buffer, totalRead, startAddress, bytesToRead);
movePageToHead(page);
if (readBytes <= 0) {
break;
}
bytesToRead -= readBytes;
startAddress += readBytes;
totalRead += readBytes;
}
_position = startAddress;
return totalRead == 0 ? -1 : totalRead;
}
/**
* Writes the buffer to cache using pages
*
* @param buffer
* source buffer
* @param length
* how many bytes to write
*/
public void write(byte[] buffer, int length) throws Db4oIOException {
validateReadOnly();
long startAddress = _position;
int bytesToWrite = length;
int bufferOffset = 0;
while (bytesToWrite > 0) {
// page doesn't need to loadFromDisk if the whole page is dirty
boolean loadFromDisk = (bytesToWrite < _pageSize)
|| (startAddress % _pageSize != 0);
final Page page = getPage(startAddress, loadFromDisk);
page.ensureEndAddress(getLength());
final int writtenBytes = page.write(buffer, bufferOffset, startAddress, bytesToWrite);
flushIfHeaderBlockPage(page);
movePageToHead(page);
bytesToWrite -= writtenBytes;
startAddress += writtenBytes;
bufferOffset += writtenBytes;
}
long endAddress = startAddress;
_position = endAddress;
_fileLength = Math.max(endAddress, _fileLength);
}
private void flushIfHeaderBlockPage(final Page page) {
if(containsHeaderBlock(page)) {
flushPage(page);
}
}
private void validateReadOnly() {
if(_readOnly) {
throw new Db4oIOException();
}
}
/**
* Flushes cache to a physical storage
*/
public void sync() throws Db4oIOException {
validateReadOnly();
flushAllPages();
_io.sync();
}
/**
* Returns the file length
*/
public long getLength() throws Db4oIOException {
return _fileLength;
}
/**
* Flushes and closes the file
*/
public void close() throws Db4oIOException {
try {
flushAllPages();
}
finally {
_io.close();
}
}
public IoAdapter delegatedIoAdapter() {
return _io.delegatedIoAdapter();
}
private Page getPage(long startAddress, boolean loadFromDisk)
throws Db4oIOException {
Page page = getPageFromCache(startAddress);
if (page != null) {
if (containsHeaderBlock(page)) {
getPageFromDisk(page, startAddress);
}
page.ensureEndAddress(_fileLength);
return page;
}
// in case that page is not found in the cache
page = getFreePageFromCache();
if (loadFromDisk) {
getPageFromDisk(page, startAddress);
} else {
resetPageAddress(page, startAddress);
}
return page;
}
private boolean containsHeaderBlock(Page page) {
return page.startAddress() <= FileHeader1.HEADER_LENGTH;
}
private void resetPageAddress(Page page, long startAddress) {
page.startAddress(startAddress);
page.endAddress(startAddress + _pageSize);
}
private Page getFreePageFromCache() throws Db4oIOException {
if (!_tail.isFree()) {
flushPage(_tail);
// _posPageMap.remove(new Long(tail.startPosition / PAGE_SIZE));
}
return _tail;
}
private Page getPageFromCache(long pos) throws Db4oIOException {
Page page = _head;
while (page != null) {
if (page.contains(pos)) {
return page;
}
page = page._next;
}
return null;
// Page page = (Page) _posPageMap.get(new Long(pos/PAGE_SIZE));
// return page;
}
private void flushAllPages() throws Db4oIOException {
Page node = _head;
while (node != null) {
flushPage(node);
node = node._next;
}
}
private void flushPage(Page page) throws Db4oIOException {
if (!page._dirty) {
return;
}
ioSeek(page.startAddress());
writePageToDisk(page);
return;
}
private void getPageFromDisk(Page page, long pos) throws Db4oIOException {
long startAddress = pos - pos % _pageSize;
page.startAddress(startAddress);
ioSeek(page._startAddress);
int count = ioRead(page);
if (count > 0) {
page.endAddress(startAddress + count);
} else {
page.endAddress(startAddress);
}
// _posPageMap.put(new Long(page.startPosition / PAGE_SIZE), page);
}
private int ioRead(Page page) throws Db4oIOException {
int count = _io.read(page._buffer);
if (count > 0) {
_filePointer = page._startAddress + count;
}
return count;
}
private void movePageToHead(Page page) {
if (page == _head) {
return;
}
if (page == _tail) {
Page tempTail = _tail._prev;
tempTail._next = null;
_tail._next = _head;
_tail._prev = null;
_head._prev = page;
_head = _tail;
_tail = tempTail;
} else {
page._prev._next = page._next;
page._next._prev = page._prev;
page._next = _head;
_head._prev = page;
page._prev = null;
_head = page;
}
}
private void writePageToDisk(Page page) throws Db4oIOException {
validateReadOnly();
try{
_io.write(page._buffer, page.size());
_filePointer = page.endAddress();
page._dirty = false;
}catch (Db4oIOException e){
_readOnly = true;
throw e;
}
}
/**
* Moves the pointer to the specified file position
*
* @param pos
* position within the file
*/
public void seek(long pos) throws Db4oIOException {
_position = pos;
}
private void ioSeek(long pos) throws Db4oIOException {
if (_filePointer != pos) {
_io.seek(pos);
_filePointer = pos;
}
}
private static class Page {
byte[] _buffer;
long _startAddress = -1;
long _endAddress;
final int _bufferSize;
boolean _dirty;
Page _prev;
Page _next;
private byte[] zeroBytes;
public Page(int size) {
_bufferSize = size;
_buffer = new byte[_bufferSize];
}
/*
* This method must be invoked before page.write/read, because seek and
* write may write ahead the end of file.
*/
void ensureEndAddress(long fileLength) {
long bufferEndAddress = _startAddress + _bufferSize;
if (_endAddress < bufferEndAddress && fileLength > _endAddress) {
long newEndAddress = Math.min(fileLength, bufferEndAddress);
if (zeroBytes == null) {
zeroBytes = new byte[_bufferSize];
}
System.arraycopy(zeroBytes, 0, _buffer,
(int) (_endAddress - _startAddress),
(int) (newEndAddress - _endAddress));
_endAddress = newEndAddress;
}
}
long endAddress() {
return _endAddress;
}
void startAddress(long address) {
_startAddress = address;
}
long startAddress() {
return _startAddress;
}
void endAddress(long address) {
_endAddress = address;
}
int size() {
return (int) (_endAddress - _startAddress);
}
int read(byte[] out, int outOffset, long startAddress, int length) {
int bufferOffset = (int) (startAddress - _startAddress);
int pageAvailbeDataSize = (int) (_endAddress - startAddress);
int readBytes = Math.min(pageAvailbeDataSize, length);
if (readBytes <= 0) { // meaning reach EOF
return -1;
}
System.arraycopy(_buffer, bufferOffset, out, outOffset, readBytes);
return readBytes;
}
int write(byte[] data, int dataOffset, long startAddress, int length) {
int bufferOffset = (int) (startAddress - _startAddress);
int pageAvailabeBufferSize = _bufferSize - bufferOffset;
int writtenBytes = Math.min(pageAvailabeBufferSize, length);
System.arraycopy(data, dataOffset, _buffer, bufferOffset,
writtenBytes);
long endAddress = startAddress + writtenBytes;
if (endAddress > _endAddress) {
_endAddress = endAddress;
}
_dirty = true;
return writtenBytes;
}
boolean contains(long address) {
return (_startAddress != -1 && address >= _startAddress && address < _startAddress
+ _bufferSize);
}
boolean isFree() {
return _startAddress == -1;
}
}
}
| potty-dzmeia/db4o | src/db4oj/core/src/com/db4o/io/CachedIoAdapter.java | Java | gpl-3.0 | 13,271 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qcoreapplication.h>
#include <qdebug.h>
#include <qfiledialog.h>
#include <qabstractitemdelegate.h>
#include <qdirmodel.h>
#include <qitemdelegate.h>
#include <qlistview.h>
#include <qcombobox.h>
#include <qpushbutton.h>
#include <qtoolbutton.h>
#include <qtreeview.h>
#include <qheaderview.h>
#include <qcompleter.h>
#include <qaction.h>
#include <qdialogbuttonbox.h>
#include <qsortfilterproxymodel.h>
#include <qlineedit.h>
#include <qlayout.h>
#include <qmenu.h>
#include "../../../../../src/widgets/dialogs/qsidebar_p.h"
#include "../../../../../src/widgets/dialogs/qfilesystemmodel_p.h"
#include "../../../../../src/widgets/dialogs/qfiledialog_p.h"
#include <qpa/qplatformdialoghelper.h>
#if defined(Q_OS_WIN)
#include "../../../network-settings.h"
#endif
#if defined QT_BUILD_INTERNAL
QT_BEGIN_NAMESPACE
Q_GUI_EXPORT bool qt_test_isFetchedRoot();
Q_GUI_EXPORT void qt_test_resetFetchedRoot();
QT_END_NAMESPACE
#endif
static QByteArray msgDoesNotExist(const QString &name)
{
return (QLatin1Char('"') + QDir::toNativeSeparators(name)
+ QLatin1String("\" does not exist.")).toLocal8Bit();
}
class tst_QFileDialog2 : public QObject
{
Q_OBJECT
public:
tst_QFileDialog2();
private slots:
void initTestCase();
void init();
void cleanup();
#ifdef QT_BUILD_INTERNAL
void deleteDirAndFiles();
void listRoot();
void task227304_proxyOnFileDialog();
void task236402_dontWatchDeletedDir();
void task251321_sideBarHiddenEntries();
void task251341_sideBarRemoveEntries();
void task257579_sideBarWithNonCleanUrls();
#endif
void heapCorruption();
void filter();
void showNameFilterDetails();
void unc();
void emptyUncPath();
#if !defined(QT_NO_CONTEXTMENU) && !defined(QT_NO_MENU)
void task143519_deleteAndRenameActionBehavior();
#endif
void task178897_minimumSize();
void task180459_lastDirectory_data();
void task180459_lastDirectory();
#ifndef Q_OS_MAC
void task227930_correctNavigationKeyboardBehavior();
#endif
#if defined(Q_OS_WIN)
void task226366_lowerCaseHardDriveWindows();
#endif
void completionOnLevelAfterRoot();
void task233037_selectingDirectory();
void task235069_hideOnEscape_data();
void task235069_hideOnEscape();
void task203703_returnProperSeparator();
void task228844_ensurePreviousSorting();
void task239706_editableFilterCombo();
void task218353_relativePaths();
void task254490_selectFileMultipleTimes();
void task259105_filtersCornerCases();
void QTBUG4419_lineEditSelectAll();
void QTBUG6558_showDirsOnly();
void QTBUG4842_selectFilterWithHideNameFilterDetails();
void dontShowCompleterOnRoot();
void nameFilterParsing_data();
void nameFilterParsing();
private:
void cleanupSettingsFile();
QTemporaryDir tempDir;
};
tst_QFileDialog2::tst_QFileDialog2()
: tempDir(QDir::tempPath() + "/tst_qfiledialog2.XXXXXX")
{
QCoreApplication::setAttribute(Qt::AA_DontUseNativeDialogs);
}
void tst_QFileDialog2::cleanupSettingsFile()
{
// clean up the sidebar between each test
QSettings settings(QSettings::UserScope, QLatin1String("QtProject"));
settings.beginGroup(QLatin1String("FileDialog"));
settings.remove(QString());
settings.endGroup();
settings.beginGroup(QLatin1String("Qt")); // Compatibility settings
settings.remove(QLatin1String("filedialog"));
settings.endGroup();
}
void tst_QFileDialog2::initTestCase()
{
QVERIFY2(tempDir.isValid(), qPrintable(tempDir.errorString()));
QStandardPaths::setTestModeEnabled(true);
cleanupSettingsFile();
}
void tst_QFileDialog2::init()
{
QFileDialogPrivate::setLastVisitedDirectory(QUrl());
// populate the sidebar with some default settings
QFileDialog fd;
}
void tst_QFileDialog2::cleanup()
{
cleanupSettingsFile();
}
#ifdef QT_BUILD_INTERNAL
void tst_QFileDialog2::listRoot()
{
QFileInfoGatherer fileInfoGatherer;
fileInfoGatherer.start();
QTest::qWait(1500);
qt_test_resetFetchedRoot();
QString dir(QDir::currentPath());
QFileDialog fd(0, QString(), dir);
fd.show();
QCOMPARE(qt_test_isFetchedRoot(),false);
fd.setDirectory("");
QTest::qWait(500);
QCOMPARE(qt_test_isFetchedRoot(),true);
}
#endif
void tst_QFileDialog2::heapCorruption()
{
QVector<QFileDialog*> dialogs;
for (int i=0; i < 10; i++) {
QFileDialog *f = new QFileDialog(NULL);
dialogs << f;
}
qDeleteAll(dialogs);
}
struct FriendlyQFileDialog : public QFileDialog
{
friend class tst_QFileDialog2;
Q_DECLARE_PRIVATE(QFileDialog)
};
#ifdef QT_BUILD_INTERNAL
void tst_QFileDialog2::deleteDirAndFiles()
{
QString tempPath = tempDir.path() + "/QFileDialogTestDir4FullDelete";
QDir dir;
QVERIFY(dir.mkpath(tempPath + "/foo"));
QVERIFY(dir.mkpath(tempPath + "/foo/B"));
QVERIFY(dir.mkpath(tempPath + "/foo/B"));
QVERIFY(dir.mkpath(tempPath + "/foo/c"));
QVERIFY(dir.mkpath(tempPath + "/bar"));
QFile(tempPath + "/foo/a");
QTemporaryFile *t;
t = new QTemporaryFile(tempPath + "/foo/aXXXXXX");
t->setAutoRemove(false);
QVERIFY2(t->open(), qPrintable(t->errorString()));
t->close();
delete t;
t = new QTemporaryFile(tempPath + "/foo/B/yXXXXXX");
t->setAutoRemove(false);
QVERIFY2(t->open(), qPrintable(t->errorString()));
t->close();
delete t;
FriendlyQFileDialog fd;
fd.d_func()->removeDirectory(tempPath);
QFileInfo info(tempPath);
QTest::qWait(2000);
QVERIFY(!info.exists());
}
#endif
void tst_QFileDialog2::filter()
{
QFileDialog fd;
QAction *hiddenAction = fd.findChild<QAction*>("qt_show_hidden_action");
QVERIFY(hiddenAction);
QVERIFY(hiddenAction->isEnabled());
QVERIFY(!hiddenAction->isChecked());
QDir::Filters filter = fd.filter();
filter |= QDir::Hidden;
fd.setFilter(filter);
QVERIFY(hiddenAction->isChecked());
}
void tst_QFileDialog2::showNameFilterDetails()
{
QFileDialog fd;
QComboBox *filters = fd.findChild<QComboBox*>("fileTypeCombo");
QVERIFY(filters);
QVERIFY(fd.isNameFilterDetailsVisible());
QStringList filterChoices;
filterChoices << "Image files (*.png *.xpm *.jpg)"
<< "Text files (*.txt)"
<< "Any files (*.*)";
fd.setNameFilters(filterChoices);
fd.setNameFilterDetailsVisible(false);
QCOMPARE(filters->itemText(0), QString("Image files"));
QCOMPARE(filters->itemText(1), QString("Text files"));
QCOMPARE(filters->itemText(2), QString("Any files"));
fd.setNameFilterDetailsVisible(true);
QCOMPARE(filters->itemText(0), filterChoices.at(0));
QCOMPARE(filters->itemText(1), filterChoices.at(1));
QCOMPARE(filters->itemText(2), filterChoices.at(2));
}
void tst_QFileDialog2::unc()
{
#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
// Only test UNC on Windows./
QString dir("\\\\" + QtNetworkSettings::winServerName() + "\\testsharewritable");
#else
QString dir(QDir::currentPath());
#endif
QVERIFY2(QFile::exists(dir), msgDoesNotExist(dir).constData());
QFileDialog fd(0, QString(), dir);
QFileSystemModel *model = fd.findChild<QFileSystemModel*>("qt_filesystem_model");
QVERIFY(model);
QCOMPARE(model->index(fd.directory().absolutePath()), model->index(dir));
}
void tst_QFileDialog2::emptyUncPath()
{
QFileDialog fd;
fd.show();
QLineEdit *lineEdit = fd.findChild<QLineEdit*>("fileNameEdit");
QVERIFY(lineEdit);
// press 'keys' for the input
for (int i = 0; i < 3 ; ++i)
QTest::keyPress(lineEdit, Qt::Key_Backslash);
QFileSystemModel *model = fd.findChild<QFileSystemModel*>("qt_filesystem_model");
QVERIFY(model);
}
#if !defined(QT_NO_CONTEXTMENU) && !defined(QT_NO_MENU)
struct MenuCloser : public QObject {
QWidget *w;
explicit MenuCloser(QWidget *w) : w(w) {}
void close()
{
QMenu *menu = w->findChild<QMenu*>();
if (!menu) {
qDebug("%s: cannot find file dialog child of type QMenu", Q_FUNC_INFO);
w->close();
}
QTest::keyClick(menu, Qt::Key_Escape);
}
};
static bool openContextMenu(QFileDialog &fd)
{
QListView *list = fd.findChild<QListView*>("listView");
if (!list) {
qDebug("%s: didn't find file dialog child \"listView\"", Q_FUNC_INFO);
return false;
}
QTimer timer;
timer.setInterval(300);
timer.setSingleShot(true);
MenuCloser closer(&fd);
QObject::connect(&timer, &QTimer::timeout, &closer, &MenuCloser::close);
timer.start();
QContextMenuEvent cme(QContextMenuEvent::Mouse, QPoint(10, 10));
qApp->sendEvent(list->viewport(), &cme); // blocks until menu is closed again.
return true;
}
void tst_QFileDialog2::task143519_deleteAndRenameActionBehavior()
{
// test based on task233037_selectingDirectory
struct TestContext {
explicit TestContext(const QString &path) : current(path) {}
~TestContext() {
file.remove();
current.rmdir(test.dirName());
}
QDir current;
QDir test;
QFile file;
};
TestContext ctx(tempDir.path());
// setup testbed
QVERIFY(ctx.current.mkdir("task143519_deleteAndRenameActionBehavior_test")); // ensure at least one item
ctx.test = ctx.current;
QVERIFY(ctx.test.cd("task143519_deleteAndRenameActionBehavior_test"));
ctx.file.setFileName(ctx.test.absoluteFilePath("hello"));
QVERIFY(ctx.file.open(QIODevice::WriteOnly));
QVERIFY(ctx.file.permissions() & QFile::WriteUser);
ctx.file.close();
QFileDialog fd;
fd.setViewMode(QFileDialog::List);
fd.setDirectory(ctx.test.absolutePath());
fd.selectFile(ctx.file.fileName());
fd.show();
QTest::qWaitForWindowActive(&fd);
// grab some internals:
QAction *rm = fd.findChild<QAction*>("qt_delete_action");
QVERIFY(rm);
QAction *mv = fd.findChild<QAction*>("qt_rename_action");
QVERIFY(mv);
// these are the real test cases:
// defaults
QVERIFY(openContextMenu(fd));
QCOMPARE(fd.selectedFiles(), QStringList(ctx.file.fileName()));
QCOMPARE(rm->isEnabled(), !fd.isReadOnly());
QCOMPARE(mv->isEnabled(), !fd.isReadOnly());
// change to non-defaults:
fd.setReadOnly(!fd.isReadOnly());
QVERIFY(openContextMenu(fd));
QCOMPARE(fd.selectedFiles().size(), 1);
QCOMPARE(rm->isEnabled(), !fd.isReadOnly());
QCOMPARE(mv->isEnabled(), !fd.isReadOnly());
// and changed back to defaults:
fd.setReadOnly(!fd.isReadOnly());
QVERIFY(openContextMenu(fd));
QCOMPARE(fd.selectedFiles().size(), 1);
QCOMPARE(rm->isEnabled(), !fd.isReadOnly());
QCOMPARE(mv->isEnabled(), !fd.isReadOnly());
}
#endif // !QT_NO_CONTEXTMENU && !QT_NO_MENU
void tst_QFileDialog2::task178897_minimumSize()
{
QFileDialog fd;
QSize oldMs = fd.layout()->minimumSize();
QStringList history = fd.history();
history << QDir::toNativeSeparators("/verylongdirectory/"
"aaaaaaaaaabbbbbbbbcccccccccccddddddddddddddeeeeeeeeeeeeffffffffffgggtggggggggghhhhhhhhiiiiiijjjk");
fd.setHistory(history);
fd.show();
QSize ms = fd.layout()->minimumSize();
QVERIFY(ms.width() <= oldMs.width());
}
void tst_QFileDialog2::task180459_lastDirectory_data()
{
QTest::addColumn<QString>("path");
QTest::addColumn<QString>("directory");
QTest::addColumn<bool>("isEnabled");
QTest::addColumn<QString>("result");
QTest::newRow("path+file") << QDir::homePath() + QDir::separator() + "foo"
<< QDir::homePath() << true
<< QDir::homePath() + QDir::separator() + "foo" ;
QTest::newRow("no path") << ""
<< tempDir.path() << false << QString();
QTest::newRow("file") << "foo"
<< QDir::currentPath() << true
<< QDir::currentPath() + QDir::separator() + "foo" ;
QTest::newRow("path") << QDir::homePath()
<< QDir::homePath() << false << QString();
QTest::newRow("path not existing") << "/usr/bin/foo/bar/foo/foo.txt"
<< tempDir.path() << true
<< tempDir.path() + QDir::separator() + "foo.txt";
}
void tst_QFileDialog2::task180459_lastDirectory()
{
if (!QGuiApplication::platformName().compare(QLatin1String("cocoa"), Qt::CaseInsensitive))
QSKIP("Insignificant on OSX"); //QTBUG-39183
//first visit the temp directory and close the dialog
QFileDialog *dlg = new QFileDialog(0, "", tempDir.path());
QFileSystemModel *model = dlg->findChild<QFileSystemModel*>("qt_filesystem_model");
QVERIFY(model);
QCOMPARE(model->index(tempDir.path()), model->index(dlg->directory().absolutePath()));
delete dlg;
QFETCH(QString, path);
QFETCH(QString, directory);
QFETCH(bool, isEnabled);
QFETCH(QString, result);
dlg = new QFileDialog(0, "", path);
model = dlg->findChild<QFileSystemModel*>("qt_filesystem_model");
QVERIFY(model);
dlg->setAcceptMode(QFileDialog::AcceptSave);
QCOMPARE(model->index(dlg->directory().absolutePath()), model->index(directory));
QDialogButtonBox *buttonBox = dlg->findChild<QDialogButtonBox*>("buttonBox");
QPushButton *button = buttonBox->button(QDialogButtonBox::Save);
QVERIFY(button);
QCOMPARE(button->isEnabled(), isEnabled);
if (isEnabled)
QCOMPARE(model->index(result), model->index(dlg->selectedFiles().first()));
delete dlg;
}
class FilterDirModel : public QSortFilterProxyModel
{
public:
FilterDirModel(QString root, QObject* parent=0):QSortFilterProxyModel(parent), m_root(root)
{}
~FilterDirModel()
{};
protected:
bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
QModelIndex parentIndex;
parentIndex = source_parent;
QString path;
path = parentIndex.child(source_row,0).data(Qt::DisplayRole).toString();
do {
path = parentIndex.data(Qt::DisplayRole).toString() + QLatin1Char('/') + path;
parentIndex = parentIndex.parent();
} while(parentIndex.isValid());
QFileInfo info(path);
if (info.isDir() && (QDir(path) != m_root))
return false;
return true;
}
private:
QDir m_root;
};
class sortProxy : public QSortFilterProxyModel
{
public:
sortProxy(QObject *parent) : QSortFilterProxyModel(parent)
{
}
protected:
virtual bool lessThan(const QModelIndex &left, const QModelIndex &right) const
{
QFileSystemModel * const model = qobject_cast<QFileSystemModel *>(sourceModel());
const QFileInfo leftInfo(model->fileInfo(left));
const QFileInfo rightInfo(model->fileInfo(right));
if (leftInfo.isDir() == rightInfo.isDir())
return(leftInfo.filePath().compare(rightInfo.filePath(),Qt::CaseInsensitive) < 0);
else if (leftInfo.isDir())
return(false);
else
return(true);
}
};
class CrashDialog : public QFileDialog
{
Q_OBJECT
public:
CrashDialog(QWidget *parent, const QString &caption, const
QString &dir, const QString &filter)
: QFileDialog(parent, caption, dir, filter)
{
sortProxy *proxyModel = new sortProxy(this);
setProxyModel(proxyModel);
}
};
#ifdef QT_BUILD_INTERNAL
void tst_QFileDialog2::task227304_proxyOnFileDialog()
{
QFileDialog fd(0, "", QDir::currentPath(), 0);
fd.setProxyModel(new FilterDirModel(QDir::currentPath()));
fd.show();
QLineEdit *edit = fd.findChild<QLineEdit*>("fileNameEdit");
QTest::qWait(200);
QTest::keyClick(edit, Qt::Key_T);
QTest::keyClick(edit, Qt::Key_S);
QTest::qWait(200);
QTest::keyClick(edit->completer()->popup(), Qt::Key_Down);
CrashDialog *dialog = new CrashDialog(0, QString("crash dialog test"), QDir::homePath(), QString("*") );
dialog->setFileMode(QFileDialog::ExistingFile);
dialog->show();
QListView *list = dialog->findChild<QListView*>("listView");
QTest::qWait(200);
QTest::keyClick(list, Qt::Key_Down);
QTest::keyClick(list, Qt::Key_Return);
QTest::qWait(200);
dialog->close();
fd.close();
QFileDialog fd2(0, "I should not crash with a proxy", tempDir.path(), 0);
QSortFilterProxyModel *pm = new QSortFilterProxyModel;
fd2.setProxyModel(pm);
fd2.show();
QSidebar *sidebar = fd2.findChild<QSidebar*>("sidebar");
sidebar->setFocus();
sidebar->selectUrl(QUrl::fromLocalFile(QDir::homePath()));
QTest::mouseClick(sidebar->viewport(), Qt::LeftButton, 0, sidebar->visualRect(sidebar->model()->index(1, 0)).center());
QTest::qWait(250);
//We shouldn't crash
}
#endif
#ifndef Q_OS_MAC
// The following test implies the folder created will appear first in
// the list. On Mac files sorting depends on the locale and the order
// displayed cannot be known for sure.
void tst_QFileDialog2::task227930_correctNavigationKeyboardBehavior()
{
QDir current = QDir::currentPath();
current.mkdir("test");
current.cd("test");
QFile file("test/out.txt");
QFile file2("test/out2.txt");
QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
QVERIFY(file2.open(QIODevice::WriteOnly | QIODevice::Text));
current.cdUp();
current.mkdir("test2");
QFileDialog fd;
fd.setViewMode(QFileDialog::List);
fd.setDirectory(current.absolutePath());
fd.show();
QListView *list = fd.findChild<QListView*>("listView");
QTest::qWait(200);
QTest::keyClick(list, Qt::Key_Down);
QTest::keyClick(list, Qt::Key_Return);
QTest::qWait(200);
QTest::mouseClick(list->viewport(), Qt::LeftButton,0);
QTest::keyClick(list, Qt::Key_Down);
QTest::keyClick(list, Qt::Key_Backspace);
QTest::qWait(200);
QTest::keyClick(list, Qt::Key_Down);
QTest::keyClick(list, Qt::Key_Down);
QTest::keyClick(list, Qt::Key_Return);
QTest::qWait(200);
QCOMPARE(fd.isVisible(), true);
QTest::qWait(200);
file.close();
file2.close();
file.remove();
file2.remove();
current.rmdir("test");
current.rmdir("test2");
}
#endif
#if defined(Q_OS_WIN)
void tst_QFileDialog2::task226366_lowerCaseHardDriveWindows()
{
QFileDialog fd;
fd.setDirectory(QDir::root().path());
fd.show();
QLineEdit *edit = fd.findChild<QLineEdit*>("fileNameEdit");
QToolButton *buttonParent = fd.findChild<QToolButton*>("toParentButton");
QTest::qWait(200);
QTest::mouseClick(buttonParent, Qt::LeftButton,0,QPoint(0,0));
QTest::qWait(2000);
QTest::keyClick(edit, Qt::Key_C);
QTest::qWait(200);
QTest::keyClick(edit->completer()->popup(), Qt::Key_Down);
QTest::qWait(200);
QCOMPARE(edit->text(), QString("C:/"));
QTest::qWait(2000);
//i clear my previous selection in the completer
QTest::keyClick(edit->completer()->popup(), Qt::Key_Down);
edit->clear();
QTest::keyClick(edit, (char)(Qt::Key_C | Qt::SHIFT));
QTest::qWait(200);
QTest::keyClick(edit->completer()->popup(), Qt::Key_Down);
QCOMPARE(edit->text(), QString("C:/"));
}
#endif
void tst_QFileDialog2::completionOnLevelAfterRoot()
{
QFileDialog fd;
#if defined(Q_OS_WIN)
fd.setDirectory("C:/");
QDir current = fd.directory();
QStringList entryList = current.entryList(QStringList(), QDir::Dirs);
// Find a suitable test dir under c:-root:
// - At least 6 characters long
// - Ascii, letters only
// - No another dir with same start
QString testDir;
foreach (const QString &entry, entryList) {
if (entry.size() > 5 && QString(entry.toLatin1()).compare(entry) == 0) {
bool invalid = false;
for (int i = 0; i < 5; i++) {
if (!entry.at(i).isLetter()) {
invalid = true;
break;
}
}
if (!invalid) {
foreach (const QString &check, entryList) {
if (check.startsWith(entry.left(5), Qt::CaseInsensitive) && check != entry) {
invalid = true;
break;
}
}
}
if (!invalid) {
testDir = entry;
break;
}
}
}
if (testDir.isEmpty())
QSKIP("This test requires to have an unique directory of at least six ascii characters under c:/");
#else
fd.setFilter(QDir::Hidden | QDir::AllDirs | QDir::Files | QDir::System);
fd.setDirectory("/");
QDir etc("/etc");
if (!etc.exists())
QSKIP("This test requires to have an etc directory under /");
#endif
fd.show();
QLineEdit *edit = fd.findChild<QLineEdit*>("fileNameEdit");
QTest::qWait(2000);
#if defined(Q_OS_WIN)
//I love testlib :D
for (int i = 0; i < 5; i++)
QTest::keyClick(edit, testDir.at(i).toLower().toLatin1() - 'a' + Qt::Key_A);
#else
QTest::keyClick(edit, Qt::Key_E);
QTest::keyClick(edit, Qt::Key_T);
#endif
QTest::qWait(200);
QTest::keyClick(edit->completer()->popup(), Qt::Key_Down);
QTest::qWait(200);
#if defined(Q_OS_WIN)
QCOMPARE(edit->text(), testDir);
#else
QTRY_COMPARE(edit->text(), QString("etc"));
#endif
}
void tst_QFileDialog2::task233037_selectingDirectory()
{
QDir current = QDir::currentPath();
current.mkdir("test");
QFileDialog fd;
fd.setViewMode(QFileDialog::List);
fd.setDirectory(current.absolutePath());
fd.setAcceptMode( QFileDialog::AcceptSave);
fd.show();
QListView *list = fd.findChild<QListView*>("listView");
QTest::qWait(3000); // Wait for sort to settle (I need a signal).
#ifdef QT_KEYPAD_NAVIGATION
list->setEditFocus(true);
#endif
QTest::keyClick(list, Qt::Key_Down);
QTest::qWait(100);
QDialogButtonBox *buttonBox = fd.findChild<QDialogButtonBox*>("buttonBox");
QPushButton *button = buttonBox->button(QDialogButtonBox::Save);
QVERIFY(button);
QCOMPARE(button->isEnabled(), true);
current.rmdir("test");
}
void tst_QFileDialog2::task235069_hideOnEscape_data()
{
QTest::addColumn<QString>("childName");
QTest::addColumn<QFileDialog::ViewMode>("viewMode");
QTest::newRow("listView") << QStringLiteral("listView") << QFileDialog::List;
QTest::newRow("fileNameEdit") << QStringLiteral("fileNameEdit") << QFileDialog::List;
QTest::newRow("treeView") << QStringLiteral("treeView") << QFileDialog::Detail;
}
void tst_QFileDialog2::task235069_hideOnEscape()
{
QFETCH(QString, childName);
QFETCH(QFileDialog::ViewMode, viewMode);
QDir current = QDir::currentPath();
QFileDialog fd;
QSignalSpy spyFinished(&fd, &QDialog::finished);
QVERIFY(spyFinished.isValid());
QSignalSpy spyRejected(&fd, &QDialog::rejected);
QVERIFY(spyRejected.isValid());
fd.setViewMode(viewMode);
fd.setDirectory(current.absolutePath());
fd.setAcceptMode(QFileDialog::AcceptSave);
fd.show();
QWidget *child = fd.findChild<QWidget *>(childName);
QVERIFY(child);
child->setFocus();
QTest::qWait(200);
QTest::keyClick(child, Qt::Key_Escape);
QCOMPARE(fd.isVisible(), false);
QCOMPARE(spyFinished.count(), 1); // QTBUG-7690
QCOMPARE(spyRejected.count(), 1); // reject(), don't hide()
}
#ifdef QT_BUILD_INTERNAL
void tst_QFileDialog2::task236402_dontWatchDeletedDir()
{
//THIS TEST SHOULD NOT DISPLAY WARNINGS
QDir current = QDir::currentPath();
//make sure it is the first on the list
current.mkdir("aaaaaaaaaa");
FriendlyQFileDialog fd;
fd.setViewMode(QFileDialog::List);
fd.setDirectory(current.absolutePath());
fd.setAcceptMode( QFileDialog::AcceptSave);
fd.show();
QListView *list = fd.findChild<QListView*>("listView");
list->setFocus();
QTest::qWait(200);
QTest::keyClick(list, Qt::Key_Return);
QTest::qWait(200);
QTest::keyClick(list, Qt::Key_Backspace);
QTest::keyClick(list, Qt::Key_Down);
QTest::qWait(200);
fd.d_func()->removeDirectory(current.absolutePath() + "/aaaaaaaaaa/");
QTest::qWait(1000);
}
#endif
void tst_QFileDialog2::task203703_returnProperSeparator()
{
QDir current = QDir::currentPath();
current.mkdir("aaaaaaaaaaaaaaaaaa");
QFileDialog fd;
fd.setDirectory(current.absolutePath());
fd.setViewMode(QFileDialog::List);
fd.setFileMode(QFileDialog::Directory);
fd.show();
QTest::qWait(500);
QListView *list = fd.findChild<QListView*>("listView");
list->setFocus();
QTest::qWait(200);
QTest::keyClick(list, Qt::Key_Return);
QTest::qWait(1000);
QDialogButtonBox *buttonBox = fd.findChild<QDialogButtonBox*>("buttonBox");
QPushButton *button = buttonBox->button(QDialogButtonBox::Cancel);
QTest::keyClick(button, Qt::Key_Return);
QTest::qWait(500);
QString result = fd.selectedFiles().first();
QVERIFY(result.at(result.count() - 1) != '/');
QVERIFY(!result.contains('\\'));
current.rmdir("aaaaaaaaaaaaaaaaaa");
}
void tst_QFileDialog2::task228844_ensurePreviousSorting()
{
QDir current = QDir::currentPath();
current.mkdir("aaaaaaaaaaaaaaaaaa");
current.cd("aaaaaaaaaaaaaaaaaa");
current.mkdir("a");
current.mkdir("b");
current.mkdir("c");
current.mkdir("d");
current.mkdir("e");
current.mkdir("f");
current.mkdir("g");
QTemporaryFile *tempFile = new QTemporaryFile(current.absolutePath() + "/rXXXXXX");
QVERIFY2(tempFile->open(), qPrintable(tempFile->errorString()));
current.cdUp();
QFileDialog fd;
fd.setDirectory(current.absolutePath());
fd.setViewMode(QFileDialog::Detail);
fd.show();
QTest::qWait(500);
QTreeView *tree = fd.findChild<QTreeView*>("treeView");
tree->header()->setSortIndicator(3,Qt::DescendingOrder);
QTest::qWait(200);
QDialogButtonBox *buttonBox = fd.findChild<QDialogButtonBox*>("buttonBox");
QPushButton *button = buttonBox->button(QDialogButtonBox::Open);
QTest::mouseClick(button, Qt::LeftButton);
QTest::qWait(500);
QFileDialog fd2;
fd2.setFileMode(QFileDialog::Directory);
fd2.restoreState(fd.saveState());
current.cd("aaaaaaaaaaaaaaaaaa");
fd2.setDirectory(current.absolutePath());
fd2.show();
QTest::qWait(500);
QTreeView *tree2 = fd2.findChild<QTreeView*>("treeView");
tree2->setFocus();
QCOMPARE(tree2->rootIndex().data(QFileSystemModel::FilePathRole).toString(),current.absolutePath());
QDialogButtonBox *buttonBox2 = fd2.findChild<QDialogButtonBox*>("buttonBox");
QPushButton *button2 = buttonBox2->button(QDialogButtonBox::Open);
fd2.selectFile("g");
QTest::mouseClick(button2, Qt::LeftButton);
QTest::qWait(500);
QCOMPARE(fd2.selectedFiles().first(), current.absolutePath() + QLatin1String("/g"));
QFileDialog fd3(0, "This is a third file dialog", tempFile->fileName());
fd3.restoreState(fd.saveState());
fd3.setFileMode(QFileDialog::Directory);
fd3.show();
QTest::qWait(500);
QTreeView *tree3 = fd3.findChild<QTreeView*>("treeView");
tree3->setFocus();
QCOMPARE(tree3->rootIndex().data(QFileSystemModel::FilePathRole).toString(), current.absolutePath());
QDialogButtonBox *buttonBox3 = fd3.findChild<QDialogButtonBox*>("buttonBox");
QPushButton *button3 = buttonBox3->button(QDialogButtonBox::Open);
QTest::mouseClick(button3, Qt::LeftButton);
QTest::qWait(500);
QCOMPARE(fd3.selectedFiles().first(), tempFile->fileName());
current.cd("aaaaaaaaaaaaaaaaaa");
current.rmdir("a");
current.rmdir("b");
current.rmdir("c");
current.rmdir("d");
current.rmdir("e");
current.rmdir("f");
current.rmdir("g");
tempFile->close();
delete tempFile;
current.cdUp();
current.rmdir("aaaaaaaaaaaaaaaaaa");
}
void tst_QFileDialog2::task239706_editableFilterCombo()
{
QFileDialog d;
d.setNameFilter("*.cpp *.h");
d.show();
QTest::qWait(500);
QList<QComboBox *> comboList = d.findChildren<QComboBox *>();
QComboBox *filterCombo = 0;
foreach (QComboBox *combo, comboList) {
if (combo->objectName() == QString("fileTypeCombo")) {
filterCombo = combo;
break;
}
}
QVERIFY(filterCombo);
filterCombo->setEditable(true);
QTest::mouseClick(filterCombo, Qt::LeftButton);
QTest::keyPress(filterCombo, Qt::Key_X);
QTest::keyPress(filterCombo, Qt::Key_Enter); // should not trigger assertion failure
}
void tst_QFileDialog2::task218353_relativePaths()
{
QDir appDir = QDir::current();
QVERIFY(appDir.cdUp() != false);
QFileDialog d(0, "TestDialog", "..");
QCOMPARE(d.directory().absolutePath(), appDir.absolutePath());
d.setDirectory(appDir.absolutePath() + QLatin1String("/non-existing-directory/../another-non-existing-dir/../"));
QCOMPARE(d.directory().absolutePath(), appDir.absolutePath());
QDir::current().mkdir("test");
appDir = QDir::current();
d.setDirectory(appDir.absolutePath() + QLatin1String("/test/../test/../"));
QCOMPARE(d.directory().absolutePath(), appDir.absolutePath());
appDir.rmdir("test");
}
#ifdef QT_BUILD_INTERNAL
void tst_QFileDialog2::task251321_sideBarHiddenEntries()
{
QFileDialog fd;
QDir current = QDir::currentPath();
current.mkdir(".hidden");
QDir hiddenDir = QDir(".hidden");
hiddenDir.mkdir("subdir");
QDir hiddenSubDir = QDir(".hidden/subdir");
hiddenSubDir.mkdir("happy");
hiddenSubDir.mkdir("happy2");
QList<QUrl> urls;
urls << QUrl::fromLocalFile(hiddenSubDir.absolutePath());
fd.setSidebarUrls(urls);
fd.show();
QTest::qWait(250);
QSidebar *sidebar = fd.findChild<QSidebar*>("sidebar");
sidebar->setFocus();
sidebar->selectUrl(QUrl::fromLocalFile(hiddenSubDir.absolutePath()));
QTest::mouseClick(sidebar->viewport(), Qt::LeftButton, 0, sidebar->visualRect(sidebar->model()->index(0, 0)).center());
// give the background processes more time on windows mobile
QTest::qWait(250);
QFileSystemModel *model = fd.findChild<QFileSystemModel*>("qt_filesystem_model");
QCOMPARE(model->rowCount(model->index(hiddenSubDir.absolutePath())), 2);
hiddenSubDir.rmdir("happy2");
hiddenSubDir.rmdir("happy");
hiddenDir.rmdir("subdir");
current.rmdir(".hidden");
}
#endif
#if defined QT_BUILD_INTERNAL
class MyQSideBar : public QSidebar
{
public :
MyQSideBar(QWidget *parent = 0) : QSidebar(parent)
{}
void removeSelection() {
QList<QModelIndex> idxs = selectionModel()->selectedIndexes();
QList<QPersistentModelIndex> indexes;
for (int i = 0; i < idxs.count(); i++)
indexes.append(idxs.at(i));
for (int i = 0; i < indexes.count(); ++i)
if (!indexes.at(i).data(Qt::UserRole + 1).toUrl().path().isEmpty())
model()->removeRow(indexes.at(i).row());
}
};
#endif
#ifdef QT_BUILD_INTERNAL
void tst_QFileDialog2::task251341_sideBarRemoveEntries()
{
QFileDialog fd;
QDir current = QDir::currentPath();
current.mkdir("testDir");
QDir testSubDir = QDir("testDir");
QList<QUrl> urls;
urls << QUrl::fromLocalFile(testSubDir.absolutePath());
urls << QUrl::fromLocalFile("NotFound");
fd.setSidebarUrls(urls);
fd.show();
QTest::qWait(250);
QSidebar *sidebar = fd.findChild<QSidebar*>("sidebar");
sidebar->setFocus();
//We enter in the first bookmark
sidebar->selectUrl(QUrl::fromLocalFile(testSubDir.absolutePath()));
QTest::mouseClick(sidebar->viewport(), Qt::LeftButton, 0, sidebar->visualRect(sidebar->model()->index(0, 0)).center());
QTest::qWait(250);
QFileSystemModel *model = fd.findChild<QFileSystemModel*>("qt_filesystem_model");
//There is no file
QCOMPARE(model->rowCount(model->index(testSubDir.absolutePath())), 0);
//Icon is not enabled QUrlModel::EnabledRole
QVariant value = sidebar->model()->index(0, 0).data(Qt::UserRole + 2);
QCOMPARE(qvariant_cast<bool>(value), true);
sidebar->setFocus();
//We enter in the second bookmark which is invalid
sidebar->selectUrl(QUrl::fromLocalFile("NotFound"));
QTest::mouseClick(sidebar->viewport(), Qt::LeftButton, 0, sidebar->visualRect(sidebar->model()->index(1, 0)).center());
QTest::qWait(250);
//We fallback to root because the entry in the bookmark is invalid
QCOMPARE(model->rowCount(model->index("NotFound")), model->rowCount(model->index(model->rootPath())));
//Icon is not enabled QUrlModel::EnabledRole
value = sidebar->model()->index(1, 0).data(Qt::UserRole + 2);
QCOMPARE(qvariant_cast<bool>(value), false);
MyQSideBar mySideBar;
mySideBar.setModelAndUrls(model, urls);
mySideBar.show();
mySideBar.selectUrl(QUrl::fromLocalFile(testSubDir.absolutePath()));
QTest::qWait(1000);
mySideBar.removeSelection();
//We remove the first entry
QList<QUrl> expected;
expected << QUrl::fromLocalFile("NotFound");
QCOMPARE(mySideBar.urls(), expected);
mySideBar.selectUrl(QUrl::fromLocalFile("NotFound"));
mySideBar.removeSelection();
//We remove the second entry
expected.clear();
QCOMPARE(mySideBar.urls(), expected);
current.rmdir("testDir");
}
#endif
void tst_QFileDialog2::task254490_selectFileMultipleTimes()
{
QString tempPath = tempDir.path();
QTemporaryFile *t;
t = new QTemporaryFile;
QVERIFY2(t->open(), qPrintable(t->errorString()));
t->open();
QFileDialog fd(0, "TestFileDialog");
fd.setDirectory(tempPath);
fd.setViewMode(QFileDialog::List);
fd.setAcceptMode(QFileDialog::AcceptSave);
fd.setFileMode(QFileDialog::AnyFile);
//This should select the file in the QFileDialog
fd.selectFile(t->fileName());
//This should clear the selection and write it into the filename line edit
fd.selectFile("new_file.txt");
fd.show();
QTest::qWait(250);
QLineEdit *lineEdit = fd.findChild<QLineEdit*>("fileNameEdit");
QVERIFY(lineEdit);
QCOMPARE(lineEdit->text(),QLatin1String("new_file.txt"));
QListView *list = fd.findChild<QListView*>("listView");
QVERIFY(list);
QCOMPARE(list->selectionModel()->selectedRows(0).count(), 0);
t->deleteLater();
}
#ifdef QT_BUILD_INTERNAL
void tst_QFileDialog2::task257579_sideBarWithNonCleanUrls()
{
QDir dir(tempDir.path());
QLatin1String dirname("autotest_task257579");
dir.rmdir(dirname); //makes sure it doesn't exist any more
QVERIFY(dir.mkdir(dirname));
QString url = dir.absolutePath() + QLatin1Char('/') + dirname + QLatin1String("/..");
QFileDialog fd;
fd.setSidebarUrls(QList<QUrl>() << QUrl::fromLocalFile(url));
QSidebar *sidebar = fd.findChild<QSidebar*>("sidebar");
QCOMPARE(sidebar->urls().count(), 1);
QVERIFY(sidebar->urls().first().toLocalFile() != url);
QCOMPARE(sidebar->urls().first().toLocalFile(), QDir::cleanPath(url));
#ifdef Q_OS_WIN
QCOMPARE(sidebar->model()->index(0,0).data().toString().toLower(), dir.dirName().toLower());
#else
QCOMPARE(sidebar->model()->index(0,0).data().toString(), dir.dirName());
#endif
//all tests are finished, we can remove the temporary dir
QVERIFY(dir.rmdir(dirname));
}
#endif
void tst_QFileDialog2::task259105_filtersCornerCases()
{
QFileDialog fd(0, "TestFileDialog");
fd.setNameFilter(QLatin1String("All Files! (*);;Text Files (*.txt)"));
fd.setOption(QFileDialog::HideNameFilterDetails, true);
fd.show();
QTest::qWait(250);
//Extensions are hidden
QComboBox *filters = fd.findChild<QComboBox*>("fileTypeCombo");
QVERIFY(filters);
QCOMPARE(filters->currentText(), QLatin1String("All Files!"));
filters->setCurrentIndex(1);
QCOMPARE(filters->currentText(), QLatin1String("Text Files"));
//We should have the full names
fd.setOption(QFileDialog::HideNameFilterDetails, false);
QTest::qWait(250);
filters->setCurrentIndex(0);
QCOMPARE(filters->currentText(), QLatin1String("All Files! (*)"));
filters->setCurrentIndex(1);
QCOMPARE(filters->currentText(), QLatin1String("Text Files (*.txt)"));
//Corner case undocumented of the task
fd.setNameFilter(QLatin1String("\352 (I like cheese) All Files! (*);;Text Files (*.txt)"));
QCOMPARE(filters->currentText(), QLatin1String("\352 (I like cheese) All Files! (*)"));
filters->setCurrentIndex(1);
QCOMPARE(filters->currentText(), QLatin1String("Text Files (*.txt)"));
fd.setOption(QFileDialog::HideNameFilterDetails, true);
filters->setCurrentIndex(0);
QTest::qWait(500);
QCOMPARE(filters->currentText(), QLatin1String("\352 (I like cheese) All Files!"));
filters->setCurrentIndex(1);
QCOMPARE(filters->currentText(), QLatin1String("Text Files"));
fd.setOption(QFileDialog::HideNameFilterDetails, true);
filters->setCurrentIndex(0);
QTest::qWait(500);
QCOMPARE(filters->currentText(), QLatin1String("\352 (I like cheese) All Files!"));
filters->setCurrentIndex(1);
QCOMPARE(filters->currentText(), QLatin1String("Text Files"));
}
void tst_QFileDialog2::QTBUG4419_lineEditSelectAll()
{
QString tempPath = tempDir.path();
QTemporaryFile temporaryFile(tempPath + "/tst_qfiledialog2_lineEditSelectAll.XXXXXX");
QVERIFY2(temporaryFile.open(), qPrintable(temporaryFile.errorString()));
QFileDialog fd(0, "TestFileDialog", temporaryFile.fileName());
fd.setDirectory(tempPath);
fd.setViewMode(QFileDialog::List);
fd.setAcceptMode(QFileDialog::AcceptSave);
fd.setFileMode(QFileDialog::AnyFile);
fd.show();
QApplication::setActiveWindow(&fd);
QVERIFY(QTest::qWaitForWindowActive(&fd));
QCOMPARE(fd.isVisible(), true);
QCOMPARE(QApplication::activeWindow(), static_cast<QWidget*>(&fd));
QLineEdit *lineEdit = fd.findChild<QLineEdit*>("fileNameEdit");
QVERIFY(lineEdit);
QTRY_COMPARE(tempPath + QChar('/') + lineEdit->text(), temporaryFile.fileName());
QCOMPARE(tempPath + QChar('/') + lineEdit->selectedText(), temporaryFile.fileName());
}
void tst_QFileDialog2::QTBUG6558_showDirsOnly()
{
const QString tempPath = tempDir.path();
QDir dirTemp(tempPath);
const QString tempName = QLatin1String("showDirsOnly.") + QString::number(qrand());
dirTemp.mkdir(tempName);
dirTemp.cd(tempName);
QTRY_VERIFY(dirTemp.exists());
const QString dirPath = dirTemp.absolutePath();
QDir dir(dirPath);
//We create two dirs
dir.mkdir("a");
dir.mkdir("b");
//Create a file
QFile tempFile(dirPath + "/plop.txt");
tempFile.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&tempFile);
out << "The magic number is: " << 49 << "\n";
tempFile.close();
QFileDialog fd(0, "TestFileDialog");
fd.setDirectory(dir.absolutePath());
fd.setViewMode(QFileDialog::List);
fd.setAcceptMode(QFileDialog::AcceptSave);
fd.setOption(QFileDialog::ShowDirsOnly, true);
fd.show();
QApplication::setActiveWindow(&fd);
QVERIFY(QTest::qWaitForWindowActive(&fd));
QCOMPARE(fd.isVisible(), true);
QCOMPARE(QApplication::activeWindow(), static_cast<QWidget*>(&fd));
QFileSystemModel *model = fd.findChild<QFileSystemModel*>("qt_filesystem_model");
QTRY_COMPARE(model->rowCount(model->index(dir.absolutePath())), 2);
fd.setOption(QFileDialog::ShowDirsOnly, false);
QTRY_COMPARE(model->rowCount(model->index(dir.absolutePath())), 3);
fd.setOption(QFileDialog::ShowDirsOnly, true);
QTRY_COMPARE(model->rowCount(model->index(dir.absolutePath())), 2);
fd.setFileMode(QFileDialog::DirectoryOnly);
QTRY_COMPARE(model->rowCount(model->index(dir.absolutePath())), 2);
QTRY_COMPARE(bool(fd.options() & QFileDialog::ShowDirsOnly), true);
fd.setFileMode(QFileDialog::AnyFile);
QTRY_COMPARE(model->rowCount(model->index(dir.absolutePath())), 3);
QTRY_COMPARE(bool(fd.options() & QFileDialog::ShowDirsOnly), false);
fd.setDirectory(QDir::homePath());
//We remove the dirs
dir.rmdir("a");
dir.rmdir("b");
//we delete the file
tempFile.remove();
dirTemp.cdUp();
dirTemp.rmdir(tempName);
}
void tst_QFileDialog2::QTBUG4842_selectFilterWithHideNameFilterDetails()
{
QStringList filtersStr;
filtersStr << "Images (*.png *.xpm *.jpg)" << "Text files (*.txt)" << "XML files (*.xml)";
QString chosenFilterString("Text files (*.txt)");
QFileDialog fd(0, "TestFileDialog");
fd.setAcceptMode(QFileDialog::AcceptSave);
fd.setOption(QFileDialog::HideNameFilterDetails, true);
fd.setNameFilters(filtersStr);
fd.selectNameFilter(chosenFilterString);
fd.show();
QApplication::setActiveWindow(&fd);
QVERIFY(QTest::qWaitForWindowActive(&fd));
QCOMPARE(fd.isVisible(), true);
QCOMPARE(QApplication::activeWindow(), static_cast<QWidget*>(&fd));
QComboBox *filters = fd.findChild<QComboBox*>("fileTypeCombo");
//We compare the current combobox text with the stripped version
QCOMPARE(filters->currentText(), QString("Text files"));
QFileDialog fd2(0, "TestFileDialog");
fd2.setAcceptMode(QFileDialog::AcceptSave);
fd2.setOption(QFileDialog::HideNameFilterDetails, false);
fd2.setNameFilters(filtersStr);
fd2.selectNameFilter(chosenFilterString);
fd2.show();
QApplication::setActiveWindow(&fd2);
QVERIFY(QTest::qWaitForWindowActive(&fd2));
QCOMPARE(fd2.isVisible(), true);
QCOMPARE(QApplication::activeWindow(), static_cast<QWidget*>(&fd2));
QComboBox *filters2 = fd2.findChild<QComboBox*>("fileTypeCombo");
//We compare the current combobox text with the non stripped version
QCOMPARE(filters2->currentText(), chosenFilterString);
}
void tst_QFileDialog2::dontShowCompleterOnRoot()
{
QFileDialog fd(0, "TestFileDialog");
fd.setAcceptMode(QFileDialog::AcceptSave);
fd.show();
QApplication::setActiveWindow(&fd);
QVERIFY(QTest::qWaitForWindowActive(&fd));
QCOMPARE(fd.isVisible(), true);
QCOMPARE(QApplication::activeWindow(), static_cast<QWidget*>(&fd));
fd.setDirectory("");
QLineEdit *lineEdit = fd.findChild<QLineEdit*>("fileNameEdit");
QTRY_VERIFY(lineEdit->text().isEmpty());
//The gatherer thread will then return the result
QApplication::processEvents();
QTRY_VERIFY(lineEdit->completer()->popup()->isHidden());
}
void tst_QFileDialog2::nameFilterParsing_data()
{
QTest::addColumn<QString>("filterString");
QTest::addColumn<QStringList>("filters");
// QTBUG-47923: Do not trip over "*,v".
QTest::newRow("text") << "plain text document (*.txt *.asc *,v *.doc)"
<< (QStringList() << "*.txt" << "*.asc" << "*,v" << "*.doc");
QTest::newRow("html") << "HTML document (*.html *.htm)"
<< (QStringList() << "*.html" << "*.htm");
}
void tst_QFileDialog2::nameFilterParsing()
{
QFETCH(QString, filterString);
QFETCH(QStringList, filters);
QCOMPARE(QPlatformFileDialogHelper::cleanFilterList(filterString), filters);
}
QTEST_MAIN(tst_QFileDialog2)
#include "tst_qfiledialog2.moc"
| geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtbase/tests/auto/widgets/dialogs/qfiledialog2/tst_qfiledialog2.cpp | C++ | gpl-3.0 | 44,399 |
<?php
declare(strict_types = 1);
namespace AppBundle\Repository;
use AppBundle\Model\Edit;
use AppBundle\Model\Page;
use AppBundle\Model\Project;
/**
* An EditRepository fetches data about a single revision.
* @codeCoverageIgnore
*/
class EditRepository extends Repository
{
/**
* Get an Edit instance given the revision ID. This does NOT set the associated User or Page.
* @param Project $project
* @param int $revId
* @param Page|null $page Provide if you already know the Page, so as to point to the same instance.
* @return Edit|null Null if not found.
*/
public function getEditFromRevIdForPage(Project $project, int $revId, ?Page $page = null): ?Edit
{
$revisionTable = $project->getTableName('revision', '');
$commentTable = $project->getTableName('comment', 'revision');
$actorTable = $project->getTableName('actor', 'revision');
$pageSelect = '';
$pageJoin = '';
if (null === $page) {
$pageTable = $project->getTableName('page');
$pageSelect = "page_title,";
$pageJoin = "JOIN $pageTable ON revs.rev_page = page_id";
}
$sql = "SELECT $pageSelect
revs.rev_id AS id,
actor_name AS username,
revs.rev_timestamp AS timestamp,
revs.rev_minor_edit AS minor,
revs.rev_len AS length,
(CAST(revs.rev_len AS SIGNED) - IFNULL(parentrevs.rev_len, 0)) AS length_change,
comment_text AS comment
FROM $revisionTable AS revs
$pageJoin
JOIN $actorTable ON actor_id = rev_actor
LEFT JOIN $revisionTable AS parentrevs ON (revs.rev_parent_id = parentrevs.rev_id)
LEFT OUTER JOIN $commentTable ON (revs.rev_comment_id = comment_id)
WHERE revs.rev_id = :revId";
$result = $this->executeProjectsQuery($sql, ['revId' => $revId])->fetch();
// Create the Page instance.
if (null === $page) {
$page = new Page($project, $result['page_title']);
}
$edit = new Edit($page, $result);
$edit->setRepository($this);
return $edit;
}
/**
* Use the Compare API to get HTML for the diff.
* @param Edit $edit
* @return string|null Raw HTML, must be wrapped in a <table> tag. Null if no comparison found.
*/
public function getDiffHtml(Edit $edit): ?string
{
$params = [
'action' => 'compare',
'fromrev' => $edit->getId(),
'torelative' => 'prev',
];
$res = $this->executeApiRequest($edit->getProject(), $params);
return $res['compare']['*'] ?? null;
}
}
| x-Tools/xtools | src/AppBundle/Repository/EditRepository.php | PHP | gpl-3.0 | 2,791 |
<?php
namespace app\modules\systemJournal\models;
use app\components\custom\TSearchModelTools;
use app\components\helpers\TimeHelper;
use Yii;
use yii\data\ActiveDataProvider;
class SystemJournalSearch extends SystemJournal
{
const VIEW_MODE_ALL = 'All';
const VIEW_MODE_DELETED = 'Deleted';
use TSearchModelTools;
public $hasContent;
public function rules()
{
return array_merge(parent::rules(), [
[['viewMode', 'hasContent'], 'safe'],
]);
}
public function view($params)
{
$this->setAttributes($params);
$query = self::find()
->filterWhere(['system_journal.id' => $this->id])
->andFilterWhere(['system_journal.severity_name' => $this->severity_name])
->andFilterWhere(['like', 'system_journal.subject', $this->subject])
->andFilterWhere(['like', 'system_journal.reporter_user_name', $this->reporter_user_name])
->select([
'system_journal.id',
'system_journal.severity_name',
'system_journal.reporter_user_name',
'system_journal.subject',
'LENGTH(system_journal.content) AS hasContent',
'system_journal.is_readed',
'system_journal.created_at',
'system_journal.deleted_at',
]);
$date = explode(' - ', $this->created_at);
if (count($date) == 2) {
$query->andFilterWhere(['between', 'system_journal.created_at', TimeHelper::format($date[0], TimeHelper::FORMAT_TIMESTAMP), TimeHelper::format($date[1], TimeHelper::FORMAT_TIMESTAMP)]);
$this->created_at = $date[0];
} else {
$this->created_at = null;
}
switch ($this->viewMode) {
case self::VIEW_MODE_DELETED:
$query->andWhere(['IS NOT', 'deleted_at', null]);
break;
default:
$query->andWhere(['system_journal.deleted_at' => null]);
break;
}
return new ActiveDataProvider([
'query' => $query,
'sort' => [
'attributes' => [
'id' => [
'asc' => ['system_journal.id' => SORT_ASC],
'desc' => ['system_journal.id' => SORT_DESC],
],
'reporter_user_name' => [
'asc' => ['system_journal.reporter_user_name' => SORT_ASC],
'desc' => ['system_journal.reporter_user_name' => SORT_DESC],
],
'severity_name' => [
'asc' => ['system_journal.severity_name' => SORT_ASC],
'desc' => ['system_journal.severity_name' => SORT_DESC],
],
'subject' => [
'asc' => ['system_journal.subject' => SORT_ASC],
'desc' => ['system_journal.subject' => SORT_DESC],
],
'is_readed' => [
'asc' => ['system_journal.is_readed' => SORT_ASC],
'desc' => ['system_journal.is_readed' => SORT_DESC],
],
'created_at' => [
'asc' => ['system_journal.created_at' => SORT_ASC],
'desc' => ['system_journal.created_at' => SORT_DESC],
],
],
'defaultOrder' => ['is_readed' => SORT_ASC, 'id' => SORT_DESC],
],
]);
}
public static function listViewModes()
{
return [self::VIEW_MODE_ALL, self::VIEW_MODE_DELETED];
}
}
| eugene-siderka/randevu | modules/systemJournal/models/SystemJournalSearch.php | PHP | gpl-3.0 | 3,828 |
/***********************************************************************************
Copyright (C) 2014-2015 Ahmet Öztürk (aoz_2@yahoo.com)
This file is part of Lifeograph.
Lifeograph is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Lifeograph is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Lifeograph. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************************/
#include <winsock2.h> // just to silence the compiler
#include <windows.h>
#include <commctrl.h>
#include "win_wao.hpp"
LRESULT CALLBACK
waoWC_button0Proc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
static TRACKMOUSEEVENT tME;
switch( msg )
{
case WM_CREATE:
{
tME.cbSize = sizeof( TRACKMOUSEEVENT );
//tME.dwFlags = TME_HOVER;
tME.dwHoverTime = 0;
SendMessage( GetParent (hwnd), WAOM_TBBTNCREATED,
MAKEWPARAM( WAOM_TBBTNCREATED_LW,
GetWindowLong( hwnd, GWL_ID ) ), ( LPARAM ) hwnd );
return FALSE;
}
case WM_ENABLE:
if( GetWindowLong( hwnd, GWL_USERDATA ) & WAO_TBBS_CHECKED )
SetWindowLong( hwnd, GWL_USERDATA,
wParam ? ( WAO_TBBS_NORMAL | WAO_TBBS_CHECKED ) :
( WAO_TBBS_DISABLED | WAO_TBBS_CHECKED ) );
else
SetWindowLong( hwnd, GWL_USERDATA, wParam ? WAO_TBBS_NORMAL : WAO_TBBS_DISABLED );
RedrawWindow( hwnd, NULL, NULL, RDW_ERASE | RDW_INVALIDATE );
return FALSE;
case WM_MOUSEMOVE:
if( GetWindowLong( hwnd, GWL_USERDATA ) != WAO_TBBS_NORMAL )
return FALSE;
SetWindowLong( hwnd, GWL_USERDATA, WAO_TBBS_HOVERED );
RedrawWindow( hwnd, NULL, NULL, RDW_ERASE | RDW_INVALIDATE );
tME.dwFlags = TME_LEAVE;
tME.hwndTrack = hwnd;
TrackMouseEvent( &tME );
return FALSE;
case WM_MOUSELEAVE:
SetWindowLong( hwnd, GWL_USERDATA, WAO_TBBS_NORMAL );
RedrawWindow( hwnd, NULL, NULL, RDW_ERASE | RDW_INVALIDATE );
return FALSE;
case WM_RBUTTONDOWN:
if( GetWindowLong( hwnd, GWL_STYLE ) & BS_RIGHTBUTTON )
{
long btnStt = GetWindowLong( hwnd, GWL_USERDATA );
SetWindowLong( hwnd, GWL_USERDATA,
WAO_TBBS_CLICKED | ( btnStt & WAO_TBBS_CHECKED ) );
}
return FALSE;
case WM_LBUTTONDOWN:
{
long btnStt = GetWindowLong( hwnd, GWL_USERDATA );
SetWindowLong( hwnd, GWL_USERDATA, WAO_TBBS_CLICKED | ( btnStt & WAO_TBBS_CHECKED ) );
RedrawWindow( hwnd, NULL, NULL, RDW_ERASE | RDW_INVALIDATE );
if( GetWindowLong( hwnd, GWL_STYLE ) & BS_NOTIFY )
SetTimer( hwnd, WAO_TMR_TBRPW, WAO_TBBN_RPWTIME, NULL );
return FALSE;
}
case WM_LBUTTONUP:
// should be clicked first:
if( !( GetWindowLong( hwnd, GWL_USERDATA ) & WAO_TBBS_CLICKED ) )
return FALSE;
case WM_CLEAR: // tweak to check with one internal message
{
SetWindowLong( hwnd, GWL_USERDATA, WAO_TBBS_NORMAL );
RedrawWindow( hwnd, NULL, NULL, RDW_ERASE | RDW_INVALIDATE );
DLGPROC parProc = ( DLGPROC ) GetWindowLong ( GetParent( hwnd ), DWL_DLGPROC );
if( msg != WM_CLEAR ) // what about making this a seperate thread?
parProc( GetParent ( hwnd ), WM_COMMAND,
MAKEWPARAM( GetWindowLong( hwnd, GWL_ID ),
WAO_TBBN_LCLCKED ),
( LPARAM ) hwnd );
if( GetWindowLong( hwnd, GWL_STYLE ) & BS_NOTIFY )
{
KillTimer( hwnd, WAO_TMR_TBRPW );
KillTimer( hwnd, WAO_TMR_TBRPT );
}
return FALSE;
}
case WM_RBUTTONUP:
// should be clicked first:
if( !( GetWindowLong( hwnd, GWL_USERDATA ) & WAO_TBBS_CLICKED ) )
return FALSE;
if( GetWindowLong( hwnd, GWL_STYLE ) & BS_RIGHTBUTTON )
{
DLGPROC parProc = ( DLGPROC ) GetWindowLong( GetParent( hwnd ), DWL_DLGPROC );
parProc( GetParent( hwnd ),
WM_COMMAND,
MAKEWPARAM( GetWindowLong ( hwnd, GWL_ID ), WAO_TBBN_RCLCKED ),
( LPARAM ) hwnd );
}
return FALSE;
case WM_TIMER:
{
if( wParam == WAO_TMR_TBRPW ) // repeat wait
{
KillTimer( hwnd, WAO_TMR_TBRPW );
SetTimer( hwnd, WAO_TMR_TBRPT, WAO_TBBN_RPTTIME, NULL );
}
DLGPROC parProc = ( DLGPROC ) GetWindowLong( GetParent( hwnd ), DWL_DLGPROC );
parProc( GetParent( hwnd ),
WM_COMMAND,
MAKEWPARAM( GetWindowLong( hwnd, GWL_ID ), WAO_TBBN_LCLCKED ),
( LPARAM ) hwnd );
return FALSE;
}
case WM_PAINT:
{
PAINTSTRUCT paintStruct;
BeginPaint( hwnd, &paintStruct );
RECT rcWnd;
GetClientRect( hwnd, &rcWnd ); // should this be calculated every time?
int btnStt = GetWindowLong( hwnd, GWL_USERDATA );
if( btnStt & WAO_TBBS_CHECKED )
{
FillRect( paintStruct.hdc, &rcWnd, CreateSolidBrush( 0x99ffff ) );
DrawEdge( paintStruct.hdc, &rcWnd, BDR_SUNKENOUTER, BF_RECT );
}
else if( btnStt == WAO_TBBS_CLICKED )
{
DrawEdge( paintStruct.hdc, &rcWnd, BDR_SUNKENOUTER, BF_RECT );
}
else if( btnStt == WAO_TBBS_HOVERED )
{
DrawEdge( paintStruct.hdc, &rcWnd, BDR_RAISEDINNER, BF_RECT );
}
// drawing icon
if( GetWindowLong( hwnd, GWL_STYLE ) & BS_ICON ) // maybe later bitmap too
{
HICON hIco = ( HICON ) GetPropA( hwnd, WAO_PROP_ICON );
DrawIconEx( paintStruct.hdc,
( rcWnd.right - rcWnd.left - 16 ) / 2,
( rcWnd.bottom - rcWnd.top - 16 ) / 2,
hIco, 16, 16, 0, NULL, DI_NORMAL );
}
// drawing text
else
{
int tmpLen = GetWindowTextLength( hwnd );
wchar_t buffer[ tmpLen + 1 ];
SIZE tmpSze;
GetWindowText( hwnd, buffer, tmpLen + 1 );
SetBkMode( paintStruct.hdc, TRANSPARENT );
SelectObject( paintStruct.hdc, GetStockObject( DEFAULT_GUI_FONT ) );
GetTextExtentPoint32( paintStruct.hdc, buffer, tmpLen, &tmpSze );
DrawState( paintStruct.hdc, NULL, NULL,
( LPARAM ) buffer, tmpLen,
( rcWnd.right-rcWnd.left-tmpSze.cx ) / 2,
( rcWnd.bottom-rcWnd.top-tmpSze.cy ) / 2,
tmpSze.cx, tmpSze.cy, DST_TEXT|(
( btnStt & WAO_TBBS_DISABLED ) ? DSS_DISABLED : 0 ) );
}
EndPaint( hwnd, &paintStruct );
return FALSE;
}
default:
return DefWindowProc( hwnd, msg, wParam, lParam );
}
}
LRESULT CALLBACK
waoWC_buttonChkProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{ static TRACKMOUSEEVENT tME;
switch( msg )
{
case WM_CREATE:
{
tME.cbSize = sizeof( TRACKMOUSEEVENT );
tME.dwHoverTime = 0;
SendMessage( GetParent( hwnd ),
WAOM_TBBTNCREATED,
MAKEWPARAM( WAOM_TBBTNCREATED_LW, GetWindowLong( hwnd, GWL_ID ) ),
( LPARAM ) hwnd );
}
case WM_MOUSELEAVE:
if( !( GetWindowLong( hwnd, GWL_USERDATA ) & WAO_TBBS_CHECKED ) )
{
SetWindowLong( hwnd, GWL_USERDATA, WAO_TBBS_NORMAL );
RedrawWindow( hwnd, NULL, NULL, RDW_ERASE | RDW_INVALIDATE );
}
else
SetWindowLong( hwnd, GWL_USERDATA, WAO_TBBS_CHECKED | WAO_TBBS_NORMAL );
break;
case WM_LBUTTONUP:
{
// should be clicked first:
if( !( GetWindowLong( hwnd, GWL_USERDATA ) & WAO_TBBS_CLICKED ) )
return FALSE;
if( GetWindowLong( hwnd, GWL_USERDATA ) & WAO_TBBS_CHECKED )
{
if( !( GetWindowLong( hwnd, GWL_STYLE ) & BS_AUTORADIOBUTTON ) )
{
SetWindowLong( hwnd, GWL_USERDATA, WAO_TBBS_HOVERED );
tME.dwFlags = TME_LEAVE;
tME.hwndTrack = hwnd;
TrackMouseEvent( &tME );
}
}
else
{
SetWindowLong( hwnd, GWL_USERDATA, WAO_TBBS_CHECKED );
if( GetWindowLong( hwnd, GWL_STYLE ) & BS_RADIOBUTTON )
{
long wStyle;
HWND t_hndWnd = hwnd;
while( ( t_hndWnd = GetWindow( t_hndWnd, GW_HWNDPREV ) ) )
{
wchar_t buffer[ 16 ];
GetClassName( t_hndWnd, buffer, 15 );
if( lstrcmp( buffer, L"wao_BUTTON_Chk" ) )
break;
wStyle = GetWindowLong( t_hndWnd, GWL_STYLE );
if( !( wStyle & BS_RADIOBUTTON ) )
break;
SetWindowLong( t_hndWnd, GWL_USERDATA, WAO_TBBS_NORMAL );
RedrawWindow( t_hndWnd, NULL, NULL, RDW_ERASE | RDW_INVALIDATE );
if( wStyle & WS_GROUP )
break;
}
t_hndWnd = hwnd;
while( ( t_hndWnd = GetWindow( t_hndWnd, GW_HWNDNEXT ) ) )
{
wchar_t buffer[ 16 ];
GetClassName( t_hndWnd, buffer, 15 );
if( lstrcmp( buffer, L"wao_BUTTON_Chk" ) )
break;
wStyle = GetWindowLong( t_hndWnd, GWL_STYLE );
if( !( wStyle & BS_RADIOBUTTON ) )
break;
SetWindowLong( t_hndWnd, GWL_USERDATA, WAO_TBBS_NORMAL );
RedrawWindow( t_hndWnd, NULL, NULL, RDW_ERASE | RDW_INVALIDATE );
if( wStyle & WS_GROUP )
break;
}
}
}
RedrawWindow( hwnd, NULL, NULL, RDW_ERASE | RDW_INVALIDATE );
// RADIO BUTTON
DLGPROC parProc = ( DLGPROC ) GetWindowLong( GetParent( hwnd ), DWL_DLGPROC );
parProc( GetParent( hwnd ),
WM_COMMAND,
MAKEWPARAM( GetWindowLong( hwnd, GWL_ID ), WAO_TBBN_LCLCKED ),
( LPARAM ) hwnd );
}
break;
default:
return( waoWC_button0Proc( hwnd, msg, wParam, lParam ) );
}
return 0; // just to silence the compiler
}
LRESULT CALLBACK
WAO_advanced_edit_proc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam,
UINT_PTR uIdSubclass, DWORD_PTR dwRefData )
{
switch( msg )
{
case WM_KEYDOWN:
if( wparam == VK_RETURN )
SendMessage( GetParent( hwnd ),
WAOM_EDITACTIVATED,
MAKEWPARAM( GetWindowLong( hwnd, GWL_ID ), WAOM_EDITACTIVATED_HW ),
( LPARAM ) hwnd );
else if( wparam == VK_ESCAPE )
SendMessage( GetParent( hwnd ),
WAOM_EDITABORTED,
MAKEWPARAM( GetWindowLong( hwnd, GWL_ID ), WAOM_EDITACTIVATED_HW ),
( LPARAM ) hwnd );
break;
default:
return DefSubclassProc( hwnd, msg, wparam, lparam );
}
return 0;
}
#include <ctime>
bool
WAO_init()
{
WNDCLASS waoWC_button0, waoWC_buttonChk;
waoWC_button0.style = CS_OWNDC | CS_BYTEALIGNWINDOW | CS_PARENTDC;
waoWC_button0.lpfnWndProc = waoWC_button0Proc;
waoWC_button0.cbClsExtra = 0;
waoWC_button0.cbWndExtra = 0; // state bits?
waoWC_button0.hInstance = GetModuleHandle( NULL );
waoWC_button0.hIcon = NULL;
waoWC_button0.hCursor = LoadCursor( NULL, IDC_HAND );
waoWC_button0.hbrBackground = CreateSolidBrush( GetSysColor( COLOR_BTNFACE ) );
waoWC_button0.lpszMenuName = NULL;
waoWC_button0.lpszClassName = L"wao_BUTTON_0";
waoWC_buttonChk = waoWC_button0;
waoWC_buttonChk.lpfnWndProc = waoWC_buttonChkProc;
waoWC_buttonChk.lpszClassName = L"wao_BUTTON_Chk";
if( !RegisterClass( &waoWC_button0 ) )
{
MessageBoxA( NULL, "waoWC_button0 Registration Failed!", "WAO", MB_OK );
return false;
}
if( !RegisterClass( &waoWC_buttonChk ) )
{
MessageBoxA( NULL, "waoWC_buttonChk Registration Failed!", "WAO", MB_OK );
return false;
}
return true;
}
BOOL CALLBACK
WAO_toolbar_proc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
return FALSE;
}
BOOL
WAO_set_icon( HWND hwnd, HICON hIcon )
{
BOOL retv = SetPropA( hwnd, WAO_PROP_ICON, hIcon );
InvalidateRect( hwnd, NULL, TRUE );
return retv;
}
// INPUT DIALOG ====================================================================================
WAO_InputDlg::WAO_InputDlg( const Wstring& title, const Wstring& text )
: m_text( text ), m_title( title )
{
}
bool
WAO_InputDlg::launch( HWND hWPar, DLGPROC redirProc )
{
DialogBox( GetModuleHandle( NULL ), MAKEINTRESOURCE( WAO_IDD_INPUT ), hWPar, redirProc );
return m_result;
}
bool
WAO_InputDlg::proc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{
case WM_INITDIALOG:
m_hwnd = hwnd;
SetWindowText( m_hwnd, m_title.c_str() );
SetDlgItemText( m_hwnd, WAO_IDE_INPUT, m_text.c_str() );
m_result = false;
return TRUE;
case WM_COMMAND:
switch( LOWORD( wParam ) )
{
case IDOK:
{
m_result = true;
wchar_t buffer[ 1024 ];
GetDlgItemText( m_hwnd, WAO_IDE_INPUT, buffer, 1023 );
m_text = buffer;
EndDialog( m_hwnd, 0 );
}
return FALSE;
}
return FALSE;
case WM_DESTROY:
m_hwnd = NULL; // whenever window is destroyed hW is nullified
return FALSE;
default:
return FALSE;
}
}
// MENU ============================================================================================
WAO_Menu::WAO_Menu()
{
m_hmenu = NULL;
}
HMENU
WAO_Menu::init()
{
return( m_hmenu = CreatePopupMenu() );
}
// APPEND
bool
WAO_Menu::append( UINT flags, UINT newItm, LPCTSTR content )
{
return AppendMenu( m_hmenu, flags, newItm, content );
}
// TRACK MENU
int
WAO_Menu::track( UINT flags, HWND hWOwn, int posX, int posY )
{
//hMenuAct = hMenu;
//hMenu = NULL; // to avoid recreation during append()
if( posX < 0 )
{
POINT pnt;
GetCursorPos (&pnt);
posX = pnt.x;
posY = pnt.y;
}
return TrackPopupMenu( m_hmenu, flags, posX, posY, 0, hWOwn, NULL );
}
// SET DEFAULT ITEM
bool
WAO_Menu::set_default_item( UINT itm, UINT byPos )
{
return SetMenuDefaultItem( m_hmenu, itm, byPos );
}
// WHETHER THE MENU IS ACTIVE
bool
WAO_Menu::is_active()
{
return( ( bool ) m_hmenu );
}
// DESTROY MENU IF IT IS ACTIVE
bool
WAO_Menu::destroy()
{
if( m_hmenu )
{
DestroyMenu( m_hmenu );
m_hmenu = 0;
return true; // it was active
}
else
return false; // it was already inactive
}
| blhps/lifeograph-windows | src/win_wao.cpp | C++ | gpl-3.0 | 17,191 |
<?php
/**
* @link https://github.com/old-town/workflow-zf2-toolkit
* @author Malofeykin Andrey <and-rey2@yandex.ru>
*/
namespace OldTown\Workflow\ZF2\Toolkit\DoctrineWorkflowStory\Exception;
use OldTown\Workflow\ZF2\Toolkit\Exception\InvalidArgumentException as Exception;
/**
* Class InvalidArgumentException
*
* @package OldTown\Workflow\ZF2\Toolkit\DoctrineWorkflowStory\Exception
*/
class InvalidArgumentException extends Exception implements
ExceptionInterface
{
}
| old-town/workflow-zf2-toolkit | src/DoctrineWorkflowStory/Exception/InvalidArgumentException.php | PHP | gpl-3.0 | 488 |
// --------------------------------------------------------------------------------------------------
// Copyright (c) 2016 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// --------------------------------------------------------------------------------------------------
package com.microsoft.Malmo.Utils;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.stats.StatBase;
import net.minecraft.stats.StatFileWriter;
import net.minecraft.stats.StatList;
import net.minecraft.util.BlockPos;
import net.minecraft.util.ResourceLocation;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
/**
* Helper class for building the "World data" to be passed from Minecraft back to the agent.<br>
* This class contains helper methods to build up a JSON tree of useful information, such as health, XP, food levels, distance travelled, etc.etc.<br>
* It can also build up a grid of the block types around the player.
* Call this on the Server side only.
*/
public class JSONWorldDataHelper
{
/**
* Simple class to hold the dimensions of the environment around the player
* that we want to return in the World Data.<br>
* Min and max define an inclusive range, where the player's feet are situated at (0,0,0)
*/
static public class ImmediateEnvironmentDimensions {
public int xMin;
public int xMax;
public int yMin;
public int yMax;
public int zMin;
public int zMax;
/**
* Default constructor asks for an environment just big enough to contain
* the player and one block all around him.
*/
public ImmediateEnvironmentDimensions() {
this.xMin = -1; this.xMax = 1;
this.zMin = -1; this.zMax = 1;
this.yMin = -1; this.yMax = 2;
}
/**
* Convenient constructor - effectively specifies the margin around the player<br>
* Passing (1,1,1) will have the same effect as the default constructor.
* @param xMargin number of blocks to the left and right of the player
* @param yMargin number of blocks above and below player
* @param zMargin number of blocks in front of and behind player
*/
public ImmediateEnvironmentDimensions(int xMargin, int yMargin, int zMargin) {
this.xMin = -xMargin; this.xMax = xMargin;
this.yMin = -yMargin; this.yMax = yMargin + 1; // +1 because the player is two blocks tall.
this.zMin = -zMargin; this.zMax = zMargin;
}
/**
* Convenient constructor for the case where all that is required is the flat patch of ground<br>
* around the player's feet.
* @param xMargin number of blocks around the player in the x-axis
* @param zMargin number of blocks around the player in the z-axis
*/
public ImmediateEnvironmentDimensions(int xMargin, int zMargin) {
this.xMin = -xMargin; this.xMax = xMargin;
this.yMin = -1; this.yMax = -1; // Flat patch of ground at the player's feet.
this.zMin = -zMargin; this.zMax = zMargin;
}
};
/** Builds the basic achievement world data to be used as observation signals by the listener.
* @param json a JSON object into which the achievement stats will be added.
*/
public static void buildAchievementStats(JsonObject json, EntityPlayerMP player)
{
StatFileWriter sfw = player.getStatFile();
json.addProperty("DistanceTravelled",
sfw.readStat((StatBase)StatList.distanceWalkedStat)
+ sfw.readStat((StatBase)StatList.distanceSwumStat)
+ sfw.readStat((StatBase)StatList.distanceDoveStat)
+ sfw.readStat((StatBase)StatList.distanceFallenStat)
); // TODO: there are many other ways of moving!
json.addProperty("TimeAlive", sfw.readStat((StatBase)StatList.timeSinceDeathStat));
json.addProperty("MobsKilled", sfw.readStat((StatBase)StatList.mobKillsStat));
json.addProperty("DamageTaken", sfw.readStat((StatBase)StatList.damageTakenStat));
/* Other potential reinforcement signals that may be worth researching:
json.addProperty("BlocksDestroyed", sfw.readStat((StatBase)StatList.objectBreakStats) - but objectBreakStats is an array of 32000 StatBase objects - indexed by block type.);
json.addProperty("Blocked", ev.player.isMovementBlocked()) - but isMovementBlocker() is a protected method (can get round this with reflection)
*/
}
/** Builds the basic life world data to be used as observation signals by the listener.
* @param json a JSON object into which the life stats will be added.
*/
public static void buildLifeStats(JsonObject json, EntityPlayerMP player)
{
json.addProperty("Life", player.getHealth());
json.addProperty("Score", player.getScore()); // Might always be the same as XP?
json.addProperty("Food", player.getFoodStats().getFoodLevel());
json.addProperty("XP", player.experienceTotal);
json.addProperty("IsAlive", !player.isDead);
json.addProperty("Air", player.getAir());
}
/** Builds the player position data to be used as observation signals by the listener.
* @param json a JSON object into which the positional information will be added.
*/
public static void buildPositionStats(JsonObject json, EntityPlayerMP player)
{
json.addProperty("XPos", player.posX);
json.addProperty("YPos", player.posY);
json.addProperty("ZPos", player.posZ);
json.addProperty("Pitch", player.rotationPitch);
json.addProperty("Yaw", player.rotationYaw);
}
/**
* Build a signal for the cubic block grid centred on the player.<br>
* Default is 3x3x4. (One cube all around the player.)<br>
* Blocks are returned as a 1D array, in order
* along the x, then z, then y axes.<br>
* Data will be returned in an array called "Cells"
* @param json a JSON object into which the info for the object under the mouse will be added.
* @param environmentDimensions object which specifies the required dimensions of the grid to be returned.
* @param jsonName name to use for identifying the returned JSON array.
*/
public static void buildGridData(JsonObject json, ImmediateEnvironmentDimensions environmentDimensions, EntityPlayerMP player, String jsonName)
{
if (player == null || json == null)
return;
JsonArray arr = new JsonArray();
BlockPos pos = player.getPosition();
for (int y = environmentDimensions.yMin; y <= environmentDimensions.yMax; y++)
{
for (int z = environmentDimensions.zMin; z <= environmentDimensions.zMax; z++)
{
for (int x = environmentDimensions.xMin; x <= environmentDimensions.xMax; x++)
{
BlockPos p = pos.add(x, y, z);
String name = "";
IBlockState state = player.worldObj.getBlockState(p);
Object blockName = Block.blockRegistry.getNameForObject(state.getBlock());
if (blockName instanceof ResourceLocation)
{
name = ((ResourceLocation)blockName).getResourcePath();
}
JsonElement element = new JsonPrimitive(name);
arr.add(element);
}
}
}
json.add(jsonName, arr);
}
}
| maxfoow/MalmoExperience | Malmo-0.16.0-Windows-64bit/Minecraft/src/main/java/com/microsoft/Malmo/Utils/JSONWorldDataHelper.java | Java | gpl-3.0 | 8,861 |
/*
* This file is part of EchoPet.
*
* EchoPet is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EchoPet is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EchoPet. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.echopet.compat.nms.v1_14_R1.entity.type;
import com.dsh105.echopet.compat.api.entity.EntityPetType;
import com.dsh105.echopet.compat.api.entity.EntitySize;
import com.dsh105.echopet.compat.api.entity.IPet;
import com.dsh105.echopet.compat.api.entity.PetType;
import com.dsh105.echopet.compat.api.entity.SizeCategory;
import com.dsh105.echopet.compat.api.entity.type.nms.IEntityEvokerPet;
import net.minecraft.server.v1_14_R1.DataWatcher;
import net.minecraft.server.v1_14_R1.DataWatcherObject;
import net.minecraft.server.v1_14_R1.DataWatcherRegistry;
import net.minecraft.server.v1_14_R1.EntityInsentient;
import net.minecraft.server.v1_14_R1.EntityTypes;
import net.minecraft.server.v1_14_R1.World;
/**
* @since Nov 19, 2016
*/
@EntitySize(width = 0.6F, height = 1.95F)
@EntityPetType(petType = PetType.EVOKER)
public class EntityEvokerPet extends EntityIllagerAbstractPet implements IEntityEvokerPet{
// EntityIllagerWizard
private static final DataWatcherObject<Byte> c = DataWatcher.a(EntityEvokerPet.class, DataWatcherRegistry.a);// some sorta spell shit
public EntityEvokerPet(EntityTypes<? extends EntityInsentient> type, World world){
super(type, world);
}
public EntityEvokerPet(EntityTypes<? extends EntityInsentient> type, World world, IPet pet){
super(type, world, pet);
}
public EntityEvokerPet(World world){
this(EntityTypes.EVOKER, world);
}
public EntityEvokerPet(World world, IPet pet){
this(EntityTypes.EVOKER, world, pet);
}
@Override
protected void initDatawatcher(){
super.initDatawatcher();
this.datawatcher.register(c, (byte) 0);
}
@Override
public SizeCategory getSizeCategory(){
return SizeCategory.REGULAR;
}
}
| Borlea/EchoPet | modules/v1_14_R1/src/com/dsh105/echopet/compat/nms/v1_14_R1/entity/type/EntityEvokerPet.java | Java | gpl-3.0 | 2,379 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
namespace SharpFtpServer
{
// TODO: Implement a real user store.
[Obsolete]
public static class UserStore
{
private static List<User> _users;
static UserStore()
{
_users = new List<User>();
XmlSerializer serializer = new XmlSerializer(_users.GetType(), new XmlRootAttribute("Users"));
if (File.Exists("users.xml"))
{
_users = serializer.Deserialize(new StreamReader("users.xml")) as List<User>;
}
else
{
_users.Add(new User {
Username = "rick",
Password = "test",
HomeDir = "C:\\Utils"
});
using (StreamWriter w = new StreamWriter("users.xml"))
{
serializer.Serialize(w, _users);
}
}
}
public static User Validate(string username, string password)
{
User user = (from u in _users where u.Username == username && u.Password == password select u).SingleOrDefault();
return user;
}
}
}
| staywarde/windows-iot-miniFTPServer | windows-iot-miniFTPServer/windows-iot-miniFTPServer/FTPServer/UserStore.cs | C# | gpl-3.0 | 1,300 |
/*
* R Cloud - R-based Cloud Platform for Computational Research
* at EMBL-EBI (European Bioinformatics Institute)
*
* Copyright (C) 2007-2015 European Bioinformatics Institute
* Copyright (C) 2009-2015 Andrew Tikhonov - andrew.tikhonov@gmail.com
* Copyright (C) 2007-2009 Karim Chine - karim.chine@m4x.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package workbench.views.basiceditor.highlighting;
import workbench.util.EditorUtil;
/**
* Created by IntelliJ IDEA.
* User: andrew
* Date: 17/02/2012
* Time: 17:27
* To change this template use File | Settings | File Templates.
*/
public class DocumentBlockLevels {
public int insideCodeBlock = 0;
public int insideArgsBlock = 0;
public int insideArrayBlock = 0;
public static DocumentBlockLevels analyzeNestedLevels(String text, int pos) {
int start = pos;
int i_code_b = 0;
int i_args_b = 0;
int i_arra_b = 0;
char i_am_in_text = EditorUtil.EMPTY;
DocumentBlockLevels structure = new DocumentBlockLevels();
while (start >= 0) {
char c = text.charAt(start);
if (i_am_in_text == EditorUtil.EMPTY) {
if (c == EditorUtil.CODEOPEN) {
i_code_b++;
} else if (c == EditorUtil.CODECLOSE) {
i_code_b--;
} else if (c == EditorUtil.ARGSOPEN) {
i_args_b++;
} else if (c == EditorUtil.ARGSCLOSE) {
i_args_b--;
} else if (c == EditorUtil.ARRAYOPEN) {
i_arra_b++;
} else if (c == EditorUtil.ARRAYCLOSE) {
i_arra_b--;
}
}
if (c == EditorUtil.QUOTE1) {
if (i_am_in_text == EditorUtil.EMPTY) {
// entering text
i_am_in_text = EditorUtil.QUOTE1;
} else if (i_am_in_text == EditorUtil.QUOTE1) {
// exiting text
i_am_in_text = EditorUtil.EMPTY;
}
}
if (c == EditorUtil.QUOTE2) {
if (i_am_in_text == EditorUtil.EMPTY) {
// entering text
i_am_in_text = EditorUtil.QUOTE2;
} else if (i_am_in_text == EditorUtil.QUOTE2) {
// exiting text
i_am_in_text = EditorUtil.EMPTY;
}
}
if (c == EditorUtil.COMMENT) {
i_code_b = 0;
i_args_b = 0;
i_arra_b = 0;
}
if (c == EditorUtil.NEWLINE || start == 0) {
structure.insideCodeBlock += i_code_b;
structure.insideArgsBlock += i_args_b;
structure.insideArrayBlock += i_arra_b;
i_code_b = 0;
i_args_b = 0;
i_arra_b = 0;
}
start--;
}
return structure;
}
}
| andrewtikhonov/RCloud | rcloud-bench/src/main/java/workbench/views/basiceditor/highlighting/DocumentBlockLevels.java | Java | gpl-3.0 | 3,628 |
package com.benjaminsproule.cloud.domain;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Data
@Setter(AccessLevel.PACKAGE)
@NoArgsConstructor(access = AccessLevel.PACKAGE)
public class Track {
private String id;
private String path;
private Long trackNumber;
private String title;
private String artist;
private String album;
private String genre;
private String rating;
private Long length;
private boolean offline;
private String encodingType;
private ServiceName serviceName;
private Long lastModified;
}
| gigaSproule/cloud-services | src/main/java/com/benjaminsproule/cloud/domain/Track.java | Java | gpl-3.0 | 618 |
function chkSubRes{{ $nIDtxt }}j{{ $j }}() {
if (document.getElementById("n{{ $nIDtxt }}fld{{ $j }}").checked) {
setSubResponses({{ $nID }}, "{{ $nSffx }}res{{ $j }}", true, new Array({{ $grankids }}));
$("#n{{ $nIDtxt }}fld{{ $j }}sub").slideDown("fast");
} else {
$("#n{{ $nIDtxt }}fld{{ $j }}sub").slideUp("fast");
setTimeout( function() {
setSubResponses({{ $nID }}, "{{ $nSffx }}res{{ $j }}", false, new Array({{ $grankids }}));
}, 500);
}
return true;
}
$(document).on("click", "#n{{ $nIDtxt }}fld{{ $j }}", function() { chkSubRes{{ $nIDtxt }}j{{ $j }}(); }); | wikiworldorder/survloop | src/Views/forms/formtree-sub-response-ajax.blade.php | PHP | gpl-3.0 | 634 |
/*
Copyright © 2007, 2008, 2009, 2010, 2011 Vladimír Vondruš <mosra@centrum.cz>
This file is part of Kompas.
Kompas is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 3
only, as published by the Free Software Foundation.
Kompas is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License version 3 for more details.
*/
#include "Matrix.h"
#include <algorithm> /* sort() */
using namespace std;
namespace Kompas { namespace Sdl {
/* Zakázání položky */
template<class Item> void Matrix<Item>::disableItem(itemId item) {
items[item].flags |= DISABLED;
reloadItems();
}
/* Povolení položky */
template<class Item> void Matrix<Item>::enableItem(itemId item) {
items[item].flags &= ~DISABLED;
reloadItems();
}
/* Obnovení položek */
template<class Item> void Matrix<Item>::reloadItems() {
sortedHorizontal.clear(); sortedHorizontal.reserve(items.size());
sortedVertical.clear(); sortedVertical.reserve(items.size());
/* Naplnění tříděných jen aktivními položkami */
for(typename vector<Item>::const_iterator it = items.begin(); it != items.end(); ++it) {
if(!((*it).flags & DISABLED)) {
sortedHorizontal.push_back(it);
sortedVertical.push_back(it);
}
}
sort(sortedHorizontal.begin(), sortedHorizontal.end(), horizontalCompare);
sort(sortedVertical.begin(), sortedVertical.end(), verticalCompare);
if(sortedVertical.size() != 0) actualItem = sortedVertical.front();
else actualItem = items.end();
}
/* Posun nahoru */
template<class Item> bool Matrix<Item>::moveUp(void) {
if(sortedHorizontal.size() == 0) return false;
/* Nalezení aktuální položky */
typename vector<typename vector<Item>::const_iterator>::const_iterator it = sortedHorizontal.begin();
for( ; it != sortedHorizontal.end(); ++it) {
if(*it == actualItem) break;
}
/* Hledání jiného řádku (nekonečné procházení, dokud se nevrátíme zpět na počáteční položku) */
do {
if(it-- == sortedHorizontal.begin()) it = sortedHorizontal.end()-1;
} while(*it != actualItem && (**it).y == (*actualItem).y);
/* Žádný jiný řádek neexistuje, jsme zpět na aktuální položce */
if(*it == actualItem) return false;
/* Hledání lepšího kandidáta v daném řádku (y) - blíže k x než předešlý */
int y = (**it).y; int x = (*actualItem).x; actualItem = *it;
while(it-- != sortedHorizontal.begin() && (**it).y == y) {
/* Pokud je položka blíže aktuální než předešlý kandidát, přiřazení */
if( ((**it).x <= x && (*actualItem).x < (**it).x) || /* vlevo od aktuální */
((**it).x >= x && (*actualItem).x > (**it).x) /* vpravo od aktuální */
) actualItem = *it;
/* Položka je dále než předešlý kandidát, konec */
else break;
}
return true;
}
/* Posun dolů */
template<class Item> bool Matrix<Item>::moveDown(void) {
if(sortedHorizontal.size() == 0) return false;
/* Nalezení aktuální položky */
typename vector<typename vector<Item>::const_iterator>::const_iterator it = sortedHorizontal.begin();
for( ; it != sortedHorizontal.end(); ++it) {
if(*it == actualItem) break;
}
/* Hledání jiného řádku (nekonečné procházení, dokud se nevrátíme zpět na počáteční položku) */
do {
if(++it == sortedHorizontal.end()) it = sortedHorizontal.begin();
} while(*it != actualItem && (**it).y == (*actualItem).y);
/* Žádný jiný řádek neexistuje, jsme zpět na aktuální položce */
if(*it == actualItem) return false;
/* Hledání lepšího kandidáta v daném řádku (y) - blíže k x než předešlý */
int y = (**it).y; int x = (*actualItem).x; actualItem = *it;
while(++it != sortedHorizontal.end() && (**it).y == y) {
/* Pokud je položka blíže aktuální než předešlý kandidát, přiřazení */
if( ((**it).x <= x && (*actualItem).x < (**it).x) || /* vlevo od aktuální */
((**it).x >= x && (*actualItem).x > (**it).x) /* vpravo od aktuální */
) actualItem = *it;
/* Položka je dále než předešlý kandidát, konec */
else break;
}
return true;
}
/* Posun doleva */
template<class Item> bool Matrix<Item>::moveLeft(void) {
if(sortedVertical.size() == 0) return false;
/* Nalezení aktuální položky */
typename vector<typename vector<Item>::const_iterator>::const_iterator it = sortedVertical.begin();
for( ; it != sortedVertical.end(); ++it) {
if(*it == actualItem) break;
}
/* Hledání jiného sloupce (nekonečné procházení, dokud se nevrátíme zpět na počáteční položku) */
do {
if(it-- == sortedVertical.begin()) it = sortedVertical.end()-1;
} while(*it != actualItem && (**it).x == (*actualItem).x);
/* Žádný jiný sloupec neexistuje, jsme zpět na aktuální položce */
if(*it == actualItem) return false;
/* Hledání lepšího kandidáta v daném sloupci (x) - blíže k y než předešlý */
int x = (**it).x; int y = (*actualItem).y; actualItem = *it;
while(it-- != sortedVertical.begin() && (**it).x == x) {
/* Pokud je položka blíže aktuální než předešlý kandidát, přiřazení */
if( ((**it).y <= y && (*actualItem).y < (**it).y) || /* výše než aktuální */
((**it).y >= y && (*actualItem).y > (**it).y) /* níže než aktuální */
) actualItem = *it;
/* Položka je dále než předešlý kandidát, konec */
else break;
}
return true;
}
/* Posun doprava */
template<class Item> bool Matrix<Item>::moveRight(void) {
if(sortedVertical.size() == 0) return false;
/* Nalezení aktuální položky */
typename vector<typename vector<Item>::const_iterator>::const_iterator it = sortedVertical.begin();
for( ; it != sortedVertical.end(); ++it) {
if(*it == actualItem) break;
}
/* Hledání jiného sloupce (nekonečné procházení, dokud se nevrátíme zpět na počáteční položku) */
do {
if(++it == sortedVertical.end()) it = sortedVertical.begin();
} while(*it != actualItem && (**it).x == (*actualItem).x);
/* Žádný jiný sloupec neexistuje, jsme zpět na aktuální položce */
if(*it == actualItem) return false;
/* Hledání lepšího kandidáta v daném sloupci (x) - blíže k y než předešlý */
int x = (**it).x; int y = (*actualItem).y; actualItem = *it;
while(++it != sortedVertical.end() && (**it).x == x) {
/* Pokud je položka blíže aktuální než předešlý kandidát, přiřazení */
if( ((**it).y <= y && (*actualItem).y < (**it).y) || /* výše než aktuální */
((**it).y >= y && (*actualItem).y > (**it).y) /* níže než aktuální */
) actualItem = *it;
/* Položka je dále než předešlý kandidát (už lepší nenajdeme), konec */
else break;
}
return true;
}
}}
| mosra/kompas-sdl | src/Matrix.cpp | C++ | gpl-3.0 | 7,345 |
import "@/lang/locale/en"
import './main' | leek-wars/leek-wars-client | src/main-en.ts | TypeScript | gpl-3.0 | 41 |
'use strict';
var winston = require('winston'),
loggerUtils = require('alien-node-winston-utils');
module.exports = {
port : 3000, // TODO this isnt setup for nginx yet
server : {
// Ports on which to run node instances. Should be n-1 instances, where n is the number of cores.
enabledPorts : [3000]
},
mysql : {
connectionLimit : 10,
host : 'localhost',
user : process.env.MYSQL_USER,
password : process.env.MYSQL_PASS,
database : 'club540'
},
// // Email configuration
// email : {
// smtp : {
// host : "smtp.mailgun.org",
// port : 465,
// sender : "noreply@playlist.com",
// username : "postmaster@playlist.com",
// password : "Playlist123"
// }
// },
redis : {
host : 'localhost',
port : 6379,
password : ''
},
logging : {
winston : {
transports : [
{
name : 'console',
level : 'debug',
timestamp : loggerUtils.getDateString,
colorize : true,
transportType : 'console'
}
// TODO: allow parallel logging strategies
// using this strategy will disable console logging of errors
// {
// name : 'file',
// level : 'debug',
// timestamp : loggerUtils.getTimestamp,
// colorize : true,
// transportType : 'file',
// filename : 'logs/activity.log',
// json : false, // required for formatter to work
// formatter : loggerUtils.getFormatter,
// handleExceptions : true,
// datePattern : '.yyyy-MM-dd' // dictates how logs are rotated - more specific pattern rotates more often
// }
],
strategies : {
console : winston.transports.Console,
file : winston.transports.DailyRotateFile
}
}
},
errors : {
db : {
NO_RESULTS : {
code : 6000,
message : 'No results'
}
}
}
};
| SeanCannon/club540 | config/production.js | JavaScript | gpl-3.0 | 2,188 |
/*
* jStorybook: すべての小説家・作者のためのオープンソース・ソフトウェア
* Copyright (C) 2008 - 2012 Martin Mustun
* (このソースの製作者) KMY
*
* このプログラムはフリーソフトです。
* あなたは、自由に修正し、再配布することが出来ます。
* あなたの権利は、the Free Software Foundationによって発表されたGPL ver.2以降によって保護されています。
*
* このプログラムは、小説・ストーリーの制作がよりよくなるようにという願いを込めて再配布されています。
* あなたがこのプログラムを再配布するときは、GPLライセンスに同意しなければいけません。
* <http://www.gnu.org/licenses/>.
*/
package jstorybook.view.pane;
/**
* 比較可能なペイン
*
* @author KMY
*/
public interface IComparablePane {
public PaneType getPaneType ();
public long getPaneId ();
public default boolean isEqualPane (IComparablePane other) {
return this.getPaneType() == other.getPaneType() && this.getPaneId() == other.getPaneId();
}
}
| kmycode/jstorybook | src/jstorybook/view/pane/IComparablePane.java | Java | gpl-3.0 | 1,126 |
/*
* Grakn - A Distributed Semantic Database
* Copyright (C) 2016 Grakn Labs Limited
*
* Grakn is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Grakn is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>.
*/
package ai.grakn.graph.internal;
import ai.grakn.concept.Concept;
import ai.grakn.concept.Instance;
import ai.grakn.concept.Relation;
import ai.grakn.concept.RoleType;
import ai.grakn.exception.NoEdgeException;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* An internal concept used to represent the link between a roleplayer and it's role.
* For example Pacino as an actor would be represented by a single casting regardless of the number of movies he acts in.
*/
class CastingImpl extends ConceptImpl {
CastingImpl(Vertex v, RoleType type, AbstractGraknGraph graknGraph) {
super(v, type, graknGraph);
}
/**
*
* @return The {@link RoleType} this casting is linked with
*/
public RoleType getRole() {
Concept concept = getParentIsa();
if(concept != null)
return concept.asRoleType();
else
throw new NoEdgeException(toString(), Schema.BaseType.ROLE_TYPE.name());
}
/**
*
* @return The {@link Instance} which is the roleplayer in this casting
*/
public InstanceImpl getRolePlayer() {
Concept concept = getOutgoingNeighbour(Schema.EdgeLabel.ROLE_PLAYER);
if(concept != null)
return (InstanceImpl) concept;
else
return null;
}
/**
* Sets thew internal index of this casting toi allow for faster lookup.
* @param role The {@link RoleType} this casting is linked with
* @param rolePlayer The {@link Instance} which is the roleplayer in this casting
* @return The casting itself.
*/
public CastingImpl setHash(RoleTypeImpl role, InstanceImpl rolePlayer){
String hash;
if(getGraknGraph().isBatchLoadingEnabled())
hash = "CastingBaseId_" + this.getBaseIdentifier() + UUID.randomUUID().toString();
else
hash = generateNewHash(role, rolePlayer);
setUniqueProperty(Schema.ConceptProperty.INDEX, hash);
return this;
}
/**
*
* @param role The {@link RoleType} this casting is linked with
* @param rolePlayer The {@link Instance} which is the roleplayer in this casting
* @return A unique hash for the casting.
*/
public static String generateNewHash(RoleTypeImpl role, InstanceImpl rolePlayer){
return "Casting-Role-" + role.getId() + "-RolePlayer-" + rolePlayer.getId();
}
/**
*
* @return All the {@link Relation} this casting is linked with.
*/
public Set<RelationImpl> getRelations() {
ConceptImpl<?, ?> thisRef = this;
Set<RelationImpl> relations = new HashSet<>();
Set<ConceptImpl> concepts = thisRef.getIncomingNeighbours(Schema.EdgeLabel.CASTING);
if(concepts.size() > 0){
relations.addAll(concepts.stream().map(concept -> (RelationImpl) concept).collect(Collectors.toList()));
}
return relations;
}
}
| fppt/mindmapsdb | grakn-graph/src/main/java/ai/grakn/graph/internal/CastingImpl.java | Java | gpl-3.0 | 3,785 |
package com.nilhcem.bblfr.core.dagger;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jakewharton.picasso.OkHttp3Downloader;
import com.nilhcem.bblfr.BBLApplication;
import com.nilhcem.bblfr.BuildConfig;
import com.nilhcem.bblfr.core.map.LocationProvider;
import com.nilhcem.bblfr.core.prefs.Preferences;
import com.squareup.picasso.Picasso;
import java.io.File;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import timber.log.Timber;
@Module
public class BBLModule {
private static final int DISK_CACHE_SIZE = 52_428_800; // 50MB (50 * 1024 * 1024)
private final BBLApplication mApp;
public BBLModule(BBLApplication app) {
mApp = app;
}
@Provides @Singleton LocationProvider provideLocationProvider() {
return new LocationProvider();
}
@Provides @Singleton Preferences providePreferences() {
return new Preferences(mApp);
}
@Provides @Singleton OkHttpClient provideOkHttpClient() {
// Install an HTTP cache in the application cache directory.
File cacheDir = new File(mApp.getCacheDir(), "http");
Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
return new OkHttpClient.Builder().cache(cache).build();
}
@Provides @Singleton ObjectMapper provideObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
return mapper;
}
@Provides @Singleton Picasso providePicasso(OkHttpClient client) {
Picasso.Builder builder = new Picasso.Builder(mApp).downloader(new OkHttp3Downloader(client));
if (BuildConfig.DEBUG) {
builder.listener((picasso, uri, e) -> Timber.e(e, "Failed to load image: %s", uri));
}
return builder.build();
}
}
| Nilhcem/bblfr-android | app/src/main/java/com/nilhcem/bblfr/core/dagger/BBLModule.java | Java | gpl-3.0 | 1,947 |
//Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda.
//This file is part of SIAT. SIAT is licensed under the terms
//of the GNU General Public License, version 3.
//See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt>
package ar.gov.rosario.siat.gde.buss.bean;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import ar.gov.rosario.siat.base.iface.util.BaseError;
import ar.gov.rosario.siat.def.buss.bean.ServicioBanco;
import ar.gov.rosario.siat.def.iface.util.DefError;
import ar.gov.rosario.siat.gde.buss.dao.GdeDAOFactory;
import ar.gov.rosario.siat.gde.iface.util.GdeError;
import coop.tecso.demoda.buss.bean.BaseBO;
import coop.tecso.demoda.iface.helper.DateUtil;
/**
* Bean correspondiente a Servicio Banco Descuentos Generales
*
* @author tecso
*/
@Entity
@Table(name = "gde_serBanDesGen")
public class SerBanDesGen extends BaseBO {
private static final long serialVersionUID = 1L;
@Column(name = "fechaDesde")
private Date fechaDesde;
@Column(name = "fechaHasta")
private Date fechaHasta;
@ManyToOne()
@JoinColumn(name="idServicioBanco")
private ServicioBanco servicioBanco;
@ManyToOne()
@JoinColumn(name="idDesGen")
private DesGen desGen;
//Constructores
public SerBanDesGen(){
super();
}
// Getters y Setters
public Date getFechaDesde(){
return fechaDesde;
}
public void setFechaDesde(Date fechaDesde){
this.fechaDesde = fechaDesde;
}
public Date getFechaHasta(){
return fechaHasta;
}
public void setFechaHasta(Date fechaHasta){
this.fechaHasta = fechaHasta;
}
public ServicioBanco getServicioBanco(){
return servicioBanco;
}
public void setServicioBanco(ServicioBanco servicioBanco){
this.servicioBanco = servicioBanco;
}
public DesGen getDesGen(){
return desGen;
}
public void setDesGen(DesGen desGen){
this.desGen = desGen;
}
// Metodos de Clase
public static SerBanDesGen getById(Long id) {
return (SerBanDesGen) GdeDAOFactory.getSerBanDesGenDAO().getById(id);
}
public static SerBanDesGen getByIdNull(Long id) {
return (SerBanDesGen) GdeDAOFactory.getSerBanDesGenDAO().getByIdNull(id);
}
public static List<SerBanDesGen> getList() {
return (ArrayList<SerBanDesGen>) GdeDAOFactory.getSerBanDesGenDAO().getList();
}
public static List<SerBanDesGen> getListActivos() {
return (ArrayList<SerBanDesGen>) GdeDAOFactory.getSerBanDesGenDAO().getListActiva();
}
// Metodos de Instancia
// Validaciones
/**
* Valida la creacion
* @author
*/
public boolean validateCreate() throws Exception{
//limpiamos la lista de errores
clearError();
this.validate();
if (hasError()) {
return false;
}
return !hasError();
}
/**
* Valida la actualizacion
* @author
*/
public boolean validateUpdate() throws Exception{
//limpiamos la lista de errores
clearError();
this.validate();
if (hasError()) {
return false;
}
return !hasError();
}
private boolean validate() throws Exception{
//limpiamos la lista de errores
clearError();
//UniqueMap uniqueMap = new UniqueMap();
//Validaciones de Requeridos
if (getServicioBanco()==null) {
addRecoverableError(BaseError.MSG_CAMPO_REQUERIDO, GdeError.SERBANDESGEN_SERVICIOBANCO);
}
if (getDesGen()==null) {
addRecoverableError(BaseError.MSG_CAMPO_REQUERIDO, GdeError.SERBANDESGEN_DESGEN);
}
if (getFechaDesde()==null) {
addRecoverableError(BaseError.MSG_CAMPO_REQUERIDO, GdeError.SERBANDESGEN_FECHADESDE);
}
if (hasError()) {
return false;
}
// Validaciones de Unicidad
// Otras Validaciones
// Valida que la Fecha Desde no sea mayor que la fecha Hasta
if(!DateUtil.isDateBefore(this.fechaDesde, this.fechaHasta)){
addRecoverableError(BaseError.MSG_VALORMAYORQUE, DefError.SERBANREC_FECHADESDE, DefError.SERBANREC_FECHAHASTA);
}
return !hasError();
}
/**
* Valida la eliminacion
* @author
*/
public boolean validateDelete() {
//limpiamos la lista de errores
clearError();
//Validaciones de VO
if (hasError()) {
return false;
}
// Validaciones de Negocio
return true;
}
// Metodos de negocio
}
| avdata99/SIAT | siat-1.0-SOURCE/src/buss/src/ar/gov/rosario/siat/gde/buss/bean/SerBanDesGen.java | Java | gpl-3.0 | 4,361 |
'use strict';
const path = require('path');
const os = require('os');
const fs = require('fs-extra');
const fieHome = require('fie-home');
const debug = require('debug')('core-report');
const fieUser = require('fie-user');
const execSync = require('child_process').execSync;
const spawn = require('cross-spawn');
const cache = require('fie-cache');
/**
* 环境变量获取
*/
const cacheEnvGetter = {
fieVersion() {
return (
process.env.FIE_VERSION ||
execSync('npm view fie version')
.toString()
.replace(/[\nv]/g, '')
);
},
email() {
return fieUser.getEmail();
},
nodeVersion() {
return execSync('node -v')
.toString()
.replace(/[\nv]/g, '');
},
npmVersion() {
try {
return execSync('npm -v')
.toString()
.replace('\n', '');
} catch (e) {
return null;
}
},
tnpmVersion() {
try {
return execSync('tnpm -v')
.toString()
.split('\n')[0]
.match(/\d+\.\d+\.\d+/)[0];
} catch (ex) {
// 外网无tnpm
return null;
}
},
system() {
return `${os.platform()} ${os.release()}`;
},
};
/**
* 获取当前分支版本
* @param cwd
* @returns {string}
*/
exports.getCurBranch = function(cwd) {
const headerFile = path.join(cwd, '.git/HEAD');
let version = '';
if (fs.existsSync(headerFile)) {
const gitVersion = fs.readFileSync(headerFile, { encoding: 'utf8' });
const arr = gitVersion.split(/refs[\\\/]heads[\\\/]/g);
if (arr && arr.length > 1) {
version = arr[1];
}
}
return version.trim();
};
/**
* 获取项目URL
* @returns {*}
*/
exports.getProjectUrl = function() {
let url;
try {
url = (
spawn
.sync('git', ['config', '--get', 'remote.origin.url'], { silent: true })
.stdout.toString() || ''
).trim();
// 有些git的url是http开头的,需要格式化为git@格式,方便统一处理
const match = url.match(/http:\/\/gitlab.alibaba-inc.com\/(.*)/);
if (match && match[1]) {
url = `git@gitlab.alibaba-inc.com:${match[1]}`;
}
} catch (err) {
debug('git config 错误:', err.message);
}
return url;
};
/**
* 获取项目相关环境
*/
exports.getProjectInfo = function(cwd) {
const branch = exports.getCurBranch(cwd);
const pkgPath = path.join(cwd, 'package.json');
const CONFIG_FILE = process.env.FIE_CONFIG_FILE || 'fie.config.js';
const fiePath = path.join(cwd, CONFIG_FILE);
// 这里不能使用fieConfig这个包,会循环引用
let pkg;
let fie;
let repository = exports.getProjectUrl();
// 判断pkg是否存在
if (fs.existsSync(pkgPath)) {
pkg = fs.readJsonSync(pkgPath, { throws: false });
}
// 判断fie.config.js是否存在
if (fs.existsSync(fiePath)) {
delete require.cache[fiePath];
try {
fie = require(fiePath);
} catch (e) {
fie = null;
}
}
// 如果git中没有则尝试从pkg中获取
if (pkg && pkg.repository && pkg.repository.url) {
repository = pkg.repository.url;
}
return {
cwd,
branch,
pkg,
fie,
repository,
};
};
/**
* 获取项目的环境信息
* @param force 为true时 则获取实时信息,否则读取缓存
* 对 tnpm, node 版本等重新获取,一般在报错的时候才传入 true
* @returns {*}
*/
exports.getProjectEnv = function(force) {
let cacheEnv = cache.get('reportEnvCache');
if (!cacheEnv || force) {
cacheEnv = {};
const cacheEnvKeys = Object.keys(cacheEnvGetter);
cacheEnvKeys.forEach(item => {
cacheEnv[item] = cacheEnvGetter[item]();
});
// 缓存三天
cache.set('reportEnvCache', cacheEnv, { expires: 259200000 });
}
return cacheEnv;
};
/**
* 获取当前执行的命令,移除用户路径
*/
exports.getCommand = function(arg) {
let argv = arg || process.argv;
argv = argv.map(item => {
const match = item.match(/\\bin\\(((?!bin).)*)$|\/bin\/(.*)/);
// mac
if (match && match[3]) {
// 一般 node fie -v 这种方式则不需要显示 node
return match[3] === 'node' ? '' : match[3];
} else if (match && match[1]) {
// 一般 node fie -v 这种方式则不需要显示 node
return match[1] === 'node.exe' ? '' : match[1];
} else if (!match && item.indexOf('node.exe') !== -1) {
// fix如果C:\\node.exe 这种不带bin的路径
// TODO 当然这里的正则可以再优化兼容一下
return '';
}
return item;
});
return argv.join(' ').trim();
};
/**
* 获取模块的类型和版本
*/
exports.getFieModuleVersion = function(mod) {
const modPkgPath = path.join(fieHome.getModulesPath(), mod, 'package.json');
let pkg = {};
if (fs.existsSync(modPkgPath)) {
pkg = fs.readJsonSync(modPkgPath, { throws: false }) || {};
}
return pkg.version;
};
| fieteam/fie | packages/fie-report/lib/utils.js | JavaScript | gpl-3.0 | 4,841 |
module.exports = {
'extends': ['google', 'plugin:react/recommended'],
'parserOptions': {
'ecmaVersion': 6,
'sourceType': 'module',
'ecmaFeatures': {
'jsx': true
}
},
'env': {
'browser': true,
},
'plugins': [
'react'
]
};
| BadgerTek/mern-skeleton | .eslintrc.client.js | JavaScript | gpl-3.0 | 293 |
#-------------------------------------------------------------------------------
# Name: MissingPersomForm.py
#
# Purpose: Create Missing Person Flyer from data stored in the Subject
# Information data layer within MapSAR
#
# Author: Don Ferguson
#
# Created: 12/12/2011
# Copyright: (c) Don Ferguson 2011
# Licence:
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# The GNU General Public License can be found at
# <http://www.gnu.org/licenses/>.
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import arcpy
from datetime import datetime
#workspc = arcpy.GetParameterAsText(0)
output = arcpy.GetParameterAsText(0)
#arcpy.env.workspace = workspc
arcpy.env.overwriteOutput = "True"
fc3="Incident_Information"
fc2="Lead Agency"
rows = arcpy.SearchCursor(fc3)
row = rows.next()
arcpy.AddMessage("Get Incident Info")
while row:
# you need to insert correct field names in your getvalue function
LeadAgency = row.getValue("Lead_Agency")
where2 = '"Lead_Agency" = ' + "'" + LeadAgency + "'"
arcpy.AddMessage(where2)
rows2 = arcpy.SearchCursor(fc2, where2)
row2 = rows2.next()
Phone = 'none'
email = 'none'
while row2:
# you need to insert correct field names in your getvalue function
Phone = row2.getValue("Lead_Phone")
if Phone == 'none':
Phone = " "
arcpy.AddWarning("No Phone number provided for Lead Agency")
email = row2.getValue("E_Mail")
if email == 'none':
email = " "
arcpy.AddWarning("No e-mail address provided for Lead Agency")
row2 = rows2.next()
del rows2
del row2
row = rows.next()
del rows
del row
Callback = "If you have information please call: " + str(LeadAgency) + " at phone: " + str(Phone) + " or e-mail:" + str(email)
fc1="Subject_Information"
rows = arcpy.SearchCursor(fc1)
row = rows.next()
while row:
# you need to insert correct field names in your getvalue function
try:
Subject_Name = row.getValue("Name")
if len(Subject_Name) == 0:
arcpy.AddWarning('Need to provide a Subject Name')
except:
Subject_Name = " "
arcpy.AddWarning('Need to provide a Subject Name')
try:
fDate = row.getValue("Date_Seen")
Date_Seen = fDate.strftime("%m/%d/%Y")
except:
Date_Seen = " "
try:
fTime = row.getValue("Time_Seen")
except:
fTime = " "
Where_Last = row.getValue("WhereLastSeen")
Age = row.getValue("Age")
Gender = row.getValue("Gender")
Race = row.getValue("Race")
try:
Height1 = (row.getValue("Height"))/12.0
feet = int(Height1)
inches = int((Height1 - feet)*12.0)
fInches = "%1.0f" %inches
Height = str(feet) + " ft " + fInches +" in"
except:
Height = "NA"
Weight = row.getValue("Weight")
Build = row.getValue("Build")
Complex = row.getValue("Complexion")
Hair = row.getValue("Hair")
Eyes = row.getValue("Eyes")
Other = row.getValue("Other")
Shirt = row.getValue("Shirt")
Pants = row.getValue("Pants")
Jacket = row.getValue("Jacket")
Hat = row.getValue("Hat")
Footwear = row.getValue("Footwear")
Info = row.getValue("Info")
try:
QRCode = row.getValue("QRCode")
except:
QRCode = " "
filename = output + "/" + str(Subject_Name) + ".fdf"
txt= open (filename, "w")
txt.write("%FDF-1.2\n")
txt.write("%????\n")
txt.write("1 0 obj<</FDF<</F(MissingPersonForm.pdf)/Fields 2 0 R>>>>\n")
txt.write("endobj\n")
txt.write("2 0 obj[\n")
txt.write ("\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_Name[0])/V(" + str(Subject_Name) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPFAge[0])/V(" + str(Age) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPFSex[0])/V(" + str(Gender) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_Location[0])/V(" + str(Where_Last) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_TimeMissing[0])/V(" + fTime + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_DateMissing[0])/V(" + str(Date_Seen) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_Race[0])/V(" + str(Race) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_Height[0])/V(" + Height + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_Weight[0])/V(" + str(Weight) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_Build[0])/V(" + str(Build) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_Complex[0])/V(" + str(Complex) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_HairColor[0])/V(" + str(Hair) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_EyeColor[0])/V(" + str(Eyes) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_OtherPhy[0])/V(" + str(Other) + ")>>\n")
#txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_OtherPhy[1])/V(" + str(Incident_Name) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_ShirtClothing[0])/V(" + str(Shirt) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_PantsClothing[0])/V(" + str(Pants) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_JacketClothing[0])/V(" + str(Jacket) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_HatClothing[0])/V(" + str(Hat) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_FootClothing[0])/V(" + str(Footwear) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_OtherInfo[0])/V(" + str(Info) + ")>>\n")
txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].MPF_CallNumber[0])/V(" + str(Callback) + ")>>\n")
#txt.write("<</T(topmostSubform[0].Page1[0].Layer[0].Layer[0].ImageField1[0])/V(" + str(Incident_Name) + ")>>\n")
txt.write("]\n")
txt.write("endobj\n")
txt.write("trailer\n")
txt.write("<</Root 1 0 R>>\n")
txt.write("%%EO\n")
txt.close ()
row = rows.next()
del rows
del row
#arcpy.DeleteFeatures_management(fc3) | dferguso/IGT4SAR | MissingPersonForm.py | Python | gpl-3.0 | 6,940 |
/**
* Client.
* @module client
*/
/**
* View configuration.
* @class ViewConfig
*/
function ViewConfig(resources) {
this.playAnimations = true;
this.resources = resources;
}
/**
* Should we play animations?
* @method setPlayAnimations
*/
ViewConfig.prototype.setPlayAnimations = function(value) {
this.playAnimations = value;
}
/**
* Should we play animations?
* @method getPlayAnimations
*/
ViewConfig.prototype.getPlayAnimations = function() {
return this.playAnimations;
}
/**
* Scale animation time.
* @method scaleAnimationTime
*/
ViewConfig.prototype.scaleAnimationTime = function(millis) {
if (this.playAnimations)
return millis;
return 1;
}
/**
* Get resources.
* @method getResources
*/
ViewConfig.prototype.getResources = function() {
return this.resources;
}
module.exports = ViewConfig; | limikael/netpoker | src/client/resources/ViewConfig.js | JavaScript | gpl-3.0 | 832 |
from kivy.lib import osc
from time import sleep
import pocketclient
from kivy.utils import platform as kivy_platform
SERVICE_PORT = 4000
def platform():
p = kivy_platform()
if p.lower() in ('linux', 'waindows', 'osx'):
return 'desktop'
else:
return p
class Service(object):
def __init__(self):
osc.init()
self.last_update = 0
self.oscid = osc.listen(ipAddr='localhost', port=SERVICE_PORT)
osc.bind(self.oscid, self.pocket_connect, '/pocket/connect')
osc.bind(self.oscid, self.pocket_list, '/pocket/list')
osc.bind(self.oscid, self.pocket_mark_read, '/pocket/mark_read')
def send(self, **kwargs):
osc.sendMsg()
def run(self):
while self._run:
osc.readQueue(self.oscid)
sleep(.1)
def pocket_connect(self, **kwargs):
if 'token' in kwargs:
self.token = kwargs['token']
else:
pocketclient.authorize(platform(), self.save_pocket_token)
def save_pocket_token(self, api_key, token, username):
self.token = {
'key': api_key,
'token': token,
'username': username
}
def pocket_list(self, *args):
if not self.token:
if self.pocket_last_update:
pocketclient.get_items(self.
else:
pass
pass
def pocket_mark_read(self, *args):
pass
if __name__ == '__main__':
Service().run()
| tshirtman/kpritz | service/main.py | Python | gpl-3.0 | 1,497 |
package it.niedermann.owncloud.notes.main.items.selection;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.selection.ItemKeyProvider;
import androidx.recyclerview.widget.RecyclerView;
import static androidx.recyclerview.widget.RecyclerView.NO_POSITION;
public class ItemIdKeyProvider extends ItemKeyProvider<Long> {
private final RecyclerView recyclerView;
public ItemIdKeyProvider(RecyclerView recyclerView) {
super(SCOPE_MAPPED);
this.recyclerView = recyclerView;
}
@Nullable
@Override
public Long getKey(int position) {
final RecyclerView.Adapter<?> adapter = recyclerView.getAdapter();
if (adapter == null) {
throw new IllegalStateException("RecyclerView adapter is not set!");
}
return adapter.getItemId(position);
}
@Override
public int getPosition(@NonNull Long key) {
final RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForItemId(key);
return viewHolder == null ? NO_POSITION : viewHolder.getLayoutPosition();
}
} | stefan-niedermann/OwnCloud-Notes | app/src/main/java/it/niedermann/owncloud/notes/main/items/selection/ItemIdKeyProvider.java | Java | gpl-3.0 | 1,115 |
package com.github.cunvoas.iam.persistance.entity;
import com.github.cunvoas.iam.persistance.entity.RessourceValeur;
import javax.annotation.Generated;
import javax.persistence.metamodel.ListAttribute;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.0.v20130507-rNA", date="2014-12-29T14:58:17")
@StaticMetamodel(Valeur.class)
public class Valeur_ {
public static volatile SingularAttribute<Valeur, Integer> id;
public static volatile SingularAttribute<Valeur, String> valeur;
public static volatile ListAttribute<Valeur, RessourceValeur> ressourceValues;
} | cunvoas/springsecurity_iam | iam-core/src/main/java/com/github/cunvoas/iam/persistance/entity/Valeur_.java | Java | gpl-3.0 | 666 |
using System;
using System.Collections.Generic;
using System.Text;
using libtcodWrapper;
namespace RogueBasin
{
class MapGeneratorCave
{
Map baseMap;
/// <summary>
/// Chance of digging surrounding squares
/// </summary>
public int DiggingChance { get; set; }
/// <summary>
/// When connecting stairs, the chance to expand the corridor
/// </summary>
public int MineChance { get; set; }
/// <summary>
/// How much of the level must be open (not necessarily connected)
/// </summary>
public double PercOpenRequired { get; set; }
/// <summary>
/// How far away the stairs are guaranteed to be
/// </summary>
public double RequiredStairDistance { get; set; }
public int Width {get; set;}
public int Height {get; set;}
Point upStaircase;
Point downStaircase;
Point pcStartLocation;
public bool DoFillInPass = false;
public int FillInChance = 33;
public MapTerrain FillInTerrain = MapTerrain.Empty;
public Map Map { get {return baseMap;} }
private List<MapTerrain> closedTerrainType;
private List<MapTerrain> openTerrainType;
public MapGeneratorCave()
{
closedTerrainType = new List<MapTerrain>();
openTerrainType = new List<MapTerrain>();
closedTerrainType.Add(MapTerrain.Wall);
openTerrainType.Add(MapTerrain.Empty);
}
public Map GenerateMap() {
LogFile.Log.LogEntry("Making cave map");
if (Width < 1 || Height < 1)
{
LogFile.Log.LogEntry("Can't make 0 dimension map");
throw new ApplicationException("Can't make with 0 dimension");
}
DiggingChance = 20;
MineChance = 15;
PercOpenRequired = 0.4;
RequiredStairDistance = 40;
int maxStairConnectAttempts = 10;
//Since we can't gaurantee connectivity, we will run the map gen many times until we get a map that meets our criteria
bool badMap = true;
int mapsMade = 0;
do
{
baseMap = new Map(Width, Height);
mapsMade++;
//Fill map with walls
for (int i = 0; i < Width; i++)
{
for (int j = 0; j < Height; j++)
{
SetSquareClosed(i, j);
}
}
//Start digging from a random point
int noDiggingPoints = 4 + Game.Random.Next(4);
for (int i = 0; i < noDiggingPoints; i++)
{
int x = Game.Random.Next(Width);
int y = Game.Random.Next(Height);
//Don't dig right to the edge
if (x == 0)
x = 1;
if (x == Width - 1)
x = Width - 2;
if (y == 0)
y = 1;
if (y == Height - 1)
y = Height - 2;
Dig(x, y);
}
//Check if we are too small, and add more digs
while (CalculatePercentageOpen() < PercOpenRequired)
{
int x = Game.Random.Next(Width);
int y = Game.Random.Next(Height);
//Don't dig right to the edge
if (x == 0)
x = 1;
if (x == Width - 1)
x = Width - 2;
if (y == 0)
y = 1;
if (y == Height - 1)
y = Height - 2;
Dig(x, y);
}
//Find places for the stairs
//We will attempt this several times before we give up and redo the whole map
int attempts = 0;
do
{
double stairDistance;
do
{
upStaircase = RandomPoint();
downStaircase = RandomPoint();
stairDistance = Math.Sqrt(Math.Pow(upStaircase.x - downStaircase.x, 2) + Math.Pow(upStaircase.y - downStaircase.y, 2));
} while (stairDistance < RequiredStairDistance);
//If the stairs aren't connected, try placing them in different random spots, by relooping
if (ArePointsConnected(upStaircase, downStaircase))
{
badMap = false;
break;
}
attempts++;
} while (attempts < maxStairConnectAttempts);
} while (badMap);
//If requested do a final pass and fill in with some interesting terrain
//Fill map with walls
if (DoFillInPass)
{
for (int i = 0; i < Width; i++)
{
for (int j = 0; j < Height; j++)
{
if (openTerrainType.Contains(baseMap.mapSquares[i, j].Terrain))
{
if (Game.Random.Next(100) < FillInChance)
baseMap.mapSquares[i, j].Terrain = FillInTerrain;
}
}
}
}
//Caves are not guaranteed connected
baseMap.GuaranteedConnected = false;
//Set the player start location to that of the up staircase (only used on the first level)
pcStartLocation = upStaircase;
LogFile.Log.LogEntry("Total maps made: " + mapsMade.ToString());
return baseMap;
}
/// <summary>
/// Add g + rand(noRandom) water features
/// 15, 4 is good
/// </summary>
/// <param name="noGuaranteed"></param>
/// <param name="noRandom"></param>
public void AddWaterToCave(int noGuaranteed, int noRandom)
{
//Add some water features
int noWaterFeatures = noGuaranteed + Game.Random.Next(noRandom);
//Guarantee water features starting from the upstaircase
for (int i = 0; i < 2; i++)
{
int deltaX = Game.Random.Next(3) - 1;
int deltaY = Game.Random.Next(3) - 1;
AddWaterFeature(upStaircase.x, upStaircase.y, deltaX, deltaY);
}
for (int i = 0; i < noWaterFeatures; i++)
{
int x, y;
//Loop until we find an empty place to start
do
{
x = Game.Random.Next(Width);
y = Game.Random.Next(Height);
} while (!openTerrainType.Contains( baseMap.mapSquares[x, y].Terrain ));
int deltaX = Game.Random.Next(3) - 1;
int deltaY = Game.Random.Next(3) - 1;
AddWaterFeature(x, y, deltaX, deltaY);
}
}
/// <summary>
/// Call before adding list of new terrain types
/// </summary>
public void ResetClosedSquareTerrainType()
{
closedTerrainType.Clear();
}
/// <summary>
/// Call before adding list of new terrain types
/// </summary>
public void ResetOpenSquareTerrainType()
{
openTerrainType.Clear();
}
public void SetClosedSquareTerrainType(MapTerrain type)
{
closedTerrainType.Add(type);
}
public void SetOpenSquareTerrainType(MapTerrain type)
{
openTerrainType.Add(type);
}
private void SetSquareClosed(int i, int j)
{
int noClosedTerrain = closedTerrainType.Count;
baseMap.mapSquares[i, j].Terrain = closedTerrainType[Game.Random.Next(noClosedTerrain)];
baseMap.mapSquares[i, j].BlocksLight = true;
baseMap.mapSquares[i, j].Walkable = false;
}
private void SetSquareOpen(int i, int j)
{
int noOpenTerrain = openTerrainType.Count;
baseMap.mapSquares[i, j].Terrain = openTerrainType[Game.Random.Next(noOpenTerrain)];
baseMap.mapSquares[i, j].BlocksLight = false;
baseMap.mapSquares[i, j].Walkable = true;
}
private double CalculatePercentageOpen()
{
int totalOpen = 0;
for (int i = 0; i < Width; i++)
{
for (int j = 0; j < Height; j++)
{
if (openTerrainType.Contains(baseMap.mapSquares[i, j].Terrain))
totalOpen++;
}
}
double percOpen = totalOpen / (double)(Width * Height);
return percOpen;
}
private bool ArePointsConnected(Point firstPoint, Point secondPoint)
{
//Build map representations
PathingMap map = new PathingMap(Width, Height);
for (int i = 0; i < Width; i++)
{
for (int j = 0; j < Height; j++)
{
map.setCell(i, j, baseMap.mapSquares[i, j].Walkable ? PathingTerrain.Walkable : PathingTerrain.Unwalkable);
}
}
//Try to walk a path between the 2 staircases
LibTCOD.TCODPathFindingWrapper pathFinder = new LibTCOD.TCODPathFindingWrapper();
pathFinder.updateMap(0, map);
return pathFinder.arePointsConnected(0, firstPoint, secondPoint, Pathing.PathingPermission.Normal);
}
private void ConnectPoints(Point upStairsPoint, Point downStairsPoint)
{
//First check if the stairs are connected...
if (ArePointsConnected(upStaircase, downStaircase))
return;
//If not, open a path between the staircases
foreach (Point p in Utility.GetPointsOnLine(upStairsPoint, downStairsPoint))
{
int nextX = p.x;
int nextY = p.y;
Random rand = Game.Random;
SetSquareOpen(nextX, nextY);
//Chance surrounding squares also get done
if (nextX - 1 > 0 && nextY - 1 > 0)
{
if (rand.Next(100) < MineChance)
{
SetSquareOpen(nextX - 1, nextY - 1);
}
}
if (nextY - 1 > 0)
{
if (rand.Next(100) < MineChance)
{
SetSquareOpen(nextX, nextY - 1);
}
}
if (nextX + 1 < Width && nextY - 1 > 0)
{
if (rand.Next(100) < MineChance)
{
SetSquareOpen(nextX + 1, nextY - 1);
}
}
if (nextX - 1 > 0)
{
if (rand.Next(100) < MineChance)
{
SetSquareOpen(nextX - 1, nextY);
}
}
if (nextX + 1 < Width)
{
if (rand.Next(100) < MineChance)
{
SetSquareOpen(nextX + 1, nextY);
}
}
if (nextX - 1 > 0 && nextY + 1 < Height)
{
if (rand.Next(100) < MineChance)
{
SetSquareOpen(nextX - 1, nextY + 1);
}
}
if (nextY + 1 < Height)
{
if (rand.Next(100) < MineChance)
{
SetSquareOpen(nextX, nextY + 1);
}
}
if (nextX + 1 < Width && nextY + 1 < Height)
{
if (rand.Next(100) < MineChance)
{
SetSquareOpen(nextX + 1, nextY + 1);
}
}
}
}
private Point RandomPoint()
{
do
{
int x = Game.Random.Next(Width);
int y = Game.Random.Next(Height);
if (openTerrainType.Contains(baseMap.mapSquares[x, y].Terrain))
{
return new Point(x, y);
}
}
while (true);
}
public void Dig(int x, int y)
{
//Check this is a valid square to dig
if (x == 0 || y == 0 || x == Width - 1 || y == Height - 1)
return;
//Already dug
if (openTerrainType.Contains(baseMap.mapSquares[x, y].Terrain))
return;
//Set this as open
SetSquareOpen(x, y);
//Did in all the directions
Random rand = Game.Random;
//TL
if (rand.Next(100) < DiggingChance)
Dig(x - 1, y - 1);
//T
if (rand.Next(100) < DiggingChance)
Dig(x, y - 1);
//TR
if (rand.Next(100) < DiggingChance)
Dig(x + 1, y - 1);
//CL
if (rand.Next(100) < DiggingChance)
Dig(x - 1, y);
//CR
if (rand.Next(100) < DiggingChance)
Dig(x + 1, y);
//BL
if (rand.Next(100) < DiggingChance)
Dig(x - 1, y + 1);
//B
if (rand.Next(100) < DiggingChance)
Dig(x, y + 1);
//BR
if (rand.Next(100) < DiggingChance)
Dig(x + 1, y + 1);
}
private void AddWaterFeature(int x, int y, int deltaX, int deltaY)
{
//Calculate this square's coords
int squareX = x + deltaX;
int squareY = y + deltaY;
//Check this is a valid square to operate on
if (squareX == 0 || squareY == 0 || squareX == Width - 1 || squareY == Height - 1)
return;
//Already water
//if (baseMap.mapSquares[x, y].Terrain == MapTerrain.Empty)
// return;
//If this square is empty it becomes water
if (baseMap.mapSquares[x, y].Terrain == MapTerrain.Empty)
{
baseMap.mapSquares[x, y].Terrain = MapTerrain.Flooded;
}
//We are most likely to continue on the way we are going
int chance = Game.Random.Next(100);
if (chance < 75)
{
x += deltaX;
y += deltaY;
AddWaterFeature(x, y, deltaX, deltaY);
return;
}
//Chance we'll change direction
else if (chance < 98)
{
deltaX = Game.Random.Next(3) - 1;
deltaY = Game.Random.Next(3) - 1;
AddWaterFeature(x, y, deltaX, deltaY);
return;
}
//Otherwise we stop
else
{
return;
}
}
/// <summary>
/// Add staircases to the map once it has been added to dungeon
/// </summary>
/// <param name="levelNo"></param>
public void AddStaircases(int levelNo) {
Game.Dungeon.AddFeature(new Features.StaircaseUp(), levelNo, upStaircase);
Game.Dungeon.AddFeature(new Features.StaircaseDown(), levelNo, downStaircase);
}
/// <summary>
/// Add staircases to the map once it has been added to dungeon
/// </summary>
/// <param name="levelNo"></param>
public void AddDownStaircaseOnly(int levelNo)
{
//Game.Dungeon.AddFeature(new Features.StaircaseUp(), levelNo, upStaircase);
Game.Dungeon.AddFeature(new Features.StaircaseDown(), levelNo, downStaircase);
}
/// <summary>
/// Add staircases to the map once it has been added to dungeon
/// </summary>
/// <param name="levelNo"></param>
public void AddUpStaircaseOnly(int levelNo)
{
Game.Dungeon.AddFeature(new Features.StaircaseUp(), levelNo, upStaircase);
//Game.Dungeon.AddFeature(new Features.StaircaseDown(), levelNo, downStaircase);
}
/// <summary>
/// Add an exit staircase at the up staircase location
/// </summary>
internal void AddExitStaircaseOnly(int levelNo)
{
Game.Dungeon.AddFeature(new Features.StaircaseExit(levelNo), levelNo, upStaircase);
}
/// <summary>
/// Only used on the first level
/// </summary>
/// <returns></returns>
public Point GetPCStartLocation()
{
return pcStartLocation;
}
}
}
| flend/roguelike | RogueBasin/RogueBasin/MapGeneratorCave.cs | C# | gpl-3.0 | 17,934 |
/*
* Copyright (C) 2010-2015 JPEXS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jpexs.decompiler.flash.gui.player;
/**
*
* @author JPEXS
*/
public interface MediaDisplayListener {
void mediaDisplayStateChanged(MediaDisplay source);
void playingFinished(MediaDisplay source);
}
| izstas/jpexs-decompiler | src/com/jpexs/decompiler/flash/gui/player/MediaDisplayListener.java | Java | gpl-3.0 | 951 |
import cv2
import numpy as np
import datetime as dt
# constant
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
OPENCV_METHODS = {
"Correlation": 0,
"Chi-Squared": 1,
"Intersection": 2,
"Hellinger": 3}
hist_limit = 0.6
ttl = 1 * 60
q_limit = 3
# init variables
total_count = 0
prev_count = 0
total_delta = 0
stm = {}
q = []
term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
video_capture = cv2.VideoCapture(0)
while True:
for t in list(stm): # short term memory
if (dt.datetime.now() - t).seconds > ttl:
stm.pop(t, None)
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.2,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
count = len(faces)
if len(q) >= q_limit: del q[0]
q.append(count)
isSame = True
for c in q: # Protect from fluctuation
if c != count: isSame = False
if isSame is False: continue
max_hist = 0
total_delta = 0
for (x, y, w, h) in faces:
# Draw a rectangle around the faces
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
if count == prev_count: continue
# set up the ROI
face = frame[y: y + h, x: x + w]
hsv_roi = cv2.cvtColor(face, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(face, np.array((0., 60., 32.)), np.array((180., 255., 255.)))
face_hist = cv2.calcHist([face], [0], mask, [180], [0, 180])
cv2.normalize(face_hist, face_hist, 0, 255, cv2.NORM_MINMAX)
isFound = False
for t in stm:
hist_compare = cv2.compareHist(stm[t], face_hist, OPENCV_METHODS["Correlation"])
if hist_compare > max_hist: max_hist = hist_compare
if hist_compare >= hist_limit: isFound = True
if (len(stm) == 0) or (isFound is False and max_hist > 0):
total_delta += 1
stm[dt.datetime.now()] = face_hist
if prev_count != count:
total_count += total_delta
print("", count, " > ", total_count)
prev_count = count
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
| kvasnyj/face_counter | counter.py | Python | gpl-3.0 | 2,444 |
/*
* EcologicalIndexEuclideanCommand.java Copyright (C) 2021. Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package megan.clusteranalysis.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.indices.EuclideanDistance;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* method=Euclidean command
* Daniel Huson, 6.2010
*/
public class EcologicalIndexEuclideanCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getEcologicalIndex().equalsIgnoreCase(EuclideanDistance.NAME);
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use Euclidean";
}
/**
* get description to be used as a tool-tip
*
* @return description
*/
public String getDescription() {
return "Use Euclidean ecological index";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* action to be performed
*
* @param ev
*/
public void actionPerformed(ActionEvent ev) {
execute("set index=" + EuclideanDistance.NAME + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer().getParentViewer() != null && getViewer().getParentViewer().hasComparableData()
&& getViewer().getParentViewer().getSelectedNodes().size() > 0;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* parses the given command and executes it
*
* @param np
* @throws java.io.IOException
*/
public void apply(NexusStreamParser np) throws Exception {
}
/**
* get command-line usage description
*
* @return usage
*/
public String getSyntax() {
return null;
}
}
| danielhuson/megan-ce | src/megan/clusteranalysis/commands/EcologicalIndexEuclideanCommand.java | Java | gpl-3.0 | 3,496 |
using Hyper.NodeServices.Contracts;
namespace Hyper.NodeServices.Extensibility.EventTracking
{
/// <summary>
/// Event arguments passed to an implementation of <see cref="IHyperNodeEventHandler"/> when the <see cref="IHyperNodeService"/> finishes executing the current task.
/// </summary>
public interface ITaskCompletedEventArgs : IHyperNodeEventArgs
{
/// <summary>
/// The finished response for the current task.
/// </summary>
IReadOnlyHyperNodeResponseInfo ResponseInfo { get; }
}
}
| jheitz1117/Hyper | Hyper.NodeServices.Extensibility/EventTracking/ITaskCompletedEventArgs.cs | C# | gpl-3.0 | 549 |
/*
* Copyright (C) 2014 Institute for Bioinformatics and Systems Biology, University Giessen, Germany
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.cebitec.readxplorer.transcriptionanalyses.wizard;
import de.cebitec.readxplorer.databackend.dataobjects.PersistentTrack;
import de.cebitec.readxplorer.ui.dialogmenus.OpenTracksWizardPanel;
import de.cebitec.readxplorer.ui.dialogmenus.SelectFeatureTypeWizardPanel;
import de.cebitec.readxplorer.ui.dialogmenus.SelectReadClassWizardPanel;
import java.awt.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import javax.swing.JComponent;
import javax.swing.event.ChangeListener;
import org.openide.WizardDescriptor;
import org.openide.WizardDescriptor.Panel;
import org.openide.util.ChangeSupport;
/**
* Wizard page iterator for a transcription analyses wizard.
* <p>
* @author Rolf Hilker <rhilker at cebitec.uni-bielefeld.de>
*/
public final class TranscriptionAnalysesWizardIterator implements
WizardDescriptor.Iterator<WizardDescriptor> {
public static final String PROP_TSS_ANALYSIS = "tssAnalysis";
public static final String PROP_OPERON_ANALYSIS = "Operon";
public static final String PROP_NORM_ANALYSIS = "Normalization";
public static final String PROP_UNANNOTATED_TRANSCRIPT_DET = "unannotatedTranscriptDetection";
public static final String PROP_AUTO_TSS_PARAMS = "automaticsTSSParameterEstimation";
public static final String PROP_AUTO_OPERON_PARAMS = "automaticOperonParameterEstimation";
public static final String PROP_MIN_TOTAL_INCREASE = "minTotalIncrease";
public static final String PROP_MIN_PERCENT_INCREASE = "minTotalPercentIncrease";
public static final String PROP_MAX_LOW_COV_INIT_COUNT = "maxLowCovInitialCount";
public static final String PROP_MIN_LOW_COV_INC = "minLowCovIncrease";
public static final String PROP_MIN_TRANSCRIPT_EXTENSION_COV = "minTranscriptExtensionCov";
public static final String PROP_MAX_LEADERLESS_DISTANCE = "maxLeaderlessDistance";
public static final String PROP_MAX_FEATURE_DISTANCE = "maxFeatureDistance";
public static final String PROP_MIN_NUMBER_READS = "minNumberReads";
public static final String PROP_MAX_NUMBER_READS = "maxNumberReads";
public static final String PROP_USE_EFFECTIVE_LENGTH = "useEffectiveLength";
public static final String PROP_MIN_SPANNING_READS = "minNumberSpanningReads";
public static final String PROP_ANALYSIS_DIRECTION = "analysisDirection";
public static final String PROP_ASSOCIATE_TSS_WINDOW = "associateTssWindow";
public static final String PROP_IS_ASSOCIATE_TSS = "isAssociateTss";
static final String PROP_WIZARD_NAME = "TransAnalyses";
private static final String FINISH_MSG = "Press 'Finish' to start";
private int index;
private final ChangeSupport changeSupport;
private WizardDescriptor wiz;
private String[] steps;
private final int referenceId;
private List<WizardDescriptor.Panel<WizardDescriptor>> allPanels;
private List<WizardDescriptor.Panel<WizardDescriptor>> currentPanels;
private TransAnalysesSelectionWizardPanel selectionPanel = new TransAnalysesSelectionWizardPanel();
private TransAnalysesTSSWizardPanel tSSPanel = new TransAnalysesTSSWizardPanel();
private TransAnalysesOperonWizardPanel operonPanel = new TransAnalysesOperonWizardPanel();
private TransAnalysesNormWizardPanel normalizationPanel = new TransAnalysesNormWizardPanel();
private OpenTracksWizardPanel openTracksPanel;
private SelectReadClassWizardPanel readClassPanel;
private SelectFeatureTypeWizardPanel featTypeNormPanel;
private SelectFeatureTypeWizardPanel featTypeOperonPanel;
private final Map<WizardDescriptor.Panel<WizardDescriptor>, Integer> panelToStepMap = new HashMap<>();
/**
* Wizard page iterator for a transcription analyses wizard. In order to use
* it correctly, the wizard, in which this iterator is used has to be set.
* @param referenceId The id of the current reference
*/
public TranscriptionAnalysesWizardIterator( int referenceId ) {
this.referenceId = referenceId;
this.changeSupport = new ChangeSupport( this );
this.initializePanels();
}
/**
* @return the sequence of all wizard panels of this wizard
*/
private List<WizardDescriptor.Panel<WizardDescriptor>> initializePanels() {
if( allPanels == null ) {
allPanels = new ArrayList<>();
openTracksPanel = new OpenTracksWizardPanel( PROP_WIZARD_NAME, referenceId );
selectionPanel = new TransAnalysesSelectionWizardPanel();
readClassPanel = new SelectReadClassWizardPanel( PROP_WIZARD_NAME, true );
tSSPanel = new TransAnalysesTSSWizardPanel();
operonPanel = new TransAnalysesOperonWizardPanel();
normalizationPanel = new TransAnalysesNormWizardPanel();
featTypeNormPanel = new SelectFeatureTypeWizardPanel( PROP_NORM_ANALYSIS, true );
featTypeOperonPanel = new SelectFeatureTypeWizardPanel( PROP_OPERON_ANALYSIS, false );
featTypeOperonPanel.getComponent().showDisplayName( true );
featTypeNormPanel.getComponent().showDisplayName( true );
allPanels.add( openTracksPanel );
allPanels.add( selectionPanel );
allPanels.add( readClassPanel );
allPanels.add( tSSPanel );
allPanels.add( operonPanel );
allPanels.add( featTypeOperonPanel );
allPanels.add( normalizationPanel );
allPanels.add( featTypeNormPanel );
this.panelToStepMap.put( openTracksPanel, 0 );
this.panelToStepMap.put( selectionPanel, 1 );
this.panelToStepMap.put( readClassPanel, 2 );
this.panelToStepMap.put( tSSPanel, 3 );
this.panelToStepMap.put( operonPanel, 4 );
this.panelToStepMap.put( featTypeOperonPanel, 5 );
this.panelToStepMap.put( normalizationPanel, 6 );
this.panelToStepMap.put( featTypeNormPanel, 7 );
this.steps = new String[allPanels.size() + 1];
for( int i = 0; i < allPanels.size(); i++ ) {
Component c = allPanels.get( i ).getComponent();
// Default step name to component name of panel.
steps[i] = c.getName();
if( c instanceof JComponent ) { // assume Swing components
JComponent jc = (JComponent) c;
jc.putClientProperty( WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, i );
jc.putClientProperty( WizardDescriptor.PROP_AUTO_WIZARD_STYLE, true );
jc.putClientProperty( WizardDescriptor.PROP_CONTENT_DISPLAYED, true );
jc.putClientProperty( WizardDescriptor.PROP_CONTENT_NUMBERED, true );
}
}
steps[steps.length - 1] = FINISH_MSG;
String[] initiallyShownSteps = new String[]{ steps[0], steps[1], "...", steps[steps.length - 1] };
openTracksPanel.getComponent().putClientProperty( WizardDescriptor.PROP_CONTENT_DATA, initiallyShownSteps );
currentPanels = new ArrayList<>();
currentPanels.add( openTracksPanel );
currentPanels.add( selectionPanel );
currentPanels.add( readClassPanel );
}
return allPanels;
}
/**
* @return the current wizard panel
*/
@Override
public WizardDescriptor.Panel<WizardDescriptor> current() {
return currentPanels.get( index );
}
@Override
public String name() {
return index + 1 + ". from " + currentPanels.size();
}
@Override
public boolean hasNext() {
return index < currentPanels.size() - 1;
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public void nextPanel() {
if( index == 1 ) {
this.updatePanelList( selectionPanel.getComponent().isTSSAnalysisSelected(), tSSPanel );
this.updatePanelList( selectionPanel.getComponent().isOperonAnalysisSelected(), operonPanel );
this.updatePanelList( selectionPanel.getComponent().isOperonAnalysisSelected(), featTypeOperonPanel );
this.updatePanelList( selectionPanel.getComponent().isNormAnalysisSelected(), normalizationPanel );
this.updatePanelList( selectionPanel.getComponent().isNormAnalysisSelected(), featTypeNormPanel );
String[] newStepArray = new String[0];
List<String> newSteps = new ArrayList<>();
for( Panel<WizardDescriptor> panel : currentPanels ) {
newSteps.add( this.steps[this.panelToStepMap.get( panel )] );
}
newSteps.add( FINISH_MSG );
wiz.putProperty( WizardDescriptor.PROP_CONTENT_DATA, newSteps.toArray( newStepArray ) );
}
if( !hasNext() ) {
throw new NoSuchElementException();
}
++index;
wiz.putProperty( WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, index );
}
@Override
public void previousPanel() {
if( !hasPrevious() ) {
throw new NoSuchElementException();
}
--index;
wiz.putProperty( WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, index );
}
// If nothing unusual changes in the middle of the wizard, simply:
@Override
public void addChangeListener( ChangeListener l ) {
changeSupport.addChangeListener( l );
}
@Override
public void removeChangeListener( ChangeListener l ) {
changeSupport.removeChangeListener( l );
}
// If something changes dynamically (besides moving between panels), e.g.
// the number of panels changes in response to user input, then use
// ChangeSupport to implement add/removeChangeListener and call fireChange
// when needed
/**
* @param wiz the wizard, in which this wizard iterator is contained. If it
* is not set, no properties can be stored, thus it always has to
* be set.
*/
public void setWiz( WizardDescriptor wiz ) {
this.wiz = wiz;
}
/**
* @return the wizard, in which this wizard iterator is contained.
*/
public WizardDescriptor getWiz() {
return wiz;
}
/**
* Updates the wizard's panel list with the given analysis panel and it's
* steps with the newStep string, if the given analysis is selected and the
* analysis panel is not already contained in the wizard panel list.
* <p>
* @param analysisSelected true, if the analysis is selected, false
* otherwise
* @param analysisPanel the analysis panel to add to the list of panels
*/
private void updatePanelList( boolean analysisSelected, Panel<WizardDescriptor> analysisPanel ) {
if( analysisSelected ) {
if( !currentPanels.contains( analysisPanel ) ) {
currentPanels.add( analysisPanel );
}
} else if( currentPanels.contains( analysisPanel ) ) {
currentPanels.remove( analysisPanel );
}
}
/**
* @return The dynamically generated property name for the read class
* selection for this wizard. Can be used to obtain the
* corresponding read class parameters.
*/
public String getReadClassPropForWiz() {
return readClassPanel.getPropReadClassParams();
}
/**
* @return The property string for the selected feature type list for the
* corresponding read count normalization analysis.
*/
public String getPropSelectedNormFeatTypes() {
return featTypeNormPanel.getPropSelectedFeatTypes();
}
/**
* @return The property string for the feature start offset configured for
* the read count normalization analysis.
*/
public String getPropNormFeatureStartOffset() {
return featTypeNormPanel.getPropFeatureStartOffset();
}
/**
* @return The property string for the feature stop offset configured for
* the read count normalization analysis.
*/
public String getPropNormFeatureStopOffset() {
return featTypeNormPanel.getPropFeatureStopOffset();
}
/**
* @return The property string for the selected feature type list for the
* corresponding operon detection.
*/
public String getPropSelectedOperonFeatTypes() {
return featTypeOperonPanel.getPropSelectedFeatTypes();
}
/**
* @return The dynamically generated property name for the combine tracks
* selection for this wizard. Can be used to obtain the
* corresponding boolean if the tracks shall be combined.
*/
public String getCombineTracksPropForWiz() {
return openTracksPanel.getPropCombineTracks();
}
/**
* @return The list of track selected in this wizard.
*/
public List<PersistentTrack> getSelectedTracks() {
return openTracksPanel.getComponent().getSelectedTracks();
}
}
| rhilker/ReadXplorer | readxplorer-tools-transcriptionanalyses/src/main/java/de/cebitec/readxplorer/transcriptionanalyses/wizard/TranscriptionAnalysesWizardIterator.java | Java | gpl-3.0 | 13,878 |
/*
* 08/06/2004
*
* RSyntaxUtilities.java - Utility methods used by RSyntaxTextArea and its
* views.
*
* This library is distributed under a modified BSD license. See the included
* RSyntaxTextArea.License.txt file for details.
*/
package com.fr.design.gui.syntax.ui.rsyntaxtextarea;
import java.awt.Color;
import java.awt.Container;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Toolkit;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Caret;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.Position;
import javax.swing.text.Segment;
import javax.swing.text.TabExpander;
import javax.swing.text.View;
import com.fr.design.gui.syntax.ui.rsyntaxtextarea.TokenUtils.TokenSubList;
import com.fr.design.gui.syntax.ui.rsyntaxtextarea.folding.FoldManager;
import com.fr.design.gui.syntax.ui.rtextarea.Gutter;
import com.fr.design.gui.syntax.ui.rtextarea.RTextArea;
import com.fr.design.gui.syntax.ui.rtextarea.RTextScrollPane;
/**
* Utility methods used by <code>RSyntaxTextArea</code> and its associated
* classes.
*
* @author Robert Futrell
* @version 0.2
*/
public class RSyntaxUtilities implements SwingConstants {
/**
* Integer constant representing a Windows-variant OS.
*/
public static final int OS_WINDOWS = 1;
/**
* Integer constant representing Mac OS X.
*/
public static final int OS_MAC_OSX = 2;
/**
* Integer constant representing Linux.
*/
public static final int OS_LINUX = 4;
/**
* Integer constant representing an "unknown" OS. 99.99% of the
* time, this means some UNIX variant (AIX, SunOS, etc.).
*/
public static final int OS_OTHER = 8;
/**
* Used for the color of hyperlinks when a LookAndFeel uses light text
* against a dark background.
*/
private static final Color LIGHT_HYPERLINK_FG = new Color(0xd8ffff);
private static final int OS = getOSImpl();
//private static final int DIGIT_MASK = 1;
private static final int LETTER_MASK = 2;
//private static final int WHITESPACE_MASK = 4;
//private static final int UPPER_CASE_MASK = 8;
private static final int HEX_CHARACTER_MASK = 16;
private static final int LETTER_OR_DIGIT_MASK = 32;
private static final int BRACKET_MASK = 64;
private static final int JAVA_OPERATOR_MASK = 128;
/**
* A lookup table used to quickly decide if a 16-bit Java char is a
* US-ASCII letter (A-Z or a-z), a digit, a whitespace char (either space
* (0x0020) or tab (0x0009)), etc. This method should be faster
* than <code>Character.isLetter</code>, <code>Character.isDigit</code>,
* and <code>Character.isWhitespace</code> because we know we are dealing
* with ASCII chars and so don't have to worry about code planes, etc.
*/
private static final int[] dataTable = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, // 0-15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31
4, 128, 0, 0, 0, 128, 128, 0, 64, 64, 128, 128, 0, 128, 0, 128, // 32-47
49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 128, 0, 128, 128, 128, 128, // 48-63
0, 58, 58, 58, 58, 58, 58, 42, 42, 42, 42, 42, 42, 42, 42, 42, // 64-79
42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 64, 0, 64, 128, 0, // 80-95
0, 50, 50, 50, 50, 50, 50, 34, 34, 34, 34, 34, 34, 34, 34, 34, // 96-111
34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 64, 128, 64, 128, 0, // 112-127
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 128-143
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 144-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 176-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 192-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 208-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 224-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // 240-255.
};
/**
* Used in bracket matching methods.
*/
private static Segment charSegment = new Segment();
/**
* Used in token list manipulation methods.
*/
private static final TokenImpl tempToken = new TokenImpl();
/**
* Used internally.
*/
private static final char[] JS_KEYWORD_RETURN = { 'r', 'e', 't', 'u', 'r', 'n' };
/**
* Used internally.
*/
private static final String BRACKETS = "{([})]";
/**
* Returns a string with characters that are special to HTML (such as
* <code><</code>, <code>></code> and <code>&</code>) replaced
* by their HTML escape sequences.
*
* @param s The input string.
* @param newlineReplacement What to replace newline characters with.
* If this is <code>null</code>, they are simply removed.
* @param inPreBlock Whether this HTML will be in within <code>pre</code>
* tags. If this is <code>true</code>, spaces will be kept as-is;
* otherwise, they will be converted to "<code> </code>".
* @return The escaped version of <code>s</code>.
*/
public static final String escapeForHtml(String s,
String newlineReplacement, boolean inPreBlock) {
if (s==null) {
return null;
}
if (newlineReplacement==null) {
newlineReplacement = "";
}
final String tabString = " ";
boolean lastWasSpace = false;
StringBuilder sb = new StringBuilder();
for (int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case ' ':
if (inPreBlock || !lastWasSpace) {
sb.append(' ');
}
else {
sb.append(" ");
}
lastWasSpace = true;
break;
case '\n':
sb.append(newlineReplacement);
lastWasSpace = false;
break;
case '&':
sb.append("&");
lastWasSpace = false;
break;
case '\t':
sb.append(tabString);
lastWasSpace = false;
break;
case '<':
sb.append("<");
lastWasSpace = false;
break;
case '>':
sb.append(">");
lastWasSpace = false;
break;
default:
sb.append(ch);
lastWasSpace = false;
break;
}
}
return sb.toString();
}
/**
* Returns the rendering hints for text that will most accurately reflect
* those of the native windowing system.
*
* @return The rendering hints, or <code>null</code> if they cannot be
* determined.
*/
public static Map<?,?> getDesktopAntiAliasHints() {
return (Map<?,?>)Toolkit.getDefaultToolkit().
getDesktopProperty("awt.font.desktophints");
}
/**
* Returns the color to use for the line underneath a folded region line.
*
* @param textArea The text area.
* @return The color to use.
*/
public static Color getFoldedLineBottomColor(RSyntaxTextArea textArea) {
Color color = Color.gray;
Gutter gutter = RSyntaxUtilities.getGutter(textArea);
if (gutter!=null) {
color = gutter.getFoldIndicatorForeground();
}
return color;
}
/**
* Returns the gutter component of the scroll pane containing a text
* area, if any.
*
* @param textArea The text area.
* @return The gutter, or <code>null</code> if the text area is not in
* an {@link RTextScrollPane}.
* @see RTextScrollPane#getGutter()
*/
public static Gutter getGutter(RTextArea textArea) {
Gutter gutter = null;
Container parent = textArea.getParent();
if (parent instanceof JViewport) {
parent = parent.getParent();
if (parent instanceof RTextScrollPane) {
RTextScrollPane sp = (RTextScrollPane)parent;
gutter = sp.getGutter(); // Should always be non-null
}
}
return gutter;
}
/**
* Returns the color to use for hyperlink-style components. This method
* will return <code>Color.blue</code> unless it appears that the current
* LookAndFeel uses light text on a dark background, in which case a
* brighter alternative is returned.
*
* @return The color to use for hyperlinks.
* @see #isLightForeground(Color)
*/
public static final Color getHyperlinkForeground() {
// This property is defined by all standard LaFs, even Nimbus (!),
// but you never know what crazy LaFs there are...
Color fg = UIManager.getColor("Label.foreground");
if (fg==null) {
fg = new JLabel().getForeground();
}
return isLightForeground(fg) ? LIGHT_HYPERLINK_FG : Color.blue;
}
/**
* Returns the leading whitespace of a string.
*
* @param text The String to check.
* @return The leading whitespace.
* @see #getLeadingWhitespace(Document, int)
*/
public static String getLeadingWhitespace(String text) {
int count = 0;
int len = text.length();
while (count<len && RSyntaxUtilities.isWhitespace(text.charAt(count))) {
count++;
}
return text.substring(0, count);
}
/**
* Returns the leading whitespace of a specific line in a document.
*
* @param doc The document.
* @param offs The offset whose line to get the leading whitespace for.
* @return The leading whitespace.
* @throws BadLocationException If <code>offs</code> is not a valid offset
* in the document.
* @see #getLeadingWhitespace(String)
*/
public static String getLeadingWhitespace(Document doc, int offs)
throws BadLocationException {
Element root = doc.getDefaultRootElement();
int line = root.getElementIndex(offs);
Element elem = root.getElement(line);
int startOffs = elem.getStartOffset();
int endOffs = elem.getEndOffset() - 1;
String text = doc.getText(startOffs, endOffs-startOffs);
return getLeadingWhitespace(text);
}
private static final Element getLineElem(Document d, int offs) {
Element map = d.getDefaultRootElement();
int index = map.getElementIndex(offs);
Element elem = map.getElement(index);
if ((offs>=elem.getStartOffset()) && (offs<elem.getEndOffset())) {
return elem;
}
return null;
}
/**
* Returns the bounding box (in the current view) of a specified position
* in the model. This method is designed for line-wrapped views to use,
* as it allows you to specify a "starting position" in the line, from
* which the x-value is assumed to be zero. The idea is that you specify
* the first character in a physical line as <code>p0</code>, as this is
* the character where the x-pixel value is 0.
*
* @param textArea The text area containing the text.
* @param s A segment in which to load the line. This is passed in so we
* don't have to reallocate a new <code>Segment</code> for each
* call.
* @param p0 The starting position in the physical line in the document.
* @param p1 The position for which to get the bounding box in the view.
* @param e How to expand tabs.
* @param rect The rectangle whose x- and width-values are changed to
* represent the bounding box of <code>p1</code>. This is reused
* to keep from needlessly reallocating Rectangles.
* @param x0 The x-coordinate (pixel) marking the left-hand border of the
* text. This is useful if the text area has a border, for example.
* @return The bounding box in the view of the character <code>p1</code>.
* @throws BadLocationException If <code>p0</code> or <code>p1</code> is
* not a valid location in the specified text area's document.
* @throws IllegalArgumentException If <code>p0</code> and <code>p1</code>
* are not on the same line.
*/
public static Rectangle getLineWidthUpTo(RSyntaxTextArea textArea,
Segment s, int p0, int p1,
TabExpander e, Rectangle rect,
int x0)
throws BadLocationException {
RSyntaxDocument doc = (RSyntaxDocument)textArea.getDocument();
// Ensure p0 and p1 are valid document positions.
if (p0<0)
throw new BadLocationException("Invalid document position", p0);
else if (p1>doc.getLength())
throw new BadLocationException("Invalid document position", p1);
// Ensure p0 and p1 are in the same line, and get the start/end
// offsets for that line.
Element map = doc.getDefaultRootElement();
int lineNum = map.getElementIndex(p0);
// We do ">1" because p1 might be the first position on the next line
// or the last position on the previous one.
// if (lineNum!=map.getElementIndex(p1))
if (Math.abs(lineNum-map.getElementIndex(p1))>1)
throw new IllegalArgumentException("p0 and p1 are not on the " +
"same line (" + p0 + ", " + p1 + ").");
// Get the token list.
Token t = doc.getTokenListForLine(lineNum);
// Modify the token list 't' to begin at p0 (but still have correct
// token types, etc.), and get the x-location (in pixels) of the
// beginning of this new token list.
TokenSubList subList = TokenUtils.getSubTokenList(t, p0, e, textArea,
0, tempToken);
t = subList.tokenList;
rect = t.listOffsetToView(textArea, e, p1, x0, rect);
return rect;
}
/**
* Returns the location of the bracket paired with the one at the current
* caret position.
*
* @param textArea The text area.
* @param input A point to use as the return value. If this is
* <code>null</code>, a new object is created and returned.
* @return A point representing the matched bracket info. The "x" field
* is the offset of the bracket at the caret position (either just
* before or just after the caret), and the "y" field is the offset
* of the matched bracket. Both "x" and "y" will be
* <code>-1</code> if there isn't a matching bracket (or the caret
* isn't on a bracket).
*/
public static Point getMatchingBracketPosition(RSyntaxTextArea textArea,
Point input) {
if (input==null) {
input = new Point();
}
input.setLocation(-1, -1);
try {
// Actually position just BEFORE caret.
int caretPosition = textArea.getCaretPosition() - 1;
RSyntaxDocument doc = (RSyntaxDocument)textArea.getDocument();
char bracket = 0;
// If the caret was at offset 0, we can't check "to its left."
if (caretPosition>=0) {
bracket = doc.charAt(caretPosition);
}
// Try to match a bracket "to the right" of the caret if one
// was not found on the left.
int index = BRACKETS.indexOf(bracket);
if (index==-1 && caretPosition<doc.getLength()-1) {
bracket = doc.charAt(++caretPosition);
}
// First, see if the char was a bracket (one of "{[()]}").
if (index==-1) {
index = BRACKETS.indexOf(bracket);
if (index==-1) {
return input;
}
}
// If it was, then make sure this bracket isn't sitting in
// the middle of a comment or string. If it isn't, then
// initialize some stuff so we can continue on.
char bracketMatch;
boolean goForward;
Element map = doc.getDefaultRootElement();
int curLine = map.getElementIndex(caretPosition);
Element line = map.getElement(curLine);
int start = line.getStartOffset();
int end = line.getEndOffset();
Token token = doc.getTokenListForLine(curLine);
token = RSyntaxUtilities.getTokenAtOffset(token, caretPosition);
// All brackets are always returned as "separators."
if (token.getType()!=Token.SEPARATOR) {
return input;
}
if (index<3) { // One of "{[("
goForward = true;
bracketMatch = BRACKETS.charAt(index + 3);
}
else { // One of ")]}"
goForward = false;
bracketMatch = BRACKETS.charAt(index - 3);
}
if (goForward) {
int lastLine = map.getElementCount();
// Start just after the found bracket since we're sure
// we're not in a comment.
start = caretPosition + 1;
int numEmbedded = 0;
boolean haveTokenList = false;
while (true) {
doc.getText(start,end-start, charSegment);
int segOffset = charSegment.offset;
for (int i=segOffset; i<segOffset+charSegment.count; i++) {
char ch = charSegment.array[i];
if (ch==bracket) {
if (haveTokenList==false) {
token = doc.getTokenListForLine(curLine);
haveTokenList = true;
}
int offset = start + (i-segOffset);
token = RSyntaxUtilities.getTokenAtOffset(token, offset);
if (token.getType()==Token.SEPARATOR)
numEmbedded++;
}
else if (ch==bracketMatch) {
if (haveTokenList==false) {
token = doc.getTokenListForLine(curLine);
haveTokenList = true;
}
int offset = start + (i-segOffset);
token = RSyntaxUtilities.getTokenAtOffset(token, offset);
if (token.getType()==Token.SEPARATOR) {
if (numEmbedded==0) {
if (textArea.isCodeFoldingEnabled() &&
textArea.getFoldManager().isLineHidden(curLine)) {
return input; // Match hidden in a fold
}
input.setLocation(caretPosition, offset);
return input;
}
numEmbedded--;
}
}
} // End of for (int i=segOffset; i<segOffset+charSegment.count; i++).
// Bail out if we've gone through all lines and
// haven't found the match.
if (++curLine==lastLine)
return input;
// Otherwise, go through the next line.
haveTokenList = false;
line = map.getElement(curLine);
start = line.getStartOffset();
end = line.getEndOffset();
} // End of while (true).
} // End of if (goForward).
// Otherwise, we're going backward through the file
// (since we found '}', ')' or ']').
else { // goForward==false
// End just before the found bracket since we're sure
// we're not in a comment.
end = caretPosition;// - 1;
int numEmbedded = 0;
boolean haveTokenList = false;
Token t2;
while (true) {
doc.getText(start,end-start, charSegment);
int segOffset = charSegment.offset;
int iStart = segOffset + charSegment.count - 1;
for (int i=iStart; i>=segOffset; i--) {
char ch = charSegment.array[i];
if (ch==bracket) {
if (haveTokenList==false) {
token = doc.getTokenListForLine(curLine);
haveTokenList = true;
}
int offset = start + (i-segOffset);
t2 = RSyntaxUtilities.getTokenAtOffset(token, offset);
if (t2.getType()==Token.SEPARATOR)
numEmbedded++;
}
else if (ch==bracketMatch) {
if (haveTokenList==false) {
token = doc.getTokenListForLine(curLine);
haveTokenList = true;
}
int offset = start + (i-segOffset);
t2 = RSyntaxUtilities.getTokenAtOffset(token, offset);
if (t2.getType()==Token.SEPARATOR) {
if (numEmbedded==0) {
input.setLocation(caretPosition, offset);
return input;
}
numEmbedded--;
}
}
}
// Bail out if we've gone through all lines and
// haven't found the match.
if (--curLine==-1) {
return input;
}
// Otherwise, get ready for going through the
// next line.
haveTokenList = false;
line = map.getElement(curLine);
start = line.getStartOffset();
end = line.getEndOffset();
} // End of while (true).
} // End of else.
} catch (BadLocationException ble) {
// Shouldn't ever happen.
ble.printStackTrace();
}
// Something went wrong...
return input;
}
/**
* Returns the next non-whitespace, non-comment token in a text area.
*
* @param t The next token in this line's token list.
* @param textArea The text area.
* @param line The current line index (the line index of <code>t</code>).
* @return The next non-whitespace, non-comment token, or <code>null</code>
* if there isn't one.
* @see #getPreviousImportantToken(RSyntaxTextArea, int)
*/
public static final Token getNextImportantToken(Token t,
RSyntaxTextArea textArea, int line) {
while (t!=null && t.isPaintable() && t.isCommentOrWhitespace()) {
t = t.getNextToken();
}
if ((t==null || !t.isPaintable()) && line<textArea.getLineCount()-1) {
t = textArea.getTokenListForLine(++line);
return getNextImportantToken(t, textArea, line);
}
return t;
}
/**
* Provides a way to determine the next visually represented model
* location at which one might place a caret.
* Some views may not be visible,
* they might not be in the same order found in the model, or they just
* might not allow access to some of the locations in the model.<p>
*
* NOTE: You should only call this method if the passed-in
* <code>javax.swing.text.View</code> is an instance of
* {@link TokenOrientedView} and <code>javax.swing.text.TabExpander</code>;
* otherwise, a <code>ClassCastException</code> could be thrown.
*
* @param pos the position to convert >= 0
* @param a the allocated region in which to render
* @param direction the direction from the current position that can
* be thought of as the arrow keys typically found on a keyboard.
* This will be one of the following values:
* <ul>
* <li>SwingConstants.WEST
* <li>SwingConstants.EAST
* <li>SwingConstants.NORTH
* <li>SwingConstants.SOUTH
* </ul>
* @return the location within the model that best represents the next
* location visual position
* @exception BadLocationException
* @exception IllegalArgumentException if <code>direction</code>
* doesn't have one of the legal values above
*/
public static int getNextVisualPositionFrom(int pos, Position.Bias b,
Shape a, int direction,
Position.Bias[] biasRet, View view)
throws BadLocationException {
RSyntaxTextArea target = (RSyntaxTextArea)view.getContainer();
biasRet[0] = Position.Bias.Forward;
// Do we want the "next position" above, below, to the left or right?
switch (direction) {
case NORTH:
case SOUTH:
if (pos == -1) {
pos = (direction == NORTH) ?
Math.max(0, view.getEndOffset() - 1) :
view.getStartOffset();
break;
}
Caret c = (target != null) ? target.getCaret() : null;
// YECK! Ideally, the x location from the magic caret
// position would be passed in.
Point mcp;
if (c != null)
mcp = c.getMagicCaretPosition();
else
mcp = null;
int x;
if (mcp == null) {
Rectangle loc = target.modelToView(pos);
x = (loc == null) ? 0 : loc.x;
}
else {
x = mcp.x;
}
if (direction == NORTH)
pos = getPositionAbove(target,pos,x,(TabExpander)view);
else
pos = getPositionBelow(target,pos,x,(TabExpander)view);
break;
case WEST:
if(pos == -1) {
pos = Math.max(0, view.getEndOffset() - 1);
}
else {
pos = Math.max(0, pos - 1);
if (target.isCodeFoldingEnabled()) {
int last = target.getLineOfOffset(pos+1);
int current = target.getLineOfOffset(pos);
if (last!=current) { // If moving up a line...
FoldManager fm = target.getFoldManager();
if (fm.isLineHidden(current)) {
while (--current>0 && fm.isLineHidden(current));
pos = target.getLineEndOffset(current) - 1;
}
}
}
}
break;
case EAST:
if(pos == -1) {
pos = view.getStartOffset();
}
else {
pos = Math.min(pos + 1, view.getDocument().getLength());
if (target.isCodeFoldingEnabled()) {
int last = target.getLineOfOffset(pos-1);
int current = target.getLineOfOffset(pos);
if (last!=current) { // If moving down a line...
FoldManager fm = target.getFoldManager();
if (fm.isLineHidden(current)) {
int lineCount = target.getLineCount();
while (++current<lineCount && fm.isLineHidden(current));
pos = current==lineCount ?
target.getLineEndOffset(last)-1 : // Was the last visible line
target.getLineStartOffset(current);
}
}
}
}
break;
default:
throw new IllegalArgumentException(
"Bad direction: " + direction);
}
return pos;
}
/**
* Determines the position in the model that is closest to the given
* view location in the row above. The component given must have a
* size to compute the result. If the component doesn't have a size
* a value of -1 will be returned.
*
* @param c the editor
* @param offs the offset in the document >= 0
* @param x the X coordinate >= 0
* @return the position >= 0 if the request can be computed, otherwise
* a value of -1 will be returned.
* @exception BadLocationException if the offset is out of range
*/
public static final int getPositionAbove(RSyntaxTextArea c, int offs,
float x, TabExpander e) throws BadLocationException {
TokenOrientedView tov = (TokenOrientedView)e;
Token token = tov.getTokenListForPhysicalLineAbove(offs);
if (token==null)
return -1;
// A line containing only Token.NULL is an empty line.
else if (token.getType()==Token.NULL) {
int line = c.getLineOfOffset(offs); // Sure to be >0 ??
return c.getLineStartOffset(line-1);
}
else {
return token.getListOffset(c, e, 0, x);
}
}
/**
* Determines the position in the model that is closest to the given
* view location in the row below. The component given must have a
* size to compute the result. If the component doesn't have a size
* a value of -1 will be returned.
*
* @param c the editor
* @param offs the offset in the document >= 0
* @param x the X coordinate >= 0
* @return the position >= 0 if the request can be computed, otherwise
* a value of -1 will be returned.
* @exception BadLocationException if the offset is out of range
*/
public static final int getPositionBelow(RSyntaxTextArea c, int offs,
float x, TabExpander e) throws BadLocationException {
TokenOrientedView tov = (TokenOrientedView)e;
Token token = tov.getTokenListForPhysicalLineBelow(offs);
if (token==null)
return -1;
// A line containing only Token.NULL is an empty line.
else if (token.getType()==Token.NULL) {
int line = c.getLineOfOffset(offs); // Sure to be > c.getLineCount()-1 ??
// return c.getLineStartOffset(line+1);
FoldManager fm = c.getFoldManager();
line = fm.getVisibleLineBelow(line);
return c.getLineStartOffset(line);
}
else {
return token.getListOffset(c, e, 0, x);
}
}
/**
* Returns the last non-whitespace, non-comment token, starting with the
* specified line.
*
* @param textArea The text area.
* @param line The line at which to start looking.
* @return The last non-whitespace, non-comment token, or <code>null</code>
* if there isn't one.
* @see #getNextImportantToken(Token, RSyntaxTextArea, int)
*/
public static final Token getPreviousImportantToken(
RSyntaxTextArea textArea, int line){
if (line<0) {
return null;
}
Token t = textArea.getTokenListForLine(line);
if (t!=null) {
t = t.getLastNonCommentNonWhitespaceToken();
if (t!=null) {
return t;
}
}
return getPreviousImportantToken(textArea, line-1);
}
/**
* Returns the token at the specified index, or <code>null</code> if
* the given offset isn't in this token list's range.<br>
* Note that this method does NOT check to see if <code>tokenList</code>
* is null; callers should check for themselves.
*
* @param tokenList The list of tokens in which to search.
* @param offset The offset at which to get the token.
* @return The token at <code>offset</code>, or <code>null</code> if
* none of the tokens are at that offset.
*/
public static final Token getTokenAtOffset(Token tokenList, int offset) {
for (Token t=tokenList; t!=null && t.isPaintable(); t=t.getNextToken()){
if (t.containsPosition(offset))
return t;
}
return null;
}
/**
* Returns the end of the word at the given offset.
*
* @param textArea The text area.
* @param offs The offset into the text area's content.
* @return The end offset of the word.
* @throws BadLocationException If <code>offs</code> is invalid.
* @see #getWordStart(RSyntaxTextArea, int)
*/
public static int getWordEnd(RSyntaxTextArea textArea, int offs)
throws BadLocationException {
Document doc = textArea.getDocument();
int endOffs = textArea.getLineEndOffsetOfCurrentLine();
int lineEnd = Math.min(endOffs, doc.getLength());
if (offs == lineEnd) { // End of the line.
return offs;
}
String s = doc.getText(offs, lineEnd-offs-1);
if (s!=null && s.length()>0) { // Should always be true
int i = 0;
int count = s.length();
char ch = s.charAt(i);
if (Character.isWhitespace(ch)) {
while (i<count && Character.isWhitespace(s.charAt(i++)));
}
else if (Character.isLetterOrDigit(ch)) {
while (i<count && Character.isLetterOrDigit(s.charAt(i++)));
}
else {
i = 2;
}
offs += i - 1;
}
return offs;
}
/**
* Returns the start of the word at the given offset.
*
* @param textArea The text area.
* @param offs The offset into the text area's content.
* @return The start offset of the word.
* @throws BadLocationException If <code>offs</code> is invalid.
* @see #getWordEnd(RSyntaxTextArea, int)
*/
public static int getWordStart(RSyntaxTextArea textArea, int offs)
throws BadLocationException {
Document doc = textArea.getDocument();
Element line = getLineElem(doc, offs);
if (line == null) {
throw new BadLocationException("No word at " + offs, offs);
}
int lineStart = line.getStartOffset();
if (offs==lineStart) { // Start of the line.
return offs;
}
int endOffs = Math.min(offs+1, doc.getLength());
String s = doc.getText(lineStart, endOffs-lineStart);
if(s != null && s.length() > 0) {
int i = s.length() - 1;
char ch = s.charAt(i);
if (Character.isWhitespace(ch)) {
while (i>0 && Character.isWhitespace(s.charAt(i-1))) {
i--;
}
offs = lineStart + i;
}
else if (Character.isLetterOrDigit(ch)) {
while (i>0 && Character.isLetterOrDigit(s.charAt(i-1))) {
i--;
}
offs = lineStart + i;
}
}
return offs;
}
/**
* Determines the width of the given token list taking tabs
* into consideration. This is implemented in a 1.1 style coordinate
* system where ints are used and 72dpi is assumed.<p>
*
* This method also assumes that the passed-in token list begins at
* x-pixel <code>0</code> in the view (for tab purposes).
*
* @param tokenList The tokenList list representing the text.
* @param textArea The text area in which this token list resides.
* @param e The tab expander. This value cannot be <code>null</code>.
* @return The width of the token list, in pixels.
*/
public static final float getTokenListWidth(Token tokenList,
RSyntaxTextArea textArea,
TabExpander e) {
return getTokenListWidth(tokenList, textArea, e, 0);
}
/**
* Determines the width of the given token list taking tabs
* into consideration. This is implemented in a 1.1 style coordinate
* system where ints are used and 72dpi is assumed.<p>
*
* @param tokenList The token list list representing the text.
* @param textArea The text area in which this token list resides.
* @param e The tab expander. This value cannot be <code>null</code>.
* @param x0 The x-pixel coordinate of the start of the token list.
* @return The width of the token list, in pixels.
* @see #getTokenListWidthUpTo
*/
public static final float getTokenListWidth(final Token tokenList,
RSyntaxTextArea textArea,
TabExpander e, float x0) {
float width = x0;
for (Token t=tokenList; t!=null&&t.isPaintable(); t=t.getNextToken()) {
width += t.getWidth(textArea, e, width);
}
return width - x0;
}
/**
* Determines the width of the given token list taking tabs into
* consideration and only up to the given index in the document
* (exclusive).
*
* @param tokenList The token list representing the text.
* @param textArea The text area in which this token list resides.
* @param e The tab expander. This value cannot be <code>null</code>.
* @param x0 The x-pixel coordinate of the start of the token list.
* @param upTo The document position at which you want to stop,
* exclusive. If this position is before the starting position
* of the token list, a width of <code>0</code> will be
* returned; similarly, if this position comes after the entire
* token list, the width of the entire token list is returned.
* @return The width of the token list, in pixels, up to, but not
* including, the character at position <code>upTo</code>.
* @see #getTokenListWidth
*/
public static final float getTokenListWidthUpTo(final Token tokenList,
RSyntaxTextArea textArea, TabExpander e,
float x0, int upTo) {
float width = 0;
for (Token t=tokenList; t!=null&&t.isPaintable(); t=t.getNextToken()) {
if (t.containsPosition(upTo)) {
return width + t.getWidthUpTo(upTo-t.getOffset(), textArea, e,
x0+width);
}
width += t.getWidth(textArea, e, x0+width);
}
return width;
}
/**
* Returns whether or not this character is a "bracket" to be matched by
* such programming languages as C, C++, and Java.
*
* @param ch The character to check.
* @return Whether or not the character is a "bracket" - one of '(', ')',
* '[', ']', '{', and '}'.
*/
public static final boolean isBracket(char ch) {
// We need the first condition as it might be that ch>255, and thus
// not in our table. '}' is the highest-valued char in the bracket
// set.
return ch<='}' && (dataTable[ch]&BRACKET_MASK)>0;
}
/**
* Returns whether or not a character is a digit (0-9).
*
* @param ch The character to check.
* @return Whether or not the character is a digit.
*/
public static final boolean isDigit(char ch) {
// We do it this way as we'd need to do two conditions anyway (first
// to check that ch<255 so it can index into our table, then whether
// that table position has the digit mask).
return ch>='0' && ch<='9';
}
/**
* Returns whether or not this character is a hex character. This method
* accepts both upper- and lower-case letters a-f.
*
* @param ch The character to check.
* @return Whether or not the character is a hex character 0-9, a-f, or
* A-F.
*/
public static final boolean isHexCharacter(char ch) {
// We need the first condition as it could be that ch>255 (and thus
// not a valid index into our table). 'f' is the highest-valued
// char that is a valid hex character.
return (ch<='f') && (dataTable[ch]&HEX_CHARACTER_MASK)>0;
}
/**
* Returns whether a character is a Java operator. Note that C and C++
* operators are the same as Java operators.
*
* @param ch The character to check.
* @return Whether or not the character is a Java operator.
*/
public static final boolean isJavaOperator(char ch) {
// We need the first condition as it could be that ch>255 (and thus
// not a valid index into our table). '~' is the highest-valued
// char that is a valid Java operator.
return (ch<='~') && (dataTable[ch]&JAVA_OPERATOR_MASK)>0;
}
/**
* Returns whether a character is a US-ASCII letter (A-Z or a-z).
*
* @param ch The character to check.
* @return Whether or not the character is a US-ASCII letter.
*/
public static final boolean isLetter(char ch) {
// We need the first condition as it could be that ch>255 (and thus
// not a valid index into our table).
return (ch<='z') && (dataTable[ch]&LETTER_MASK)>0;
}
/**
* Returns whether or not a character is a US-ASCII letter or a digit.
*
* @param ch The character to check.
* @return Whether or not the character is a US-ASCII letter or a digit.
*/
public static final boolean isLetterOrDigit(char ch) {
// We need the first condition as it could be that ch>255 (and thus
// not a valid index into our table).
return (ch<='z') && (dataTable[ch]&LETTER_OR_DIGIT_MASK)>0;
}
/**
* Returns whether the specified color is "light" to use as a foreground.
* Colors that return <code>true</code> indicate that the current Look and
* Feel probably uses light text colors on a dark background.
*
* @param fg The foreground color.
* @return Whether it is a "light" foreground color.
* @see #getHyperlinkForeground()
*/
public static final boolean isLightForeground(Color fg) {
return fg.getRed()>0xa0 && fg.getGreen()>0xa0 && fg.getBlue()>0xa0;
}
/**
* Returns whether or not a character is a whitespace character (either
* a space ' ' or tab '\t'). This checks for the Unicode character values
* 0x0020 and 0x0009.
*
* @param ch The character to check.
* @return Whether or not the character is a whitespace character.
*/
public static final boolean isWhitespace(char ch) {
// We do it this way as we'd need to do two conditions anyway (first
// to check that ch<255 so it can index into our table, then whether
// that table position has the whitespace mask).
return ch==' ' || ch=='\t';
}
/**
* Returns whether a regular expression token can follow the specified
* token in JavaScript.
*
* @param t The token to check, which may be <code>null</code>.
* @return Whether a regular expression token may follow this one in
* JavaScript.
*/
public static boolean regexCanFollowInJavaScript(Token t) {
char ch;
// We basically try to mimic Eclipse's JS editor's behavior here.
return t==null ||
//t.isOperator() ||
(t.length()==1 && (
(ch=t.charAt(0))=='=' ||
ch=='(' ||
ch==',' ||
ch=='?' ||
ch==':' ||
ch=='[' ||
ch=='!' ||
ch=='&'
)) ||
/* Operators "==", "===", "!=", "!==" */
(t.getType()==Token.OPERATOR &&
t.charAt(t.length()-1)=='=') ||
t.is(Token.RESERVED_WORD_2, JS_KEYWORD_RETURN);
}
/**
* If the character is an upper-case US-ASCII letter, it returns the
* lower-case version of that letter; otherwise, it just returns the
* character.
*
* @param ch The character to lower-case (if it is a US-ASCII upper-case
* character).
* @return The lower-case version of the character.
*/
public static final char toLowerCase(char ch) {
// We can logical OR with 32 because A-Z are 65-90 in the ASCII table
// and none of them have the 6th bit (32) set, and a-z are 97-122 in
// the ASCII table, which is 32 over from A-Z.
// We do it this way as we'd need to do two conditions anyway (first
// to check that ch<255 so it can index into our table, then whether
// that table position has the upper-case mask).
if (ch>='A' && ch<='Z')
return (char)(ch | 0x20);
return ch;
}
/**
* Returns an integer constant representing the OS. This can be handy for
* special case situations such as Mac OS-X (special application
* registration) or Windows (allow mixed case, etc.).
*
* @return An integer constant representing the OS.
*/
public static final int getOS() {
return OS;
}
/**
* Returns an integer constant representing the OS. This can be handy for
* special case situations such as Mac OS-X (special application
* registration) or Windows (allow mixed case, etc.).
*
* @return An integer constant representing the OS.
*/
private static final int getOSImpl() {
int os = OS_OTHER;
String osName = System.getProperty("os.name");
if (osName!=null) { // Should always be true.
osName = osName.toLowerCase();
if (osName.indexOf("windows") > -1)
os = OS_WINDOWS;
else if (osName.indexOf("mac os x") > -1)
os = OS_MAC_OSX;
else if (osName.indexOf("linux") > -1)
os = OS_LINUX;
else
os = OS_OTHER;
}
return os;
}
/**
* Creates a regular expression pattern that matches a "wildcard" pattern.
*
* @param wildcard The wildcard pattern.
* @param matchCase Whether the pattern should be case sensitive.
* @param escapeStartChar Whether to escape a starting <code>'^'</code>
* character.
* @return The pattern.
*/
public static Pattern wildcardToPattern(String wildcard, boolean matchCase,
boolean escapeStartChar) {
int flags = 0;
if (!matchCase) {
flags = Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE;
}
StringBuilder sb = new StringBuilder();
for (int i=0; i<wildcard.length(); i++) {
char ch = wildcard.charAt(i);
switch (ch) {
case '*':
sb.append(".*");
break;
case '?':
sb.append('.');
break;
case '^':
if (i>0 || escapeStartChar) {
sb.append('\\');
}
sb.append('^');
break;
case '\\':
case '.': case '|':
case '+': case '-':
case '$':
case '[': case ']':
case '{': case '}':
case '(': case ')':
sb.append('\\').append(ch);
break;
default:
sb.append(ch);
break;
}
}
Pattern p = null;
try {
p = Pattern.compile(sb.toString(), flags);
} catch (PatternSyntaxException pse) {
pse.printStackTrace();
p = Pattern.compile(".+");
}
return p;
}
} | fanruan/finereport-design | designer_base/src/com/fr/design/gui/syntax/ui/rsyntaxtextarea/RSyntaxUtilities.java | Java | gpl-3.0 | 42,360 |
#include "utf8.hpp"
#include "utf8/utf8.h"
#include <cstring>
namespace core
{
UTF8String::UTF8String()
{}
UTF8String::UTF8String(const UTF8String& cp)
: m_src(cp.m_src)
{}
UTF8String::UTF8String(const std::string& src)
: m_src(src)
{}
UTF8String::~UTF8String()
{
}
size_t UTF8String::size() const
{
utf8::iterator<std::string::const_iterator> it(m_src.cbegin(), m_src.cbegin(), m_src.cend());
utf8::iterator<std::string::const_iterator> end(m_src.cend(), m_src.cbegin(), m_src.cend());
size_t count = 0;
while(it != end) {
++count;
++it;
}
return count;
}
void UTF8String::clear()
{
m_src.clear();
}
bool UTF8String::empty() const
{
return m_src.empty();
}
bool UTF8String::valid() const
{
return utf8::is_valid(m_src.begin(), m_src.end());
}
void UTF8String::removeErrors()
{
std::string temp;
utf8::replace_invalid(m_src.begin(), m_src.end(), std::back_inserter(temp));
m_src = temp;
}
UTF8String& UTF8String::operator=(const UTF8String& cp)
{
m_src = cp.m_src;
return *this;
}
std::string UTF8String::getSrc() const
{
return m_src;
}
UTF8String::operator std::string() const
{
return getSrc();
}
unsigned int UTF8String::operator[](size_t idx) const
{
utf8::iterator<std::string::const_iterator> it(m_src.cbegin(), m_src.cbegin(), m_src.cend());
for(size_t i = 0; i < idx; ++i)
++it;
return *it;
}
bool operator==(const UTF8String& s1, const UTF8String& s2)
{
return s1.getSrc() == s2.getSrc();
}
std::ostream& operator<<(std::ostream& os, const UTF8String& str)
{
os << str.getSrc();
return os;
}
}
| DWARVES/Project-Warrior | src/core/utf8.cpp | C++ | gpl-3.0 | 1,932 |
<?php
/**
* \file T_Courses.php
* \brief Associates an \e integer constant to each type of courses.
*/
error_reporting(E_ALL);
if (0 > version_compare(PHP_VERSION, '5'))
{
die('This file was written for PHP 5');
}
define("CM", 0);
define("TD", 1);
define("TP", 2);
define("CONFERENCE", 3);
define("EXAMEN", 4);
define("RATTRAPAGE", 5);
?>
| VeryTastyTomato/GaliDAV | types/T_Courses.php | PHP | gpl-3.0 | 345 |
/*
Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments
Copyright (C) ITsysCOM GmbH
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT MetaAny WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package engine
import (
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/cgrates/cgrates/config"
"github.com/cgrates/cgrates/utils"
)
// Can hold different units as seconds or monetary
type Balance struct {
Uuid string //system wide unique
ID string // account wide unique
Value float64
ExpirationDate time.Time
Weight float64
DestinationIDs utils.StringMap
RatingSubject string
Categories utils.StringMap
SharedGroups utils.StringMap
Timings []*RITiming
TimingIDs utils.StringMap
Disabled bool
Factor ValueFactor
Blocker bool
precision int
account *Account // used to store ub reference for shared balances
dirty bool
}
func (b *Balance) Equal(o *Balance) bool {
if len(b.DestinationIDs) == 0 {
b.DestinationIDs = utils.StringMap{utils.MetaAny: true}
}
if len(o.DestinationIDs) == 0 {
o.DestinationIDs = utils.StringMap{utils.MetaAny: true}
}
return b.Uuid == o.Uuid &&
b.ID == o.ID &&
b.ExpirationDate.Equal(o.ExpirationDate) &&
b.Weight == o.Weight &&
b.DestinationIDs.Equal(o.DestinationIDs) &&
b.RatingSubject == o.RatingSubject &&
b.Categories.Equal(o.Categories) &&
b.SharedGroups.Equal(o.SharedGroups) &&
b.Disabled == o.Disabled &&
b.Blocker == o.Blocker
}
func (b *Balance) MatchFilter(o *BalanceFilter, skipIds, skipExpiry bool) bool {
if o == nil {
return true
}
if !skipIds && o.Uuid != nil && *o.Uuid != "" {
return b.Uuid == *o.Uuid
}
if !skipIds && o.ID != nil && *o.ID != "" {
return b.ID == *o.ID
}
if !skipExpiry {
if o.ExpirationDate != nil && !b.ExpirationDate.Equal(*o.ExpirationDate) {
return false
}
}
return (o.Weight == nil || b.Weight == *o.Weight) &&
(o.Blocker == nil || b.Blocker == *o.Blocker) &&
(o.Disabled == nil || b.Disabled == *o.Disabled) &&
(o.DestinationIDs == nil || b.DestinationIDs.Includes(*o.DestinationIDs)) &&
(o.Categories == nil || b.Categories.Includes(*o.Categories)) &&
(o.TimingIDs == nil || b.TimingIDs.Includes(*o.TimingIDs)) &&
(o.SharedGroups == nil || b.SharedGroups.Includes(*o.SharedGroups)) &&
(o.RatingSubject == nil || b.RatingSubject == *o.RatingSubject)
}
func (b *Balance) HardMatchFilter(o *BalanceFilter, skipIds bool) bool {
if o == nil {
return true
}
if !skipIds && o.Uuid != nil && *o.Uuid != "" {
return b.Uuid == *o.Uuid
}
if !skipIds && o.ID != nil && *o.ID != "" {
return b.ID == *o.ID
}
return (o.ExpirationDate == nil || b.ExpirationDate.Equal(*o.ExpirationDate)) &&
(o.Weight == nil || b.Weight == *o.Weight) &&
(o.Blocker == nil || b.Blocker == *o.Blocker) &&
(o.Disabled == nil || b.Disabled == *o.Disabled) &&
(o.DestinationIDs == nil || b.DestinationIDs.Equal(*o.DestinationIDs)) &&
(o.Categories == nil || b.Categories.Equal(*o.Categories)) &&
(o.TimingIDs == nil || b.TimingIDs.Equal(*o.TimingIDs)) &&
(o.SharedGroups == nil || b.SharedGroups.Equal(*o.SharedGroups)) &&
(o.RatingSubject == nil || b.RatingSubject == *o.RatingSubject)
}
// the default balance has standard Id
func (b *Balance) IsDefault() bool {
return b.ID == utils.MetaDefault
}
// IsExpiredAt check if ExpirationDate is before time t
func (b *Balance) IsExpiredAt(t time.Time) bool {
return !b.ExpirationDate.IsZero() && b.ExpirationDate.Before(t)
}
func (b *Balance) IsActive() bool {
return b.IsActiveAt(time.Now())
}
func (b *Balance) IsActiveAt(t time.Time) bool {
if b.Disabled {
return false
}
if len(b.Timings) == 0 {
return true
}
for _, tim := range b.Timings {
if tim.IsActiveAt(t) {
return true
}
}
return false
}
func (b *Balance) MatchCategory(category string) bool {
return len(b.Categories) == 0 || b.Categories[category] == true
}
func (b *Balance) HasDestination() bool {
return len(b.DestinationIDs) > 0 && b.DestinationIDs[utils.MetaAny] == false
}
func (b *Balance) MatchDestination(destinationID string) bool {
return !b.HasDestination() || b.DestinationIDs[destinationID] == true
}
func (b *Balance) MatchActionTrigger(at *ActionTrigger) bool {
return b.HardMatchFilter(at.Balance, false)
}
func (b *Balance) Clone() *Balance {
if b == nil {
return nil
}
n := &Balance{
Uuid: b.Uuid,
ID: b.ID,
Value: b.Value, // this value is in seconds
ExpirationDate: b.ExpirationDate,
Weight: b.Weight,
RatingSubject: b.RatingSubject,
Categories: b.Categories,
SharedGroups: b.SharedGroups,
TimingIDs: b.TimingIDs,
Timings: b.Timings, // should not be a problem with aliasing
Blocker: b.Blocker,
Disabled: b.Disabled,
dirty: b.dirty,
}
if b.DestinationIDs != nil {
n.DestinationIDs = b.DestinationIDs.Clone()
}
return n
}
func (b *Balance) getMatchingPrefixAndDestID(dest string) (prefix, destID string) {
if len(b.DestinationIDs) != 0 && b.DestinationIDs[utils.MetaAny] == false {
for _, p := range utils.SplitPrefix(dest, MIN_PREFIX_MATCH) {
if destIDs, err := dm.GetReverseDestination(p, true, true, utils.NonTransactional); err == nil {
for _, dID := range destIDs {
if b.DestinationIDs[dID] == true {
return p, dID
}
}
}
}
}
return
}
// Returns the available number of seconds for a specified credit
func (b *Balance) GetMinutesForCredit(origCD *CallDescriptor, initialCredit float64) (duration time.Duration, credit float64) {
cd := origCD.Clone()
availableDuration := time.Duration(b.GetValue()) * time.Second
duration = availableDuration
credit = initialCredit
cc, err := b.GetCost(cd, false)
if err != nil {
utils.Logger.Err(fmt.Sprintf("Error getting new cost for balance subject: %v", err))
return 0, credit
}
if cc.deductConnectFee {
connectFee := cc.GetConnectFee()
if connectFee <= credit {
credit -= connectFee
// remove connect fee from the total cost
cc.Cost -= connectFee
} else {
return 0, credit
}
}
if cc.Cost > 0 {
duration = 0
for _, ts := range cc.Timespans {
ts.createIncrementsSlice()
if cd.MaxRate > 0 && cd.MaxRateUnit > 0 {
rate, _, rateUnit := ts.RateInterval.GetRateParameters(ts.GetGroupStart())
if rate/float64(rateUnit.Nanoseconds()) > cd.MaxRate/float64(cd.MaxRateUnit.Nanoseconds()) {
return
}
}
for _, incr := range ts.Increments {
if incr.Cost <= credit && availableDuration-incr.Duration >= 0 {
credit -= incr.Cost
duration += incr.Duration
availableDuration -= incr.Duration
} else {
return
}
}
}
}
return
}
// Gets the cost using balance RatingSubject if present otherwize
// retuns a callcost obtained using standard rating
func (b *Balance) GetCost(cd *CallDescriptor, getStandardIfEmpty bool) (*CallCost, error) {
// testing only
if cd.testCallcost != nil {
return cd.testCallcost, nil
}
if b.RatingSubject != "" && !strings.HasPrefix(b.RatingSubject, utils.MetaRatingSubjectPrefix) {
origSubject := cd.Subject
cd.Subject = b.RatingSubject
origAccount := cd.Account
cd.Account = cd.Subject
cd.RatingInfos = nil
cc, err := cd.getCost()
// restor orig values
cd.Subject = origSubject
cd.Account = origAccount
return cc, err
}
if getStandardIfEmpty {
cd.RatingInfos = nil
return cd.getCost()
} else {
cc := cd.CreateCallCost()
cc.Cost = 0
return cc, nil
}
}
func (b *Balance) GetValue() float64 {
return b.Value
}
func (b *Balance) AddValue(amount float64) {
b.SetValue(b.GetValue() + amount)
}
func (b *Balance) SubstractValue(amount float64) {
b.SetValue(b.GetValue() - amount)
}
func (b *Balance) SetValue(amount float64) {
b.Value = amount
b.Value = utils.Round(b.GetValue(), globalRoundingDecimals, utils.MetaRoundingMiddle)
b.dirty = true
}
func (b *Balance) SetDirty() {
b.dirty = true
}
// debitUnits will debit units for call descriptor.
// returns the amount debited within cc
func (b *Balance) debitUnits(cd *CallDescriptor, ub *Account, moneyBalances Balances, count bool, dryRun, debitConnectFee bool) (cc *CallCost, err error) {
if !b.IsActiveAt(cd.TimeStart) || b.GetValue() <= 0 {
return
}
if duration, err := utils.ParseZeroRatingSubject(cd.ToR, b.RatingSubject, config.CgrConfig().RalsCfg().BalanceRatingSubject); err == nil {
// we have *zero based units
cc = cd.CreateCallCost()
cc.Timespans = append(cc.Timespans, &TimeSpan{
TimeStart: cd.TimeStart,
TimeEnd: cd.TimeEnd,
})
ts := cc.Timespans[0]
ts.RoundToDuration(duration)
ts.RateInterval = &RateInterval{
Rating: &RIRate{
Rates: RateGroups{
&RGRate{
GroupIntervalStart: 0,
Value: 0,
RateIncrement: duration,
RateUnit: duration,
},
},
},
}
prefix, destid := b.getMatchingPrefixAndDestID(cd.Destination)
if prefix == "" {
prefix = cd.Destination
}
if destid == "" {
destid = utils.MetaAny
}
ts.setRatingInfo(&RatingInfo{
MatchedSubject: b.Uuid,
MatchedPrefix: prefix,
MatchedDestId: destid,
RatingPlanId: utils.MetaNone,
})
ts.createIncrementsSlice()
//log.Printf("CC: %+v", ts)
for incIndex, inc := range ts.Increments {
//log.Printf("INCREMENET: %+v", inc)
amount := float64(inc.Duration.Nanoseconds())
if b.Factor != nil {
amount = utils.Round(amount/b.Factor.GetValue(cd.ToR),
globalRoundingDecimals, utils.MetaRoundingUp)
}
if b.GetValue() >= amount {
b.SubstractValue(amount)
inc.BalanceInfo.Unit = &UnitInfo{
UUID: b.Uuid,
ID: b.ID,
Value: b.Value,
DestinationID: cc.Destination,
Consumed: amount,
ToR: cc.ToR,
RateInterval: nil,
}
inc.BalanceInfo.AccountID = ub.ID
inc.Cost = 0
inc.paid = true
if count {
ub.countUnits(amount, cc.ToR, cc, b)
}
} else {
inc.paid = false
// delete the rest of the unpiad increments/timespans
if incIndex == 0 {
// cut the entire current timespan
cc.Timespans = nil
} else {
ts.SplitByIncrement(incIndex)
}
if len(cc.Timespans) == 0 {
cc = nil
}
return cc, nil
}
}
} else {
// get the cost from balance
//log.Printf("::::::: %+v", cd)
var debitedConnectFeeBalance Balance
var ok bool
cc, err = b.GetCost(cd, true)
if err != nil {
return nil, err
}
if debitConnectFee {
// this is the first add, debit the connect fee
if ok, debitedConnectFeeBalance = ub.DebitConnectionFee(cc, moneyBalances, count, true); !ok {
// found blocker balance
return nil, nil
}
}
cc.Timespans.Decompress()
//log.Printf("CC: %+v", cc)
for tsIndex, ts := range cc.Timespans {
if ts.Increments == nil {
ts.createIncrementsSlice()
}
if ts.RateInterval == nil {
utils.Logger.Err(fmt.Sprintf("Nil RateInterval ERROR on TS: %+v, CC: %+v, from CD: %+v", ts, cc, cd))
return nil, errors.New("timespan with no rate interval assigned")
}
if tsIndex == 0 && ts.RateInterval.Rating.ConnectFee > 0 && debitConnectFee && cc.deductConnectFee && ok {
inc := &Increment{
Duration: 0,
Cost: ts.RateInterval.Rating.ConnectFee,
BalanceInfo: &DebitInfo{
Monetary: &MonetaryInfo{
UUID: debitedConnectFeeBalance.Uuid,
ID: debitedConnectFeeBalance.ID,
Value: debitedConnectFeeBalance.Value,
},
AccountID: ub.ID,
},
}
incs := []*Increment{inc}
ts.Increments = append(incs, ts.Increments...)
}
maxCost, strategy := ts.RateInterval.GetMaxCost()
for incIndex, inc := range ts.Increments {
if tsIndex == 0 && incIndex == 0 && ts.RateInterval.Rating.ConnectFee > 0 && debitConnectFee && cc.deductConnectFee && ok {
// go to nextincrement
continue
}
// debit minutes and money
amount := float64(inc.Duration.Nanoseconds())
if b.Factor != nil {
amount = utils.Round(amount/b.Factor.GetValue(cd.ToR), globalRoundingDecimals, utils.MetaRoundingUp)
}
cost := inc.Cost
inc.paid = false
if strategy == utils.MetaMaxCostDisconnect && cd.MaxCostSoFar >= maxCost {
// cut the entire current timespan
cc.maxCostDisconect = true
if dryRun {
if incIndex == 0 {
// cut the entire current timespan
cc.Timespans = cc.Timespans[:tsIndex]
} else {
ts.SplitByIncrement(incIndex)
cc.Timespans = cc.Timespans[:tsIndex+1]
}
return cc, nil
}
}
if strategy == utils.MetaMaxCostFree && cd.MaxCostSoFar >= maxCost {
cost, inc.Cost = 0.0, 0.0
inc.BalanceInfo.Monetary = &MonetaryInfo{
UUID: b.Uuid,
ID: b.ID,
Value: b.Value,
RateInterval: ts.RateInterval,
}
inc.BalanceInfo.AccountID = ub.ID
inc.paid = true
if count {
ub.countUnits(cost, utils.MetaMonetary, cc, b)
}
// go to nextincrement
continue
}
var moneyBal *Balance
for _, mb := range moneyBalances {
if mb.GetValue() >= cost {
moneyBal = mb
break
}
}
if cost != 0 && moneyBal == nil && (!dryRun || ub.AllowNegative) { // Fix for issue #685
utils.Logger.Warning(fmt.Sprintf("<RALs> Going negative on account %s with AllowNegative: false", cd.GetAccountKey()))
moneyBal = ub.GetDefaultMoneyBalance()
}
if b.GetValue() >= amount && (moneyBal != nil || cost == 0) {
b.SubstractValue(amount)
inc.BalanceInfo.Unit = &UnitInfo{
UUID: b.Uuid,
ID: b.ID,
Value: b.Value,
DestinationID: cc.Destination,
Consumed: amount,
ToR: cc.ToR,
RateInterval: ts.RateInterval,
}
inc.BalanceInfo.AccountID = ub.ID
if cost != 0 {
moneyBal.SubstractValue(cost)
inc.BalanceInfo.Monetary = &MonetaryInfo{
UUID: moneyBal.Uuid,
ID: moneyBal.ID,
Value: moneyBal.Value,
}
cd.MaxCostSoFar += cost
}
inc.paid = true
if count {
ub.countUnits(amount, cc.ToR, cc, b)
if cost != 0 {
ub.countUnits(cost, utils.MetaMonetary, cc, moneyBal)
}
}
} else {
inc.paid = false
// delete the rest of the unpaid increments/timespans
if incIndex == 0 {
// cut the entire current timespan
cc.Timespans = cc.Timespans[:tsIndex]
} else {
ts.SplitByIncrement(incIndex)
cc.Timespans = cc.Timespans[:tsIndex+1]
}
if len(cc.Timespans) == 0 {
cc = nil
}
return cc, nil
}
}
}
}
return
}
func (b *Balance) debitMoney(cd *CallDescriptor, ub *Account, moneyBalances Balances, count bool, dryRun, debitConnectFee bool) (cc *CallCost, err error) {
if !b.IsActiveAt(cd.TimeStart) || b.GetValue() <= 0 {
return
}
//log.Print("B: ", utils.ToJSON(b))
//log.Printf("}}}}}}} %+v", cd.testCallcost)
cc, err = b.GetCost(cd, true)
if err != nil {
return nil, err
}
var debitedConnectFeeBalance Balance
var ok bool
//log.Print("cc: " + utils.ToJSON(cc))
if debitConnectFee {
// this is the first add, debit the connect fee
if ok, debitedConnectFeeBalance = ub.DebitConnectionFee(cc, moneyBalances, count, true); !ok {
// balance is blocker
return nil, nil
}
}
cc.Timespans.Decompress()
//log.Printf("CallCost In Debit: %+v", cc)
//for _, ts := range cc.Timespans {
// log.Printf("CC_TS: %+v", ts.RateInterval.Rating.Rates[0])
//}
for tsIndex, ts := range cc.Timespans {
if ts.Increments == nil {
ts.createIncrementsSlice()
}
//log.Printf("TS: %+v", ts)
if ts.RateInterval == nil {
utils.Logger.Err(fmt.Sprintf("Nil RateInterval ERROR on TS: %+v, CC: %+v, from CD: %+v", ts, cc, cd))
return nil, errors.New("timespan with no rate interval assigned")
}
if tsIndex == 0 && ts.RateInterval.Rating.ConnectFee > 0 && debitConnectFee && cc.deductConnectFee && ok {
inc := &Increment{
Duration: 0,
Cost: ts.RateInterval.Rating.ConnectFee,
BalanceInfo: &DebitInfo{
Monetary: &MonetaryInfo{
UUID: debitedConnectFeeBalance.Uuid,
ID: debitedConnectFeeBalance.ID,
Value: debitedConnectFeeBalance.Value,
},
AccountID: ub.ID,
},
}
incs := []*Increment{inc}
ts.Increments = append(incs, ts.Increments...)
}
maxCost, strategy := ts.RateInterval.GetMaxCost()
//log.Printf("Timing: %+v", ts.RateInterval.Timing)
//log.Printf("RGRate: %+v", ts.RateInterval.Rating)
for incIndex, inc := range ts.Increments {
// check standard subject tags
//log.Printf("INC: %+v", inc)
if tsIndex == 0 && incIndex == 0 && ts.RateInterval.Rating.ConnectFee > 0 && cc.deductConnectFee && ok {
// go to nextincrement
continue
}
amount := inc.Cost
inc.paid = false
if strategy == utils.MetaMaxCostDisconnect && cd.MaxCostSoFar >= maxCost {
// cut the entire current timespan
cc.maxCostDisconect = true
if dryRun {
if incIndex == 0 {
// cut the entire current timespan
cc.Timespans = cc.Timespans[:tsIndex]
} else {
ts.SplitByIncrement(incIndex)
cc.Timespans = cc.Timespans[:tsIndex+1]
}
return cc, nil
}
}
if strategy == utils.MetaMaxCostFree && cd.MaxCostSoFar >= maxCost {
amount, inc.Cost = 0.0, 0.0
inc.BalanceInfo.Monetary = &MonetaryInfo{
UUID: b.Uuid,
ID: b.ID,
Value: b.Value,
}
inc.BalanceInfo.AccountID = ub.ID
if b.RatingSubject != "" {
inc.BalanceInfo.Monetary.RateInterval = ts.RateInterval
}
inc.paid = true
if count {
ub.countUnits(amount, utils.MetaMonetary, cc, b)
}
//log.Printf("TS: %+v", cc.Cost)
// go to nextincrement
continue
}
if b.GetValue() >= amount {
b.SubstractValue(amount)
cd.MaxCostSoFar += amount
inc.BalanceInfo.Monetary = &MonetaryInfo{
UUID: b.Uuid,
ID: b.ID,
Value: b.Value,
}
inc.BalanceInfo.AccountID = ub.ID
if b.RatingSubject != "" {
inc.BalanceInfo.Monetary.RateInterval = ts.RateInterval
}
inc.paid = true
if count {
ub.countUnits(amount, utils.MetaMonetary, cc, b)
}
} else {
inc.paid = false
// delete the rest of the unpiad increments/timespans
if incIndex == 0 {
// cut the entire current timespan
cc.Timespans = cc.Timespans[:tsIndex]
} else {
ts.SplitByIncrement(incIndex)
cc.Timespans = cc.Timespans[:tsIndex+1]
}
if len(cc.Timespans) == 0 {
cc = nil
}
return cc, nil
}
}
}
//log.Printf("END: %+v", cd.testCallcost)
if len(cc.Timespans) == 0 {
cc = nil
}
return cc, nil
}
// AsBalanceSummary converts the balance towards compressed information to be displayed
func (b *Balance) AsBalanceSummary(typ string) *BalanceSummary {
bd := &BalanceSummary{UUID: b.Uuid, ID: b.ID, Type: typ, Value: b.Value, Disabled: b.Disabled}
if bd.ID == "" {
bd.ID = b.Uuid
}
return bd
}
/*
Structure to store minute buckets according to weight, precision or price.
*/
type Balances []*Balance
func (bc Balances) Len() int {
return len(bc)
}
func (bc Balances) Swap(i, j int) {
bc[i], bc[j] = bc[j], bc[i]
}
// we need the better ones at the beginning
func (bc Balances) Less(j, i int) bool {
return bc[i].precision < bc[j].precision ||
(bc[i].precision == bc[j].precision && bc[i].Weight < bc[j].Weight)
}
func (bc Balances) Sort() {
sort.Sort(bc)
}
func (bc Balances) GetTotalValue() (total float64) {
for _, b := range bc {
if !b.IsExpiredAt(time.Now()) && b.IsActive() {
total += b.GetValue()
}
}
total = utils.Round(total, globalRoundingDecimals, utils.MetaRoundingMiddle)
return
}
func (bc Balances) Equal(o Balances) bool {
if len(bc) != len(o) {
return false
}
bc.Sort()
o.Sort()
for i := 0; i < len(bc); i++ {
if !bc[i].Equal(o[i]) {
return false
}
}
return true
}
func (bc Balances) Clone() Balances {
var newChain Balances
for _, b := range bc {
newChain = append(newChain, b.Clone())
}
return newChain
}
func (bc Balances) GetBalance(uuid string) *Balance {
for _, balance := range bc {
if balance.Uuid == uuid {
return balance
}
}
return nil
}
func (bc Balances) HasBalance(balance *Balance) bool {
for _, b := range bc {
if b.Equal(balance) {
return true
}
}
return false
}
func (bc Balances) SaveDirtyBalances(acc *Account) {
savedAccounts := make(map[string]*Account)
for _, b := range bc {
if b.account != nil && b.account != acc && b.dirty && savedAccounts[b.account.ID] == nil {
dm.SetAccount(b.account)
savedAccounts[b.account.ID] = b.account
}
}
if len(savedAccounts) != 0 {
for _, acnt := range savedAccounts {
acntSummary := acnt.AsAccountSummary()
cgrEv := &utils.CGREvent{
Tenant: acntSummary.Tenant,
ID: utils.GenUUID(),
Time: utils.TimePointer(time.Now()),
Event: acntSummary.AsMapInterface(),
Opts: map[string]interface{}{
utils.MetaEventType: utils.AccountUpdate,
},
}
if len(config.CgrConfig().RalsCfg().ThresholdSConns) != 0 {
var tIDs []string
if err := connMgr.Call(config.CgrConfig().RalsCfg().ThresholdSConns, nil,
utils.ThresholdSv1ProcessEvent, &ThresholdsArgsProcessEvent{
CGREvent: cgrEv,
}, &tIDs); err != nil &&
err.Error() != utils.ErrNotFound.Error() {
utils.Logger.Warning(
fmt.Sprintf("<AccountS> error: %s processing account event %+v with ThresholdS.", err.Error(), cgrEv))
}
}
if len(config.CgrConfig().RalsCfg().StatSConns) != 0 {
var stsIDs []string
if err := connMgr.Call(config.CgrConfig().RalsCfg().StatSConns, nil,
utils.StatSv1ProcessEvent, &StatsArgsProcessEvent{
CGREvent: cgrEv,
}, &stsIDs); err != nil &&
err.Error() != utils.ErrNotFound.Error() {
utils.Logger.Warning(
fmt.Sprintf("<AccountS> error: %s processing account event %+v with StatS.", err.Error(), cgrEv))
}
}
}
}
}
type ValueFactor map[string]float64
func (f ValueFactor) GetValue(tor string) float64 {
if value, ok := f[tor]; ok {
return value
}
return 1.0
}
// BalanceSummary represents compressed information about a balance
type BalanceSummary struct {
UUID string // Balance UUID
ID string // Balance ID if not defined
Type string // *voice, *data, etc
Initial float64 // initial value before the debit operation
Value float64
Disabled bool
}
// BalanceSummaries is a list of BalanceSummaries
type BalanceSummaries []*BalanceSummary
// BalanceSummaryWithUUD returns a BalanceSummary based on an UUID
func (bs BalanceSummaries) BalanceSummaryWithUUD(bsUUID string) (b *BalanceSummary) {
for _, blc := range bs {
if blc.UUID == bsUUID {
b = blc
break
}
}
return
}
// FieldAsInterface func to help EventCost FieldAsInterface
func (bl *BalanceSummary) FieldAsInterface(fldPath []string) (val interface{}, err error) {
if len(fldPath) != 1 {
return nil, utils.ErrNotFound
}
switch fldPath[0] {
default:
return nil, fmt.Errorf("unsupported field prefix: <%s>", fldPath[0])
case utils.UUID:
return bl.UUID, nil
case utils.ID:
return bl.ID, nil
case utils.Type:
return bl.Type, nil
case utils.Value:
return bl.Value, nil
case utils.Disabled:
return bl.Disabled, nil
}
}
| TeoV/cgrates | engine/balances.go | GO | gpl-3.0 | 23,880 |
package com.earth2me.essentials.textreader;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.I18n;
import static com.earth2me.essentials.I18n._;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class TextPager
{
private final transient IText text;
private final transient boolean onePage;
public TextPager(final IText text)
{
this(text, false);
}
public TextPager(final IText text, final boolean onePage)
{
this.text = text;
this.onePage = onePage;
}
public void showPage(final String pageStr, final String chapterPageStr, final String commandName, final CommandSource sender)
{
List<String> lines = text.getLines();
List<String> chapters = text.getChapters();
Map<String, Integer> bookmarks = text.getBookmarks();
//This code deals with the initial chapter. We use this to display the initial output or contents.
//We also use this code to display some extra information if we don't intend to use chapters
if (pageStr == null || pageStr.isEmpty() || pageStr.matches("[0-9]+"))
{
//If an info file starts with a chapter title, list the chapters
//If not display the text up until the first chapter.
if (!lines.isEmpty() && lines.get(0).startsWith("#"))
{
if (onePage)
{
return;
}
sender.sendMessage(_("infoChapter"));
final StringBuilder sb = new StringBuilder();
boolean first = true;
for (String string : chapters)
{
if (!first)
{
sb.append(", ");
}
first = false;
sb.append(string);
}
sender.sendMessage(sb.toString());
return;
}
else
{
int page = 1;
try
{
page = Integer.parseInt(pageStr);
}
catch (NumberFormatException ex)
{
page = 1;
}
if (page < 1)
{
page = 1;
}
int start = onePage ? 0 : (page - 1) * 9;
int end;
for (end = 0; end < lines.size(); end++)
{
String line = lines.get(end);
if (line.startsWith("#"))
{
break;
}
}
int pages = end / 9 + (end % 9 > 0 ? 1 : 0);
if (!onePage && commandName != null)
{
StringBuilder content = new StringBuilder();
final String[] title = commandName.split(" ", 2);
if (title.length > 1)
{
content.append(I18n.capitalCase(title[0])).append(": ");
content.append(title[1]);
}
else
{
content.append(I18n.capitalCase(commandName));
}
sender.sendMessage(_("infoPages", page, pages, content));
}
for (int i = start; i < end && i < start + (onePage ? 20 : 9); i++)
{
sender.sendMessage("§r" + lines.get(i));
}
if (!onePage && page < pages && commandName != null)
{
sender.sendMessage(_("readNextPage", commandName, page + 1));
}
return;
}
}
//If we have a chapter, check to see if we have a page number
int chapterpage = 0;
if (chapterPageStr != null)
{
try
{
chapterpage = Integer.parseInt(chapterPageStr) - 1;
}
catch (NumberFormatException ex)
{
chapterpage = 0;
}
if (chapterpage < 0)
{
chapterpage = 0;
}
}
//This checks to see if we have the chapter in the index
if (!bookmarks.containsKey(pageStr.toLowerCase(Locale.ENGLISH)))
{
sender.sendMessage(_("infoUnknownChapter"));
return;
}
//Since we have a valid chapter, count the number of lines in the chapter
final int chapterstart = bookmarks.get(pageStr.toLowerCase(Locale.ENGLISH)) + 1;
int chapterend;
for (chapterend = chapterstart; chapterend < lines.size(); chapterend++)
{
final String line = lines.get(chapterend);
if (line.length() > 0 && line.charAt(0) == '#')
{
break;
}
}
//Display the chapter from the starting position
final int start = chapterstart + (onePage ? 0 : chapterpage * 9);
final int page = chapterpage + 1;
final int pages = (chapterend - chapterstart) / 9 + ((chapterend - chapterstart) % 9 > 0 ? 1 : 0);
if (!onePage && commandName != null)
{
StringBuilder content = new StringBuilder();
content.append(I18n.capitalCase(commandName)).append(": ");
content.append(pageStr);
sender.sendMessage(_("infoChapterPages", content, page, pages));
}
for (int i = start; i < chapterend && i < start + (onePage ? 20 : 9); i++)
{
sender.sendMessage("§r" + lines.get(i));
}
if (!onePage && page < pages && commandName != null)
{
sender.sendMessage(_("readNextPage", commandName, pageStr + " " + (page + 1)));
}
}
}
| DarkSino98/Essentials | Essentials/src/com/earth2me/essentials/textreader/TextPager.java | Java | gpl-3.0 | 4,490 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/trace_event/trace_log.h"
#include <algorithm>
#include <cmath>
#include <memory>
#include <utility>
#include "base/base_switches.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/debug/leak_annotations.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/ref_counted_memory.h"
#include "base/memory/singleton.h"
#include "base/process/process_metrics.h"
#include "base/stl_util.h"
#include "base/strings/string_split.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/stringprintf.h"
#include "base/sys_info.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread_id_name_manager.h"
#include "base/threading/worker_pool.h"
#include "base/time/time.h"
#include "base/trace_event/heap_profiler.h"
#include "base/trace_event/heap_profiler_allocation_context_tracker.h"
#include "base/trace_event/memory_dump_manager.h"
#include "base/trace_event/memory_dump_provider.h"
#include "base/trace_event/process_memory_dump.h"
#include "base/trace_event/trace_buffer.h"
#include "base/trace_event/trace_event.h"
#include "base/trace_event/trace_event_synthetic_delay.h"
#include "base/trace_event/trace_sampling_thread.h"
#include "build/build_config.h"
#if defined(OS_WIN)
#include "base/trace_event/trace_event_etw_export_win.h"
#endif
// The thread buckets for the sampling profiler.
BASE_EXPORT TRACE_EVENT_API_ATOMIC_WORD g_trace_state[3];
namespace base {
namespace internal {
class DeleteTraceLogForTesting {
public:
static void Delete() {
Singleton<trace_event::TraceLog,
LeakySingletonTraits<trace_event::TraceLog>>::OnExit(0);
}
};
} // namespace internal
namespace trace_event {
namespace {
// Controls the number of trace events we will buffer in-memory
// before throwing them away.
const size_t kTraceBufferChunkSize = TraceBufferChunk::kTraceBufferChunkSize;
const size_t kTraceEventVectorBigBufferChunks =
512000000 / kTraceBufferChunkSize;
static_assert(
kTraceEventVectorBigBufferChunks <= TraceBufferChunk::kMaxChunkIndex,
"Too many big buffer chunks");
const size_t kTraceEventVectorBufferChunks = 256000 / kTraceBufferChunkSize;
static_assert(
kTraceEventVectorBufferChunks <= TraceBufferChunk::kMaxChunkIndex,
"Too many vector buffer chunks");
const size_t kTraceEventRingBufferChunks = kTraceEventVectorBufferChunks / 4;
// ECHO_TO_CONSOLE needs a small buffer to hold the unfinished COMPLETE events.
const size_t kEchoToConsoleTraceEventBufferChunks = 256;
const size_t kTraceEventBufferSizeInBytes = 100 * 1024;
const int kThreadFlushTimeoutMs = 3000;
#define MAX_CATEGORY_GROUPS 105
// Parallel arrays g_category_groups and g_category_group_enabled are separate
// so that a pointer to a member of g_category_group_enabled can be easily
// converted to an index into g_category_groups. This allows macros to deal
// only with char enabled pointers from g_category_group_enabled, and we can
// convert internally to determine the category name from the char enabled
// pointer.
const char* g_category_groups[MAX_CATEGORY_GROUPS] = {
"toplevel",
"tracing already shutdown",
"tracing categories exhausted; must increase MAX_CATEGORY_GROUPS",
"__metadata"};
// The enabled flag is char instead of bool so that the API can be used from C.
unsigned char g_category_group_enabled[MAX_CATEGORY_GROUPS] = {0};
// Indexes here have to match the g_category_groups array indexes above.
const int g_category_already_shutdown = 1;
const int g_category_categories_exhausted = 2;
const int g_category_metadata = 3;
const int g_num_builtin_categories = 4;
// Skip default categories.
base::subtle::AtomicWord g_category_index = g_num_builtin_categories;
// The name of the current thread. This is used to decide if the current
// thread name has changed. We combine all the seen thread names into the
// output name for the thread.
LazyInstance<ThreadLocalPointer<const char>>::Leaky g_current_thread_name =
LAZY_INSTANCE_INITIALIZER;
ThreadTicks ThreadNow() {
return ThreadTicks::IsSupported() ? ThreadTicks::Now() : ThreadTicks();
}
template <typename T>
void InitializeMetadataEvent(TraceEvent* trace_event,
int thread_id,
const char* metadata_name,
const char* arg_name,
const T& value) {
if (!trace_event)
return;
int num_args = 1;
unsigned char arg_type;
unsigned long long arg_value;
::trace_event_internal::SetTraceValue(value, &arg_type, &arg_value);
trace_event->Initialize(
thread_id,
TimeTicks(),
ThreadTicks(),
TRACE_EVENT_PHASE_METADATA,
&g_category_group_enabled[g_category_metadata],
metadata_name,
trace_event_internal::kGlobalScope, // scope
trace_event_internal::kNoId, // id
trace_event_internal::kNoId, // bind_id
num_args,
&arg_name,
&arg_type,
&arg_value,
nullptr,
TRACE_EVENT_FLAG_NONE);
}
class AutoThreadLocalBoolean {
public:
explicit AutoThreadLocalBoolean(ThreadLocalBoolean* thread_local_boolean)
: thread_local_boolean_(thread_local_boolean) {
DCHECK(!thread_local_boolean_->Get());
thread_local_boolean_->Set(true);
}
~AutoThreadLocalBoolean() { thread_local_boolean_->Set(false); }
private:
ThreadLocalBoolean* thread_local_boolean_;
DISALLOW_COPY_AND_ASSIGN(AutoThreadLocalBoolean);
};
// Use this function instead of TraceEventHandle constructor to keep the
// overhead of ScopedTracer (trace_event.h) constructor minimum.
void MakeHandle(uint32_t chunk_seq,
size_t chunk_index,
size_t event_index,
TraceEventHandle* handle) {
DCHECK(chunk_seq);
DCHECK(chunk_index <= TraceBufferChunk::kMaxChunkIndex);
DCHECK(event_index < TraceBufferChunk::kTraceBufferChunkSize);
handle->chunk_seq = chunk_seq;
handle->chunk_index = static_cast<uint16_t>(chunk_index);
handle->event_index = static_cast<uint16_t>(event_index);
}
} // namespace
// A helper class that allows the lock to be acquired in the middle of the scope
// and unlocks at the end of scope if locked.
class TraceLog::OptionalAutoLock {
public:
explicit OptionalAutoLock(Lock* lock) : lock_(lock), locked_(false) {}
~OptionalAutoLock() {
if (locked_)
lock_->Release();
}
void EnsureAcquired() {
if (!locked_) {
lock_->Acquire();
locked_ = true;
}
}
private:
Lock* lock_;
bool locked_;
DISALLOW_COPY_AND_ASSIGN(OptionalAutoLock);
};
class TraceLog::ThreadLocalEventBuffer
: public MessageLoop::DestructionObserver,
public MemoryDumpProvider {
public:
explicit ThreadLocalEventBuffer(TraceLog* trace_log);
~ThreadLocalEventBuffer() override;
TraceEvent* AddTraceEvent(TraceEventHandle* handle);
TraceEvent* GetEventByHandle(TraceEventHandle handle) {
if (!chunk_ || handle.chunk_seq != chunk_->seq() ||
handle.chunk_index != chunk_index_) {
return nullptr;
}
return chunk_->GetEventAt(handle.event_index);
}
int generation() const { return generation_; }
private:
// MessageLoop::DestructionObserver
void WillDestroyCurrentMessageLoop() override;
// MemoryDumpProvider implementation.
bool OnMemoryDump(const MemoryDumpArgs& args,
ProcessMemoryDump* pmd) override;
void FlushWhileLocked();
void CheckThisIsCurrentBuffer() const {
DCHECK(trace_log_->thread_local_event_buffer_.Get() == this);
}
// Since TraceLog is a leaky singleton, trace_log_ will always be valid
// as long as the thread exists.
TraceLog* trace_log_;
std::unique_ptr<TraceBufferChunk> chunk_;
size_t chunk_index_;
int generation_;
DISALLOW_COPY_AND_ASSIGN(ThreadLocalEventBuffer);
};
TraceLog::ThreadLocalEventBuffer::ThreadLocalEventBuffer(TraceLog* trace_log)
: trace_log_(trace_log),
chunk_index_(0),
generation_(trace_log->generation()) {
// ThreadLocalEventBuffer is created only if the thread has a message loop, so
// the following message_loop won't be NULL.
MessageLoop* message_loop = MessageLoop::current();
message_loop->AddDestructionObserver(this);
// This is to report the local memory usage when memory-infra is enabled.
MemoryDumpManager::GetInstance()->RegisterDumpProvider(
this, "ThreadLocalEventBuffer", ThreadTaskRunnerHandle::Get());
AutoLock lock(trace_log->lock_);
trace_log->thread_message_loops_.insert(message_loop);
}
TraceLog::ThreadLocalEventBuffer::~ThreadLocalEventBuffer() {
CheckThisIsCurrentBuffer();
MessageLoop::current()->RemoveDestructionObserver(this);
MemoryDumpManager::GetInstance()->UnregisterDumpProvider(this);
{
AutoLock lock(trace_log_->lock_);
FlushWhileLocked();
trace_log_->thread_message_loops_.erase(MessageLoop::current());
}
trace_log_->thread_local_event_buffer_.Set(NULL);
}
TraceEvent* TraceLog::ThreadLocalEventBuffer::AddTraceEvent(
TraceEventHandle* handle) {
CheckThisIsCurrentBuffer();
if (chunk_ && chunk_->IsFull()) {
AutoLock lock(trace_log_->lock_);
FlushWhileLocked();
chunk_.reset();
}
if (!chunk_) {
AutoLock lock(trace_log_->lock_);
chunk_ = trace_log_->logged_events_->GetChunk(&chunk_index_);
trace_log_->CheckIfBufferIsFullWhileLocked();
}
if (!chunk_)
return NULL;
size_t event_index;
TraceEvent* trace_event = chunk_->AddTraceEvent(&event_index);
if (trace_event && handle)
MakeHandle(chunk_->seq(), chunk_index_, event_index, handle);
return trace_event;
}
void TraceLog::ThreadLocalEventBuffer::WillDestroyCurrentMessageLoop() {
delete this;
}
bool TraceLog::ThreadLocalEventBuffer::OnMemoryDump(const MemoryDumpArgs& args,
ProcessMemoryDump* pmd) {
if (!chunk_)
return true;
std::string dump_base_name = StringPrintf(
"tracing/thread_%d", static_cast<int>(PlatformThread::CurrentId()));
TraceEventMemoryOverhead overhead;
chunk_->EstimateTraceMemoryOverhead(&overhead);
overhead.DumpInto(dump_base_name.c_str(), pmd);
return true;
}
void TraceLog::ThreadLocalEventBuffer::FlushWhileLocked() {
if (!chunk_)
return;
trace_log_->lock_.AssertAcquired();
if (trace_log_->CheckGeneration(generation_)) {
// Return the chunk to the buffer only if the generation matches.
trace_log_->logged_events_->ReturnChunk(chunk_index_, std::move(chunk_));
}
// Otherwise this method may be called from the destructor, or TraceLog will
// find the generation mismatch and delete this buffer soon.
}
TraceLogStatus::TraceLogStatus() : event_capacity(0), event_count(0) {}
TraceLogStatus::~TraceLogStatus() {}
// static
TraceLog* TraceLog::GetInstance() {
return Singleton<TraceLog, LeakySingletonTraits<TraceLog>>::get();
}
TraceLog::TraceLog()
: mode_(DISABLED),
num_traces_recorded_(0),
event_callback_(0),
dispatching_to_observer_list_(false),
process_sort_index_(0),
process_id_hash_(0),
process_id_(0),
watch_category_(0),
trace_options_(kInternalRecordUntilFull),
sampling_thread_handle_(0),
trace_config_(TraceConfig()),
event_callback_trace_config_(TraceConfig()),
thread_shared_chunk_index_(0),
generation_(0),
use_worker_thread_(false) {
// Trace is enabled or disabled on one thread while other threads are
// accessing the enabled flag. We don't care whether edge-case events are
// traced or not, so we allow races on the enabled flag to keep the trace
// macros fast.
// TODO(jbates): ANNOTATE_BENIGN_RACE_SIZED crashes windows TSAN bots:
// ANNOTATE_BENIGN_RACE_SIZED(g_category_group_enabled,
// sizeof(g_category_group_enabled),
// "trace_event category enabled");
for (int i = 0; i < MAX_CATEGORY_GROUPS; ++i) {
ANNOTATE_BENIGN_RACE(&g_category_group_enabled[i],
"trace_event category enabled");
}
#if defined(OS_NACL) // NaCl shouldn't expose the process id.
SetProcessID(0);
#else
SetProcessID(static_cast<int>(GetCurrentProcId()));
#endif
logged_events_.reset(CreateTraceBuffer());
MemoryDumpManager::GetInstance()->RegisterDumpProvider(this, "TraceLog",
nullptr);
}
TraceLog::~TraceLog() {}
void TraceLog::InitializeThreadLocalEventBufferIfSupported() {
// A ThreadLocalEventBuffer needs the message loop
// - to know when the thread exits;
// - to handle the final flush.
// For a thread without a message loop or the message loop may be blocked, the
// trace events will be added into the main buffer directly.
if (thread_blocks_message_loop_.Get() || !MessageLoop::current())
return;
HEAP_PROFILER_SCOPED_IGNORE;
auto thread_local_event_buffer = thread_local_event_buffer_.Get();
if (thread_local_event_buffer &&
!CheckGeneration(thread_local_event_buffer->generation())) {
delete thread_local_event_buffer;
thread_local_event_buffer = NULL;
}
if (!thread_local_event_buffer) {
thread_local_event_buffer = new ThreadLocalEventBuffer(this);
thread_local_event_buffer_.Set(thread_local_event_buffer);
}
}
bool TraceLog::OnMemoryDump(const MemoryDumpArgs& args,
ProcessMemoryDump* pmd) {
// TODO(ssid): Use MemoryDumpArgs to create light dumps when requested
// (crbug.com/499731).
TraceEventMemoryOverhead overhead;
overhead.Add("TraceLog", sizeof(*this));
{
AutoLock lock(lock_);
if (logged_events_)
logged_events_->EstimateTraceMemoryOverhead(&overhead);
for (auto& metadata_event : metadata_events_)
metadata_event->EstimateTraceMemoryOverhead(&overhead);
}
overhead.AddSelf();
overhead.DumpInto("tracing/main_trace_log", pmd);
return true;
}
const unsigned char* TraceLog::GetCategoryGroupEnabled(
const char* category_group) {
TraceLog* tracelog = GetInstance();
if (!tracelog) {
DCHECK(!g_category_group_enabled[g_category_already_shutdown]);
return &g_category_group_enabled[g_category_already_shutdown];
}
return tracelog->GetCategoryGroupEnabledInternal(category_group);
}
const char* TraceLog::GetCategoryGroupName(
const unsigned char* category_group_enabled) {
// Calculate the index of the category group by finding
// category_group_enabled in g_category_group_enabled array.
uintptr_t category_begin =
reinterpret_cast<uintptr_t>(g_category_group_enabled);
uintptr_t category_ptr = reinterpret_cast<uintptr_t>(category_group_enabled);
DCHECK(category_ptr >= category_begin &&
category_ptr < reinterpret_cast<uintptr_t>(g_category_group_enabled +
MAX_CATEGORY_GROUPS))
<< "out of bounds category pointer";
uintptr_t category_index =
(category_ptr - category_begin) / sizeof(g_category_group_enabled[0]);
return g_category_groups[category_index];
}
void TraceLog::UpdateCategoryGroupEnabledFlag(size_t category_index) {
unsigned char enabled_flag = 0;
const char* category_group = g_category_groups[category_index];
if (mode_ == RECORDING_MODE &&
trace_config_.IsCategoryGroupEnabled(category_group)) {
enabled_flag |= ENABLED_FOR_RECORDING;
}
if (event_callback_ &&
event_callback_trace_config_.IsCategoryGroupEnabled(category_group)) {
enabled_flag |= ENABLED_FOR_EVENT_CALLBACK;
}
#if defined(OS_WIN)
if (base::trace_event::TraceEventETWExport::IsCategoryGroupEnabled(
category_group)) {
enabled_flag |= ENABLED_FOR_ETW_EXPORT;
}
#endif
g_category_group_enabled[category_index] = enabled_flag;
}
void TraceLog::UpdateCategoryGroupEnabledFlags() {
size_t category_index = base::subtle::NoBarrier_Load(&g_category_index);
for (size_t i = 0; i < category_index; i++)
UpdateCategoryGroupEnabledFlag(i);
}
void TraceLog::UpdateSyntheticDelaysFromTraceConfig() {
ResetTraceEventSyntheticDelays();
const TraceConfig::StringList& delays =
trace_config_.GetSyntheticDelayValues();
TraceConfig::StringList::const_iterator ci;
for (ci = delays.begin(); ci != delays.end(); ++ci) {
StringTokenizer tokens(*ci, ";");
if (!tokens.GetNext())
continue;
TraceEventSyntheticDelay* delay =
TraceEventSyntheticDelay::Lookup(tokens.token());
while (tokens.GetNext()) {
std::string token = tokens.token();
char* duration_end;
double target_duration = strtod(token.c_str(), &duration_end);
if (duration_end != token.c_str()) {
delay->SetTargetDuration(TimeDelta::FromMicroseconds(
static_cast<int64_t>(target_duration * 1e6)));
} else if (token == "static") {
delay->SetMode(TraceEventSyntheticDelay::STATIC);
} else if (token == "oneshot") {
delay->SetMode(TraceEventSyntheticDelay::ONE_SHOT);
} else if (token == "alternating") {
delay->SetMode(TraceEventSyntheticDelay::ALTERNATING);
}
}
}
}
const unsigned char* TraceLog::GetCategoryGroupEnabledInternal(
const char* category_group) {
DCHECK(!strchr(category_group, '"'))
<< "Category groups may not contain double quote";
// The g_category_groups is append only, avoid using a lock for the fast path.
size_t current_category_index = base::subtle::Acquire_Load(&g_category_index);
// Search for pre-existing category group.
for (size_t i = 0; i < current_category_index; ++i) {
if (strcmp(g_category_groups[i], category_group) == 0) {
return &g_category_group_enabled[i];
}
}
unsigned char* category_group_enabled = NULL;
// This is the slow path: the lock is not held in the case above, so more
// than one thread could have reached here trying to add the same category.
// Only hold to lock when actually appending a new category, and
// check the categories groups again.
AutoLock lock(lock_);
size_t category_index = base::subtle::Acquire_Load(&g_category_index);
for (size_t i = 0; i < category_index; ++i) {
if (strcmp(g_category_groups[i], category_group) == 0) {
return &g_category_group_enabled[i];
}
}
// Create a new category group.
DCHECK(category_index < MAX_CATEGORY_GROUPS)
<< "must increase MAX_CATEGORY_GROUPS";
if (category_index < MAX_CATEGORY_GROUPS) {
// Don't hold on to the category_group pointer, so that we can create
// category groups with strings not known at compile time (this is
// required by SetWatchEvent).
const char* new_group = strdup(category_group);
ANNOTATE_LEAKING_OBJECT_PTR(new_group);
g_category_groups[category_index] = new_group;
DCHECK(!g_category_group_enabled[category_index]);
// Note that if both included and excluded patterns in the
// TraceConfig are empty, we exclude nothing,
// thereby enabling this category group.
UpdateCategoryGroupEnabledFlag(category_index);
category_group_enabled = &g_category_group_enabled[category_index];
// Update the max index now.
base::subtle::Release_Store(&g_category_index, category_index + 1);
} else {
category_group_enabled =
&g_category_group_enabled[g_category_categories_exhausted];
}
return category_group_enabled;
}
void TraceLog::GetKnownCategoryGroups(
std::vector<std::string>* category_groups) {
AutoLock lock(lock_);
size_t category_index = base::subtle::NoBarrier_Load(&g_category_index);
for (size_t i = g_num_builtin_categories; i < category_index; i++)
category_groups->push_back(g_category_groups[i]);
}
void TraceLog::SetEnabled(const TraceConfig& trace_config, Mode mode) {
std::vector<EnabledStateObserver*> observer_list;
{
AutoLock lock(lock_);
// Can't enable tracing when Flush() is in progress.
DCHECK(!flush_task_runner_);
InternalTraceOptions new_options =
GetInternalOptionsFromTraceConfig(trace_config);
InternalTraceOptions old_options = trace_options();
if (IsEnabled()) {
if (new_options != old_options) {
DLOG(ERROR) << "Attempting to re-enable tracing with a different "
<< "set of options.";
}
if (mode != mode_) {
DLOG(ERROR) << "Attempting to re-enable tracing with a different mode.";
}
trace_config_.Merge(trace_config);
UpdateCategoryGroupEnabledFlags();
return;
}
if (dispatching_to_observer_list_) {
DLOG(ERROR)
<< "Cannot manipulate TraceLog::Enabled state from an observer.";
return;
}
mode_ = mode;
if (new_options != old_options) {
subtle::NoBarrier_Store(&trace_options_, new_options);
UseNextTraceBuffer();
}
num_traces_recorded_++;
trace_config_ = TraceConfig(trace_config);
UpdateCategoryGroupEnabledFlags();
UpdateSyntheticDelaysFromTraceConfig();
if (new_options & kInternalEnableSampling) {
sampling_thread_.reset(new TraceSamplingThread);
sampling_thread_->RegisterSampleBucket(
&g_trace_state[0], "bucket0",
Bind(&TraceSamplingThread::DefaultSamplingCallback));
sampling_thread_->RegisterSampleBucket(
&g_trace_state[1], "bucket1",
Bind(&TraceSamplingThread::DefaultSamplingCallback));
sampling_thread_->RegisterSampleBucket(
&g_trace_state[2], "bucket2",
Bind(&TraceSamplingThread::DefaultSamplingCallback));
if (!PlatformThread::Create(0, sampling_thread_.get(),
&sampling_thread_handle_)) {
DCHECK(false) << "failed to create thread";
}
}
dispatching_to_observer_list_ = true;
observer_list = enabled_state_observer_list_;
}
// Notify observers outside the lock in case they trigger trace events.
for (size_t i = 0; i < observer_list.size(); ++i)
observer_list[i]->OnTraceLogEnabled();
{
AutoLock lock(lock_);
dispatching_to_observer_list_ = false;
}
}
void TraceLog::SetArgumentFilterPredicate(
const ArgumentFilterPredicate& argument_filter_predicate) {
AutoLock lock(lock_);
DCHECK(!argument_filter_predicate.is_null());
DCHECK(argument_filter_predicate_.is_null());
argument_filter_predicate_ = argument_filter_predicate;
}
TraceLog::InternalTraceOptions TraceLog::GetInternalOptionsFromTraceConfig(
const TraceConfig& config) {
InternalTraceOptions ret =
config.IsSamplingEnabled() ? kInternalEnableSampling : kInternalNone;
if (config.IsArgumentFilterEnabled())
ret |= kInternalEnableArgumentFilter;
switch (config.GetTraceRecordMode()) {
case RECORD_UNTIL_FULL:
return ret | kInternalRecordUntilFull;
case RECORD_CONTINUOUSLY:
return ret | kInternalRecordContinuously;
case ECHO_TO_CONSOLE:
return ret | kInternalEchoToConsole;
case RECORD_AS_MUCH_AS_POSSIBLE:
return ret | kInternalRecordAsMuchAsPossible;
}
NOTREACHED();
return kInternalNone;
}
TraceConfig TraceLog::GetCurrentTraceConfig() const {
AutoLock lock(lock_);
return trace_config_;
}
void TraceLog::SetDisabled() {
AutoLock lock(lock_);
SetDisabledWhileLocked();
}
void TraceLog::SetDisabledWhileLocked() {
lock_.AssertAcquired();
if (!IsEnabled())
return;
if (dispatching_to_observer_list_) {
DLOG(ERROR)
<< "Cannot manipulate TraceLog::Enabled state from an observer.";
return;
}
mode_ = DISABLED;
if (sampling_thread_.get()) {
// Stop the sampling thread.
sampling_thread_->Stop();
lock_.Release();
PlatformThread::Join(sampling_thread_handle_);
lock_.Acquire();
sampling_thread_handle_ = PlatformThreadHandle();
sampling_thread_.reset();
}
trace_config_.Clear();
subtle::NoBarrier_Store(&watch_category_, 0);
watch_event_name_ = "";
UpdateCategoryGroupEnabledFlags();
AddMetadataEventsWhileLocked();
// Remove metadata events so they will not get added to a subsequent trace.
metadata_events_.clear();
dispatching_to_observer_list_ = true;
std::vector<EnabledStateObserver*> observer_list =
enabled_state_observer_list_;
{
// Dispatch to observers outside the lock in case the observer triggers a
// trace event.
AutoUnlock unlock(lock_);
for (size_t i = 0; i < observer_list.size(); ++i)
observer_list[i]->OnTraceLogDisabled();
}
dispatching_to_observer_list_ = false;
}
int TraceLog::GetNumTracesRecorded() {
AutoLock lock(lock_);
if (!IsEnabled())
return -1;
return num_traces_recorded_;
}
void TraceLog::AddEnabledStateObserver(EnabledStateObserver* listener) {
AutoLock lock(lock_);
enabled_state_observer_list_.push_back(listener);
}
void TraceLog::RemoveEnabledStateObserver(EnabledStateObserver* listener) {
AutoLock lock(lock_);
std::vector<EnabledStateObserver*>::iterator it =
std::find(enabled_state_observer_list_.begin(),
enabled_state_observer_list_.end(), listener);
if (it != enabled_state_observer_list_.end())
enabled_state_observer_list_.erase(it);
}
bool TraceLog::HasEnabledStateObserver(EnabledStateObserver* listener) const {
AutoLock lock(lock_);
return ContainsValue(enabled_state_observer_list_, listener);
}
TraceLogStatus TraceLog::GetStatus() const {
AutoLock lock(lock_);
TraceLogStatus result;
result.event_capacity = static_cast<uint32_t>(logged_events_->Capacity());
result.event_count = static_cast<uint32_t>(logged_events_->Size());
return result;
}
bool TraceLog::BufferIsFull() const {
AutoLock lock(lock_);
return logged_events_->IsFull();
}
TraceEvent* TraceLog::AddEventToThreadSharedChunkWhileLocked(
TraceEventHandle* handle,
bool check_buffer_is_full) {
lock_.AssertAcquired();
if (thread_shared_chunk_ && thread_shared_chunk_->IsFull()) {
logged_events_->ReturnChunk(thread_shared_chunk_index_,
std::move(thread_shared_chunk_));
}
if (!thread_shared_chunk_) {
thread_shared_chunk_ =
logged_events_->GetChunk(&thread_shared_chunk_index_);
if (check_buffer_is_full)
CheckIfBufferIsFullWhileLocked();
}
if (!thread_shared_chunk_)
return NULL;
size_t event_index;
TraceEvent* trace_event = thread_shared_chunk_->AddTraceEvent(&event_index);
if (trace_event && handle) {
MakeHandle(thread_shared_chunk_->seq(), thread_shared_chunk_index_,
event_index, handle);
}
return trace_event;
}
void TraceLog::CheckIfBufferIsFullWhileLocked() {
lock_.AssertAcquired();
if (logged_events_->IsFull()) {
if (buffer_limit_reached_timestamp_.is_null()) {
buffer_limit_reached_timestamp_ = OffsetNow();
}
SetDisabledWhileLocked();
}
}
void TraceLog::SetEventCallbackEnabled(const TraceConfig& trace_config,
EventCallback cb) {
AutoLock lock(lock_);
subtle::NoBarrier_Store(&event_callback_,
reinterpret_cast<subtle::AtomicWord>(cb));
event_callback_trace_config_ = trace_config;
UpdateCategoryGroupEnabledFlags();
}
void TraceLog::SetEventCallbackDisabled() {
AutoLock lock(lock_);
subtle::NoBarrier_Store(&event_callback_, 0);
UpdateCategoryGroupEnabledFlags();
}
// Flush() works as the following:
// 1. Flush() is called in thread A whose task runner is saved in
// flush_task_runner_;
// 2. If thread_message_loops_ is not empty, thread A posts task to each message
// loop to flush the thread local buffers; otherwise finish the flush;
// 3. FlushCurrentThread() deletes the thread local event buffer:
// - The last batch of events of the thread are flushed into the main buffer;
// - The message loop will be removed from thread_message_loops_;
// If this is the last message loop, finish the flush;
// 4. If any thread hasn't finish its flush in time, finish the flush.
void TraceLog::Flush(const TraceLog::OutputCallback& cb,
bool use_worker_thread) {
FlushInternal(cb, use_worker_thread, false);
}
void TraceLog::CancelTracing(const OutputCallback& cb) {
SetDisabled();
FlushInternal(cb, false, true);
}
void TraceLog::FlushInternal(const TraceLog::OutputCallback& cb,
bool use_worker_thread,
bool discard_events) {
use_worker_thread_ = use_worker_thread;
if (IsEnabled()) {
// Can't flush when tracing is enabled because otherwise PostTask would
// - generate more trace events;
// - deschedule the calling thread on some platforms causing inaccurate
// timing of the trace events.
scoped_refptr<RefCountedString> empty_result = new RefCountedString;
if (!cb.is_null())
cb.Run(empty_result, false);
LOG(WARNING) << "Ignored TraceLog::Flush called when tracing is enabled";
return;
}
int generation = this->generation();
// Copy of thread_message_loops_ to be used without locking.
std::vector<scoped_refptr<SingleThreadTaskRunner>>
thread_message_loop_task_runners;
{
AutoLock lock(lock_);
DCHECK(!flush_task_runner_);
flush_task_runner_ = ThreadTaskRunnerHandle::IsSet()
? ThreadTaskRunnerHandle::Get()
: nullptr;
DCHECK(!thread_message_loops_.size() || flush_task_runner_);
flush_output_callback_ = cb;
if (thread_shared_chunk_) {
logged_events_->ReturnChunk(thread_shared_chunk_index_,
std::move(thread_shared_chunk_));
}
if (thread_message_loops_.size()) {
for (hash_set<MessageLoop*>::const_iterator it =
thread_message_loops_.begin();
it != thread_message_loops_.end(); ++it) {
thread_message_loop_task_runners.push_back((*it)->task_runner());
}
}
}
if (thread_message_loop_task_runners.size()) {
for (size_t i = 0; i < thread_message_loop_task_runners.size(); ++i) {
thread_message_loop_task_runners[i]->PostTask(
FROM_HERE, Bind(&TraceLog::FlushCurrentThread, Unretained(this),
generation, discard_events));
}
flush_task_runner_->PostDelayedTask(
FROM_HERE, Bind(&TraceLog::OnFlushTimeout, Unretained(this), generation,
discard_events),
TimeDelta::FromMilliseconds(kThreadFlushTimeoutMs));
return;
}
FinishFlush(generation, discard_events);
}
// Usually it runs on a different thread.
void TraceLog::ConvertTraceEventsToTraceFormat(
std::unique_ptr<TraceBuffer> logged_events,
const OutputCallback& flush_output_callback,
const ArgumentFilterPredicate& argument_filter_predicate) {
if (flush_output_callback.is_null())
return;
HEAP_PROFILER_SCOPED_IGNORE;
// The callback need to be called at least once even if there is no events
// to let the caller know the completion of flush.
scoped_refptr<RefCountedString> json_events_str_ptr = new RefCountedString();
while (const TraceBufferChunk* chunk = logged_events->NextChunk()) {
for (size_t j = 0; j < chunk->size(); ++j) {
size_t size = json_events_str_ptr->size();
if (size > kTraceEventBufferSizeInBytes) {
flush_output_callback.Run(json_events_str_ptr, true);
json_events_str_ptr = new RefCountedString();
} else if (size) {
json_events_str_ptr->data().append(",\n");
}
chunk->GetEventAt(j)->AppendAsJSON(&(json_events_str_ptr->data()),
argument_filter_predicate);
}
}
flush_output_callback.Run(json_events_str_ptr, false);
}
void TraceLog::FinishFlush(int generation, bool discard_events) {
std::unique_ptr<TraceBuffer> previous_logged_events;
OutputCallback flush_output_callback;
ArgumentFilterPredicate argument_filter_predicate;
if (!CheckGeneration(generation))
return;
{
AutoLock lock(lock_);
previous_logged_events.swap(logged_events_);
UseNextTraceBuffer();
thread_message_loops_.clear();
flush_task_runner_ = NULL;
flush_output_callback = flush_output_callback_;
flush_output_callback_.Reset();
if (trace_options() & kInternalEnableArgumentFilter) {
CHECK(!argument_filter_predicate_.is_null());
argument_filter_predicate = argument_filter_predicate_;
}
}
if (discard_events) {
if (!flush_output_callback.is_null()) {
scoped_refptr<RefCountedString> empty_result = new RefCountedString;
flush_output_callback.Run(empty_result, false);
}
return;
}
if (use_worker_thread_ &&
WorkerPool::PostTask(
FROM_HERE, Bind(&TraceLog::ConvertTraceEventsToTraceFormat,
Passed(&previous_logged_events),
flush_output_callback, argument_filter_predicate),
true)) {
return;
}
ConvertTraceEventsToTraceFormat(std::move(previous_logged_events),
flush_output_callback,
argument_filter_predicate);
}
// Run in each thread holding a local event buffer.
void TraceLog::FlushCurrentThread(int generation, bool discard_events) {
{
AutoLock lock(lock_);
if (!CheckGeneration(generation) || !flush_task_runner_) {
// This is late. The corresponding flush has finished.
return;
}
}
// This will flush the thread local buffer.
delete thread_local_event_buffer_.Get();
AutoLock lock(lock_);
if (!CheckGeneration(generation) || !flush_task_runner_ ||
thread_message_loops_.size())
return;
flush_task_runner_->PostTask(
FROM_HERE, Bind(&TraceLog::FinishFlush, Unretained(this), generation,
discard_events));
}
void TraceLog::OnFlushTimeout(int generation, bool discard_events) {
{
AutoLock lock(lock_);
if (!CheckGeneration(generation) || !flush_task_runner_) {
// Flush has finished before timeout.
return;
}
LOG(WARNING)
<< "The following threads haven't finished flush in time. "
"If this happens stably for some thread, please call "
"TraceLog::GetInstance()->SetCurrentThreadBlocksMessageLoop() from "
"the thread to avoid its trace events from being lost.";
for (hash_set<MessageLoop*>::const_iterator it =
thread_message_loops_.begin();
it != thread_message_loops_.end(); ++it) {
LOG(WARNING) << "Thread: " << (*it)->thread_name();
}
}
FinishFlush(generation, discard_events);
}
void TraceLog::UseNextTraceBuffer() {
logged_events_.reset(CreateTraceBuffer());
subtle::NoBarrier_AtomicIncrement(&generation_, 1);
thread_shared_chunk_.reset();
thread_shared_chunk_index_ = 0;
}
TraceEventHandle TraceLog::AddTraceEvent(
char phase,
const unsigned char* category_group_enabled,
const char* name,
const char* scope,
unsigned long long id,
int num_args,
const char** arg_names,
const unsigned char* arg_types,
const unsigned long long* arg_values,
std::unique_ptr<ConvertableToTraceFormat>* convertable_values,
unsigned int flags) {
int thread_id = static_cast<int>(base::PlatformThread::CurrentId());
base::TimeTicks now = base::TimeTicks::Now();
return AddTraceEventWithThreadIdAndTimestamp(
phase,
category_group_enabled,
name,
scope,
id,
trace_event_internal::kNoId, // bind_id
thread_id,
now,
num_args,
arg_names,
arg_types,
arg_values,
convertable_values,
flags);
}
TraceEventHandle TraceLog::AddTraceEventWithBindId(
char phase,
const unsigned char* category_group_enabled,
const char* name,
const char* scope,
unsigned long long id,
unsigned long long bind_id,
int num_args,
const char** arg_names,
const unsigned char* arg_types,
const unsigned long long* arg_values,
std::unique_ptr<ConvertableToTraceFormat>* convertable_values,
unsigned int flags) {
int thread_id = static_cast<int>(base::PlatformThread::CurrentId());
base::TimeTicks now = base::TimeTicks::Now();
return AddTraceEventWithThreadIdAndTimestamp(
phase,
category_group_enabled,
name,
scope,
id,
bind_id,
thread_id,
now,
num_args,
arg_names,
arg_types,
arg_values,
convertable_values,
flags | TRACE_EVENT_FLAG_HAS_CONTEXT_ID);
}
TraceEventHandle TraceLog::AddTraceEventWithProcessId(
char phase,
const unsigned char* category_group_enabled,
const char* name,
const char* scope,
unsigned long long id,
int process_id,
int num_args,
const char** arg_names,
const unsigned char* arg_types,
const unsigned long long* arg_values,
std::unique_ptr<ConvertableToTraceFormat>* convertable_values,
unsigned int flags) {
base::TimeTicks now = base::TimeTicks::Now();
return AddTraceEventWithThreadIdAndTimestamp(
phase,
category_group_enabled,
name,
scope,
id,
trace_event_internal::kNoId, // bind_id
process_id,
now,
num_args,
arg_names,
arg_types,
arg_values,
convertable_values,
flags | TRACE_EVENT_FLAG_HAS_PROCESS_ID);
}
// Handle legacy calls to AddTraceEventWithThreadIdAndTimestamp
// with kNoId as bind_id
TraceEventHandle TraceLog::AddTraceEventWithThreadIdAndTimestamp(
char phase,
const unsigned char* category_group_enabled,
const char* name,
const char* scope,
unsigned long long id,
int thread_id,
const TimeTicks& timestamp,
int num_args,
const char** arg_names,
const unsigned char* arg_types,
const unsigned long long* arg_values,
std::unique_ptr<ConvertableToTraceFormat>* convertable_values,
unsigned int flags) {
return AddTraceEventWithThreadIdAndTimestamp(
phase,
category_group_enabled,
name,
scope,
id,
trace_event_internal::kNoId, // bind_id
thread_id,
timestamp,
num_args,
arg_names,
arg_types,
arg_values,
convertable_values,
flags);
}
TraceEventHandle TraceLog::AddTraceEventWithThreadIdAndTimestamp(
char phase,
const unsigned char* category_group_enabled,
const char* name,
const char* scope,
unsigned long long id,
unsigned long long bind_id,
int thread_id,
const TimeTicks& timestamp,
int num_args,
const char** arg_names,
const unsigned char* arg_types,
const unsigned long long* arg_values,
std::unique_ptr<ConvertableToTraceFormat>* convertable_values,
unsigned int flags) {
TraceEventHandle handle = {0, 0, 0};
if (!*category_group_enabled)
return handle;
// Avoid re-entrance of AddTraceEvent. This may happen in GPU process when
// ECHO_TO_CONSOLE is enabled: AddTraceEvent -> LOG(ERROR) ->
// GpuProcessLogMessageHandler -> PostPendingTask -> TRACE_EVENT ...
if (thread_is_in_trace_event_.Get())
return handle;
AutoThreadLocalBoolean thread_is_in_trace_event(&thread_is_in_trace_event_);
DCHECK(name);
DCHECK(!timestamp.is_null());
if (flags & TRACE_EVENT_FLAG_MANGLE_ID) {
if ((flags & TRACE_EVENT_FLAG_FLOW_IN) ||
(flags & TRACE_EVENT_FLAG_FLOW_OUT))
bind_id = MangleEventId(bind_id);
id = MangleEventId(id);
}
TimeTicks offset_event_timestamp = OffsetTimestamp(timestamp);
ThreadTicks thread_now = ThreadNow();
// |thread_local_event_buffer_| can be null if the current thread doesn't have
// a message loop or the message loop is blocked.
InitializeThreadLocalEventBufferIfSupported();
auto thread_local_event_buffer = thread_local_event_buffer_.Get();
// Check and update the current thread name only if the event is for the
// current thread to avoid locks in most cases.
if (thread_id == static_cast<int>(PlatformThread::CurrentId())) {
const char* new_name =
ThreadIdNameManager::GetInstance()->GetName(thread_id);
// Check if the thread name has been set or changed since the previous
// call (if any), but don't bother if the new name is empty. Note this will
// not detect a thread name change within the same char* buffer address: we
// favor common case performance over corner case correctness.
if (new_name != g_current_thread_name.Get().Get() && new_name &&
*new_name) {
g_current_thread_name.Get().Set(new_name);
AutoLock thread_info_lock(thread_info_lock_);
hash_map<int, std::string>::iterator existing_name =
thread_names_.find(thread_id);
if (existing_name == thread_names_.end()) {
// This is a new thread id, and a new name.
thread_names_[thread_id] = new_name;
} else {
// This is a thread id that we've seen before, but potentially with a
// new name.
std::vector<StringPiece> existing_names = base::SplitStringPiece(
existing_name->second, ",", base::KEEP_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
bool found = std::find(existing_names.begin(), existing_names.end(),
new_name) != existing_names.end();
if (!found) {
if (existing_names.size())
existing_name->second.push_back(',');
existing_name->second.append(new_name);
}
}
}
}
#if defined(OS_WIN)
// This is done sooner rather than later, to avoid creating the event and
// acquiring the lock, which is not needed for ETW as it's already threadsafe.
if (*category_group_enabled & ENABLED_FOR_ETW_EXPORT)
TraceEventETWExport::AddEvent(phase, category_group_enabled, name, id,
num_args, arg_names, arg_types, arg_values,
convertable_values);
#endif // OS_WIN
std::string console_message;
if (*category_group_enabled & ENABLED_FOR_RECORDING) {
OptionalAutoLock lock(&lock_);
TraceEvent* trace_event = NULL;
if (thread_local_event_buffer) {
trace_event = thread_local_event_buffer->AddTraceEvent(&handle);
} else {
lock.EnsureAcquired();
trace_event = AddEventToThreadSharedChunkWhileLocked(&handle, true);
}
if (trace_event) {
trace_event->Initialize(thread_id,
offset_event_timestamp,
thread_now,
phase,
category_group_enabled,
name,
scope,
id,
bind_id,
num_args,
arg_names,
arg_types,
arg_values,
convertable_values,
flags);
#if defined(OS_ANDROID)
trace_event->SendToATrace();
#endif
}
if (trace_options() & kInternalEchoToConsole) {
console_message = EventToConsoleMessage(
phase == TRACE_EVENT_PHASE_COMPLETE ? TRACE_EVENT_PHASE_BEGIN : phase,
timestamp, trace_event);
}
}
if (console_message.size())
LOG(ERROR) << console_message;
if (reinterpret_cast<const unsigned char*>(
subtle::NoBarrier_Load(&watch_category_)) == category_group_enabled) {
bool event_name_matches;
WatchEventCallback watch_event_callback_copy;
{
AutoLock lock(lock_);
event_name_matches = watch_event_name_ == name;
watch_event_callback_copy = watch_event_callback_;
}
if (event_name_matches) {
if (!watch_event_callback_copy.is_null())
watch_event_callback_copy.Run();
}
}
if (*category_group_enabled & ENABLED_FOR_EVENT_CALLBACK) {
EventCallback event_callback = reinterpret_cast<EventCallback>(
subtle::NoBarrier_Load(&event_callback_));
if (event_callback) {
event_callback(
offset_event_timestamp,
phase == TRACE_EVENT_PHASE_COMPLETE ? TRACE_EVENT_PHASE_BEGIN : phase,
category_group_enabled, name, scope, id, num_args, arg_names,
arg_types, arg_values, flags);
}
}
// TODO(primiano): Add support for events with copied name crbug.com/581078
if (!(flags & TRACE_EVENT_FLAG_COPY)) {
if (AllocationContextTracker::capture_enabled()) {
if (phase == TRACE_EVENT_PHASE_BEGIN ||
phase == TRACE_EVENT_PHASE_COMPLETE) {
AllocationContextTracker::GetInstanceForCurrentThread()
->PushPseudoStackFrame(name);
} else if (phase == TRACE_EVENT_PHASE_END)
// The pop for |TRACE_EVENT_PHASE_COMPLETE| events
// is in |TraceLog::UpdateTraceEventDuration|.
AllocationContextTracker::GetInstanceForCurrentThread()
->PopPseudoStackFrame(name);
}
}
return handle;
}
void TraceLog::AddMetadataEvent(
const unsigned char* category_group_enabled,
const char* name,
int num_args,
const char** arg_names,
const unsigned char* arg_types,
const unsigned long long* arg_values,
std::unique_ptr<ConvertableToTraceFormat>* convertable_values,
unsigned int flags) {
HEAP_PROFILER_SCOPED_IGNORE;
std::unique_ptr<TraceEvent> trace_event(new TraceEvent);
int thread_id = static_cast<int>(base::PlatformThread::CurrentId());
ThreadTicks thread_now = ThreadNow();
TimeTicks now = OffsetNow();
AutoLock lock(lock_);
trace_event->Initialize(
thread_id, now, thread_now, TRACE_EVENT_PHASE_METADATA,
category_group_enabled, name,
trace_event_internal::kGlobalScope, // scope
trace_event_internal::kNoId, // id
trace_event_internal::kNoId, // bind_id
num_args, arg_names, arg_types, arg_values, convertable_values, flags);
metadata_events_.push_back(std::move(trace_event));
}
// May be called when a COMPELETE event ends and the unfinished event has been
// recycled (phase == TRACE_EVENT_PHASE_END and trace_event == NULL).
std::string TraceLog::EventToConsoleMessage(unsigned char phase,
const TimeTicks& timestamp,
TraceEvent* trace_event) {
HEAP_PROFILER_SCOPED_IGNORE;
AutoLock thread_info_lock(thread_info_lock_);
// The caller should translate TRACE_EVENT_PHASE_COMPLETE to
// TRACE_EVENT_PHASE_BEGIN or TRACE_EVENT_END.
DCHECK(phase != TRACE_EVENT_PHASE_COMPLETE);
TimeDelta duration;
int thread_id =
trace_event ? trace_event->thread_id() : PlatformThread::CurrentId();
if (phase == TRACE_EVENT_PHASE_END) {
duration = timestamp - thread_event_start_times_[thread_id].top();
thread_event_start_times_[thread_id].pop();
}
std::string thread_name = thread_names_[thread_id];
if (thread_colors_.find(thread_name) == thread_colors_.end())
thread_colors_[thread_name] = (thread_colors_.size() % 6) + 1;
std::ostringstream log;
log << base::StringPrintf("%s: \x1b[0;3%dm", thread_name.c_str(),
thread_colors_[thread_name]);
size_t depth = 0;
if (thread_event_start_times_.find(thread_id) !=
thread_event_start_times_.end())
depth = thread_event_start_times_[thread_id].size();
for (size_t i = 0; i < depth; ++i)
log << "| ";
if (trace_event)
trace_event->AppendPrettyPrinted(&log);
if (phase == TRACE_EVENT_PHASE_END)
log << base::StringPrintf(" (%.3f ms)", duration.InMillisecondsF());
log << "\x1b[0;m";
if (phase == TRACE_EVENT_PHASE_BEGIN)
thread_event_start_times_[thread_id].push(timestamp);
return log.str();
}
void TraceLog::UpdateTraceEventDuration(
const unsigned char* category_group_enabled,
const char* name,
TraceEventHandle handle) {
char category_group_enabled_local = *category_group_enabled;
if (!category_group_enabled_local)
return;
// Avoid re-entrance of AddTraceEvent. This may happen in GPU process when
// ECHO_TO_CONSOLE is enabled: AddTraceEvent -> LOG(ERROR) ->
// GpuProcessLogMessageHandler -> PostPendingTask -> TRACE_EVENT ...
if (thread_is_in_trace_event_.Get())
return;
AutoThreadLocalBoolean thread_is_in_trace_event(&thread_is_in_trace_event_);
ThreadTicks thread_now = ThreadNow();
TimeTicks now = OffsetNow();
#if defined(OS_WIN)
// Generate an ETW event that marks the end of a complete event.
if (category_group_enabled_local & ENABLED_FOR_ETW_EXPORT)
TraceEventETWExport::AddCompleteEndEvent(name);
#endif // OS_WIN
std::string console_message;
if (category_group_enabled_local & ENABLED_FOR_RECORDING) {
OptionalAutoLock lock(&lock_);
TraceEvent* trace_event = GetEventByHandleInternal(handle, &lock);
if (trace_event) {
DCHECK(trace_event->phase() == TRACE_EVENT_PHASE_COMPLETE);
trace_event->UpdateDuration(now, thread_now);
#if defined(OS_ANDROID)
trace_event->SendToATrace();
#endif
}
if (trace_options() & kInternalEchoToConsole) {
console_message =
EventToConsoleMessage(TRACE_EVENT_PHASE_END, now, trace_event);
}
if (base::trace_event::AllocationContextTracker::capture_enabled()) {
// The corresponding push is in |AddTraceEventWithThreadIdAndTimestamp|.
base::trace_event::AllocationContextTracker::GetInstanceForCurrentThread()
->PopPseudoStackFrame(name);
}
}
if (console_message.size())
LOG(ERROR) << console_message;
if (category_group_enabled_local & ENABLED_FOR_EVENT_CALLBACK) {
EventCallback event_callback = reinterpret_cast<EventCallback>(
subtle::NoBarrier_Load(&event_callback_));
if (event_callback) {
event_callback(
now, TRACE_EVENT_PHASE_END, category_group_enabled, name,
trace_event_internal::kGlobalScope, trace_event_internal::kNoId, 0,
nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
}
}
}
void TraceLog::SetWatchEvent(const std::string& category_name,
const std::string& event_name,
const WatchEventCallback& callback) {
const unsigned char* category =
GetCategoryGroupEnabled(category_name.c_str());
AutoLock lock(lock_);
subtle::NoBarrier_Store(&watch_category_,
reinterpret_cast<subtle::AtomicWord>(category));
watch_event_name_ = event_name;
watch_event_callback_ = callback;
}
void TraceLog::CancelWatchEvent() {
AutoLock lock(lock_);
subtle::NoBarrier_Store(&watch_category_, 0);
watch_event_name_ = "";
watch_event_callback_.Reset();
}
uint64_t TraceLog::MangleEventId(uint64_t id) {
return id ^ process_id_hash_;
}
void TraceLog::AddMetadataEventsWhileLocked() {
lock_.AssertAcquired();
// Move metadata added by |AddMetadataEvent| into the trace log.
while (!metadata_events_.empty()) {
TraceEvent* event = AddEventToThreadSharedChunkWhileLocked(nullptr, false);
event->MoveFrom(std::move(metadata_events_.back()));
metadata_events_.pop_back();
}
#if !defined(OS_NACL) // NaCl shouldn't expose the process id.
InitializeMetadataEvent(AddEventToThreadSharedChunkWhileLocked(NULL, false),
0, "num_cpus", "number",
base::SysInfo::NumberOfProcessors());
#endif
int current_thread_id = static_cast<int>(base::PlatformThread::CurrentId());
if (process_sort_index_ != 0) {
InitializeMetadataEvent(AddEventToThreadSharedChunkWhileLocked(NULL, false),
current_thread_id, "process_sort_index",
"sort_index", process_sort_index_);
}
if (process_name_.size()) {
InitializeMetadataEvent(AddEventToThreadSharedChunkWhileLocked(NULL, false),
current_thread_id, "process_name", "name",
process_name_);
}
if (process_labels_.size() > 0) {
std::vector<std::string> labels;
for (base::hash_map<int, std::string>::iterator it =
process_labels_.begin();
it != process_labels_.end(); it++) {
labels.push_back(it->second);
}
InitializeMetadataEvent(AddEventToThreadSharedChunkWhileLocked(NULL, false),
current_thread_id, "process_labels", "labels",
base::JoinString(labels, ","));
}
// Thread sort indices.
for (hash_map<int, int>::iterator it = thread_sort_indices_.begin();
it != thread_sort_indices_.end(); it++) {
if (it->second == 0)
continue;
InitializeMetadataEvent(AddEventToThreadSharedChunkWhileLocked(NULL, false),
it->first, "thread_sort_index", "sort_index",
it->second);
}
// Thread names.
AutoLock thread_info_lock(thread_info_lock_);
for (hash_map<int, std::string>::iterator it = thread_names_.begin();
it != thread_names_.end(); it++) {
if (it->second.empty())
continue;
InitializeMetadataEvent(AddEventToThreadSharedChunkWhileLocked(NULL, false),
it->first, "thread_name", "name", it->second);
}
// If buffer is full, add a metadata record to report this.
if (!buffer_limit_reached_timestamp_.is_null()) {
InitializeMetadataEvent(AddEventToThreadSharedChunkWhileLocked(NULL, false),
current_thread_id, "trace_buffer_overflowed",
"overflowed_at_ts",
buffer_limit_reached_timestamp_);
}
}
void TraceLog::WaitSamplingEventForTesting() {
if (!sampling_thread_)
return;
sampling_thread_->WaitSamplingEventForTesting();
}
void TraceLog::DeleteForTesting() {
internal::DeleteTraceLogForTesting::Delete();
}
TraceEvent* TraceLog::GetEventByHandle(TraceEventHandle handle) {
return GetEventByHandleInternal(handle, NULL);
}
TraceEvent* TraceLog::GetEventByHandleInternal(TraceEventHandle handle,
OptionalAutoLock* lock) {
if (!handle.chunk_seq)
return NULL;
if (thread_local_event_buffer_.Get()) {
TraceEvent* trace_event =
thread_local_event_buffer_.Get()->GetEventByHandle(handle);
if (trace_event)
return trace_event;
}
// The event has been out-of-control of the thread local buffer.
// Try to get the event from the main buffer with a lock.
if (lock)
lock->EnsureAcquired();
if (thread_shared_chunk_ &&
handle.chunk_index == thread_shared_chunk_index_) {
return handle.chunk_seq == thread_shared_chunk_->seq()
? thread_shared_chunk_->GetEventAt(handle.event_index)
: NULL;
}
return logged_events_->GetEventByHandle(handle);
}
void TraceLog::SetProcessID(int process_id) {
process_id_ = process_id;
// Create a FNV hash from the process ID for XORing.
// See http://isthe.com/chongo/tech/comp/fnv/ for algorithm details.
unsigned long long offset_basis = 14695981039346656037ull;
unsigned long long fnv_prime = 1099511628211ull;
unsigned long long pid = static_cast<unsigned long long>(process_id_);
process_id_hash_ = (offset_basis ^ pid) * fnv_prime;
}
void TraceLog::SetProcessSortIndex(int sort_index) {
AutoLock lock(lock_);
process_sort_index_ = sort_index;
}
void TraceLog::SetProcessName(const std::string& process_name) {
AutoLock lock(lock_);
process_name_ = process_name;
}
void TraceLog::UpdateProcessLabel(int label_id,
const std::string& current_label) {
if (!current_label.length())
return RemoveProcessLabel(label_id);
AutoLock lock(lock_);
process_labels_[label_id] = current_label;
}
void TraceLog::RemoveProcessLabel(int label_id) {
AutoLock lock(lock_);
base::hash_map<int, std::string>::iterator it =
process_labels_.find(label_id);
if (it == process_labels_.end())
return;
process_labels_.erase(it);
}
void TraceLog::SetThreadSortIndex(PlatformThreadId thread_id, int sort_index) {
AutoLock lock(lock_);
thread_sort_indices_[static_cast<int>(thread_id)] = sort_index;
}
void TraceLog::SetTimeOffset(TimeDelta offset) {
time_offset_ = offset;
}
size_t TraceLog::GetObserverCountForTest() const {
return enabled_state_observer_list_.size();
}
void TraceLog::SetCurrentThreadBlocksMessageLoop() {
thread_blocks_message_loop_.Set(true);
if (thread_local_event_buffer_.Get()) {
// This will flush the thread local buffer.
delete thread_local_event_buffer_.Get();
}
}
TraceBuffer* TraceLog::CreateTraceBuffer() {
HEAP_PROFILER_SCOPED_IGNORE;
InternalTraceOptions options = trace_options();
if (options & kInternalRecordContinuously)
return TraceBuffer::CreateTraceBufferRingBuffer(
kTraceEventRingBufferChunks);
else if (options & kInternalEchoToConsole)
return TraceBuffer::CreateTraceBufferRingBuffer(
kEchoToConsoleTraceEventBufferChunks);
else if (options & kInternalRecordAsMuchAsPossible)
return TraceBuffer::CreateTraceBufferVectorOfSize(
kTraceEventVectorBigBufferChunks);
return TraceBuffer::CreateTraceBufferVectorOfSize(
kTraceEventVectorBufferChunks);
}
#if defined(OS_WIN)
void TraceLog::UpdateETWCategoryGroupEnabledFlags() {
AutoLock lock(lock_);
size_t category_index = base::subtle::NoBarrier_Load(&g_category_index);
// Go through each category and set/clear the ETW bit depending on whether the
// category is enabled.
for (size_t i = 0; i < category_index; i++) {
const char* category_group = g_category_groups[i];
DCHECK(category_group);
if (base::trace_event::TraceEventETWExport::IsCategoryGroupEnabled(
category_group)) {
g_category_group_enabled[i] |= ENABLED_FOR_ETW_EXPORT;
} else {
g_category_group_enabled[i] &= ~ENABLED_FOR_ETW_EXPORT;
}
}
}
#endif // defined(OS_WIN)
void ConvertableToTraceFormat::EstimateTraceMemoryOverhead(
TraceEventMemoryOverhead* overhead) {
overhead->Add("ConvertableToTraceFormat(Unknown)", sizeof(*this));
}
} // namespace trace_event
} // namespace base
namespace trace_event_internal {
ScopedTraceBinaryEfficient::ScopedTraceBinaryEfficient(
const char* category_group,
const char* name) {
// The single atom works because for now the category_group can only be "gpu".
DCHECK_EQ(strcmp(category_group, "gpu"), 0);
static TRACE_EVENT_API_ATOMIC_WORD atomic = 0;
INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO_CUSTOM_VARIABLES(
category_group, atomic, category_group_enabled_);
name_ = name;
if (*category_group_enabled_) {
event_handle_ =
TRACE_EVENT_API_ADD_TRACE_EVENT_WITH_THREAD_ID_AND_TIMESTAMP(
TRACE_EVENT_PHASE_COMPLETE,
category_group_enabled_,
name,
trace_event_internal::kGlobalScope, // scope
trace_event_internal::kNoId, // id
static_cast<int>(base::PlatformThread::CurrentId()), // thread_id
base::TimeTicks::Now(),
trace_event_internal::kZeroNumArgs,
nullptr,
nullptr,
nullptr,
nullptr,
TRACE_EVENT_FLAG_NONE);
}
}
ScopedTraceBinaryEfficient::~ScopedTraceBinaryEfficient() {
if (*category_group_enabled_) {
TRACE_EVENT_API_UPDATE_TRACE_EVENT_DURATION(category_group_enabled_, name_,
event_handle_);
}
}
} // namespace trace_event_internal
| golden1232004/webrtc_new | chromium/src/base/trace_event/trace_log.cc | C++ | gpl-3.0 | 59,466 |
/*******************************************************************************
* Copyright (c) 2008,2010 itemis AG (http://www.itemis.eu) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.emf.mwe2.runtime;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Matches {
String value();
}
| HelgeDMI/trollflow | java/org.eclipse.emf.mwe2.runtime.source_2.7.0.v201409021027/org/eclipse/emf/mwe2/runtime/Matches.java | Java | gpl-3.0 | 796 |
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* MultiHandler.java
* Copyright (C) 2017 University of Waikato, Hamilton, NZ
*/
package adams.core.logging;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
/**
* Combines multiple handlers.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class MultiHandler
extends AbstractLogHandler {
/** the logging handlers to use. */
protected Handler[] m_Handlers;
/**
* Initializes the members.
*/
@Override
protected void initialize() {
super.initialize();
setHandlers(new Handler[0]);
}
/**
* Sets the handlers to use.
*
* @param value the handlers
*/
public void setHandlers(Handler[] value) {
m_Handlers = value;
reset();
}
/**
* Returns the current handlers.
*
* @return the handlers
*/
public Handler[] getHandlers() {
return m_Handlers;
}
/**
* Adds the specified handler.
*
* @param value the handler
*/
public void addHandler(Handler value) {
Handler[] handlers;
int i;
handlers = new Handler[m_Handlers.length + 1];
for (i = 0; i < m_Handlers.length; i++)
handlers[i] = m_Handlers[i];
handlers[handlers.length - 1] = value;
m_Handlers = handlers;
}
/**
* Removes the specified handler.
*
* @param index the handler index
*/
public void removeHandler(int index) {
Handler[] handlers;
int i;
int n;
handlers = new Handler[m_Handlers.length - 1];
n = 0;
for (i = 0; i < m_Handlers.length; i++) {
if (i == index)
continue;
handlers[n] = m_Handlers[i];
n++;
}
m_Handlers = handlers;
}
/**
* Flush any buffered output.
*/
@Override
public void flush() {
super.flush();
if (m_Handlers != null) {
for (Handler h : m_Handlers)
h.flush();
}
}
/**
* Close the <tt>Handler</tt> and free all associated resources.
* <p>
* The close method will perform a <tt>flush</tt> and then close the
* <tt>Handler</tt>. After close has been called this <tt>Handler</tt>
* should no longer be used. Method calls may either be silently
* ignored or may throw runtime exceptions.
*
* @exception SecurityException if a security manager exists and if
* the caller does not have <tt>LoggingPermission("control")</tt>.
*/
@Override
public void close() throws SecurityException {
if (m_Handlers != null) {
for (Handler h : m_Handlers)
h.close();
}
super.close();
}
/**
* Publish a <tt>LogRecord</tt>.
* <p>
* The logging request was made initially to a <tt>Logger</tt> object,
* which initialized the <tt>LogRecord</tt> and forwarded it here.
* <p>
* The <tt>Handler</tt> is responsible for formatting the message, when and
* if necessary. The formatting should include localization.
*
* @param record description of the log event. A null record is
* silently ignored and is not published
*/
@Override
protected void doPublish(LogRecord record) {
for (Handler h: m_Handlers)
h.publish(record);
}
/**
* Compares the handler with itself.
*
* @param o the other handler
* @return less than 0, equal to 0, or greater than 0 if the
* handler is less, equal to, or greater than this one
*/
public int compareTo(Handler o) {
int result;
MultiHandler other;
int i;
result = super.compareTo(o);
if (result == 0) {
other = (MultiHandler) o;
result = new Integer(getHandlers().length).compareTo(other.getHandlers().length);
if (result == 0) {
for (i = 0; i < getHandlers().length; i++) {
if ((getHandlers()[i] instanceof AbstractLogHandler) && (other.getHandlers()[i] instanceof AbstractLogHandler))
result = ((AbstractLogHandler) getHandlers()[i]).compareTo(other.getHandlers()[i]);
else
result = new Integer(getHandlers()[i].hashCode()).compareTo(other.getHandlers()[i].hashCode());
if (result != 0)
break;
}
}
}
return result;
}
}
| waikato-datamining/adams-base | adams-core/src/main/java/adams/core/logging/MultiHandler.java | Java | gpl-3.0 | 4,758 |
package org.saga.shape;
import org.bukkit.Material;
import org.bukkit.block.Block;
import java.util.HashSet;
public class BlockFilter implements ShapeFilter {
/**
* Materials.
*/
private HashSet<Material> materials = new HashSet<>();
/**
* If true then the check will return the reverse result.
*/
private boolean flip = false;
// Initialisation:
/**
* Initialises.
*
*/
public BlockFilter() {
}
/**
* Adds a material.
*
* @param material
* material
*/
public void addMaterial(Material material) {
materials.add(material);
}
/**
* Flips the check result.
*
*/
public void flip() {
flip = true;
}
// Filtering:
/*
* (non-Javadoc)
*
* @see org.saga.shape.ShapeFilter#checkBlock(org.bukkit.block.Block)
*/
@Override
public boolean checkBlock(Block block) {
if (flip)
return !materials.contains(block.getType());
return materials.contains(block.getType());
}
}
| Olyol95/Saga | src/org/saga/shape/BlockFilter.java | Java | gpl-3.0 | 957 |
package org.activityinfo.ui.client.component.importDialog.validation;
/*
* #%L
* ActivityInfo Server
* %%
* Copyright (C) 2009 - 2013 UNICEF
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.TextHeader;
import com.google.gwt.user.client.ui.ResizeComposite;
import org.activityinfo.core.shared.importing.validation.ValidationResult;
import org.activityinfo.i18n.shared.I18N;
import org.activityinfo.ui.client.style.table.DataGridResources;
import java.util.List;
/**
* @author yuriyz on 4/30/14.
*/
public class ValidationMappingGrid extends ResizeComposite {
private DataGrid<ValidationResult> dataGrid;
public ValidationMappingGrid() {
this.dataGrid = new DataGrid<>(100, DataGridResources.INSTANCE);
dataGrid.addColumn(new ValidationClassGridColumn(), new TextHeader(I18N.CONSTANTS.message()));
initWidget(dataGrid);
}
public void refresh(List<ValidationResult> resultList) {
dataGrid.setRowData(resultList);
}
}
| LeoTremblay/activityinfo | server/src/main/java/org/activityinfo/ui/client/component/importDialog/validation/ValidationMappingGrid.java | Java | gpl-3.0 | 1,707 |
/*******************************************************************************
* Copyright (c) 2011-2014 SirSengir.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Various Contributors including, but not limited to:
* SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges
******************************************************************************/
package forestry.apiculture.gui;
import net.minecraft.entity.player.InventoryPlayer;
import forestry.apiculture.multiblock.TileAlvearyPlain;
import forestry.core.gui.ContainerTile;
import forestry.core.network.PacketGuiUpdate;
public class ContainerAlveary extends ContainerTile<TileAlvearyPlain> {
public ContainerAlveary(InventoryPlayer player, TileAlvearyPlain tile) {
super(tile, player, 8, 108);
ContainerBeeHelper.addSlots(this, tile, false);
}
@Override
public void detectAndSendChanges() {
super.detectAndSendChanges();
PacketGuiUpdate packet = new PacketGuiUpdate(tile);
sendPacketToCrafters(packet);
}
}
| AnodeCathode/ForestryMC | src/main/java/forestry/apiculture/gui/ContainerAlveary.java | Java | gpl-3.0 | 1,213 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Xml;
using System.Diagnostics;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace RunMusicOpenWPF {
public partial class AppCenter {
public static readonly string resPath = AppDomain.CurrentDomain.BaseDirectory + "Data\\";
public List<SoTrack> trackList; //Czy jest to dalej potrzebne?
public int trackIndex {
get { return save.trackIndex; }
set { save.trackIndex = value; }
}
public Save save;
public ISubValue TypRun;
public AppCenter() {
save.trackIndex = 0;
}
public AppCenter(ISubValue nextRun, Save save) {
TypRun = nextRun;
this.save = save;
}
/// <summary>
/// z pliku tracklist.JSON tworzy i wczytuje całą listę do obiektu TrackList
/// </summary>
public void LoadTrackList() {
if (trackList != null) return;
trackList = new List<SoTrack>();
JArray trackarray = JsonConvert.DeserializeObject<JArray>(File.ReadAllText(Save.tracklistlocation));
for(int i = 0; i < trackarray.Count; i++) {
string Name = (string)trackarray[i]["Name"];
string Adres = (string)trackarray[i]["Adres"];
int Votes = (int)trackarray[i]["Votes"];
trackList.Add(SoTrack.Create(Name,Votes,Adres));
}
trackList.Sort((x, y) =>
{
return y.Votes.CompareTo(x.Votes);
});
}
public void LoadTrackToListView(ListView listview) {
listview.Items.Clear();
for (int x = 0; x < trackList.Count; x++)
listview.Items.Add(trackList[x]);
}
/// <summary>
/// Ustawia główny Indeks na następny utwór na liście TrackList
/// </summary>
public void NextIndexTrack() {
if (trackIndex == trackList.Count - 1) {
trackIndex = -1;
}
trackIndex++;
}
}
}
| Dorion300/PlaylistMusicRun | RunMusicOpenWPF/Center/AppCenter.cs | C# | gpl-3.0 | 2,254 |