code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
<?php
/**
* @package Joomla.Administrator
* @subpackage com_sciclubpadova
*
* @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
/**
* SciClubPadova Model
*
* @since 0.0.1
*/
class SciClubPadovaModelSciClubPadova extends JModelItem
{
/**
* @var object item
*/
protected $item;
/**
* Method to auto-populate the model state.
*
* This method should only be called once per instantiation and is designed
* to be called on the first call to the getState() method unless the model
* configuration flag to ignore the request is set.
*
* Note. Calling getState in this method will result in recursion.
*
* @return void
* @since 2.5
*/
protected function populateState()
{
// Get the message id
$jinput = JFactory::getApplication()->input;
$id = $jinput->get('id', 1, 'INT');
$this->setState('message.id', $id);
// Load the parameters.
$this->setState('params', JFactory::getApplication()->getParams());
parent::populateState();
}
/**
* Method to get a table object, load it if necessary.
*
* @param string $type The table name. Optional.
* @param string $prefix The class prefix. Optional.
* @param array $config Configuration array for model. Optional.
*
* @return JTable A JTable object
*
* @since 1.6
*/
public function getTable($type = 'SciClubPadova', $prefix = 'SciClubPadovaTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
/**
* Get the message
* @return object The message to be displayed to the user
*/
public function getItem()
{
if (!isset($this->item))
{
$id = $this->getState('message.id');
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('h.greeting, h.params, c.title as category')
->from('#__sciclubpadova as h')
->leftJoin('#__categories as c ON h.catid=c.id')
->where('h.id=' . (int)$id);
$db->setQuery((string)$query);
if ($this->item = $db->loadObject())
{
// Load the JSON string
$params = new JRegistry;
$params->loadString($this->item->params, 'JSON');
$this->item->params = $params;
// Merge global params with item params
$params = clone $this->getState('params');
$params->merge($this->item->params);
$this->item->params = $params;
}
}
return $this->item;
}
}
| Java |
body {
word-wrap: break-word;
word-break: break-all;
padding: 2px 5px;
background-color: #FFFFFF;
color: #000000;
max-width: 1024px;
margin: 0px auto;
box-shadow: 0 0 15px #ccc;
tab-size: 4; -moz-tab-size: 4; -o-tab-size: 4; -webkit-tab-size: 4;
}
p, div {
overflow: hidden;
}
p {
margin: 0px;
padding: 2px 1px 2px 1px;
}
.tp {
margin: 0px;
background-color: #E6F3FF;
}
a {
text-decoration: none;
color: #08C;
}
form {
margin: 0px;
padding: 0px;
}
img, input, textarea {
max-width: 100%;
vertical-align: middle;
}
hr {
height: 1px;
border: 1px solid #BED8EA;
border-left: none;
border-right: none;
}
textarea {
width: 270px;
height: 55px;
overflow-y: visible;
}
pre, textarea {
white-space: pre-wrap;
word-wrap: break-word;
word-break: break-all;
}
ol, ul {
margin: 0px;
}
.success {
color: green;
}
.failure {
color: red;
}
.notice {
color: red;
}
img {
max-width: 100%;
}
.info-box {
text-align: center;
border: solid red 1px;
}
.video {
width: 600px;
height: 400px;
border: none;
max-width: 100%;
}
.audio {
width: 600px;
border: none;
max-width: 100%;
}
#content_title {
width: 270px;
max-width: 100%;
}
/* 针对电脑屏幕 */
@media screen and (min-width: 800px) {
img {
max-width: 800px;
max-height: 600px;
}
}
/* 小说阅读器 */
.topic-ul {
list-style-type: none;
padding: 0;
}
.topic-ul > li {
padding: 5px 10px 2px 10px;
border-bottom: 1px solid #EEE;
display: flex;
align-items: center;
justify-content: space-between;
}
.topic-ul > li .topic-meta {
margin: 0px;
}
.topic-ul > li .topic-reply-count {
width: 5%;
display: flex;
font-weight: 300;
font-size: 30px;
color: gray;
}
.topic-ul > li .topic-reply-count a {
color: gray;
}
.topic-ul > li .topic-forum-name {
width: 15%;
display: flex;
}
.topic-ul > li .topic-forum-name a {
color: gray;
}
.topic-ul > li .topic-anchor {
width: 20%;
display: flex;
flex-direction: column;
align-items: center;
word-break: break-all;
}
.topic-ul > li .topic-anchor > a {
color: gray;
}
.topic-ul > li .topic-title {
width: 60%;
display: flex;
flex-direction: column;
justify-content: center;
}
.topic-ul > li .topic-title > a {
font-size: 18px;
display: block;
}
.page-jumper {
overflow: hidden;
display: inline-flex;
flex-wrap: wrap;
align-content: center;
padding-left: 2px;
margin: 10px 0 0 20px;
}
.page-jumper > li {
display: inline-block;
}
.page-jumper > li > input {
height: 22px;
width: 38px;
position: relative;
margin-left: -1px;
display: block;
padding: 5px 10px;
border: 1px solid #ddd;
border-radius: 5px;
color: #337ab7;
}
.pagination {
overflow: hidden;
display: inline-flex;
flex-wrap: wrap;
align-content: center;
padding-left: 2px;
margin: 10px 0 0 20px;
}
.pagination > li {
display: inline-block;
}
.pagination > li:first-child > a {
border-radius: 5px 0 0 5px;
}
.pagination > li:last-child > a {
border-radius: 0 5px 5px 0;
}
.pagination > li > a {
position: relative;
margin-left: -1px;
display: block;
padding: 5px 10px;
border: 1px solid #ddd;
color: #337ab7;
}
.pagination > .disabled > a {
color: #777;
cursor: not-allowed;
background-color: #fff;
}
.pagination > .disabled > a:focus {
color: #777;
cursor: not-allowed;
background-color: #fff;
}
.pagination > .disabled > a:hover {
color: #777;
cursor: not-allowed;
background-color: #fff;
}
.pagination > .active > a {
color: #fff;
cursor: default;
background-color: #337ab7;
border-color: #337ab7;
}
.pagination > .active > a:focus {
color: #fff;
cursor: default;
background-color: #337ab7;
border-color: #337ab7;
}
.pagination > .active > a:hover {
color: #fff;
cursor: default;
background-color: #337ab7;
border-color: #337ab7;
}
@media screen and (max-width: 600px) {
.topic-ul > li .topic-reply-count {
display: block;
}
.topic-ul > li .topic-reply-count .number {
display: block;
font-size: 14px;
}
.topic-ul > li .topic-reply-count .spliter {
display: none;
}
.topic-ul > li .topic-reply-count .forum {
display: block;
font-size: 14px;
}
.topic-ul > li .topic-anchor > a {
font-size: 14px;
}
.topic-ul > li .topic-title > a {
font-size: 16px;
}
.topic-ul > li .topic-reply-count {
display: none;
}
.topic-ul > li .topic-forum-name {
display: none;
}
.topic-ul > li .topic-title {
width: 80%;
}
}
/* 关注与屏蔽列表样式 */
.relationship-wrapper .empty {
width: 100%;
text-align: center;
color: #999fa5;
font-size: 14px;
}
.relationship-wrapper .user-item {
height: 60px;
color: #333333;
display: block;
border-bottom: 1px solid #f5f5f5;
}
.relationship-wrapper .user-item a {
text-decoration: none;
}
.relationship-wrapper .user-item a:nth-child(1) {
display: inline-block;
width: calc(100% - 60px);
}
.relationship-wrapper .user-item .avatar {
float: left;
height: 50px;
width: 50px;
margin-left: 20px;
margin-top: 5px;
display: inline-block;
border-radius: 50px;
}
.relationship-wrapper .user-item .info {
margin-left: 15px;
margin-top: 10px;
display: inline-block;
width: calc(100% - 100px);
}
.relationship-wrapper .user-item .info .name {
font-size: 18px;
}
.relationship-wrapper .user-item .info .signature {
color: #999fa5;
font-size: 12px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.relationship-wrapper .user-item .remove {
float: right;
height: 100%;
width: 60px;
display: inline-block;
padding-top: 20px;
color: #ff0000;
text-align: center;
}
/*回复列表中的区块引用*/
.reply-box blockquote {
background: #f9f9f9;
border-left: 10px solid #ccc;
margin: 1.5em 10px;
padding: 0.5em 10px;
max-height: 500px;
overflow: hidden;
text-overflow: ellipsis;
}
.reply-box blockquote:before {
color: #ccc;
font-size: 4em;
line-height: 0.1em;
margin-right: 0.25em;
vertical-align: -0.4em;
}
#searchType-label {
display: inline-block;
}
.hu60_face, #face img {
width: 32px;
max-width: 32px;
}
/*代码高亮*/
.hu60_code code, .markdown-body pre code {
white-space: pre-wrap !important;
word-wrap: break-word !important;
word-break: break-all !important;
}
.hu60_code code {
background-color: #f7f7f7;
}
| Java |
<?php
/** PHPExcel root directory */
if (!defined('PHPEXCEL_ROOT')) {
/**
* @ignore
*/
define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
}
/**
* PHPExcel_Reader_SYLK
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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 for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_Reader
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_Reader_SYLK extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader
{
/**
* Input encoding
*
* @var string
*/
private $inputEncoding = 'ANSI';
/**
* Sheet index to read
*
* @var int
*/
private $sheetIndex = 0;
/**
* Formats
*
* @var array
*/
private $formats = array();
/**
* Format Count
*
* @var int
*/
private $format = 0;
/**
* Create a new PHPExcel_Reader_SYLK
*/
public function __construct()
{
$this->readFilter = new PHPExcel_Reader_DefaultReadFilter();
}
/**
* Validate that the current file is a SYLK file
*
* @return boolean
*/
protected function isValidFormat()
{
// Read sample data (first 2 KB will do)
$data = fread($this->fileHandle, 2048);
// Count delimiters in file
$delimiterCount = substr_count($data, ';');
if ($delimiterCount < 1) {
return false;
}
// Analyze first line looking for ID; signature
$lines = explode("\n", $data);
if (substr($lines[0], 0, 4) != 'ID;P') {
return false;
}
return true;
}
/**
* Set input encoding
*
* @param string $pValue Input encoding
*/
public function setInputEncoding($pValue = 'ANSI')
{
$this->inputEncoding = $pValue;
return $this;
}
/**
* Get input encoding
*
* @return string
*/
public function getInputEncoding()
{
return $this->inputEncoding;
}
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
*
* @param string $pFilename
* @throws PHPExcel_Reader_Exception
*/
public function listWorksheetInfo($pFilename)
{
// Open file
$this->openFile($pFilename);
if (!$this->isValidFormat()) {
fclose($this->fileHandle);
throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->fileHandle;
rewind($fileHandle);
$worksheetInfo = array();
$worksheetInfo[0]['worksheetName'] = 'Worksheet';
$worksheetInfo[0]['lastColumnLetter'] = 'A';
$worksheetInfo[0]['lastColumnIndex'] = 0;
$worksheetInfo[0]['totalRows'] = 0;
$worksheetInfo[0]['totalColumns'] = 0;
// Loop through file
$rowData = array();
// loop through one row (line) at a time in the file
$rowIndex = 0;
while (($rowData = fgets($fileHandle)) !== false) {
$columnIndex = 0;
// convert SYLK encoded $rowData to UTF-8
$rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData);
// explode each row at semicolons while taking into account that literal semicolon (;)
// is escaped like this (;;)
$rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData)))));
$dataType = array_shift($rowData);
if ($dataType == 'C') {
// Read cell value data
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'C':
case 'X':
$columnIndex = substr($rowDatum, 1) - 1;
break;
case 'R':
case 'Y':
$rowIndex = substr($rowDatum, 1);
break;
}
$worksheetInfo[0]['totalRows'] = max($worksheetInfo[0]['totalRows'], $rowIndex);
$worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], $columnIndex);
}
}
}
$worksheetInfo[0]['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']);
$worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1;
// Close file
fclose($fileHandle);
return $worksheetInfo;
}
/**
* Loads PHPExcel from file
*
* @param string $pFilename
* @return PHPExcel
* @throws PHPExcel_Reader_Exception
*/
public function load($pFilename)
{
// Create new PHPExcel
$objPHPExcel = new PHPExcel();
// Load into this instance
return $this->loadIntoExisting($pFilename, $objPHPExcel);
}
/**
* Loads PHPExcel from file into PHPExcel instance
*
* @param string $pFilename
* @param PHPExcel $objPHPExcel
* @return PHPExcel
* @throws PHPExcel_Reader_Exception
*/
public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
{
// Open file
$this->openFile($pFilename);
if (!$this->isValidFormat()) {
fclose($this->fileHandle);
throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->fileHandle;
rewind($fileHandle);
// Create new PHPExcel
while ($objPHPExcel->getSheetCount() <= $this->sheetIndex) {
$objPHPExcel->createSheet();
}
$objPHPExcel->setActiveSheetIndex($this->sheetIndex);
$fromFormats = array('\-', '\ ');
$toFormats = array('-', ' ');
// Loop through file
$rowData = array();
$column = $row = '';
// loop through one row (line) at a time in the file
while (($rowData = fgets($fileHandle)) !== false) {
// convert SYLK encoded $rowData to UTF-8
$rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData);
// explode each row at semicolons while taking into account that literal semicolon (;)
// is escaped like this (;;)
$rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData)))));
$dataType = array_shift($rowData);
// Read shared styles
if ($dataType == 'P') {
$formatArray = array();
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'P':
$formatArray['numberformat']['code'] = str_replace($fromFormats, $toFormats, substr($rowDatum, 1));
break;
case 'E':
case 'F':
$formatArray['font']['name'] = substr($rowDatum, 1);
break;
case 'L':
$formatArray['font']['size'] = substr($rowDatum, 1);
break;
case 'S':
$styleSettings = substr($rowDatum, 1);
for ($i=0; $i<strlen($styleSettings); ++$i) {
switch ($styleSettings{$i}) {
case 'I':
$formatArray['font']['italic'] = true;
break;
case 'D':
$formatArray['font']['bold'] = true;
break;
case 'T':
$formatArray['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'B':
$formatArray['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'L':
$formatArray['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'R':
$formatArray['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
}
}
break;
}
}
$this->formats['P'.$this->format++] = $formatArray;
// Read cell value data
} elseif ($dataType == 'C') {
$hasCalculatedValue = false;
$cellData = $cellDataFormula = '';
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'C':
case 'X':
$column = substr($rowDatum, 1);
break;
case 'R':
case 'Y':
$row = substr($rowDatum, 1);
break;
case 'K':
$cellData = substr($rowDatum, 1);
break;
case 'E':
$cellDataFormula = '='.substr($rowDatum, 1);
// Convert R1C1 style references to A1 style references (but only when not quoted)
$temp = explode('"', $cellDataFormula);
$key = false;
foreach ($temp as &$value) {
// Only count/replace in alternate array entries
if ($key = !$key) {
preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER+PREG_OFFSET_CAPTURE);
// Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
// through the formula from left to right. Reversing means that we work right to left.through
// the formula
$cellReferences = array_reverse($cellReferences);
// Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent,
// then modify the formula to use that new reference
foreach ($cellReferences as $cellReference) {
$rowReference = $cellReference[2][0];
// Empty R reference is the current row
if ($rowReference == '') {
$rowReference = $row;
}
// Bracketed R references are relative to the current row
if ($rowReference{0} == '[') {
$rowReference = $row + trim($rowReference, '[]');
}
$columnReference = $cellReference[4][0];
// Empty C reference is the current column
if ($columnReference == '') {
$columnReference = $column;
}
// Bracketed C references are relative to the current column
if ($columnReference{0} == '[') {
$columnReference = $column + trim($columnReference, '[]');
}
$A1CellReference = PHPExcel_Cell::stringFromColumnIndex($columnReference-1).$rowReference;
$value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0]));
}
}
}
unset($value);
// Then rebuild the formula string
$cellDataFormula = implode('"', $temp);
$hasCalculatedValue = true;
break;
}
}
$columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1);
$cellData = PHPExcel_Calculation::unwrapResult($cellData);
// Set cell value
$objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData);
if ($hasCalculatedValue) {
$cellData = PHPExcel_Calculation::unwrapResult($cellData);
$objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setCalculatedValue($cellData);
}
// Read cell formatting
} elseif ($dataType == 'F') {
$formatStyle = $columnWidth = $styleSettings = '';
$styleData = array();
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'C':
case 'X':
$column = substr($rowDatum, 1);
break;
case 'R':
case 'Y':
$row = substr($rowDatum, 1);
break;
case 'P':
$formatStyle = $rowDatum;
break;
case 'W':
list($startCol, $endCol, $columnWidth) = explode(' ', substr($rowDatum, 1));
break;
case 'S':
$styleSettings = substr($rowDatum, 1);
for ($i=0; $i<strlen($styleSettings); ++$i) {
switch ($styleSettings{$i}) {
case 'I':
$styleData['font']['italic'] = true;
break;
case 'D':
$styleData['font']['bold'] = true;
break;
case 'T':
$styleData['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'B':
$styleData['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'L':
$styleData['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'R':
$styleData['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
}
}
break;
}
}
if (($formatStyle > '') && ($column > '') && ($row > '')) {
$columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1);
if (isset($this->formats[$formatStyle])) {
$objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($this->formats[$formatStyle]);
}
}
if ((!empty($styleData)) && ($column > '') && ($row > '')) {
$columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1);
$objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($styleData);
}
if ($columnWidth > '') {
if ($startCol == $endCol) {
$startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1);
$objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
} else {
$startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1);
$endCol = PHPExcel_Cell::stringFromColumnIndex($endCol-1);
$objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
do {
$objPHPExcel->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth);
} while ($startCol != $endCol);
}
}
} else {
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'C':
case 'X':
$column = substr($rowDatum, 1);
break;
case 'R':
case 'Y':
$row = substr($rowDatum, 1);
break;
}
}
}
}
// Close file
fclose($fileHandle);
// Return
return $objPHPExcel;
}
/**
* Get sheet index
*
* @return int
*/
public function getSheetIndex()
{
return $this->sheetIndex;
}
/**
* Set sheet index
*
* @param int $pValue Sheet index
* @return PHPExcel_Reader_SYLK
*/
public function setSheetIndex($pValue = 0)
{
$this->sheetIndex = $pValue;
return $this;
}
}
| Java |
import math
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtGui import QCloseEvent
from PyQt5.QtWidgets import QDialog, QInputDialog
from urh import settings
from urh.models.FuzzingTableModel import FuzzingTableModel
from urh.signalprocessing.ProtocoLabel import ProtocolLabel
from urh.signalprocessing.ProtocolAnalyzerContainer import ProtocolAnalyzerContainer
from urh.ui.ui_fuzzing import Ui_FuzzingDialog
class FuzzingDialog(QDialog):
def __init__(self, protocol: ProtocolAnalyzerContainer, label_index: int, msg_index: int, proto_view: int,
parent=None):
super().__init__(parent)
self.ui = Ui_FuzzingDialog()
self.ui.setupUi(self)
self.setAttribute(Qt.WA_DeleteOnClose)
self.setWindowFlags(Qt.Window)
self.protocol = protocol
msg_index = msg_index if msg_index != -1 else 0
self.ui.spinBoxFuzzMessage.setValue(msg_index + 1)
self.ui.spinBoxFuzzMessage.setMinimum(1)
self.ui.spinBoxFuzzMessage.setMaximum(self.protocol.num_messages)
self.ui.comboBoxFuzzingLabel.addItems([l.name for l in self.message.message_type])
self.ui.comboBoxFuzzingLabel.setCurrentIndex(label_index)
self.proto_view = proto_view
self.fuzz_table_model = FuzzingTableModel(self.current_label, proto_view)
self.fuzz_table_model.remove_duplicates = self.ui.chkBRemoveDuplicates.isChecked()
self.ui.tblFuzzingValues.setModel(self.fuzz_table_model)
self.fuzz_table_model.update()
self.ui.spinBoxFuzzingStart.setValue(self.current_label_start + 1)
self.ui.spinBoxFuzzingEnd.setValue(self.current_label_end)
self.ui.spinBoxFuzzingStart.setMaximum(len(self.message_data))
self.ui.spinBoxFuzzingEnd.setMaximum(len(self.message_data))
self.update_message_data_string()
self.ui.tblFuzzingValues.resize_me()
self.create_connects()
self.restoreGeometry(settings.read("{}/geometry".format(self.__class__.__name__), type=bytes))
@property
def message(self):
return self.protocol.messages[int(self.ui.spinBoxFuzzMessage.value() - 1)]
@property
def current_label_index(self):
return self.ui.comboBoxFuzzingLabel.currentIndex()
@property
def current_label(self) -> ProtocolLabel:
if len(self.message.message_type) == 0:
return None
cur_label = self.message.message_type[self.current_label_index].get_copy()
self.message.message_type[self.current_label_index] = cur_label
cur_label.fuzz_values = [fv for fv in cur_label.fuzz_values if fv] # Remove empty strings
if len(cur_label.fuzz_values) == 0:
cur_label.fuzz_values.append(self.message.plain_bits_str[cur_label.start:cur_label.end])
return cur_label
@property
def current_label_start(self):
if self.current_label and self.message:
return self.message.get_label_range(self.current_label, self.proto_view, False)[0]
else:
return -1
@property
def current_label_end(self):
if self.current_label and self.message:
return self.message.get_label_range(self.current_label, self.proto_view, False)[1]
else:
return -1
@property
def message_data(self):
if self.proto_view == 0:
return self.message.plain_bits_str
elif self.proto_view == 1:
return self.message.plain_hex_str
elif self.proto_view == 2:
return self.message.plain_ascii_str
else:
return None
def create_connects(self):
self.ui.spinBoxFuzzingStart.valueChanged.connect(self.on_fuzzing_start_changed)
self.ui.spinBoxFuzzingEnd.valueChanged.connect(self.on_fuzzing_end_changed)
self.ui.comboBoxFuzzingLabel.currentIndexChanged.connect(self.on_combo_box_fuzzing_label_current_index_changed)
self.ui.btnRepeatValues.clicked.connect(self.on_btn_repeat_values_clicked)
self.ui.btnAddRow.clicked.connect(self.on_btn_add_row_clicked)
self.ui.btnDelRow.clicked.connect(self.on_btn_del_row_clicked)
self.ui.tblFuzzingValues.deletion_wanted.connect(self.delete_lines)
self.ui.chkBRemoveDuplicates.stateChanged.connect(self.on_remove_duplicates_state_changed)
self.ui.sBAddRangeStart.valueChanged.connect(self.on_fuzzing_range_start_changed)
self.ui.sBAddRangeEnd.valueChanged.connect(self.on_fuzzing_range_end_changed)
self.ui.checkBoxLowerBound.stateChanged.connect(self.on_lower_bound_checked_changed)
self.ui.checkBoxUpperBound.stateChanged.connect(self.on_upper_bound_checked_changed)
self.ui.spinBoxLowerBound.valueChanged.connect(self.on_lower_bound_changed)
self.ui.spinBoxUpperBound.valueChanged.connect(self.on_upper_bound_changed)
self.ui.spinBoxRandomMinimum.valueChanged.connect(self.on_random_range_min_changed)
self.ui.spinBoxRandomMaximum.valueChanged.connect(self.on_random_range_max_changed)
self.ui.spinBoxFuzzMessage.valueChanged.connect(self.on_fuzz_msg_changed)
self.ui.btnAddFuzzingValues.clicked.connect(self.on_btn_add_fuzzing_values_clicked)
self.ui.comboBoxFuzzingLabel.editTextChanged.connect(self.set_current_label_name)
def update_message_data_string(self):
fuz_start = self.current_label_start
fuz_end = self.current_label_end
num_proto_bits = 10
num_fuz_bits = 16
proto_start = fuz_start - num_proto_bits
preambel = "... "
if proto_start <= 0:
proto_start = 0
preambel = ""
proto_end = fuz_end + num_proto_bits
postambel = " ..."
if proto_end >= len(self.message_data) - 1:
proto_end = len(self.message_data) - 1
postambel = ""
fuzamble = ""
if fuz_end - fuz_start > num_fuz_bits:
fuz_end = fuz_start + num_fuz_bits
fuzamble = "..."
self.ui.lPreBits.setText(preambel + self.message_data[proto_start:self.current_label_start])
self.ui.lFuzzedBits.setText(self.message_data[fuz_start:fuz_end] + fuzamble)
self.ui.lPostBits.setText(self.message_data[self.current_label_end:proto_end] + postambel)
self.set_add_spinboxes_maximum_on_label_change()
def closeEvent(self, event: QCloseEvent):
settings.write("{}/geometry".format(self.__class__.__name__), self.saveGeometry())
super().closeEvent(event)
@pyqtSlot(int)
def on_fuzzing_start_changed(self, value: int):
self.ui.spinBoxFuzzingEnd.setMinimum(self.ui.spinBoxFuzzingStart.value())
new_start = self.message.convert_index(value - 1, self.proto_view, 0, False)[0]
self.current_label.start = new_start
self.current_label.fuzz_values[:] = []
self.update_message_data_string()
self.fuzz_table_model.update()
self.ui.tblFuzzingValues.resize_me()
@pyqtSlot(int)
def on_fuzzing_end_changed(self, value: int):
self.ui.spinBoxFuzzingStart.setMaximum(self.ui.spinBoxFuzzingEnd.value())
new_end = self.message.convert_index(value - 1, self.proto_view, 0, False)[1] + 1
self.current_label.end = new_end
self.current_label.fuzz_values[:] = []
self.update_message_data_string()
self.fuzz_table_model.update()
self.ui.tblFuzzingValues.resize_me()
@pyqtSlot(int)
def on_combo_box_fuzzing_label_current_index_changed(self, index: int):
self.fuzz_table_model.fuzzing_label = self.current_label
self.fuzz_table_model.update()
self.update_message_data_string()
self.ui.tblFuzzingValues.resize_me()
self.ui.spinBoxFuzzingStart.blockSignals(True)
self.ui.spinBoxFuzzingStart.setValue(self.current_label_start + 1)
self.ui.spinBoxFuzzingStart.blockSignals(False)
self.ui.spinBoxFuzzingEnd.blockSignals(True)
self.ui.spinBoxFuzzingEnd.setValue(self.current_label_end)
self.ui.spinBoxFuzzingEnd.blockSignals(False)
@pyqtSlot()
def on_btn_add_row_clicked(self):
self.current_label.add_fuzz_value()
self.fuzz_table_model.update()
@pyqtSlot()
def on_btn_del_row_clicked(self):
min_row, max_row, _, _ = self.ui.tblFuzzingValues.selection_range()
self.delete_lines(min_row, max_row)
@pyqtSlot(int, int)
def delete_lines(self, min_row, max_row):
if min_row == -1:
self.current_label.fuzz_values = self.current_label.fuzz_values[:-1]
else:
self.current_label.fuzz_values = self.current_label.fuzz_values[:min_row] + self.current_label.fuzz_values[
max_row + 1:]
_ = self.current_label # if user deleted all, this will restore a fuzz value
self.fuzz_table_model.update()
@pyqtSlot()
def on_remove_duplicates_state_changed(self):
self.fuzz_table_model.remove_duplicates = self.ui.chkBRemoveDuplicates.isChecked()
self.fuzz_table_model.update()
self.remove_duplicates()
@pyqtSlot()
def set_add_spinboxes_maximum_on_label_change(self):
nbits = self.current_label.end - self.current_label.start # Use Bit Start/End for maximum calc.
if nbits >= 32:
nbits = 31
max_val = 2 ** nbits - 1
self.ui.sBAddRangeStart.setMaximum(max_val - 1)
self.ui.sBAddRangeEnd.setMaximum(max_val)
self.ui.sBAddRangeEnd.setValue(max_val)
self.ui.sBAddRangeStep.setMaximum(max_val)
self.ui.spinBoxLowerBound.setMaximum(max_val - 1)
self.ui.spinBoxUpperBound.setMaximum(max_val)
self.ui.spinBoxUpperBound.setValue(max_val)
self.ui.spinBoxBoundaryNumber.setMaximum(int(max_val / 2) + 1)
self.ui.spinBoxRandomMinimum.setMaximum(max_val - 1)
self.ui.spinBoxRandomMaximum.setMaximum(max_val)
self.ui.spinBoxRandomMaximum.setValue(max_val)
@pyqtSlot(int)
def on_fuzzing_range_start_changed(self, value: int):
self.ui.sBAddRangeEnd.setMinimum(value)
self.ui.sBAddRangeStep.setMaximum(self.ui.sBAddRangeEnd.value() - value)
@pyqtSlot(int)
def on_fuzzing_range_end_changed(self, value: int):
self.ui.sBAddRangeStart.setMaximum(value - 1)
self.ui.sBAddRangeStep.setMaximum(value - self.ui.sBAddRangeStart.value())
@pyqtSlot()
def on_lower_bound_checked_changed(self):
if self.ui.checkBoxLowerBound.isChecked():
self.ui.spinBoxLowerBound.setEnabled(True)
self.ui.spinBoxBoundaryNumber.setEnabled(True)
elif not self.ui.checkBoxUpperBound.isChecked():
self.ui.spinBoxLowerBound.setEnabled(False)
self.ui.spinBoxBoundaryNumber.setEnabled(False)
else:
self.ui.spinBoxLowerBound.setEnabled(False)
@pyqtSlot()
def on_upper_bound_checked_changed(self):
if self.ui.checkBoxUpperBound.isChecked():
self.ui.spinBoxUpperBound.setEnabled(True)
self.ui.spinBoxBoundaryNumber.setEnabled(True)
elif not self.ui.checkBoxLowerBound.isChecked():
self.ui.spinBoxUpperBound.setEnabled(False)
self.ui.spinBoxBoundaryNumber.setEnabled(False)
else:
self.ui.spinBoxUpperBound.setEnabled(False)
@pyqtSlot()
def on_lower_bound_changed(self):
self.ui.spinBoxUpperBound.setMinimum(self.ui.spinBoxLowerBound.value())
self.ui.spinBoxBoundaryNumber.setMaximum(math.ceil((self.ui.spinBoxUpperBound.value()
- self.ui.spinBoxLowerBound.value()) / 2))
@pyqtSlot()
def on_upper_bound_changed(self):
self.ui.spinBoxLowerBound.setMaximum(self.ui.spinBoxUpperBound.value() - 1)
self.ui.spinBoxBoundaryNumber.setMaximum(math.ceil((self.ui.spinBoxUpperBound.value()
- self.ui.spinBoxLowerBound.value()) / 2))
@pyqtSlot()
def on_random_range_min_changed(self):
self.ui.spinBoxRandomMaximum.setMinimum(self.ui.spinBoxRandomMinimum.value())
@pyqtSlot()
def on_random_range_max_changed(self):
self.ui.spinBoxRandomMinimum.setMaximum(self.ui.spinBoxRandomMaximum.value() - 1)
@pyqtSlot()
def on_btn_add_fuzzing_values_clicked(self):
if self.ui.comboBoxStrategy.currentIndex() == 0:
self.__add_fuzzing_range()
elif self.ui.comboBoxStrategy.currentIndex() == 1:
self.__add_fuzzing_boundaries()
elif self.ui.comboBoxStrategy.currentIndex() == 2:
self.__add_random_fuzzing_values()
def __add_fuzzing_range(self):
start = self.ui.sBAddRangeStart.value()
end = self.ui.sBAddRangeEnd.value()
step = self.ui.sBAddRangeStep.value()
self.fuzz_table_model.add_range(start, end + 1, step)
def __add_fuzzing_boundaries(self):
lower_bound = -1
if self.ui.spinBoxLowerBound.isEnabled():
lower_bound = self.ui.spinBoxLowerBound.value()
upper_bound = -1
if self.ui.spinBoxUpperBound.isEnabled():
upper_bound = self.ui.spinBoxUpperBound.value()
num_vals = self.ui.spinBoxBoundaryNumber.value()
self.fuzz_table_model.add_boundaries(lower_bound, upper_bound, num_vals)
def __add_random_fuzzing_values(self):
n = self.ui.spinBoxNumberRandom.value()
minimum = self.ui.spinBoxRandomMinimum.value()
maximum = self.ui.spinBoxRandomMaximum.value()
self.fuzz_table_model.add_random(n, minimum, maximum)
def remove_duplicates(self):
if self.ui.chkBRemoveDuplicates.isChecked():
for lbl in self.message.message_type:
seq = lbl.fuzz_values[:]
seen = set()
add_seen = seen.add
lbl.fuzz_values = [l for l in seq if not (l in seen or add_seen(l))]
@pyqtSlot()
def set_current_label_name(self):
self.current_label.name = self.ui.comboBoxFuzzingLabel.currentText()
self.ui.comboBoxFuzzingLabel.setItemText(self.ui.comboBoxFuzzingLabel.currentIndex(), self.current_label.name)
@pyqtSlot(int)
def on_fuzz_msg_changed(self, index: int):
self.ui.comboBoxFuzzingLabel.setDisabled(False)
sel_label_ind = self.ui.comboBoxFuzzingLabel.currentIndex()
self.ui.comboBoxFuzzingLabel.blockSignals(True)
self.ui.comboBoxFuzzingLabel.clear()
if len(self.message.message_type) == 0:
self.ui.comboBoxFuzzingLabel.setDisabled(True)
return
self.ui.comboBoxFuzzingLabel.addItems([lbl.name for lbl in self.message.message_type])
self.ui.comboBoxFuzzingLabel.blockSignals(False)
if sel_label_ind < self.ui.comboBoxFuzzingLabel.count():
self.ui.comboBoxFuzzingLabel.setCurrentIndex(sel_label_ind)
else:
self.ui.comboBoxFuzzingLabel.setCurrentIndex(0)
self.fuzz_table_model.fuzzing_label = self.current_label
self.fuzz_table_model.update()
self.update_message_data_string()
@pyqtSlot()
def on_btn_repeat_values_clicked(self):
num_repeats, ok = QInputDialog.getInt(self, self.tr("How many times shall values be repeated?"),
self.tr("Number of repeats:"), 1, 1)
if ok:
self.ui.chkBRemoveDuplicates.setChecked(False)
min_row, max_row, _, _ = self.ui.tblFuzzingValues.selection_range()
if min_row == -1:
start, end = 0, len(self.current_label.fuzz_values)
else:
start, end = min_row, max_row + 1
self.fuzz_table_model.repeat_fuzzing_values(start, end, num_repeats)
| Java |
import os
import unittest
from vsg.rules import iteration_scheme
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_300_test_input.vhd'))
dIndentMap = utils.read_indent_file()
lExpected = []
lExpected.append('')
utils.read_file(os.path.join(sTestDir, 'rule_300_test_input.fixed.vhd'), lExpected)
class test_iteration_scheme_rule(unittest.TestCase):
def setUp(self):
self.oFile = vhdlFile.vhdlFile(lFile)
self.assertIsNone(eError)
self.oFile.set_indent_map(dIndentMap)
def test_rule_300(self):
oRule = iteration_scheme.rule_300()
self.assertTrue(oRule)
self.assertEqual(oRule.name, 'iteration_scheme')
self.assertEqual(oRule.identifier, '300')
lExpected = [13, 17]
oRule.analyze(self.oFile)
self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations))
def test_fix_rule_300(self):
oRule = iteration_scheme.rule_300()
oRule.fix(self.oFile)
lActual = self.oFile.get_lines()
self.assertEqual(lExpected, lActual)
oRule.analyze(self.oFile)
self.assertEqual(oRule.violations, [])
| Java |
<?php
class ControllerCheckoutRegister extends Controller {
public function index() {
$this->language->load('checkout/checkout');
$this->data['text_checkout_payment_address'] = __('text_checkout_payment_address');
$this->data['text_your_details'] = __('text_your_details');
$this->data['text_your_address'] = __('text_your_address');
$this->data['text_your_password'] = __('text_your_password');
$this->data['text_select'] = __('text_select');
$this->data['text_none'] = __('text_none');
$this->data['text_modify'] = __('text_modify');
$this->data['entry_firstname'] = __('entry_firstname');
$this->data['entry_lastname'] = __('entry_lastname');
$this->data['entry_email'] = __('entry_email');
$this->data['entry_telephone'] = __('entry_telephone');
$this->data['entry_fax'] = __('entry_fax');
$this->data['entry_company'] = __('entry_company');
$this->data['entry_customer_group'] = __('entry_customer_group');
$this->data['entry_address_1'] = __('entry_address_1');
$this->data['entry_address_2'] = __('entry_address_2');
$this->data['entry_postcode'] = __('entry_postcode');
$this->data['entry_city'] = __('entry_city');
$this->data['entry_country'] = __('entry_country');
$this->data['entry_zone'] = __('entry_zone');
$this->data['entry_newsletter'] = sprintf(__('entry_newsletter'), $this->config->get('config_name'));
$this->data['entry_password'] = __('entry_password');
$this->data['entry_confirm'] = __('entry_confirm');
$this->data['entry_shipping'] = __('entry_shipping');
$this->data['button_continue'] = __('button_continue');
$this->data['customer_groups'] = array();
if (is_array($this->config->get('config_customer_group_display'))) {
$this->load->model('account/customer_group');
$customer_groups = $this->model_account_customer_group->getCustomerGroups();
foreach ($customer_groups as $customer_group) {
if (in_array($customer_group['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$this->data['customer_groups'][] = $customer_group;
}
}
}
$this->data['customer_group_id'] = $this->config->get('config_customer_group_id');
if (isset($this->session->data['shipping_addess']['postcode'])) {
$this->data['postcode'] = $this->session->data['shipping_addess']['postcode'];
} else {
$this->data['postcode'] = '';
}
if (isset($this->session->data['shipping_addess']['country_id'])) {
$this->data['country_id'] = $this->session->data['shipping_addess']['country_id'];
} else {
$this->data['country_id'] = $this->config->get('config_country_id');
}
if (isset($this->session->data['shipping_addess']['zone_id'])) {
$this->data['zone_id'] = $this->session->data['shipping_addess']['zone_id'];
} else {
$this->data['zone_id'] = '';
}
$this->load->model('localisation/country');
$this->data['countries'] = $this->model_localisation_country->getCountries();
if ($this->config->get('config_account_id')) {
$this->load->model('catalog/information');
$information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));
if ($information_info) {
$this->data['text_agree'] = sprintf(__('text_agree'), $this->url->link('information/information/info', 'information_id=' . $this->config->get('config_account_id'), 'SSL'), $information_info['title'], $information_info['title']);
} else {
$this->data['text_agree'] = '';
}
} else {
$this->data['text_agree'] = '';
}
$this->data['shipping_required'] = $this->cart->hasShipping();
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/register.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/register.tpl';
} else {
$this->template = 'default/template/checkout/register.tpl';
}
$this->response->setOutput($this->render());
}
public function save() {
$this->language->load('checkout/checkout');
$json = array();
// Validate if customer is already logged out.
if ($this->customer->isLogged()) {
$json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
}
// Validate cart has products and has stock.
if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
$json['redirect'] = $this->url->link('checkout/cart');
}
// Validate minimum quantity requirments.
$products = $this->cart->getProducts();
foreach ($products as $product) {
$product_total = 0;
foreach ($products as $product_2) {
if ($product_2['product_id'] == $product['product_id']) {
$product_total += $product_2['quantity'];
}
}
if ($product['minimum'] > $product_total) {
$json['redirect'] = $this->url->link('checkout/cart');
break;
}
}
if (!$json) {
$this->load->model('account/customer');
if ((utf8_strlen($this->request->post['firstname']) < 1) || (utf8_strlen($this->request->post['firstname']) > 32)) {
$json['error']['firstname'] = __('error_firstname');
}
if ((utf8_strlen($this->request->post['lastname']) < 1) || (utf8_strlen($this->request->post['lastname']) > 32)) {
$json['error']['lastname'] = __('error_lastname');
}
if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email'])) {
$json['error']['email'] = __('error_email');
}
if ($this->model_account_customer->getTotalCustomersByEmail($this->request->post['email'])) {
$json['error']['warning'] = __('error_exists');
}
if ((utf8_strlen($this->request->post['telephone']) < 3) || (utf8_strlen($this->request->post['telephone']) > 32)) {
$json['error']['telephone'] = __('error_telephone');
}
// Customer Group
$this->load->model('account/customer_group');
if (isset($this->request->post['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($this->request->post['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$customer_group_id = $this->request->post['customer_group_id'];
} else {
$customer_group_id = $this->config->get('config_customer_group_id');
}
$customer_group = $this->model_account_customer_group->getCustomerGroup($customer_group_id);
if ($customer_group) {
}
if ((utf8_strlen($this->request->post['address_1']) < 3) || (utf8_strlen($this->request->post['address_1']) > 128)) {
$json['error']['address_1'] = __('error_address_1');
}
if ((utf8_strlen($this->request->post['city']) < 2) || (utf8_strlen($this->request->post['city']) > 128)) {
$json['error']['city'] = __('error_city');
}
$this->load->model('localisation/country');
$country_info = $this->model_localisation_country->getCountry($this->request->post['country_id']);
if ($country_info && $country_info['postcode_required'] && (utf8_strlen($this->request->post['postcode']) < 2) || (utf8_strlen($this->request->post['postcode']) > 10)) {
$json['error']['postcode'] = __('error_postcode');
}
if ($this->request->post['country_id'] == '') {
$json['error']['country'] = __('error_country');
}
if (!isset($this->request->post['zone_id']) || $this->request->post['zone_id'] == '') {
$json['error']['zone'] = __('error_zone');
}
if ((utf8_strlen($this->request->post['password']) < 4) || (utf8_strlen($this->request->post['password']) > 20)) {
$json['error']['password'] = __('error_password');
}
if ($this->request->post['confirm'] != $this->request->post['password']) {
$json['error']['confirm'] = __('error_confirm');
}
if ($this->config->get('config_account_id')) {
$this->load->model('catalog/information');
$information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));
if ($information_info && !isset($this->request->post['agree'])) {
$json['error']['warning'] = sprintf(__('error_agree'), $information_info['title']);
}
}
}
if (!$json) {
$this->model_account_customer->addCustomer($this->request->post);
$this->session->data['account'] = 'register';
if ($customer_group && !$customer_group['approval']) {
$this->customer->login($this->request->post['email'], $this->request->post['password']);
// Default Payment Address
$this->load->model('account/address');
$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
if (!empty($this->request->post['shipping_address'])) {
$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
} else {
$json['redirect'] = $this->url->link('account/success');
}
unset($this->session->data['guest']);
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
}
$this->response->setOutput(json_encode($json));
}
}
?> | Java |
/*
* Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
* Copyright (C) 1999-2014 Hiroyuki Yamamoto and the Claws Mail team
*
* 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/>.
*
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#include "claws-features.h"
#endif
#include <glib.h>
#include <glib/gi18n.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#ifdef G_OS_WIN32
# include <w32lib.h>
#endif
#include "procheader.h"
#include "procmsg.h"
#include "codeconv.h"
#include "prefs_common.h"
#include "hooks.h"
#include "utils.h"
#include "defs.h"
#define BUFFSIZE 8192
static gchar monthstr[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
typedef char *(*getlinefunc) (char *, size_t, void *);
typedef int (*peekcharfunc) (void *);
typedef int (*getcharfunc) (void *);
typedef gint (*get_one_field_func) (gchar *, size_t, void *, HeaderEntry[]);
static gint string_get_one_field(gchar *buf, size_t len, char **str,
HeaderEntry hentry[]);
static char *string_getline(char *buf, size_t len, char **str);
static int string_peekchar(char **str);
static int file_peekchar(FILE *fp);
static gint generic_get_one_field(gchar *buf, size_t len, void *data,
HeaderEntry hentry[],
getlinefunc getline,
peekcharfunc peekchar,
gboolean unfold);
static MsgInfo *parse_stream(void *data, gboolean isstring, MsgFlags flags,
gboolean full, gboolean decrypted);
gint procheader_get_one_field(gchar *buf, size_t len, FILE *fp,
HeaderEntry hentry[])
{
return generic_get_one_field(buf, len, fp, hentry,
(getlinefunc)fgets_crlf, (peekcharfunc)file_peekchar,
TRUE);
}
static gint string_get_one_field(gchar *buf, size_t len, char **str,
HeaderEntry hentry[])
{
return generic_get_one_field(buf, len, str, hentry,
(getlinefunc)string_getline,
(peekcharfunc)string_peekchar,
TRUE);
}
static char *string_getline(char *buf, size_t len, char **str)
{
gboolean is_cr = FALSE;
gboolean last_was_cr = FALSE;
if (!*str || !**str)
return NULL;
for (; **str && len > 1; --len) {
is_cr = (**str == '\r');
if ((*buf++ = *(*str)++) == '\n') {
break;
}
if (last_was_cr) {
*(--buf) = '\n';
buf++;
break;
}
last_was_cr = is_cr;
}
*buf = '\0';
return buf;
}
static int string_peekchar(char **str)
{
return **str;
}
static int file_peekchar(FILE *fp)
{
return ungetc(getc(fp), fp);
}
static gint generic_get_one_field(gchar *buf, size_t len, void *data,
HeaderEntry *hentry,
getlinefunc getline, peekcharfunc peekchar,
gboolean unfold)
{
gint nexthead;
gint hnum = 0;
HeaderEntry *hp = NULL;
if (hentry != NULL) {
/* skip non-required headers */
do {
do {
if (getline(buf, len, data) == NULL)
return -1;
if (buf[0] == '\r' || buf[0] == '\n')
return -1;
} while (buf[0] == ' ' || buf[0] == '\t');
for (hp = hentry, hnum = 0; hp->name != NULL;
hp++, hnum++) {
if (!g_ascii_strncasecmp(hp->name, buf,
strlen(hp->name)))
break;
}
} while (hp->name == NULL);
} else {
if (getline(buf, len, data) == NULL) return -1;
if (buf[0] == '\r' || buf[0] == '\n') return -1;
}
/* unfold line */
while (1) {
nexthead = peekchar(data);
/* ([*WSP CRLF] 1*WSP) */
if (nexthead == ' ' || nexthead == '\t') {
size_t buflen;
gboolean skiptab = (nexthead == '\t');
/* trim previous trailing \n if requesting one header or
* unfolding was requested */
if ((!hentry && unfold) || (hp && hp->unfold))
strretchomp(buf);
buflen = strlen(buf);
/* concatenate next line */
if ((len - buflen) > 2) {
if (getline(buf + buflen, len - buflen, data) == NULL)
break;
if (skiptab) { /* replace tab with space */
*(buf + buflen) = ' ';
}
} else
break;
} else {
/* remove trailing new line */
strretchomp(buf);
break;
}
}
return hnum;
}
gint procheader_get_one_field_asis(gchar *buf, size_t len, FILE *fp)
{
return generic_get_one_field(buf, len, fp, NULL,
(getlinefunc)fgets_crlf,
(peekcharfunc)file_peekchar,
FALSE);
}
GPtrArray *procheader_get_header_array_asis(FILE *fp)
{
gchar buf[BUFFSIZE];
GPtrArray *headers;
Header *header;
cm_return_val_if_fail(fp != NULL, NULL);
headers = g_ptr_array_new();
while (procheader_get_one_field_asis(buf, sizeof(buf), fp) != -1) {
if ((header = procheader_parse_header(buf)) != NULL)
g_ptr_array_add(headers, header);
}
return headers;
}
void procheader_header_array_destroy(GPtrArray *harray)
{
gint i;
Header *header;
for (i = 0; i < harray->len; i++) {
header = g_ptr_array_index(harray, i);
procheader_header_free(header);
}
g_ptr_array_free(harray, TRUE);
}
void procheader_header_free(Header *header)
{
if (!header) return;
g_free(header->name);
g_free(header->body);
g_free(header);
}
/*
tests whether two headers' names are equal
remove the trailing ':' or ' ' before comparing
*/
gboolean procheader_headername_equal(char * hdr1, char * hdr2)
{
int len1;
int len2;
len1 = strlen(hdr1);
len2 = strlen(hdr2);
if (hdr1[len1 - 1] == ':')
len1--;
if (hdr2[len2 - 1] == ':')
len2--;
if (len1 != len2)
return 0;
return (g_ascii_strncasecmp(hdr1, hdr2, len1) == 0);
}
/*
parse headers, for example :
From: dinh@enseirb.fr becomes :
header->name = "From:"
header->body = "dinh@enseirb.fr"
*/
static gboolean header_is_addr_field(const gchar *hdr)
{
static char *addr_headers[] = {
"To:",
"Cc:",
"Bcc:",
"From:",
"Reply-To:",
"Followup-To:",
"Followup-and-Reply-To:",
"Disposition-Notification-To:",
"Return-Receipt-To:",
NULL};
int i;
if (!hdr)
return FALSE;
for (i = 0; addr_headers[i] != NULL; i++)
if (!strcasecmp(hdr, addr_headers[i]))
return FALSE;
return FALSE;
}
Header * procheader_parse_header(gchar * buf)
{
gchar *p;
Header * header;
gboolean addr_field = FALSE;
if ((*buf == ':') || (*buf == ' '))
return NULL;
for (p = buf; *p ; p++) {
if ((*p == ':') || (*p == ' ')) {
header = g_new(Header, 1);
header->name = g_strndup(buf, p - buf + 1);
addr_field = header_is_addr_field(header->name);
p++;
while (*p == ' ' || *p == '\t') p++;
header->body = conv_unmime_header(p, NULL, addr_field);
return header;
}
}
return NULL;
}
void procheader_get_header_fields(FILE *fp, HeaderEntry hentry[])
{
gchar buf[BUFFSIZE];
HeaderEntry *hp;
gint hnum;
gchar *p;
if (hentry == NULL) return;
while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, hentry))
!= -1) {
hp = hentry + hnum;
p = buf + strlen(hp->name);
while (*p == ' ' || *p == '\t') p++;
if (hp->body == NULL)
hp->body = g_strdup(p);
else if (procheader_headername_equal(hp->name, "To") ||
procheader_headername_equal(hp->name, "Cc")) {
gchar *tp = hp->body;
hp->body = g_strconcat(tp, ", ", p, NULL);
g_free(tp);
}
}
}
MsgInfo *procheader_parse_file(const gchar *file, MsgFlags flags,
gboolean full, gboolean decrypted)
{
GStatBuf s;
FILE *fp;
MsgInfo *msginfo;
if (g_stat(file, &s) < 0) {
FILE_OP_ERROR(file, "stat");
return NULL;
}
if (!S_ISREG(s.st_mode))
return NULL;
if ((fp = g_fopen(file, "rb")) == NULL) {
FILE_OP_ERROR(file, "fopen");
return NULL;
}
msginfo = procheader_parse_stream(fp, flags, full, decrypted);
fclose(fp);
if (msginfo) {
msginfo->size = s.st_size;
msginfo->mtime = s.st_mtime;
}
return msginfo;
}
MsgInfo *procheader_parse_str(const gchar *str, MsgFlags flags, gboolean full,
gboolean decrypted)
{
return parse_stream(&str, TRUE, flags, full, decrypted);
}
enum
{
H_DATE = 0,
H_FROM,
H_TO,
H_CC,
H_NEWSGROUPS,
H_SUBJECT,
H_MSG_ID,
H_REFERENCES,
H_IN_REPLY_TO,
H_CONTENT_TYPE,
H_SEEN,
H_STATUS,
H_FROM_SPACE,
H_SC_PLANNED_DOWNLOAD,
H_SC_MESSAGE_SIZE,
H_FACE,
H_X_FACE,
H_DISPOSITION_NOTIFICATION_TO,
H_RETURN_RECEIPT_TO,
H_SC_PARTIALLY_RETRIEVED,
H_SC_ACCOUNT_SERVER,
H_SC_ACCOUNT_LOGIN,
H_LIST_POST,
H_LIST_SUBSCRIBE,
H_LIST_UNSUBSCRIBE,
H_LIST_HELP,
H_LIST_ARCHIVE,
H_LIST_OWNER,
H_RESENT_FROM,
};
static HeaderEntry hentry_full[] = {
{"Date:", NULL, FALSE},
{"From:", NULL, TRUE},
{"To:", NULL, TRUE},
{"Cc:", NULL, TRUE},
{"Newsgroups:", NULL, TRUE},
{"Subject:", NULL, TRUE},
{"Message-ID:", NULL, FALSE},
{"References:", NULL, FALSE},
{"In-Reply-To:", NULL, FALSE},
{"Content-Type:", NULL, FALSE},
{"Seen:", NULL, FALSE},
{"Status:", NULL, FALSE},
{"From ", NULL, FALSE},
{"SC-Marked-For-Download:", NULL, FALSE},
{"SC-Message-Size:", NULL, FALSE},
{"Face:", NULL, FALSE},
{"X-Face:", NULL, FALSE},
{"Disposition-Notification-To:", NULL, FALSE},
{"Return-Receipt-To:", NULL, FALSE},
{"SC-Partially-Retrieved:", NULL, FALSE},
{"SC-Account-Server:", NULL, FALSE},
{"SC-Account-Login:",NULL, FALSE},
{"List-Post:", NULL, TRUE},
{"List-Subscribe:", NULL, TRUE},
{"List-Unsubscribe:",NULL, TRUE},
{"List-Help:", NULL, TRUE},
{"List-Archive:", NULL, TRUE},
{"List-Owner:", NULL, TRUE},
{"Resent-From:", NULL, TRUE},
{NULL, NULL, FALSE}};
static HeaderEntry hentry_short[] = {
{"Date:", NULL, FALSE},
{"From:", NULL, TRUE},
{"To:", NULL, TRUE},
{"Cc:", NULL, TRUE},
{"Newsgroups:", NULL, TRUE},
{"Subject:", NULL, TRUE},
{"Message-ID:", NULL, FALSE},
{"References:", NULL, FALSE},
{"In-Reply-To:", NULL, FALSE},
{"Content-Type:", NULL, FALSE},
{"Seen:", NULL, FALSE},
{"Status:", NULL, FALSE},
{"From ", NULL, FALSE},
{"SC-Marked-For-Download:", NULL, FALSE},
{"SC-Message-Size:",NULL, FALSE},
{NULL, NULL, FALSE}};
static HeaderEntry* procheader_get_headernames(gboolean full)
{
return full ? hentry_full : hentry_short;
}
MsgInfo *procheader_parse_stream(FILE *fp, MsgFlags flags, gboolean full,
gboolean decrypted)
{
return parse_stream(fp, FALSE, flags, full, decrypted);
}
static gboolean avatar_from_some_face(gpointer source, gpointer userdata)
{
AvatarCaptureData *acd = (AvatarCaptureData *)source;
if (*(acd->content) == '\0') /* won't be null, but may be empty */
return FALSE;
if (!strcmp(acd->header, hentry_full[H_FACE].name)) {
debug_print("avatar_from_some_face: found 'Face' header\n");
procmsg_msginfo_add_avatar(acd->msginfo, AVATAR_FACE, acd->content);
}
#if HAVE_LIBCOMPFACE
else if (!strcmp(acd->header, hentry_full[H_X_FACE].name)) {
debug_print("avatar_from_some_face: found 'X-Face' header\n");
procmsg_msginfo_add_avatar(acd->msginfo, AVATAR_XFACE, acd->content);
}
#endif
return FALSE;
}
static guint avatar_hook_id = 0;
static MsgInfo *parse_stream(void *data, gboolean isstring, MsgFlags flags,
gboolean full, gboolean decrypted)
{
MsgInfo *msginfo;
gchar buf[BUFFSIZE];
gchar *p, *tmp;
gchar *hp;
HeaderEntry *hentry;
gint hnum;
void *orig_data = data;
get_one_field_func get_one_field =
isstring ? (get_one_field_func)string_get_one_field
: (get_one_field_func)procheader_get_one_field;
hentry = procheader_get_headernames(full);
if (MSG_IS_QUEUED(flags) || MSG_IS_DRAFT(flags)) {
while (get_one_field(buf, sizeof(buf), data, NULL) != -1) {
if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
strlen("X-Claws-End-Special-Headers:"))) ||
(!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
strlen("X-Sylpheed-End-Special-Headers:"))))
break;
/* from other mailers */
if (!strncmp(buf, "Date: ", 6)
|| !strncmp(buf, "To: ", 4)
|| !strncmp(buf, "From: ", 6)
|| !strncmp(buf, "Subject: ", 9)) {
if (isstring)
data = orig_data;
else
rewind((FILE *)data);
break;
}
}
}
msginfo = procmsg_msginfo_new();
if (flags.tmp_flags || flags.perm_flags)
msginfo->flags = flags;
else
MSG_SET_PERM_FLAGS(msginfo->flags, MSG_NEW | MSG_UNREAD);
msginfo->inreplyto = NULL;
if (avatar_hook_id == 0 && (prefs_common.enable_avatars & AVATARS_ENABLE_CAPTURE)) {
avatar_hook_id = hooks_register_hook(AVATAR_HEADER_UPDATE_HOOKLIST, avatar_from_some_face, NULL);
} else if (avatar_hook_id != 0 && !(prefs_common.enable_avatars & AVATARS_ENABLE_CAPTURE)) {
hooks_unregister_hook(AVATAR_HEADER_UPDATE_HOOKLIST, avatar_hook_id);
avatar_hook_id = 0;
}
while ((hnum = get_one_field(buf, sizeof(buf), data, hentry))
!= -1) {
hp = buf + strlen(hentry[hnum].name);
while (*hp == ' ' || *hp == '\t') hp++;
switch (hnum) {
case H_DATE:
if (msginfo->date) break;
msginfo->date_t =
procheader_date_parse(NULL, hp, 0);
if (g_utf8_validate(hp, -1, NULL)) {
msginfo->date = g_strdup(hp);
} else {
gchar *utf = conv_codeset_strdup(
hp,
conv_get_locale_charset_str_no_utf8(),
CS_INTERNAL);
if (utf == NULL ||
!g_utf8_validate(utf, -1, NULL)) {
g_free(utf);
utf = g_malloc(strlen(buf)*2+1);
conv_localetodisp(utf,
strlen(hp)*2+1, hp);
}
msginfo->date = utf;
}
break;
case H_FROM:
if (msginfo->from) break;
msginfo->from = conv_unmime_header(hp, NULL, TRUE);
msginfo->fromname = procheader_get_fromname(msginfo->from);
remove_return(msginfo->from);
remove_return(msginfo->fromname);
break;
case H_TO:
tmp = conv_unmime_header(hp, NULL, TRUE);
remove_return(tmp);
if (msginfo->to) {
p = msginfo->to;
msginfo->to =
g_strconcat(p, ", ", tmp, NULL);
g_free(p);
} else
msginfo->to = g_strdup(tmp);
g_free(tmp);
break;
case H_CC:
tmp = conv_unmime_header(hp, NULL, TRUE);
remove_return(tmp);
if (msginfo->cc) {
p = msginfo->cc;
msginfo->cc =
g_strconcat(p, ", ", tmp, NULL);
g_free(p);
} else
msginfo->cc = g_strdup(tmp);
g_free(tmp);
break;
case H_NEWSGROUPS:
if (msginfo->newsgroups) {
p = msginfo->newsgroups;
msginfo->newsgroups =
g_strconcat(p, ",", hp, NULL);
g_free(p);
} else
msginfo->newsgroups = g_strdup(hp);
break;
case H_SUBJECT:
if (msginfo->subject) break;
msginfo->subject = conv_unmime_header(hp, NULL, FALSE);
unfold_line(msginfo->subject);
break;
case H_MSG_ID:
if (msginfo->msgid) break;
extract_parenthesis(hp, '<', '>');
remove_space(hp);
msginfo->msgid = g_strdup(hp);
break;
case H_REFERENCES:
msginfo->references =
references_list_prepend(msginfo->references,
hp);
break;
case H_IN_REPLY_TO:
if (msginfo->inreplyto) break;
eliminate_parenthesis(hp, '(', ')');
if ((p = strrchr(hp, '<')) != NULL &&
strchr(p + 1, '>') != NULL) {
extract_parenthesis(p, '<', '>');
remove_space(p);
if (*p != '\0')
msginfo->inreplyto = g_strdup(p);
}
break;
case H_CONTENT_TYPE:
if (!g_ascii_strncasecmp(hp, "multipart/", 10))
MSG_SET_TMP_FLAGS(msginfo->flags, MSG_MULTIPART);
break;
case H_DISPOSITION_NOTIFICATION_TO:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->dispositionnotificationto) break;
msginfo->extradata->dispositionnotificationto = g_strdup(hp);
break;
case H_RETURN_RECEIPT_TO:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->returnreceiptto) break;
msginfo->extradata->returnreceiptto = g_strdup(hp);
break;
/* partial download infos */
case H_SC_PARTIALLY_RETRIEVED:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->partial_recv) break;
msginfo->extradata->partial_recv = g_strdup(hp);
break;
case H_SC_ACCOUNT_SERVER:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->account_server) break;
msginfo->extradata->account_server = g_strdup(hp);
break;
case H_SC_ACCOUNT_LOGIN:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->account_login) break;
msginfo->extradata->account_login = g_strdup(hp);
break;
case H_SC_MESSAGE_SIZE:
if (msginfo->total_size) break;
msginfo->total_size = atoi(hp);
break;
case H_SC_PLANNED_DOWNLOAD:
msginfo->planned_download = atoi(hp);
break;
/* end partial download infos */
case H_FROM_SPACE:
if (msginfo->fromspace) break;
msginfo->fromspace = g_strdup(hp);
remove_return(msginfo->fromspace);
break;
/* list infos */
case H_LIST_POST:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_post) break;
msginfo->extradata->list_post = g_strdup(hp);
break;
case H_LIST_SUBSCRIBE:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_subscribe) break;
msginfo->extradata->list_subscribe = g_strdup(hp);
break;
case H_LIST_UNSUBSCRIBE:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_unsubscribe) break;
msginfo->extradata->list_unsubscribe = g_strdup(hp);
break;
case H_LIST_HELP:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_help) break;
msginfo->extradata->list_help = g_strdup(hp);
break;
case H_LIST_ARCHIVE:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_archive) break;
msginfo->extradata->list_archive = g_strdup(hp);
break;
case H_LIST_OWNER:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_owner) break;
msginfo->extradata->list_owner = g_strdup(hp);
break;
case H_RESENT_FROM:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->resent_from) break;
msginfo->extradata->resent_from = g_strdup(hp);
break;
/* end list infos */
default:
break;
}
/* to avoid performance penalty hooklist is invoked only for
headers known to be able to generate avatars */
if (hnum == H_FROM || hnum == H_X_FACE || hnum == H_FACE) {
AvatarCaptureData *acd = g_new0(AvatarCaptureData, 1);
/* no extra memory is wasted, hooks are expected to
take care of copying members when needed */
acd->msginfo = msginfo;
acd->header = hentry_full[hnum].name;
acd->content = hp;
hooks_invoke(AVATAR_HEADER_UPDATE_HOOKLIST, (gpointer)acd);
g_free(acd);
}
}
if (!msginfo->inreplyto && msginfo->references)
msginfo->inreplyto =
g_strdup((gchar *)msginfo->references->data);
return msginfo;
}
gchar *procheader_get_fromname(const gchar *str)
{
gchar *tmp, *name;
Xstrdup_a(tmp, str, return NULL);
if (*tmp == '\"') {
extract_quote(tmp, '\"');
g_strstrip(tmp);
} else if (strchr(tmp, '<')) {
eliminate_parenthesis(tmp, '<', '>');
g_strstrip(tmp);
if (*tmp == '\0') {
strcpy(tmp, str);
extract_parenthesis(tmp, '<', '>');
g_strstrip(tmp);
}
} else if (strchr(tmp, '(')) {
extract_parenthesis(tmp, '(', ')');
g_strstrip(tmp);
}
if (*tmp == '\0')
name = g_strdup(str);
else
name = g_strdup(tmp);
return name;
}
static gint procheader_scan_date_string(const gchar *str,
gchar *weekday, gint *day,
gchar *month, gint *year,
gint *hh, gint *mm, gint *ss,
gchar *zone)
{
gint result;
gint month_n;
gint secfract;
gint zone1 = 0, zone2 = 0;
gchar offset_sign, zonestr[7];
gchar sep1;
if (str == NULL)
return -1;
result = sscanf(str, "%10s %d %9s %d %2d:%2d:%2d %6s",
weekday, day, month, year, hh, mm, ss, zone);
if (result == 8) return 0;
/* RFC2822 */
result = sscanf(str, "%3s,%d %9s %d %2d:%2d:%2d %6s",
weekday, day, month, year, hh, mm, ss, zone);
if (result == 8) return 0;
result = sscanf(str, "%d %9s %d %2d:%2d:%2d %6s",
day, month, year, hh, mm, ss, zone);
if (result == 7) return 0;
*zone = '\0';
result = sscanf(str, "%10s %d %9s %d %2d:%2d:%2d",
weekday, day, month, year, hh, mm, ss);
if (result == 7) return 0;
result = sscanf(str, "%d %9s %d %2d:%2d:%2d",
day, month, year, hh, mm, ss);
if (result == 6) return 0;
*ss = 0;
result = sscanf(str, "%10s %d %9s %d %2d:%2d %6s",
weekday, day, month, year, hh, mm, zone);
if (result == 7) return 0;
result = sscanf(str, "%d %9s %d %2d:%2d %5s",
day, month, year, hh, mm, zone);
if (result == 6) return 0;
*zone = '\0';
result = sscanf(str, "%10s %d %9s %d %2d:%2d",
weekday, day, month, year, hh, mm);
if (result == 6) return 0;
result = sscanf(str, "%d %9s %d %2d:%2d",
day, month, year, hh, mm);
if (result == 5) return 0;
*weekday = '\0';
/* RFC3339 subset, with fraction of second */
result = sscanf(str, "%4d-%2d-%2d%c%2d:%2d:%2d.%d%6s",
year, &month_n, day, &sep1, hh, mm, ss, &secfract, zonestr);
if (result == 9
&& (sep1 == 'T' || sep1 == 't' || sep1 == ' ')) {
if (month_n >= 1 && month_n <= 12) {
strncpy2(month, monthstr+((month_n-1)*3), 4);
if (zonestr[0] == 'z' || zonestr[0] == 'Z') {
strcat(zone, "+00:00");
} else if (sscanf(zonestr, "%c%2d:%2d",
&offset_sign, &zone1, &zone2) == 3) {
strcat(zone, zonestr);
}
return 0;
}
}
/* RFC3339 subset, no fraction of second */
result = sscanf(str, "%4d-%2d-%2d%c%2d:%2d:%2d%6s",
year, &month_n, day, &sep1, hh, mm, ss, zonestr);
if (result == 8
&& (sep1 == 'T' || sep1 == 't' || sep1 == ' ')) {
if (month_n >= 1 && month_n <= 12) {
strncpy2(month, monthstr+((month_n-1)*3), 4);
if (zonestr[0] == 'z' || zonestr[0] == 'Z') {
strcat(zone, "+00:00");
} else if (sscanf(zonestr, "%c%2d:%2d",
&offset_sign, &zone1, &zone2) == 3) {
strcat(zone, zonestr);
}
return 0;
}
}
*zone = '\0';
/* RFC3339 subset */
/* This particular "subset" is invalid, RFC requires the time offset */
result = sscanf(str, "%4d-%2d-%2d %2d:%2d:%2d",
year, &month_n, day, hh, mm, ss);
if (result == 6) {
if (1 <= month_n && month_n <= 12) {
strncpy2(month, monthstr+((month_n-1)*3), 4);
return 0;
}
}
return -1;
}
/*
* Hiro, most UNIXen support this function:
* http://www.mcsr.olemiss.edu/cgi-bin/man-cgi?getdate
*/
gboolean procheader_date_parse_to_tm(const gchar *src, struct tm *t, char *zone)
{
gchar weekday[11];
gint day;
gchar month[10];
gint year;
gint hh, mm, ss;
GDateMonth dmonth;
gchar *p;
if (!t)
return FALSE;
memset(t, 0, sizeof *t);
if (procheader_scan_date_string(src, weekday, &day, month, &year,
&hh, &mm, &ss, zone) < 0) {
g_warning("Invalid date: %s", src);
return FALSE;
}
/* Y2K compliant :) */
if (year < 100) {
if (year < 70)
year += 2000;
else
year += 1900;
}
month[3] = '\0';
if ((p = strstr(monthstr, month)) != NULL)
dmonth = (gint)(p - monthstr) / 3 + 1;
else {
g_warning("Invalid month: %s", month);
dmonth = G_DATE_BAD_MONTH;
}
t->tm_sec = ss;
t->tm_min = mm;
t->tm_hour = hh;
t->tm_mday = day;
t->tm_mon = dmonth - 1;
t->tm_year = year - 1900;
t->tm_wday = 0;
t->tm_yday = 0;
t->tm_isdst = -1;
mktime(t);
return TRUE;
}
time_t procheader_date_parse(gchar *dest, const gchar *src, gint len)
{
gchar weekday[11];
gint day;
gchar month[10];
gint year;
gint hh, mm, ss;
gchar zone[7];
GDateMonth dmonth = G_DATE_BAD_MONTH;
struct tm t;
gchar *p;
time_t timer;
time_t tz_offset;
if (procheader_scan_date_string(src, weekday, &day, month, &year,
&hh, &mm, &ss, zone) < 0) {
if (dest && len > 0)
strncpy2(dest, src, len);
return 0;
}
/* Y2K compliant :) */
if (year < 1000) {
if (year < 50)
year += 2000;
else
year += 1900;
}
month[3] = '\0';
for (p = monthstr; *p != '\0'; p += 3) {
if (!g_ascii_strncasecmp(p, month, 3)) {
dmonth = (gint)(p - monthstr) / 3 + 1;
break;
}
}
t.tm_sec = ss;
t.tm_min = mm;
t.tm_hour = hh;
t.tm_mday = day;
t.tm_mon = dmonth - 1;
t.tm_year = year - 1900;
t.tm_wday = 0;
t.tm_yday = 0;
t.tm_isdst = -1;
timer = mktime(&t);
tz_offset = remote_tzoffset_sec(zone);
if (tz_offset != -1)
timer += tzoffset_sec(&timer) - tz_offset;
if (dest)
procheader_date_get_localtime(dest, len, timer);
return timer;
}
void procheader_date_get_localtime(gchar *dest, gint len, const time_t timer)
{
struct tm *lt;
gchar *default_format = "%y/%m/%d(%a) %H:%M";
gchar *str;
const gchar *src_codeset, *dest_codeset;
struct tm buf;
if (timer > 0)
lt = localtime_r(&timer, &buf);
else {
time_t dummy = 1;
lt = localtime_r(&dummy, &buf);
}
if (prefs_common.date_format)
fast_strftime(dest, len, prefs_common.date_format, lt);
else
fast_strftime(dest, len, default_format, lt);
if (!g_utf8_validate(dest, -1, NULL)) {
src_codeset = conv_get_locale_charset_str_no_utf8();
dest_codeset = CS_UTF_8;
str = conv_codeset_strdup(dest, src_codeset, dest_codeset);
if (str) {
strncpy2(dest, str, len);
g_free(str);
}
}
}
/* Added by Mel Hadasht on 27 Aug 2001 */
/* Get a header from msginfo */
gint procheader_get_header_from_msginfo(MsgInfo *msginfo, gchar *buf, gint len, gchar *header)
{
gchar *file;
FILE *fp;
HeaderEntry hentry[]={ { NULL, NULL, TRUE },
{ NULL, NULL, FALSE } };
gint val;
hentry[0].name = header;
cm_return_val_if_fail(msginfo != NULL, -1);
file = procmsg_get_message_file_path(msginfo);
if ((fp = g_fopen(file, "rb")) == NULL) {
FILE_OP_ERROR(file, "fopen");
g_free(file);
return -1;
}
val = procheader_get_one_field(buf,len, fp, hentry);
if (fclose(fp) == EOF) {
FILE_OP_ERROR(file, "fclose");
claws_unlink(file);
g_free(file);
return -1;
}
g_free(file);
if (val == -1)
return -1;
return 0;
}
HeaderEntry *procheader_entries_from_str(const gchar *str)
{
HeaderEntry *entries = NULL, *he;
int numh = 0, i = 0;
gchar **names = NULL;
const gchar *s = str;
if (s == NULL) {
return NULL;
}
while (*s != '\0') {
if (*s == ' ') ++numh;
++s;
}
if (numh == 0) {
return NULL;
}
entries = g_new0(HeaderEntry, numh + 1); /* room for last NULL */
s = str;
++s; /* skip first space */
names = g_strsplit(s, " ", numh);
he = entries;
while (names[i]) {
he->name = g_strdup_printf("%s:", names[i]);
he->body = NULL;
he->unfold = FALSE;
++i, ++he;
}
he->name = NULL;
g_strfreev(names);
return entries;
}
void procheader_entries_free (HeaderEntry *entries)
{
if (entries != NULL) {
HeaderEntry *he = entries;
while (he->name != NULL) {
g_free(he->name);
if (he->body != NULL)
g_free(he->body);
++he;
}
g_free(entries);
}
}
gboolean procheader_header_is_internal(const gchar *hdr_name)
{
const gchar *internal_hdrs[] = {
"AF:", "NF:", "PS:", "SRH:", "SFN:", "DSR:", "MID:", "CFG:",
"PT:", "S:", "RQ:", "SSV:", "NSV:", "SSH:", "R:", "MAID:",
"SCF:", "RMID:", "FMID:", "NAID:",
"X-Claws-Account-Id:",
"X-Claws-Sign:",
"X-Claws-Encrypt:",
"X-Claws-Privacy-System:",
"X-Claws-Auto-Wrapping:",
"X-Claws-Auto-Indent:",
"X-Claws-End-Special-Headers:",
"X-Sylpheed-Account-Id:",
"X-Sylpheed-Sign:",
"X-Sylpheed-Encrypt:",
"X-Sylpheed-Privacy-System:",
"X-Sylpheed-End-Special-Headers:",
NULL
};
int i;
for (i = 0; internal_hdrs[i]; i++) {
if (!strcmp(hdr_name, internal_hdrs[i]))
return TRUE;
}
return FALSE;
}
| Java |
../../../linux-headers-3.0.0-12/include/linux/ide.h | Java |
package telinc.telicraft.util;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.ChatMessageComponent;
import net.minecraft.util.StatCollector;
public class PetrifyDamageSource extends TelicraftDamageSource {
protected EntityLivingBase entity;
protected PetrifyDamageSource(EntityLivingBase par1EntityLivingBase) {
super("petrify");
this.setDamageAllowedInCreativeMode();
this.setDamageBypassesArmor();
this.entity = par1EntityLivingBase;
}
@Override
public Entity getEntity() {
return this.entity;
}
@Override
public ChatMessageComponent getDeathMessage(EntityLivingBase par1EntityLivingBase) {
EntityLivingBase attacker = par1EntityLivingBase.func_94060_bK();
String deathSelf = this.getRawDeathMessage();
String deathPlayer = deathSelf + ".player";
return attacker != null && StatCollector.func_94522_b(deathPlayer) ? ChatMessageComponent.func_111082_b(deathPlayer, new Object[]{par1EntityLivingBase.getTranslatedEntityName(), attacker.getTranslatedEntityName()}) : ChatMessageComponent.func_111082_b(deathSelf, new Object[]{par1EntityLivingBase.getTranslatedEntityName()});
}
}
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Fri Dec 04 23:17:14 GMT 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory (Solr 5.4.0 API)</title>
<meta name="date" content="2015-12-04">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory (Solr 5.4.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/solr/update/processor/ParseBooleanFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/update/processor/class-use/ParseBooleanFieldUpdateProcessorFactory.html" target="_top">Frames</a></li>
<li><a href="ParseBooleanFieldUpdateProcessorFactory.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory" class="title">Uses of Class<br>org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/solr/update/processor/ParseBooleanFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/update/processor/class-use/ParseBooleanFieldUpdateProcessorFactory.html" target="_top">Frames</a></li>
<li><a href="ParseBooleanFieldUpdateProcessorFactory.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2015 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| Java |
$Name = 'VyOS'
$SwitchName = 'Internal'
$HardDiskSize = 2GB
$HDPath = 'E:\Hyper-V\Virtual Hard Disks'+'\'+$Name+'.vhdx'
$Generation = '1'
$ISO_Path = 'D:\ISOs\vyos-1.1.6-amd64.iso'
New-VM -Name $Name -SwitchName $SwitchName `
-NewVHDSizeBytes $HardDiskSize `
-NewVHDPath $HDPath -Generation $Generation -MemoryStartupBytes 512MB
Add-VMDvdDrive -VMName $Name -Path $ISO_Path
Add-VMNetworkAdapter -VMName $Name -SwitchName External | Java |
<?php namespace Darryldecode\Cart;
/**
* Created by PhpStorm.
* User: darryl
* Date: 1/15/2015
* Time: 9:46 PM
*/
use Illuminate\Support\Collection;
class CartConditionCollection extends Collection {
} | Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>GNU Radio 7f75d35b C++ API: volk_32fc_x2_square_dist_32f_a.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">GNU Radio 7f75d35b C++ API
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.7.6.1 -->
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('volk__32fc__x2__square__dist__32f__a_8h.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="headertitle">
<div class="title">volk_32fc_x2_square_dist_32f_a.h</div> </div>
</div><!--header-->
<div class="contents">
<a href="volk__32fc__x2__square__dist__32f__a_8h.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="preprocessor">#ifndef INCLUDED_volk_32fc_x2_square_dist_32f_a_H</span>
<a name="l00002"></a>00002 <span class="preprocessor"></span><span class="preprocessor">#define INCLUDED_volk_32fc_x2_square_dist_32f_a_H</span>
<a name="l00003"></a>00003 <span class="preprocessor"></span>
<a name="l00004"></a>00004 <span class="preprocessor">#include<<a class="code" href="inttypes_8h.html">inttypes.h</a>></span>
<a name="l00005"></a>00005 <span class="preprocessor">#include<stdio.h></span>
<a name="l00006"></a>00006 <span class="preprocessor">#include<<a class="code" href="volk__complex_8h.html">volk/volk_complex.h</a>></span>
<a name="l00007"></a>00007
<a name="l00008"></a>00008 <span class="preprocessor">#ifdef LV_HAVE_SSE3</span>
<a name="l00009"></a>00009 <span class="preprocessor"></span><span class="preprocessor">#include<xmmintrin.h></span>
<a name="l00010"></a>00010 <span class="preprocessor">#include<pmmintrin.h></span>
<a name="l00011"></a>00011
<a name="l00012"></a>00012 <span class="keyword">static</span> <span class="keyword">inline</span> <span class="keywordtype">void</span> volk_32fc_x2_square_dist_32f_a_sse3(<span class="keywordtype">float</span>* target, <a class="code" href="volk__complex_8h.html#ace50e1c8ef539cdeee04bc86f0e99169">lv_32fc_t</a>* src0, <a class="code" href="volk__complex_8h.html#ace50e1c8ef539cdeee04bc86f0e99169">lv_32fc_t</a>* points, <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> num_bytes) {
<a name="l00013"></a>00013
<a name="l00014"></a>00014
<a name="l00015"></a>00015 __m128 xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7;
<a name="l00016"></a>00016
<a name="l00017"></a>00017 <a class="code" href="volk__complex_8h.html#ace50e1c8ef539cdeee04bc86f0e99169">lv_32fc_t</a> diff;
<a name="l00018"></a>00018 <span class="keywordtype">float</span> sq_dist;
<a name="l00019"></a>00019 <span class="keywordtype">int</span> bound = num_bytes >> 5;
<a name="l00020"></a>00020 <span class="keywordtype">int</span> leftovers0 = (num_bytes >> 4) & 1;
<a name="l00021"></a>00021 <span class="keywordtype">int</span> leftovers1 = (num_bytes >> 3) & 1;
<a name="l00022"></a>00022 <span class="keywordtype">int</span> i = 0;
<a name="l00023"></a>00023
<a name="l00024"></a>00024 xmm1 = _mm_setzero_ps();
<a name="l00025"></a>00025 xmm1 = _mm_loadl_pi(xmm1, (__m64*)src0);
<a name="l00026"></a>00026 xmm2 = _mm_load_ps((<span class="keywordtype">float</span>*)&points[0]);
<a name="l00027"></a>00027 xmm1 = _mm_movelh_ps(xmm1, xmm1);
<a name="l00028"></a>00028 xmm3 = _mm_load_ps((<span class="keywordtype">float</span>*)&points[2]);
<a name="l00029"></a>00029
<a name="l00030"></a>00030
<a name="l00031"></a>00031 <span class="keywordflow">for</span>(; i < bound - 1; ++i) {
<a name="l00032"></a>00032 xmm4 = _mm_sub_ps(xmm1, xmm2);
<a name="l00033"></a>00033 xmm5 = _mm_sub_ps(xmm1, xmm3);
<a name="l00034"></a>00034 points += 4;
<a name="l00035"></a>00035 xmm6 = _mm_mul_ps(xmm4, xmm4);
<a name="l00036"></a>00036 xmm7 = _mm_mul_ps(xmm5, xmm5);
<a name="l00037"></a>00037
<a name="l00038"></a>00038 xmm2 = _mm_load_ps((<span class="keywordtype">float</span>*)&points[0]);
<a name="l00039"></a>00039
<a name="l00040"></a>00040 xmm4 = _mm_hadd_ps(xmm6, xmm7);
<a name="l00041"></a>00041
<a name="l00042"></a>00042 xmm3 = _mm_load_ps((<span class="keywordtype">float</span>*)&points[2]);
<a name="l00043"></a>00043
<a name="l00044"></a>00044 _mm_store_ps(target, xmm4);
<a name="l00045"></a>00045
<a name="l00046"></a>00046 target += 4;
<a name="l00047"></a>00047
<a name="l00048"></a>00048 }
<a name="l00049"></a>00049
<a name="l00050"></a>00050 xmm4 = _mm_sub_ps(xmm1, xmm2);
<a name="l00051"></a>00051 xmm5 = _mm_sub_ps(xmm1, xmm3);
<a name="l00052"></a>00052
<a name="l00053"></a>00053
<a name="l00054"></a>00054
<a name="l00055"></a>00055 points += 4;
<a name="l00056"></a>00056 xmm6 = _mm_mul_ps(xmm4, xmm4);
<a name="l00057"></a>00057 xmm7 = _mm_mul_ps(xmm5, xmm5);
<a name="l00058"></a>00058
<a name="l00059"></a>00059 xmm4 = _mm_hadd_ps(xmm6, xmm7);
<a name="l00060"></a>00060
<a name="l00061"></a>00061 _mm_store_ps(target, xmm4);
<a name="l00062"></a>00062
<a name="l00063"></a>00063 target += 4;
<a name="l00064"></a>00064
<a name="l00065"></a>00065 <span class="keywordflow">for</span>(i = 0; i < leftovers0; ++i) {
<a name="l00066"></a>00066
<a name="l00067"></a>00067 xmm2 = _mm_load_ps((<span class="keywordtype">float</span>*)&points[0]);
<a name="l00068"></a>00068
<a name="l00069"></a>00069 xmm4 = _mm_sub_ps(xmm1, xmm2);
<a name="l00070"></a>00070
<a name="l00071"></a>00071 points += 2;
<a name="l00072"></a>00072
<a name="l00073"></a>00073 xmm6 = _mm_mul_ps(xmm4, xmm4);
<a name="l00074"></a>00074
<a name="l00075"></a>00075 xmm4 = _mm_hadd_ps(xmm6, xmm6);
<a name="l00076"></a>00076
<a name="l00077"></a>00077 _mm_storeh_pi((__m64*)target, xmm4);
<a name="l00078"></a>00078
<a name="l00079"></a>00079 target += 2;
<a name="l00080"></a>00080 }
<a name="l00081"></a>00081
<a name="l00082"></a>00082 <span class="keywordflow">for</span>(i = 0; i < leftovers1; ++i) {
<a name="l00083"></a>00083
<a name="l00084"></a>00084 diff = src0[0] - points[0];
<a name="l00085"></a>00085
<a name="l00086"></a>00086 sq_dist = <a class="code" href="volk__complex_8h.html#a9e9cedc79eafa6db42f03878b5a5ba47">lv_creal</a>(diff) * <a class="code" href="volk__complex_8h.html#a9e9cedc79eafa6db42f03878b5a5ba47">lv_creal</a>(diff) + <a class="code" href="volk__complex_8h.html#a1f58129a88c382411b2e8997c8dd89e4">lv_cimag</a>(diff) * <a class="code" href="volk__complex_8h.html#a1f58129a88c382411b2e8997c8dd89e4">lv_cimag</a>(diff);
<a name="l00087"></a>00087
<a name="l00088"></a>00088 target[0] = sq_dist;
<a name="l00089"></a>00089 }
<a name="l00090"></a>00090 }
<a name="l00091"></a>00091
<a name="l00092"></a>00092 <span class="preprocessor">#endif </span><span class="comment">/*LV_HAVE_SSE3*/</span>
<a name="l00093"></a>00093
<a name="l00094"></a>00094 <span class="preprocessor">#ifdef LV_HAVE_GENERIC</span>
<a name="l00095"></a>00095 <span class="preprocessor"></span><span class="keyword">static</span> <span class="keyword">inline</span> <span class="keywordtype">void</span> volk_32fc_x2_square_dist_32f_a_generic(<span class="keywordtype">float</span>* target, <a class="code" href="volk__complex_8h.html#ace50e1c8ef539cdeee04bc86f0e99169">lv_32fc_t</a>* src0, <a class="code" href="volk__complex_8h.html#ace50e1c8ef539cdeee04bc86f0e99169">lv_32fc_t</a>* points, <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> num_bytes) {
<a name="l00096"></a>00096 <a class="code" href="volk__complex_8h.html#ace50e1c8ef539cdeee04bc86f0e99169">lv_32fc_t</a> diff;
<a name="l00097"></a>00097 <span class="keywordtype">float</span> sq_dist;
<a name="l00098"></a>00098 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> i = 0;
<a name="l00099"></a>00099
<a name="l00100"></a>00100 <span class="keywordflow">for</span>(; i < num_bytes >> 3; ++i) {
<a name="l00101"></a>00101 diff = src0[0] - points[i];
<a name="l00102"></a>00102
<a name="l00103"></a>00103 sq_dist = <a class="code" href="volk__complex_8h.html#a9e9cedc79eafa6db42f03878b5a5ba47">lv_creal</a>(diff) * <a class="code" href="volk__complex_8h.html#a9e9cedc79eafa6db42f03878b5a5ba47">lv_creal</a>(diff) + <a class="code" href="volk__complex_8h.html#a1f58129a88c382411b2e8997c8dd89e4">lv_cimag</a>(diff) * <a class="code" href="volk__complex_8h.html#a1f58129a88c382411b2e8997c8dd89e4">lv_cimag</a>(diff);
<a name="l00104"></a>00104
<a name="l00105"></a>00105 target[i] = sq_dist;
<a name="l00106"></a>00106 }
<a name="l00107"></a>00107 }
<a name="l00108"></a>00108
<a name="l00109"></a>00109 <span class="preprocessor">#endif </span><span class="comment">/*LV_HAVE_GENERIC*/</span>
<a name="l00110"></a>00110
<a name="l00111"></a>00111
<a name="l00112"></a>00112 <span class="preprocessor">#endif </span><span class="comment">/*INCLUDED_volk_32fc_x2_square_dist_32f_a_H*/</span>
</pre></div></div><!-- contents -->
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="volk__32fc__x2__square__dist__32f__a_8h.html">volk_32fc_x2_square_dist_32f_a.h</a> </li>
<li class="footer">Generated on Thu Sep 27 2012 10:49:26 for GNU Radio 7f75d35b C++ API by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.6.1 </li>
</ul>
</div>
</body>
</html>
| Java |
package com.github.dozzatq.phoenix.advertising;
/**
* Created by Rodion Bartoshik on 04.07.2017.
*/
interface Reflector {
FactoryAd reflection();
int state();
}
| Java |
/*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports 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 for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.web.commands;
import net.sf.jasperreports.engine.JRConstants;
import net.sf.jasperreports.web.JRInteractiveException;
/**
* @author Narcis Marcu (narcism@users.sourceforge.net)
*/
public class CommandException extends JRInteractiveException
{
private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;
public CommandException(String message) {
super(message);
}
public CommandException(Throwable t) {
super(t);
}
public CommandException(String message, Throwable t) {
super(message, t);
}
public CommandException(String messageKey, Object[] args, Throwable t)
{
super(messageKey, args, t);
}
public CommandException(String messageKey, Object[] args)
{
super(messageKey, args);
}
}
| Java |
#
# LMirror is Copyright (C) 2010 Robert Collins <robertc@robertcollins.net>
#
# LMirror 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/>.
#
# In the LMirror source tree the file COPYING.txt contains the GNU General Public
# License version 3.
#
"""Tests for logging support code."""
from StringIO import StringIO
import logging
import os.path
import time
from l_mirror import logging_support
from l_mirror.tests import ResourcedTestCase
from l_mirror.tests.logging_resource import LoggingResourceManager
from l_mirror.tests.stubpackage import TempDirResource
class TestLoggingSetup(ResourcedTestCase):
resources = [('logging', LoggingResourceManager())]
def test_configure_logging_sets_converter(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out)
self.assertEqual(c_log, logging.root.handlers[0])
self.assertEqual(f_log, logging.root.handlers[1])
self.assertEqual(None, c_log.formatter)
self.assertEqual(formatter, f_log.formatter)
self.assertEqual(time.gmtime, formatter.converter)
self.assertEqual("%Y-%m-%d %H:%M:%SZ", formatter.datefmt)
self.assertEqual(logging.StreamHandler, c_log.__class__)
self.assertEqual(out, c_log.stream)
self.assertEqual(logging.FileHandler, f_log.__class__)
self.assertEqual(os.path.expanduser("~/.cache/lmirror/log"), f_log.baseFilename)
def test_can_supply_filename_None(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out, None)
self.assertEqual(None, f_log)
| Java |
namespace _03BarracksWars.Contracts
{
public interface IRunnable
{
void Run();
}
}
| Java |
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Web.Http;
using TodoList.Api.Infrastructure.Authentication;
[assembly: OwinStartup(typeof(TodoList.Api.Startup))]
namespace TodoList.Api
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
//SwaggerConfig.Register();
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
//Rest of code is here;
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
} | Java |
\alpha
\beta
\gamma
\delta
\epsilon
\zeta
\eta
\theta
\iota
\kappa
\lambda
\mu
\nu
\xi
\omicron
\pi
\rho
\sigma
\tau
\upsilon
\phi
\chi
\psi
\omega
| Java |
/*
* Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
* Copyright (C) 1999-2015 Hiroyuki Yamamoto and the Claws Mail team
*
* 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/>.
*
*/
/* alfons - all folder item specific settings should migrate into
* folderlist.xml!!! the old folderitemrc file will only serve for a few
* versions (for compatibility) */
#ifdef HAVE_CONFIG_H
# include "config.h"
#include "claws-features.h"
#endif
#include "defs.h"
#include <glib.h>
#include <glib/gi18n.h>
#include "folder.h"
#include "alertpanel.h"
#include "prefs_folder_item.h"
#include "folderview.h"
#include "folder.h"
#include "summaryview.h"
#include "menu.h"
#include "account.h"
#include "prefs_gtk.h"
#include "manage_window.h"
#include "utils.h"
#include "addr_compl.h"
#include "prefs_common.h"
#include "gtkutils.h"
#include "filtering.h"
#include "folder_item_prefs.h"
#include "gtk/colorsel.h"
#include "string_match.h"
#include "quote_fmt.h"
#include "combobox.h"
#if USE_ENCHANT
#include "gtkaspell.h"
#endif
#define ASSIGN_STRING(string, value) \
{ \
g_free(string); \
string = (value); \
}
typedef struct _FolderItemGeneralPage FolderItemGeneralPage;
typedef struct _FolderItemComposePage FolderItemComposePage;
typedef struct _FolderItemTemplatesPage FolderItemTemplatesPage;
static gboolean can_save = TRUE;
struct _FolderItemGeneralPage
{
PrefsPage page;
FolderItem *item;
GtkWidget *table;
GtkWidget *no_save_warning;
GtkWidget *folder_type;
#ifndef G_OS_WIN32
GtkWidget *checkbtn_simplify_subject;
GtkWidget *entry_simplify_subject;
GtkWidget *entry_regexp_test_string;
GtkWidget *entry_regexp_test_result;
#endif
GtkWidget *checkbtn_folder_chmod;
GtkWidget *entry_folder_chmod;
GtkWidget *folder_color_btn;
GtkWidget *checkbtn_enable_processing;
GtkWidget *checkbtn_enable_processing_when_opening;
GtkWidget *checkbtn_newmailcheck;
GtkWidget *checkbtn_offlinesync;
GtkWidget *label_offlinesync;
GtkWidget *entry_offlinesync;
GtkWidget *label_end_offlinesync;
GtkWidget *checkbtn_remove_old_offlinesync;
GtkWidget *promote_html_part;
/* apply to sub folders */
#ifndef G_OS_WIN32
GtkWidget *simplify_subject_rec_checkbtn;
#endif
GtkWidget *folder_chmod_rec_checkbtn;
GtkWidget *folder_color_rec_checkbtn;
GtkWidget *enable_processing_rec_checkbtn;
GtkWidget *enable_processing_when_opening_rec_checkbtn;
GtkWidget *newmailcheck_rec_checkbtn;
GtkWidget *offlinesync_rec_checkbtn;
GtkWidget *promote_html_part_rec_checkbtn;
gint folder_color;
};
struct _FolderItemComposePage
{
PrefsPage page;
FolderItem *item;
GtkWidget *window;
GtkWidget *table;
GtkWidget *no_save_warning;
GtkWidget *checkbtn_request_return_receipt;
GtkWidget *checkbtn_save_copy_to_folder;
GtkWidget *checkbtn_default_to;
GtkWidget *entry_default_to;
GtkWidget *checkbtn_default_reply_to;
GtkWidget *entry_default_reply_to;
GtkWidget *checkbtn_default_cc;
GtkWidget *entry_default_cc;
GtkWidget *checkbtn_default_bcc;
GtkWidget *entry_default_bcc;
GtkWidget *checkbtn_default_replyto;
GtkWidget *entry_default_replyto;
GtkWidget *checkbtn_enable_default_account;
GtkWidget *optmenu_default_account;
#if USE_ENCHANT
GtkWidget *checkbtn_enable_default_dictionary;
GtkWidget *checkbtn_enable_default_alt_dictionary;
GtkWidget *combo_default_dictionary;
GtkWidget *combo_default_alt_dictionary;
#endif
/* apply to sub folders */
GtkWidget *request_return_receipt_rec_checkbtn;
GtkWidget *save_copy_to_folder_rec_checkbtn;
GtkWidget *default_to_rec_checkbtn;
GtkWidget *default_reply_to_rec_checkbtn;
GtkWidget *default_cc_rec_checkbtn;
GtkWidget *default_bcc_rec_checkbtn;
GtkWidget *default_replyto_rec_checkbtn;
GtkWidget *default_account_rec_checkbtn;
#if USE_ENCHANT
GtkWidget *default_dictionary_rec_checkbtn;
GtkWidget *default_alt_dictionary_rec_checkbtn;
#endif
};
struct _FolderItemTemplatesPage
{
PrefsPage page;
FolderItem *item;
GtkWidget *window;
GtkWidget *table;
GtkWidget *checkbtn_compose_with_format;
GtkWidget *compose_override_from_format;
GtkWidget *compose_subject_format;
GtkWidget *compose_body_format;
GtkWidget *checkbtn_reply_with_format;
GtkWidget *reply_quotemark;
GtkWidget *reply_override_from_format;
GtkWidget *reply_body_format;
GtkWidget *checkbtn_forward_with_format;
GtkWidget *forward_quotemark;
GtkWidget *forward_override_from_format;
GtkWidget *forward_body_format;
/* apply to sub folders */
GtkWidget *new_msg_format_rec_checkbtn;
GtkWidget *reply_format_rec_checkbtn;
GtkWidget *forward_format_rec_checkbtn;
};
static void general_save_folder_prefs(FolderItem *folder, FolderItemGeneralPage *page);
static void compose_save_folder_prefs(FolderItem *folder, FolderItemComposePage *page);
static void templates_save_folder_prefs(FolderItem *folder, FolderItemTemplatesPage *page);
static gboolean general_save_recurse_func(GNode *node, gpointer data);
static gboolean compose_save_recurse_func(GNode *node, gpointer data);
static gboolean templates_save_recurse_func(GNode *node, gpointer data);
static gint prefs_folder_item_chmod_mode (gchar *folder_chmod);
static void folder_color_set_dialog(GtkWidget *widget, gpointer data);
static void clean_cache_cb(GtkWidget *widget, gpointer data);
#ifndef G_OS_WIN32
static void folder_regexp_test_cb(GtkWidget *widget, gpointer data);
static void folder_regexp_set_subject_example_cb(GtkWidget *widget, gpointer data);
#endif
#define SAFE_STRING(str) \
(str) ? (str) : ""
static void prefs_folder_item_general_create_widget_func(PrefsPage * page_,
GtkWindow * window,
gpointer data)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *) page_;
FolderItem *item = (FolderItem *) data;
guint rowcount;
GtkWidget *table;
GtkWidget *hbox, *hbox2, *hbox_spc;
GtkWidget *label;
GtkListStore *folder_type_menu;
GtkWidget *folder_type;
GtkTreeIter iter;
GtkWidget *dummy_checkbtn, *clean_cache_btn;
SpecialFolderItemType type;
GtkWidget *no_save_warning = NULL;
#ifndef G_OS_WIN32
GtkWidget *checkbtn_simplify_subject;
GtkWidget *entry_simplify_subject;
GtkWidget *label_regexp_test;
GtkWidget *entry_regexp_test_string;
GtkWidget *label_regexp_result;
GtkWidget *entry_regexp_test_result;
#endif
GtkWidget *checkbtn_folder_chmod;
GtkWidget *entry_folder_chmod;
GtkWidget *folder_color;
GtkWidget *folder_color_btn;
GtkWidget *checkbtn_enable_processing;
GtkWidget *checkbtn_enable_processing_when_opening;
GtkWidget *checkbtn_newmailcheck;
GtkWidget *checkbtn_offlinesync;
GtkWidget *label_offlinesync;
GtkWidget *entry_offlinesync;
GtkWidget *label_end_offlinesync;
GtkWidget *checkbtn_remove_old_offlinesync;
GtkWidget *promote_html_part;
GtkListStore *promote_html_part_menu;
#ifndef G_OS_WIN32
GtkWidget *simplify_subject_rec_checkbtn;
#endif
GtkWidget *folder_chmod_rec_checkbtn;
GtkWidget *folder_color_rec_checkbtn;
GtkWidget *enable_processing_rec_checkbtn;
GtkWidget *enable_processing_when_opening_rec_checkbtn;
GtkWidget *newmailcheck_rec_checkbtn;
GtkWidget *offlinesync_rec_checkbtn;
GtkWidget *promote_html_part_rec_checkbtn;
page->item = item;
/* Table */
table = gtk_table_new(12, 3, FALSE);
gtk_container_set_border_width (GTK_CONTAINER (table), VBOX_BORDER);
gtk_table_set_row_spacings(GTK_TABLE(table), 4);
gtk_table_set_col_spacings(GTK_TABLE(table), 4);
rowcount = 0;
if (!can_save) {
no_save_warning = gtk_label_new(
_("<i>These preferences will not be saved as this folder "
"is a top-level folder. However, you can set them for the "
"whole mailbox tree by using \"Apply to subfolders\".</i>"));
gtk_label_set_use_markup(GTK_LABEL(no_save_warning), TRUE);
gtk_label_set_line_wrap(GTK_LABEL(no_save_warning), TRUE);
gtk_misc_set_alignment(GTK_MISC(no_save_warning), 0.0, 0.5);
gtk_table_attach(GTK_TABLE(table), no_save_warning, 0, 3,
rowcount, rowcount + 1, GTK_FILL, 0, 0, 0);
rowcount++;
}
/* Apply to subfolders */
label = gtk_label_new(_("Apply to\nsubfolders"));
gtk_misc_set_alignment(GTK_MISC(label), 0.5, 0.5);
gtk_table_attach(GTK_TABLE(table), label, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* folder_type */
folder_type = gtkut_sc_combobox_create(NULL, FALSE);
gtk_widget_show (folder_type);
type = F_NORMAL;
if (item->stype == F_INBOX)
type = F_INBOX;
else if (folder_has_parent_of_type(item, F_OUTBOX))
type = F_OUTBOX;
else if (folder_has_parent_of_type(item, F_DRAFT))
type = F_DRAFT;
else if (folder_has_parent_of_type(item, F_QUEUE))
type = F_QUEUE;
else if (folder_has_parent_of_type(item, F_TRASH))
type = F_TRASH;
folder_type_menu = GTK_LIST_STORE(gtk_combo_box_get_model(
GTK_COMBO_BOX(folder_type)));
COMBOBOX_ADD (folder_type_menu, _("Normal"), F_NORMAL);
COMBOBOX_ADD (folder_type_menu, _("Inbox"), F_INBOX);
COMBOBOX_ADD (folder_type_menu, _("Outbox"), F_OUTBOX);
COMBOBOX_ADD (folder_type_menu, _("Drafts"), F_DRAFT);
COMBOBOX_ADD (folder_type_menu, _("Queue"), F_QUEUE);
COMBOBOX_ADD (folder_type_menu, _("Trash"), F_TRASH);
combobox_select_by_data(GTK_COMBO_BOX(folder_type), type);
dummy_checkbtn = gtk_check_button_new();
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(dummy_checkbtn), type != F_INBOX);
gtk_widget_set_sensitive(dummy_checkbtn, FALSE);
if (type == item->stype && type == F_NORMAL)
gtk_widget_set_sensitive(folder_type, TRUE);
else
gtk_widget_set_sensitive(folder_type, FALSE);
label = gtk_label_new(_("Folder type"));
gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
gtk_table_attach(GTK_TABLE(table), label, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_table_attach(GTK_TABLE(table), folder_type, 1, 2,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_table_attach(GTK_TABLE(table), dummy_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
#ifndef G_OS_WIN32
/* Simplify Subject */
checkbtn_simplify_subject = gtk_check_button_new_with_label(_("Simplify Subject RegExp"));
gtk_table_attach(GTK_TABLE(table), checkbtn_simplify_subject, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_simplify_subject),
item->prefs->enable_simplify_subject);
g_signal_connect(G_OBJECT(checkbtn_simplify_subject), "toggled",
G_CALLBACK(folder_regexp_set_subject_example_cb), page);
entry_simplify_subject = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_simplify_subject, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, entry_simplify_subject);
gtk_entry_set_text(GTK_ENTRY(entry_simplify_subject),
SAFE_STRING(item->prefs->simplify_subject_regexp));
g_signal_connect(G_OBJECT(entry_simplify_subject), "changed",
G_CALLBACK(folder_regexp_test_cb), page);
simplify_subject_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), simplify_subject_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Test string */
label_regexp_test = gtk_label_new(_("Test string:"));
gtk_misc_set_alignment(GTK_MISC(label_regexp_test), 1, 0.5);
gtk_table_attach(GTK_TABLE(table), label_regexp_test, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, label_regexp_test);
entry_regexp_test_string = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_regexp_test_string, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, entry_regexp_test_string);
g_signal_connect(G_OBJECT(entry_regexp_test_string), "changed",
G_CALLBACK(folder_regexp_test_cb), page);
rowcount++;
/* Test result */
label_regexp_result = gtk_label_new(_("Result:"));
gtk_misc_set_alignment(GTK_MISC(label_regexp_result), 1, 0.5);
gtk_table_attach(GTK_TABLE(table), label_regexp_result, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, label_regexp_result);
entry_regexp_test_result = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_regexp_test_result, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, entry_regexp_test_result);
gtk_editable_set_editable(GTK_EDITABLE(entry_regexp_test_result), FALSE);
rowcount++;
#endif
/* Folder chmod */
checkbtn_folder_chmod = gtk_check_button_new_with_label(_("Folder chmod"));
gtk_table_attach(GTK_TABLE(table), checkbtn_folder_chmod, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_folder_chmod),
item->prefs->enable_folder_chmod);
entry_folder_chmod = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_folder_chmod, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_folder_chmod, entry_folder_chmod);
if (item->prefs->folder_chmod) {
gchar *buf;
buf = g_strdup_printf("%o", item->prefs->folder_chmod);
gtk_entry_set_text(GTK_ENTRY(entry_folder_chmod), buf);
g_free(buf);
}
folder_chmod_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), folder_chmod_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Folder color */
folder_color = gtk_label_new(_("Folder color"));
gtk_misc_set_alignment(GTK_MISC(folder_color), 0, 0.5);
gtk_table_attach(GTK_TABLE(table), folder_color, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
hbox = gtk_hbox_new(FALSE, 0);
gtk_table_attach(GTK_TABLE(table), hbox, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
folder_color_btn = gtk_button_new_with_label("");
gtk_widget_set_size_request(folder_color_btn, 36, 26);
gtk_box_pack_start (GTK_BOX(hbox), folder_color_btn, FALSE, FALSE, 0);
CLAWS_SET_TIP(folder_color_btn,
_("Pick color for folder"));
page->folder_color = item->prefs->color;
g_signal_connect(G_OBJECT(folder_color_btn), "clicked",
G_CALLBACK(folder_color_set_dialog),
page);
gtkut_set_widget_bgcolor_rgb(folder_color_btn, item->prefs->color);
folder_color_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), folder_color_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Enable processing at startup */
checkbtn_enable_processing =
gtk_check_button_new_with_label(_("Run Processing rules at start-up"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_processing, 0, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_processing),
item->prefs->enable_processing);
enable_processing_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), enable_processing_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Enable processing rules when opening folder */
checkbtn_enable_processing_when_opening =
gtk_check_button_new_with_label(_("Run Processing rules when opening"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_processing_when_opening, 0, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_processing_when_opening),
item->prefs->enable_processing_when_opening);
enable_processing_when_opening_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), enable_processing_when_opening_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Check folder for new mail */
checkbtn_newmailcheck = gtk_check_button_new_with_label(_("Scan for new mail"));
CLAWS_SET_TIP(checkbtn_newmailcheck,
_("Turn this option on if mail is delivered directly "
"to this folder by server side filtering on IMAP or "
"by an external application"));
gtk_table_attach(GTK_TABLE(table), checkbtn_newmailcheck, 0, 2,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_newmailcheck),
item->prefs->newmailcheck);
newmailcheck_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), newmailcheck_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Select HTML part by default? */
hbox = gtk_hbox_new (FALSE, 2);
gtk_widget_show (hbox);
gtk_table_attach (GTK_TABLE(table), hbox, 0, 2,
rowcount, rowcount+1, GTK_FILL, GTK_FILL, 0, 0);
label = gtk_label_new(_("Select the HTML part of multipart messages"));
gtk_widget_show (label);
gtk_box_pack_start (GTK_BOX(hbox), label, FALSE, FALSE, 0);
promote_html_part = gtkut_sc_combobox_create (NULL, FALSE);
gtk_widget_show (promote_html_part);
gtk_box_pack_start (GTK_BOX(hbox), promote_html_part, FALSE, FALSE, 0);
promote_html_part_menu = GTK_LIST_STORE(gtk_combo_box_get_model(
GTK_COMBO_BOX(promote_html_part)));
COMBOBOX_ADD (promote_html_part_menu, _("Default"), HTML_PROMOTE_DEFAULT);
COMBOBOX_ADD (promote_html_part_menu, _("No"), HTML_PROMOTE_NEVER);
COMBOBOX_ADD (promote_html_part_menu, _("Yes"), HTML_PROMOTE_ALWAYS);
combobox_select_by_data(GTK_COMBO_BOX(promote_html_part),
item->prefs->promote_html_part);
CLAWS_SET_TIP(hbox, _("\"Default\" will follow global preference (found in /Preferences/"
"Message View/Text Options)"));
promote_html_part_rec_checkbtn = gtk_check_button_new();
gtk_widget_show (promote_html_part_rec_checkbtn);
gtk_table_attach(GTK_TABLE(table), promote_html_part_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Synchronise folder for offline use */
checkbtn_offlinesync = gtk_check_button_new_with_label(_("Synchronise for offline use"));
gtk_table_attach(GTK_TABLE(table), checkbtn_offlinesync, 0, 2,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
offlinesync_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), offlinesync_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
hbox = gtk_hbox_new (FALSE, 8);
gtk_widget_show (hbox);
gtk_table_attach(GTK_TABLE(table), hbox, 0, 3,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
rowcount++;
hbox_spc = gtk_hbox_new (FALSE, 0);
gtk_widget_show (hbox_spc);
gtk_box_pack_start (GTK_BOX (hbox), hbox_spc, FALSE, FALSE, 0);
gtk_widget_set_size_request (hbox_spc, 12, -1);
label_offlinesync = gtk_label_new(_("Fetch message bodies from the last"));
gtk_widget_show (label_offlinesync);
gtk_box_pack_start (GTK_BOX (hbox), label_offlinesync, FALSE, FALSE, 0);
entry_offlinesync = gtk_entry_new();
gtk_widget_set_size_request (entry_offlinesync, 64, -1);
gtk_widget_show (entry_offlinesync);
CLAWS_SET_TIP(entry_offlinesync, _("0: all bodies"));
gtk_box_pack_start (GTK_BOX (hbox), entry_offlinesync, FALSE, FALSE, 0);
label_end_offlinesync = gtk_label_new(_("days"));
gtk_widget_show (label_end_offlinesync);
gtk_box_pack_start (GTK_BOX (hbox), label_end_offlinesync, FALSE, FALSE, 0);
checkbtn_remove_old_offlinesync = gtk_check_button_new_with_label(
_("Remove older messages bodies"));
hbox2 = gtk_hbox_new (FALSE, 8);
gtk_widget_show (hbox2);
gtk_table_attach(GTK_TABLE(table), hbox2, 0, 3,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
rowcount++;
hbox_spc = gtk_hbox_new (FALSE, 0);
gtk_widget_show (hbox_spc);
gtk_box_pack_start (GTK_BOX (hbox2), hbox_spc, FALSE, FALSE, 0);
gtk_widget_set_size_request (hbox_spc, 12, -1);
gtk_box_pack_start (GTK_BOX (hbox2), checkbtn_remove_old_offlinesync, FALSE, FALSE, 0);
SET_TOGGLE_SENSITIVITY (checkbtn_offlinesync, hbox);
SET_TOGGLE_SENSITIVITY (checkbtn_offlinesync, hbox2);
clean_cache_btn = gtk_button_new_with_label(_("Discard folder cache"));
gtk_widget_show (clean_cache_btn);
gtk_table_attach(GTK_TABLE(table), clean_cache_btn, 0, 1,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
g_signal_connect(G_OBJECT(clean_cache_btn), "clicked",
G_CALLBACK(clean_cache_cb),
page);
gtk_widget_show_all(table);
if (item->folder && (item->folder->klass->type != F_IMAP &&
item->folder->klass->type != F_NEWS)) {
item->prefs->offlinesync = TRUE;
item->prefs->offlinesync_days = 0;
item->prefs->remove_old_bodies = FALSE;
gtk_widget_set_sensitive(GTK_WIDGET(checkbtn_offlinesync),
FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(offlinesync_rec_checkbtn),
FALSE);
gtk_widget_hide(GTK_WIDGET(checkbtn_offlinesync));
gtk_widget_hide(GTK_WIDGET(hbox));
gtk_widget_hide(GTK_WIDGET(hbox2));
gtk_widget_hide(GTK_WIDGET(offlinesync_rec_checkbtn));
gtk_widget_hide(GTK_WIDGET(clean_cache_btn));
}
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_offlinesync),
item->prefs->offlinesync);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_remove_old_offlinesync),
item->prefs->remove_old_bodies);
gtk_entry_set_text(GTK_ENTRY(entry_offlinesync), itos(item->prefs->offlinesync_days));
page->table = table;
page->folder_type = folder_type;
page->no_save_warning = no_save_warning;
#ifndef G_OS_WIN32
page->checkbtn_simplify_subject = checkbtn_simplify_subject;
page->entry_simplify_subject = entry_simplify_subject;
page->entry_regexp_test_string = entry_regexp_test_string;
page->entry_regexp_test_result = entry_regexp_test_result;
#endif
page->checkbtn_folder_chmod = checkbtn_folder_chmod;
page->entry_folder_chmod = entry_folder_chmod;
page->folder_color_btn = folder_color_btn;
page->checkbtn_enable_processing = checkbtn_enable_processing;
page->checkbtn_enable_processing_when_opening = checkbtn_enable_processing_when_opening;
page->checkbtn_newmailcheck = checkbtn_newmailcheck;
page->checkbtn_offlinesync = checkbtn_offlinesync;
page->label_offlinesync = label_offlinesync;
page->entry_offlinesync = entry_offlinesync;
page->label_end_offlinesync = label_end_offlinesync;
page->checkbtn_remove_old_offlinesync = checkbtn_remove_old_offlinesync;
page->promote_html_part = promote_html_part;
#ifndef G_OS_WIN32
page->simplify_subject_rec_checkbtn = simplify_subject_rec_checkbtn;
#endif
page->folder_chmod_rec_checkbtn = folder_chmod_rec_checkbtn;
page->folder_color_rec_checkbtn = folder_color_rec_checkbtn;
page->enable_processing_rec_checkbtn = enable_processing_rec_checkbtn;
page->enable_processing_when_opening_rec_checkbtn = enable_processing_when_opening_rec_checkbtn;
page->newmailcheck_rec_checkbtn = newmailcheck_rec_checkbtn;
page->offlinesync_rec_checkbtn = offlinesync_rec_checkbtn;
page->promote_html_part_rec_checkbtn = promote_html_part_rec_checkbtn;
page->page.widget = table;
#ifndef G_OS_WIN32
folder_regexp_set_subject_example_cb(NULL, page);
#endif
}
static void prefs_folder_item_general_destroy_widget_func(PrefsPage *page_)
{
/* FolderItemGeneralPage *page = (FolderItemGeneralPage *) page_; */
}
/** \brief Save the prefs in page to folder.
*
* If the folder is not the one specified in page->item, then only those properties
* that have the relevant 'apply to sub folders' button checked are saved
*/
static void general_save_folder_prefs(FolderItem *folder, FolderItemGeneralPage *page)
{
FolderItemPrefs *prefs = folder->prefs;
gchar *buf;
gboolean all = FALSE, summary_update_needed = FALSE;
SpecialFolderItemType type = F_NORMAL;
FolderView *folderview = mainwindow_get_mainwindow()->folderview;
HTMLPromoteType promote_html_part = HTML_PROMOTE_DEFAULT;
if (folder->path == NULL)
return;
cm_return_if_fail(prefs != NULL);
if (page->item == folder)
all = TRUE;
type = combobox_get_active_data(GTK_COMBO_BOX(page->folder_type));
if (all && folder->stype != type && page->item->parent_stype == F_NORMAL) {
folder_item_change_type(folder, type);
summary_update_needed = TRUE;
}
promote_html_part =
combobox_get_active_data(GTK_COMBO_BOX(page->promote_html_part));
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->promote_html_part_rec_checkbtn)))
prefs->promote_html_part = promote_html_part;
#ifndef G_OS_WIN32
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->simplify_subject_rec_checkbtn))) {
gboolean old_simplify_subject = prefs->enable_simplify_subject;
int regexp_diffs = strcmp2(prefs->simplify_subject_regexp, gtk_editable_get_chars(
GTK_EDITABLE(page->entry_simplify_subject), 0, -1));
prefs->enable_simplify_subject =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_simplify_subject));
ASSIGN_STRING(prefs->simplify_subject_regexp,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_simplify_subject), 0, -1));
if (old_simplify_subject != prefs->enable_simplify_subject || regexp_diffs != 0)
summary_update_needed = TRUE;
}
#endif
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->folder_chmod_rec_checkbtn))) {
prefs->enable_folder_chmod =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_folder_chmod));
buf = gtk_editable_get_chars(GTK_EDITABLE(page->entry_folder_chmod), 0, -1);
prefs->folder_chmod = prefs_folder_item_chmod_mode(buf);
g_free(buf);
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->folder_color_rec_checkbtn))) {
int old_color = prefs->color;
prefs->color = page->folder_color;
/* update folder view */
if (prefs->color != old_color)
folder_item_update(folder, F_ITEM_UPDATE_MSGCNT);
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->enable_processing_rec_checkbtn))) {
prefs->enable_processing =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_enable_processing));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->enable_processing_when_opening_rec_checkbtn))) {
prefs->enable_processing_when_opening =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_enable_processing_when_opening));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->newmailcheck_rec_checkbtn))) {
prefs->newmailcheck =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_newmailcheck));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->offlinesync_rec_checkbtn))) {
prefs->offlinesync =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_offlinesync));
prefs->offlinesync_days =
atoi(gtk_entry_get_text(GTK_ENTRY(page->entry_offlinesync)));
prefs->remove_old_bodies =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_remove_old_offlinesync));
}
folder_item_prefs_save_config(folder);
if (folder->opened && summary_update_needed) {
summary_set_prefs_from_folderitem(folderview->summaryview, folder);
summary_show(folderview->summaryview, folder);
}
}
static gboolean general_save_recurse_func(GNode *node, gpointer data)
{
FolderItem *item = (FolderItem *) node->data;
FolderItemGeneralPage *page = (FolderItemGeneralPage *) data;
cm_return_val_if_fail(item != NULL, TRUE);
cm_return_val_if_fail(page != NULL, TRUE);
general_save_folder_prefs(item, page);
/* optimise by not continuing if none of the 'apply to sub folders'
check boxes are selected - and optimise the checking by only doing
it once */
if ((node == page->item->node) &&
!(
#ifndef G_OS_WIN32
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->simplify_subject_rec_checkbtn)) ||
#endif
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->folder_chmod_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->folder_color_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->enable_processing_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->enable_processing_when_opening_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->newmailcheck_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->offlinesync_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->promote_html_part_rec_checkbtn))
))
return TRUE;
else
return FALSE;
}
static void prefs_folder_item_general_save_func(PrefsPage *page_)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *) page_;
g_node_traverse(page->item->node, G_PRE_ORDER, G_TRAVERSE_ALL,
-1, general_save_recurse_func, page);
main_window_set_menu_sensitive(mainwindow_get_mainwindow());
}
static RecvProtocol item_protocol(FolderItem *item)
{
if (!item)
return A_NONE;
if (!item->folder)
return A_NONE;
if (!item->folder->account)
return A_NONE;
return item->folder->account->protocol;
}
static void prefs_folder_item_compose_create_widget_func(PrefsPage * page_,
GtkWindow * window,
gpointer data)
{
FolderItemComposePage *page = (FolderItemComposePage *) page_;
FolderItem *item = (FolderItem *) data;
guint rowcount;
gchar *text = NULL;
GtkWidget *table;
GtkWidget *label;
GtkWidget *no_save_warning = NULL;
GtkWidget *checkbtn_request_return_receipt = NULL;
GtkWidget *checkbtn_save_copy_to_folder = NULL;
GtkWidget *checkbtn_default_to = NULL;
GtkWidget *entry_default_to = NULL;
GtkWidget *checkbtn_default_reply_to = NULL;
GtkWidget *entry_default_reply_to = NULL;
GtkWidget *checkbtn_default_cc = NULL;
GtkWidget *entry_default_cc = NULL;
GtkWidget *checkbtn_default_bcc = NULL;
GtkWidget *entry_default_bcc = NULL;
GtkWidget *checkbtn_default_replyto = NULL;
GtkWidget *entry_default_replyto = NULL;
GtkWidget *checkbtn_enable_default_account = NULL;
GtkWidget *optmenu_default_account = NULL;
GtkListStore *optmenu_default_account_menu = NULL;
GtkTreeIter iter;
#if USE_ENCHANT
GtkWidget *checkbtn_enable_default_dictionary = NULL;
GtkWidget *combo_default_dictionary = NULL;
GtkWidget *checkbtn_enable_default_alt_dictionary = NULL;
GtkWidget *combo_default_alt_dictionary = NULL;
GtkWidget *default_dictionary_rec_checkbtn = NULL;
GtkWidget *default_alt_dictionary_rec_checkbtn = NULL;
gchar *dictionary;
#endif
GtkWidget *request_return_receipt_rec_checkbtn = NULL;
GtkWidget *save_copy_to_folder_rec_checkbtn = NULL;
GtkWidget *default_to_rec_checkbtn = NULL;
GtkWidget *default_reply_to_rec_checkbtn = NULL;
GtkWidget *default_cc_rec_checkbtn = NULL;
GtkWidget *default_bcc_rec_checkbtn = NULL;
GtkWidget *default_replyto_rec_checkbtn = NULL;
GtkWidget *default_account_rec_checkbtn = NULL;
GList *cur_ac;
GList *account_list;
PrefsAccount *ac_prefs;
gboolean default_account_set = FALSE;
page->item = item;
/* Table */
#if USE_ENCHANT
# define TABLEHEIGHT 7
#else
# define TABLEHEIGHT 6
#endif
table = gtk_table_new(TABLEHEIGHT, 3, FALSE);
gtk_container_set_border_width (GTK_CONTAINER (table), VBOX_BORDER);
gtk_table_set_row_spacings(GTK_TABLE(table), 4);
gtk_table_set_col_spacings(GTK_TABLE(table), 4);
rowcount = 0;
if (!can_save) {
no_save_warning = gtk_label_new(
_("<i>These preferences will not be saved as this folder "
"is a top-level folder. However, you can set them for the "
"whole mailbox tree by using \"Apply to subfolders\".</i>"));
gtk_label_set_use_markup(GTK_LABEL(no_save_warning), TRUE);
gtk_label_set_line_wrap(GTK_LABEL(no_save_warning), TRUE);
gtk_misc_set_alignment(GTK_MISC(no_save_warning), 0.0, 0.5);
gtk_table_attach(GTK_TABLE(table), no_save_warning, 0, 3,
rowcount, rowcount + 1, GTK_FILL, 0, 0, 0);
rowcount++;
}
/* Apply to subfolders */
label = gtk_label_new(_("Apply to\nsubfolders"));
gtk_misc_set_alignment(GTK_MISC(label), 0.5, 0.5);
gtk_table_attach(GTK_TABLE(table), label, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
if (item_protocol(item) != A_NNTP) {
/* Request Return Receipt */
checkbtn_request_return_receipt = gtk_check_button_new_with_label
(_("Request Return Receipt"));
gtk_table_attach(GTK_TABLE(table), checkbtn_request_return_receipt,
0, 2, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL,
GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_request_return_receipt),
item->ret_rcpt ? TRUE : FALSE);
request_return_receipt_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), request_return_receipt_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Save Copy to Folder */
checkbtn_save_copy_to_folder = gtk_check_button_new_with_label
(_("Save copy of outgoing messages to this folder instead of Sent"));
gtk_table_attach(GTK_TABLE(table), checkbtn_save_copy_to_folder, 0, 2,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_save_copy_to_folder),
item->prefs->save_copy_to_folder ? TRUE : FALSE);
save_copy_to_folder_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), save_copy_to_folder_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default To */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("To:"), NULL);
checkbtn_default_to = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_to, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_to),
item->prefs->enable_default_to);
g_free(text);
entry_default_to = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_to, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_to, entry_default_to);
gtk_entry_set_text(GTK_ENTRY(entry_default_to), SAFE_STRING(item->prefs->default_to));
address_completion_register_entry(GTK_ENTRY(entry_default_to),
TRUE);
default_to_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_to_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default address to reply to */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("To:"),
_(" for replies"), NULL);
checkbtn_default_reply_to = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_reply_to, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_reply_to),
item->prefs->enable_default_reply_to);
g_free(text);
entry_default_reply_to = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_reply_to, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_reply_to, entry_default_reply_to);
gtk_entry_set_text(GTK_ENTRY(entry_default_reply_to), SAFE_STRING(item->prefs->default_reply_to));
address_completion_register_entry(
GTK_ENTRY(entry_default_reply_to), TRUE);
default_reply_to_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_reply_to_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default Cc */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("Cc:"), NULL);
checkbtn_default_cc = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_cc, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_cc),
item->prefs->enable_default_cc);
g_free(text);
entry_default_cc = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_cc, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_cc, entry_default_cc);
gtk_entry_set_text(GTK_ENTRY(entry_default_cc), SAFE_STRING(item->prefs->default_cc));
address_completion_register_entry(GTK_ENTRY(entry_default_cc),
TRUE);
default_cc_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_cc_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default Bcc */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("Bcc:"), NULL);
checkbtn_default_bcc = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_bcc, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_bcc),
item->prefs->enable_default_bcc);
g_free(text);
entry_default_bcc = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_bcc, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_bcc, entry_default_bcc);
gtk_entry_set_text(GTK_ENTRY(entry_default_bcc), SAFE_STRING(item->prefs->default_bcc));
address_completion_register_entry(GTK_ENTRY(entry_default_bcc),
TRUE);
default_bcc_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_bcc_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default Reply-to */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("Reply-To:"), NULL);
checkbtn_default_replyto = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_replyto, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_replyto),
item->prefs->enable_default_replyto);
g_free(text);
entry_default_replyto = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_replyto, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_replyto, entry_default_replyto);
gtk_entry_set_text(GTK_ENTRY(entry_default_replyto), SAFE_STRING(item->prefs->default_replyto));
address_completion_register_entry(GTK_ENTRY(entry_default_replyto),
TRUE);
default_replyto_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_replyto_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
}
/* Default account */
checkbtn_enable_default_account = gtk_check_button_new_with_label(_("Default account"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_default_account, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_default_account),
item->prefs->enable_default_account);
optmenu_default_account = gtkut_sc_combobox_create(NULL, FALSE);
gtk_table_attach(GTK_TABLE(table), optmenu_default_account, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
optmenu_default_account_menu = GTK_LIST_STORE(
gtk_combo_box_get_model(GTK_COMBO_BOX(optmenu_default_account)));
account_list = account_get_list();
for (cur_ac = account_list; cur_ac != NULL; cur_ac = cur_ac->next) {
ac_prefs = (PrefsAccount *)cur_ac->data;
if (item->folder->account &&
( (item_protocol(item) == A_NNTP && ac_prefs->protocol != A_NNTP)
||(item_protocol(item) != A_NNTP && ac_prefs->protocol == A_NNTP)))
continue;
if (item->folder->klass->type != F_NEWS && ac_prefs->protocol == A_NNTP)
continue;
COMBOBOX_ADD_ESCAPED (optmenu_default_account_menu,
ac_prefs->account_name?ac_prefs->account_name : _("Untitled"),
ac_prefs->account_id);
/* Set combobox to current default account id */
if (ac_prefs->account_id == item->prefs->default_account) {
combobox_select_by_data(GTK_COMBO_BOX(optmenu_default_account),
ac_prefs->account_id);
default_account_set = TRUE;
}
}
/* If nothing has been set (folder doesn't have a default account set),
* pre-select global default account, since that's what actually used
* anyway. We don't want nothing selected in combobox. */
if( !default_account_set )
combobox_select_by_data(GTK_COMBO_BOX(optmenu_default_account),
account_get_default()->account_id);
SET_TOGGLE_SENSITIVITY(checkbtn_enable_default_account, optmenu_default_account);
default_account_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_account_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
#if USE_ENCHANT
/* Default dictionary */
checkbtn_enable_default_dictionary = gtk_check_button_new_with_label(_("Default dictionary"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_default_dictionary, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_default_dictionary),
item->prefs->enable_default_dictionary);
combo_default_dictionary = gtkaspell_dictionary_combo_new(TRUE);
gtk_table_attach(GTK_TABLE(table), combo_default_dictionary, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
dictionary = item->prefs->default_dictionary;
if (dictionary && strrchr(dictionary, '/')) {
gchar *tmp = g_strdup(strrchr(dictionary, '/')+1);
g_free(item->prefs->default_dictionary);
item->prefs->default_dictionary = tmp;
dictionary = item->prefs->default_dictionary;
}
if (item->prefs->default_dictionary &&
strchr(item->prefs->default_dictionary, '-')) {
*(strchr(item->prefs->default_dictionary, '-')) = '\0';
}
if (dictionary)
gtkaspell_set_dictionary_menu_active_item(
GTK_COMBO_BOX(combo_default_dictionary), dictionary);
SET_TOGGLE_SENSITIVITY(checkbtn_enable_default_dictionary, combo_default_dictionary);
default_dictionary_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_dictionary_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default dictionary */
checkbtn_enable_default_alt_dictionary = gtk_check_button_new_with_label(_("Default alternate dictionary"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_default_alt_dictionary, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_default_alt_dictionary),
item->prefs->enable_default_alt_dictionary);
combo_default_alt_dictionary = gtkaspell_dictionary_combo_new(FALSE);
gtk_table_attach(GTK_TABLE(table), combo_default_alt_dictionary, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
dictionary = item->prefs->default_alt_dictionary;
if (dictionary && strrchr(dictionary, '/')) {
gchar *tmp = g_strdup(strrchr(dictionary, '/')+1);
g_free(item->prefs->default_alt_dictionary);
item->prefs->default_alt_dictionary = tmp;
dictionary = item->prefs->default_alt_dictionary;
}
if (item->prefs->default_alt_dictionary &&
strchr(item->prefs->default_alt_dictionary, '-')) {
*(strchr(item->prefs->default_alt_dictionary, '-')) = '\0';
}
if (dictionary)
gtkaspell_set_dictionary_menu_active_item(
GTK_COMBO_BOX(combo_default_alt_dictionary), dictionary);
SET_TOGGLE_SENSITIVITY(checkbtn_enable_default_alt_dictionary, combo_default_alt_dictionary);
default_alt_dictionary_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_alt_dictionary_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
#endif
gtk_widget_show_all(table);
page->window = GTK_WIDGET(window);
page->table = table;
page->no_save_warning = no_save_warning;
page->checkbtn_request_return_receipt = checkbtn_request_return_receipt;
page->checkbtn_save_copy_to_folder = checkbtn_save_copy_to_folder;
page->checkbtn_default_to = checkbtn_default_to;
page->entry_default_to = entry_default_to;
page->checkbtn_default_reply_to = checkbtn_default_reply_to;
page->entry_default_reply_to = entry_default_reply_to;
page->checkbtn_default_cc = checkbtn_default_cc;
page->entry_default_cc = entry_default_cc;
page->checkbtn_default_bcc = checkbtn_default_bcc;
page->entry_default_bcc = entry_default_bcc;
page->checkbtn_default_replyto = checkbtn_default_replyto;
page->entry_default_replyto = entry_default_replyto;
page->checkbtn_enable_default_account = checkbtn_enable_default_account;
page->optmenu_default_account = optmenu_default_account;
#ifdef USE_ENCHANT
page->checkbtn_enable_default_dictionary = checkbtn_enable_default_dictionary;
page->combo_default_dictionary = combo_default_dictionary;
page->checkbtn_enable_default_alt_dictionary = checkbtn_enable_default_alt_dictionary;
page->combo_default_alt_dictionary = combo_default_alt_dictionary;
#endif
page->request_return_receipt_rec_checkbtn = request_return_receipt_rec_checkbtn;
page->save_copy_to_folder_rec_checkbtn = save_copy_to_folder_rec_checkbtn;
page->default_to_rec_checkbtn = default_to_rec_checkbtn;
page->default_reply_to_rec_checkbtn = default_reply_to_rec_checkbtn;
page->default_cc_rec_checkbtn = default_cc_rec_checkbtn;
page->default_bcc_rec_checkbtn = default_bcc_rec_checkbtn;
page->default_replyto_rec_checkbtn = default_replyto_rec_checkbtn;
page->default_account_rec_checkbtn = default_account_rec_checkbtn;
#if USE_ENCHANT
page->default_dictionary_rec_checkbtn = default_dictionary_rec_checkbtn;
page->default_alt_dictionary_rec_checkbtn = default_alt_dictionary_rec_checkbtn;
#endif
page->page.widget = table;
}
static void prefs_folder_item_compose_destroy_widget_func(PrefsPage *page_)
{
FolderItemComposePage *page = (FolderItemComposePage *) page_;
if (page->entry_default_to)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_to));
if (page->entry_default_reply_to)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_reply_to));
if (page->entry_default_cc)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_cc));
if (page->entry_default_bcc)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_bcc));
if (page->entry_default_replyto)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_replyto));
}
/** \brief Save the prefs in page to folder.
*
* If the folder is not the one specified in page->item, then only those properties
* that have the relevant 'apply to sub folders' button checked are saved
*/
static void compose_save_folder_prefs(FolderItem *folder, FolderItemComposePage *page)
{
FolderItemPrefs *prefs = folder->prefs;
gboolean all = FALSE;
if (folder->path == NULL)
return;
if (page->item == folder)
all = TRUE;
cm_return_if_fail(prefs != NULL);
if (item_protocol(folder) != A_NNTP) {
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->request_return_receipt_rec_checkbtn))) {
prefs->request_return_receipt =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_request_return_receipt));
/* MIGRATION */
folder->ret_rcpt = prefs->request_return_receipt;
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->save_copy_to_folder_rec_checkbtn))) {
prefs->save_copy_to_folder =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_save_copy_to_folder));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_to_rec_checkbtn))) {
prefs->enable_default_to =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_to));
ASSIGN_STRING(prefs->default_to,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_to), 0, -1));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_reply_to_rec_checkbtn))) {
prefs->enable_default_reply_to =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_reply_to));
ASSIGN_STRING(prefs->default_reply_to,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_reply_to), 0, -1));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_cc_rec_checkbtn))) {
prefs->enable_default_cc =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_cc));
ASSIGN_STRING(prefs->default_cc,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_cc), 0, -1));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_bcc_rec_checkbtn))) {
prefs->enable_default_bcc =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_bcc));
ASSIGN_STRING(prefs->default_bcc,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_bcc), 0, -1));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_replyto_rec_checkbtn))) {
prefs->enable_default_replyto =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_replyto));
ASSIGN_STRING(prefs->default_replyto,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_replyto), 0, -1));
}
} else {
prefs->request_return_receipt = FALSE;
prefs->save_copy_to_folder = FALSE;
prefs->enable_default_to = FALSE;
prefs->enable_default_reply_to = FALSE;
prefs->enable_default_cc = FALSE;
prefs->enable_default_bcc = FALSE;
prefs->enable_default_replyto = FALSE;
}
if (all || gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON(page->default_account_rec_checkbtn))) {
prefs->enable_default_account =
gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON(page->checkbtn_enable_default_account));
prefs->default_account = combobox_get_active_data(
GTK_COMBO_BOX(page->optmenu_default_account));
}
#if USE_ENCHANT
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_dictionary_rec_checkbtn))) {
prefs->enable_default_dictionary =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_enable_default_dictionary));
ASSIGN_STRING(prefs->default_dictionary,
gtkaspell_get_dictionary_menu_active_item(
GTK_COMBO_BOX(page->combo_default_dictionary)));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_alt_dictionary_rec_checkbtn))) {
prefs->enable_default_alt_dictionary =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_enable_default_alt_dictionary));
ASSIGN_STRING(prefs->default_alt_dictionary,
gtkaspell_get_dictionary_menu_active_item(
GTK_COMBO_BOX(page->combo_default_alt_dictionary)));
}
#endif
folder_item_prefs_save_config(folder);
}
static gboolean compose_save_recurse_func(GNode *node, gpointer data)
{
FolderItem *item = (FolderItem *) node->data;
FolderItemComposePage *page = (FolderItemComposePage *) data;
cm_return_val_if_fail(item != NULL, TRUE);
cm_return_val_if_fail(page != NULL, TRUE);
compose_save_folder_prefs(item, page);
/* optimise by not continuing if none of the 'apply to sub folders'
check boxes are selected - and optimise the checking by only doing
it once */
if ((node == page->item->node) && item_protocol(item) != A_NNTP &&
!(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->request_return_receipt_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->save_copy_to_folder_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_to_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_account_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_cc_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_bcc_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_replyto_rec_checkbtn)) ||
#if USE_ENCHANT
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_dictionary_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_alt_dictionary_rec_checkbtn)) ||
#endif
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_reply_to_rec_checkbtn))
))
return TRUE;
else if ((node == page->item->node) && item_protocol(item) == A_NNTP &&
!(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_account_rec_checkbtn))
#if USE_ENCHANT
|| gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_dictionary_rec_checkbtn))
|| gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_alt_dictionary_rec_checkbtn))
#endif
))
return TRUE;
else
return FALSE;
}
static void prefs_folder_item_compose_save_func(PrefsPage *page_)
{
FolderItemComposePage *page = (FolderItemComposePage *) page_;
g_node_traverse(page->item->node, G_PRE_ORDER, G_TRAVERSE_ALL,
-1, compose_save_recurse_func, page);
}
static void prefs_folder_item_templates_create_widget_func(PrefsPage * page_,
GtkWindow * window,
gpointer data)
{
FolderItemTemplatesPage *page = (FolderItemTemplatesPage *) page_;
FolderItem *item = (FolderItem *) data;
GtkWidget *notebook;
GtkWidget *vbox;
GtkWidget *page_vbox;
GtkWidget *no_save_warning;
GtkWidget *new_msg_format_rec_checkbtn;
GtkWidget *reply_format_rec_checkbtn;
GtkWidget *forward_format_rec_checkbtn;
GtkWidget *hbox;
GtkWidget *vbox_format;
page->item = item;
page_vbox = gtk_vbox_new (FALSE, 0);
gtk_container_set_border_width (GTK_CONTAINER (page_vbox), VBOX_BORDER);
gtk_widget_show (page_vbox);
if (!can_save) {
no_save_warning = gtk_label_new(
_("<i>These preferences will not be saved as this folder "
"is a top-level folder. However, you can set them for the "
"whole mailbox tree by using \"Apply to subfolders\".</i>"));
gtk_label_set_use_markup(GTK_LABEL(no_save_warning), TRUE);
gtk_label_set_line_wrap(GTK_LABEL(no_save_warning), TRUE);
gtk_misc_set_alignment(GTK_MISC(no_save_warning), 0.0, 0.5);
gtk_box_pack_start(GTK_BOX(page_vbox), no_save_warning, FALSE, FALSE, 0);
}
/* Notebook */
notebook = gtk_notebook_new();
gtk_widget_show(notebook);
gtk_box_pack_start(GTK_BOX(page_vbox), notebook, TRUE, TRUE, 4);
/* compose format */
vbox = gtk_vbox_new (FALSE, VSPACING);
gtk_widget_show (vbox);
gtk_container_set_border_width (GTK_CONTAINER (vbox), VBOX_BORDER);
quotefmt_create_new_msg_fmt_widgets(
window,
vbox,
&page->checkbtn_compose_with_format,
&page->compose_override_from_format,
&page->compose_subject_format,
&page->compose_body_format,
FALSE, FALSE);
address_completion_register_entry(GTK_ENTRY(page->compose_override_from_format),
TRUE);
vbox_format = gtk_widget_get_parent(
gtk_widget_get_parent(page->compose_body_format));
hbox = gtk_hbox_new (FALSE, 0);
gtk_box_pack_end (GTK_BOX(vbox_format), hbox, FALSE, FALSE, 0);
quotefmt_add_info_button(window, hbox);
new_msg_format_rec_checkbtn = gtk_check_button_new_with_label(
_("Apply to subfolders"));
gtk_box_pack_end (GTK_BOX(hbox), new_msg_format_rec_checkbtn, FALSE, FALSE, 0);
gtk_notebook_append_page(GTK_NOTEBOOK(notebook), vbox, gtk_label_new(_("Compose")));
/* reply format */
vbox = gtk_vbox_new (FALSE, VSPACING);
gtk_widget_show (vbox);
gtk_container_set_border_width (GTK_CONTAINER (vbox), VBOX_BORDER);
quotefmt_create_reply_fmt_widgets(
window,
vbox,
&page->checkbtn_reply_with_format,
&page->reply_override_from_format,
&page->reply_quotemark,
&page->reply_body_format,
FALSE, FALSE);
address_completion_register_entry(GTK_ENTRY(page->reply_override_from_format),
TRUE);
vbox_format = gtk_widget_get_parent(
gtk_widget_get_parent(page->reply_body_format));
hbox = gtk_hbox_new (FALSE, 0);
gtk_box_pack_end (GTK_BOX(vbox_format), hbox, FALSE, FALSE, 0);
quotefmt_add_info_button(window, hbox);
reply_format_rec_checkbtn = gtk_check_button_new_with_label(
_("Apply to subfolders"));
gtk_box_pack_end (GTK_BOX(hbox), reply_format_rec_checkbtn, FALSE, FALSE, 0);
gtk_notebook_append_page(GTK_NOTEBOOK(notebook), vbox, gtk_label_new(_("Reply")));
/* forward format */
vbox = gtk_vbox_new (FALSE, VSPACING);
gtk_widget_show (vbox);
gtk_container_set_border_width (GTK_CONTAINER (vbox), VBOX_BORDER);
quotefmt_create_forward_fmt_widgets(
window,
vbox,
&page->checkbtn_forward_with_format,
&page->forward_override_from_format,
&page->forward_quotemark,
&page->forward_body_format,
FALSE, FALSE);
address_completion_register_entry(GTK_ENTRY(page->forward_override_from_format),
TRUE);
vbox_format = gtk_widget_get_parent(
gtk_widget_get_parent(page->forward_body_format));
hbox = gtk_hbox_new (FALSE, 0);
gtk_box_pack_end (GTK_BOX(vbox_format), hbox, FALSE, FALSE, 0);
quotefmt_add_info_button(window, hbox);
forward_format_rec_checkbtn = gtk_check_button_new_with_label(
_("Apply to subfolders"));
gtk_box_pack_end (GTK_BOX(hbox), forward_format_rec_checkbtn, FALSE, FALSE, 0);
gtk_notebook_append_page(GTK_NOTEBOOK(notebook), vbox, gtk_label_new(_("Forward")));
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(page->checkbtn_compose_with_format),
item->prefs->compose_with_format);
pref_set_entry_from_pref(GTK_ENTRY(page->compose_override_from_format),
item->prefs->compose_override_from_format);
pref_set_entry_from_pref(GTK_ENTRY(page->compose_subject_format),
item->prefs->compose_subject_format);
pref_set_textview_from_pref(GTK_TEXT_VIEW(page->compose_body_format),
item->prefs->compose_body_format);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(page->checkbtn_reply_with_format),
item->prefs->reply_with_format);
pref_set_entry_from_pref(GTK_ENTRY(page->reply_quotemark),
item->prefs->reply_quotemark);
pref_set_entry_from_pref(GTK_ENTRY(page->reply_override_from_format),
item->prefs->reply_override_from_format);
pref_set_textview_from_pref(GTK_TEXT_VIEW(page->reply_body_format),
item->prefs->reply_body_format);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(page->checkbtn_forward_with_format),
item->prefs->forward_with_format);
pref_set_entry_from_pref(GTK_ENTRY(page->forward_quotemark),
item->prefs->forward_quotemark);
pref_set_entry_from_pref(GTK_ENTRY(page->forward_override_from_format),
item->prefs->forward_override_from_format);
pref_set_textview_from_pref(GTK_TEXT_VIEW(page->forward_body_format),
item->prefs->forward_body_format);
gtk_widget_show_all(page_vbox);
page->window = GTK_WIDGET(window);
page->new_msg_format_rec_checkbtn = new_msg_format_rec_checkbtn;
page->reply_format_rec_checkbtn = reply_format_rec_checkbtn;
page->forward_format_rec_checkbtn = forward_format_rec_checkbtn;
page->page.widget = page_vbox;
}
static void prefs_folder_item_templates_destroy_widget_func(PrefsPage *page_)
{
FolderItemTemplatesPage *page = (FolderItemTemplatesPage *) page_;
if (page->compose_override_from_format)
address_completion_unregister_entry(GTK_ENTRY(page->compose_override_from_format));
if (page->reply_override_from_format)
address_completion_unregister_entry(GTK_ENTRY(page->reply_override_from_format));
if (page->forward_override_from_format)
address_completion_unregister_entry(GTK_ENTRY(page->forward_override_from_format));
}
/** \brief Save the prefs in page to folder.
*
* If the folder is not the one specified in page->item, then only those properties
* that have the relevant 'apply to sub folders' button checked are saved
*/
static void templates_save_folder_prefs(FolderItem *folder, FolderItemTemplatesPage *page)
{
FolderItemPrefs *prefs = folder->prefs;
gboolean all = FALSE;
if (folder->path == NULL)
return;
if (page->item == folder)
all = TRUE;
cm_return_if_fail(prefs != NULL);
/* save and check formats */
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->new_msg_format_rec_checkbtn))) {
prefs->compose_with_format =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_compose_with_format));
prefs->compose_override_from_format = pref_get_pref_from_entry(
GTK_ENTRY(page->compose_override_from_format));
prefs->compose_subject_format = pref_get_pref_from_entry(
GTK_ENTRY(page->compose_subject_format));
prefs->compose_body_format = pref_get_pref_from_textview(
GTK_TEXT_VIEW(page->compose_body_format));
quotefmt_check_new_msg_formats(prefs->compose_with_format,
prefs->compose_override_from_format,
prefs->compose_subject_format,
prefs->compose_body_format);
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->reply_format_rec_checkbtn))) {
prefs->reply_with_format =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_reply_with_format));
prefs->reply_quotemark = gtk_editable_get_chars(
GTK_EDITABLE(page->reply_quotemark), 0, -1);
prefs->reply_override_from_format = pref_get_pref_from_entry(
GTK_ENTRY(page->reply_override_from_format));
prefs->reply_body_format = pref_get_pref_from_textview(
GTK_TEXT_VIEW(page->reply_body_format));
quotefmt_check_reply_formats(prefs->reply_with_format,
prefs->reply_override_from_format,
prefs->reply_quotemark,
prefs->reply_body_format);
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->forward_format_rec_checkbtn))) {
prefs->forward_with_format =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_forward_with_format));
prefs->forward_quotemark = gtk_editable_get_chars(
GTK_EDITABLE(page->forward_quotemark), 0, -1);
prefs->forward_override_from_format = pref_get_pref_from_entry(
GTK_ENTRY(page->forward_override_from_format));
prefs->forward_body_format = pref_get_pref_from_textview(
GTK_TEXT_VIEW(page->forward_body_format));
quotefmt_check_forward_formats(prefs->forward_with_format,
prefs->forward_override_from_format,
prefs->forward_quotemark,
prefs->forward_body_format);
}
folder_item_prefs_save_config(folder);
}
static gboolean templates_save_recurse_func(GNode *node, gpointer data)
{
FolderItem *item = (FolderItem *) node->data;
FolderItemTemplatesPage *page = (FolderItemTemplatesPage *) data;
cm_return_val_if_fail(item != NULL, TRUE);
cm_return_val_if_fail(page != NULL, TRUE);
templates_save_folder_prefs(item, page);
/* optimise by not continuing if none of the 'apply to sub folders'
check boxes are selected - and optimise the checking by only doing
it once */
if ((node == page->item->node) &&
!(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->new_msg_format_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->reply_format_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->forward_format_rec_checkbtn))))
return TRUE;
else
return FALSE;
return FALSE;
}
static void prefs_folder_item_templates_save_func(PrefsPage *page_)
{
FolderItemTemplatesPage *page = (FolderItemTemplatesPage *) page_;
g_node_traverse(page->item->node, G_PRE_ORDER, G_TRAVERSE_ALL,
-1, templates_save_recurse_func, page);
}
static gint prefs_folder_item_chmod_mode(gchar *folder_chmod)
{
gint newmode = 0;
gchar *tmp;
if (folder_chmod) {
newmode = strtol(folder_chmod, &tmp, 8);
if (!(*(folder_chmod) && !(*tmp)))
newmode = 0;
}
return newmode;
}
static void folder_color_set_dialog(GtkWidget *widget, gpointer data)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *) data;
gint rgbcolor;
rgbcolor = colorsel_select_color_rgb(_("Pick color for folder"),
page->folder_color);
gtkut_set_widget_bgcolor_rgb(page->folder_color_btn, rgbcolor);
page->folder_color = rgbcolor;
}
static void clean_cache_cb(GtkWidget *widget, gpointer data)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *) data;
FolderItem *item = page->item;
gboolean was_open = FALSE;
FolderView *folderview = NULL;
if (alertpanel_full(_("Discard cache"),
_("Do you really want to discard the local cached "
"data for this folder?"),
GTK_STOCK_CANCEL, _("+Discard"), NULL, FALSE,
NULL, ALERT_WARNING, G_ALERTDEFAULT)
!= G_ALERTALTERNATE)
return;
if (mainwindow_get_mainwindow())
folderview = mainwindow_get_mainwindow()->folderview;
if (folderview && item->opened) {
folderview_close_opened(folderview);
was_open = TRUE;
}
folder_item_discard_cache(item);
if (was_open)
folderview_select(folderview,item);
}
#ifndef G_OS_WIN32
static regex_t *summary_compile_simplify_regexp(gchar *simplify_subject_regexp)
{
int err;
gchar buf[BUFFSIZE];
regex_t *preg = NULL;
preg = g_new0(regex_t, 1);
err = string_match_precompile(simplify_subject_regexp,
preg, REG_EXTENDED);
if (err) {
regerror(err, preg, buf, BUFFSIZE);
g_free(preg);
preg = NULL;
}
return preg;
}
static void folder_regexp_test_cb(GtkWidget *widget, gpointer data)
{
#if !GTK_CHECK_VERSION(3, 0, 0)
static GdkColor red;
static gboolean colors_initialised = FALSE;
#else
static GdkColor red = { (guint32)0, (guint16)0xff, (guint16)0x70, (guint16)0x70 };
#endif
static gchar buf[BUFFSIZE];
FolderItemGeneralPage *page = (FolderItemGeneralPage *)data;
gchar *test_string, *regexp;
regex_t *preg;
regexp = g_strdup(gtk_entry_get_text(GTK_ENTRY(page->entry_simplify_subject)));
test_string = g_strdup(gtk_entry_get_text(GTK_ENTRY(page->entry_regexp_test_string)));
if (!regexp || !regexp[0]) {
gtk_widget_modify_base(page->entry_simplify_subject,
GTK_STATE_NORMAL, NULL);
if (test_string)
gtk_entry_set_text(GTK_ENTRY(page->entry_regexp_test_result), test_string);
g_free(test_string);
g_free(regexp);
return;
}
if (!test_string || !test_string[0]) {
g_free(test_string);
g_free(regexp);
return;
}
#if !GTK_CHECK_VERSION(3, 0, 0)
if (!colors_initialised) {
gdk_color_parse("#ff7070", &red);
colors_initialised = gdk_colormap_alloc_color(
gdk_colormap_get_system(), &red, FALSE, TRUE);
}
#endif
preg = summary_compile_simplify_regexp(regexp);
#if !GTK_CHECK_VERSION(3, 0, 0)
if (colors_initialised)
gtk_widget_modify_base(page->entry_simplify_subject,
GTK_STATE_NORMAL, preg ? NULL : &red);
#endif
if (preg != NULL) {
string_remove_match(buf, BUFFSIZE, test_string, preg);
gtk_entry_set_text(GTK_ENTRY(page->entry_regexp_test_result), buf);
regfree(preg);
g_free(preg);
}
g_free(test_string);
g_free(regexp);
}
static gchar *folder_regexp_get_subject_example(void)
{
MsgInfo *msginfo_selected;
SummaryView *summaryview = NULL;
if (!mainwindow_get_mainwindow())
return NULL;
summaryview = mainwindow_get_mainwindow()->summaryview;
msginfo_selected = summary_get_selected_msg(summaryview);
return msginfo_selected ? g_strdup(msginfo_selected->subject) : NULL;
}
static void folder_regexp_set_subject_example_cb(GtkWidget *widget, gpointer data)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *)data;
if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_simplify_subject))) {
gchar *subject = folder_regexp_get_subject_example();
if (subject) {
gtk_entry_set_text(GTK_ENTRY(page->entry_regexp_test_string), subject);
g_free(subject);
}
}
}
#endif
static void register_general_page()
{
static gchar *pfi_general_path[2];
static FolderItemGeneralPage folder_item_general_page;
pfi_general_path[0] = _("General");
pfi_general_path[1] = NULL;
folder_item_general_page.page.path = pfi_general_path;
folder_item_general_page.page.create_widget = prefs_folder_item_general_create_widget_func;
folder_item_general_page.page.destroy_widget = prefs_folder_item_general_destroy_widget_func;
folder_item_general_page.page.save_page = prefs_folder_item_general_save_func;
prefs_folder_item_register_page((PrefsPage *) &folder_item_general_page, NULL);
}
static void register_compose_page(void)
{
static gchar *pfi_compose_path[2];
static FolderItemComposePage folder_item_compose_page;
pfi_compose_path[0] = _("Compose");
pfi_compose_path[1] = NULL;
folder_item_compose_page.page.path = pfi_compose_path;
folder_item_compose_page.page.create_widget = prefs_folder_item_compose_create_widget_func;
folder_item_compose_page.page.destroy_widget = prefs_folder_item_compose_destroy_widget_func;
folder_item_compose_page.page.save_page = prefs_folder_item_compose_save_func;
prefs_folder_item_register_page((PrefsPage *) &folder_item_compose_page, NULL);
}
static void register_templates_page(void)
{
static gchar *pfi_templates_path[2];
static FolderItemTemplatesPage folder_item_templates_page;
pfi_templates_path[0] = _("Templates");
pfi_templates_path[1] = NULL;
folder_item_templates_page.page.path = pfi_templates_path;
folder_item_templates_page.page.create_widget = prefs_folder_item_templates_create_widget_func;
folder_item_templates_page.page.destroy_widget = prefs_folder_item_templates_destroy_widget_func;
folder_item_templates_page.page.save_page = prefs_folder_item_templates_save_func;
prefs_folder_item_register_page((PrefsPage *) &folder_item_templates_page, NULL);
}
static GSList *prefs_pages = NULL;
static void prefs_folder_item_address_completion_start(PrefsWindow *window)
{
address_completion_start(window->window);
}
static void prefs_folder_item_address_completion_end(PrefsWindow *window)
{
address_completion_end(window->window);
}
void prefs_folder_item_open(FolderItem *item)
{
gchar *id, *title;
GSList *pages;
if (prefs_pages == NULL) {
register_general_page();
register_compose_page();
register_templates_page();
}
if (item->path) {
id = folder_item_get_identifier (item);
can_save = TRUE;
} else {
id = g_strdup(item->name);
can_save = FALSE;
}
pages = g_slist_concat(
g_slist_copy(prefs_pages),
g_slist_copy(item->folder->klass->prefs_pages));
title = g_strdup_printf (_("Properties for folder %s"), id);
g_free (id);
prefswindow_open(title, pages, item,
&prefs_common.folderitemwin_width, &prefs_common.folderitemwin_height,
prefs_folder_item_address_completion_start,
NULL,
prefs_folder_item_address_completion_end);
g_slist_free(pages);
g_free (title);
}
void prefs_folder_item_register_page(PrefsPage *page, FolderClass *klass)
{
if (klass != NULL)
klass->prefs_pages = g_slist_append(klass->prefs_pages, page);
else
prefs_pages = g_slist_append(prefs_pages, page);
}
void prefs_folder_item_unregister_page(PrefsPage *page, FolderClass *klass)
{
if (klass != NULL)
klass->prefs_pages = g_slist_remove(klass->prefs_pages, page);
else
prefs_pages = g_slist_remove(prefs_pages, page);
}
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML
><HEAD
><TITLE
>FcAtomicCreate</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REL="HOME"
HREF="index.html"><LINK
REL="UP"
TITLE="FcAtomic"
HREF="x102.html#AEN3766"><LINK
REL="PREVIOUS"
TITLE="FUNCTIONS"
HREF="x102.html"><LINK
REL="NEXT"
TITLE="FcAtomicLock"
HREF="fcatomiclock.html"></HEAD
><BODY
CLASS="REFENTRY"
BGCOLOR="#FFFFFF"
TEXT="#000000"
LINK="#0000FF"
VLINK="#840084"
ALINK="#0000FF"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="3"
ALIGN="center"
></TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="bottom"
><A
HREF="x102.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="80%"
ALIGN="center"
VALIGN="bottom"
></TD
><TD
WIDTH="10%"
ALIGN="right"
VALIGN="bottom"
><A
HREF="fcatomiclock.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><H1
><A
NAME="FCATOMICCREATE"
></A
>FcAtomicCreate</H1
><DIV
CLASS="REFNAMEDIV"
><A
NAME="AEN3774"
></A
><H2
>Name</H2
>FcAtomicCreate -- create an FcAtomic object</DIV
><DIV
CLASS="REFSYNOPSISDIV"
><A
NAME="AEN3777"
></A
><H2
>Synopsis</H2
><DIV
CLASS="FUNCSYNOPSIS"
><P
></P
><A
NAME="AEN3778"
></A
><PRE
CLASS="FUNCSYNOPSISINFO"
>#include <fontconfig/fontconfig.h>
</PRE
><P
><CODE
><CODE
CLASS="FUNCDEF"
>FcAtomic * FcAtomicCreate</CODE
>(const FcChar8 *file);</CODE
></P
><P
></P
></DIV
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN3785"
></A
><H2
>Description</H2
><P
>Creates a data structure containing data needed to control access to <CODE
CLASS="PARAMETER"
>file</CODE
>.
Writing is done to a separate file. Once that file is complete, the original
configuration file is atomically replaced so that reading process always see
a consistent and complete file without the need to lock for reading.
</P
></DIV
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="x102.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="fcatomiclock.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>FUNCTIONS</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="x102.html#AEN3766"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>FcAtomicLock</TD
></TR
></TABLE
></DIV
></BODY
></HTML
> | Java |
# -*- coding: utf8 -*-
###########################################################################
# This is the package latexparser
#
# 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/>.
###########################################################################
# copyright (c) Laurent Claessens, 2010,2012-2016
# email: laurent@claessens-donadello.eu
import codecs
from latexparser.InputPaths import InputPaths
class Occurrence(object):
"""
self.as_written : the code as it appears in the file, including \MyMacro, including the backslash.
self.position : the position at which this occurrence appears.
Example, if we look at the LatexCode
Hello word, \MyMacro{first}
and then \MyMacro{second}
the first occurrence of \MyMacro has position=12
"""
def __init__(self,name,arguments,as_written="",position=0):
self.arguments = arguments
self.number_of_arguments = len(arguments)
self.name = name
self.as_written = as_written
self.arguments_list = arguments
self.position = position
def configuration(self):
r"""
Return the way the arguments are separated in as_written.
Example, if we have
\MyMacro<space>{A}<tab>{B}
{C},
we return the list
["<space>","tab","\n"]
The following has to be true:
self.as_written == self.name+self.configuration()[0]+self.arguments_list[0]+etc.
"""
l=[]
a = self.as_written.split(self.name)[1]
for arg in self.arguments_list:
split = a.split("{"+arg+"}")
separator=split[0]
try:
a=split[1]
except IndexError:
print(self.as_written)
raise
l.append(separator)
return l
def change_argument(self,num,func):
r"""
Apply the function <func> to the <n>th argument of self. Then return a new object.
"""
n=num-1 # Internally, the arguments are numbered from 0.
arguments=self.arguments_list
configuration=self.configuration()
arguments[n]=func(arguments[n])
new_text=self.name
if len(arguments) != len(configuration):
print("Error : length of the configuration list has to be the same as the number of arguments")
raise ValueError
for i in range(len(arguments)):
new_text=new_text+configuration[i]+"{"+arguments[i]+"}"
return Occurrence(self.name,arguments,new_text,self.position)
def analyse(self):
return globals()["Occurrence_"+self.name[1:]](self) # We have to remove the initial "\" in the name of the macro.
def __getitem__(self,a):
return self.arguments[a]
def __str__(self):
return self.as_written
class Occurrence_newlabel(object):
r"""
takes an occurrence of \newlabel and creates an object which contains the information.
In the self.section_name we remove "\relax" from the string.
"""
def __init__(self,occurrence):
self.occurrence = occurrence
self.arguments = self.occurrence.arguments
if len(self.arguments) == 0 :
self.name = "Non interesting; probably the definition"
self.listoche = [None,None,None,None,None]
self.value,self.page,self.section_name,self.fourth,self.fifth=(None,None,None,None,None)
else :
self.name = self.arguments[0][0]
self.listoche = [a[0] for a in SearchArguments(self.arguments[1][0],5)[0]]
self.value = self.listoche[0]
self.page = self.listoche[1]
self.section_name = self.listoche[2].replace(r"\relax","")
self.fourth = self.listoche[3] # I don't know the role of the fourth argument of \newlabel
self.fifth = self.listoche[4] # I don't know the role of the fifth argument of \newlabel
class Occurrence_addInputPath(object):
def __init__(self,Occurrence):
self.directory=Occurrence[0]
class Occurrence_cite(object):
def __init__(self,occurrence):
self.label = occurrence[0]
def entry(self,codeBibtex):
return codeBibtex[self.label]
class Occurrence_newcommand(object):
def __init__(self,occurrence):
self.occurrence = occurrence
self.number_of_arguments = 0
if self.occurrence[1][1] == "[]":
self.number_of_arguments = self.occurrence[1][0]
self.name = self.occurrence[0][0]#[0]
self.definition = self.occurrence[-1][0]
class Occurrence_label(object):
def __init__(self,occurrence):
self.occurrence=occurrence
self.label=self.occurrence.arguments[0]
class Occurrence_ref(object):
def __init__(self,occurrence):
self.occurrence=occurrence
self.label=self.occurrence.arguments[0]
class Occurrence_eqref(object):
def __init__(self,occurrence):
self.occurrence=occurrence
self.label=self.occurrence.arguments[0]
class Occurrence_input(Occurrence):
def __init__(self,occurrence):
Occurrence.__init__(self,occurrence.name,occurrence.arguments,as_written=occurrence.as_written,position=occurrence.position)
self.occurrence = occurrence
self.filename = self.occurrence[0]
self.input_paths=InputPaths()
self._file_content=None # Make file_content "lazy"
def file_content(self,input_paths=None):
r"""
return the content of the file corresponding to this occurrence of
\input.
This is not recursive.
- 'input_path' is the list of paths in which we can search for files.
See the macro `\addInputPath` in the file
https://github.com/LaurentClaessens/mazhe/blob/master/configuration.tex
"""
import os.path
# Memoize
if self._file_content is not None :
return self._file_content
# At least, we are searching in the current directory :
if input_paths is None :
raise # Just to know who should do something like that
# Creating the filename
filename=self.filename
strict_filename = filename
if "." not in filename:
strict_filename=filename+".tex"
# Searching for the correct file in the subdirectories
fn=input_paths.get_file(strict_filename)
try:
# Without [:-1] I got an artificial empty line at the end.
text = "".join( codecs.open(fn,"r",encoding="utf8") )[:-1]
except IOError :
print("Warning : file %s not found."%strict_filename)
raise
self._file_content=text
return self._file_content
| Java |
<div>
<nav>
<ul id="menu">
{% for m in menu %}
<li>
{% if m.subsistemas %}
{{ m.nombreDireccion }}
<ul>
{% for submenu in m.subsistemas %}
<li>
<a href="{{submenu.target}}">{{ submenu.nombreSistema }}</a>
</li>
{% endfor %}
</ul>
{% else %}
<a href="{{m.target}}"> {{ m.nombreDireccion }}</a>
{% endif%}
</li>
{% endfor %}
<li>
{% firstof user.get_short_name user.get_username %}
<a href="{% url 'logout_view' %}" id="logout">Cerrar sesion</a>
</li>
</ul>
</nav>
</br> </br> </br>
</div>
| Java |
% acronyms for text or math mode
\newcommand {\ccast} {\mbox{\small CCAST}}
\newcommand {\cris} {\mbox{\small CrIS}}
\newcommand {\airs} {\mbox{\small AIRS}}
\newcommand {\iasi} {\mbox{\small IASI}}
\newcommand {\idps} {\mbox{\small IDPS}}
\newcommand {\nasa} {\mbox{\small NASA}}
\newcommand {\noaa} {\mbox{\small NOAA}}
\newcommand {\umbc} {\mbox{\small UMBC}}
\newcommand {\uw} {\mbox{\small UW}}
\newcommand {\fft} {\mbox{\small FFT}}
\newcommand {\ifft} {\mbox{\small IFFT}}
\newcommand {\fir} {\mbox{\small FIR}}
\newcommand {\fov} {\mbox{\small FOV}}
\newcommand {\for} {\mbox{\small FOR}}
\newcommand {\ict} {\mbox{\small ICT}}
\newcommand {\ils} {\mbox{\small ILS}}
\newcommand {\igm} {\mbox{\small IGM}}
\newcommand {\opd} {\mbox{\small OPD}}
\newcommand {\rms} {\mbox{\small RMS}}
\newcommand {\zpd} {\mbox{\small ZPD}}
\newcommand {\ppm} {\mbox{\small PPM}}
\newcommand {\srf} {\mbox{\small SRF}}
\newcommand {\ES} {\mbox{\small ES}}
\newcommand {\SP} {\mbox{\small SP}}
\newcommand {\IT} {\mbox{\small IT}}
\newcommand {\SA} {\mbox{\small SA}}
\newcommand {\ET} {\mbox{\small ET}}
\newcommand {\FT} {\mbox{\small FT}}
% abbreviations, mainly for math mode
\newcommand {\real} {\mbox{real}}
\newcommand {\imag} {\mbox{imag}}
\newcommand {\atan} {\mbox{atan}}
\newcommand {\obs} {\mbox{obs}}
\newcommand {\calc} {\mbox{calc}}
\newcommand {\sinc} {\mbox{sinc}}
\newcommand {\psinc} {\mbox{psinc}}
% symbols, for math mode only
\newcommand {\wnum} {\mbox{cm$^{-1}$}}
\newcommand {\lmax} {L_{\mbox{\tiny max}}}
\newcommand {\vmax} {V_{\mbox{\tiny max}}}
\newcommand {\rIT} {R_{\mbox{\tiny IT}}}
\newcommand {\tauobs} {\tau_{\mbox{\tiny obs}}}
\newcommand {\taucal} {\tau_{\mbox{\tiny calc}}}
\newcommand {\Vdc} {V_{\mbox{\tiny DC}}}
| Java |
#!/bin/bash
APP_DIR=`pwd`/books/
LOCALE_DIR=$APP_DIR/locale/
echo $APP_DIR
pushd $APP_DIR
echo `pwd`
for lang in `ls $LOCALE_DIR`; do
echo "Setting up locale for $lang"
django-admin.py makemessages -l $lang
done
echo "*************************"
django-admin.py compilemessages
popd
| Java |
/********************************************************************************
Copyright (C) Binod Nepal, Mix Open Foundation (http://mixof.org).
This file is part of MixERP.
MixERP 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.
MixERP 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 MixERP. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************************/
using MixERP.Net.Common.Helpers;
using MixERP.Net.Common.Models.Core;
using MixERP.Net.Common.Models.Transactions;
using System;
using System.Collections.ObjectModel;
namespace MixERP.Net.Core.Modules.Sales.Data.Transactions
{
public static class Delivery
{
public static long Add(DateTime valueDate, int storeId, string partyCode, int priceTypeId, int paymentTermId, Collection<StockMasterDetailModel> details, int shipperId, string shippingAddressCode, decimal shippingCharge, int costCenterId, string referenceNumber, int agentId, string statementReference, Collection<int> transactionIdCollection, Collection<AttachmentModel> attachments, bool nonTaxable)
{
StockMasterModel stockMaster = new StockMasterModel();
stockMaster.PartyCode = partyCode;
stockMaster.IsCredit = true;//Credit
stockMaster.PaymentTermId = paymentTermId;
stockMaster.PriceTypeId = priceTypeId;
stockMaster.ShipperId = shipperId;
stockMaster.ShippingAddressCode = shippingAddressCode;
stockMaster.ShippingCharge = shippingCharge;
stockMaster.SalespersonId = agentId;
stockMaster.CashRepositoryId = 0;//Credit
stockMaster.StoreId = storeId;
long transactionMasterId = GlTransaction.Add("Sales.Delivery", valueDate, SessionHelper.GetOfficeId(), SessionHelper.GetUserId(), SessionHelper.GetLogOnId(), costCenterId, referenceNumber, statementReference, stockMaster, details, attachments, nonTaxable);
TransactionGovernor.Autoverification.Autoverify.PassTransactionMasterId(transactionMasterId);
return transactionMasterId;
}
}
} | Java |
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_FM_session' | Java |
import java.util.*;
public class Pali {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String str=sc.next();
StringBuffer buff=new StringBuffer(str).reverse();
String str1=buff.toString();
if(str.isequals(str1))
{
System.out.println("Palindrome");
}
else
{
System.out.println("Not a Palindrome");
}
}
| Java |
/******************************************************************************
* NTRU Cryptography Reference Source Code
* Copyright (c) 2009-2013, by Security Innovation, Inc. All rights reserved.
*
* ntru_crypto_hash.c is a component of ntru-crypto.
*
* Copyright (C) 2009-2013 Security Innovation
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*****************************************************************************/
/******************************************************************************
*
* File: ntru_crypto_hash.c
*
* Contents: Routines implementing the hash object abstraction.
*
*****************************************************************************/
#include "ntru_crypto.h"
#include "ntru_crypto_hash.h"
typedef uint32_t (*NTRU_CRYPTO_HASH_INIT_FN)(
void *c);
typedef uint32_t (*NTRU_CRYPTO_HASH_UPDATE_FN)(
void *c,
void const *data,
uint32_t len);
typedef uint32_t (*NTRU_CRYPTO_HASH_FINAL_FN)(
void *c,
void *md);
typedef uint32_t (*NTRU_CRYPTO_HASH_DIGEST_FN)(
void const *data,
uint32_t len,
void *md);
typedef struct _NTRU_CRYPTO_HASH_ALG_PARAMS {
uint8_t algid;
uint16_t block_length;
uint16_t digest_length;
NTRU_CRYPTO_HASH_INIT_FN init;
NTRU_CRYPTO_HASH_UPDATE_FN update;
NTRU_CRYPTO_HASH_FINAL_FN final;
NTRU_CRYPTO_HASH_DIGEST_FN digest;
} NTRU_CRYPTO_HASH_ALG_PARAMS;
static NTRU_CRYPTO_HASH_ALG_PARAMS const algs_params[] = {
{
NTRU_CRYPTO_HASH_ALGID_SHA1,
SHA_1_BLK_LEN,
SHA_1_MD_LEN,
(NTRU_CRYPTO_HASH_INIT_FN) SHA_1_INIT_FN,
(NTRU_CRYPTO_HASH_UPDATE_FN) SHA_1_UPDATE_FN,
(NTRU_CRYPTO_HASH_FINAL_FN) SHA_1_FINAL_FN,
(NTRU_CRYPTO_HASH_DIGEST_FN) SHA_1_DIGEST_FN,
},
{
NTRU_CRYPTO_HASH_ALGID_SHA256,
SHA_256_BLK_LEN,
SHA_256_MD_LEN,
(NTRU_CRYPTO_HASH_INIT_FN) SHA_256_INIT_FN,
(NTRU_CRYPTO_HASH_UPDATE_FN) SHA_256_UPDATE_FN,
(NTRU_CRYPTO_HASH_FINAL_FN) SHA_256_FINAL_FN,
(NTRU_CRYPTO_HASH_DIGEST_FN) SHA_256_DIGEST_FN,
},
};
static int const numalgs = (sizeof(algs_params)/sizeof(algs_params[0]));
/* get_alg_params
*
* Return a pointer to the hash algorithm parameters for the hash algorithm
* specified, by looking for algid in the global algs_params table.
* If not found, return NULL.
*/
static NTRU_CRYPTO_HASH_ALG_PARAMS const *
get_alg_params(
NTRU_CRYPTO_HASH_ALGID algid) /* in - the hash algorithm to find */
{
int i;
for (i = 0; i < numalgs; i++)
{
if (algs_params[i].algid == algid)
{
return &algs_params[i];
}
}
return NULL;
}
/* ntru_crypto_hash_set_alg
*
* Sets the hash algorithm for the hash context. This must be called before
* any calls to ntru_crypto_hash_block_length(),
* ntru_crypto_hash_digest_length(), or ntru_crypto_hash_init() are made.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the specified algorithm is not supported.
*/
uint32_t
ntru_crypto_hash_set_alg(
NTRU_CRYPTO_HASH_ALGID algid, /* in - hash algorithm to be used */
NTRU_CRYPTO_HASH_CTX *c) /* in/out - pointer to the hash context */
{
if (!c)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
c->alg_params = get_alg_params(algid);
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
HASH_RET(NTRU_CRYPTO_HASH_OK);
}
/* ntru_crypto_hash_block_length
*
* Gets the number of bytes in an input block for the hash algorithm
* specified in the hash context. The hash algorithm must have been set
* in the hash context with a call to ntru_crypto_hash_set_alg() prior to
* calling this function.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_block_length(
NTRU_CRYPTO_HASH_CTX *c, /* in - pointer to the hash context */
uint16_t *blk_len) /* out - address for block length in bytes */
{
if (!c || !blk_len)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
*blk_len = c->alg_params->block_length;
HASH_RET(NTRU_CRYPTO_HASH_OK);
}
/* ntru_crypto_hash_digest_length
*
* Gets the number of bytes needed to hold the message digest for the
* hash algorithm specified in the hash context. The algorithm must have
* been set in the hash context with a call to ntru_crypto_hash_set_alg() prior
* to calling this function.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_digest_length(
NTRU_CRYPTO_HASH_CTX const *c, /* in - pointer to the hash context */
uint16_t *md_len) /* out - addr for digest length in bytes */
{
if (!c || !md_len)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
*md_len = c->alg_params->digest_length;
HASH_RET(NTRU_CRYPTO_HASH_OK);
}
/* ntru_crypto_hash_init
*
* This routine performs standard initialization of the hash state.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_FAIL with corrupted context.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_init(
NTRU_CRYPTO_HASH_CTX *c) /* in/out - pointer to hash context */
{
if (!c)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
return c->alg_params->init(&c->alg_ctx);
}
/* ntru_crypto_hash_update
*
* This routine processes input data and updates the hash calculation.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_FAIL with corrupted context.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_OVERFLOW if too much text has been fed to the
* hash algorithm. The size limit is dependent on the hash algorithm,
* and not all algorithms have this limit.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_update(
NTRU_CRYPTO_HASH_CTX *c, /* in/out - pointer to hash context */
uint8_t const *data, /* in - pointer to input data */
uint32_t data_len) /* in - number of bytes of input data */
{
if (!c || (data_len && !data))
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
return c->alg_params->update(&c->alg_ctx, data, data_len);
}
/* ntru_crypto_hash_final
*
* This routine completes the hash calculation and returns the message digest.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_FAIL with corrupted context.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_final(
NTRU_CRYPTO_HASH_CTX *c, /* in/out - pointer to hash context */
uint8_t *md) /* out - address for message digest */
{
if (!c || !md)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
return c->alg_params->final(&c->alg_ctx, md);
}
/* ntru_crypto_hash_digest
*
* This routine computes a message digest. It is assumed that the
* output buffer md is large enough to hold the output (see
* ntru_crypto_hash_digest_length)
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_FAIL with corrupted context.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_OVERFLOW if too much text has been fed to the
* hash algorithm. The size limit is dependent on the hash algorithm,
* and not all algorithms have this limit.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the specified algorithm is not supported.
*/
uint32_t
ntru_crypto_hash_digest(
NTRU_CRYPTO_HASH_ALGID algid, /* in - the hash algorithm to use */
uint8_t const *data, /* in - pointer to input data */
uint32_t data_len, /* in - number of bytes of input data */
uint8_t *md) /* out - address for message digest */
{
NTRU_CRYPTO_HASH_ALG_PARAMS const *alg_params = get_alg_params(algid);
if (!alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
if ((data_len && !data) || !md)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
return alg_params->digest(data, data_len, md);
}
| Java |
#!/usr/bin/env python
#
# MCP320x
#
# Author: Maurik Holtrop
#
# This module interfaces with the MCP300x or MCP320x family of chips. These
# are 10-bit and 12-bit ADCs respectively. The x number indicates the number
# of multiplexed analog inputs: 2 (MCP3202), 4 (MCP3204) or 8 (MCP3208)
# Communications with this chip are over the SPI protocol.
# See: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
#
# The version of the code has two SPI interfaces: the builtin hardware
# SPI interface on the RPI, or a "bit-banged" GPIO version.
#
# Bit-Bang GPIO:
# We emulate a SPI port in software using the GPIO lines.
# This is a bit slower than the hardware interface, but it is far more
# clear what is going on, plus the RPi has only one SPI device.
# Connections: RPi GPIO to MCP320x
# CS_bar_pin = CS/SHDN
# CLK_pin = CLK
# MOSI_pin = D_in
# MISO_pin = D_out
#
# Hardware SPI:
# This uses the builtin hardware on the RPi. You need to enable this with the
# raspi-config program first. The data rate can be up to 1MHz.
# Connections: RPi pins to MCP320x
# CE0 or CE1 = CS/SHDN (chip select) set CS_bar = 0 or 1
# SCK = CLK set CLK_pin = 1000000 (transfer speed)
# MOSI = D_in set MOSI_pin = 0
# MISO = D_out set MISO_pin = 0
# The SPI protocol simulated here is MODE=0, CPHA=0, which has a positive polarity clock,
# (the clock is 0 at rest, active at 1) and a positive phase (0 to 1 transition) for reading
# or writing the data. Thus corresponds to the specifications of the MCP320x chips.
#
# From MCP3208 datasheet:
# Outging data : MCU latches data to A/D converter on rising edges of SCLK
# Incoming data: Data is clocked out of A/D converter on falling edges, so should be read on rising edge.
try:
import RPi.GPIO as GPIO
except ImportError as error:
pass
try:
import Adafruit_BBIO as GPIO
except ImportError as error:
pass
try:
import spidev
except ImportError as error:
pass
from DevLib.MyValues import MyValues
class MCP320x:
"""This is an class that implements an interface to the MCP320x ADC chips.
Standard is the MCP3208, but is will also work wiht the MCP3202, MCP3204, MCP3002, MCP3004 and MCP3008."""
def __init__(self, cs_bar_pin, clk_pin=1000000, mosi_pin=0, miso_pin=0, chip='MCP3208',
channel_max=None, bit_length=None, single_ended=True):
"""Initialize the code and set the GPIO pins.
The last argument, ch_max, is 2 for the MCP3202, 4 for the
MCP3204 or 8 for the MCS3208."""
self._CLK = clk_pin
self._MOSI = mosi_pin
self._MISO = miso_pin
self._CS_bar = cs_bar_pin
chip_dictionary = {
"MCP3202": (2, 12),
"MCP3204": (4, 12),
"MCP3208": (8, 12),
"MCP3002": (2, 10),
"MCP3004": (4, 10),
"MCP3008": (8, 10)
}
if chip in chip_dictionary:
self._ChannelMax = chip_dictionary[chip][0]
self._BitLength = chip_dictionary[chip][1]
elif chip is None and (channel_max is not None) and (bit_length is not None):
self._ChannelMax = channel_max
self._BitLength = bit_length
else:
print("Unknown chip: {} - Please re-initialize.")
self._ChannelMax = 0
self._BitLength = 0
return
self._SingleEnded = single_ended
self._Vref = 3.3
self._values = MyValues(self.read_adc, self._ChannelMax)
self._volts = MyValues(self.read_volts, self._ChannelMax)
# This is used to speed up the SPIDEV communication. Send out MSB first.
# control[0] - bit7-3: upper 5 bits 0, because we can only send 8 bit sequences.
# - bit2 : Start bit - starts conversion in ADCs
# - bit1 : Select single_ended=1 or differential=0
# - bit0 : D2 high bit of channel select.
# control[1] - bit7 : D1 middle bit of channel select.
# - bit6 : D0 low bit of channel select.
# - bit5-0 : Don't care.
if self._SingleEnded:
self._control0 = [0b00000110, 0b00100000, 0] # Pre-compute part of the control word.
else:
self._control0 = [0b00000100, 0b00100000, 0] # Pre-compute part of the control word.
if self._MOSI > 0: # Bing Bang mode
assert self._MISO != 0 and self._CLK < 32
if GPIO.getmode() != 11:
GPIO.setmode(GPIO.BCM) # Use the BCM numbering scheme
GPIO.setup(self._CLK, GPIO.OUT) # Setup the ports for in and output
GPIO.setup(self._MOSI, GPIO.OUT)
GPIO.setup(self._MISO, GPIO.IN)
GPIO.setup(self._CS_bar, GPIO.OUT)
GPIO.output(self._CLK, 0) # Set the clock low.
GPIO.output(self._MOSI, 0) # Set the Master Out low
GPIO.output(self._CS_bar, 1) # Set the CS_bar high
else:
self._dev = spidev.SpiDev(0, self._CS_bar) # Start a SpiDev device
self._dev.mode = 0 # Set SPI mode (phase)
self._dev.max_speed_hz = self._CLK # Set the data rate
self._dev.bits_per_word = 8 # Number of bit per word. ALWAYS 8
def __del__(self):
""" Cleanup the GPIO before being destroyed """
if self._MOSI > 0:
GPIO.cleanup(self._CS_bar)
GPIO.cleanup(self._CLK)
GPIO.cleanup(self._MOSI)
GPIO.cleanup(self._MISO)
def get_channel_max(self):
"""Return the maximum number of channels"""
return self._ChannelMax
def get_bit_length(self):
"""Return the number of bits that will be read"""
return self._BitLength
def get_value_max(self):
"""Return the maximum value possible for an ADC read"""
return 2 ** self._BitLength - 1
def send_bit(self, bit):
""" Send out a single bit, and pulse clock."""
if self._MOSI == 0:
return
#
# The input is read on the rising edge of the clock.
#
GPIO.output(self._MOSI, bit) # Set the bit.
GPIO.output(self._CLK, 1) # Rising edge sends data
GPIO.output(self._CLK, 0) # Return clock to zero.
def read_bit(self):
""" Read a single bit from the ADC and pulse clock."""
if self._MOSI == 0:
return 0
#
# The output is going out on the falling edge of the clock,
# and is to be read on the rising edge of the clock.
# Clock should be already low, and data should already be set.
GPIO.output(self._CLK, 1) # Set the clock high. Ready to read.
bit = GPIO.input(self._MISO) # Read the bit.
GPIO.output(self._CLK, 0) # Return clock low, next bit will be set.
return bit
def read_adc(self, channel):
"""This reads the actual ADC value, after connecting the analog multiplexer to
the desired channel.
ADC value is returned at a n-bit integer value, with n=10 or 12 depending on the chip.
The value can be converted to a voltage with:
volts = data*Vref/(2**n-1)"""
if channel < 0 or channel >= self._ChannelMax:
print("Error - chip does not have channel = {}".format(channel))
if self._MOSI == 0:
# SPIdev Code
# This builds up the control word, which selects the channel
# and sets single/differential more.
control = [self._control0[0] + ((channel & 0b100) >> 2), self._control0[1]+((channel & 0b011) << 6), 0]
dat = self._dev.xfer(control)
value = (dat[1] << 8)+dat[2] # Unpack the two 8-bit words to a single integer.
return value
else:
# Bit Bang code.
# To read out this chip you need to send:
# 1 - start bit
# 2 - Single ended (1) or differential (0) mode
# 3 - Channel select: 1 bit for x=2 or 3 bits for x=4,8
# 4 - MSB first (1) or LSB first (0)
#
# Start of sequence sets CS_bar low, and sends sequence
#
GPIO.output(self._CLK, 0) # Make sure clock starts low.
GPIO.output(self._MOSI, 0)
GPIO.output(self._CS_bar, 0) # Select the chip.
self.send_bit(1) # Start bit = 1
self.send_bit(self._SingleEnded) # Select single or differential
if self._ChannelMax > 2:
self.send_bit(int((channel & 0b100) > 0)) # Send high bit of channel = DS2
self.send_bit(int((channel & 0b010) > 0)) # Send mid bit of channel = DS1
self.send_bit(int((channel & 0b001) > 0)) # Send low bit of channel = DS0
else:
self.send_bit(channel)
self.send_bit(0) # MSB First (for MCP3x02) or don't care.
# The clock is currently low, and the dummy bit = 0 is on the output of the ADC
#
self.read_bit() # Read the bit.
data = 0
for i in range(self._BitLength):
# Note you need to shift left first, or else you shift the last bit (bit 0)
# to the 1 position.
data <<= 1
bit = self.read_bit()
data += bit
GPIO.output(self._CS_bar, 1) # Unselect the chip.
return data
def read_volts(self, channel):
"""Read the ADC value from channel and convert to volts, assuming that Vref is set correctly. """
return self._Vref * self.read_adc(channel) / self.get_value_max()
def fast_read_adc0(self):
"""This reads the actual ADC value of channel 0, with as little overhead as possible.
Use with SPIDEV ONLY!!!!
returns: The ADC value as an n-bit integer value, with n=10 or 12 depending on the chip."""
dat = self._dev.xfer(self._control0)
value = (dat[1] << 8) + dat[2]
return value
@property
def values(self):
"""ADC values presented as a list."""
return self._values
@property
def volts(self):
"""ADC voltages presented as a list"""
return self._volts
@property
def accuracy(self):
"""The fractional voltage of the least significant bit. """
return self._Vref / float(self.get_value_max())
@property
def vref(self):
"""Reference voltage used by the chip. You need to set this. It defaults to 3.3V"""
return self._Vref
@vref.setter
def vref(self, vr):
self._Vref = vr
def main(argv):
"""Test code for the MCP320x driver. This assumes you are using a MCP3208
If no arguments are supplied, then use SPIdev for CE0 and read channel 0"""
if len(argv) < 3:
print("Args : ", argv)
cs_bar = 0
clk_pin = 1000000
mosi_pin = 0
miso_pin = 0
if len(argv) < 2:
channel = 0
else:
channel = int(argv[1])
elif len(argv) < 6:
print("Please supply: cs_bar_pin clk_pin mosi_pin miso_pin channel")
sys.exit(1)
else:
cs_bar = int(argv[1])
clk_pin = int(argv[2])
mosi_pin = int(argv[3])
miso_pin = int(argv[4])
channel = int(argv[5])
adc_chip = MCP320x(cs_bar, clk_pin, mosi_pin, miso_pin)
try:
while True:
value = adc_chip.read_adc(channel)
print("{:4d}".format(value))
time.sleep(0.1)
except KeyboardInterrupt:
sys.exit(0)
if __name__ == '__main__':
import sys
import time
main(sys.argv)
| Java |
/*
No-Babylon a job search engine with filtering ability
Copyright (C) 2012-2014 ferenc.jdev@gmail.com
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 org.laatusys.nobabylon.support;
import java.util.regex.Pattern;
public class ExcludeRegexpFilter implements Filter {
private final Pattern pattern;
public ExcludeRegexpFilter(String regexp, boolean caseSensitive) {
pattern = caseSensitive ? Pattern.compile(regexp) : Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
}
public ExcludeRegexpFilter(String regexp) {
this(regexp, false);
}
@Override
public boolean accept(String description) {
return !pattern.matcher(description).find();
}
}
| Java |
# __init__.py
# Copyright (C) 2006, 2007, 2008, 2009, 2010 Michael Bayer mike_mp@zzzcomputing.com
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
__version__ = '0.3.4'
| Java |
#!/usr/bin/python
import sys
print "divsum_analysis.py DivsumFile NumberOfNucleotides"
try:
file = sys.argv[1]
except:
file = raw_input("Introduce RepeatMasker's Divsum file: ")
try:
nucs = sys.argv[2]
except:
nucs = raw_input("Introduce number of analysed nucleotides: ")
nucs = int(nucs)
data = open(file).readlines()
s_matrix = data.index("Coverage for each repeat class and divergence (Kimura)\n")
matrix = []
elements = data[s_matrix+1]
elements = elements.split()
for element in elements[1:]:
matrix.append([element,[]])
n_el = len(matrix)
for line in data[s_matrix+2:]:
# print line
info = line.split()
info = info[1:]
for n in range(0,n_el):
matrix[n][1].append(int(info[n]))
abs = open(file+".abs", "w")
rel = open(file+".rel", "w")
for n in range(0,n_el):
abs.write("%s\t%s\n" % (matrix[n][0], sum(matrix[n][1])))
rel.write("%s\t%s\n" % (matrix[n][0], round(1.0*sum(matrix[n][1])/nucs,100)))
| Java |
/*
TShock, a server mod for Terraria
Copyright (C) 2011-2018 Pryaxis & TShock 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/>.
*/
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Terraria;
using Terraria.ID;
using Terraria.Localization;
using TShockAPI.DB;
using TerrariaApi.Server;
using TShockAPI.Hooks;
using Terraria.GameContent.Events;
using Microsoft.Xna.Framework;
using OTAPI.Tile;
using TShockAPI.Localization;
using System.Text.RegularExpressions;
namespace TShockAPI
{
public delegate void CommandDelegate(CommandArgs args);
public class CommandArgs : EventArgs
{
public string Message { get; private set; }
public TSPlayer Player { get; private set; }
public bool Silent { get; private set; }
/// <summary>
/// Parameters passed to the arguement. Does not include the command name.
/// IE '/kick "jerk face"' will only have 1 argument
/// </summary>
public List<string> Parameters { get; private set; }
public Player TPlayer
{
get { return Player.TPlayer; }
}
public CommandArgs(string message, TSPlayer ply, List<string> args)
{
Message = message;
Player = ply;
Parameters = args;
Silent = false;
}
public CommandArgs(string message, bool silent, TSPlayer ply, List<string> args)
{
Message = message;
Player = ply;
Parameters = args;
Silent = silent;
}
}
public class Command
{
/// <summary>
/// Gets or sets whether to allow non-players to use this command.
/// </summary>
public bool AllowServer { get; set; }
/// <summary>
/// Gets or sets whether to do logging of this command.
/// </summary>
public bool DoLog { get; set; }
/// <summary>
/// Gets or sets the help text of this command.
/// </summary>
public string HelpText { get; set; }
/// <summary>
/// Gets or sets an extended description of this command.
/// </summary>
public string[] HelpDesc { get; set; }
/// <summary>
/// Gets the name of the command.
/// </summary>
public string Name { get { return Names[0]; } }
/// <summary>
/// Gets the names of the command.
/// </summary>
public List<string> Names { get; protected set; }
/// <summary>
/// Gets the permissions of the command.
/// </summary>
public List<string> Permissions { get; protected set; }
private CommandDelegate commandDelegate;
public CommandDelegate CommandDelegate
{
get { return commandDelegate; }
set
{
if (value == null)
throw new ArgumentNullException();
commandDelegate = value;
}
}
public Command(List<string> permissions, CommandDelegate cmd, params string[] names)
: this(cmd, names)
{
Permissions = permissions;
}
public Command(string permissions, CommandDelegate cmd, params string[] names)
: this(cmd, names)
{
Permissions = new List<string> { permissions };
}
public Command(CommandDelegate cmd, params string[] names)
{
if (cmd == null)
throw new ArgumentNullException("cmd");
if (names == null || names.Length < 1)
throw new ArgumentException("names");
AllowServer = true;
CommandDelegate = cmd;
DoLog = true;
HelpText = "No help available.";
HelpDesc = null;
Names = new List<string>(names);
Permissions = new List<string>();
}
public bool Run(string msg, bool silent, TSPlayer ply, List<string> parms)
{
if (!CanRun(ply))
return false;
try
{
CommandDelegate(new CommandArgs(msg, silent, ply, parms));
}
catch (Exception e)
{
ply.SendErrorMessage("Command failed, check logs for more details.");
TShock.Log.Error(e.ToString());
}
return true;
}
public bool Run(string msg, TSPlayer ply, List<string> parms)
{
return Run(msg, false, ply, parms);
}
public bool HasAlias(string name)
{
return Names.Contains(name);
}
public bool CanRun(TSPlayer ply)
{
if (Permissions == null || Permissions.Count < 1)
return true;
foreach (var Permission in Permissions)
{
if (ply.HasPermission(Permission))
return true;
}
return false;
}
}
public static class Commands
{
public static List<Command> ChatCommands = new List<Command>();
public static ReadOnlyCollection<Command> TShockCommands = new ReadOnlyCollection<Command>(new List<Command>());
/// <summary>
/// The command specifier, defaults to "/"
/// </summary>
public static string Specifier
{
get { return string.IsNullOrWhiteSpace(TShock.Config.CommandSpecifier) ? "/" : TShock.Config.CommandSpecifier; }
}
/// <summary>
/// The silent command specifier, defaults to "."
/// </summary>
public static string SilentSpecifier
{
get { return string.IsNullOrWhiteSpace(TShock.Config.CommandSilentSpecifier) ? "." : TShock.Config.CommandSilentSpecifier; }
}
private delegate void AddChatCommand(string permission, CommandDelegate command, params string[] names);
public static void InitCommands()
{
List<Command> tshockCommands = new List<Command>(100);
Action<Command> add = (cmd) =>
{
tshockCommands.Add(cmd);
ChatCommands.Add(cmd);
};
add(new Command(SetupToken, "setup")
{
AllowServer = false,
HelpText = "Used to authenticate as superadmin when first setting up TShock."
});
add(new Command(Permissions.user, ManageUsers, "user")
{
DoLog = false,
HelpText = "Manages user accounts."
});
#region Account Commands
add(new Command(Permissions.canlogin, AttemptLogin, "login")
{
AllowServer = false,
DoLog = false,
HelpText = "Logs you into an account."
});
add(new Command(Permissions.canlogout, Logout, "logout")
{
AllowServer = false,
DoLog = false,
HelpText = "Logs you out of your current account."
});
add(new Command(Permissions.canchangepassword, PasswordUser, "password")
{
AllowServer = false,
DoLog = false,
HelpText = "Changes your account's password."
});
add(new Command(Permissions.canregister, RegisterUser, "register")
{
AllowServer = false,
DoLog = false,
HelpText = "Registers you an account."
});
add(new Command(Permissions.checkaccountinfo, ViewAccountInfo, "accountinfo", "ai")
{
HelpText = "Shows information about a user."
});
#endregion
#region Admin Commands
add(new Command(Permissions.ban, Ban, "ban")
{
HelpText = "Manages player bans."
});
add(new Command(Permissions.broadcast, Broadcast, "broadcast", "bc", "say")
{
HelpText = "Broadcasts a message to everyone on the server."
});
add(new Command(Permissions.logs, DisplayLogs, "displaylogs")
{
HelpText = "Toggles whether you receive server logs."
});
add(new Command(Permissions.managegroup, Group, "group")
{
HelpText = "Manages groups."
});
add(new Command(Permissions.manageitem, ItemBan, "itemban")
{
HelpText = "Manages item bans."
});
add(new Command(Permissions.manageprojectile, ProjectileBan, "projban")
{
HelpText = "Manages projectile bans."
});
add(new Command(Permissions.managetile, TileBan, "tileban")
{
HelpText = "Manages tile bans."
});
add(new Command(Permissions.manageregion, Region, "region")
{
HelpText = "Manages regions."
});
add(new Command(Permissions.kick, Kick, "kick")
{
HelpText = "Removes a player from the server."
});
add(new Command(Permissions.mute, Mute, "mute", "unmute")
{
HelpText = "Prevents a player from talking."
});
add(new Command(Permissions.savessc, OverrideSSC, "overridessc", "ossc")
{
HelpText = "Overrides serverside characters for a player, temporarily."
});
add(new Command(Permissions.savessc, SaveSSC, "savessc")
{
HelpText = "Saves all serverside characters."
});
add(new Command(Permissions.uploaddata, UploadJoinData, "uploadssc")
{
HelpText = "Upload the account information when you joined the server as your Server Side Character data."
});
add(new Command(Permissions.settempgroup, TempGroup, "tempgroup")
{
HelpText = "Temporarily sets another player's group."
});
add(new Command(Permissions.su, SubstituteUser, "su")
{
HelpText = "Temporarily elevates you to Super Admin."
});
add(new Command(Permissions.su, SubstituteUserDo, "sudo")
{
HelpText = "Executes a command as the super admin."
});
add(new Command(Permissions.userinfo, GrabUserUserInfo, "userinfo", "ui")
{
HelpText = "Shows information about a player."
});
#endregion
#region Annoy Commands
add(new Command(Permissions.annoy, Annoy, "annoy")
{
HelpText = "Annoys a player for an amount of time."
});
add(new Command(Permissions.annoy, Confuse, "confuse")
{
HelpText = "Confuses a player for an amount of time."
});
add(new Command(Permissions.annoy, Rocket, "rocket")
{
HelpText = "Rockets a player upwards. Requires SSC."
});
add(new Command(Permissions.annoy, FireWork, "firework")
{
HelpText = "Spawns fireworks at a player."
});
#endregion
#region Configuration Commands
add(new Command(Permissions.maintenance, CheckUpdates, "checkupdates")
{
HelpText = "Checks for TShock updates."
});
add(new Command(Permissions.maintenance, Off, "off", "exit", "stop")
{
HelpText = "Shuts down the server while saving."
});
add(new Command(Permissions.maintenance, OffNoSave, "off-nosave", "exit-nosave", "stop-nosave")
{
HelpText = "Shuts down the server without saving."
});
add(new Command(Permissions.cfgreload, Reload, "reload")
{
HelpText = "Reloads the server configuration file."
});
add(new Command(Permissions.cfgpassword, ServerPassword, "serverpassword")
{
HelpText = "Changes the server password."
});
add(new Command(Permissions.maintenance, GetVersion, "version")
{
HelpText = "Shows the TShock version."
});
add(new Command(Permissions.whitelist, Whitelist, "whitelist")
{
HelpText = "Manages the server whitelist."
});
#endregion
#region Item Commands
add(new Command(Permissions.give, Give, "give", "g")
{
HelpText = "Gives another player an item."
});
add(new Command(Permissions.item, Item, "item", "i")
{
AllowServer = false,
HelpText = "Gives yourself an item."
});
#endregion
#region NPC Commands
add(new Command(Permissions.butcher, Butcher, "butcher")
{
HelpText = "Kills hostile NPCs or NPCs of a certain type."
});
add(new Command(Permissions.renamenpc, RenameNPC, "renamenpc")
{
HelpText = "Renames an NPC."
});
add(new Command(Permissions.invade, Invade, "invade")
{
HelpText = "Starts an NPC invasion."
});
add(new Command(Permissions.maxspawns, MaxSpawns, "maxspawns")
{
HelpText = "Sets the maximum number of NPCs."
});
add(new Command(Permissions.spawnboss, SpawnBoss, "spawnboss", "sb")
{
AllowServer = false,
HelpText = "Spawns a number of bosses around you."
});
add(new Command(Permissions.spawnmob, SpawnMob, "spawnmob", "sm")
{
AllowServer = false,
HelpText = "Spawns a number of mobs around you."
});
add(new Command(Permissions.spawnrate, SpawnRate, "spawnrate")
{
HelpText = "Sets the spawn rate of NPCs."
});
add(new Command(Permissions.clearangler, ClearAnglerQuests, "clearangler")
{
HelpText = "Resets the list of users who have completed an angler quest that day."
});
#endregion
#region TP Commands
add(new Command(Permissions.home, Home, "home")
{
AllowServer = false,
HelpText = "Sends you to your spawn point."
});
add(new Command(Permissions.spawn, Spawn, "spawn")
{
AllowServer = false,
HelpText = "Sends you to the world's spawn point."
});
add(new Command(Permissions.tp, TP, "tp")
{
AllowServer = false,
HelpText = "Teleports a player to another player."
});
add(new Command(Permissions.tpothers, TPHere, "tphere")
{
AllowServer = false,
HelpText = "Teleports a player to yourself."
});
add(new Command(Permissions.tpnpc, TPNpc, "tpnpc")
{
AllowServer = false,
HelpText = "Teleports you to an npc."
});
add(new Command(Permissions.tppos, TPPos, "tppos")
{
AllowServer = false,
HelpText = "Teleports you to tile coordinates."
});
add(new Command(Permissions.getpos, GetPos, "pos")
{
AllowServer = false,
HelpText = "Returns the user's or specified user's current position."
});
add(new Command(Permissions.tpallow, TPAllow, "tpallow")
{
AllowServer = false,
HelpText = "Toggles whether other people can teleport you."
});
#endregion
#region World Commands
add(new Command(Permissions.toggleexpert, ToggleExpert, "expert", "expertmode")
{
HelpText = "Toggles expert mode."
});
add(new Command(Permissions.antibuild, ToggleAntiBuild, "antibuild")
{
HelpText = "Toggles build protection."
});
add(new Command(Permissions.bloodmoon, Bloodmoon, "bloodmoon")
{
HelpText = "Sets a blood moon."
});
add(new Command(Permissions.grow, Grow, "grow")
{
AllowServer = false,
HelpText = "Grows plants at your location."
});
add(new Command(Permissions.dropmeteor, DropMeteor, "dropmeteor")
{
HelpText = "Drops a meteor somewhere in the world."
});
add(new Command(Permissions.eclipse, Eclipse, "eclipse")
{
HelpText = "Sets an eclipse."
});
add(new Command(Permissions.halloween, ForceHalloween, "forcehalloween")
{
HelpText = "Toggles halloween mode (goodie bags, pumpkins, etc)."
});
add(new Command(Permissions.xmas, ForceXmas, "forcexmas")
{
HelpText = "Toggles christmas mode (present spawning, santa, etc)."
});
add(new Command(Permissions.fullmoon, Fullmoon, "fullmoon")
{
HelpText = "Sets a full moon."
});
add(new Command(Permissions.hardmode, Hardmode, "hardmode")
{
HelpText = "Toggles the world's hardmode status."
});
add(new Command(Permissions.editspawn, ProtectSpawn, "protectspawn")
{
HelpText = "Toggles spawn protection."
});
add(new Command(Permissions.sandstorm, Sandstorm, "sandstorm")
{
HelpText = "Toggles sandstorms."
});
add(new Command(Permissions.rain, Rain, "rain")
{
HelpText = "Toggles the rain."
});
add(new Command(Permissions.worldsave, Save, "save")
{
HelpText = "Saves the world file."
});
add(new Command(Permissions.worldspawn, SetSpawn, "setspawn")
{
AllowServer = false,
HelpText = "Sets the world's spawn point to your location."
});
add(new Command(Permissions.dungeonposition, SetDungeon, "setdungeon")
{
AllowServer = false,
HelpText = "Sets the dungeon's position to your location."
});
add(new Command(Permissions.worldsettle, Settle, "settle")
{
HelpText = "Forces all liquids to update immediately."
});
add(new Command(Permissions.time, Time, "time")
{
HelpText = "Sets the world time."
});
add(new Command(Permissions.wind, Wind, "wind")
{
HelpText = "Changes the wind speed."
});
add(new Command(Permissions.worldinfo, WorldInfo, "world")
{
HelpText = "Shows information about the current world."
});
#endregion
#region Other Commands
add(new Command(Permissions.buff, Buff, "buff")
{
AllowServer = false,
HelpText = "Gives yourself a buff for an amount of time."
});
add(new Command(Permissions.clear, Clear, "clear")
{
HelpText = "Clears item drops or projectiles."
});
add(new Command(Permissions.buffplayer, GBuff, "gbuff", "buffplayer")
{
HelpText = "Gives another player a buff for an amount of time."
});
add(new Command(Permissions.godmode, ToggleGodMode, "godmode")
{
HelpText = "Toggles godmode on a player."
});
add(new Command(Permissions.heal, Heal, "heal")
{
HelpText = "Heals a player in HP and MP."
});
add(new Command(Permissions.kill, Kill, "kill")
{
HelpText = "Kills another player."
});
add(new Command(Permissions.cantalkinthird, ThirdPerson, "me")
{
HelpText = "Sends an action message to everyone."
});
add(new Command(Permissions.canpartychat, PartyChat, "party", "p")
{
AllowServer = false,
HelpText = "Sends a message to everyone on your team."
});
add(new Command(Permissions.whisper, Reply, "reply", "r")
{
HelpText = "Replies to a PM sent to you."
});
add(new Command(Rests.RestPermissions.restmanage, ManageRest, "rest")
{
HelpText = "Manages the REST API."
});
add(new Command(Permissions.slap, Slap, "slap")
{
HelpText = "Slaps a player, dealing damage."
});
add(new Command(Permissions.serverinfo, ServerInfo, "serverinfo")
{
HelpText = "Shows the server information."
});
add(new Command(Permissions.warp, Warp, "warp")
{
HelpText = "Teleports you to a warp point or manages warps."
});
add(new Command(Permissions.whisper, Whisper, "whisper", "w", "tell")
{
HelpText = "Sends a PM to a player."
});
add(new Command(Permissions.createdumps, CreateDumps, "dump-reference-data")
{
HelpText = "Creates a reference tables for Terraria data types and the TShock permission system in the server folder."
});
#endregion
add(new Command(Aliases, "aliases")
{
HelpText = "Shows a command's aliases."
});
add(new Command(Help, "help")
{
HelpText = "Lists commands or gives help on them."
});
add(new Command(Motd, "motd")
{
HelpText = "Shows the message of the day."
});
add(new Command(ListConnectedPlayers, "playing", "online", "who")
{
HelpText = "Shows the currently connected players."
});
add(new Command(Rules, "rules")
{
HelpText = "Shows the server's rules."
});
TShockCommands = new ReadOnlyCollection<Command>(tshockCommands);
}
public static bool HandleCommand(TSPlayer player, string text)
{
string cmdText = text.Remove(0, 1);
string cmdPrefix = text[0].ToString();
bool silent = false;
if (cmdPrefix == SilentSpecifier)
silent = true;
int index = -1;
for (int i = 0; i < cmdText.Length; i++)
{
if (IsWhiteSpace(cmdText[i]))
{
index = i;
break;
}
}
string cmdName;
if (index == 0) // Space after the command specifier should not be supported
{
player.SendErrorMessage("Invalid command entered. Type {0}help for a list of valid commands.", Specifier);
return true;
}
else if (index < 0)
cmdName = cmdText.ToLower();
else
cmdName = cmdText.Substring(0, index).ToLower();
List<string> args;
if (index < 0)
args = new List<string>();
else
args = ParseParameters(cmdText.Substring(index));
IEnumerable<Command> cmds = ChatCommands.FindAll(c => c.HasAlias(cmdName));
if (Hooks.PlayerHooks.OnPlayerCommand(player, cmdName, cmdText, args, ref cmds, cmdPrefix))
return true;
if (cmds.Count() == 0)
{
if (player.AwaitingResponse.ContainsKey(cmdName))
{
Action<CommandArgs> call = player.AwaitingResponse[cmdName];
player.AwaitingResponse.Remove(cmdName);
call(new CommandArgs(cmdText, player, args));
return true;
}
player.SendErrorMessage("Invalid command entered. Type {0}help for a list of valid commands.", Specifier);
return true;
}
foreach (Command cmd in cmds)
{
if (!cmd.CanRun(player))
{
TShock.Utils.SendLogs(string.Format("{0} tried to execute {1}{2}.", player.Name, Specifier, cmdText), Color.PaleVioletRed, player);
player.SendErrorMessage("You do not have access to this command.");
if (player.HasPermission(Permissions.su))
{
player.SendInfoMessage("You can use '{0}sudo {0}{1}' to override this check.", Specifier, cmdText);
}
}
else if (!cmd.AllowServer && !player.RealPlayer)
{
player.SendErrorMessage("You must use this command in-game.");
}
else
{
if (cmd.DoLog)
TShock.Utils.SendLogs(string.Format("{0} executed: {1}{2}.", player.Name, silent ? SilentSpecifier : Specifier, cmdText), Color.PaleVioletRed, player);
cmd.Run(cmdText, silent, player, args);
}
}
return true;
}
/// <summary>
/// Parses a string of parameters into a list. Handles quotes.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static List<String> ParseParameters(string str)
{
var ret = new List<string>();
var sb = new StringBuilder();
bool instr = false;
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
if (c == '\\' && ++i < str.Length)
{
if (str[i] != '"' && str[i] != ' ' && str[i] != '\\')
sb.Append('\\');
sb.Append(str[i]);
}
else if (c == '"')
{
instr = !instr;
if (!instr)
{
ret.Add(sb.ToString());
sb.Clear();
}
else if (sb.Length > 0)
{
ret.Add(sb.ToString());
sb.Clear();
}
}
else if (IsWhiteSpace(c) && !instr)
{
if (sb.Length > 0)
{
ret.Add(sb.ToString());
sb.Clear();
}
}
else
sb.Append(c);
}
if (sb.Length > 0)
ret.Add(sb.ToString());
return ret;
}
private static bool IsWhiteSpace(char c)
{
return c == ' ' || c == '\t' || c == '\n';
}
#region Account commands
private static void AttemptLogin(CommandArgs args)
{
if (args.Player.LoginAttempts > TShock.Config.MaximumLoginAttempts && (TShock.Config.MaximumLoginAttempts != -1))
{
TShock.Log.Warn(String.Format("{0} ({1}) had {2} or more invalid login attempts and was kicked automatically.",
args.Player.IP, args.Player.Name, TShock.Config.MaximumLoginAttempts));
args.Player.Kick("Too many invalid login attempts.");
return;
}
if (args.Player.IsLoggedIn)
{
args.Player.SendErrorMessage("You are already logged in, and cannot login again.");
return;
}
UserAccount account = TShock.UserAccounts.GetUserAccountByName(args.Player.Name);
string password = "";
bool usingUUID = false;
if (args.Parameters.Count == 0 && !TShock.Config.DisableUUIDLogin)
{
if (PlayerHooks.OnPlayerPreLogin(args.Player, args.Player.Name, ""))
return;
usingUUID = true;
}
else if (args.Parameters.Count == 1)
{
if (PlayerHooks.OnPlayerPreLogin(args.Player, args.Player.Name, args.Parameters[0]))
return;
password = args.Parameters[0];
}
else if (args.Parameters.Count == 2 && TShock.Config.AllowLoginAnyUsername)
{
if (String.IsNullOrEmpty(args.Parameters[0]))
{
args.Player.SendErrorMessage("Bad login attempt.");
return;
}
if (PlayerHooks.OnPlayerPreLogin(args.Player, args.Parameters[0], args.Parameters[1]))
return;
account = TShock.UserAccounts.GetUserAccountByName(args.Parameters[0]);
password = args.Parameters[1];
}
else
{
args.Player.SendErrorMessage("Syntax: {0}login - Logs in using your UUID and character name", Specifier);
args.Player.SendErrorMessage(" {0}login <password> - Logs in using your password and character name", Specifier);
args.Player.SendErrorMessage(" {0}login <username> <password> - Logs in using your username and password", Specifier);
args.Player.SendErrorMessage("If you forgot your password, there is no way to recover it.");
return;
}
try
{
if (account == null)
{
args.Player.SendErrorMessage("A user account by that name does not exist.");
}
else if (account.VerifyPassword(password) ||
(usingUUID && account.UUID == args.Player.UUID && !TShock.Config.DisableUUIDLogin &&
!String.IsNullOrWhiteSpace(args.Player.UUID)))
{
args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, account.ID);
var group = TShock.Groups.GetGroupByName(account.Group);
args.Player.Group = group;
args.Player.tempGroup = null;
args.Player.Account = account;
args.Player.IsLoggedIn = true;
args.Player.IsDisabledForSSC = false;
if (Main.ServerSideCharacter)
{
if (args.Player.HasPermission(Permissions.bypassssc))
{
args.Player.PlayerData.CopyCharacter(args.Player);
TShock.CharacterDB.InsertPlayerData(args.Player);
}
args.Player.PlayerData.RestoreCharacter(args.Player);
}
args.Player.LoginFailsBySsi = false;
if (args.Player.HasPermission(Permissions.ignorestackhackdetection))
args.Player.IsDisabledForStackDetection = false;
if (args.Player.HasPermission(Permissions.usebanneditem))
args.Player.IsDisabledForBannedWearable = false;
args.Player.SendSuccessMessage("Authenticated as " + account.Name + " successfully.");
TShock.Log.ConsoleInfo(args.Player.Name + " authenticated successfully as user: " + account.Name + ".");
if ((args.Player.LoginHarassed) && (TShock.Config.RememberLeavePos))
{
if (TShock.RememberedPos.GetLeavePos(args.Player.Name, args.Player.IP) != Vector2.Zero)
{
Vector2 pos = TShock.RememberedPos.GetLeavePos(args.Player.Name, args.Player.IP);
args.Player.Teleport((int)pos.X * 16, (int)pos.Y * 16);
}
args.Player.LoginHarassed = false;
}
TShock.UserAccounts.SetUserAccountUUID(account, args.Player.UUID);
Hooks.PlayerHooks.OnPlayerPostLogin(args.Player);
}
else
{
if (usingUUID && !TShock.Config.DisableUUIDLogin)
{
args.Player.SendErrorMessage("UUID does not match this character!");
}
else
{
args.Player.SendErrorMessage("Invalid password!");
}
TShock.Log.Warn(args.Player.IP + " failed to authenticate as user: " + account.Name + ".");
args.Player.LoginAttempts++;
}
}
catch (Exception ex)
{
args.Player.SendErrorMessage("There was an error processing your request.");
TShock.Log.Error(ex.ToString());
}
}
private static void Logout(CommandArgs args)
{
if (!args.Player.IsLoggedIn)
{
args.Player.SendErrorMessage("You are not logged in.");
return;
}
args.Player.Logout();
args.Player.SendSuccessMessage("You have been successfully logged out of your account.");
if (Main.ServerSideCharacter)
{
args.Player.SendWarningMessage("Server side characters are enabled. You need to be logged in to play.");
}
}
private static void PasswordUser(CommandArgs args)
{
try
{
if (args.Player.IsLoggedIn && args.Parameters.Count == 2)
{
string password = args.Parameters[0];
if (args.Player.Account.VerifyPassword(password))
{
try
{
args.Player.SendSuccessMessage("You changed your password!");
TShock.UserAccounts.SetUserAccountPassword(args.Player.Account, args.Parameters[1]); // SetUserPassword will hash it for you.
TShock.Log.ConsoleInfo(args.Player.IP + " named " + args.Player.Name + " changed the password of account " +
args.Player.Account.Name + ".");
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
}
}
else
{
args.Player.SendErrorMessage("You failed to change your password!");
TShock.Log.ConsoleError(args.Player.IP + " named " + args.Player.Name + " failed to change password for account: " +
args.Player.Account.Name + ".");
}
}
else
{
args.Player.SendErrorMessage("Not logged in or invalid syntax! Proper syntax: {0}password <oldpassword> <newpassword>", Specifier);
}
}
catch (UserAccountManagerException ex)
{
args.Player.SendErrorMessage("Sorry, an error occured: " + ex.Message + ".");
TShock.Log.ConsoleError("PasswordUser returned an error: " + ex);
}
}
private static void RegisterUser(CommandArgs args)
{
try
{
var account = new UserAccount();
string echoPassword = "";
if (args.Parameters.Count == 1)
{
account.Name = args.Player.Name;
echoPassword = args.Parameters[0];
try
{
account.CreateBCryptHash(args.Parameters[0]);
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
return;
}
}
else if (args.Parameters.Count == 2 && TShock.Config.AllowRegisterAnyUsername)
{
account.Name = args.Parameters[0];
echoPassword = args.Parameters[1];
try
{
account.CreateBCryptHash(args.Parameters[1]);
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
return;
}
}
else
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}register <password>", Specifier);
return;
}
account.Group = TShock.Config.DefaultRegistrationGroupName; // FIXME -- we should get this from the DB. --Why?
account.UUID = args.Player.UUID;
if (TShock.UserAccounts.GetUserAccountByName(account.Name) == null && account.Name != TSServerPlayer.AccountName) // Cheap way of checking for existance of a user
{
args.Player.SendSuccessMessage("Account \"{0}\" has been registered.", account.Name);
args.Player.SendSuccessMessage("Your password is {0}.", echoPassword);
TShock.UserAccounts.AddUserAccount(account);
TShock.Log.ConsoleInfo("{0} registered an account: \"{1}\".", args.Player.Name, account.Name);
}
else
{
args.Player.SendErrorMessage("Sorry, " + account.Name + " was already taken by another person.");
args.Player.SendErrorMessage("Please try a different username.");
TShock.Log.ConsoleInfo(args.Player.Name + " failed to register an existing account: " + account.Name);
}
}
catch (UserAccountManagerException ex)
{
args.Player.SendErrorMessage("Sorry, an error occured: " + ex.Message + ".");
TShock.Log.ConsoleError("RegisterUser returned an error: " + ex);
}
}
private static void ManageUsers(CommandArgs args)
{
// This guy needs to be here so that people don't get exceptions when they type /user
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid user syntax. Try {0}user help.", Specifier);
return;
}
string subcmd = args.Parameters[0];
// Add requires a username, password, and a group specified.
if (subcmd == "add" && args.Parameters.Count == 4)
{
var account = new UserAccount();
account.Name = args.Parameters[1];
try
{
account.CreateBCryptHash(args.Parameters[2]);
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
return;
}
account.Group = args.Parameters[3];
try
{
TShock.UserAccounts.AddUserAccount(account);
args.Player.SendSuccessMessage("Account " + account.Name + " has been added to group " + account.Group + "!");
TShock.Log.ConsoleInfo(args.Player.Name + " added Account " + account.Name + " to group " + account.Group);
}
catch (GroupNotExistsException)
{
args.Player.SendErrorMessage("Group " + account.Group + " does not exist!");
}
catch (UserAccountExistsException)
{
args.Player.SendErrorMessage("User " + account.Name + " already exists!");
}
catch (UserAccountManagerException e)
{
args.Player.SendErrorMessage("User " + account.Name + " could not be added, check console for details.");
TShock.Log.ConsoleError(e.ToString());
}
}
// User deletion requires a username
else if (subcmd == "del" && args.Parameters.Count == 2)
{
var account = new UserAccount();
account.Name = args.Parameters[1];
try
{
TShock.UserAccounts.RemoveUserAccount(account);
args.Player.SendSuccessMessage("Account removed successfully.");
TShock.Log.ConsoleInfo(args.Player.Name + " successfully deleted account: " + args.Parameters[1] + ".");
}
catch (UserAccountNotExistException)
{
args.Player.SendErrorMessage("The user " + account.Name + " does not exist! Deleted nobody!");
}
catch (UserAccountManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
TShock.Log.ConsoleError(ex.ToString());
}
}
// Password changing requires a username, and a new password to set
else if (subcmd == "password" && args.Parameters.Count == 3)
{
var account = new UserAccount();
account.Name = args.Parameters[1];
try
{
TShock.UserAccounts.SetUserAccountPassword(account, args.Parameters[2]);
TShock.Log.ConsoleInfo(args.Player.Name + " changed the password of account " + account.Name);
args.Player.SendSuccessMessage("Password change succeeded for " + account.Name + ".");
}
catch (UserAccountNotExistException)
{
args.Player.SendErrorMessage("User " + account.Name + " does not exist!");
}
catch (UserAccountManagerException e)
{
args.Player.SendErrorMessage("Password change for " + account.Name + " failed! Check console!");
TShock.Log.ConsoleError(e.ToString());
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
}
}
// Group changing requires a username or IP address, and a new group to set
else if (subcmd == "group" && args.Parameters.Count == 3)
{
var account = new UserAccount();
account.Name = args.Parameters[1];
try
{
TShock.UserAccounts.SetUserGroup(account, args.Parameters[2]);
TShock.Log.ConsoleInfo(args.Player.Name + " changed account " + account.Name + " to group " + args.Parameters[2] + ".");
args.Player.SendSuccessMessage("Account " + account.Name + " has been changed to group " + args.Parameters[2] + "!");
}
catch (GroupNotExistsException)
{
args.Player.SendErrorMessage("That group does not exist!");
}
catch (UserAccountNotExistException)
{
args.Player.SendErrorMessage("User " + account.Name + " does not exist!");
}
catch (UserAccountManagerException e)
{
args.Player.SendErrorMessage("User " + account.Name + " could not be added. Check console for details.");
TShock.Log.ConsoleError(e.ToString());
}
}
else if (subcmd == "help")
{
args.Player.SendInfoMessage("Use command help:");
args.Player.SendInfoMessage("{0}user add username password group -- Adds a specified user", Specifier);
args.Player.SendInfoMessage("{0}user del username -- Removes a specified user", Specifier);
args.Player.SendInfoMessage("{0}user password username newpassword -- Changes a user's password", Specifier);
args.Player.SendInfoMessage("{0}user group username newgroup -- Changes a user's group", Specifier);
}
else
{
args.Player.SendErrorMessage("Invalid user syntax. Try {0}user help.", Specifier);
}
}
#endregion
#region Stupid commands
private static void ServerInfo(CommandArgs args)
{
args.Player.SendInfoMessage("Memory usage: " + Process.GetCurrentProcess().WorkingSet64);
args.Player.SendInfoMessage("Allocated memory: " + Process.GetCurrentProcess().VirtualMemorySize64);
args.Player.SendInfoMessage("Total processor time: " + Process.GetCurrentProcess().TotalProcessorTime);
args.Player.SendInfoMessage("WinVer: " + Environment.OSVersion);
args.Player.SendInfoMessage("Proc count: " + Environment.ProcessorCount);
args.Player.SendInfoMessage("Machine name: " + Environment.MachineName);
}
private static void WorldInfo(CommandArgs args)
{
args.Player.SendInfoMessage("World name: " + (TShock.Config.UseServerName ? TShock.Config.ServerName : Main.worldName));
args.Player.SendInfoMessage("World size: {0}x{1}", Main.maxTilesX, Main.maxTilesY);
args.Player.SendInfoMessage("World ID: " + Main.worldID);
}
#endregion
#region Player Management Commands
private static void GrabUserUserInfo(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}userinfo <player>", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count < 1)
args.Player.SendErrorMessage("Invalid player.");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var message = new StringBuilder();
message.Append("IP Address: ").Append(players[0].IP);
if (players[0].Account != null && players[0].IsLoggedIn)
message.Append(" | Logged in as: ").Append(players[0].Account.Name).Append(" | Group: ").Append(players[0].Group.Name);
args.Player.SendSuccessMessage(message.ToString());
}
}
private static void ViewAccountInfo(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}accountinfo <username>", Specifier);
return;
}
string username = String.Join(" ", args.Parameters);
if (!string.IsNullOrWhiteSpace(username))
{
var account = TShock.UserAccounts.GetUserAccountByName(username);
if (account != null)
{
DateTime LastSeen;
string Timezone = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours.ToString("+#;-#");
if (DateTime.TryParse(account.LastAccessed, out LastSeen))
{
LastSeen = DateTime.Parse(account.LastAccessed).ToLocalTime();
args.Player.SendSuccessMessage("{0}'s last login occured {1} {2} UTC{3}.", account.Name, LastSeen.ToShortDateString(),
LastSeen.ToShortTimeString(), Timezone);
}
if (args.Player.Group.HasPermission(Permissions.advaccountinfo))
{
List<string> KnownIps = JsonConvert.DeserializeObject<List<string>>(account.KnownIps?.ToString() ?? string.Empty);
string ip = KnownIps?[KnownIps.Count - 1] ?? "N/A";
DateTime Registered = DateTime.Parse(account.Registered).ToLocalTime();
args.Player.SendSuccessMessage("{0}'s group is {1}.", account.Name, account.Group);
args.Player.SendSuccessMessage("{0}'s last known IP is {1}.", account.Name, ip);
args.Player.SendSuccessMessage("{0}'s register date is {1} {2} UTC{3}.", account.Name, Registered.ToShortDateString(), Registered.ToShortTimeString(), Timezone);
}
}
else
args.Player.SendErrorMessage("User {0} does not exist.", username);
}
else args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}accountinfo <username>", Specifier);
}
private static void Kick(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}kick <player> [reason]", Specifier);
return;
}
if (args.Parameters[0].Length == 0)
{
args.Player.SendErrorMessage("Missing player name.");
return;
}
string plStr = args.Parameters[0];
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
string reason = args.Parameters.Count > 1
? String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1))
: "Misbehaviour.";
if (!players[0].Kick(reason, !args.Player.RealPlayer, false, args.Player.Name))
{
args.Player.SendErrorMessage("You can't kick another admin!");
}
}
}
private static void Ban(CommandArgs args)
{
string subcmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subcmd)
{
case "add":
#region Add Ban
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid command. Format: {0}ban add <player> [time] [reason]", Specifier);
args.Player.SendErrorMessage("Example: {0}ban add Shank 10d Hacking and cheating", Specifier);
args.Player.SendErrorMessage("Example: {0}ban add Ash", Specifier);
args.Player.SendErrorMessage("Use the time 0 (zero) for a permanent ban.");
return;
}
// Used only to notify if a ban was successful and who the ban was about
bool success = false;
string targetGeneralizedName = "";
// Effective ban target assignment
List<TSPlayer> players = TSPlayer.FindByNameOrID(args.Parameters[1]);
// Bad case: Players contains more than 1 person so we can't ban them
if (players.Count > 1)
{
//Fail fast
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
return;
}
UserAccount offlineUserAccount = TShock.UserAccounts.GetUserAccountByName(args.Parameters[1]);
// Storage variable to determine if the command executor is the server console
// If it is, we assume they have full control and let them override permission checks
bool callerIsServerConsole = args.Player is TSServerPlayer;
// The ban reason the ban is going to have
string banReason = "Unknown.";
// The default ban length
// 0 is permanent ban, otherwise temp ban
int banLengthInSeconds = 0;
// Figure out if param 2 is a time or 0 or garbage
if (args.Parameters.Count >= 3)
{
bool parsedOkay = false;
if (args.Parameters[2] != "0")
{
parsedOkay = TShock.Utils.TryParseTime(args.Parameters[2], out banLengthInSeconds);
}
else
{
parsedOkay = true;
}
if (!parsedOkay)
{
args.Player.SendErrorMessage("Invalid time format. Example: 10d 5h 3m 2s.");
args.Player.SendErrorMessage("Use 0 (zero) for a permanent ban.");
return;
}
}
// If a reason exists, use the given reason.
if (args.Parameters.Count > 3)
{
banReason = String.Join(" ", args.Parameters.Skip(3));
}
// Good case: Online ban for matching character.
if (players.Count == 1)
{
TSPlayer target = players[0];
if (target.HasPermission(Permissions.immunetoban) && !callerIsServerConsole)
{
args.Player.SendErrorMessage("Permission denied. Target {0} is immune to ban.", target.Name);
return;
}
targetGeneralizedName = target.Name;
success = TShock.Bans.AddBan(target.IP, target.Name, target.UUID, target.Account?.Name ?? "", banReason, false, args.Player.Account.Name,
banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
// Since this is an online ban, we need to dc the player and tell them now.
if (success)
{
if (banLengthInSeconds == 0)
{
target.Disconnect(String.Format("Permanently banned for {0}", banReason));
}
else
{
target.Disconnect(String.Format("Banned for {0} seconds for {1}", banLengthInSeconds, banReason));
}
}
}
// Case: Players & user are invalid, could be IP?
// Note: Order matters. If this method is above the online player check,
// This enables you to ban an IP even if the player exists in the database as a player.
// You'll get two bans for the price of one, in theory, because both IP and user named IP will be banned.
// ??? edge cases are weird, but this is going to happen
// The only way around this is to either segregate off the IP code or do something else.
if (players.Count == 0)
{
// If the target is a valid IP...
string pattern = @"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
if (r.IsMatch(args.Parameters[1]))
{
targetGeneralizedName = "IP: " + args.Parameters[1];
success = TShock.Bans.AddBan(args.Parameters[1], "", "", "", banReason,
false, args.Player.Account.Name, banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
if (success && offlineUserAccount != null)
{
args.Player.SendSuccessMessage("Target IP {0} was banned successfully.", targetGeneralizedName);
args.Player.SendErrorMessage("Note: An account named with this IP address also exists.");
args.Player.SendErrorMessage("Note: It will also be banned.");
}
}
else
{
// Apparently there is no way to not IP ban someone
// This means that where we would normally just ban a "character name" here
// We can't because it requires some IP as a primary key.
if (offlineUserAccount == null)
{
args.Player.SendErrorMessage("Unable to ban target {0}.", args.Parameters[1]);
args.Player.SendErrorMessage("Target is not a valid IP address, a valid online player, or a known offline user.");
return;
}
}
}
// Case: Offline ban
if (players.Count == 0 && offlineUserAccount != null)
{
// Catch: we don't know an offline player's last login character name
// This means that we're banning their *user name* on the assumption that
// user name == character name
// (which may not be true)
// This needs to be fixed in a future implementation.
targetGeneralizedName = offlineUserAccount.Name;
if (TShock.Groups.GetGroupByName(offlineUserAccount.Group).HasPermission(Permissions.immunetoban) &&
!callerIsServerConsole)
{
args.Player.SendErrorMessage("Permission denied. Target {0} is immune to ban.", targetGeneralizedName);
return;
}
if (offlineUserAccount.KnownIps == null)
{
args.Player.SendErrorMessage("Unable to ban target {0} because they have no valid IP to ban.", targetGeneralizedName);
return;
}
string lastIP = JsonConvert.DeserializeObject<List<string>>(offlineUserAccount.KnownIps).Last();
success =
TShock.Bans.AddBan(lastIP,
"", offlineUserAccount.UUID, offlineUserAccount.Name, banReason, false, args.Player.Account.Name,
banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
}
if (success)
{
args.Player.SendSuccessMessage("{0} was successfully banned.", targetGeneralizedName);
args.Player.SendInfoMessage("Length: {0}", banLengthInSeconds == 0 ? "Permanent." : banLengthInSeconds + " seconds.");
args.Player.SendInfoMessage("Reason: {0}", banReason);
if (!args.Silent)
{
if (banLengthInSeconds == 0)
{
TSPlayer.All.SendErrorMessage("{0} was permanently banned by {1} for: {2}",
targetGeneralizedName, args.Player.Account.Name, banReason);
}
else
{
TSPlayer.All.SendErrorMessage("{0} was temp banned for {1} seconds by {2} for: {3}",
targetGeneralizedName, banLengthInSeconds, args.Player.Account.Name, banReason);
}
}
}
else
{
args.Player.SendErrorMessage("{0} was NOT banned due to a database error or other system problem.", targetGeneralizedName);
args.Player.SendErrorMessage("If this player is online, they have NOT been kicked.");
args.Player.SendErrorMessage("Check the system logs for details.");
}
return;
}
#endregion
case "del":
#region Delete ban
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}ban del <player>", Specifier);
return;
}
string plStr = args.Parameters[1];
Ban ban = TShock.Bans.GetBanByName(plStr, false);
if (ban != null)
{
if (TShock.Bans.RemoveBan(ban.Name, true))
args.Player.SendSuccessMessage("Unbanned {0} ({1}).", ban.Name, ban.IP);
else
args.Player.SendErrorMessage("Failed to unban {0} ({1}), check logs.", ban.Name, ban.IP);
}
else
args.Player.SendErrorMessage("No bans for {0} exist.", plStr);
}
#endregion
return;
case "delip":
#region Delete IP ban
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}ban delip <ip>", Specifier);
return;
}
string ip = args.Parameters[1];
Ban ban = TShock.Bans.GetBanByIp(ip);
if (ban != null)
{
if (TShock.Bans.RemoveBan(ban.IP, false))
args.Player.SendSuccessMessage("Unbanned IP {0} ({1}).", ban.IP, ban.Name);
else
args.Player.SendErrorMessage("Failed to unban IP {0} ({1}), check logs.", ban.IP, ban.Name);
}
else
args.Player.SendErrorMessage("IP {0} is not banned.", ip);
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <target> <time> [reason] - Bans a player or user account if the player is not online.",
"del <player> - Unbans a player.",
"delip <ip> - Unbans an IP.",
"list [page] - Lists all player bans.",
"listip [page] - Lists all IP bans."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Ban Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}ban help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "list":
#region List bans
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
{
return;
}
List<Ban> bans = TShock.Bans.GetBans();
var nameBans = from ban in bans
where !String.IsNullOrEmpty(ban.Name)
select ban.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(nameBans),
new PaginationTools.Settings
{
HeaderFormat = "Bans ({0}/{1}):",
FooterFormat = "Type {0}ban list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no bans."
});
}
#endregion
return;
case "listip":
#region List IP bans
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
{
return;
}
List<Ban> bans = TShock.Bans.GetBans();
var ipBans = from ban in bans
where String.IsNullOrEmpty(ban.Name)
select ban.IP;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(ipBans),
new PaginationTools.Settings
{
HeaderFormat = "IP Bans ({0}/{1}):",
FooterFormat = "Type {0}ban listip {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no IP bans."
});
}
#endregion
return;
default:
args.Player.SendErrorMessage("Invalid subcommand! Type {0}ban help for more information.", Specifier);
return;
}
}
private static void Whitelist(CommandArgs args)
{
if (args.Parameters.Count == 1)
{
using (var tw = new StreamWriter(FileTools.WhitelistPath, true))
{
tw.WriteLine(args.Parameters[0]);
}
args.Player.SendSuccessMessage("Added " + args.Parameters[0] + " to the whitelist.");
}
}
private static void DisplayLogs(CommandArgs args)
{
args.Player.DisplayLogs = (!args.Player.DisplayLogs);
args.Player.SendSuccessMessage("You will " + (args.Player.DisplayLogs ? "now" : "no longer") + " receive logs.");
}
private static void SaveSSC(CommandArgs args)
{
if (Main.ServerSideCharacter)
{
args.Player.SendSuccessMessage("SSC has been saved.");
foreach (TSPlayer player in TShock.Players)
{
if (player != null && player.IsLoggedIn && !player.IsDisabledPendingTrashRemoval)
{
TShock.CharacterDB.InsertPlayerData(player, true);
}
}
}
}
private static void OverrideSSC(CommandArgs args)
{
if (!Main.ServerSideCharacter)
{
args.Player.SendErrorMessage("Server Side Characters is disabled.");
return;
}
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Correct usage: {0}overridessc|{0}ossc <player name>", Specifier);
return;
}
string playerNameToMatch = string.Join(" ", args.Parameters);
var matchedPlayers = TSPlayer.FindByNameOrID(playerNameToMatch);
if (matchedPlayers.Count < 1)
{
args.Player.SendErrorMessage("No players matched \"{0}\".", playerNameToMatch);
return;
}
else if (matchedPlayers.Count > 1)
{
args.Player.SendMultipleMatchError(matchedPlayers.Select(p => p.Name));
return;
}
TSPlayer matchedPlayer = matchedPlayers[0];
if (matchedPlayer.IsLoggedIn)
{
args.Player.SendErrorMessage("Player \"{0}\" is already logged in.", matchedPlayer.Name);
return;
}
if (!matchedPlayer.LoginFailsBySsi)
{
args.Player.SendErrorMessage("Player \"{0}\" has to perform a /login attempt first.", matchedPlayer.Name);
return;
}
if (matchedPlayer.IsDisabledPendingTrashRemoval)
{
args.Player.SendErrorMessage("Player \"{0}\" has to reconnect first.", matchedPlayer.Name);
return;
}
TShock.CharacterDB.InsertPlayerData(matchedPlayer);
args.Player.SendSuccessMessage("SSC of player \"{0}\" has been overriden.", matchedPlayer.Name);
}
private static void UploadJoinData(CommandArgs args)
{
TSPlayer targetPlayer = args.Player;
if (args.Parameters.Count == 1 && args.Player.HasPermission(Permissions.uploadothersdata))
{
List<TSPlayer> players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
return;
}
else if (players.Count == 0)
{
args.Player.SendErrorMessage("No player was found matching'{0}'", args.Parameters[0]);
return;
}
else
{
targetPlayer = players[0];
}
}
else if (args.Parameters.Count == 1)
{
args.Player.SendErrorMessage("You do not have permission to upload another player's character data.");
return;
}
else if (args.Parameters.Count > 0)
{
args.Player.SendErrorMessage("Usage: /uploadssc [playername]");
return;
}
else if (args.Parameters.Count == 0 && args.Player is TSServerPlayer)
{
args.Player.SendErrorMessage("A console can not upload their player data.");
args.Player.SendErrorMessage("Usage: /uploadssc [playername]");
return;
}
if (targetPlayer.IsLoggedIn)
{
if (TShock.CharacterDB.InsertSpecificPlayerData(targetPlayer, targetPlayer.DataWhenJoined))
{
targetPlayer.DataWhenJoined.RestoreCharacter(targetPlayer);
targetPlayer.SendSuccessMessage("Your local character data has been uploaded to the server.");
args.Player.SendSuccessMessage("The player's character data was successfully uploaded.");
}
else
{
args.Player.SendErrorMessage("Failed to upload your character data, are you logged in to an account?");
}
}
else
{
args.Player.SendErrorMessage("The target player has not logged in yet.");
}
}
private static void ForceHalloween(CommandArgs args)
{
TShock.Config.ForceHalloween = !TShock.Config.ForceHalloween;
Main.checkHalloween();
if (args.Silent)
args.Player.SendInfoMessage("{0}abled halloween mode!", (TShock.Config.ForceHalloween ? "en" : "dis"));
else
TSPlayer.All.SendInfoMessage("{0} {1}abled halloween mode!", args.Player.Name, (TShock.Config.ForceHalloween ? "en" : "dis"));
}
private static void ForceXmas(CommandArgs args)
{
TShock.Config.ForceXmas = !TShock.Config.ForceXmas;
Main.checkXMas();
if (args.Silent)
args.Player.SendInfoMessage("{0}abled Christmas mode!", (TShock.Config.ForceXmas ? "en" : "dis"));
else
TSPlayer.All.SendInfoMessage("{0} {1}abled Christmas mode!", args.Player.Name, (TShock.Config.ForceXmas ? "en" : "dis"));
}
private static void TempGroup(CommandArgs args)
{
if (args.Parameters.Count < 2)
{
args.Player.SendInfoMessage("Invalid usage");
args.Player.SendInfoMessage("Usage: {0}tempgroup <username> <new group> [time]", Specifier);
return;
}
List<TSPlayer> ply = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (ply.Count < 1)
{
args.Player.SendErrorMessage("Could not find player {0}.", args.Parameters[0]);
return;
}
if (ply.Count > 1)
{
args.Player.SendMultipleMatchError(ply.Select(p => p.Account.Name));
}
if (!TShock.Groups.GroupExists(args.Parameters[1]))
{
args.Player.SendErrorMessage("Could not find group {0}", args.Parameters[1]);
return;
}
if (args.Parameters.Count > 2)
{
int time;
if (!TShock.Utils.TryParseTime(args.Parameters[2], out time))
{
args.Player.SendErrorMessage("Invalid time string! Proper format: _d_h_m_s, with at least one time specifier.");
args.Player.SendErrorMessage("For example, 1d and 10h-30m+2m are both valid time strings, but 2 is not.");
return;
}
ply[0].tempGroupTimer = new System.Timers.Timer(time * 1000);
ply[0].tempGroupTimer.Elapsed += ply[0].TempGroupTimerElapsed;
ply[0].tempGroupTimer.Start();
}
Group g = TShock.Groups.GetGroupByName(args.Parameters[1]);
ply[0].tempGroup = g;
if (args.Parameters.Count < 3)
{
args.Player.SendSuccessMessage(String.Format("You have changed {0}'s group to {1}", ply[0].Name, g.Name));
ply[0].SendSuccessMessage(String.Format("Your group has temporarily been changed to {0}", g.Name));
}
else
{
args.Player.SendSuccessMessage(String.Format("You have changed {0}'s group to {1} for {2}",
ply[0].Name, g.Name, args.Parameters[2]));
ply[0].SendSuccessMessage(String.Format("Your group has been changed to {0} for {1}",
g.Name, args.Parameters[2]));
}
}
private static void SubstituteUser(CommandArgs args)
{
if (args.Player.tempGroup != null)
{
args.Player.tempGroup = null;
args.Player.tempGroupTimer.Stop();
args.Player.SendSuccessMessage("Your previous permission set has been restored.");
return;
}
else
{
args.Player.tempGroup = new SuperAdminGroup();
args.Player.tempGroupTimer = new System.Timers.Timer(600 * 1000);
args.Player.tempGroupTimer.Elapsed += args.Player.TempGroupTimerElapsed;
args.Player.tempGroupTimer.Start();
args.Player.SendSuccessMessage("Your account has been elevated to Super Admin for 10 minutes.");
return;
}
}
#endregion Player Management Commands
#region Server Maintenence Commands
// Executes a command as a superuser if you have sudo rights.
private static void SubstituteUserDo(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendErrorMessage("Usage: /sudo [command].");
args.Player.SendErrorMessage("Example: /sudo /ban add Shank 2d Hacking.");
return;
}
string replacementCommand = String.Join(" ", args.Parameters);
args.Player.tempGroup = new SuperAdminGroup();
HandleCommand(args.Player, replacementCommand);
args.Player.tempGroup = null;
return;
}
private static void Broadcast(CommandArgs args)
{
string message = string.Join(" ", args.Parameters);
TShock.Utils.Broadcast(
"(Server Broadcast) " + message,
Convert.ToByte(TShock.Config.BroadcastRGB[0]), Convert.ToByte(TShock.Config.BroadcastRGB[1]),
Convert.ToByte(TShock.Config.BroadcastRGB[2]));
}
private static void Off(CommandArgs args)
{
if (Main.ServerSideCharacter)
{
foreach (TSPlayer player in TShock.Players)
{
if (player != null && player.IsLoggedIn && !player.IsDisabledPendingTrashRemoval)
{
player.SaveServerCharacter();
}
}
}
string reason = ((args.Parameters.Count > 0) ? "Server shutting down: " + String.Join(" ", args.Parameters) : "Server shutting down!");
TShock.Utils.StopServer(true, reason);
}
private static void OffNoSave(CommandArgs args)
{
string reason = ((args.Parameters.Count > 0) ? "Server shutting down: " + String.Join(" ", args.Parameters) : "Server shutting down!");
TShock.Utils.StopServer(false, reason);
}
private static void CheckUpdates(CommandArgs args)
{
args.Player.SendInfoMessage("An update check has been queued.");
try
{
TShock.UpdateManager.UpdateCheckAsync(null);
}
catch (Exception)
{
//swallow the exception
return;
}
}
private static void ManageRest(CommandArgs args)
{
string subCommand = "help";
if (args.Parameters.Count > 0)
subCommand = args.Parameters[0];
switch (subCommand.ToLower())
{
case "listusers":
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
Dictionary<string, int> restUsersTokens = new Dictionary<string, int>();
foreach (Rests.SecureRest.TokenData tokenData in TShock.RestApi.Tokens.Values)
{
if (restUsersTokens.ContainsKey(tokenData.Username))
restUsersTokens[tokenData.Username]++;
else
restUsersTokens.Add(tokenData.Username, 1);
}
List<string> restUsers = new List<string>(
restUsersTokens.Select(ut => string.Format("{0} ({1} tokens)", ut.Key, ut.Value)));
PaginationTools.SendPage(
args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(restUsers), new PaginationTools.Settings
{
NothingToDisplayString = "There are currently no active REST users.",
HeaderFormat = "Active REST Users ({0}/{1}):",
FooterFormat = "Type {0}rest listusers {{0}} for more.".SFormat(Specifier)
}
);
break;
}
case "destroytokens":
{
TShock.RestApi.Tokens.Clear();
args.Player.SendSuccessMessage("All REST tokens have been destroyed.");
break;
}
default:
{
args.Player.SendInfoMessage("Available REST Sub-Commands:");
args.Player.SendMessage("listusers - Lists all REST users and their current active tokens.", Color.White);
args.Player.SendMessage("destroytokens - Destroys all current REST tokens.", Color.White);
break;
}
}
}
#endregion Server Maintenence Commands
#region Cause Events and Spawn Monsters Commands
private static void DropMeteor(CommandArgs args)
{
WorldGen.spawnMeteor = false;
WorldGen.dropMeteor();
if (args.Silent)
{
args.Player.SendInfoMessage("A meteor has been triggered.");
}
else
{
TSPlayer.All.SendInfoMessage("{0} triggered a meteor.", args.Player.Name);
}
}
private static void Fullmoon(CommandArgs args)
{
TSPlayer.Server.SetFullMoon();
if (args.Silent)
{
args.Player.SendInfoMessage("Started a full moon.");
}
else
{
TSPlayer.All.SendInfoMessage("{0} started a full moon.", args.Player.Name);
}
}
private static void Bloodmoon(CommandArgs args)
{
TSPlayer.Server.SetBloodMoon(!Main.bloodMoon);
if (args.Silent)
{
args.Player.SendInfoMessage("{0}ed a blood moon.", Main.bloodMoon ? "start" : "stopp");
}
else
{
TSPlayer.All.SendInfoMessage("{0} {1}ed a blood moon.", args.Player.Name, Main.bloodMoon ? "start" : "stopp");
}
}
private static void Eclipse(CommandArgs args)
{
TSPlayer.Server.SetEclipse(!Main.eclipse);
if (args.Silent)
{
args.Player.SendInfoMessage("{0}ed an eclipse.", Main.eclipse ? "start" : "stopp");
}
else
{
TSPlayer.All.SendInfoMessage("{0} {1}ed an eclipse.", args.Player.Name, Main.eclipse ? "start" : "stopp");
}
}
private static void Invade(CommandArgs args)
{
if (Main.invasionSize <= 0)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}invade <invasion type> [wave]", Specifier);
return;
}
int wave = 1;
switch (args.Parameters[0].ToLower())
{
case "goblin":
case "goblins":
TSPlayer.All.SendInfoMessage("{0} has started a goblin army invasion.", args.Player.Name);
TShock.Utils.StartInvasion(1);
break;
case "snowman":
case "snowmen":
TSPlayer.All.SendInfoMessage("{0} has started a snow legion invasion.", args.Player.Name);
TShock.Utils.StartInvasion(2);
break;
case "pirate":
case "pirates":
TSPlayer.All.SendInfoMessage("{0} has started a pirate invasion.", args.Player.Name);
TShock.Utils.StartInvasion(3);
break;
case "pumpkin":
case "pumpkinmoon":
if (args.Parameters.Count > 1)
{
if (!int.TryParse(args.Parameters[1], out wave) || wave <= 0)
{
args.Player.SendErrorMessage("Invalid wave!");
break;
}
}
TSPlayer.Server.SetPumpkinMoon(true);
Main.bloodMoon = false;
NPC.waveKills = 0f;
NPC.waveNumber = wave;
TSPlayer.All.SendInfoMessage("{0} started the pumpkin moon at wave {1}!", args.Player.Name, wave);
break;
case "frost":
case "frostmoon":
if (args.Parameters.Count > 1)
{
if (!int.TryParse(args.Parameters[1], out wave) || wave <= 0)
{
args.Player.SendErrorMessage("Invalid wave!");
return;
}
}
TSPlayer.Server.SetFrostMoon(true);
Main.bloodMoon = false;
NPC.waveKills = 0f;
NPC.waveNumber = wave;
TSPlayer.All.SendInfoMessage("{0} started the frost moon at wave {1}!", args.Player.Name, wave);
break;
case "martian":
case "martians":
TSPlayer.All.SendInfoMessage("{0} has started a martian invasion.", args.Player.Name);
TShock.Utils.StartInvasion(4);
break;
}
}
else if (DD2Event.Ongoing)
{
DD2Event.StopInvasion();
TSPlayer.All.SendInfoMessage("{0} has ended the Old One's Army event.", args.Player.Name);
}
else
{
TSPlayer.All.SendInfoMessage("{0} has ended the invasion.", args.Player.Name);
Main.invasionSize = 0;
}
}
private static void ClearAnglerQuests(CommandArgs args)
{
if (args.Parameters.Count > 0)
{
var result = Main.anglerWhoFinishedToday.RemoveAll(s => s.ToLower().Equals(args.Parameters[0].ToLower()));
if (result > 0)
{
args.Player.SendSuccessMessage("Removed {0} players from the angler quest completion list for today.", result);
foreach (TSPlayer ply in TShock.Players.Where(p => p != null && p.Active && p.TPlayer.name.ToLower().Equals(args.Parameters[0].ToLower())))
{
//this will always tell the client that they have not done the quest today.
ply.SendData((PacketTypes)74, "");
}
}
else
args.Player.SendErrorMessage("Failed to find any users by that name on the list.");
}
else
{
Main.anglerWhoFinishedToday.Clear();
NetMessage.SendAnglerQuest(-1);
args.Player.SendSuccessMessage("Cleared all users from the angler quest completion list for today.");
}
}
private static void ToggleExpert(CommandArgs args)
{
Main.expertMode = !Main.expertMode;
TSPlayer.All.SendData(PacketTypes.WorldInfo);
args.Player.SendSuccessMessage("Expert mode is now {0}.", Main.expertMode ? "on" : "off");
}
private static void Hardmode(CommandArgs args)
{
if (Main.hardMode)
{
Main.hardMode = false;
TSPlayer.All.SendData(PacketTypes.WorldInfo);
args.Player.SendSuccessMessage("Hardmode is now off.");
}
else if (!TShock.Config.DisableHardmode)
{
WorldGen.StartHardmode();
args.Player.SendSuccessMessage("Hardmode is now on.");
}
else
{
args.Player.SendErrorMessage("Hardmode is disabled via config.");
}
}
private static void SpawnBoss(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}spawnboss <boss type> [amount]", Specifier);
return;
}
int amount = 1;
if (args.Parameters.Count == 2 && (!int.TryParse(args.Parameters[1], out amount) || amount <= 0))
{
args.Player.SendErrorMessage("Invalid boss amount!");
return;
}
NPC npc = new NPC();
switch (args.Parameters[0].ToLower())
{
case "*":
case "all":
int[] npcIds = { 4, 13, 35, 50, 125, 126, 127, 134, 222, 245, 262, 266, 370, 398 };
TSPlayer.Server.SetTime(false, 0.0);
foreach (int i in npcIds)
{
npc.SetDefaults(i);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
}
TSPlayer.All.SendSuccessMessage("{0} has spawned all bosses {1} time(s).", args.Player.Name, amount);
return;
case "brain":
case "brain of cthulhu":
npc.SetDefaults(266);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Brain of Cthulhu {1} time(s).", args.Player.Name, amount);
return;
case "destroyer":
npc.SetDefaults(134);
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Destroyer {1} time(s).", args.Player.Name, amount);
return;
case "duke":
case "duke fishron":
case "fishron":
npc.SetDefaults(370);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Duke Fishron {1} time(s).", args.Player.Name, amount);
return;
case "eater":
case "eater of worlds":
npc.SetDefaults(13);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Eater of Worlds {1} time(s).", args.Player.Name, amount);
return;
case "eye":
case "eye of cthulhu":
npc.SetDefaults(4);
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Eye of Cthulhu {1} time(s).", args.Player.Name, amount);
return;
case "golem":
npc.SetDefaults(245);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Golem {1} time(s).", args.Player.Name, amount);
return;
case "king":
case "king slime":
npc.SetDefaults(50);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned King Slime {1} time(s).", args.Player.Name, amount);
return;
case "plantera":
npc.SetDefaults(262);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Plantera {1} time(s).", args.Player.Name, amount);
return;
case "prime":
case "skeletron prime":
npc.SetDefaults(127);
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Skeletron Prime {1} time(s).", args.Player.Name, amount);
return;
case "queen":
case "queen bee":
npc.SetDefaults(222);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Queen Bee {1} time(s).", args.Player.Name, amount);
return;
case "skeletron":
npc.SetDefaults(35);
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Skeletron {1} time(s).", args.Player.Name, amount);
return;
case "twins":
TSPlayer.Server.SetTime(false, 0.0);
npc.SetDefaults(125);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
npc.SetDefaults(126);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Twins {1} time(s).", args.Player.Name, amount);
return;
case "wof":
case "wall of flesh":
if (Main.wof >= 0)
{
args.Player.SendErrorMessage("There is already a Wall of Flesh!");
return;
}
if (args.Player.Y / 16f < Main.maxTilesY - 205)
{
args.Player.SendErrorMessage("You must spawn the Wall of Flesh in hell!");
return;
}
NPC.SpawnWOF(new Vector2(args.Player.X, args.Player.Y));
TSPlayer.All.SendSuccessMessage("{0} has spawned the Wall of Flesh.", args.Player.Name);
return;
case "moon":
case "moon lord":
npc.SetDefaults(398);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Moon Lord {1} time(s).", args.Player.Name, amount);
return;
default:
args.Player.SendErrorMessage("Invalid boss type!");
return;
}
}
private static void SpawnMob(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}spawnmob <mob type> [amount]", Specifier);
return;
}
if (args.Parameters[0].Length == 0)
{
args.Player.SendErrorMessage("Invalid mob type!");
return;
}
int amount = 1;
if (args.Parameters.Count == 2 && !int.TryParse(args.Parameters[1], out amount))
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}spawnmob <mob type> [amount]", Specifier);
return;
}
amount = Math.Min(amount, Main.maxNPCs);
var npcs = TShock.Utils.GetNPCByIdOrName(args.Parameters[0]);
if (npcs.Count == 0)
{
args.Player.SendErrorMessage("Invalid mob type!");
}
else if (npcs.Count > 1)
{
args.Player.SendMultipleMatchError(npcs.Select(n => $"{n.FullName}({n.type})"));
}
else
{
var npc = npcs[0];
if (npc.type >= 1 && npc.type < Main.maxNPCTypes && npc.type != 113)
{
TSPlayer.Server.SpawnNPC(npc.netID, npc.FullName, amount, args.Player.TileX, args.Player.TileY, 50, 20);
if (args.Silent)
{
args.Player.SendSuccessMessage("Spawned {0} {1} time(s).", npc.FullName, amount);
}
else
{
TSPlayer.All.SendSuccessMessage("{0} has spawned {1} {2} time(s).", args.Player.Name, npc.FullName, amount);
}
}
else if (npc.type == 113)
{
if (Main.wof >= 0 || (args.Player.Y / 16f < (Main.maxTilesY - 205)))
{
args.Player.SendErrorMessage("Can't spawn Wall of Flesh!");
return;
}
NPC.SpawnWOF(new Vector2(args.Player.X, args.Player.Y));
if (args.Silent)
{
args.Player.SendSuccessMessage("Spawned Wall of Flesh!");
}
else
{
TSPlayer.All.SendSuccessMessage("{0} has spawned a Wall of Flesh!", args.Player.Name);
}
}
else
{
args.Player.SendErrorMessage("Invalid mob type!");
}
}
}
#endregion Cause Events and Spawn Monsters Commands
#region Teleport Commands
private static void Home(CommandArgs args)
{
args.Player.Spawn();
args.Player.SendSuccessMessage("Teleported to your spawnpoint.");
}
private static void Spawn(CommandArgs args)
{
if (args.Player.Teleport(Main.spawnTileX * 16, (Main.spawnTileY * 16) - 48))
args.Player.SendSuccessMessage("Teleported to the map's spawnpoint.");
}
private static void TP(CommandArgs args)
{
if (args.Parameters.Count != 1 && args.Parameters.Count != 2)
{
if (args.Player.HasPermission(Permissions.tpothers))
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tp <player> [player 2]", Specifier);
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tp <player>", Specifier);
return;
}
if (args.Parameters.Count == 1)
{
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var target = players[0];
if (!target.TPAllow && !args.Player.HasPermission(Permissions.tpoverride))
{
args.Player.SendErrorMessage("{0} has disabled players from teleporting.", target.Name);
return;
}
if (args.Player.Teleport(target.TPlayer.position.X, target.TPlayer.position.Y))
{
args.Player.SendSuccessMessage("Teleported to {0}.", target.Name);
if (!args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} teleported to you.", args.Player.Name);
}
}
}
else
{
if (!args.Player.HasPermission(Permissions.tpothers))
{
args.Player.SendErrorMessage("You do not have access to this command.");
return;
}
var players1 = TSPlayer.FindByNameOrID(args.Parameters[0]);
var players2 = TSPlayer.FindByNameOrID(args.Parameters[1]);
if (players2.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players2.Count > 1)
args.Player.SendMultipleMatchError(players2.Select(p => p.Name));
else if (players1.Count == 0)
{
if (args.Parameters[0] == "*")
{
if (!args.Player.HasPermission(Permissions.tpallothers))
{
args.Player.SendErrorMessage("You do not have access to this command.");
return;
}
var target = players2[0];
foreach (var source in TShock.Players.Where(p => p != null && p != args.Player))
{
if (!target.TPAllow && !args.Player.HasPermission(Permissions.tpoverride))
continue;
if (source.Teleport(target.TPlayer.position.X, target.TPlayer.position.Y))
{
if (args.Player != source)
{
if (args.Player.HasPermission(Permissions.tpsilent))
source.SendSuccessMessage("You were teleported to {0}.", target.Name);
else
source.SendSuccessMessage("{0} teleported you to {1}.", args.Player.Name, target.Name);
}
if (args.Player != target)
{
if (args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} was teleported to you.", source.Name);
if (!args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} teleported {1} to you.", args.Player.Name, source.Name);
}
}
}
args.Player.SendSuccessMessage("Teleported everyone to {0}.", target.Name);
}
else
args.Player.SendErrorMessage("Invalid player!");
}
else if (players1.Count > 1)
args.Player.SendMultipleMatchError(players1.Select(p => p.Name));
else
{
var source = players1[0];
if (!source.TPAllow && !args.Player.HasPermission(Permissions.tpoverride))
{
args.Player.SendErrorMessage("{0} has disabled players from teleporting.", source.Name);
return;
}
var target = players2[0];
if (!target.TPAllow && !args.Player.HasPermission(Permissions.tpoverride))
{
args.Player.SendErrorMessage("{0} has disabled players from teleporting.", target.Name);
return;
}
args.Player.SendSuccessMessage("Teleported {0} to {1}.", source.Name, target.Name);
if (source.Teleport(target.TPlayer.position.X, target.TPlayer.position.Y))
{
if (args.Player != source)
{
if (args.Player.HasPermission(Permissions.tpsilent))
source.SendSuccessMessage("You were teleported to {0}.", target.Name);
else
source.SendSuccessMessage("{0} teleported you to {1}.", args.Player.Name, target.Name);
}
if (args.Player != target)
{
if (args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} was teleported to you.", source.Name);
if (!args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} teleported {1} to you.", args.Player.Name, source.Name);
}
}
}
}
}
private static void TPHere(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
if (args.Player.HasPermission(Permissions.tpallothers))
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tphere <player|*>", Specifier);
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tphere <player>", Specifier);
return;
}
string playerName = String.Join(" ", args.Parameters);
var players = TSPlayer.FindByNameOrID(playerName);
if (players.Count == 0)
{
if (playerName == "*")
{
if (!args.Player.HasPermission(Permissions.tpallothers))
{
args.Player.SendErrorMessage("You do not have permission to use this command.");
return;
}
for (int i = 0; i < Main.maxPlayers; i++)
{
if (Main.player[i].active && (Main.player[i] != args.TPlayer))
{
if (TShock.Players[i].Teleport(args.TPlayer.position.X, args.TPlayer.position.Y))
TShock.Players[i].SendSuccessMessage(String.Format("You were teleported to {0}.", args.Player.Name));
}
}
args.Player.SendSuccessMessage("Teleported everyone to yourself.");
}
else
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var plr = players[0];
if (plr.Teleport(args.TPlayer.position.X, args.TPlayer.position.Y))
{
plr.SendInfoMessage("You were teleported to {0}.", args.Player.Name);
args.Player.SendSuccessMessage("Teleported {0} to yourself.", plr.Name);
}
}
}
private static void TPNpc(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tpnpc <NPC>", Specifier);
return;
}
var npcStr = string.Join(" ", args.Parameters);
var matches = new List<NPC>();
foreach (var npc in Main.npc.Where(npc => npc.active))
{
var englishName = EnglishLanguage.GetNpcNameById(npc.netID);
if (string.Equals(npc.FullName, npcStr, StringComparison.InvariantCultureIgnoreCase) ||
string.Equals(englishName, npcStr, StringComparison.InvariantCultureIgnoreCase))
{
matches = new List<NPC> { npc };
break;
}
if (npc.FullName.ToLowerInvariant().StartsWith(npcStr.ToLowerInvariant()) ||
englishName?.StartsWith(npcStr, StringComparison.InvariantCultureIgnoreCase) == true)
matches.Add(npc);
}
if (matches.Count > 1)
{
args.Player.SendMultipleMatchError(matches.Select(n => $"{n.FullName}({n.whoAmI})"));
return;
}
if (matches.Count == 0)
{
args.Player.SendErrorMessage("Invalid NPC!");
return;
}
var target = matches[0];
args.Player.Teleport(target.position.X, target.position.Y);
args.Player.SendSuccessMessage("Teleported to the '{0}'.", target.FullName);
}
private static void GetPos(CommandArgs args)
{
var player = args.Player.Name;
if (args.Parameters.Count > 0)
{
player = String.Join(" ", args.Parameters);
}
var players = TSPlayer.FindByNameOrID(player);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
args.Player.SendSuccessMessage("Location of {0} is ({1}, {2}).", players[0].Name, players[0].TileX, players[0].TileY);
}
}
private static void TPPos(CommandArgs args)
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tppos <tile x> <tile y>", Specifier);
return;
}
int x, y;
if (!int.TryParse(args.Parameters[0], out x) || !int.TryParse(args.Parameters[1], out y))
{
args.Player.SendErrorMessage("Invalid tile positions!");
return;
}
x = Math.Max(0, x);
y = Math.Max(0, y);
x = Math.Min(x, Main.maxTilesX - 1);
y = Math.Min(y, Main.maxTilesY - 1);
args.Player.Teleport(16 * x, 16 * y);
args.Player.SendSuccessMessage("Teleported to {0}, {1}!", x, y);
}
private static void TPAllow(CommandArgs args)
{
if (!args.Player.TPAllow)
args.Player.SendSuccessMessage("You have removed your teleportation protection.");
if (args.Player.TPAllow)
args.Player.SendSuccessMessage("You have enabled teleportation protection.");
args.Player.TPAllow = !args.Player.TPAllow;
}
private static void Warp(CommandArgs args)
{
bool hasManageWarpPermission = args.Player.HasPermission(Permissions.managewarp);
if (args.Parameters.Count < 1)
{
if (hasManageWarpPermission)
{
args.Player.SendInfoMessage("Invalid syntax! Proper syntax: {0}warp [command] [arguments]", Specifier);
args.Player.SendInfoMessage("Commands: add, del, hide, list, send, [warpname]");
args.Player.SendInfoMessage("Arguments: add [warp name], del [warp name], list [page]");
args.Player.SendInfoMessage("Arguments: send [player] [warp name], hide [warp name] [Enable(true/false)]");
args.Player.SendInfoMessage("Examples: {0}warp add foobar, {0}warp hide foobar true, {0}warp foobar", Specifier);
return;
}
else
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp [name] or {0}warp list <page>", Specifier);
return;
}
}
if (args.Parameters[0].Equals("list"))
{
#region List warps
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<string> warpNames = from warp in TShock.Warps.Warps
where !warp.IsPrivate
select warp.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(warpNames),
new PaginationTools.Settings
{
HeaderFormat = "Warps ({0}/{1}):",
FooterFormat = "Type {0}warp list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no warps defined."
});
#endregion
}
else if (args.Parameters[0].ToLower() == "add" && hasManageWarpPermission)
{
#region Add warp
if (args.Parameters.Count == 2)
{
string warpName = args.Parameters[1];
if (warpName == "list" || warpName == "hide" || warpName == "del" || warpName == "add")
{
args.Player.SendErrorMessage("Name reserved, use a different name.");
}
else if (TShock.Warps.Add(args.Player.TileX, args.Player.TileY, warpName))
{
args.Player.SendSuccessMessage("Warp added: " + warpName);
}
else
{
args.Player.SendErrorMessage("Warp " + warpName + " already exists.");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp add [name]", Specifier);
#endregion
}
else if (args.Parameters[0].ToLower() == "del" && hasManageWarpPermission)
{
#region Del warp
if (args.Parameters.Count == 2)
{
string warpName = args.Parameters[1];
if (TShock.Warps.Remove(warpName))
{
args.Player.SendSuccessMessage("Warp deleted: " + warpName);
}
else
args.Player.SendErrorMessage("Could not find the specified warp.");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp del [name]", Specifier);
#endregion
}
else if (args.Parameters[0].ToLower() == "hide" && hasManageWarpPermission)
{
#region Hide warp
if (args.Parameters.Count == 3)
{
string warpName = args.Parameters[1];
bool state = false;
if (Boolean.TryParse(args.Parameters[2], out state))
{
if (TShock.Warps.Hide(args.Parameters[1], state))
{
if (state)
args.Player.SendSuccessMessage("Warp " + warpName + " is now private.");
else
args.Player.SendSuccessMessage("Warp " + warpName + " is now public.");
}
else
args.Player.SendErrorMessage("Could not find specified warp.");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp hide [name] <true/false>", Specifier);
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp hide [name] <true/false>", Specifier);
#endregion
}
else if (args.Parameters[0].ToLower() == "send" && args.Player.HasPermission(Permissions.tpothers))
{
#region Warp send
if (args.Parameters.Count < 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp send [player] [warpname]", Specifier);
return;
}
var foundplr = TSPlayer.FindByNameOrID(args.Parameters[1]);
if (foundplr.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
else if (foundplr.Count > 1)
{
args.Player.SendMultipleMatchError(foundplr.Select(p => p.Name));
return;
}
string warpName = args.Parameters[2];
var warp = TShock.Warps.Find(warpName);
var plr = foundplr[0];
if (warp.Position != Point.Zero)
{
if (plr.Teleport(warp.Position.X * 16, warp.Position.Y * 16))
{
plr.SendSuccessMessage(String.Format("{0} warped you to {1}.", args.Player.Name, warpName));
args.Player.SendSuccessMessage(String.Format("You warped {0} to {1}.", plr.Name, warpName));
}
}
else
{
args.Player.SendErrorMessage("Specified warp not found.");
}
#endregion
}
else
{
string warpName = String.Join(" ", args.Parameters);
var warp = TShock.Warps.Find(warpName);
if (warp != null)
{
if (args.Player.Teleport(warp.Position.X * 16, warp.Position.Y * 16))
args.Player.SendSuccessMessage("Warped to " + warpName + ".");
}
else
{
args.Player.SendErrorMessage("The specified warp was not found.");
}
}
}
#endregion Teleport Commands
#region Group Management
private static void Group(CommandArgs args)
{
string subCmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subCmd)
{
case "add":
#region Add group
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group add <group name> [permissions]", Specifier);
return;
}
string groupName = args.Parameters[1];
args.Parameters.RemoveRange(0, 2);
string permissions = String.Join(",", args.Parameters);
try
{
TShock.Groups.AddGroup(groupName, null, permissions, TShockAPI.Group.defaultChatColor);
args.Player.SendSuccessMessage("The group was added successfully!");
}
catch (GroupExistsException)
{
args.Player.SendErrorMessage("That group already exists!");
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.ToString());
}
}
#endregion
return;
case "addperm":
#region Add permissions
{
if (args.Parameters.Count < 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group addperm <group name> <permissions...>", Specifier);
return;
}
string groupName = args.Parameters[1];
args.Parameters.RemoveRange(0, 2);
if (groupName == "*")
{
foreach (Group g in TShock.Groups)
{
TShock.Groups.AddPermissions(g.Name, args.Parameters);
}
args.Player.SendSuccessMessage("Modified all groups.");
return;
}
try
{
string response = TShock.Groups.AddPermissions(groupName, args.Parameters);
if (response.Length > 0)
{
args.Player.SendSuccessMessage(response);
}
return;
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.ToString());
}
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <name> <permissions...> - Adds a new group.",
"addperm <group> <permissions...> - Adds permissions to a group.",
"color <group> <rrr,ggg,bbb> - Changes a group's chat color.",
"rename <group> <new name> - Changes a group's name.",
"del <group> - Deletes a group.",
"delperm <group> <permissions...> - Removes permissions from a group.",
"list [page] - Lists groups.",
"listperm <group> [page] - Lists a group's permissions.",
"parent <group> <parent group> - Changes a group's parent group.",
"prefix <group> <prefix> - Changes a group's prefix.",
"suffix <group> <suffix> - Changes a group's suffix."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Group Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}group help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "parent":
#region Parent
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group parent <group name> [new parent group name]", Specifier);
return;
}
string groupName = args.Parameters[1];
Group group = TShock.Groups.GetGroupByName(groupName);
if (group == null)
{
args.Player.SendErrorMessage("No such group \"{0}\".", groupName);
return;
}
if (args.Parameters.Count > 2)
{
string newParentGroupName = string.Join(" ", args.Parameters.Skip(2));
if (!string.IsNullOrWhiteSpace(newParentGroupName) && !TShock.Groups.GroupExists(newParentGroupName))
{
args.Player.SendErrorMessage("No such group \"{0}\".", newParentGroupName);
return;
}
try
{
TShock.Groups.UpdateGroup(groupName, newParentGroupName, group.Permissions, group.ChatColor, group.Suffix, group.Prefix);
if (!string.IsNullOrWhiteSpace(newParentGroupName))
args.Player.SendSuccessMessage("Parent of group \"{0}\" set to \"{1}\".", groupName, newParentGroupName);
else
args.Player.SendSuccessMessage("Removed parent of group \"{0}\".", groupName);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
else
{
if (group.Parent != null)
args.Player.SendSuccessMessage("Parent of \"{0}\" is \"{1}\".", group.Name, group.Parent.Name);
else
args.Player.SendSuccessMessage("Group \"{0}\" has no parent.", group.Name);
}
}
#endregion
return;
case "suffix":
#region Suffix
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group suffix <group name> [new suffix]", Specifier);
return;
}
string groupName = args.Parameters[1];
Group group = TShock.Groups.GetGroupByName(groupName);
if (group == null)
{
args.Player.SendErrorMessage("No such group \"{0}\".", groupName);
return;
}
if (args.Parameters.Count > 2)
{
string newSuffix = string.Join(" ", args.Parameters.Skip(2));
try
{
TShock.Groups.UpdateGroup(groupName, group.ParentName, group.Permissions, group.ChatColor, newSuffix, group.Prefix);
if (!string.IsNullOrWhiteSpace(newSuffix))
args.Player.SendSuccessMessage("Suffix of group \"{0}\" set to \"{1}\".", groupName, newSuffix);
else
args.Player.SendSuccessMessage("Removed suffix of group \"{0}\".", groupName);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
else
{
if (!string.IsNullOrWhiteSpace(group.Suffix))
args.Player.SendSuccessMessage("Suffix of \"{0}\" is \"{1}\".", group.Name, group.Suffix);
else
args.Player.SendSuccessMessage("Group \"{0}\" has no suffix.", group.Name);
}
}
#endregion
return;
case "prefix":
#region Prefix
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group prefix <group name> [new prefix]", Specifier);
return;
}
string groupName = args.Parameters[1];
Group group = TShock.Groups.GetGroupByName(groupName);
if (group == null)
{
args.Player.SendErrorMessage("No such group \"{0}\".", groupName);
return;
}
if (args.Parameters.Count > 2)
{
string newPrefix = string.Join(" ", args.Parameters.Skip(2));
try
{
TShock.Groups.UpdateGroup(groupName, group.ParentName, group.Permissions, group.ChatColor, group.Suffix, newPrefix);
if (!string.IsNullOrWhiteSpace(newPrefix))
args.Player.SendSuccessMessage("Prefix of group \"{0}\" set to \"{1}\".", groupName, newPrefix);
else
args.Player.SendSuccessMessage("Removed prefix of group \"{0}\".", groupName);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
else
{
if (!string.IsNullOrWhiteSpace(group.Prefix))
args.Player.SendSuccessMessage("Prefix of \"{0}\" is \"{1}\".", group.Name, group.Prefix);
else
args.Player.SendSuccessMessage("Group \"{0}\" has no prefix.", group.Name);
}
}
#endregion
return;
case "color":
#region Color
{
if (args.Parameters.Count < 2 || args.Parameters.Count > 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group color <group name> [new color(000,000,000)]", Specifier);
return;
}
string groupName = args.Parameters[1];
Group group = TShock.Groups.GetGroupByName(groupName);
if (group == null)
{
args.Player.SendErrorMessage("No such group \"{0}\".", groupName);
return;
}
if (args.Parameters.Count == 3)
{
string newColor = args.Parameters[2];
String[] parts = newColor.Split(',');
byte r;
byte g;
byte b;
if (parts.Length == 3 && byte.TryParse(parts[0], out r) && byte.TryParse(parts[1], out g) && byte.TryParse(parts[2], out b))
{
try
{
TShock.Groups.UpdateGroup(groupName, group.ParentName, group.Permissions, newColor, group.Suffix, group.Prefix);
args.Player.SendSuccessMessage("Color of group \"{0}\" set to \"{1}\".", groupName, newColor);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
else
{
args.Player.SendErrorMessage("Invalid syntax for color, expected \"rrr,ggg,bbb\"");
}
}
else
{
args.Player.SendSuccessMessage("Color of \"{0}\" is \"{1}\".", group.Name, group.ChatColor);
}
}
#endregion
return;
case "rename":
#region Rename group
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group rename <group> <new name>", Specifier);
return;
}
string group = args.Parameters[1];
string newName = args.Parameters[2];
try
{
string response = TShock.Groups.RenameGroup(group, newName);
args.Player.SendSuccessMessage(response);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
#endregion
return;
case "del":
#region Delete group
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group del <group name>", Specifier);
return;
}
try
{
string response = TShock.Groups.DeleteGroup(args.Parameters[1]);
if (response.Length > 0)
{
args.Player.SendSuccessMessage(response);
}
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.ToString());
}
}
#endregion
return;
case "delperm":
#region Delete permissions
{
if (args.Parameters.Count < 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group delperm <group name> <permissions...>", Specifier);
return;
}
string groupName = args.Parameters[1];
args.Parameters.RemoveRange(0, 2);
if (groupName == "*")
{
foreach (Group g in TShock.Groups)
{
TShock.Groups.DeletePermissions(g.Name, args.Parameters);
}
args.Player.SendSuccessMessage("Modified all groups.");
return;
}
try
{
string response = TShock.Groups.DeletePermissions(groupName, args.Parameters);
if (response.Length > 0)
{
args.Player.SendSuccessMessage(response);
}
return;
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.ToString());
}
}
#endregion
return;
case "list":
#region List groups
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var groupNames = from grp in TShock.Groups.groups
select grp.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(groupNames),
new PaginationTools.Settings
{
HeaderFormat = "Groups ({0}/{1}):",
FooterFormat = "Type {0}group list {{0}} for more.".SFormat(Specifier)
});
}
#endregion
return;
case "listperm":
#region List permissions
{
if (args.Parameters.Count == 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group listperm <group name> [page]", Specifier);
return;
}
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 2, args.Player, out pageNumber))
return;
if (!TShock.Groups.GroupExists(args.Parameters[1]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
Group grp = TShock.Groups.GetGroupByName(args.Parameters[1]);
List<string> permissions = grp.TotalPermissions;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(permissions),
new PaginationTools.Settings
{
HeaderFormat = "Permissions for " + grp.Name + " ({0}/{1}):",
FooterFormat = "Type {0}group listperm {1} {{0}} for more.".SFormat(Specifier, grp.Name),
NothingToDisplayString = "There are currently no permissions for " + grp.Name + "."
});
}
#endregion
return;
}
}
#endregion Group Management
#region Item Management
private static void ItemBan(CommandArgs args)
{
string subCmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subCmd)
{
case "add":
#region Add item
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}itemban add <item name>", Specifier);
return;
}
List<Item> items = TShock.Utils.GetItemByIdOrName(args.Parameters[1]);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item.");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
TShock.Itembans.AddNewBan(EnglishLanguage.GetItemNameById(items[0].type));
args.Player.SendSuccessMessage("Banned " + items[0].Name + ".");
}
}
#endregion
return;
case "allow":
#region Allow group to item
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}itemban allow <item name> <group name>", Specifier);
return;
}
List<Item> items = TShock.Utils.GetItemByIdOrName(args.Parameters[1]);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item.");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
ItemBan ban = TShock.Itembans.GetItemBanByName(EnglishLanguage.GetItemNameById(items[0].type));
if (ban == null)
{
args.Player.SendErrorMessage("{0} is not banned.", items[0].Name);
return;
}
if (!ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.Itembans.AllowGroup(EnglishLanguage.GetItemNameById(items[0].type), args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been allowed to use {1}.", args.Parameters[2], items[0].Name);
}
else
{
args.Player.SendWarningMessage("{0} is already allowed to use {1}.", args.Parameters[2], items[0].Name);
}
}
}
#endregion
return;
case "del":
#region Delete item
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}itemban del <item name>", Specifier);
return;
}
List<Item> items = TShock.Utils.GetItemByIdOrName(args.Parameters[1]);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item.");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
TShock.Itembans.RemoveBan(EnglishLanguage.GetItemNameById(items[0].type));
args.Player.SendSuccessMessage("Unbanned " + items[0].Name + ".");
}
}
#endregion
return;
case "disallow":
#region Disllow group from item
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}itemban disallow <item name> <group name>", Specifier);
return;
}
List<Item> items = TShock.Utils.GetItemByIdOrName(args.Parameters[1]);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item.");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
ItemBan ban = TShock.Itembans.GetItemBanByName(EnglishLanguage.GetItemNameById(items[0].type));
if (ban == null)
{
args.Player.SendErrorMessage("{0} is not banned.", items[0].Name);
return;
}
if (ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.Itembans.RemoveGroup(EnglishLanguage.GetItemNameById(items[0].type), args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been disallowed to use {1}.", args.Parameters[2], items[0].Name);
}
else
{
args.Player.SendWarningMessage("{0} is already disallowed to use {1}.", args.Parameters[2], items[0].Name);
}
}
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <item> - Adds an item ban.",
"allow <item> <group> - Allows a group to use an item.",
"del <item> - Deletes an item ban.",
"disallow <item> <group> - Disallows a group from using an item.",
"list [page] - Lists all item bans."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Item Ban Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}itemban help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "list":
#region List items
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<string> itemNames = from itemBan in TShock.Itembans.ItemBans
select itemBan.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(itemNames),
new PaginationTools.Settings
{
HeaderFormat = "Item bans ({0}/{1}):",
FooterFormat = "Type {0}itemban list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no banned items."
});
}
#endregion
return;
}
}
#endregion Item Management
#region Projectile Management
private static void ProjectileBan(CommandArgs args)
{
string subCmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subCmd)
{
case "add":
#region Add projectile
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}projban add <proj id>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id > 0 && id < Main.maxProjectileTypes)
{
TShock.ProjectileBans.AddNewBan(id);
args.Player.SendSuccessMessage("Banned projectile {0}.", id);
}
else
args.Player.SendErrorMessage("Invalid projectile ID!");
}
#endregion
return;
case "allow":
#region Allow group to projectile
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}projban allow <id> <group>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id > 0 && id < Main.maxProjectileTypes)
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
ProjectileBan ban = TShock.ProjectileBans.GetBanById(id);
if (ban == null)
{
args.Player.SendErrorMessage("Projectile {0} is not banned.", id);
return;
}
if (!ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.ProjectileBans.AllowGroup(id, args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been allowed to use projectile {1}.", args.Parameters[2], id);
}
else
args.Player.SendWarningMessage("{0} is already allowed to use projectile {1}.", args.Parameters[2], id);
}
else
args.Player.SendErrorMessage("Invalid projectile ID!");
}
#endregion
return;
case "del":
#region Delete projectile
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}projban del <id>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id > 0 && id < Main.maxProjectileTypes)
{
TShock.ProjectileBans.RemoveBan(id);
args.Player.SendSuccessMessage("Unbanned projectile {0}.", id);
return;
}
else
args.Player.SendErrorMessage("Invalid projectile ID!");
}
#endregion
return;
case "disallow":
#region Disallow group from projectile
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}projban disallow <id> <group name>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id > 0 && id < Main.maxProjectileTypes)
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
ProjectileBan ban = TShock.ProjectileBans.GetBanById(id);
if (ban == null)
{
args.Player.SendErrorMessage("Projectile {0} is not banned.", id);
return;
}
if (ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.ProjectileBans.RemoveGroup(id, args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been disallowed from using projectile {1}.", args.Parameters[2], id);
return;
}
else
args.Player.SendWarningMessage("{0} is already prevented from using projectile {1}.", args.Parameters[2], id);
}
else
args.Player.SendErrorMessage("Invalid projectile ID!");
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <projectile ID> - Adds a projectile ban.",
"allow <projectile ID> <group> - Allows a group to use a projectile.",
"del <projectile ID> - Deletes an projectile ban.",
"disallow <projectile ID> <group> - Disallows a group from using a projectile.",
"list [page] - Lists all projectile bans."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Projectile Ban Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}projban help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "list":
#region List projectiles
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<Int16> projectileIds = from projectileBan in TShock.ProjectileBans.ProjectileBans
select projectileBan.ID;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(projectileIds),
new PaginationTools.Settings
{
HeaderFormat = "Projectile bans ({0}/{1}):",
FooterFormat = "Type {0}projban list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no banned projectiles."
});
}
#endregion
return;
}
}
#endregion Projectile Management
#region Tile Management
private static void TileBan(CommandArgs args)
{
string subCmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subCmd)
{
case "add":
#region Add tile
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tileban add <tile id>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id >= 0 && id < Main.maxTileSets)
{
TShock.TileBans.AddNewBan(id);
args.Player.SendSuccessMessage("Banned tile {0}.", id);
}
else
args.Player.SendErrorMessage("Invalid tile ID!");
}
#endregion
return;
case "allow":
#region Allow group to place tile
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tileban allow <id> <group>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id >= 0 && id < Main.maxTileSets)
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
TileBan ban = TShock.TileBans.GetBanById(id);
if (ban == null)
{
args.Player.SendErrorMessage("Tile {0} is not banned.", id);
return;
}
if (!ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.TileBans.AllowGroup(id, args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been allowed to place tile {1}.", args.Parameters[2], id);
}
else
args.Player.SendWarningMessage("{0} is already allowed to place tile {1}.", args.Parameters[2], id);
}
else
args.Player.SendErrorMessage("Invalid tile ID!");
}
#endregion
return;
case "del":
#region Delete tile ban
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tileban del <id>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id >= 0 && id < Main.maxTileSets)
{
TShock.TileBans.RemoveBan(id);
args.Player.SendSuccessMessage("Unbanned tile {0}.", id);
return;
}
else
args.Player.SendErrorMessage("Invalid tile ID!");
}
#endregion
return;
case "disallow":
#region Disallow group from placing tile
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tileban disallow <id> <group name>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id >= 0 && id < Main.maxTileSets)
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
TileBan ban = TShock.TileBans.GetBanById(id);
if (ban == null)
{
args.Player.SendErrorMessage("Tile {0} is not banned.", id);
return;
}
if (ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.TileBans.RemoveGroup(id, args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been disallowed from placing tile {1}.", args.Parameters[2], id);
return;
}
else
args.Player.SendWarningMessage("{0} is already prevented from placing tile {1}.", args.Parameters[2], id);
}
else
args.Player.SendErrorMessage("Invalid tile ID!");
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <tile ID> - Adds a tile ban.",
"allow <tile ID> <group> - Allows a group to place a tile.",
"del <tile ID> - Deletes a tile ban.",
"disallow <tile ID> <group> - Disallows a group from place a tile.",
"list [page] - Lists all tile bans."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Tile Ban Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}tileban help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "list":
#region List tile bans
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<Int16> tileIds = from tileBan in TShock.TileBans.TileBans
select tileBan.ID;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(tileIds),
new PaginationTools.Settings
{
HeaderFormat = "Tile bans ({0}/{1}):",
FooterFormat = "Type {0}tileban list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no banned tiles."
});
}
#endregion
return;
}
}
#endregion Tile Management
#region Server Config Commands
private static void SetSpawn(CommandArgs args)
{
Main.spawnTileX = args.Player.TileX + 1;
Main.spawnTileY = args.Player.TileY + 3;
SaveManager.Instance.SaveWorld(false);
args.Player.SendSuccessMessage("Spawn has now been set at your location.");
}
private static void SetDungeon(CommandArgs args)
{
Main.dungeonX = args.Player.TileX + 1;
Main.dungeonY = args.Player.TileY + 3;
SaveManager.Instance.SaveWorld(false);
args.Player.SendSuccessMessage("The dungeon's position has now been set at your location.");
}
private static void Reload(CommandArgs args)
{
TShock.Utils.Reload();
Hooks.GeneralHooks.OnReloadEvent(args.Player);
args.Player.SendSuccessMessage(
"Configuration, permissions, and regions reload complete. Some changes may require a server restart.");
}
private static void ServerPassword(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}serverpassword \"<new password>\"", Specifier);
return;
}
string passwd = args.Parameters[0];
TShock.Config.ServerPassword = passwd;
args.Player.SendSuccessMessage(string.Format("Server password has been changed to: {0}.", passwd));
}
private static void Save(CommandArgs args)
{
SaveManager.Instance.SaveWorld(false);
foreach (TSPlayer tsply in TShock.Players.Where(tsply => tsply != null))
{
tsply.SaveServerCharacter();
}
args.Player.SendSuccessMessage("Save succeeded.");
}
private static void Settle(CommandArgs args)
{
if (Liquid.panicMode)
{
args.Player.SendWarningMessage("Liquids are already settling!");
return;
}
Liquid.StartPanic();
args.Player.SendInfoMessage("Settling liquids.");
}
private static void MaxSpawns(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendInfoMessage("Current maximum spawns: {0}", TShock.Config.DefaultMaximumSpawns);
return;
}
if (String.Equals(args.Parameters[0], "default", StringComparison.CurrentCultureIgnoreCase))
{
TShock.Config.DefaultMaximumSpawns = NPC.defaultMaxSpawns = 5;
if (args.Silent)
{
args.Player.SendInfoMessage("Changed the maximum spawns to 5.");
}
else
{
TSPlayer.All.SendInfoMessage("{0} changed the maximum spawns to 5.", args.Player.Name);
}
return;
}
int maxSpawns = -1;
if (!int.TryParse(args.Parameters[0], out maxSpawns) || maxSpawns < 0 || maxSpawns > Main.maxNPCs)
{
args.Player.SendWarningMessage("Invalid maximum spawns! Acceptable range is {0} to {1}", 0, Main.maxNPCs);
return;
}
TShock.Config.DefaultMaximumSpawns = NPC.defaultMaxSpawns = maxSpawns;
if (args.Silent)
{
args.Player.SendInfoMessage("Changed the maximum spawns to {0}.", maxSpawns);
}
else
{
TSPlayer.All.SendInfoMessage("{0} changed the maximum spawns to {1}.", args.Player.Name, maxSpawns);
}
}
private static void SpawnRate(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendInfoMessage("Current spawn rate: {0}", TShock.Config.DefaultSpawnRate);
return;
}
if (String.Equals(args.Parameters[0], "default", StringComparison.CurrentCultureIgnoreCase))
{
TShock.Config.DefaultSpawnRate = NPC.defaultSpawnRate = 600;
if (args.Silent)
{
args.Player.SendInfoMessage("Changed the spawn rate to 600.");
}
else
{
TSPlayer.All.SendInfoMessage("{0} changed the spawn rate to 600.", args.Player.Name);
}
return;
}
int spawnRate = -1;
if (!int.TryParse(args.Parameters[0], out spawnRate) || spawnRate < 0)
{
args.Player.SendWarningMessage("Invalid spawn rate!");
return;
}
TShock.Config.DefaultSpawnRate = NPC.defaultSpawnRate = spawnRate;
if (args.Silent)
{
args.Player.SendInfoMessage("Changed the spawn rate to {0}.", spawnRate);
}
else
{
TSPlayer.All.SendInfoMessage("{0} changed the spawn rate to {1}.", args.Player.Name, spawnRate);
}
}
#endregion Server Config Commands
#region Time/PvpFun Commands
private static void Time(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
double time = Main.time / 3600.0;
time += 4.5;
if (!Main.dayTime)
time += 15.0;
time = time % 24.0;
args.Player.SendInfoMessage("The current time is {0}:{1:D2}.", (int)Math.Floor(time), (int)Math.Floor((time % 1.0) * 60.0));
return;
}
switch (args.Parameters[0].ToLower())
{
case "day":
TSPlayer.Server.SetTime(true, 0.0);
TSPlayer.All.SendInfoMessage("{0} set the time to 4:30.", args.Player.Name);
break;
case "night":
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.All.SendInfoMessage("{0} set the time to 19:30.", args.Player.Name);
break;
case "noon":
TSPlayer.Server.SetTime(true, 27000.0);
TSPlayer.All.SendInfoMessage("{0} set the time to 12:00.", args.Player.Name);
break;
case "midnight":
TSPlayer.Server.SetTime(false, 16200.0);
TSPlayer.All.SendInfoMessage("{0} set the time to 0:00.", args.Player.Name);
break;
default:
string[] array = args.Parameters[0].Split(':');
if (array.Length != 2)
{
args.Player.SendErrorMessage("Invalid time string! Proper format: hh:mm, in 24-hour time.");
return;
}
int hours;
int minutes;
if (!int.TryParse(array[0], out hours) || hours < 0 || hours > 23
|| !int.TryParse(array[1], out minutes) || minutes < 0 || minutes > 59)
{
args.Player.SendErrorMessage("Invalid time string! Proper format: hh:mm, in 24-hour time.");
return;
}
decimal time = hours + (minutes / 60.0m);
time -= 4.50m;
if (time < 0.00m)
time += 24.00m;
if (time >= 15.00m)
{
TSPlayer.Server.SetTime(false, (double)((time - 15.00m) * 3600.0m));
}
else
{
TSPlayer.Server.SetTime(true, (double)(time * 3600.0m));
}
TSPlayer.All.SendInfoMessage("{0} set the time to {1}:{2:D2}.", args.Player.Name, hours, minutes);
break;
}
}
private static void Sandstorm(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}sandstorm <stop/start>", Specifier);
return;
}
switch (args.Parameters[0].ToLowerInvariant())
{
case "start":
Terraria.GameContent.Events.Sandstorm.StartSandstorm();
TSPlayer.All.SendInfoMessage("{0} started a sandstorm.", args.Player.Name);
break;
case "stop":
Terraria.GameContent.Events.Sandstorm.StopSandstorm();
TSPlayer.All.SendInfoMessage("{0} stopped the sandstorm.", args.Player.Name);
break;
default:
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}sandstorm <stop/start>", Specifier);
break;
}
}
private static void Rain(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}rain [slime] <stop/start>", Specifier);
return;
}
int switchIndex = 0;
if (args.Parameters.Count == 2 && args.Parameters[0].ToLowerInvariant() == "slime")
{
switchIndex = 1;
}
switch (args.Parameters[switchIndex].ToLower())
{
case "start":
if (switchIndex == 1)
{
Main.StartSlimeRain(false);
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} caused it to rain slime.", args.Player.Name);
}
else
{
Main.StartRain();
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} caused it to rain.", args.Player.Name);
}
break;
case "stop":
if (switchIndex == 1)
{
Main.StopSlimeRain(false);
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} ended the slimey downpour.", args.Player.Name);
}
else
{
Main.StopRain();
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} ended the downpour.", args.Player.Name);
}
break;
default:
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}rain [slime] <stop/start>", Specifier);
break;
}
}
private static void Slap(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}slap <player> [damage]", Specifier);
return;
}
if (args.Parameters[0].Length == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
string plStr = args.Parameters[0];
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
var plr = players[0];
int damage = 5;
if (args.Parameters.Count == 2)
{
int.TryParse(args.Parameters[1], out damage);
}
if (!args.Player.HasPermission(Permissions.kill))
{
damage = TShock.Utils.Clamp(damage, 15, 0);
}
plr.DamagePlayer(damage);
TSPlayer.All.SendInfoMessage("{0} slapped {1} for {2} damage.", args.Player.Name, plr.Name, damage);
TShock.Log.Info("{0} slapped {1} for {2} damage.", args.Player.Name, plr.Name, damage);
}
}
private static void Wind(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}wind <speed>", Specifier);
return;
}
int speed;
if (!int.TryParse(args.Parameters[0], out speed) || speed * 100 < 0)
{
args.Player.SendErrorMessage("Invalid wind speed!");
return;
}
Main.windSpeed = speed;
Main.windSpeedSet = speed;
Main.windSpeedSpeed = 0f;
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} changed the wind speed to {1}.", args.Player.Name, speed);
}
#endregion Time/PvpFun Commands
#region Region Commands
private static void Region(CommandArgs args)
{
string cmd = "help";
if (args.Parameters.Count > 0)
{
cmd = args.Parameters[0].ToLower();
}
switch (cmd)
{
case "name":
{
{
args.Player.SendInfoMessage("Hit a block to get the name of the region");
args.Player.AwaitingName = true;
args.Player.AwaitingNameParameters = args.Parameters.Skip(1).ToArray();
}
break;
}
case "set":
{
int choice = 0;
if (args.Parameters.Count == 2 &&
int.TryParse(args.Parameters[1], out choice) &&
choice >= 1 && choice <= 2)
{
args.Player.SendInfoMessage("Hit a block to Set Point " + choice);
args.Player.AwaitingTempPoint = choice;
}
else
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: /region set <1/2>");
}
break;
}
case "define":
{
if (args.Parameters.Count > 1)
{
if (!args.Player.TempPoints.Any(p => p == Point.Zero))
{
string regionName = String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1));
var x = Math.Min(args.Player.TempPoints[0].X, args.Player.TempPoints[1].X);
var y = Math.Min(args.Player.TempPoints[0].Y, args.Player.TempPoints[1].Y);
var width = Math.Abs(args.Player.TempPoints[0].X - args.Player.TempPoints[1].X);
var height = Math.Abs(args.Player.TempPoints[0].Y - args.Player.TempPoints[1].Y);
if (TShock.Regions.AddRegion(x, y, width, height, regionName, args.Player.Account.Name,
Main.worldID.ToString()))
{
args.Player.TempPoints[0] = Point.Zero;
args.Player.TempPoints[1] = Point.Zero;
args.Player.SendInfoMessage("Set region " + regionName);
}
else
{
args.Player.SendErrorMessage("Region " + regionName + " already exists");
}
}
else
{
args.Player.SendErrorMessage("Points not set up yet");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region define <name>", Specifier);
break;
}
case "protect":
{
if (args.Parameters.Count == 3)
{
string regionName = args.Parameters[1];
if (args.Parameters[2].ToLower() == "true")
{
if (TShock.Regions.SetRegionState(regionName, true))
args.Player.SendInfoMessage("Protected region " + regionName);
else
args.Player.SendErrorMessage("Could not find specified region");
}
else if (args.Parameters[2].ToLower() == "false")
{
if (TShock.Regions.SetRegionState(regionName, false))
args.Player.SendInfoMessage("Unprotected region " + regionName);
else
args.Player.SendErrorMessage("Could not find specified region");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region protect <name> <true/false>", Specifier);
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: /region protect <name> <true/false>", Specifier);
break;
}
case "delete":
{
if (args.Parameters.Count > 1)
{
string regionName = String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1));
if (TShock.Regions.DeleteRegion(regionName))
{
args.Player.SendInfoMessage("Deleted region \"{0}\".", regionName);
}
else
args.Player.SendErrorMessage("Could not find the specified region!");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region delete <name>", Specifier);
break;
}
case "clear":
{
args.Player.TempPoints[0] = Point.Zero;
args.Player.TempPoints[1] = Point.Zero;
args.Player.SendInfoMessage("Cleared temporary points.");
args.Player.AwaitingTempPoint = 0;
break;
}
case "allow":
{
if (args.Parameters.Count > 2)
{
string playerName = args.Parameters[1];
string regionName = "";
for (int i = 2; i < args.Parameters.Count; i++)
{
if (regionName == "")
{
regionName = args.Parameters[2];
}
else
{
regionName = regionName + " " + args.Parameters[i];
}
}
if (TShock.UserAccounts.GetUserAccountByName(playerName) != null)
{
if (TShock.Regions.AddNewUser(regionName, playerName))
{
args.Player.SendInfoMessage("Added user " + playerName + " to " + regionName);
}
else
args.Player.SendErrorMessage("Region " + regionName + " not found");
}
else
{
args.Player.SendErrorMessage("Player " + playerName + " not found");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region allow <name> <region>", Specifier);
break;
}
case "remove":
if (args.Parameters.Count > 2)
{
string playerName = args.Parameters[1];
string regionName = "";
for (int i = 2; i < args.Parameters.Count; i++)
{
if (regionName == "")
{
regionName = args.Parameters[2];
}
else
{
regionName = regionName + " " + args.Parameters[i];
}
}
if (TShock.UserAccounts.GetUserAccountByName(playerName) != null)
{
if (TShock.Regions.RemoveUser(regionName, playerName))
{
args.Player.SendInfoMessage("Removed user " + playerName + " from " + regionName);
}
else
args.Player.SendErrorMessage("Region " + regionName + " not found");
}
else
{
args.Player.SendErrorMessage("Player " + playerName + " not found");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region remove <name> <region>", Specifier);
break;
case "allowg":
{
if (args.Parameters.Count > 2)
{
string group = args.Parameters[1];
string regionName = "";
for (int i = 2; i < args.Parameters.Count; i++)
{
if (regionName == "")
{
regionName = args.Parameters[2];
}
else
{
regionName = regionName + " " + args.Parameters[i];
}
}
if (TShock.Groups.GroupExists(group))
{
if (TShock.Regions.AllowGroup(regionName, group))
{
args.Player.SendInfoMessage("Added group " + group + " to " + regionName);
}
else
args.Player.SendErrorMessage("Region " + regionName + " not found");
}
else
{
args.Player.SendErrorMessage("Group " + group + " not found");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region allowg <group> <region>", Specifier);
break;
}
case "removeg":
if (args.Parameters.Count > 2)
{
string group = args.Parameters[1];
string regionName = "";
for (int i = 2; i < args.Parameters.Count; i++)
{
if (regionName == "")
{
regionName = args.Parameters[2];
}
else
{
regionName = regionName + " " + args.Parameters[i];
}
}
if (TShock.Groups.GroupExists(group))
{
if (TShock.Regions.RemoveGroup(regionName, group))
{
args.Player.SendInfoMessage("Removed group " + group + " from " + regionName);
}
else
args.Player.SendErrorMessage("Region " + regionName + " not found");
}
else
{
args.Player.SendErrorMessage("Group " + group + " not found");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region removeg <group> <region>", Specifier);
break;
case "list":
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<string> regionNames = from region in TShock.Regions.Regions
where region.WorldID == Main.worldID.ToString()
select region.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(regionNames),
new PaginationTools.Settings
{
HeaderFormat = "Regions ({0}/{1}):",
FooterFormat = "Type {0}region list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no regions defined."
});
break;
}
case "info":
{
if (args.Parameters.Count == 1 || args.Parameters.Count > 4)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region info <region> [-d] [page]", Specifier);
break;
}
string regionName = args.Parameters[1];
bool displayBoundaries = args.Parameters.Skip(2).Any(
p => p.Equals("-d", StringComparison.InvariantCultureIgnoreCase)
);
Region region = TShock.Regions.GetRegionByName(regionName);
if (region == null)
{
args.Player.SendErrorMessage("Region \"{0}\" does not exist.", regionName);
break;
}
int pageNumberIndex = displayBoundaries ? 3 : 2;
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, pageNumberIndex, args.Player, out pageNumber))
break;
List<string> lines = new List<string>
{
string.Format("X: {0}; Y: {1}; W: {2}; H: {3}, Z: {4}", region.Area.X, region.Area.Y, region.Area.Width, region.Area.Height, region.Z),
string.Concat("Owner: ", region.Owner),
string.Concat("Protected: ", region.DisableBuild.ToString()),
};
if (region.AllowedIDs.Count > 0)
{
IEnumerable<string> sharedUsersSelector = region.AllowedIDs.Select(userId =>
{
UserAccount account = TShock.UserAccounts.GetUserAccountByID(userId);
if (account != null)
return account.Name;
return string.Concat("{ID: ", userId, "}");
});
List<string> extraLines = PaginationTools.BuildLinesFromTerms(sharedUsersSelector.Distinct());
extraLines[0] = "Shared with: " + extraLines[0];
lines.AddRange(extraLines);
}
else
{
lines.Add("Region is not shared with any users.");
}
if (region.AllowedGroups.Count > 0)
{
List<string> extraLines = PaginationTools.BuildLinesFromTerms(region.AllowedGroups.Distinct());
extraLines[0] = "Shared with groups: " + extraLines[0];
lines.AddRange(extraLines);
}
else
{
lines.Add("Region is not shared with any groups.");
}
PaginationTools.SendPage(
args.Player, pageNumber, lines, new PaginationTools.Settings
{
HeaderFormat = string.Format("Information About Region \"{0}\" ({{0}}/{{1}}):", region.Name),
FooterFormat = string.Format("Type {0}region info {1} {{0}} for more information.", Specifier, regionName)
}
);
if (displayBoundaries)
{
Rectangle regionArea = region.Area;
foreach (Point boundaryPoint in Utils.Instance.EnumerateRegionBoundaries(regionArea))
{
// Preferring dotted lines as those should easily be distinguishable from actual wires.
if ((boundaryPoint.X + boundaryPoint.Y & 1) == 0)
{
// Could be improved by sending raw tile data to the client instead but not really
// worth the effort as chances are very low that overwriting the wire for a few
// nanoseconds will cause much trouble.
ITile tile = Main.tile[boundaryPoint.X, boundaryPoint.Y];
bool oldWireState = tile.wire();
tile.wire(true);
try
{
args.Player.SendTileSquare(boundaryPoint.X, boundaryPoint.Y, 1);
}
finally
{
tile.wire(oldWireState);
}
}
}
Timer boundaryHideTimer = null;
boundaryHideTimer = new Timer((state) =>
{
foreach (Point boundaryPoint in Utils.Instance.EnumerateRegionBoundaries(regionArea))
if ((boundaryPoint.X + boundaryPoint.Y & 1) == 0)
args.Player.SendTileSquare(boundaryPoint.X, boundaryPoint.Y, 1);
Debug.Assert(boundaryHideTimer != null);
boundaryHideTimer.Dispose();
},
null, 5000, Timeout.Infinite
);
}
break;
}
case "z":
{
if (args.Parameters.Count == 3)
{
string regionName = args.Parameters[1];
int z = 0;
if (int.TryParse(args.Parameters[2], out z))
{
if (TShock.Regions.SetZ(regionName, z))
args.Player.SendInfoMessage("Region's z is now " + z);
else
args.Player.SendErrorMessage("Could not find specified region");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region z <name> <#>", Specifier);
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region z <name> <#>", Specifier);
break;
}
case "resize":
case "expand":
{
if (args.Parameters.Count == 4)
{
int direction;
switch (args.Parameters[2])
{
case "u":
case "up":
{
direction = 0;
break;
}
case "r":
case "right":
{
direction = 1;
break;
}
case "d":
case "down":
{
direction = 2;
break;
}
case "l":
case "left":
{
direction = 3;
break;
}
default:
{
direction = -1;
break;
}
}
int addAmount;
int.TryParse(args.Parameters[3], out addAmount);
if (TShock.Regions.ResizeRegion(args.Parameters[1], addAmount, direction))
{
args.Player.SendInfoMessage("Region Resized Successfully!");
TShock.Regions.Reload();
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region resize <region> <u/d/l/r> <amount>", Specifier);
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region resize <region> <u/d/l/r> <amount>", Specifier);
break;
}
case "rename":
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region rename <region> <new name>", Specifier);
break;
}
else
{
string oldName = args.Parameters[1];
string newName = args.Parameters[2];
if (oldName == newName)
{
args.Player.SendErrorMessage("Error: both names are the same.");
break;
}
Region oldRegion = TShock.Regions.GetRegionByName(oldName);
if (oldRegion == null)
{
args.Player.SendErrorMessage("Invalid region \"{0}\".", oldName);
break;
}
Region newRegion = TShock.Regions.GetRegionByName(newName);
if (newRegion != null)
{
args.Player.SendErrorMessage("Region \"{0}\" already exists.", newName);
break;
}
if(TShock.Regions.RenameRegion(oldName, newName))
{
args.Player.SendInfoMessage("Region renamed successfully!");
}
else
{
args.Player.SendErrorMessage("Failed to rename the region.");
}
}
break;
}
case "tp":
{
if (!args.Player.HasPermission(Permissions.tp))
{
args.Player.SendErrorMessage("You don't have the necessary permission to do that.");
break;
}
if (args.Parameters.Count <= 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region tp <region>.", Specifier);
break;
}
string regionName = string.Join(" ", args.Parameters.Skip(1));
Region region = TShock.Regions.GetRegionByName(regionName);
if (region == null)
{
args.Player.SendErrorMessage("Region \"{0}\" does not exist.", regionName);
break;
}
args.Player.Teleport(region.Area.Center.X * 16, region.Area.Center.Y * 16);
break;
}
case "help":
default:
{
int pageNumber;
int pageParamIndex = 0;
if (args.Parameters.Count > 1)
pageParamIndex = 1;
if (!PaginationTools.TryParsePageNumber(args.Parameters, pageParamIndex, args.Player, out pageNumber))
return;
List<string> lines = new List<string> {
"set <1/2> - Sets the temporary region points.",
"clear - Clears the temporary region points.",
"define <name> - Defines the region with the given name.",
"delete <name> - Deletes the given region.",
"name [-u][-z][-p] - Shows the name of the region at the given point.",
"rename <region> <new name> - Renames the given region.",
"list - Lists all regions.",
"resize <region> <u/d/l/r> <amount> - Resizes a region.",
"allow <user> <region> - Allows a user to a region.",
"remove <user> <region> - Removes a user from a region.",
"allowg <group> <region> - Allows a user group to a region.",
"removeg <group> <region> - Removes a user group from a region.",
"info <region> [-d] - Displays several information about the given region.",
"protect <name> <true/false> - Sets whether the tiles inside the region are protected or not.",
"z <name> <#> - Sets the z-order of the region.",
};
if (args.Player.HasPermission(Permissions.tp))
lines.Add("tp <region> - Teleports you to the given region's center.");
PaginationTools.SendPage(
args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Available Region Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}region {{0}} for more sub-commands.".SFormat(Specifier)
}
);
break;
}
}
}
#endregion Region Commands
#region World Protection Commands
private static void ToggleAntiBuild(CommandArgs args)
{
TShock.Config.DisableBuild = !TShock.Config.DisableBuild;
TSPlayer.All.SendSuccessMessage(string.Format("Anti-build is now {0}.", (TShock.Config.DisableBuild ? "on" : "off")));
}
private static void ProtectSpawn(CommandArgs args)
{
TShock.Config.SpawnProtection = !TShock.Config.SpawnProtection;
TSPlayer.All.SendSuccessMessage(string.Format("Spawn is now {0}.", (TShock.Config.SpawnProtection ? "protected" : "open")));
}
#endregion World Protection Commands
#region General Commands
private static void Help(CommandArgs args)
{
if (args.Parameters.Count > 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}help <command/page>", Specifier);
return;
}
int pageNumber;
if (args.Parameters.Count == 0 || int.TryParse(args.Parameters[0], out pageNumber))
{
if (!PaginationTools.TryParsePageNumber(args.Parameters, 0, args.Player, out pageNumber))
{
return;
}
IEnumerable<string> cmdNames = from cmd in ChatCommands
where cmd.CanRun(args.Player) && (cmd.Name != "auth" || TShock.SetupToken != 0)
select Specifier + cmd.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(cmdNames),
new PaginationTools.Settings
{
HeaderFormat = "Commands ({0}/{1}):",
FooterFormat = "Type {0}help {{0}} for more.".SFormat(Specifier)
});
}
else
{
string commandName = args.Parameters[0].ToLower();
if (commandName.StartsWith(Specifier))
{
commandName = commandName.Substring(1);
}
Command command = ChatCommands.Find(c => c.Names.Contains(commandName));
if (command == null)
{
args.Player.SendErrorMessage("Invalid command.");
return;
}
if (!command.CanRun(args.Player))
{
args.Player.SendErrorMessage("You do not have access to this command.");
return;
}
args.Player.SendSuccessMessage("{0}{1} help: ", Specifier, command.Name);
if (command.HelpDesc == null)
{
args.Player.SendInfoMessage(command.HelpText);
return;
}
foreach (string line in command.HelpDesc)
{
args.Player.SendInfoMessage(line);
}
}
}
private static void GetVersion(CommandArgs args)
{
args.Player.SendInfoMessage("TShock: {0} ({1}).", TShock.VersionNum, TShock.VersionCodename);
}
private static void ListConnectedPlayers(CommandArgs args)
{
bool invalidUsage = (args.Parameters.Count > 2);
bool displayIdsRequested = false;
int pageNumber = 1;
if (!invalidUsage)
{
foreach (string parameter in args.Parameters)
{
if (parameter.Equals("-i", StringComparison.InvariantCultureIgnoreCase))
{
displayIdsRequested = true;
continue;
}
if (!int.TryParse(parameter, out pageNumber))
{
invalidUsage = true;
break;
}
}
}
if (invalidUsage)
{
args.Player.SendErrorMessage("Invalid usage, proper usage: {0}who [-i] [pagenumber]", Specifier);
return;
}
if (displayIdsRequested && !args.Player.HasPermission(Permissions.seeids))
{
args.Player.SendErrorMessage("You don't have the required permission to list player ids.");
return;
}
args.Player.SendSuccessMessage("Online Players ({0}/{1})", TShock.Utils.GetActivePlayerCount(), TShock.Config.MaxSlots);
var players = new List<string>();
foreach (TSPlayer ply in TShock.Players)
{
if (ply != null && ply.Active)
{
if (displayIdsRequested)
{
players.Add(String.Format("{0} (ID: {1}{2})", ply.Name, ply.Index, ply.Account != null ? ", ID: " + ply.Account.ID : ""));
}
else
{
players.Add(ply.Name);
}
}
}
PaginationTools.SendPage(
args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(players),
new PaginationTools.Settings
{
IncludeHeader = false,
FooterFormat = string.Format("Type {0}who {1}{{0}} for more.", Specifier, displayIdsRequested ? "-i " : string.Empty)
}
);
}
private static void SetupToken(CommandArgs args)
{
if (TShock.SetupToken == 0)
{
if (args.Player.Group.Name == new SuperAdminGroup().Name)
args.Player.SendInfoMessage("The initial setup system is already disabled.");
else
{
args.Player.SendWarningMessage("The initial setup system is disabled. This incident has been logged.");
TShock.Log.Warn("{0} attempted to use the initial setup system even though it's disabled.", args.Player.IP);
return;
}
}
// If the user account is already a superadmin (permanent), disable the system
if (args.Player.IsLoggedIn && args.Player.tempGroup == null)
{
args.Player.SendSuccessMessage("Your new account has been verified, and the {0}setup system has been turned off.", Specifier);
args.Player.SendSuccessMessage("You can always use the {0}user command to manage players.", Specifier);
args.Player.SendSuccessMessage("The setup system will remain disabled as long as a superadmin exists (even if you delete setup.lock).");
args.Player.SendSuccessMessage("Share your server, talk with other admins, and more on our forums -- https://tshock.co/");
args.Player.SendSuccessMessage("Thank you for using TShock for Terraria!");
FileTools.CreateFile(Path.Combine(TShock.SavePath, "setup.lock"));
File.Delete(Path.Combine(TShock.SavePath, "setup-code.txt"));
TShock.SetupToken = 0;
return;
}
if (args.Parameters.Count == 0)
{
args.Player.SendErrorMessage("You must provide a setup code!");
return;
}
int givenCode;
if (!Int32.TryParse(args.Parameters[0], out givenCode) || givenCode != TShock.SetupToken)
{
args.Player.SendErrorMessage("Incorrect setup code. This incident has been logged.");
TShock.Log.Warn(args.Player.IP + " attempted to use an incorrect setup code.");
return;
}
if (args.Player.Group.Name != "superadmin")
args.Player.tempGroup = new SuperAdminGroup();
args.Player.SendInfoMessage("Temporary system access has been given to you, so you can run one command.");
args.Player.SendInfoMessage("Please use the following to create a permanent account for you.");
args.Player.SendInfoMessage("{0}user add <username> <password> owner", Specifier);
args.Player.SendInfoMessage("Creates: <username> with the password <password> as part of the owner group.");
args.Player.SendInfoMessage("Please use {0}login <username> <password> after this process.", Specifier);
args.Player.SendInfoMessage("If you understand, please {0}login <username> <password> now, and then type {0}setup.", Specifier);
return;
}
private static void ThirdPerson(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}me <text>", Specifier);
return;
}
if (args.Player.mute)
args.Player.SendErrorMessage("You are muted.");
else
TSPlayer.All.SendMessage(string.Format("*{0} {1}", args.Player.Name, String.Join(" ", args.Parameters)), 205, 133, 63);
}
private static void PartyChat(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}p <team chat text>", Specifier);
return;
}
int playerTeam = args.Player.Team;
if (args.Player.mute)
args.Player.SendErrorMessage("You are muted.");
else if (playerTeam != 0)
{
string msg = string.Format("<{0}> {1}", args.Player.Name, String.Join(" ", args.Parameters));
foreach (TSPlayer player in TShock.Players)
{
if (player != null && player.Active && player.Team == playerTeam)
player.SendMessage(msg, Main.teamColor[playerTeam].R, Main.teamColor[playerTeam].G, Main.teamColor[playerTeam].B);
}
}
else
args.Player.SendErrorMessage("You are not in a party!");
}
private static void Mute(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}mute <player> [reason]", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else if (players[0].HasPermission(Permissions.mute))
{
args.Player.SendErrorMessage("You cannot mute this player.");
}
else if (players[0].mute)
{
var plr = players[0];
plr.mute = false;
TSPlayer.All.SendInfoMessage("{0} has been unmuted by {1}.", plr.Name, args.Player.Name);
}
else
{
string reason = "No reason specified.";
if (args.Parameters.Count > 1)
reason = String.Join(" ", args.Parameters.ToArray(), 1, args.Parameters.Count - 1);
var plr = players[0];
plr.mute = true;
TSPlayer.All.SendInfoMessage("{0} has been muted by {1} for {2}.", plr.Name, args.Player.Name, reason);
}
}
private static void Motd(CommandArgs args)
{
args.Player.SendFileTextAsMessage(FileTools.MotdPath);
}
private static void Rules(CommandArgs args)
{
args.Player.SendFileTextAsMessage(FileTools.RulesPath);
}
private static void Whisper(CommandArgs args)
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}whisper <player> <text>", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else if (args.Player.mute)
{
args.Player.SendErrorMessage("You are muted.");
}
else
{
var plr = players[0];
var msg = string.Join(" ", args.Parameters.ToArray(), 1, args.Parameters.Count - 1);
plr.SendMessage(String.Format("<From {0}> {1}", args.Player.Name, msg), Color.MediumPurple);
args.Player.SendMessage(String.Format("<To {0}> {1}", plr.Name, msg), Color.MediumPurple);
plr.LastWhisper = args.Player;
args.Player.LastWhisper = plr;
}
}
private static void Reply(CommandArgs args)
{
if (args.Player.mute)
{
args.Player.SendErrorMessage("You are muted.");
}
else if (args.Player.LastWhisper != null)
{
var msg = string.Join(" ", args.Parameters);
args.Player.LastWhisper.SendMessage(String.Format("<From {0}> {1}", args.Player.Name, msg), Color.MediumPurple);
args.Player.SendMessage(String.Format("<To {0}> {1}", args.Player.LastWhisper.Name, msg), Color.MediumPurple);
}
else
{
args.Player.SendErrorMessage("You haven't previously received any whispers. Please use {0}whisper to whisper to other people.", Specifier);
}
}
private static void Annoy(CommandArgs args)
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}annoy <player> <seconds to annoy>", Specifier);
return;
}
int annoy = 5;
int.TryParse(args.Parameters[1], out annoy);
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var ply = players[0];
args.Player.SendSuccessMessage("Annoying " + ply.Name + " for " + annoy + " seconds.");
(new Thread(ply.Whoopie)).Start(annoy);
}
}
private static void Confuse(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}confuse <player>", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var ply = players[0];
ply.Confused = !ply.Confused;
args.Player.SendSuccessMessage("{0} is {1} confused.", ply.Name, ply.Confused ? "now" : "no longer");
}
}
private static void Rocket(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}rocket <player>", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var ply = players[0];
if (ply.IsLoggedIn && Main.ServerSideCharacter)
{
ply.TPlayer.velocity.Y = -50;
TSPlayer.All.SendData(PacketTypes.PlayerUpdate, "", ply.Index);
args.Player.SendSuccessMessage("Rocketed {0}.", ply.Name);
}
else
{
args.Player.SendErrorMessage("Failed to rocket player: Not logged in or not SSC mode.");
}
}
}
private static void FireWork(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}firework <player> [red|green|blue|yellow]", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
int type = 167;
if (args.Parameters.Count > 1)
{
if (args.Parameters[1].ToLower() == "green")
type = 168;
else if (args.Parameters[1].ToLower() == "blue")
type = 169;
else if (args.Parameters[1].ToLower() == "yellow")
type = 170;
}
var ply = players[0];
int p = Projectile.NewProjectile(ply.TPlayer.position.X, ply.TPlayer.position.Y - 64f, 0f, -8f, type, 0, (float)0);
Main.projectile[p].Kill();
args.Player.SendSuccessMessage("Launched Firework on {0}.", ply.Name);
}
}
private static void Aliases(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}aliases <command or alias>", Specifier);
return;
}
string givenCommandName = string.Join(" ", args.Parameters);
if (string.IsNullOrWhiteSpace(givenCommandName))
{
args.Player.SendErrorMessage("Please enter a proper command name or alias.");
return;
}
string commandName;
if (givenCommandName[0] == Specifier[0])
commandName = givenCommandName.Substring(1);
else
commandName = givenCommandName;
bool didMatch = false;
foreach (Command matchingCommand in ChatCommands.Where(cmd => cmd.Names.IndexOf(commandName) != -1))
{
if (matchingCommand.Names.Count > 1)
args.Player.SendInfoMessage(
"Aliases of {0}{1}: {0}{2}", Specifier, matchingCommand.Name, string.Join(", {0}".SFormat(Specifier), matchingCommand.Names.Skip(1)));
else
args.Player.SendInfoMessage("{0}{1} defines no aliases.", Specifier, matchingCommand.Name);
didMatch = true;
}
if (!didMatch)
args.Player.SendErrorMessage("No command or command alias matching \"{0}\" found.", givenCommandName);
}
private static void CreateDumps(CommandArgs args)
{
TShock.Utils.DumpPermissionMatrix("PermissionMatrix.txt");
TShock.Utils.Dump(false);
args.Player.SendSuccessMessage("Your reference dumps have been created in the server folder.");
return;
}
#endregion General Commands
#region Cheat Commands
private static void Clear(CommandArgs args)
{
if (args.Parameters.Count != 1 && args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}clear <item/npc/projectile> [radius]", Specifier);
return;
}
int radius = 50;
if (args.Parameters.Count == 2)
{
if (!int.TryParse(args.Parameters[1], out radius) || radius <= 0)
{
args.Player.SendErrorMessage("Invalid radius.");
return;
}
}
switch (args.Parameters[0].ToLower())
{
case "item":
case "items":
{
int cleared = 0;
for (int i = 0; i < Main.maxItems; i++)
{
float dX = Main.item[i].position.X - args.Player.X;
float dY = Main.item[i].position.Y - args.Player.Y;
if (Main.item[i].active && dX * dX + dY * dY <= radius * radius * 256f)
{
Main.item[i].active = false;
TSPlayer.All.SendData(PacketTypes.ItemDrop, "", i);
cleared++;
}
}
args.Player.SendSuccessMessage("Deleted {0} items within a radius of {1}.", cleared, radius);
}
break;
case "npc":
case "npcs":
{
int cleared = 0;
for (int i = 0; i < Main.maxNPCs; i++)
{
float dX = Main.npc[i].position.X - args.Player.X;
float dY = Main.npc[i].position.Y - args.Player.Y;
if (Main.npc[i].active && dX * dX + dY * dY <= radius * radius * 256f)
{
Main.npc[i].active = false;
Main.npc[i].type = 0;
TSPlayer.All.SendData(PacketTypes.NpcUpdate, "", i);
cleared++;
}
}
args.Player.SendSuccessMessage("Deleted {0} NPCs within a radius of {1}.", cleared, radius);
}
break;
case "proj":
case "projectile":
case "projectiles":
{
int cleared = 0;
for (int i = 0; i < Main.maxProjectiles; i++)
{
float dX = Main.projectile[i].position.X - args.Player.X;
float dY = Main.projectile[i].position.Y - args.Player.Y;
if (Main.projectile[i].active && dX * dX + dY * dY <= radius * radius * 256f)
{
Main.projectile[i].active = false;
Main.projectile[i].type = 0;
TSPlayer.All.SendData(PacketTypes.ProjectileNew, "", i);
cleared++;
}
}
args.Player.SendSuccessMessage("Deleted {0} projectiles within a radius of {1}.", cleared, radius);
}
break;
default:
args.Player.SendErrorMessage("Invalid clear option!");
break;
}
}
private static void Kill(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}kill <player>", Specifier);
return;
}
string plStr = String.Join(" ", args.Parameters);
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
var plr = players[0];
plr.KillPlayer();
args.Player.SendSuccessMessage(string.Format("You just killed {0}!", plr.Name));
plr.SendErrorMessage("{0} just killed you!", args.Player.Name);
}
}
private static void Butcher(CommandArgs args)
{
if (args.Parameters.Count > 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}butcher [mob type]", Specifier);
return;
}
int npcId = 0;
if (args.Parameters.Count == 1)
{
var npcs = TShock.Utils.GetNPCByIdOrName(args.Parameters[0]);
if (npcs.Count == 0)
{
args.Player.SendErrorMessage("Invalid mob type!");
return;
}
else if (npcs.Count > 1)
{
args.Player.SendMultipleMatchError(npcs.Select(n => $"{n.FullName}({n.type})"));
return;
}
else
{
npcId = npcs[0].netID;
}
}
int kills = 0;
for (int i = 0; i < Main.npc.Length; i++)
{
if (Main.npc[i].active && ((npcId == 0 && !Main.npc[i].townNPC && Main.npc[i].netID != NPCID.TargetDummy) || Main.npc[i].netID == npcId))
{
TSPlayer.Server.StrikeNPC(i, (int)(Main.npc[i].life + (Main.npc[i].defense * 0.6)), 0, 0);
kills++;
}
}
TSPlayer.All.SendInfoMessage("{0} butchered {1} NPCs.", args.Player.Name, kills);
}
private static void Item(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}item <item name/id> [item amount] [prefix id/name]", Specifier);
return;
}
int amountParamIndex = -1;
int itemAmount = 0;
for (int i = 1; i < args.Parameters.Count; i++)
{
if (int.TryParse(args.Parameters[i], out itemAmount))
{
amountParamIndex = i;
break;
}
}
string itemNameOrId;
if (amountParamIndex == -1)
itemNameOrId = string.Join(" ", args.Parameters);
else
itemNameOrId = string.Join(" ", args.Parameters.Take(amountParamIndex));
Item item;
List<Item> matchedItems = TShock.Utils.GetItemByIdOrName(itemNameOrId);
if (matchedItems.Count == 0)
{
args.Player.SendErrorMessage("Invalid item type!");
return;
}
else if (matchedItems.Count > 1)
{
args.Player.SendMultipleMatchError(matchedItems.Select(i => $"{i.Name}({i.netID})"));
return;
}
else
{
item = matchedItems[0];
}
if (item.type < 1 && item.type >= Main.maxItemTypes)
{
args.Player.SendErrorMessage("The item type {0} is invalid.", itemNameOrId);
return;
}
int prefixId = 0;
if (amountParamIndex != -1 && args.Parameters.Count > amountParamIndex + 1)
{
string prefixidOrName = args.Parameters[amountParamIndex + 1];
var prefixIds = TShock.Utils.GetPrefixByIdOrName(prefixidOrName);
if (item.accessory && prefixIds.Contains(PrefixID.Quick))
{
prefixIds.Remove(PrefixID.Quick);
prefixIds.Remove(PrefixID.Quick2);
prefixIds.Add(PrefixID.Quick2);
}
else if (!item.accessory && prefixIds.Contains(PrefixID.Quick))
prefixIds.Remove(PrefixID.Quick2);
if (prefixIds.Count > 1)
{
args.Player.SendMultipleMatchError(prefixIds.Select(p => p.ToString()));
return;
}
else if (prefixIds.Count == 0)
{
args.Player.SendErrorMessage("No prefix matched \"{0}\".", prefixidOrName);
return;
}
else
{
prefixId = prefixIds[0];
}
}
if (args.Player.InventorySlotAvailable || (item.type > 70 && item.type < 75) || item.ammo > 0 || item.type == 58 || item.type == 184)
{
if (itemAmount == 0 || itemAmount > item.maxStack)
itemAmount = item.maxStack;
if (args.Player.GiveItemCheck(item.type, EnglishLanguage.GetItemNameById(item.type), itemAmount, prefixId))
{
item.prefix = (byte)prefixId;
args.Player.SendSuccessMessage("Gave {0} {1}(s).", itemAmount, item.AffixName());
}
else
{
args.Player.SendErrorMessage("You cannot spawn banned items.");
}
}
else
{
args.Player.SendErrorMessage("Your inventory seems full.");
}
}
private static void RenameNPC(CommandArgs args)
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}renameNPC <guide, nurse, etc.> <newname>", Specifier);
return;
}
int npcId = 0;
if (args.Parameters.Count == 2)
{
List<NPC> npcs = TShock.Utils.GetNPCByIdOrName(args.Parameters[0]);
if (npcs.Count == 0)
{
args.Player.SendErrorMessage("Invalid mob type!");
return;
}
else if (npcs.Count > 1)
{
args.Player.SendMultipleMatchError(npcs.Select(n => $"{n.FullName}({n.type})"));
return;
}
else if (args.Parameters[1].Length > 200)
{
args.Player.SendErrorMessage("New name is too large!");
return;
}
else
{
npcId = npcs[0].netID;
}
}
int done = 0;
for (int i = 0; i < Main.npc.Length; i++)
{
if (Main.npc[i].active && ((npcId == 0 && !Main.npc[i].townNPC) || (Main.npc[i].netID == npcId && Main.npc[i].townNPC)))
{
Main.npc[i].GivenName = args.Parameters[1];
NetMessage.SendData(56, -1, -1, NetworkText.FromLiteral(args.Parameters[1]), i, 0f, 0f, 0f, 0);
done++;
}
}
if (done > 0)
{
TSPlayer.All.SendInfoMessage("{0} renamed the {1}.", args.Player.Name, args.Parameters[0]);
}
else
{
args.Player.SendErrorMessage("Could not rename {0}!", args.Parameters[0]);
}
}
private static void Give(CommandArgs args)
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage(
"Invalid syntax! Proper syntax: {0}give <item type/id> <player> [item amount] [prefix id/name]", Specifier);
return;
}
if (args.Parameters[0].Length == 0)
{
args.Player.SendErrorMessage("Missing item name/id.");
return;
}
if (args.Parameters[1].Length == 0)
{
args.Player.SendErrorMessage("Missing player name.");
return;
}
int itemAmount = 0;
int prefix = 0;
var items = TShock.Utils.GetItemByIdOrName(args.Parameters[0]);
args.Parameters.RemoveAt(0);
string plStr = args.Parameters[0];
args.Parameters.RemoveAt(0);
if (args.Parameters.Count == 1)
int.TryParse(args.Parameters[0], out itemAmount);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item type!");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
var item = items[0];
if (args.Parameters.Count == 2)
{
int.TryParse(args.Parameters[0], out itemAmount);
var prefixIds = TShock.Utils.GetPrefixByIdOrName(args.Parameters[1]);
if (item.accessory && prefixIds.Contains(PrefixID.Quick))
{
prefixIds.Remove(PrefixID.Quick);
prefixIds.Remove(PrefixID.Quick2);
prefixIds.Add(PrefixID.Quick2);
}
else if (!item.accessory && prefixIds.Contains(PrefixID.Quick))
prefixIds.Remove(PrefixID.Quick2);
if (prefixIds.Count == 1)
prefix = prefixIds[0];
}
if (item.type >= 1 && item.type < Main.maxItemTypes)
{
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
var plr = players[0];
if (plr.InventorySlotAvailable || (item.type > 70 && item.type < 75) || item.ammo > 0 || item.type == 58 || item.type == 184)
{
if (itemAmount == 0 || itemAmount > item.maxStack)
itemAmount = item.maxStack;
if (plr.GiveItemCheck(item.type, EnglishLanguage.GetItemNameById(item.type), itemAmount, prefix))
{
args.Player.SendSuccessMessage(string.Format("Gave {0} {1} {2}(s).", plr.Name, itemAmount, item.Name));
plr.SendSuccessMessage(string.Format("{0} gave you {1} {2}(s).", args.Player.Name, itemAmount, item.Name));
}
else
{
args.Player.SendErrorMessage("You cannot spawn banned items.");
}
}
else
{
args.Player.SendErrorMessage("Player does not have free slots!");
}
}
}
else
{
args.Player.SendErrorMessage("Invalid item type!");
}
}
}
private static void Heal(CommandArgs args)
{
TSPlayer playerToHeal;
if (args.Parameters.Count > 0)
{
string plStr = String.Join(" ", args.Parameters);
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
return;
}
else
{
playerToHeal = players[0];
}
}
else if (!args.Player.RealPlayer)
{
args.Player.SendErrorMessage("You can't heal yourself!");
return;
}
else
{
playerToHeal = args.Player;
}
playerToHeal.Heal();
if (playerToHeal == args.Player)
{
args.Player.SendSuccessMessage("You just got healed!");
}
else
{
args.Player.SendSuccessMessage(string.Format("You just healed {0}", playerToHeal.Name));
playerToHeal.SendSuccessMessage(string.Format("{0} just healed you!", args.Player.Name));
}
}
private static void Buff(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}buff <buff id/name> [time(seconds)]", Specifier);
return;
}
int id = 0;
int time = 60;
if (!int.TryParse(args.Parameters[0], out id))
{
var found = TShock.Utils.GetBuffByName(args.Parameters[0]);
if (found.Count == 0)
{
args.Player.SendErrorMessage("Invalid buff name!");
return;
}
else if (found.Count > 1)
{
args.Player.SendMultipleMatchError(found.Select(f => Lang.GetBuffName(f)));
return;
}
id = found[0];
}
if (args.Parameters.Count == 2)
int.TryParse(args.Parameters[1], out time);
if (id > 0 && id < Main.maxBuffTypes)
{
if (time < 0 || time > short.MaxValue)
time = 60;
args.Player.SetBuff(id, time * 60);
args.Player.SendSuccessMessage(string.Format("You have buffed yourself with {0}({1}) for {2} seconds!",
TShock.Utils.GetBuffName(id), TShock.Utils.GetBuffDescription(id), (time)));
}
else
args.Player.SendErrorMessage("Invalid buff ID!");
}
private static void GBuff(CommandArgs args)
{
if (args.Parameters.Count < 2 || args.Parameters.Count > 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}gbuff <player> <buff id/name> [time(seconds)]", Specifier);
return;
}
int id = 0;
int time = 60;
var foundplr = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (foundplr.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
else if (foundplr.Count > 1)
{
args.Player.SendMultipleMatchError(foundplr.Select(p => p.Name));
return;
}
else
{
if (!int.TryParse(args.Parameters[1], out id))
{
var found = TShock.Utils.GetBuffByName(args.Parameters[1]);
if (found.Count == 0)
{
args.Player.SendErrorMessage("Invalid buff name!");
return;
}
else if (found.Count > 1)
{
args.Player.SendMultipleMatchError(found.Select(b => Lang.GetBuffName(b)));
return;
}
id = found[0];
}
if (args.Parameters.Count == 3)
int.TryParse(args.Parameters[2], out time);
if (id > 0 && id < Main.maxBuffTypes)
{
if (time < 0 || time > short.MaxValue)
time = 60;
foundplr[0].SetBuff(id, time * 60);
args.Player.SendSuccessMessage(string.Format("You have buffed {0} with {1}({2}) for {3} seconds!",
foundplr[0].Name, TShock.Utils.GetBuffName(id),
TShock.Utils.GetBuffDescription(id), (time)));
foundplr[0].SendSuccessMessage(string.Format("{0} has buffed you with {1}({2}) for {3} seconds!",
args.Player.Name, TShock.Utils.GetBuffName(id),
TShock.Utils.GetBuffDescription(id), (time)));
}
else
args.Player.SendErrorMessage("Invalid buff ID!");
}
}
private static void Grow(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}grow <tree/epictree/mushroom/cactus/herb>", Specifier);
return;
}
var name = "Fail";
var x = args.Player.TileX;
var y = args.Player.TileY + 3;
if (!TShock.Regions.CanBuild(x, y, args.Player))
{
args.Player.SendErrorMessage("You're not allowed to change tiles here!");
return;
}
switch (args.Parameters[0].ToLower())
{
case "tree":
for (int i = x - 1; i < x + 2; i++)
{
Main.tile[i, y].active(true);
Main.tile[i, y].type = 2;
Main.tile[i, y].wall = 0;
}
Main.tile[x, y - 1].wall = 0;
WorldGen.GrowTree(x, y);
name = "Tree";
break;
case "epictree":
for (int i = x - 1; i < x + 2; i++)
{
Main.tile[i, y].active(true);
Main.tile[i, y].type = 2;
Main.tile[i, y].wall = 0;
}
Main.tile[x, y - 1].wall = 0;
Main.tile[x, y - 1].liquid = 0;
Main.tile[x, y - 1].active(true);
WorldGen.GrowEpicTree(x, y);
name = "Epic Tree";
break;
case "mushroom":
for (int i = x - 1; i < x + 2; i++)
{
Main.tile[i, y].active(true);
Main.tile[i, y].type = 70;
Main.tile[i, y].wall = 0;
}
Main.tile[x, y - 1].wall = 0;
WorldGen.GrowShroom(x, y);
name = "Mushroom";
break;
case "cactus":
Main.tile[x, y].type = 53;
WorldGen.GrowCactus(x, y);
name = "Cactus";
break;
case "herb":
Main.tile[x, y].active(true);
Main.tile[x, y].frameX = 36;
Main.tile[x, y].type = 83;
WorldGen.GrowAlch(x, y);
name = "Herb";
break;
default:
args.Player.SendErrorMessage("Unknown plant!");
return;
}
args.Player.SendTileSquare(x, y);
args.Player.SendSuccessMessage("Tried to grow a " + name + ".");
}
private static void ToggleGodMode(CommandArgs args)
{
TSPlayer playerToGod;
if (args.Parameters.Count > 0)
{
if (!args.Player.HasPermission(Permissions.godmodeother))
{
args.Player.SendErrorMessage("You do not have permission to god mode another player!");
return;
}
string plStr = String.Join(" ", args.Parameters);
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
return;
}
else
{
playerToGod = players[0];
}
}
else if (!args.Player.RealPlayer)
{
args.Player.SendErrorMessage("You can't god mode a non player!");
return;
}
else
{
playerToGod = args.Player;
}
playerToGod.GodMode = !playerToGod.GodMode;
if (playerToGod == args.Player)
{
args.Player.SendSuccessMessage(string.Format("You are {0} in god mode.", args.Player.GodMode ? "now" : "no longer"));
}
else
{
args.Player.SendSuccessMessage(string.Format("{0} is {1} in god mode.", playerToGod.Name, playerToGod.GodMode ? "now" : "no longer"));
playerToGod.SendSuccessMessage(string.Format("You are {0} in god mode.", playerToGod.GodMode ? "now" : "no longer"));
}
}
#endregion Cheat Comamnds
}
}
| Java |
package com.sk89q.craftbook.cart;
import java.util.ArrayList;
import java.util.Arrays;
import org.bukkit.block.Chest;
import org.bukkit.block.Sign;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.StorageMinecart;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import com.sk89q.craftbook.util.RailUtil;
import com.sk89q.craftbook.util.RedstoneUtil.Power;
import com.sk89q.craftbook.util.RegexUtil;
public class CartDeposit extends CartMechanism {
@Override
public void impact(Minecart cart, CartMechanismBlocks blocks, boolean minor) {
// validate
if (cart == null) return;
// care?
if (minor) return;
if (!(cart instanceof StorageMinecart)) return;
Inventory cartinventory = ((StorageMinecart) cart).getInventory();
// enabled?
if (Power.OFF == isActive(blocks.rail, blocks.base, blocks.sign)) return;
// collect/deposit set?
if (blocks.sign == null) return;
if (!blocks.matches("collect") && !blocks.matches("deposit")) return;
boolean collecting = blocks.matches("collect");
// search for containers
ArrayList<Chest> containers = RailUtil.getNearbyChests(blocks.base);
// are there any containers?
if (containers.isEmpty()) return;
// go
ArrayList<ItemStack> leftovers = new ArrayList<ItemStack>();
int itemID = -1;
byte itemData = -1;
try {
String[] splitLine = RegexUtil.COLON_PATTERN.split(((Sign) blocks.sign.getState()).getLine(2));
itemID = Integer.parseInt(splitLine[0]);
itemData = Byte.parseByte(splitLine[1]);
} catch (Exception ignored) {
}
if (collecting) {
// collecting
ArrayList<ItemStack> transferItems = new ArrayList<ItemStack>();
if (!((Sign) blocks.sign.getState()).getLine(2).isEmpty()) {
for (ItemStack item : cartinventory.getContents()) {
if (item == null) {
continue;
}
if (itemID < 0 || itemID == item.getTypeId()) {
if (itemData < 0 || itemData == item.getDurability()) {
transferItems.add(new ItemStack(item.getTypeId(), item.getAmount(), item.getDurability()));
cartinventory.remove(item);
}
}
}
} else {
transferItems.addAll(Arrays.asList(cartinventory.getContents()));
cartinventory.clear();
}
while (transferItems.remove(null)) {
}
// is cart non-empty?
if (transferItems.isEmpty()) return;
// System.out.println("collecting " + transferItems.size() + " item stacks");
// for (ItemStack stack: transferItems) System.out.println("collecting " + stack.getAmount() + " items of
// type " + stack.getType().toString());
for (Chest container : containers) {
if (transferItems.isEmpty()) {
break;
}
Inventory containerinventory = container.getInventory();
leftovers.addAll(containerinventory.addItem(transferItems.toArray(new ItemStack[transferItems.size()
])).values());
transferItems.clear();
transferItems.addAll(leftovers);
leftovers.clear();
container.update();
}
// System.out.println("collected items. " + transferItems.size() + " stacks left over.");
leftovers.addAll(cartinventory.addItem(transferItems.toArray(new ItemStack[transferItems.size()])).values
());
transferItems.clear();
transferItems.addAll(leftovers);
leftovers.clear();
// System.out.println("collection done. " + transferItems.size() + " stacks wouldn't fit back.");
} else {
// depositing
ArrayList<ItemStack> transferitems = new ArrayList<ItemStack>();
for (Chest container : containers) {
Inventory containerinventory = container.getInventory();
if (!((Sign) blocks.sign.getState()).getLine(2).isEmpty()) {
for (ItemStack item : containerinventory.getContents()) {
if (item == null) {
continue;
}
if (itemID < 0 || itemID == item.getTypeId())
if (itemData < 0 || itemData == item.getDurability()) {
transferitems.add(new ItemStack(item.getTypeId(), item.getAmount(),
item.getDurability()));
containerinventory.remove(item);
}
}
} else {
transferitems.addAll(Arrays.asList(containerinventory.getContents()));
containerinventory.clear();
}
container.update();
}
while (transferitems.remove(null)) {
}
// are chests empty?
if (transferitems.isEmpty()) return;
// System.out.println("depositing " + transferitems.size() + " stacks");
// for (ItemStack stack: transferitems) System.out.println("depositing " + stack.getAmount() + " items of
// type " + stack.getType().toString());
leftovers.addAll(cartinventory.addItem(transferitems.toArray(new ItemStack[transferitems.size()])).values
());
transferitems.clear();
transferitems.addAll(leftovers);
leftovers.clear();
// System.out.println("deposited, " + transferitems.size() + " items left over.");
for (Chest container : containers) {
if (transferitems.isEmpty()) {
break;
}
Inventory containerinventory = container.getInventory();
leftovers.addAll(containerinventory.addItem(transferitems.toArray(new ItemStack[transferitems.size()
])).values());
transferitems.clear();
transferitems.addAll(leftovers);
leftovers.clear();
}
// System.out.println("deposit done. " + transferitems.size() + " items wouldn't fit back.");
}
}
@Override
public String getName() {
return "Deposit";
}
@Override
public String[] getApplicableSigns() {
return new String[] {"Collect", "Deposit"};
}
} | Java |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Lang strings for course_overview block
*
* @package block_course_overview
* @copyright 2012 Adam Olley <adam.olley@netspot.com.au>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['activityoverview'] = 'You have {$a}s that need attention';
$string['alwaysshowall'] = 'Always show all';
$string['collapseall'] = 'Collapse all course lists';
$string['configotherexpanded'] = 'If enabled, other courses will be expanded by default unless overriden by user preferences.';
$string['configpreservestates'] = 'If enabled, the collapsed/expanded states set by the user are stored and used on each load.';
$string['course_overview:addinstance'] = 'Add a new course overview block';
$string['course_overview:myaddinstance'] = 'Add a new course overview block to My home';
$string['defaultmaxcourses'] = 'Default maximum courses';
$string['defaultmaxcoursesdesc'] = 'Maximum courses which should be displayed on course overview block, 0 will show all courses';
$string['expandall'] = 'Expand all course lists';
$string['forcedefaultmaxcourses'] = 'Force maximum courses';
$string['forcedefaultmaxcoursesdesc'] = 'If set then user will not be able to change his/her personal setting';
$string['hiddencoursecount'] = 'You have {$a} hidden course';
$string['hiddencoursecountplural'] = 'You have {$a} hidden courses';
$string['hiddencoursecountwithshowall'] = 'You have {$a->coursecount} hidden course ({$a->showalllink})';
$string['hiddencoursecountwithshowallplural'] = 'You have {$a->coursecount} hidden courses ({$a->showalllink})';
$string['message'] = 'message';
$string['messages'] = 'messages';
$string['movecourse'] = 'Move course: {$a}';
$string['movecoursehere'] = 'Move course here';
$string['movetofirst'] = 'Move {$a} course to top';
$string['moveafterhere'] = 'Move {$a->movingcoursename} course after {$a->currentcoursename}';
$string['movingcourse'] = 'You are moving: {$a->fullname} ({$a->cancellink})';
$string['numtodisplay'] = 'Number of courses to display: ';
$string['otherexpanded'] = 'Other courses expanded';
$string['pluginname'] = 'Assigned Courses';
$string['preservestates'] = 'Preserve expanded states';
$string['shortnameprefix'] = 'Includes {$a}';
$string['shortnamesufixsingular'] = ' (and {$a} other)';
$string['shortnamesufixprural'] = ' (and {$a} others)';
$string['showchildren'] = 'Show children';
$string['showchildrendesc'] = 'Should child courses be listed underneath the main course title?';
$string['showwelcomearea'] = 'Show welcome area';
$string['showwelcomeareadesc'] = 'Show the welcome area above the course list?';
$string['view_edit_profile'] = '(View and edit your profile.)';
$string['welcome'] = 'Welcome {$a}';
$string['youhavemessages'] = 'You have {$a} unread ';
$string['youhavenomessages'] = 'You have no unread ';
| Java |
//
// CHNOrderedCollection.h
//
// Auther:
// ned rihine <ned.rihine@gmail.com>
//
// Copyright (c) 2012 rihine All rights reserved.
//
// 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/>.
//
#ifndef coreHezelnut_classes_CHNOrderedCollection_h
#define coreHezelnut_classes_CHNOrderedCollection_h
#include "coreHezelnut/classes/CHNSequenceableCollection.h"
CHN_EXTERN_C_BEGIN
CHN_EXTERN_C_END
#endif /* coreHezelnut_classes_CHNOrderedCollection_h */
// Local Variables:
// coding: utf-8
// End:
| Java |
<?php
session_start();
include("../connect.php");
include("../function.php");
//session_start();
if($_REQUEST['cat_id'])
{
$data="";
$count=0;
$select_list_data="select * from users_data where int_fid in(".$_REQUEST['cat_id'].") and int_del_status='0'";
$result_list_data=mysql_query($select_list_data) or die(mysql_error());
$data.="<br>";
$data.="<table style='width: 270px;' id='alternatecolor' class='altrowstable1' >";
while($fetch_list_data=mysql_fetch_array($result_list_data))
{ $count++;
$imgsrc="../".$fetch_list_data['txt_real_path'];
$data.="<tr >";
$data.="<td style='padding-left:5px;'>";
$data.="<div style='width:240px;overflow:hidden;'>".$fetch_list_data['txt_file_name']."</div>";
$data.="</td>";
$data.="<td >";
$data.="<img src='images/play-icon.png' style='cursor:pointer;' title='Play Item' onclick='go(\"$imgsrc\");'>";
$data.="</td>";
$data.="</tr>";
//$main_data="<a href='javascript:load_data(\"".$fetch_list_data['txt_file_name']."\");'>".$fetch_list_data['txt_file_name']."</a>";
//$data=$data.$main_data;
//$data.="</br></br>";
}
$data.="</table>";
echo $data;
}
?> | Java |
////////////////////////////////////////////////////////
//
// GEM - Graphics Environment for Multimedia
//
// Implementation file
//
// Copyright (c) 2002-2011 IOhannes m zmölnig. forum::für::umläute. IEM. zmoelnig@iem.at
// zmoelnig@iem.kug.ac.at
// For information on usage and redistribution, and for a DISCLAIMER
// * OF ALL WARRANTIES, see the file, "GEM.LICENSE.TERMS"
//
// this file has been generated...
////////////////////////////////////////////////////////
#include "GEMglTexCoord3s.h"
CPPEXTERN_NEW_WITH_THREE_ARGS ( GEMglTexCoord3s , t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT);
/////////////////////////////////////////////////////////
//
// GEMglViewport
//
/////////////////////////////////////////////////////////
// Constructor
//
GEMglTexCoord3s :: GEMglTexCoord3s (t_floatarg arg0=0, t_floatarg arg1=0, t_floatarg arg2=0) :
s(static_cast<GLshort>(arg0)),
t(static_cast<GLshort>(arg1)),
r(static_cast<GLshort>(arg2))
{
m_inlet[0] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("s"));
m_inlet[1] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("t"));
m_inlet[2] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("r"));
}
/////////////////////////////////////////////////////////
// Destructor
//
GEMglTexCoord3s :: ~GEMglTexCoord3s () {
inlet_free(m_inlet[0]);
inlet_free(m_inlet[1]);
inlet_free(m_inlet[2]);
}
/////////////////////////////////////////////////////////
// Render
//
void GEMglTexCoord3s :: render(GemState *state) {
glTexCoord3s (s, t, r);
}
/////////////////////////////////////////////////////////
// Variables
//
void GEMglTexCoord3s :: sMess (t_float arg1) { // FUN
s = static_cast<GLshort>(arg1);
setModified();
}
void GEMglTexCoord3s :: tMess (t_float arg1) { // FUN
t = static_cast<GLshort>(arg1);
setModified();
}
void GEMglTexCoord3s :: rMess (t_float arg1) { // FUN
r = static_cast<GLshort>(arg1);
setModified();
}
/////////////////////////////////////////////////////////
// static member functions
//
void GEMglTexCoord3s :: obj_setupCallback(t_class *classPtr) {
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexCoord3s::sMessCallback), gensym("s"), A_DEFFLOAT, A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexCoord3s::tMessCallback), gensym("t"), A_DEFFLOAT, A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexCoord3s::rMessCallback), gensym("r"), A_DEFFLOAT, A_NULL);
};
void GEMglTexCoord3s :: sMessCallback (void* data, t_floatarg arg0){
GetMyClass(data)->sMess ( static_cast<t_float>(arg0));
}
void GEMglTexCoord3s :: tMessCallback (void* data, t_floatarg arg0){
GetMyClass(data)->tMess ( static_cast<t_float>(arg0));
}
void GEMglTexCoord3s :: rMessCallback (void* data, t_floatarg arg0){
GetMyClass(data)->rMess ( static_cast<t_float>(arg0));
}
| Java |
/*
* This file is part of CRISIS, an economics simulator.
*
* Copyright (C) 2015 Victor Spirin
*
* CRISIS 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.
*
* CRISIS 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 CRISIS. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.crisis_economics.abm.markets.nonclearing;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import eu.crisis_economics.abm.markets.Party;
import eu.crisis_economics.abm.markets.nonclearing.DefaultFilters.Filter;
/**
* Represents relationships between banks in the interbank market
*
* @author Victor Spirin
*/
public class InterbankNetwork {
private final Map<Party, Set<Party>> adj = new HashMap<Party, Set<Party>>();
/**
* Adds a new node to the graph. If the node already exists, this
* function is a no-op.
*
* @param node The node to add.
* @return Whether or not the node was added.
*/
private boolean addNode(Party node) {
/* If the node already exists, don't do anything. */
if (adj.containsKey(node))
return false;
/* Otherwise, add the node with an empty set of outgoing edges. */
adj.put(node, new HashSet<Party>());
return true;
}
// protected
/**
* Generates a filter from the network. This allows the network class to be used
* with a Limit Order Book.
*
* @param a Bank, for which we want to generate a filter
* @return Returns a Limit Order Book filter for the given bank. If the bank is not in the network, returns an empty filter.
*/
protected Filter generateFilter(Party party) {
if (!adj.containsKey(party))
return DefaultFilters.only(party);
return DefaultFilters.only((Party[]) adj.get(party).toArray());
}
// public interface
/**
* Adds a bilateral relationship between banks 'a' and 'b'.
* If the banks are not already in the network, also adds them to the network.
*
* @param a Bank a
* @param b Bank b
*/
public void addRelationship(Party a, Party b) {
/* Confirm both endpoints exist. */
if (!adj.containsKey(a))
addNode(a);
if (!adj.containsKey(b))
addNode(b);
/* Add the edge in both directions. */
adj.get(a).add(b);
adj.get(b).add(a);
}
/**
* Removes a bilateral relationship between banks 'a' and 'b'.
* If the banks are not already in the network, throws a NoSuchElementException
*
* @param a Bank a
* @param b Bank b
*/
public void removeRelationship(Party a, Party b) {
/* Confirm both endpoints exist. */
if (!adj.containsKey(a) || !adj.containsKey(b))
throw new NoSuchElementException("Both banks must be in the network.");
/* Remove the edges from both adjacency lists. */
adj.get(a).remove(b);
adj.get(b).remove(a);
}
/**
* Returns true if there is a bilateral relationship between banks 'a' and 'b'.
* If the banks are not already in the network, throws a NoSuchElementException
*
* @param a Bank a
* @param b Bank b
* @return Returns true if there is a relationship between banks 'a' and 'b'
*/
public boolean isRelated(Party a, Party b) {
/* Confirm both endpoints exist. */
if (!adj.containsKey(a) || !adj.containsKey(b))
throw new NoSuchElementException("Both banks must be in the network.");
/* Network is symmetric, so we can just check either endpoint. */
return adj.get(a).contains(b);
}
}
| Java |
{-# LANGUAGE OverloadedStrings #-}
module Response.Export
(pdfResponse) where
import Happstack.Server
import qualified Data.ByteString.Lazy as BS
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString.Base64.Lazy as BEnc
import ImageConversion
import TimetableImageCreator (renderTable)
import System.Random
import Latex
-- | Returns a PDF containing the image of the timetable
-- requested by the user.
pdfResponse :: String -> String -> ServerPart Response
pdfResponse courses session =
liftIO $ getPdf courses session
getPdf :: String -> String -> IO Response
getPdf courses session = do
gen <- newStdGen
let (rand, _) = next gen
svgFilename = (show rand ++ ".svg")
imageFilename = (show rand ++ ".png")
texFilename = (show rand ++ ".tex")
pdfFilename = (drop 4 texFilename) ++ ".pdf"
renderTable svgFilename courses session
returnPdfData svgFilename imageFilename pdfFilename texFilename
returnPdfData :: String -> String -> String -> String -> IO Response
returnPdfData svgFilename imageFilename pdfFilename texFilename = do
createImageFile svgFilename imageFilename
compileTex texFilename imageFilename
_ <- compileTexToPdf texFilename
pdfData <- BS.readFile texFilename
_ <- removeImage svgFilename
_ <- removeImage imageFilename
_ <- removeImage pdfFilename
_ <- removeImage texFilename
let encodedData = BEnc.encode pdfData
return $ toResponse encodedData
| Java |
<?php
# server running the wolframe daemon
$WOLFRAME_SERVER = "localhost";
# wolframe daemon port
$WOLFRAME_PORT = 7962;
# for SSL secured communication, a file with combined client certificate
# and client key
$WOLFRAME_COMBINED_CERTS = "certs/combinedcert.pem";
# which user agents should use client XSLT
$BROWSERS_USING_CLIENT_XSLT = array(
# "op12", "ie8", "ie9", "ie10", "moz23", "webkit27", "webkit28", "moz11"
);
| Java |
/**
*
*/
/**
* @author dewan
*
*/
package gradingTools.comp401f16.assignment11.testcases; | Java |
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println(rand.Int())
fmt.Println(rand.Float64())
}
| Java |
package mcid.anubisset.letsmodreboot.block;
import mcid.anubisset.letsmodreboot.creativetab.CreativeTabLMRB;
/**
* Created by Luke on 30/08/2014.
*/
public class BlockFlag extends BlockLMRB
{
public BlockFlag()
{
super();
this.setBlockName("flag");
this.setBlockTextureName("flag");
}
}
| Java |
require 'package'
class Libxau < Package
description 'xau library for libX11'
homepage 'https://x.org'
version '1.0.8'
source_url 'https://www.x.org/archive/individual/lib/libXau-1.0.8.tar.gz'
source_sha256 'c343b4ef66d66a6b3e0e27aa46b37ad5cab0f11a5c565eafb4a1c7590bc71d7b'
depends_on 'xproto'
def self.build
system "./configure"
system "make"
end
def self.install
system "make", "DESTDIR=#{CREW_DEST_DIR}", "install"
end
end
| Java |
#include "config.h"
#include "syshead.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <setjmp.h>
#include <cmocka.h>
#include <assert.h>
#include "argv.h"
#include "buffer.h"
/* Defines for use in the tests and the mock parse_line() */
#define PATH1 "/s p a c e"
#define PATH2 "/foo bar/baz"
#define PARAM1 "param1"
#define PARAM2 "param two"
#define SCRIPT_CMD "\"" PATH1 PATH2 "\"" PARAM1 "\"" PARAM2 "\""
int
__wrap_parse_line(const char *line, char **p, const int n, const char *file,
const int line_num, int msglevel, struct gc_arena *gc)
{
p[0] = PATH1 PATH2;
p[1] = PARAM1;
p[2] = PARAM2;
return 3;
}
static void
argv_printf__multiple_spaces_in_format__parsed_as_one(void **state)
{
struct argv a = argv_new();
argv_printf(&a, " %s %s %d ", PATH1, PATH2, 42);
assert_int_equal(a.argc, 3);
argv_reset(&a);
}
static void
argv_printf_cat__multiple_spaces_in_format__parsed_as_one(void **state)
{
struct argv a = argv_new();
argv_printf(&a, "%s ", PATH1);
argv_printf_cat(&a, " %s %s", PATH2, PARAM1);
assert_int_equal(a.argc, 3);
argv_reset(&a);
}
static void
argv_printf__combined_path_with_spaces__argc_correct(void **state)
{
struct argv a = argv_new();
argv_printf(&a, "%s%sc", PATH1, PATH2);
assert_int_equal(a.argc, 1);
argv_printf(&a, "%s%sc %d", PATH1, PATH2, 42);
assert_int_equal(a.argc, 2);
argv_printf(&a, "foo %s%sc %s x y", PATH2, PATH1, "foo");
assert_int_equal(a.argc, 5);
argv_reset(&a);
}
static void
argv_parse_cmd__command_string__argc_correct(void **state)
{
struct argv a = argv_new();
argv_parse_cmd(&a, SCRIPT_CMD);
assert_int_equal(a.argc, 3);
argv_reset(&a);
}
static void
argv_parse_cmd__command_and_extra_options__argc_correct(void **state)
{
struct argv a = argv_new();
argv_parse_cmd(&a, SCRIPT_CMD);
argv_printf_cat(&a, "bar baz %d %s", 42, PATH1);
assert_int_equal(a.argc, 7);
argv_reset(&a);
}
static void
argv_printf_cat__used_twice__argc_correct(void **state)
{
struct argv a = argv_new();
argv_printf(&a, "%s %s %s", PATH1, PATH2, PARAM1);
argv_printf_cat(&a, "%s", PARAM2);
argv_printf_cat(&a, "foo");
assert_int_equal(a.argc, 5);
argv_reset(&a);
}
static void
argv_str__multiple_argv__correct_output(void **state)
{
struct argv a = argv_new();
struct gc_arena gc = gc_new();
const char *output;
argv_printf(&a, "%s%sc", PATH1, PATH2);
argv_printf_cat(&a, "%s", PARAM1);
argv_printf_cat(&a, "%s", PARAM2);
output = argv_str(&a, &gc, PA_BRACKET);
assert_string_equal(output, "[" PATH1 PATH2 "] [" PARAM1 "] [" PARAM2 "]");
argv_reset(&a);
gc_free(&gc);
}
static void
argv_insert_head__empty_argv__head_only(void **state)
{
struct argv a = argv_new();
struct argv b;
b = argv_insert_head(&a, PATH1);
assert_int_equal(b.argc, 1);
assert_string_equal(b.argv[0], PATH1);
argv_reset(&b);
argv_reset(&a);
}
static void
argv_insert_head__non_empty_argv__head_added(void **state)
{
struct argv a = argv_new();
struct argv b;
int i;
argv_printf(&a, "%s", PATH2);
b = argv_insert_head(&a, PATH1);
assert_int_equal(b.argc, a.argc + 1);
for (i = 0; i < b.argc; i++) {
if (i == 0)
{
assert_string_equal(b.argv[i], PATH1);
}
else
{
assert_string_equal(b.argv[i], a.argv[i - 1]);
}
}
argv_reset(&b);
argv_reset(&a);
}
int
main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(argv_printf__multiple_spaces_in_format__parsed_as_one),
cmocka_unit_test(argv_printf_cat__multiple_spaces_in_format__parsed_as_one),
cmocka_unit_test(argv_printf__combined_path_with_spaces__argc_correct),
cmocka_unit_test(argv_parse_cmd__command_string__argc_correct),
cmocka_unit_test(argv_parse_cmd__command_and_extra_options__argc_correct),
cmocka_unit_test(argv_printf_cat__used_twice__argc_correct),
cmocka_unit_test(argv_str__multiple_argv__correct_output),
cmocka_unit_test(argv_insert_head__non_empty_argv__head_added),
};
return cmocka_run_group_tests_name("argv", tests, NULL, NULL);
}
| Java |
#!/bin/sh -xe
if [ "$1" = "ci" ]; then
armloc=$(brew fetch --bottle-tag=arm64_big_sur libomp | grep -i downloaded | grep tar.gz | cut -f2 -d:)
x64loc=$(brew fetch --bottle-tag=big_sur libomp | grep -i downloaded | grep tar.gz | cut -f2 -d:)
cp $armloc /tmp/libomp-arm64.tar.gz
mkdir /tmp/libomp-arm64 || true
tar -xzvf /tmp/libomp-arm64.tar.gz -C /tmp/libomp-arm64
cp $x64loc /tmp/libomp-x86_64.tar.gz
mkdir /tmp/libomp-x86_64 || true
tar -xzvf /tmp/libomp-x86_64.tar.gz -C /tmp/libomp-x86_64
else
brew install libomp
fi
git submodule update --init extlib/cairo extlib/freetype extlib/libdxfrw extlib/libpng extlib/mimalloc extlib/pixman extlib/zlib extlib/eigen
| Java |
/*
* Unix SMB/CIFS implementation.
* NetApi LocalGroup Support
* Copyright (C) Guenther Deschner 2008
*
* 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/>.
*/
#include "includes.h"
#include "librpc/gen_ndr/libnetapi.h"
#include "lib/netapi/netapi.h"
#include "lib/netapi/netapi_private.h"
#include "lib/netapi/libnetapi.h"
#include "rpc_client/rpc_client.h"
#include "../librpc/gen_ndr/ndr_samr_c.h"
#include "../librpc/gen_ndr/ndr_lsa_c.h"
#include "rpc_client/cli_lsarpc.h"
#include "rpc_client/init_lsa.h"
#include "../libcli/security/security.h"
static NTSTATUS libnetapi_samr_lookup_and_open_alias(TALLOC_CTX *mem_ctx,
struct rpc_pipe_client *pipe_cli,
struct policy_handle *domain_handle,
const char *group_name,
uint32_t access_rights,
struct policy_handle *alias_handle)
{
NTSTATUS status, result;
struct lsa_String lsa_account_name;
struct samr_Ids user_rids, name_types;
struct dcerpc_binding_handle *b = pipe_cli->binding_handle;
init_lsa_String(&lsa_account_name, group_name);
status = dcerpc_samr_LookupNames(b, mem_ctx,
domain_handle,
1,
&lsa_account_name,
&user_rids,
&name_types,
&result);
if (!NT_STATUS_IS_OK(status)) {
return status;
}
if (!NT_STATUS_IS_OK(result)) {
return result;
}
if (user_rids.count != 1) {
return NT_STATUS_INVALID_NETWORK_RESPONSE;
}
if (name_types.count != 1) {
return NT_STATUS_INVALID_NETWORK_RESPONSE;
}
switch (name_types.ids[0]) {
case SID_NAME_ALIAS:
case SID_NAME_WKN_GRP:
break;
default:
return NT_STATUS_INVALID_SID;
}
status = dcerpc_samr_OpenAlias(b, mem_ctx,
domain_handle,
access_rights,
user_rids.ids[0],
alias_handle,
&result);
if (!NT_STATUS_IS_OK(status)) {
return status;
}
return result;
}
/****************************************************************
****************************************************************/
static NTSTATUS libnetapi_samr_open_alias_queryinfo(TALLOC_CTX *mem_ctx,
struct rpc_pipe_client *pipe_cli,
struct policy_handle *handle,
uint32_t rid,
uint32_t access_rights,
enum samr_AliasInfoEnum level,
union samr_AliasInfo **alias_info)
{
NTSTATUS status, result;
struct policy_handle alias_handle;
union samr_AliasInfo *_alias_info = NULL;
struct dcerpc_binding_handle *b = pipe_cli->binding_handle;
ZERO_STRUCT(alias_handle);
status = dcerpc_samr_OpenAlias(b, mem_ctx,
handle,
access_rights,
rid,
&alias_handle,
&result);
if (!NT_STATUS_IS_OK(status)) {
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
status = result;
goto done;
}
status = dcerpc_samr_QueryAliasInfo(b, mem_ctx,
&alias_handle,
level,
&_alias_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
status = result;
goto done;
}
*alias_info = _alias_info;
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, mem_ctx, &alias_handle, &result);
}
return status;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupAdd_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupAdd *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct lsa_String lsa_account_name;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
uint32_t rid;
struct dcerpc_binding_handle *b = NULL;
struct LOCALGROUP_INFO_0 *info0 = NULL;
struct LOCALGROUP_INFO_1 *info1 = NULL;
const char *alias_name = NULL;
if (!r->in.buffer) {
return WERR_INVALID_PARAM;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
switch (r->in.level) {
case 0:
info0 = (struct LOCALGROUP_INFO_0 *)r->in.buffer;
alias_name = info0->lgrpi0_name;
break;
case 1:
info1 = (struct LOCALGROUP_INFO_1 *)r->in.buffer;
alias_name = info1->lgrpi1_name;
break;
default:
werr = WERR_UNKNOWN_LEVEL;
goto done;
}
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
alias_name,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
werr = WERR_ALIAS_EXISTS;
goto done;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_CREATE_ALIAS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
init_lsa_String(&lsa_account_name, alias_name);
status = dcerpc_samr_CreateDomAlias(b, talloc_tos(),
&domain_handle,
&lsa_account_name,
SEC_STD_DELETE |
SAMR_ALIAS_ACCESS_SET_INFO,
&alias_handle,
&rid,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
if (r->in.level == 1 && info1->lgrpi1_comment) {
union samr_AliasInfo alias_info;
init_lsa_String(&alias_info.description, info1->lgrpi1_comment);
status = dcerpc_samr_SetAliasInfo(b, talloc_tos(),
&alias_handle,
ALIASINFODESCRIPTION,
&alias_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
}
werr = WERR_OK;
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupAdd_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupAdd *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupAdd);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupDel_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupDel *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
struct dcerpc_binding_handle *b = NULL;
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
SEC_STD_DELETE,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto delete_alias;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_CREATE_ALIAS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
SEC_STD_DELETE,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
}
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
delete_alias:
status = dcerpc_samr_DeleteDomAlias(b, talloc_tos(),
&alias_handle,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
ZERO_STRUCT(alias_handle);
werr = WERR_OK;
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupDel_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupDel *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupDel);
}
/****************************************************************
****************************************************************/
static WERROR map_alias_info_to_buffer(TALLOC_CTX *mem_ctx,
const char *alias_name,
struct samr_AliasInfoAll *info,
uint32_t level,
uint32_t *entries_read,
uint8_t **buffer)
{
struct LOCALGROUP_INFO_0 g0;
struct LOCALGROUP_INFO_1 g1;
struct LOCALGROUP_INFO_1002 g1002;
switch (level) {
case 0:
g0.lgrpi0_name = talloc_strdup(mem_ctx, alias_name);
W_ERROR_HAVE_NO_MEMORY(g0.lgrpi0_name);
ADD_TO_ARRAY(mem_ctx, struct LOCALGROUP_INFO_0, g0,
(struct LOCALGROUP_INFO_0 **)buffer, entries_read);
break;
case 1:
g1.lgrpi1_name = talloc_strdup(mem_ctx, alias_name);
g1.lgrpi1_comment = talloc_strdup(mem_ctx, info->description.string);
W_ERROR_HAVE_NO_MEMORY(g1.lgrpi1_name);
ADD_TO_ARRAY(mem_ctx, struct LOCALGROUP_INFO_1, g1,
(struct LOCALGROUP_INFO_1 **)buffer, entries_read);
break;
case 1002:
g1002.lgrpi1002_comment = talloc_strdup(mem_ctx, info->description.string);
ADD_TO_ARRAY(mem_ctx, struct LOCALGROUP_INFO_1002, g1002,
(struct LOCALGROUP_INFO_1002 **)buffer, entries_read);
break;
default:
return WERR_UNKNOWN_LEVEL;
}
return WERR_OK;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupGetInfo_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupGetInfo *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
union samr_AliasInfo *alias_info = NULL;
uint32_t entries_read = 0;
struct dcerpc_binding_handle *b = NULL;
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 1:
case 1002:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto query_alias;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_CREATE_ALIAS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
}
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
query_alias:
status = dcerpc_samr_QueryAliasInfo(b, talloc_tos(),
&alias_handle,
ALIASINFOALL,
&alias_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
werr = map_alias_info_to_buffer(ctx,
r->in.group_name,
&alias_info->all,
r->in.level, &entries_read,
r->out.buffer);
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupGetInfo_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupGetInfo *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupGetInfo);
}
/****************************************************************
****************************************************************/
static WERROR map_buffer_to_alias_info(TALLOC_CTX *mem_ctx,
uint32_t level,
uint8_t *buffer,
enum samr_AliasInfoEnum *alias_level,
union samr_AliasInfo **alias_info)
{
struct LOCALGROUP_INFO_0 *info0;
struct LOCALGROUP_INFO_1 *info1;
struct LOCALGROUP_INFO_1002 *info1002;
union samr_AliasInfo *info = NULL;
info = talloc_zero(mem_ctx, union samr_AliasInfo);
W_ERROR_HAVE_NO_MEMORY(info);
switch (level) {
case 0:
info0 = (struct LOCALGROUP_INFO_0 *)buffer;
init_lsa_String(&info->name, info0->lgrpi0_name);
*alias_level = ALIASINFONAME;
break;
case 1:
info1 = (struct LOCALGROUP_INFO_1 *)buffer;
/* group name will be ignored */
init_lsa_String(&info->description, info1->lgrpi1_comment);
*alias_level = ALIASINFODESCRIPTION;
break;
case 1002:
info1002 = (struct LOCALGROUP_INFO_1002 *)buffer;
init_lsa_String(&info->description, info1002->lgrpi1002_comment);
*alias_level = ALIASINFODESCRIPTION;
break;
}
*alias_info = info;
return WERR_OK;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupSetInfo_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupSetInfo *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct lsa_String lsa_account_name;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
enum samr_AliasInfoEnum alias_level = 0;
union samr_AliasInfo *alias_info = NULL;
struct dcerpc_binding_handle *b = NULL;
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 1:
case 1002:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
init_lsa_String(&lsa_account_name, r->in.group_name);
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_SET_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto set_alias;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_SET_INFO,
&alias_handle);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
}
set_alias:
werr = map_buffer_to_alias_info(ctx, r->in.level, r->in.buffer,
&alias_level, &alias_info);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = dcerpc_samr_SetAliasInfo(b, talloc_tos(),
&alias_handle,
alias_level,
alias_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
werr = WERR_OK;
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupSetInfo_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupSetInfo *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupSetInfo);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupEnum_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupEnum *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
uint32_t entries_read = 0;
union samr_DomainInfo *domain_info = NULL;
union samr_DomainInfo *builtin_info = NULL;
struct samr_SamArray *domain_sam_array = NULL;
struct samr_SamArray *builtin_sam_array = NULL;
int i;
struct dcerpc_binding_handle *b = NULL;
if (!r->out.buffer) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 1:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
if (r->out.total_entries) {
*r->out.total_entries = 0;
}
if (r->out.entries_read) {
*r->out.entries_read = 0;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_LOOKUP_INFO_2 |
SAMR_DOMAIN_ACCESS_ENUM_ACCOUNTS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_LOOKUP_INFO_2 |
SAMR_DOMAIN_ACCESS_ENUM_ACCOUNTS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = dcerpc_samr_QueryDomainInfo(b, talloc_tos(),
&builtin_handle,
2,
&builtin_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
if (r->out.total_entries) {
*r->out.total_entries += builtin_info->general.num_aliases;
}
status = dcerpc_samr_QueryDomainInfo(b, talloc_tos(),
&domain_handle,
2,
&domain_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
if (r->out.total_entries) {
*r->out.total_entries += domain_info->general.num_aliases;
}
status = dcerpc_samr_EnumDomainAliases(b, talloc_tos(),
&builtin_handle,
r->in.resume_handle,
&builtin_sam_array,
r->in.prefmaxlen,
&entries_read,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
for (i=0; i<builtin_sam_array->count; i++) {
union samr_AliasInfo *alias_info = NULL;
if (r->in.level == 1) {
status = libnetapi_samr_open_alias_queryinfo(ctx, pipe_cli,
&builtin_handle,
builtin_sam_array->entries[i].idx,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
ALIASINFOALL,
&alias_info);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
werr = map_alias_info_to_buffer(ctx,
builtin_sam_array->entries[i].name.string,
alias_info ? &alias_info->all : NULL,
r->in.level,
r->out.entries_read,
r->out.buffer);
}
status = dcerpc_samr_EnumDomainAliases(b, talloc_tos(),
&domain_handle,
r->in.resume_handle,
&domain_sam_array,
r->in.prefmaxlen,
&entries_read,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
for (i=0; i<domain_sam_array->count; i++) {
union samr_AliasInfo *alias_info = NULL;
if (r->in.level == 1) {
status = libnetapi_samr_open_alias_queryinfo(ctx, pipe_cli,
&domain_handle,
domain_sam_array->entries[i].idx,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
ALIASINFOALL,
&alias_info);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
werr = map_alias_info_to_buffer(ctx,
domain_sam_array->entries[i].name.string,
alias_info ? &alias_info->all : NULL,
r->in.level,
r->out.entries_read,
r->out.buffer);
}
done:
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupEnum_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupEnum *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupEnum);
}
/****************************************************************
****************************************************************/
static NTSTATUS libnetapi_lsa_lookup_names3(TALLOC_CTX *mem_ctx,
struct rpc_pipe_client *lsa_pipe,
const char *name,
struct dom_sid *sid)
{
NTSTATUS status, result;
struct policy_handle lsa_handle;
struct dcerpc_binding_handle *b = lsa_pipe->binding_handle;
struct lsa_RefDomainList *domains = NULL;
struct lsa_TransSidArray3 sids;
uint32_t count = 0;
struct lsa_String names;
uint32_t num_names = 1;
if (!sid || !name) {
return NT_STATUS_INVALID_PARAMETER;
}
ZERO_STRUCT(sids);
init_lsa_String(&names, name);
status = rpccli_lsa_open_policy2(lsa_pipe, mem_ctx,
false,
SEC_STD_READ_CONTROL |
LSA_POLICY_VIEW_LOCAL_INFORMATION |
LSA_POLICY_LOOKUP_NAMES,
&lsa_handle);
NT_STATUS_NOT_OK_RETURN(status);
status = dcerpc_lsa_LookupNames3(b, mem_ctx,
&lsa_handle,
num_names,
&names,
&domains,
&sids,
LSA_LOOKUP_NAMES_ALL, /* sure ? */
&count,
0, 0,
&result);
NT_STATUS_NOT_OK_RETURN(status);
NT_STATUS_NOT_OK_RETURN(result);
if (count != 1 || sids.count != 1) {
return NT_STATUS_INVALID_NETWORK_RESPONSE;
}
sid_copy(sid, sids.sids[0].sid);
return NT_STATUS_OK;
}
/****************************************************************
****************************************************************/
static WERROR NetLocalGroupModifyMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupAddMembers *add,
struct NetLocalGroupDelMembers *del,
struct NetLocalGroupSetMembers *set)
{
struct NetLocalGroupAddMembers *r = NULL;
struct rpc_pipe_client *pipe_cli = NULL;
struct rpc_pipe_client *lsa_pipe = NULL;
NTSTATUS status, result;
WERROR werr;
struct lsa_String lsa_account_name;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
struct dom_sid *member_sids = NULL;
int i = 0, k = 0;
struct LOCALGROUP_MEMBERS_INFO_0 *info0 = NULL;
struct LOCALGROUP_MEMBERS_INFO_3 *info3 = NULL;
struct dom_sid *add_sids = NULL;
struct dom_sid *del_sids = NULL;
uint32_t num_add_sids = 0;
uint32_t num_del_sids = 0;
struct dcerpc_binding_handle *b = NULL;
if ((!add && !del && !set) || (add && del && set)) {
return WERR_INVALID_PARAM;
}
if (add) {
r = add;
}
if (del) {
r = (struct NetLocalGroupAddMembers *)del;
}
if (set) {
r = (struct NetLocalGroupAddMembers *)set;
}
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 3:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
if (r->in.total_entries == 0 || !r->in.buffer) {
return WERR_INVALID_PARAM;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
member_sids = talloc_zero_array(ctx, struct dom_sid,
r->in.total_entries);
W_ERROR_HAVE_NO_MEMORY(member_sids);
switch (r->in.level) {
case 0:
info0 = (struct LOCALGROUP_MEMBERS_INFO_0 *)r->in.buffer;
for (i=0; i < r->in.total_entries; i++) {
sid_copy(&member_sids[i], (struct dom_sid *)info0[i].lgrmi0_sid);
}
break;
case 3:
info3 = (struct LOCALGROUP_MEMBERS_INFO_3 *)r->in.buffer;
break;
default:
break;
}
if (r->in.level == 3) {
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_lsarpc.syntax_id,
&lsa_pipe);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
for (i=0; i < r->in.total_entries; i++) {
status = libnetapi_lsa_lookup_names3(ctx, lsa_pipe,
info3[i].lgrmi3_domainandname,
&member_sids[i]);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
TALLOC_FREE(lsa_pipe);
}
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
init_lsa_String(&lsa_account_name, r->in.group_name);
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_ADD_MEMBER |
SAMR_ALIAS_ACCESS_REMOVE_MEMBER |
SAMR_ALIAS_ACCESS_GET_MEMBERS |
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto modify_membership;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_ADD_MEMBER |
SAMR_ALIAS_ACCESS_REMOVE_MEMBER |
SAMR_ALIAS_ACCESS_GET_MEMBERS |
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
}
modify_membership:
if (add) {
for (i=0; i < r->in.total_entries; i++) {
status = add_sid_to_array_unique(ctx, &member_sids[i],
&add_sids,
&num_add_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
if (del) {
for (i=0; i < r->in.total_entries; i++) {
status = add_sid_to_array_unique(ctx, &member_sids[i],
&del_sids,
&num_del_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
if (set) {
struct lsa_SidArray current_sids;
status = dcerpc_samr_GetMembersInAlias(b, talloc_tos(),
&alias_handle,
¤t_sids,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
/* add list */
for (i=0; i < r->in.total_entries; i++) {
bool already_member = false;
for (k=0; k < current_sids.num_sids; k++) {
if (dom_sid_equal(&member_sids[i],
current_sids.sids[k].sid)) {
already_member = true;
break;
}
}
if (!already_member) {
status = add_sid_to_array_unique(ctx,
&member_sids[i],
&add_sids, &num_add_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
/* del list */
for (k=0; k < current_sids.num_sids; k++) {
bool keep_member = false;
for (i=0; i < r->in.total_entries; i++) {
if (dom_sid_equal(&member_sids[i],
current_sids.sids[k].sid)) {
keep_member = true;
break;
}
}
if (!keep_member) {
status = add_sid_to_array_unique(ctx,
current_sids.sids[k].sid,
&del_sids, &num_del_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
}
/* add list */
for (i=0; i < num_add_sids; i++) {
status = dcerpc_samr_AddAliasMember(b, talloc_tos(),
&alias_handle,
&add_sids[i],
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
}
/* del list */
for (i=0; i < num_del_sids; i++) {
status = dcerpc_samr_DeleteAliasMember(b, talloc_tos(),
&alias_handle,
&del_sids[i],
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
}
werr = WERR_OK;
done:
if (b && is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupAddMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupAddMembers *r)
{
return NetLocalGroupModifyMembers_r(ctx, r, NULL, NULL);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupAddMembers_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupAddMembers *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupAddMembers);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupDelMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupDelMembers *r)
{
return NetLocalGroupModifyMembers_r(ctx, NULL, r, NULL);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupDelMembers_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupDelMembers *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupDelMembers);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupGetMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupGetMembers *r)
{
return WERR_NOT_SUPPORTED;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupGetMembers_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupGetMembers *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupGetMembers);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupSetMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupSetMembers *r)
{
return NetLocalGroupModifyMembers_r(ctx, NULL, NULL, r);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupSetMembers_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupSetMembers *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupSetMembers);
}
| Java |
/*
* Copyright 2011 kubtek <kubtek@mail.com>
*
* This file is part of StarDict.
*
* StarDict 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.
*
* StarDict 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 StarDict. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "pluginmanagedlg.h"
#include "desktop.h"
#include <glib/gi18n.h>
#include "stardict.h"
PluginManageDlg::PluginManageDlg()
:
window(NULL),
treeview(NULL),
detail_label(NULL),
pref_button(NULL),
plugin_tree_model(NULL),
dict_changed_(false),
order_changed_(false)
{
}
PluginManageDlg::~PluginManageDlg()
{
g_assert(!window);
g_assert(!treeview);
g_assert(!detail_label);
g_assert(!pref_button);
g_assert(!plugin_tree_model);
}
void PluginManageDlg::response_handler (GtkDialog *dialog, gint res_id, PluginManageDlg *oPluginManageDlg)
{
if (res_id == GTK_RESPONSE_HELP) {
show_help("stardict-plugins");
} else if (res_id == STARDICT_RESPONSE_CONFIGURE) {
GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(oPluginManageDlg->treeview));
GtkTreeModel *model;
GtkTreeIter iter;
if (! gtk_tree_selection_get_selected (selection, &model, &iter))
return;
if (!gtk_tree_model_iter_has_child(model, &iter)) {
gchar *filename;
StarDictPlugInType plugin_type;
gtk_tree_model_get (model, &iter, 4, &filename, 5, &plugin_type, -1);
gpAppFrame->oStarDictPlugins->configure_plugin(filename, plugin_type);
g_free(filename);
}
}
}
static gboolean get_disable_list(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer data)
{
if (!gtk_tree_model_iter_has_child(model, iter)) {
gboolean enable;
gtk_tree_model_get (model, iter, 1, &enable, -1);
if (!enable) {
gchar *filename;
gtk_tree_model_get (model, iter, 4, &filename, -1);
std::list<std::string> *disable_list = (std::list<std::string> *)data;
disable_list->push_back(filename);
g_free(filename);
}
}
return FALSE;
}
void PluginManageDlg::on_plugin_enable_toggled (GtkCellRendererToggle *cell, gchar *path_str, PluginManageDlg *oPluginManageDlg)
{
GtkTreeModel *model = GTK_TREE_MODEL(oPluginManageDlg->plugin_tree_model);
GtkTreePath *path = gtk_tree_path_new_from_string (path_str);
GtkTreeIter iter;
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_path_free (path);
gboolean enable;
gchar *filename;
StarDictPlugInType plugin_type;
gboolean can_configure;
gtk_tree_model_get (model, &iter, 1, &enable, 4, &filename, 5, &plugin_type, 6, &can_configure, -1);
enable = !enable;
gtk_tree_store_set (GTK_TREE_STORE (model), &iter, 1, enable, -1);
if (enable) {
gpAppFrame->oStarDictPlugins->load_plugin(filename);
} else {
gpAppFrame->oStarDictPlugins->unload_plugin(filename, plugin_type);
}
g_free(filename);
if (enable)
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, can_configure);
else
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, FALSE);
if (plugin_type == StarDictPlugInType_VIRTUALDICT
|| plugin_type == StarDictPlugInType_NETDICT) {
oPluginManageDlg->dict_changed_ = true;
} else if (plugin_type == StarDictPlugInType_TTS) {
gpAppFrame->oMidWin.oToolWin.UpdatePronounceMenu();
}
std::list<std::string> disable_list;
gtk_tree_model_foreach(model, get_disable_list, &disable_list);
#ifdef _WIN32
{
std::list<std::string> disable_list_rel;
rel_path_to_data_dir(disable_list, disable_list_rel);
std::swap(disable_list, disable_list_rel);
}
#endif
conf->set_strlist("/apps/stardict/manage_plugins/plugin_disable_list", disable_list);
}
struct plugininfo_ParseUserData {
gchar *info_str;
gchar *detail_str;
std::string filename;
std::string name;
std::string version;
std::string short_desc;
std::string long_desc;
std::string author;
std::string website;
};
static void plugininfo_parse_start_element(GMarkupParseContext *context, const gchar *element_name, const gchar **attribute_names, const gchar **attribute_values, gpointer user_data, GError **error)
{
if (strcmp(element_name, "plugin_info")==0) {
plugininfo_ParseUserData *Data = (plugininfo_ParseUserData *)user_data;
Data->name.clear();
Data->version.clear();
Data->short_desc.clear();
Data->long_desc.clear();
Data->author.clear();
Data->website.clear();
}
}
static void plugininfo_parse_end_element(GMarkupParseContext *context, const gchar *element_name, gpointer user_data, GError **error)
{
if (strcmp(element_name, "plugin_info")==0) {
plugininfo_ParseUserData *Data = (plugininfo_ParseUserData *)user_data;
Data->info_str = g_markup_printf_escaped("<b>%s</b> %s\n%s", Data->name.c_str(), Data->version.c_str(), Data->short_desc.c_str());
Data->detail_str = g_markup_printf_escaped(_("%s\n\n<b>Author:</b>\t%s\n<b>Website:</b>\t%s\n<b>Filename:</b>\t%s"), Data->long_desc.c_str(), Data->author.c_str(), Data->website.c_str(), Data->filename.c_str());
}
}
static void plugininfo_parse_text(GMarkupParseContext *context, const gchar *text, gsize text_len, gpointer user_data, GError **error)
{
const gchar *element = g_markup_parse_context_get_element(context);
if (!element)
return;
plugininfo_ParseUserData *Data = (plugininfo_ParseUserData *)user_data;
if (strcmp(element, "name")==0) {
Data->name.assign(text, text_len);
} else if (strcmp(element, "version")==0) {
Data->version.assign(text, text_len);
} else if (strcmp(element, "short_desc")==0) {
Data->short_desc.assign(text, text_len);
} else if (strcmp(element, "long_desc")==0) {
Data->long_desc.assign(text, text_len);
} else if (strcmp(element, "author")==0) {
Data->author.assign(text, text_len);
} else if (strcmp(element, "website")==0) {
Data->website.assign(text, text_len);
}
}
static void add_tree_model(GtkTreeStore *tree_model, GtkTreeIter*parent, const std::list<StarDictPluginInfo> &infolist)
{
plugininfo_ParseUserData Data;
GMarkupParser parser;
parser.start_element = plugininfo_parse_start_element;
parser.end_element = plugininfo_parse_end_element;
parser.text = plugininfo_parse_text;
parser.passthrough = NULL;
parser.error = NULL;
GtkTreeIter iter;
for (std::list<StarDictPluginInfo>::const_iterator i = infolist.begin(); i != infolist.end(); ++i) {
Data.info_str = NULL;
Data.detail_str = NULL;
Data.filename = i->filename;
GMarkupParseContext* context = g_markup_parse_context_new(&parser, (GMarkupParseFlags)0, &Data, NULL);
g_markup_parse_context_parse(context, i->info_xml.c_str(), -1, NULL);
g_markup_parse_context_end_parse(context, NULL);
g_markup_parse_context_free(context);
gtk_tree_store_append(tree_model, &iter, parent);
bool loaded = gpAppFrame->oStarDictPlugins->get_loaded(i->filename.c_str());
gtk_tree_store_set(tree_model, &iter, 0, true, 1, loaded, 2, Data.info_str, 3, Data.detail_str, 4, i->filename.c_str(), 5, i->plugin_type, 6, i->can_configure, -1);
g_free(Data.info_str);
g_free(Data.detail_str);
}
}
static void init_tree_model(GtkTreeStore *tree_model)
{
std::list<std::pair<StarDictPlugInType, std::list<StarDictPluginInfo> > > plugin_list;
{
#ifdef _WIN32
std::list<std::string> plugin_order_list;
const std::list<std::string>& plugin_order_list_rel
= conf->get_strlist("/apps/stardict/manage_plugins/plugin_order_list");
abs_path_to_data_dir(plugin_order_list_rel, plugin_order_list);
#else
const std::list<std::string>& plugin_order_list
= conf->get_strlist("/apps/stardict/manage_plugins/plugin_order_list");
#endif
gpAppFrame->oStarDictPlugins->get_plugin_list(plugin_order_list, plugin_list);
}
GtkTreeIter iter;
for (std::list<std::pair<StarDictPlugInType, std::list<StarDictPluginInfo> > >::iterator i = plugin_list.begin(); i != plugin_list.end(); ++i) {
switch (i->first) {
case StarDictPlugInType_VIRTUALDICT:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Virtual Dictionary</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_NETDICT:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Network Dictionary</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_SPECIALDICT:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Special Dictionary</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_TTS:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>TTS Engine</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_PARSEDATA:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Data Parsing Engine</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_MISC:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Misc</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
default:
break;
}
}
}
void PluginManageDlg::on_plugin_treeview_selection_changed(GtkTreeSelection *selection, PluginManageDlg *oPluginManageDlg)
{
GtkTreeModel *model;
GtkTreeIter iter;
if (! gtk_tree_selection_get_selected (selection, &model, &iter))
return;
if (gtk_tree_model_iter_has_child(model, &iter)) {
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, FALSE);
} else {
gboolean loaded;
gchar *detail;
gboolean can_configure;
gtk_tree_model_get (model, &iter, 1, &loaded, 3, &detail, 6, &can_configure, -1);
gtk_label_set_markup(GTK_LABEL(oPluginManageDlg->detail_label), detail);
g_free(detail);
if (loaded)
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, can_configure);
else
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, FALSE);
}
}
gboolean PluginManageDlg::on_treeview_button_press(GtkWidget * widget, GdkEventButton * event, PluginManageDlg *oPluginManageDlg)
{
if (event->type==GDK_2BUTTON_PRESS) {
if (gtk_widget_get_sensitive(GTK_WIDGET(oPluginManageDlg->pref_button)))
gtk_dialog_response(GTK_DIALOG(oPluginManageDlg->window), STARDICT_RESPONSE_CONFIGURE);
return true;
} else {
return false;
}
}
static void add_order_list(std::list<std::string> &order_list, GtkTreeModel *now_tree_model, GtkTreeIter *parent)
{
gboolean have_iter;
GtkTreeIter iter;
have_iter = gtk_tree_model_iter_children(now_tree_model, &iter, parent);
gchar *filename;
while (have_iter) {
gtk_tree_model_get (now_tree_model, &iter, 4, &filename, -1);
order_list.push_back(filename);
g_free(filename);
have_iter = gtk_tree_model_iter_next(now_tree_model, &iter);
}
}
void PluginManageDlg::write_order_list()
{
std::list<std::string> order_list;
GtkTreeModel *now_tree_model = GTK_TREE_MODEL(plugin_tree_model);
gboolean have_iter;
GtkTreeIter iter;
have_iter = gtk_tree_model_get_iter_first(now_tree_model, &iter);
while (have_iter) {
if (gtk_tree_model_iter_has_child(now_tree_model, &iter)) {
add_order_list(order_list, now_tree_model, &iter);
}
have_iter = gtk_tree_model_iter_next(now_tree_model, &iter);
}
#ifdef _WIN32
{
std::list<std::string> order_list_rel;
rel_path_to_data_dir(order_list, order_list_rel);
std::swap(order_list, order_list_rel);
}
#endif
conf->set_strlist("/apps/stardict/manage_plugins/plugin_order_list", order_list);
}
void PluginManageDlg::drag_data_get_cb(GtkWidget *widget, GdkDragContext *ctx, GtkSelectionData *data, guint info, guint time, PluginManageDlg *oPluginManageDlg)
{
if (gtk_selection_data_get_target(data) == gdk_atom_intern("STARDICT_PLUGINMANAGE", FALSE)) {
GtkTreeRowReference *ref;
GtkTreePath *source_row;
ref = (GtkTreeRowReference *)g_object_get_data(G_OBJECT(ctx), "gtk-tree-view-source-row");
source_row = gtk_tree_row_reference_get_path(ref);
if (source_row == NULL)
return;
GtkTreeIter iter;
gtk_tree_model_get_iter(GTK_TREE_MODEL(oPluginManageDlg->plugin_tree_model), &iter, source_row);
gtk_selection_data_set(data, gdk_atom_intern("STARDICT_PLUGINMANAGE", FALSE), 8, (const guchar *)&iter, sizeof(iter));
gtk_tree_path_free(source_row);
}
}
void PluginManageDlg::drag_data_received_cb(GtkWidget *widget, GdkDragContext *ctx, guint x, guint y, GtkSelectionData *sd, guint info, guint t, PluginManageDlg *oPluginManageDlg)
{
if (gtk_selection_data_get_target(sd) == gdk_atom_intern("STARDICT_PLUGINMANAGE", FALSE) && gtk_selection_data_get_data(sd)) {
GtkTreePath *path = NULL;
GtkTreeViewDropPosition position;
GtkTreeIter drag_iter;
memcpy(&drag_iter, gtk_selection_data_get_data(sd), sizeof(drag_iter));
if (gtk_tree_view_get_dest_row_at_pos(GTK_TREE_VIEW(widget), x, y, &path, &position)) {
GtkTreeIter iter;
GtkTreeModel *model = GTK_TREE_MODEL(oPluginManageDlg->plugin_tree_model);
gtk_tree_model_get_iter(model, &iter, path);
if (gtk_tree_model_iter_has_child(model, &iter)) {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
if (gtk_tree_model_iter_has_child(model, &drag_iter)) {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
GtkTreeIter parent_iter;
if (!gtk_tree_model_iter_parent(model, &parent_iter, &iter)) {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
GtkTreeIter drag_parent_iter;
if (!gtk_tree_model_iter_parent(model, &drag_parent_iter, &drag_iter)) {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
char *iter_str, *drag_iter_str;
iter_str = gtk_tree_model_get_string_from_iter(model, &parent_iter);
drag_iter_str = gtk_tree_model_get_string_from_iter(model, &drag_parent_iter);
if (strcmp(iter_str, drag_iter_str) != 0) {
g_free(iter_str);
g_free(drag_iter_str);
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
g_free(iter_str);
g_free(drag_iter_str);
switch (position) {
case GTK_TREE_VIEW_DROP_AFTER:
case GTK_TREE_VIEW_DROP_INTO_OR_AFTER:
gtk_tree_store_move_after(GTK_TREE_STORE(model), &drag_iter, &iter);
break;
case GTK_TREE_VIEW_DROP_BEFORE:
case GTK_TREE_VIEW_DROP_INTO_OR_BEFORE:
gtk_tree_store_move_before(GTK_TREE_STORE(model), &drag_iter, &iter);
break;
default: {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
}
oPluginManageDlg->write_order_list();
oPluginManageDlg->order_changed_ = true;
gtk_drag_finish (ctx, TRUE, FALSE, t);
}
}
}
GtkWidget *PluginManageDlg::create_plugin_list()
{
GtkWidget *sw;
sw = gtk_scrolled_window_new (NULL, NULL);
gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (sw), GTK_SHADOW_IN);
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
plugin_tree_model = gtk_tree_store_new(7, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT, G_TYPE_BOOLEAN);
init_tree_model(plugin_tree_model);
treeview = gtk_tree_view_new_with_model (GTK_TREE_MODEL(plugin_tree_model));
g_object_unref (G_OBJECT (plugin_tree_model));
#if GTK_MAJOR_VERSION >= 3
#else
gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (treeview), TRUE);
#endif
g_signal_connect (G_OBJECT (treeview), "button_press_event", G_CALLBACK (on_treeview_button_press), this);
GtkTreeSelection *selection;
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview));
gtk_tree_selection_set_mode (selection, GTK_SELECTION_SINGLE);
g_signal_connect (selection, "changed", G_CALLBACK (on_plugin_treeview_selection_changed), this);
GtkCellRenderer *renderer;
GtkTreeViewColumn *column;
renderer = gtk_cell_renderer_toggle_new ();
g_signal_connect (renderer, "toggled", G_CALLBACK (on_plugin_enable_toggled), this);
column = gtk_tree_view_column_new_with_attributes (_("Enable"), renderer, "visible", 0, "active", 1, NULL);
gtk_tree_view_append_column (GTK_TREE_VIEW(treeview), column);
gtk_tree_view_column_set_expand(GTK_TREE_VIEW_COLUMN (column), FALSE);
gtk_tree_view_column_set_clickable (GTK_TREE_VIEW_COLUMN (column), FALSE);
renderer = gtk_cell_renderer_text_new ();
g_object_set (G_OBJECT (renderer), "xalign", 0.0, NULL);
column = gtk_tree_view_column_new_with_attributes (_("Plug-in Name"), renderer, "markup", 2, NULL);
gtk_tree_view_append_column (GTK_TREE_VIEW(treeview), column);
gtk_tree_view_column_set_expand(GTK_TREE_VIEW_COLUMN (column), TRUE);
gtk_tree_view_column_set_clickable (GTK_TREE_VIEW_COLUMN (column), FALSE);
GtkTargetEntry gte[] = {{(gchar *)"STARDICT_PLUGINMANAGE", GTK_TARGET_SAME_APP, 0}};
gtk_tree_view_enable_model_drag_source(GTK_TREE_VIEW(treeview), GDK_BUTTON1_MASK, gte, 1, GDK_ACTION_COPY);
gtk_tree_view_enable_model_drag_dest(GTK_TREE_VIEW(treeview), gte, 1, (GdkDragAction)(GDK_ACTION_COPY | GDK_ACTION_MOVE));
g_signal_connect(G_OBJECT(treeview), "drag-data-received", G_CALLBACK(drag_data_received_cb), this);
g_signal_connect(G_OBJECT(treeview), "drag-data-get", G_CALLBACK(drag_data_get_cb), this);
gtk_tree_view_expand_all(GTK_TREE_VIEW (treeview));
gtk_container_add (GTK_CONTAINER (sw), treeview);
return sw;
}
bool PluginManageDlg::ShowModal(GtkWindow *parent_win, bool &dict_changed, bool &order_changed)
{
window = gtk_dialog_new();
oStarDictPluginSystemInfo.pluginwin = window;
gtk_window_set_transient_for(GTK_WINDOW(window), parent_win);
//gtk_dialog_set_has_separator(GTK_DIALOG(window), false);
gtk_dialog_add_button(GTK_DIALOG(window), GTK_STOCK_HELP, GTK_RESPONSE_HELP);
pref_button = gtk_dialog_add_button(GTK_DIALOG(window), _("Configure Pl_ug-in"), STARDICT_RESPONSE_CONFIGURE);
gtk_widget_set_sensitive(pref_button, FALSE);
gtk_dialog_add_button(GTK_DIALOG(window), GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE);
gtk_dialog_set_default_response(GTK_DIALOG(window), GTK_RESPONSE_CLOSE);
g_signal_connect(G_OBJECT(window), "response", G_CALLBACK(response_handler), this);
GtkWidget *vbox;
#if GTK_MAJOR_VERSION >= 3
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
#else
vbox = gtk_vbox_new (FALSE, 5);
#endif
gtk_container_set_border_width (GTK_CONTAINER (vbox), 2);
GtkWidget *pluginlist = create_plugin_list();
gtk_box_pack_start (GTK_BOX (vbox), pluginlist, true, true, 0);
GtkWidget *expander = gtk_expander_new (_("<b>Plug-in Details</b>"));
gtk_expander_set_use_markup(GTK_EXPANDER(expander), TRUE);
gtk_box_pack_start (GTK_BOX (vbox), expander, false, false, 0);
detail_label = gtk_label_new (NULL);
gtk_label_set_line_wrap(GTK_LABEL(detail_label), TRUE);
gtk_label_set_selectable(GTK_LABEL (detail_label), TRUE);
gtk_container_add (GTK_CONTAINER (expander), detail_label);
gtk_box_pack_start (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG (window))), vbox, true, true, 0);
gtk_widget_show_all (gtk_dialog_get_content_area(GTK_DIALOG (window)));
gtk_window_set_title (GTK_WINDOW (window), _("Manage Plugins"));
gtk_window_set_default_size(GTK_WINDOW(window), 250, 350);
dict_changed_ = false;
order_changed_ = false;
gint result;
while (true) {
result = gtk_dialog_run(GTK_DIALOG(window));
if (result ==GTK_RESPONSE_HELP || result == STARDICT_RESPONSE_CONFIGURE) {
} else {
break;
}
}
/* When do we get GTK_RESPONSE_NONE response? Unable to reproduce. */
if (result != GTK_RESPONSE_NONE) {
dict_changed = dict_changed_;
order_changed = order_changed_;
gtk_widget_destroy(GTK_WIDGET(window));
}
window = NULL;
treeview = NULL;
detail_label = NULL;
pref_button = NULL;
plugin_tree_model = NULL;
oStarDictPluginSystemInfo.pluginwin = NULL;
return result == GTK_RESPONSE_NONE;
}
| Java |
# ChangeLog
## Version 5.2.7 (September 12th 2013)
* Add Ukranian translation from @Krezalis
* Support for do_verp
* Fix bug in CRAM-MD5 AUTH
* Propagate Debugoutput option to SMTP class (@Reblutus)
* Determine MIME type of attachments automatically
* Add cross-platform, multibyte-safe pathinfo replacement (with tests) and use it
* Add a new 'html' Debugoutput type
* Clean up SMTP debug output, remove embedded HTML
* Some small changes in header formatting to improve IETF msglint test results
* Update test_script to use some recently changed features, rename to code_generator
* Generated code actually works!
* Update SyntaxHighlighter
* Major overhaul and cleanup of example code
* New PHPMailer graphic
* msgHTML now uses RFC2392-compliant content ids
* Add line break normalization function and use it in msgHTML
* Don't set unnecessary reply-to addresses
* Make fakesendmail.sh a bit cleaner and safer
* Set a content-transfer-encoding on multiparts (fixes msglint error)
* Fix cid generation in msgHTML (Thanks to @digitalthought)
* Fix handling of multiple SMTP servers (Thanks to @NanoCaiordo)
* SMTP->connect() now supports stream context options (Thanks to @stanislavdavid)
* Add support for iCal event alternatives (Thanks to @reblutus)
* Update to Polish language file (Thanks to Krzysztof Kowalewski)
* Update to Norwegian language file (Thanks to @datagutten)
* Update to Hungarian language file (Thanks to @dominicus-75)
* Add Persian/Farsi translation from @jaii
* Make SMTPDebug property type match type in SMTP class
* Add unit tests for DKIM
* Major refactor of SMTP class
* Reformat to PSR-2 coding standard
* Introduce autoloader
* Allow overriding of SMTP class
* Overhaul of PHPDocs
* Fix broken Q-encoding
* Czech language update (Thanks to @nemelu)
* Removal of excess blank lines in messages
* Added fake POP server and unit tests for POP-before-SMTP
## Version 5.2.6 (April 11th 2013)
* Reflect move to PHPMailer GitHub organisation at https://github.com/PHPMailer/PHPMailer
* Fix unbumped version numbers
* Update packagist.org with new location
* Clean up Changelog
## Version 5.2.5 (April 6th 2013)
* First official release after move from Google Code
* Fixes for qmail when sending via mail()
* Merge in changes from Google code 5.2.4 release
* Minor coding standards cleanup in SMTP class
* Improved unit tests, now tests S/MIME signing
* Travis-CI support on GitHub, runs tests with fake SMTP server
## Version 5.2.4 (February 19, 2013)
* Fix tag and version bug.
* un-deprecate isSMTP(), isMail(), IsSendmail() and isQmail().
* Numerous translation updates
## Version 5.2.3 (February 8, 2013)
* Fix issue with older PCREs and ValidateAddress() (Bugz: 124)
* Add CRAM-MD5 authentication, thanks to Elijah madden, https://github.com/okonomiyaki3000
* Replacement of obsolete Quoted-Printable encoder with a much better implementation
* Composer package definition
* New language added: Hebrew
## Version 5.2.2 (December 3, 2012)
* Some fixes and syncs from https://github.com/Synchro/PHPMailer
* Add Slovak translation, thanks to Michal Tinka
## Version 5.2.2-rc2 (November 6, 2012)
* Fix SMTP server rotation (Bugz: 118)
* Allow override of autogen'ed 'Date' header (for Drupal's
og_mailinglist module)
* No whitespace after '-f' option (Bugz: 116)
* Work around potential warning (Bugz: 114)
## Version 5.2.2-rc1 (September 28, 2012)
* Header encoding works with long lines (Bugz: 93)
* Turkish language update (Bugz: 94)
* undefined $pattern in EncodeQ bug squashed (Bugz: 98)
* use of mail() in safe_mode now works (Bugz: 96)
* ValidateAddress() now 'public static' so people can override the
default and use their own validation scheme.
* ValidateAddress() no longer uses broken FILTER_VALIDATE_EMAIL
* Added in AUTH PLAIN SMTP authentication
## Version 5.2.2-beta2 (August 17, 2012)
* Fixed Postfix VERP support (Bugz: 92)
* Allow action_function callbacks to pass/use
the From address (passed as final param)
* Prevent inf look for get_lines() (Bugz: 77)
* New public var ($UseSendmailOptions). Only pass sendmail()
options iff we really are using sendmail or something sendmail
compatible. (Bugz: 75)
* default setting for LE returned to "\n" due to popular demand.
## Version 5.2.2-beta1 (July 13, 2012)
* Expose PreSend() and PostSend() as public methods to allow
for more control if serializing message sending.
* GetSentMIMEMessage() only constructs the message copy when
needed. Save memory.
* Only pass params to mail() if the underlying MTA is
"sendmail" (as defined as "having the string sendmail
in its pathname") [#69]
* Attachments now work with Amazon SES and others [Bugz#70]
* Debug output now sent to stdout (via echo) or error_log [Bugz#5]
* New var: Debugoutput (for above) [Bugz#5]
* SMTP reads now Timeout aware (new var: Timeout=15) [Bugz#71]
* SMTP reads now can have a Timelimit associated with them
(new var: Timelimit=30)[Bugz#71]
* Fix quoting issue associated with charsets
* default setting for LE is now RFC compliant: "\r\n"
* Return-Path can now be user defined (new var: ReturnPath)
(the default is "" which implies no change from previous
behavior, which was to use either From or Sender) [Bugz#46]
* X-Mailer header can now be disabled (by setting to a
whitespace string, eg " ") [Bugz#66]
* Bugz closed: #68, #60, #42, #43, #59, #55, #66, #48, #49,
#52, #31, #41, #5. #70, #69
## Version 5.2.1 (January 16, 2012)
* Closed several bugs#5
* Performance improvements
* MsgHTML() now returns the message as required.
* New method: GetSentMIMEMessage() (returns full copy of sent message)
## Version 5.2 (July 19, 2011)
* protected MIME body and header
* better DKIM DNS Resource Record support
* better aly handling
* htmlfilter class added to extras
* moved to Apache Extras
## Version 5.1 (October 20, 2009)
* fixed filename issue with AddStringAttachment (thanks to Tony)
* fixed "SingleTo" property, now works with Senmail, Qmail, and SMTP in
addition to PHP mail()
* added DKIM digital signing functionality, new properties:
- DKIM_domain (sets the domain name)
- DKIM_private (holds DKIM private key)
- DKIM_passphrase (holds your DKIM passphrase)
- DKIM_selector (holds the DKIM "selector")
- DKIM_identity (holds the identifying email address)
* added callback function support
- callback function parameters include:
result, to, cc, bcc, subject and body
- see the test/test_callback.php file for usage.
* added "auto" identity functionality
- can automatically add:
- Return-path (if Sender not set)
- Reply-To (if ReplyTo not set)
- can be disabled:
- $mail->SetFrom('yourname@yourdomain.com','First Last',false);
- or by adding the $mail->Sender and/or $mail->ReplyTo properties
Note: "auto" identity added to help with emails ending up in spam or junk boxes because of missing headers
## Version 5.0.2 (May 24, 2009)
* Fix for missing attachments when inline graphics are present
* Fix for missing Cc in header when using SMTP (mail was sent,
but not displayed in header -- Cc receiver only saw email To:
line and no Cc line, but did get the email (To receiver
saw same)
## Version 5.0.1 (April 05, 2009)
* Temporary fix for missing attachments
## Version 5.0.0 (April 02, 2009)
With the release of this version, we are initiating a new version numbering
system to differentiate from the PHP4 version of PHPMailer.
Most notable in this release is fully object oriented code.
### class.smtp.php:
* Refactored class.smtp.php to support new exception handling
* code size reduced from 29.2 Kb to 25.6 Kb
* Removed unnecessary functions from class.smtp.php:
- public function Expand($name) {
- public function Help($keyword="") {
- public function Noop() {
- public function Send($from) {
- public function SendOrMail($from) {
- public function Verify($name) {
### class.phpmailer.php:
* Refactored class.phpmailer.php with new exception handling
* Changed processing functionality of Sendmail and Qmail so they cannot be
inadvertently used
* removed getFile() function, just became a simple wrapper for
file_get_contents()
* added check for PHP version (will gracefully exit if not at least PHP 5.0)
* enhanced code to check if an attachment source is the same as an embedded or
inline graphic source to eliminate duplicate attachments
### New /test_script
We have written a test script you can use to test the script as part of your
installation. Once you press submit, the test script will send a multi-mime
email with either the message you type in or an HTML email with an inline
graphic. Two attachments are included in the email (one of the attachments
is also the inline graphic so you can see that only one copy of the graphic
is sent in the email). The test script will also display the functional
script that you can copy/paste to your editor to duplicate the functionality.
### New examples
All new examples in both basic and advanced modes. Advanced examples show
Exception handling.
### PHPDocumentator (phpdocs) documentation for PHPMailer version 5.0.0
All new documentation
## Version 2.3 (November 06, 2008)
* added Arabic language (many thanks to Bahjat Al Mostafa)
* removed English language from language files and made it a default within
class.phpmailer.php - if no language is found, it will default to use
the english language translation
* fixed public/private declarations
* corrected line 1728, $basedir to $directory
* added $sign_cert_file to avoid improper duplicate use of $sign_key_file
* corrected $this->Hello on line 612 to $this->Helo
* changed default of $LE to "\r\n" to comply with RFC 2822. Can be set by the user
if default is not acceptable
* removed trim() from return results in EncodeQP
* /test and three files it contained are removed from version 2.3
* fixed phpunit.php for compliance with PHP5
* changed $this->AltBody = $textMsg; to $this->AltBody = html_entity_decode($textMsg);
* We have removed the /phpdoc from the downloads. All documentation is now on
the http://phpmailer.codeworxtech.com website.
## Version 2.2.1 () July 19 2008
* fixed line 1092 in class.smtp.php (my apologies, error on my part)
## Version 2.2 () July 15 2008
* Fixed redirect issue (display of UTF-8 in thank you redirect)
* fixed error in getResponse function declaration (class.pop3.php)
* PHPMailer now PHP6 compliant
* fixed line 1092 in class.smtp.php (endless loop from missing = sign)
## Version 2.1 (Wed, June 04 2008)
NOTE: WE HAVE A NEW LANGUAGE VARIABLE FOR DIGITALLY SIGNED S/MIME EMAILS. IF YOU CAN HELP WITH LANGUAGES OTHER THAN ENGLISH AND SPANISH, IT WOULD BE APPRECIATED.
* added S/MIME functionality (ability to digitally sign emails)
BIG THANKS TO "sergiocambra" for posting this patch back in November 2007.
The "Signed Emails" functionality adds the Sign method to pass the private key
filename and the password to read it, and then email will be sent with
content-type multipart/signed and with the digital signature attached.
* fully compatible with E_STRICT error level
- Please note:
In about half the test environments this development version was subjected
to, an error was thrown for the date() functions used (line 1565 and 1569).
This is NOT a PHPMailer error, it is the result of an incorrectly configured
PHP5 installation. The fix is to modify your 'php.ini' file and include the
date.timezone = America/New York
directive, to your own server timezone
- If you do get this error, and are unable to access your php.ini file:
In your PHP script, add
`date_default_timezone_set('America/Toronto');`
- do not try to use
`$myVar = date_default_timezone_get();`
as a test, it will throw an error.
* added ability to define path (mainly for embedded images)
function `MsgHTML($message,$basedir='')` ... where:
`$basedir` is the fully qualified path
* fixed `MsgHTML()` function:
- Embedded Images where images are specified by `<protocol>://` will not be altered or embedded
* fixed the return value of SMTP exit code ( pclose )
* addressed issue of multibyte characters in subject line and truncating
* added ability to have user specified Message ID
(default is still that PHPMailer create a unique Message ID)
* corrected unidentified message type to 'application/octet-stream'
* fixed chunk_split() multibyte issue (thanks to Colin Brown, et al).
* added check for added attachments
* enhanced conversion of HTML to text in MsgHTML (thanks to "brunny")
## Version 2.1.0beta2 (Sun, Dec 02 2007)
* implemented updated EncodeQP (thanks to coolbru, aka Marcus Bointon)
* finished all testing, all known bugs corrected, enhancements tested
Note: will NOT work with PHP4.
Please note, this is BETA software **DO NOT USE THIS IN PRODUCTION OR LIVE PROJECTS; INTENDED STRICTLY FOR TESTING**
## Version 2.1.0beta1
Please note, this is BETA software
** DO NOT USE THIS IN PRODUCTION OR LIVE PROJECTS
INTENDED STRICTLY FOR TESTING
## Version 2.0.0 rc2 (Fri, Nov 16 2007), interim release
* implements new property to control VERP in class.smtp.php
example (requires instantiating class.smtp.php):
$mail->do_verp = true;
* POP-before-SMTP functionality included, thanks to Richard Davey
(see class.pop3.php & pop3_before_smtp_test.php for examples)
* included example showing how to use PHPMailer with GMAIL
* fixed the missing Cc in SendMail() and Mail()
******************
A note on sending bulk emails:
If the email you are sending is not personalized, consider using the
"undisclosed-recipient:;" strategy. That is, put all of your recipients
in the Bcc field and set the To field to "undisclosed-recipients:;".
It's a lot faster (only one send) and saves quite a bit on resources.
Contrary to some opinions, this will not get you listed in spam engines -
it's a legitimate way for you to send emails.
A partial example for use with PHPMailer:
```
$mail->AddAddress("undisclosed-recipients:;");
$mail->AddBCC("email1@anydomain.com,email2@anyotherdomain.com,email3@anyalternatedomain.com");
```
Many email service providers restrict the number of emails that can be sent
in any given time period. Often that is between 50 - 60 emails maximum
per hour or per send session.
If that's the case, then break up your Bcc lists into chunks that are one
less than your limit, and put a pause in your script.
*******************
## Version 2.0.0 rc1 (Thu, Nov 08 2007), interim release
* dramatically simplified using inline graphics ... it's fully automated and requires no user input
* added automatic document type detection for attachments and pictures
* added MsgHTML() function to replace Body tag for HTML emails
* fixed the SendMail security issues (input validation vulnerability)
* enhanced the AddAddresses functionality so that the "Name" portion is used in the email address
* removed the need to use the AltBody method (set from the HTML, or default text used)
* set the PHP Mail() function as the default (still support SendMail, SMTP Mail)
* removed the need to set the IsHTML property (set automatically)
* added Estonian language file by Indrek Päri
* added header injection patch
* added "set" method to permit users to create their own pseudo-properties like 'X-Headers', etc.
example of use:
```
$mail->set('X-Priority', '3');
$mail->set('X-MSMail-Priority', 'Normal');
```
* fixed warning message in SMTP get_lines method
* added TLS/SSL SMTP support. Example of use:
```
$mail = new PHPMailer();
$mail->Mailer = "smtp";
$mail->Host = "smtp.example.com";
$mail->SMTPSecure = "tls"; // option
//$mail->SMTPSecure = "ssl"; // option
...
$mail->Send();
```
* PHPMailer has been tested with PHP4 (4.4.7) and PHP5 (5.2.7)
* Works with PHP installed as a module or as CGI-PHP
NOTE: will NOT work with PHP5 in E_STRICT error mode
## Version 1.73 (Sun, Jun 10 2005)
* Fixed denial of service bug: http://www.cybsec.com/vuln/PHPMailer-DOS.pdf
* Now has a total of 20 translations
* Fixed alt attachments bug: http://tinyurl.com/98u9k
## Version 1.72 (Wed, May 25 2004)
* Added Dutch, Swedish, Czech, Norwegian, and Turkish translations.
* Received: Removed this method because spam filter programs like
SpamAssassin reject this header.
* Fixed error count bug.
* SetLanguage default is now "language/".
* Fixed magic_quotes_runtime bug.
## Version 1.71 (Tue, Jul 28 2003)
* Made several speed enhancements
* Added German and Italian translation files
* Fixed HELO/AUTH bugs on keep-alive connects
* Now provides an error message if language file does not load
* Fixed attachment EOL bug
* Updated some unclear documentation
* Added additional tests and improved others
## Version 1.70 (Mon, Jun 20 2003)
* Added SMTP keep-alive support
* Added IsError method for error detection
* Added error message translation support (SetLanguage)
* Refactored many methods to increase library performance
* Hello now sends the newer EHLO message before HELO as per RFC 2821
* Removed the boundary class and replaced it with GetBoundary
* Removed queue support methods
* New $Hostname variable
* New Message-ID header
* Received header reformat
* Helo variable default changed to $Hostname
* Removed extra spaces in Content-Type definition (#667182)
* Return-Path should be set to Sender when set
* Adds Q or B encoding to headers when necessary
* quoted-encoding should now encode NULs \000
* Fixed encoding of body/AltBody (#553370)
* Adds "To: undisclosed-recipients:;" when all recipients are hidden (BCC)
* Multiple bug fixes
## Version 1.65 (Fri, Aug 09 2002)
* Fixed non-visible attachment bug (#585097) for Outlook
* SMTP connections are now closed after each transaction
* Fixed SMTP::Expand return value
* Converted SMTP class documentation to phpDocumentor format
## Version 1.62 (Wed, Jun 26 2002)
* Fixed multi-attach bug
* Set proper word wrapping
* Reduced memory use with attachments
* Added more debugging
* Changed documentation to phpDocumentor format
## Version 1.60 (Sat, Mar 30 2002)
* Sendmail pipe and address patch (Christian Holtje)
* Added embedded image and read confirmation support (A. Ognio)
* Added unit tests
* Added SMTP timeout support (*nix only)
* Added possibly temporary PluginDir variable for SMTP class
* Added LE message line ending variable
* Refactored boundary and attachment code
* Eliminated SMTP class warnings
* Added SendToQueue method for future queuing support
## Version 1.54 (Wed, Dec 19 2001)
* Add some queuing support code
* Fixed a pesky multi/alt bug
* Messages are no longer forced to have "To" addresses
## Version 1.50 (Thu, Nov 08 2001)
* Fix extra lines when not using SMTP mailer
* Set WordWrap variable to int with a zero default
## Version 1.47 (Tue, Oct 16 2001)
* Fixed Received header code format
* Fixed AltBody order error
* Fixed alternate port warning
## Version 1.45 (Tue, Sep 25 2001)
* Added enhanced SMTP debug support
* Added support for multiple ports on SMTP
* Added Received header for tracing
* Fixed AddStringAttachment encoding
* Fixed possible header name quote bug
* Fixed wordwrap() trim bug
* Couple other small bug fixes
## Version 1.41 (Wed, Aug 22 2001)
* Fixed AltBody bug w/o attachments
* Fixed rfc_date() for certain mail servers
## Version 1.40 (Sun, Aug 12 2001)
* Added multipart/alternative support (AltBody)
* Documentation update
* Fixed bug in Mercury MTA
## Version 1.29 (Fri, Aug 03 2001)
* Added AddStringAttachment() method
* Added SMTP authentication support
## Version 1.28 (Mon, Jul 30 2001)
* Fixed a typo in SMTP class
* Fixed header issue with Imail (win32) SMTP server
* Made fopen() calls for attachments use "rb" to fix win32 error
## Version 1.25 (Mon, Jul 02 2001)
* Added RFC 822 date fix (Patrice)
* Added improved error handling by adding a $ErrorInfo variable
* Removed MailerDebug variable (obsolete with new error handler)
## Version 1.20 (Mon, Jun 25 2001)
* Added quoted-printable encoding (Patrice)
* Set Version as public and removed PrintVersion()
* Changed phpdoc to only display public variables and methods
## Version 1.19 (Thu, Jun 21 2001)
* Fixed MS Mail header bug
* Added fix for Bcc problem with mail(). *Does not work on Win32*
(See PHP bug report: http://www.php.net/bugs.php?id=11616)
* mail() no longer passes a fifth parameter when not needed
## Version 1.15 (Fri, Jun 15 2001)
Note: these changes contributed by Patrice Fournier
* Changed all remaining \n to \r\n
* Bcc: header no longer writen to message except
when sent directly to sendmail
* Added a small message to non-MIME compliant mail reader
* Added Sender variable to change the Sender email
used in -f for sendmail/mail and in 'MAIL FROM' for smtp mode
* Changed boundary setting to a place it will be set only once
* Removed transfer encoding for whole message when using multipart
* Message body now uses Encoding in multipart messages
* Can set encoding and type to attachments 7bit, 8bit
and binary attachment are sent as is, base64 are encoded
* Can set Encoding to base64 to send 8 bits body
through 7 bits servers
## Version 1.10 (Tue, Jun 12 2001)
* Fixed win32 mail header bug (printed out headers in message body)
## Version 1.09 (Fri, Jun 08 2001)
* Changed date header to work with Netscape mail programs
* Altered phpdoc documentation
## Version 1.08 (Tue, Jun 05 2001)
* Added enhanced error-checking
* Added phpdoc documentation to source
## Version 1.06 (Fri, Jun 01 2001)
* Added optional name for file attachments
## Version 1.05 (Tue, May 29 2001)
* Code cleanup
* Eliminated sendmail header warning message
* Fixed possible SMTP error
## Version 1.03 (Thu, May 24 2001)
* Fixed problem where qmail sends out duplicate messages
## Version 1.02 (Wed, May 23 2001)
* Added multiple recipient and attachment Clear* methods
* Added Sendmail public variable
* Fixed problem with loading SMTP library multiple times
## Version 0.98 (Tue, May 22 2001)
* Fixed problem with redundant mail hosts sending out multiple messages
* Added additional error handler code
* Added AddCustomHeader() function
* Added support for Microsoft mail client headers (affects priority)
* Fixed small bug with Mailer variable
* Added PrintVersion() function
## Version 0.92 (Tue, May 15 2001)
* Changed file names to class.phpmailer.php and class.smtp.php to match
current PHP class trend.
* Fixed problem where body not being printed when a message is attached
* Several small bug fixes
## Version 0.90 (Tue, April 17 2001)
* Initial public release
| Java |
// Copyright (c) 2016 GeometryFactory Sarl (France)
//
// This file is part of CGAL (www.cgal.org); you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 3 of the License,
// or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
// SPDX-License-Identifier: LGPL-3.0+
//
//
// Author : Andreas Fabri
#ifndef CGAL_LICENSE_CHECK_H
#define CGAL_LICENSE_CHECK_H
//#define CGAL_LICENSE_WARNING 1 // in order to get a warning during compilation
//#define CGAL_LICENSE_ERROR 1 // in order to get an error during compilation
// if no such define exists, the package is used under the GPL or LGPL
// Otherwise the number encodes the date year/month/day
// Any release made b......
// e.g.
//#define CGAL_AABB_TREE_COMMERCIAL_LICENSE 20140101
#endif // CGAL_LICENSE_CHECK_H
| Java |
#ifndef FONTDIALOG_H
#define FONTDIALOG_H
#include "DialogBox.h"
class FontSelector;
// Font selection widget
class FXAPI FontSelector : public FXPacker
{
FXDECLARE(FontSelector)
protected:
FXTextField *family;
FXList *familylist;
FXTextField *weight;
FXList *weightlist;
FXTextField *style;
FXList *stylelist;
FXTextField *size;
FXList *sizelist;
FXComboBox *charset;
FXComboBox *setwidth;
FXComboBox *pitch;
FXCheckButton *scalable;
FXCheckButton *allfonts;
FXButton *accept;
FXButton *cancel;
FXLabel *preview;
FXFont *previewfont;
FXFontDesc selected;
protected:
FontSelector()
{}
void listFontFaces();
void listWeights();
void listSlants();
void listFontSizes();
void previewFont();
private:
FontSelector(const FontSelector&);
FontSelector &operator=(const FontSelector&);
public:
long onCmdFamily(FXObject*,FXSelector,void*);
long onCmdWeight(FXObject*,FXSelector,void*);
long onCmdStyle(FXObject*,FXSelector,void*);
long onCmdStyleText(FXObject*,FXSelector,void*);
long onCmdSize(FXObject*,FXSelector,void*);
long onCmdSizeText(FXObject*,FXSelector,void*);
long onCmdCharset(FXObject*,FXSelector,void*);
long onUpdCharset(FXObject*,FXSelector,void*);
long onCmdSetWidth(FXObject*,FXSelector,void*);
long onUpdSetWidth(FXObject*,FXSelector,void*);
long onCmdPitch(FXObject*,FXSelector,void*);
long onUpdPitch(FXObject*,FXSelector,void*);
long onCmdScalable(FXObject*,FXSelector,void*);
long onUpdScalable(FXObject*,FXSelector,void*);
long onCmdAllFonts(FXObject*,FXSelector,void*);
long onUpdAllFonts(FXObject*,FXSelector,void*);
public:
enum{
ID_FAMILY=FXPacker::ID_LAST,
ID_WEIGHT,
ID_STYLE,
ID_STYLE_TEXT,
ID_SIZE,
ID_SIZE_TEXT,
ID_CHARSET,
ID_SETWIDTH,
ID_PITCH,
ID_SCALABLE,
ID_ALLFONTS,
ID_LAST
};
public:
// Constructor
FontSelector(FXComposite *p,FXObject* tgt=NULL,FXSelector sel=0,unsigned int opts=0,int x=0,int y=0,int w=0,int h=0);
// Create server-side resources
virtual void create();
// Return a pointer to the "Accept" button
FXButton *acceptButton() const
{
return accept;
}
// Return a pointer to the "Cancel" button
FXButton *cancelButton() const
{
return cancel;
}
// Set font selection
void setFontSelection(const FXFontDesc& fontdesc);
// Get font selection
void getFontSelection(FXFontDesc& fontdesc) const;
// Save to a stream
virtual void save(FXStream& store) const;
// Load from a stream
virtual void load(FXStream& store);
// Destructor
virtual ~FontSelector();
};
// Font selection dialog
class FXAPI FontDialog : public DialogBox
{
FXDECLARE(FontDialog)
protected:
FontSelector *fontbox;
protected:
FontDialog()
{}
private:
FontDialog(const FontDialog&);
FontDialog &operator=(const FontDialog&);
public:
// Constructor
FontDialog(FXWindow* owner,const FXString& name,unsigned int opts=0,int x=0,int y=0,int w=750,int h=480);
// Save dialog to a stream
virtual void save(FXStream& store) const;
// Load dialog from a stream
virtual void load(FXStream& store);
// Set the current font selection
void setFontSelection(const FXFontDesc& fontdesc);
// Get the current font selection
void getFontSelection(FXFontDesc& fontdesc) const;
// Destructor
virtual ~FontDialog();
};
#endif
| Java |
---
title: Reporting Bugs & Getting Help
weight: 10
---
BRAT is under constant development and we are eager to resolve all known issues. However, please search [existing posts](https://github.com/Riverscapes/pyBRAT/issues) first and our help pages before [posting an issue](#Posting an Issue).
# Questions or Help
You can explore or search [other user questions here](https://github.com/Riverscapes/pyBRAT/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22help+wanted%22+).
<a class="button" href="https://github.com/Riverscapes/pyBRAT/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22help+wanted%22+"><i class="fa fa-github"/> BRAT Help Wanted</a>
# Bugs
Before logging a suspected bug, please search [known open bugs](https://github.com/Riverscapes/pyBRAT/labels/bug). If you have more information to report about this bug, please post a comment to the appropriate issue. Otherwise, you can post a new bug, using the 'Bug' label.
<a class="button" href="https://github.com/Riverscapes/pyBRAT/labels/bug"><i class="fa fa-github"/> BRAT Bugs</a>
# Posting an Issue
If you find a bug, or simply want to report an issue with the software, please log a GitHub Issue. <a class="button" href="https://github.com/Riverscapes/pyBRAT/issues"><i class="fa fa-github"/> Github Issues</a>
Anyone in the BRAT community and a member of GitHub can respond, and the development team will recieve a notification. Please be patient for a response. We do not have any budget for supporting users, but we do try and respond to issues when we can.
This video shows you how to post an issue (for [GCD](http://gcd.riverscapes.xyz), but process is similar) and some helpful things to include:
<iframe width="560" height="315" src="https://www.youtube.com/embed/EFAQgvZQY0s?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
### Please always include following information:
> ## The Problem
>
> What went wrong?
>
> ## Reproduction steps
>
> 1. I did this
> 2. Then I did that...
> Include screenshots if you have them (you can drag and drop these in)
> ## Error messages (if applicable)
>
> ```text
>
> Paste the exception message you are getting from the app here. It really helps us.
>
> ```
> ## Datasets
>
> You can provide links to datasets.>
> ## BRAT & ARC Version Info
> - Version of BRAT you were using (e.g. `BRAT 3.0.19`)
> - Version of ArcGIS (e.g. `ArcGIS 10.5.1`)
The issue posting in GitHub uses [markdown syntax](https://guides.github.com/features/mastering-markdown/).
### Optional Information:
- If you do not want to provide a link to the complete copy of the BRAT project, just sharing a copy of the `*project.rs.xml` project file and changing the file extension to text and uploading it to your post can help a lot
- Record a video of what is going wrong (we recommend [FastStone Capture](http://etal.joewheaton.org/faststone-capture.html), post it to YouTube or Vimeo, and share the link (DO NOT SEND VIDEOS as attachments! just stream it). Videos can be really helpful for understanding what you are doing and what is going wrong.
------
<div align="center">
<a class="hollow button" href="{{ site.baseurl }}/Documentation"><i class="fa fa-info-circle"></i> Back to Help </a>
<a class="hollow button" href="{{ site.baseurl }}/"><img src="{{ site.baseurl }}/assets/images/favicons/favicon-16x16.png"> Back to BRAT Home </a>
</div>
| Java |
package tmp.generated_people;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public abstract class Element_ol extends GenASTNode {
protected Element_ol(Property[] p, Token firstToken, Token lastToken) { super(p, firstToken, lastToken); }
protected Element_ol(Property[] p, IToken firstToken, IToken lastToken) { super(p, firstToken, lastToken); }
}
| Java |
"""
Copyright 2014 Jason Heeris, jason.heeris@gmail.com
This file is part of the dungeon excavator web interface ("webcavate").
Webcavate 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.
Webcavate 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
webcavate. If not, see <http://www.gnu.org/licenses/>.
"""
import argparse
import uuid
from flask import Flask, render_template, request, make_response, redirect, url_for, flash
from dungeon.excavate import render_room
HELP_TEXT = """\
Web interface to the dungeon excavator."""
app = Flask('dungeon.web')
app.secret_key = str(uuid.uuid4())
@app.route("/")
def root():
""" Web interface landing page. """
return render_template('index.html')
@app.route("/error")
def error():
""" Display errors. """
return render_template('error.html')
def make_map(request, format):
tile_size = int(request.form['size'])
wall_file = request.files['walls']
floor_file = request.files['floor']
floorplan_file = request.files['floorplan']
try:
room_data, content_type = render_room(
floor_file.read(),
wall_file.read(),
floorplan_file.read(),
tile_size,
format
)
except ValueError as ve:
flash(str(ve))
return redirect(url_for('error'))
# Create response
response = make_response(room_data)
response.headers['Content-Type'] = content_type
return response
@app.route("/map.svg", methods=['POST'])
def map_svg():
return make_map(request, format='svg')
@app.route("/map.png", methods=['POST'])
def map_png():
return make_map(request, format='png')
@app.route("/map.jpg", methods=['POST'])
def map_jpg():
return make_map(request, format='jpg')
@app.route("/map", methods=['POST'])
def process():
""" Process submitted form data. """
format = request.form['format']
try:
node = {
'png': 'map_png',
'svg': 'map_svg',
'jpg': 'map_jpg',
}[format]
except KeyError:
flash("The output format you selected is not supported.")
return redirect(url_for('error'))
else:
return redirect(url_for(node, _method='POST'), code=307)
def main():
""" Parse arguments and get things going for the web interface """
parser = argparse.ArgumentParser(description=HELP_TEXT)
parser.add_argument(
'-p', '--port',
help="Port to serve the interface on.",
type=int,
default=5050
)
parser.add_argument(
'-a', '--host',
help="Host to server the interface on.",
)
args = parser.parse_args()
app.run(port=args.port, host=args.host, debug=False)
| Java |
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { of, throwError } from 'rxjs';
import { BookstoreTestModule } from '../../../test.module';
import { JhiMetricsMonitoringComponent } from 'app/admin/metrics/metrics.component';
import { JhiMetricsService } from 'app/admin/metrics/metrics.service';
describe('Component Tests', () => {
describe('JhiMetricsMonitoringComponent', () => {
let comp: JhiMetricsMonitoringComponent;
let fixture: ComponentFixture<JhiMetricsMonitoringComponent>;
let service: JhiMetricsService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [BookstoreTestModule],
declarations: [JhiMetricsMonitoringComponent]
})
.overrideTemplate(JhiMetricsMonitoringComponent, '')
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(JhiMetricsMonitoringComponent);
comp = fixture.componentInstance;
service = fixture.debugElement.injector.get(JhiMetricsService);
});
describe('refresh', () => {
it('should call refresh on init', () => {
// GIVEN
const response = {
timers: {
service: 'test',
unrelatedKey: 'test'
},
gauges: {
'jcache.statistics': {
value: 2
},
unrelatedKey: 'test'
}
};
spyOn(service, 'getMetrics').and.returnValue(of(response));
// WHEN
comp.ngOnInit();
// THEN
expect(service.getMetrics).toHaveBeenCalled();
});
});
});
});
| Java |
before words
\begin{myenv}body of myenv
\end{myenv}
after words
| Java |
<!DOCTYPE html>
<html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-GB">
<title>Ross Gammon’s Family Tree - Events</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">Ross Gammon’s Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li class = "CurrentSection"><a href="../../../events.html" title="Events">Events</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="EventDetail">
<h3>Death</h3>
<table class="infolist eventlist">
<tbody>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnGRAMPSID">E14190</td>
</tr>
<tr>
<td class="ColumnAttribute">Date</td>
<td class="ColumnColumnDate">
1982-09-08
</td>
</tr>
</tbody>
</table>
<div class="subsection" id="references">
<h4>References</h4>
<ol class="Col1" role="Volume-n-Page"type = 1>
<li>
<a href="../../../ppl/d/b/d15f6055ff1a0cf06d72b377bd.html">
LUCAS, Desmond Leslie
<span class="grampsid"> [I11896]</span>
</a>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:55:02<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
| Java |
//# BaselineSelection.cc: Class to handle the baseline selection
//# Copyright (C) 2012
//# ASTRON (Netherlands Institute for Radio Astronomy)
//# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands
//#
//# This file is part of the LOFAR software suite.
//# The LOFAR software suite 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.
//#
//# The LOFAR software suite 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 the LOFAR software suite. If not, see <http://www.gnu.org/licenses/>.
//#
//# $Id$
//#
//# @author Ger van Diepen
#include <lofar_config.h>
#include <DPPP/BaselineSelection.h>
#include <DPPP/DPLogger.h>
#include <MS/BaselineSelect.h>
#include <Common/ParameterSet.h>
#include <Common/ParameterValue.h>
#include <Common/LofarLogger.h>
#include <Common/StreamUtil.h>
using namespace casa;
using namespace std;
namespace LOFAR {
namespace DPPP {
BaselineSelection::BaselineSelection()
{}
BaselineSelection::BaselineSelection (const ParameterSet& parset,
const string& prefix,
bool minmax,
const string& defaultCorrType,
const string& defaultBaseline)
: itsStrBL (parset.getString (prefix + "baseline", defaultBaseline)),
itsCorrType (parset.getString (prefix + "corrtype", defaultCorrType)),
itsRangeBL (parset.getDoubleVector (prefix + "blrange",
vector<double>()))
{
if (minmax) {
double minbl = parset.getDouble (prefix + "blmin", -1);
double maxbl = parset.getDouble (prefix + "blmax", -1);
if (minbl > 0) {
itsRangeBL.push_back (0.);
itsRangeBL.push_back (minbl);
}
if (maxbl > 0) {
itsRangeBL.push_back (maxbl);
itsRangeBL.push_back (1e30);
}
}
ASSERTSTR (itsRangeBL.size()%2 == 0,
"NDPPP error: uneven number of lengths in baseline range");
}
bool BaselineSelection::hasSelection() const
{
return !((itsStrBL.empty() || itsStrBL == "[]") &&
itsCorrType.empty() && itsRangeBL.empty());
}
void BaselineSelection::show (ostream& os, const string& blanks) const
{
os << " Baseline selection:" << std::endl;
os << " baseline: " << blanks << itsStrBL << std::endl;
os << " corrtype: " << blanks << itsCorrType << std::endl;
os << " blrange: " << blanks << itsRangeBL << std::endl;
}
Matrix<bool> BaselineSelection::apply (const DPInfo& info) const
{
// Size and initialize the selection matrix.
int nant = info.antennaNames().size();
Matrix<bool> selectBL(nant, nant, true);
// Apply the various parts if given.
if (! itsStrBL.empty() && itsStrBL != "[]") {
handleBL (selectBL, info);
}
if (! itsCorrType.empty()) {
handleCorrType (selectBL);
}
if (! itsRangeBL.empty()) {
handleLength (selectBL, info);
}
return selectBL;
}
Vector<bool> BaselineSelection::applyVec (const DPInfo& info) const
{
Matrix<bool> sel = apply(info);
Vector<bool> vec;
vec.resize (info.nbaselines());
for (uint i=0; i<info.nbaselines(); ++i) {
vec[i] = sel(info.getAnt1()[i], info.getAnt2()[i]);
}
return vec;
}
void BaselineSelection::handleBL (Matrix<bool>& selectBL,
const DPInfo& info) const
{
// Handle the value(s) in the baseline selection string.
ParameterValue pvBL(itsStrBL);
// The value can be a vector or an MSSelection string.
// Alas the ParameterValue vector test cannot be used, because
// the first character of a MSSelection string can also be [.
// So if the first is [ and a ] is found before the end and before
// another [, it must be a MSSelection string.
bool mssel = true;
if (itsStrBL[0] == '[') {
String::size_type rb = itsStrBL.find (']');
ASSERTSTR (rb != string::npos,
"Baseline selection " + itsStrBL +
" has no ending ]");
if (rb == itsStrBL.size()-1) {
mssel = false;
} else {
String::size_type lb = itsStrBL.find ('[', 1);
mssel = (lb == string::npos || lb > rb);
}
}
if (!mssel) {
// Specified as a vector of antenna name patterns.
selectBL = selectBL && handleBLVector (pvBL, info.antennaNames());
} else {
// Specified in casacore's MSSelection format.
string msName = info.msName();
ASSERT (! msName.empty());
Matrix<bool> sel(BaselineSelect::convert (msName, itsStrBL));
// The resulting matrix can be smaller because new stations might have
// been added that are not present in the MS's ANTENNA table.
if (sel.nrow() == selectBL.nrow()) {
selectBL = selectBL && sel;
} else {
// Only and the subset.
Matrix<bool> selBL = selectBL(IPosition(2,0),
IPosition(2,sel.nrow()-1));
selBL = selBL && sel;
}
}
}
Matrix<bool> BaselineSelection::handleBLVector (const ParameterValue& pvBL,
const Vector<String>& antNames) const
{
Matrix<Bool> sel(antNames.size(), antNames.size());
sel = false;
vector<ParameterValue> pairs = pvBL.getVector();
// Each ParameterValue can be a single value (antenna) or a pair of
// values (a baseline).
// Note that [ant1,ant2] is somewhat ambiguous; it means two antennae,
// but one might think it means a baseline [[ant1,ant2]].
if (pairs.size() == 2 &&
!(pairs[0].isVector() || pairs[1].isVector())) {
LOG_WARN_STR ("PreFlagger baseline " << pvBL.get()
<< " means two antennae, but is somewhat ambigious; "
<< "it's more clear to use [[ant1],[ant2]]");
}
for (uint i=0; i<pairs.size(); ++i) {
vector<string> bl = pairs[i].getStringVector();
if (bl.size() == 1) {
// Turn the given antenna name pattern into a regex.
Regex regex(Regex::fromPattern (bl[0]));
int nmatch = 0;
// Loop through all antenna names and set matrix for matching ones.
for (uint i2=0; i2<antNames.size(); ++i2) {
if (antNames[i2].matches (regex)) {
nmatch++;
// Antenna matches, so set all corresponding flags.
for (uint j=0; j<antNames.size(); ++j) {
sel(i2,j) = true;
sel(j,i2) = true;
}
}
}
if (nmatch == 0) {
DPLOG_WARN_STR ("PreFlagger: no matches for antenna name pattern ["
<< bl[0] << "]");
}
} else {
ASSERTSTR (bl.size() == 2, "PreFlagger baseline " << bl <<
" should contain 1 or 2 antenna name patterns");
// Turn the given antenna name pattern into a regex.
Regex regex1(Regex::fromPattern (bl[0]));
Regex regex2(Regex::fromPattern (bl[1]));
int nmatch = 0;
// Loop through all antenna names and set matrix for matching ones.
for (uint i2=0; i2<antNames.size(); ++i2) {
if (antNames[i2].matches (regex2)) {
// Antenna2 matches, now try Antenna1.
for (uint i1=0; i1<antNames.size(); ++i1) {
if (antNames[i1].matches (regex1)) {
nmatch++;
sel(i1,i2) = true;
sel(i2,i1) = true;
}
}
}
}
if (nmatch == 0) {
DPLOG_WARN_STR ("PreFlagger: no matches for baseline name pattern ["
<< bl[0] << ',' << bl[1] << "]");
}
}
}
return sel;
}
void BaselineSelection::handleCorrType (Matrix<bool>& selectBL) const
{
// Process corrtype if given.
string corrType = toLower(itsCorrType);
ASSERTSTR (corrType == "auto" || corrType == "cross",
"NDPPP corrType " << corrType
<< " is invalid; must be auto, cross, or empty string");
if (corrType == "auto") {
Vector<bool> diag = selectBL.diagonal().copy();
selectBL = false;
selectBL.diagonal() = diag;
} else {
selectBL.diagonal() = false;
}
}
void BaselineSelection::handleLength (Matrix<bool>& selectBL,
const DPInfo& info) const
{
// Get baseline lengths.
const vector<double>& blength = info.getBaselineLengths();
const Vector<Int>& ant1 = info.getAnt1();
const Vector<Int>& ant2 = info.getAnt2();
for (uint i=0; i<ant1.size(); ++i) {
// Clear selection if no range matches.
bool match = false;
for (uint j=0; j<itsRangeBL.size(); j+=2) {
if (blength[i] >= itsRangeBL[j] && blength[i] <= itsRangeBL[j+1]) {
match = true;
break;
}
}
if (!match) {
int a1 = ant1[i];
int a2 = ant2[i];
selectBL(a1,a2) = false;
selectBL(a2,a1) = false;
}
}
}
} //# end namespace
}
| Java |
//
//---------------------------------------------------------------------------
//
// Copyright(C) 2005-2016 Christoph Oelckers
// All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/
//
//--------------------------------------------------------------------------
//
/*
** r_opengl.cpp
**
** OpenGL system interface
**
*/
#include "gl/system/gl_system.h"
#include "tarray.h"
#include "doomtype.h"
#include "m_argv.h"
#include "zstring.h"
#include "version.h"
#include "i_system.h"
#include "v_text.h"
#include "r_data/r_translate.h"
#include "gl/system/gl_interface.h"
#include "gl/system/gl_cvars.h"
void gl_PatchMenu();
static TArray<FString> m_Extensions;
RenderContext gl;
//==========================================================================
//
//
//
//==========================================================================
static void CollectExtensions()
{
const char *extension;
int max = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &max);
if (0 == max)
{
// Try old method to collect extensions
const char *supported = (char *)glGetString(GL_EXTENSIONS);
if (nullptr != supported)
{
char *extensions = new char[strlen(supported) + 1];
strcpy(extensions, supported);
char *extension = strtok(extensions, " ");
while (extension)
{
m_Extensions.Push(FString(extension));
extension = strtok(nullptr, " ");
}
delete [] extensions;
}
}
else
{
// Use modern method to collect extensions
for (int i = 0; i < max; i++)
{
extension = (const char*)glGetStringi(GL_EXTENSIONS, i);
m_Extensions.Push(FString(extension));
}
}
}
//==========================================================================
//
//
//
//==========================================================================
static bool CheckExtension(const char *ext)
{
for (unsigned int i = 0; i < m_Extensions.Size(); ++i)
{
if (m_Extensions[i].CompareNoCase(ext) == 0) return true;
}
return false;
}
//==========================================================================
//
//
//
//==========================================================================
static void InitContext()
{
gl.flags=0;
}
//==========================================================================
//
//
//
//==========================================================================
#define FUDGE_FUNC(name, ext) if (_ptrc_##name == NULL) _ptrc_##name = _ptrc_##name##ext;
void gl_LoadExtensions()
{
InitContext();
CollectExtensions();
const char *version = Args->CheckValue("-glversion");
const char *glversion = (const char*)glGetString(GL_VERSION);
if (version == NULL)
{
version = glversion;
}
else
{
double v1 = strtod(version, NULL);
double v2 = strtod(glversion, NULL);
if (v2 < v1) version = glversion;
else Printf("Emulating OpenGL v %s\n", version);
}
float gl_version = (float)strtod(version, NULL) + 0.01f;
// Don't even start if it's lower than 2.0 or no framebuffers are available (The framebuffer extension is needed for glGenerateMipmapsEXT!)
if ((gl_version < 2.0f || !CheckExtension("GL_EXT_framebuffer_object")) && gl_version < 3.0f)
{
I_FatalError("Unsupported OpenGL version.\nAt least OpenGL 2.0 with framebuffer support is required to run " GAMENAME ".\n");
}
// add 0.01 to account for roundoff errors making the number a tad smaller than the actual version
gl.glslversion = strtod((char*)glGetString(GL_SHADING_LANGUAGE_VERSION), NULL) + 0.01f;
gl.vendorstring = (char*)glGetString(GL_VENDOR);
// first test for optional features
if (CheckExtension("GL_ARB_texture_compression")) gl.flags |= RFL_TEXTURE_COMPRESSION;
if (CheckExtension("GL_EXT_texture_compression_s3tc")) gl.flags |= RFL_TEXTURE_COMPRESSION_S3TC;
if ((gl_version >= 3.3f || CheckExtension("GL_ARB_sampler_objects")) && !Args->CheckParm("-nosampler"))
{
gl.flags |= RFL_SAMPLER_OBJECTS;
}
// The minimum requirement for the modern render path are GL 3.0 + uniform buffers. Also exclude the Linux Mesa driver at GL 3.0 because it errors out on shader compilation.
if (gl_version < 3.0f || (gl_version < 3.1f && (!CheckExtension("GL_ARB_uniform_buffer_object") || strstr(gl.vendorstring, "X.Org") != nullptr)))
{
gl.legacyMode = true;
gl.lightmethod = LM_LEGACY;
gl.buffermethod = BM_LEGACY;
gl.glslversion = 0;
gl.flags |= RFL_NO_CLIP_PLANES;
}
else
{
gl.legacyMode = false;
gl.lightmethod = LM_DEFERRED;
gl.buffermethod = BM_DEFERRED;
if (gl_version < 4.f)
{
#ifdef _WIN32
if (strstr(gl.vendorstring, "ATI Tech"))
{
gl.flags |= RFL_NO_CLIP_PLANES; // gl_ClipDistance is horribly broken on ATI GL3 drivers for Windows.
}
#endif
}
else if (gl_version < 4.5f)
{
// don't use GL 4.x features when running a GL 3.x context.
if (CheckExtension("GL_ARB_buffer_storage"))
{
// work around a problem with older AMD drivers: Their implementation of shader storage buffer objects is piss-poor and does not match uniform buffers even closely.
// Recent drivers, GL 4.4 don't have this problem, these can easily be recognized by also supporting the GL_ARB_buffer_storage extension.
if (CheckExtension("GL_ARB_shader_storage_buffer_object"))
{
// Shader storage buffer objects are broken on current Intel drivers.
if (strstr(gl.vendorstring, "Intel") == NULL)
{
gl.flags |= RFL_SHADER_STORAGE_BUFFER;
}
}
gl.flags |= RFL_BUFFER_STORAGE;
gl.lightmethod = LM_DIRECT;
gl.buffermethod = BM_PERSISTENT;
}
}
else
{
// Assume that everything works without problems on GL 4.5 drivers where these things are core features.
gl.flags |= RFL_SHADER_STORAGE_BUFFER | RFL_BUFFER_STORAGE;
gl.lightmethod = LM_DIRECT;
gl.buffermethod = BM_PERSISTENT;
}
if (gl_version >= 4.3f || CheckExtension("GL_ARB_invalidate_subdata")) gl.flags |= RFL_INVALIDATE_BUFFER;
if (gl_version >= 4.3f || CheckExtension("GL_KHR_debug")) gl.flags |= RFL_DEBUG;
const char *lm = Args->CheckValue("-lightmethod");
if (lm != NULL)
{
if (!stricmp(lm, "deferred") && gl.lightmethod == LM_DIRECT) gl.lightmethod = LM_DEFERRED;
}
lm = Args->CheckValue("-buffermethod");
if (lm != NULL)
{
if (!stricmp(lm, "deferred") && gl.buffermethod == BM_PERSISTENT) gl.buffermethod = BM_DEFERRED;
}
}
int v;
if (!gl.legacyMode && !(gl.flags & RFL_SHADER_STORAGE_BUFFER))
{
glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, &v);
gl.maxuniforms = v;
glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &v);
gl.maxuniformblock = v;
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &v);
gl.uniformblockalignment = v;
}
else
{
gl.maxuniforms = 0;
gl.maxuniformblock = 0;
gl.uniformblockalignment = 0;
}
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &gl.max_texturesize);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
if (gl.legacyMode)
{
// fudge a bit with the framebuffer stuff to avoid redundancies in the main code. Some of the older cards do not have the ARB stuff but the calls are nearly identical.
FUDGE_FUNC(glGenerateMipmap, EXT);
FUDGE_FUNC(glGenFramebuffers, EXT);
FUDGE_FUNC(glBindFramebuffer, EXT);
FUDGE_FUNC(glDeleteFramebuffers, EXT);
FUDGE_FUNC(glFramebufferTexture2D, EXT);
FUDGE_FUNC(glGenerateMipmap, EXT);
FUDGE_FUNC(glGenFramebuffers, EXT);
FUDGE_FUNC(glBindFramebuffer, EXT);
FUDGE_FUNC(glDeleteFramebuffers, EXT);
FUDGE_FUNC(glFramebufferTexture2D, EXT);
FUDGE_FUNC(glFramebufferRenderbuffer, EXT);
FUDGE_FUNC(glGenRenderbuffers, EXT);
FUDGE_FUNC(glDeleteRenderbuffers, EXT);
FUDGE_FUNC(glRenderbufferStorage, EXT);
FUDGE_FUNC(glBindRenderbuffer, EXT);
FUDGE_FUNC(glCheckFramebufferStatus, EXT);
gl_PatchMenu();
}
}
//==========================================================================
//
//
//
//==========================================================================
void gl_PrintStartupLog()
{
int v = 0;
if (!gl.legacyMode) glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &v);
Printf ("GL_VENDOR: %s\n", glGetString(GL_VENDOR));
Printf ("GL_RENDERER: %s\n", glGetString(GL_RENDERER));
Printf ("GL_VERSION: %s (%s profile)\n", glGetString(GL_VERSION), (v & GL_CONTEXT_CORE_PROFILE_BIT)? "Core" : "Compatibility");
Printf ("GL_SHADING_LANGUAGE_VERSION: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
Printf (PRINT_LOG, "GL_EXTENSIONS:");
for (unsigned i = 0; i < m_Extensions.Size(); i++)
{
Printf(PRINT_LOG, " %s", m_Extensions[i].GetChars());
}
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &v);
Printf("\nMax. texture size: %d\n", v);
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &v);
Printf ("Max. texture units: %d\n", v);
glGetIntegerv(GL_MAX_VARYING_FLOATS, &v);
Printf ("Max. varying: %d\n", v);
if (!gl.legacyMode && !(gl.flags & RFL_SHADER_STORAGE_BUFFER))
{
glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &v);
Printf ("Max. uniform block size: %d\n", v);
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &v);
Printf ("Uniform block alignment: %d\n", v);
}
if (gl.flags & RFL_SHADER_STORAGE_BUFFER)
{
glGetIntegerv(GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS, &v);
Printf("Max. combined shader storage blocks: %d\n", v);
glGetIntegerv(GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS, &v);
Printf("Max. vertex shader storage blocks: %d\n", v);
}
// For shader-less, the special alphatexture translation must be changed to actually set the alpha, because it won't get translated by a shader.
if (gl.legacyMode)
{
FRemapTable *remap = translationtables[TRANSLATION_Standard][8];
for (int i = 0; i < 256; i++)
{
remap->Remap[i] = i;
remap->Palette[i] = PalEntry(i, 255, 255, 255);
}
}
}
| Java |
/*******************************************************************************
* Copyright (c) 2008, 2010 Xuggle Inc. All rights reserved.
*
* This file is part of Xuggle-Utils.
*
* Xuggle-Utils is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Xuggle-Utils 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 for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Xuggle-Utils. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
/**
* Provides convenience methods for registering, and
* special implementations of,
* {@link com.xuggle.utils.event.IEventHandler}.
* <p>
* There are certain types of {@link com.xuggle.utils.event.IEventHandler}
* implementations that are very common. For example, sometimes
* you want to forward an event from one
* {@link com.xuggle.utils.event.IEventDispatcher}
* to another.
* Sometimes you only want
* a {@link com.xuggle.utils.event.IEventHandler} to execute if the
* {@link com.xuggle.utils.event.IEvent#getSource()} is equal to
* a given source.
* Sometimes you only
* want to handler to execute a maximum number of times.
* </p>
* <p>
* This class tries to provide some of those implementations for you.
* </p>
* <p>
* Use the {@link com.xuggle.utils.event.handler.Handler} class to find
* Factory methods for the special handlers you want.
* </p>
* @see com.xuggle.utils.event.handler.Handler
*
*/
package com.xuggle.utils.event.handler;
| Java |
class CreatePasswords < ActiveRecord::Migration
def change
create_table :passwords do |p|
p.string :url
p.string :user
p.string :password
#p.timestamps null: false
end
end
end
| Java |
module Hazel.StringWriter where
import Control.Monad.State
------------- StringState -------------
type StringState = State String (Maybe Bool)
eval :: StringState -> String
eval s = execState s ""
newLine :: StringState
append :: String -> StringState
apply :: (String -> String) -> StringState
newLine = append "\n"
append s = apply (++s)
apply f = get >>= put.(f$) >> return (Just True)
--newLine :: StringState
--newLine = do
-- t <- get
-- put $ t++"\n"
-- return True
-- get >>= put.(++"\n") >>= return True
--append :: String -> StringState
--append s = do
-- t <- get
-- put $ t++s
-- return True
-- get >>= put.(++s) >>= return True
--modify :: (String -> String) -> StringState
--modify f = do
-- t <- get
-- put $ f t
-- return True
| Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>无聊站点</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta property="og:type" content="website">
<meta property="og:title" content="无聊站点">
<meta property="og:url" content="http://wangdongustc.com/index.html">
<meta property="og:site_name" content="无聊站点">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="Darren Wang">
<meta name="twitter:card" content="summary">
<link rel="alternate" href="/atom.xml" title="无聊站点" type="application/atom+xml">
<link rel="shortcut icon" href="/favicon.png">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">
<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="/fancybox/jquery.fancybox.min.css">
<meta name="generator" content="Hexo 5.4.0"></head>
<body>
<div id="container">
<div id="wrap">
<header id="header">
<div id="banner"></div>
<div id="header-outer" class="outer">
<div id="header-title" class="inner">
<h1 id="logo-wrap">
<a href="/" id="logo">无聊站点</a>
</h1>
<h2 id="subtitle-wrap">
<a href="/" id="subtitle">王汪汪同学的博客</a>
</h2>
</div>
<div id="header-inner" class="inner">
<nav id="main-nav">
<a id="main-nav-toggle" class="nav-icon"></a>
<a class="main-nav-link" href="/">Home</a>
<a class="main-nav-link" href="/archives">Archives</a>
</nav>
<nav id="sub-nav">
<a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
<a id="nav-search-btn" class="nav-icon" title="Suche"></a>
</nav>
<div id="search-form-wrap">
<form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Suche"><button type="submit" class="search-form-submit"></button><input type="hidden" name="sitesearch" value="http://wangdongustc.com"></form>
</div>
</div>
</div>
</header>
<div class="outer">
<section id="main">
<article id="post-hello-world" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
<div class="article-meta">
<a href="/2021/04/24/15/46/04" class="article-date">
<time class="dt-published" datetime="2021-04-24T15:46:04.791Z" itemprop="datePublished">2021-04-24</time>
</a>
</div>
<div class="article-inner">
<header class="article-header">
<h1 itemprop="name">
<a class="p-name article-title" href="/2021/04/24/15/46/04">Hello World</a>
</h1>
</header>
<div class="e-content article-entry" itemprop="articleBody">
<p>Welcome to <a target="_blank" rel="noopener" href="https://hexo.io/">Hexo</a>! This is your very first post. Check <a target="_blank" rel="noopener" href="https://hexo.io/docs/">documentation</a> for more info. If you get any problems when using Hexo, you can find the answer in <a target="_blank" rel="noopener" href="https://hexo.io/docs/troubleshooting.html">troubleshooting</a> or you can ask me on <a target="_blank" rel="noopener" href="https://github.com/hexojs/hexo/issues">GitHub</a>.</p>
<h2 id="Quick-Start"><a href="#Quick-Start" class="headerlink" title="Quick Start"></a>Quick Start</h2><h3 id="Create-a-new-post"><a href="#Create-a-new-post" class="headerlink" title="Create a new post"></a>Create a new post</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ hexo new <span class="string">"My New Post"</span></span><br></pre></td></tr></table></figure>
<p>More info: <a target="_blank" rel="noopener" href="https://hexo.io/docs/writing.html">Writing</a></p>
<h3 id="Run-server"><a href="#Run-server" class="headerlink" title="Run server"></a>Run server</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ hexo server</span><br></pre></td></tr></table></figure>
<p>More info: <a target="_blank" rel="noopener" href="https://hexo.io/docs/server.html">Server</a></p>
<h3 id="Generate-static-files"><a href="#Generate-static-files" class="headerlink" title="Generate static files"></a>Generate static files</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ hexo generate</span><br></pre></td></tr></table></figure>
<p>More info: <a target="_blank" rel="noopener" href="https://hexo.io/docs/generating.html">Generating</a></p>
<h3 id="Deploy-to-remote-sites"><a href="#Deploy-to-remote-sites" class="headerlink" title="Deploy to remote sites"></a>Deploy to remote sites</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ hexo deploy</span><br></pre></td></tr></table></figure>
<p>More info: <a target="_blank" rel="noopener" href="https://hexo.io/docs/one-command-deployment.html">Deployment</a></p>
</div>
<footer class="article-footer">
<a data-url="http://wangdongustc.com/2021/04/24/15/46/04" data-id="cknvx0bpn000098nh83v3hvss" data-title="Hello World" class="article-share-link">Teilen</a>
</footer>
</div>
</article>
</section>
<aside id="sidebar">
<div class="widget-wrap">
<h3 class="widget-title">Archiv</h3>
<div class="widget">
<ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/04/">四月 2021</a></li></ul>
</div>
</div>
<div class="widget-wrap">
<h3 class="widget-title">letzter Beitrag</h3>
<div class="widget">
<ul>
<li>
<a href="/2021/04/24/15/46/04">Hello World</a>
</li>
</ul>
</div>
</div>
</aside>
</div>
<footer id="footer">
<div class="outer">
<div id="footer-info" class="inner">
© 2021 Darren Wang<br>
Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
</div>
</div>
</footer>
</div>
<nav id="mobile-nav">
<a href="/" class="mobile-nav-link">Home</a>
<a href="/archives" class="mobile-nav-link">Archives</a>
</nav>
<script src="/js/jquery-3.4.1.min.js"></script>
<script src="/fancybox/jquery.fancybox.min.js"></script>
<script src="/js/script.js"></script>
</div>
</body>
</html> | Java |
{% extends 'bs3/base_wo_cms_toolbar.html' %}
{% load cms_tags sekizai_tags i18n l10n repanier_tags %}
{% block base_content %}
<div class="container-repanier">
<div class="container">
{# {% debug %} #}
<h4>{{ producer.long_profile_name }}</h4>
{% if object %}
<h4><span class="glyphicon glyphicon-log-out" aria-hidden="true"></span> {% translate "Previous balance" %} : {{ object.get_negative_previous_balance }}
<small>({{ object.date_previous_balance | date:"DATE_FORMAT" }})</small><br></h4>
{% endif %}
{% if offer_item_set %}
<span class="glyphicon glyphicon-minus" aria-hidden="true"></span> {% translate "Purchases" %} {{ object.permanence }} : {{ object.get_total_price_with_tax }}
{% if object.get_total_vat != 0 or object.get_total_deposit != 0 or object.delta_transport != 0 %}
<small>
. {% translate "This price include" %} <span class="glyphicon glyphicon-arrow-right"></span>
{% if object.get_total_vat != 0 %}{% translate "VAT" %} : {{ object.get_total_vat }}{% endif %}
{% if object.get_total_deposit != 0 %}
{% if object.get_total_vat != 0 %}; {% endif %}
{% translate "Deposit" %} : {{ object.get_total_deposit }}
{% endif %}
{% if object.delta_transport != 0 %}
{% if object.get_total_vat != 0 or object.get_total_deposit != 0 %}; {% endif %}
{% translate "Shipping cost" %} : {{ object.delta_transport }}
{% endif %}
</small>
<br>
{% if object.delta_price_with_tax != 0 %}
{% if object.delta_price_with_tax < 0 %}{% translate "Reduction granted" %}{% else %}{% translate "Surcharge" %}{% endif %} : {{ object.get_abs_delta_price_with_tax }}<br>
{% endif %}
{% endif %}
{% endif %}
{% for bank_account in bank_account_set %}
{% if bank_account.bank_amount_in != 0 %}
<span class="glyphicon glyphicon-minus" aria-hidden="true"></span> {% translate "Provision" %} :
{% if bank_account.operation_comment %}
{{ bank_account.operation_comment }}
{% else %}
{% translate "Refund" %}
{% endif %} : {{ bank_account.bank_amount_in }}
<small>({{ bank_account.operation_date | date:"DATE_FORMAT" }})</small><br>
{% endif %}
{% if bank_account.bank_amount_out != 0 %}
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> {% translate "Refund" %} :
{% if bank_account.operation_comment %}
{{ bank_account.operation_comment }}
{% else %}
{% translate "Payment" %}
{% endif %} : {{ bank_account.bank_amount_out }}
<small>({{ bank_account.operation_date | date:"DATE_FORMAT" }})</small><br>
{% endif %}
{% endfor %}
<div class="panel">
{% if object %}
<h4><span class="glyphicon glyphicon-log-in" aria-hidden="true"></span> {% translate "New balance" %} : {{ object.get_negative_balance }}
<small>({{ object.date_balance | date:"DATE_FORMAT" }}{% if not next_producer_invoice_id and object.invoice_sort_order %} - {% translate "last sale" %}{% endif %})</small>
</h4>
{% else %}
<h4><span class="glyphicon glyphicon-log-in" aria-hidden="true"></span> {% translate "New balance" %} : {{ producer.get_negative_balance }}
<small>({{ producer.date_balance | date:"DATE_FORMAT" }}{% if not next_producer_invoice_id %} - {% translate "last sale" %}{% endif %})</small>
</h4>
{% endif %}
<span id="basket_message">{{ basket_message }}</span>
</div>
<center>
<div class="btn-group">
{% if previous_producer_invoice_id %}
<a href="{% if uuid %}{% url 'repanier:producer_invoice_uuid_view' previous_producer_invoice_id uuid %}{% else %}{% url 'repanier:producer_invoice_view' previous_producer_invoice_id %}?producer={{ object.producer.id }}{% endif %}"
class="btn btn-info btn-disabled"> <span class="glyphicon glyphicon-arrow-left"></span> </a>
{% endif %}
{% if next_producer_invoice_id %}
<a href="{% if uuid %}{% url 'repanier:producer_invoice_uuid_view' 0 uuid %}{% else %}{% url 'repanier:producer_invoice_view' 0 %}?producer={{ object.producer.id }}{% endif %}"
class="btn btn-disabled"> {% translate "Invoice" %} </a>
{% else %}
<span class="btn btn-disabled">{% translate "Invoice" %}</span>
{% endif %}
{% if next_producer_invoice_id %}
<a href="
{% if uuid %}{% url 'repanier:producer_invoice_uuid_view' next_producer_invoice_id uuid %}{% else %}{% url 'repanier:producer_invoice_view' next_producer_invoice_id %}?producer={{ object.producer.id }}{% endif %}"
class="btn btn-info btn-disabled"> <span class="glyphicon glyphicon-arrow-right"></span> </a>
{% endif %}
</div>
</center>
{% if offer_item_set %}
<br>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>
{% translate "Reference" %}
</th>
<th>
{% translate "Product" %}
</th>
<th>
{% translate "Qty" %}
</th>
<th>
{% translate "Unit price" %}
</th>
<th>
{% translate "Total price" %}
</th>
<tr>
</thead>
<tbody>
{% for offer_item in offer_item_set %}
<tr>
<td>
{% if offer_item.reference|length < 36 %}
{{ offer_item.reference }}
{% endif %}
</td>
<td>
{{ offer_item.get_long_name_with_producer_price }}
</td>
<td align="right">
{{ offer_item.quantity_invoiced }}
</td>
<td align="right">
{{ offer_item.get_producer_unit_price_invoiced }}{% if offer_item.unit_deposit != 0 %}, ♻ {{ offer_item.unit_deposit }}{% endif %}
</td>
<td align="right">
{{ offer_item.get_producer_row_price_invoiced }}
</td>
<tr>
{% endfor %}
</tbody>
</table>
{% else %}
<h4>{% translate "No purchase found" %}</h4>
{% endif %}
</div>
</div>
<div class="hidden-xs">
<br>
</div>
{% addtoblock "lastjs" %}
<script>
$(document).ready(function () {
lien = '{% url 'repanier:order_name' %}';
$.ajax({
url: lien,
cache: false,
async: false,
success: function (result) {
$.each(result, function (key, val) {
$(key).html(val);
});
}
{# success: function (result) {#}
{# $("#my_name").html(result);#}
{# },#}
{# error: function (result) {#}
{# $("#my_name").html("{% translate "Retry5" %}");#}
{# }#}
});
});
</script>
{% endaddtoblock %}
{% addtoblock "lastjs" %}
{% if not next_producer_invoice_id %}
<script>
$(document).ready(function () {
var lien = '{% url 'repanier:producer_basket_message_form_ajax' producer.id producer.uuid %}';
$.ajax({
url: lien,
cache: false,
dataType: 'json',
async: true,
success: function (result) {
$.each(result, function (key, val) {
$(key).html(val);
});
}
{# success: function (result) {#}
{# $.each(result, function (key, val) {#}
{# $(val.id).html(val.html);#}
{# });#}
{# },#}
{# error: function (result) {#}
{# $("#basket_message").html("{% translate "Retry" %}");#}
{# }#}
});
});
</script>
{% endif %}
{% endaddtoblock %}
{% endblock %} | Java |
/*
Copyright (c) 1993-2008, Cognitive Technologies
All rights reserved.
Разрешается повторное распространение и использование как в виде исходного кода,
так и в двоичной форме, с изменениями или без, при соблюдении следующих условий:
* При повторном распространении исходного кода должны оставаться указанное
выше уведомление об авторском праве, этот список условий и последующий
отказ от гарантий.
* При повторном распространении двоичного кода в документации и/или в
других материалах, поставляемых при распространении, должны сохраняться
указанная выше информация об авторском праве, этот список условий и
последующий отказ от гарантий.
* Ни название Cognitive Technologies, ни имена ее сотрудников не могут
быть использованы в качестве средства поддержки и/или продвижения
продуктов, основанных на этом ПО, без предварительного письменного
разрешения.
ЭТА ПРОГРАММА ПРЕДОСТАВЛЕНА ВЛАДЕЛЬЦАМИ АВТОРСКИХ ПРАВ И/ИЛИ ДРУГИМИ ЛИЦАМИ "КАК
ОНА ЕСТЬ" БЕЗ КАКОГО-ЛИБО ВИДА ГАРАНТИЙ, ВЫРАЖЕННЫХ ЯВНО ИЛИ ПОДРАЗУМЕВАЕМЫХ,
ВКЛЮЧАЯ ГАРАНТИИ КОММЕРЧЕСКОЙ ЦЕННОСТИ И ПРИГОДНОСТИ ДЛЯ КОНКРЕТНОЙ ЦЕЛИ, НО НЕ
ОГРАНИЧИВАЯСЬ ИМИ. НИ ВЛАДЕЛЕЦ АВТОРСКИХ ПРАВ И НИ ОДНО ДРУГОЕ ЛИЦО, КОТОРОЕ
МОЖЕТ ИЗМЕНЯТЬ И/ИЛИ ПОВТОРНО РАСПРОСТРАНЯТЬ ПРОГРАММУ, НИ В КОЕМ СЛУЧАЕ НЕ
НЕСЁТ ОТВЕТСТВЕННОСТИ, ВКЛЮЧАЯ ЛЮБЫЕ ОБЩИЕ, СЛУЧАЙНЫЕ, СПЕЦИАЛЬНЫЕ ИЛИ
ПОСЛЕДОВАВШИЕ УБЫТКИ, СВЯЗАННЫЕ С ИСПОЛЬЗОВАНИЕМ ИЛИ ПОНЕСЕННЫЕ ВСЛЕДСТВИЕ
НЕВОЗМОЖНОСТИ ИСПОЛЬЗОВАНИЯ ПРОГРАММЫ (ВКЛЮЧАЯ ПОТЕРИ ДАННЫХ, ИЛИ ДАННЫЕ,
СТАВШИЕ НЕГОДНЫМИ, ИЛИ УБЫТКИ И/ИЛИ ПОТЕРИ ДОХОДОВ, ПОНЕСЕННЫЕ ИЗ-ЗА ДЕЙСТВИЙ
ТРЕТЬИХ ЛИЦ И/ИЛИ ОТКАЗА ПРОГРАММЫ РАБОТАТЬ СОВМЕСТНО С ДРУГИМИ ПРОГРАММАМИ,
НО НЕ ОГРАНИЧИВАЯСЬ ЭТИМИ СЛУЧАЯМИ), НО НЕ ОГРАНИЧИВАЯСЬ ИМИ, ДАЖЕ ЕСЛИ ТАКОЙ
ВЛАДЕЛЕЦ ИЛИ ДРУГОЕ ЛИЦО БЫЛИ ИЗВЕЩЕНЫ О ВОЗМОЖНОСТИ ТАКИХ УБЫТКОВ И ПОТЕРЬ.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* 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.
* Neither the name of the Cognitive Technologies 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.
*/
#include <stdio.h>
/* interface my */
#include "gystogra.h"
/* interface our util */
#include "skew1024.h"
using namespace cf;
/*---------------------------------------------------------------------------*/
Bool MakeTopBotGysts(Rect16 *pRc, int nRc, int32_t Skew, int MaxSize,
Un_GYST *pBegGt, Un_GYST *pEndGt) {
int MinBeg, MaxBeg, MinEnd, MaxEnd, i, End;
long dy, ddy;
int32_t x, yBeg, yEnd;
int32_t SkewSquar;
int *pBegSig, *pEndSig;
SkewSquar = Skew * Skew;
pBegGt->nElem = nRc;
pEndGt->nElem = nRc;
pBegSig = pBegGt->Signal;
pEndSig = pEndGt->Signal;
/* Предельные значения проекций */
x = (pRc[0].left + pRc[0].right + 1) / 2;
dy = ((-Skew * x + 0x200) >> 10);
yBeg = pRc[0].top;
yEnd = pRc[0].bottom;
ddy = ((SkewSquar * yBeg + 0x100000) >> 21);
yBeg += dy;
yBeg -= ddy;
ddy = ((SkewSquar * yEnd + 0x100000) >> 21);
yEnd += dy;
yEnd -= ddy;
MinBeg = yBeg;
MaxBeg = yBeg;
MinEnd = yEnd;
MaxEnd = yEnd;
for (i = 1; i < nRc; i++) {
x = (pRc[i].left + pRc[i].right + 1) / 2;
dy = ((-Skew * x + 0x200) >> 10);
yBeg = pRc[i].top;
yEnd = pRc[i].bottom;
ddy = ((SkewSquar * yBeg + 0x100000) >> 21);
yBeg += dy;
yBeg -= ddy;
ddy = ((SkewSquar * yEnd + 0x100000) >> 21);
yEnd += dy;
yEnd -= ddy;
if (MinBeg > yBeg)
MinBeg = yBeg;
if (MaxBeg < yBeg)
MaxBeg = yBeg;
if (MinEnd > yEnd)
MinEnd = yEnd;
if (MaxEnd < yEnd)
MaxEnd = yEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
pBegGt->Shift = MinBeg;
pBegGt->End = MaxBeg - MinBeg;
pEndGt->Shift = MinEnd;
pEndGt->End = MaxEnd - MinEnd;
End = pBegGt->End;
if (End < pEndGt->End)
End = pEndGt->End;
for (i = 0; i <= End; i++) {
pBegSig[i] = 0;
pEndSig[i] = 0;
}
for (i = 0; i < nRc; i++) {
x = (pRc[i].left + pRc[i].right + 1) / 2;
dy = ((-Skew * x + 0x200) >> 10);
yBeg = pRc[i].top;
yEnd = pRc[i].bottom;
ddy = ((SkewSquar * yBeg + 0x100000) >> 21);
yBeg += dy;
yBeg -= ddy;
ddy = ((SkewSquar * yEnd + 0x100000) >> 21);
yEnd += dy;
yEnd -= ddy;
pBegSig[yBeg - MinBeg]++;
pEndSig[yEnd - MinEnd]++;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
Bool MakeLefRigGysts(Rect16 *pRc, int nRc, int32_t Skew, int MaxSize,
Un_GYST *pBegGt, Un_GYST *pEndGt) {
int MinBeg, MaxBeg, MinEnd, MaxEnd, i, End;
long dx, ddx;
int32_t y, xBeg, xEnd;
int32_t SkewSquar;
int *pBegSig, *pEndSig;
SkewSquar = Skew * Skew;
pBegGt->nElem = nRc;
pEndGt->nElem = nRc;
pBegSig = pBegGt->Signal;
pEndSig = pEndGt->Signal;
/* Предельные значения проекций */
y = (pRc[0].top + pRc[0].bottom + 1) / 2;
dx = ((-Skew * y + 0x200) >> 10);
xBeg = pRc[0].left;
xEnd = pRc[0].right;
ddx = ((SkewSquar * xBeg + 0x100000) >> 21);
xBeg -= dx;
xBeg -= ddx;
ddx = ((SkewSquar * xEnd + 0x100000) >> 21);
xEnd -= dx;
xEnd -= ddx;
MinBeg = xBeg;
MaxBeg = xBeg;
MinEnd = xEnd;
MaxEnd = xEnd;
for (i = 1; i < nRc; i++) {
y = (pRc[i].top + pRc[i].bottom + 1) / 2;
dx = ((-Skew * y + 0x200) >> 10);
xBeg = pRc[i].left;
xEnd = pRc[i].right;
ddx = ((SkewSquar * xBeg + 0x100000) >> 21);
xBeg -= dx;
xBeg -= ddx;
ddx = ((SkewSquar * xEnd + 0x100000) >> 21);
xEnd -= dx;
xEnd -= ddx;
if (MinBeg > xBeg)
MinBeg = xBeg;
if (MaxBeg < xBeg)
MaxBeg = xBeg;
if (MinEnd > xEnd)
MinEnd = xEnd;
if (MaxEnd < xEnd)
MaxEnd = xEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
pBegGt->Shift = MinBeg;
pBegGt->End = MaxBeg - MinBeg;
pEndGt->Shift = MinEnd;
pEndGt->End = MaxEnd - MinEnd;
End = pBegGt->End;
if (End < pEndGt->End)
End = pEndGt->End;
for (i = 0; i <= End; i++) {
pBegSig[i] = 0;
pEndSig[i] = 0;
}
for (i = 0; i < nRc; i++) {
y = (pRc[i].top + pRc[i].bottom + 1) / 2;
dx = ((-Skew * y + 0x200) >> 10);
xBeg = pRc[i].left;
xEnd = pRc[i].right;
ddx = ((SkewSquar * xBeg + 0x100000) >> 21);
xBeg -= dx;
xBeg -= ddx;
ddx = ((SkewSquar * xEnd + 0x100000) >> 21);
xEnd -= dx;
xEnd -= ddx;
pBegSig[xBeg - MinBeg]++;
pEndSig[xEnd - MinEnd]++;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
Bool MakeTopMidBotGysts(Rect16 *pRc, int nRc, int32_t Skew, int MaxSize,
Un_GYST *pBegGt, Un_GYST *pMidGt, Un_GYST *pEndGt) {
int MinBeg, MaxBeg, MinMid, MaxMid, MinEnd, MaxEnd, i, End;
long dy, ddy;
int32_t x, yBeg, yMid, yEnd;
int32_t SkewSquar;
int *pBegSig, *pMidSig, *pEndSig;
SkewSquar = Skew * Skew;
pBegGt->nElem = nRc;
pMidGt->nElem = nRc;
pEndGt->nElem = nRc;
pBegSig = pBegGt->Signal;
pMidSig = pMidGt->Signal;
pEndSig = pEndGt->Signal;
/* Предельные значения проекций */
x = (pRc[0].left + pRc[0].right + 1) / 2;
dy = ((-Skew * x + 0x200) >> 10);
yBeg = pRc[0].top;
yMid = (pRc[0].top + pRc[0].bottom + 1) / 2;
yEnd = pRc[0].bottom;
ddy = ((SkewSquar * yBeg + 0x100000) >> 21);
yBeg += dy;
yBeg -= ddy;
ddy = ((SkewSquar * yMid + 0x100000) >> 21);
yMid += dy;
yMid -= ddy;
ddy = ((SkewSquar * yEnd + 0x100000) >> 21);
yEnd += dy;
yEnd -= ddy;
MinBeg = yBeg;
MaxBeg = yBeg;
MinMid = yMid;
MaxMid = yMid;
MinEnd = yEnd;
MaxEnd = yEnd;
for (i = 1; i < nRc; i++) {
x = (pRc[i].left + pRc[i].right + 1) / 2;
dy = ((-Skew * x + 0x200) >> 10);
yBeg = pRc[i].top;
yMid = (pRc[i].top + pRc[i].bottom + 1) / 2;
yEnd = pRc[i].bottom;
ddy = ((SkewSquar * yBeg + 0x100000) >> 21);
yBeg += dy;
yBeg -= ddy;
ddy = ((SkewSquar * yMid + 0x100000) >> 21);
yMid += dy;
yMid -= ddy;
ddy = ((SkewSquar * yEnd + 0x100000) >> 21);
yEnd += dy;
yEnd -= ddy;
if (MinBeg > yBeg)
MinBeg = yBeg;
if (MaxBeg < yBeg)
MaxBeg = yBeg;
if (MinMid > yMid)
MinMid = yMid;
if (MaxMid < yMid)
MaxMid = yMid;
if (MinEnd > yEnd)
MinEnd = yEnd;
if (MaxEnd < yEnd)
MaxEnd = yEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxMid - MinMid >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
pBegGt->Shift = MinBeg;
pBegGt->End = MaxBeg - MinBeg;
pMidGt->Shift = MinMid;
pMidGt->End = MaxMid - MinMid;
pEndGt->Shift = MinEnd;
pEndGt->End = MaxEnd - MinEnd;
End = pBegGt->End;
if (End < pMidGt->End)
End = pMidGt->End;
if (End < pEndGt->End)
End = pEndGt->End;
for (i = 0; i <= End; i++) {
pBegSig[i] = 0;
pMidSig[i] = 0;
pEndSig[i] = 0;
}
for (i = 0; i < nRc; i++) {
x = (pRc[i].left + pRc[i].right + 1) / 2;
dy = ((-Skew * x + 0x200) >> 10);
yBeg = pRc[i].top;
yMid = (pRc[i].top + pRc[i].bottom + 1) / 2;
yEnd = pRc[i].bottom;
ddy = ((SkewSquar * yBeg + 0x100000) >> 21);
yBeg += dy;
yBeg -= ddy;
ddy = ((SkewSquar * yMid + 0x100000) >> 21);
yMid += dy;
yMid -= ddy;
ddy = ((SkewSquar * yEnd + 0x100000) >> 21);
yEnd += dy;
yEnd -= ddy;
pBegSig[yBeg - MinBeg]++;
pMidSig[yMid - MinMid]++;
pEndSig[yEnd - MinEnd]++;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
Bool MakeLefMidRigGysts(Rect16 *pRc, int nRc, int32_t Skew, int MaxSize,
Un_GYST *pBegGt, Un_GYST *pMidGt, Un_GYST *pEndGt) {
int MinBeg, MaxBeg, MinMid, MaxMid, MinEnd, MaxEnd, i, End;
long dx, ddx;
int32_t y, xBeg, xMid, xEnd;
int32_t SkewSquar;
int *pBegSig, *pMidSig, *pEndSig;
SkewSquar = Skew * Skew;
pBegGt->nElem = nRc;
pMidGt->nElem = nRc;
pEndGt->nElem = nRc;
pBegSig = pBegGt->Signal;
pMidSig = pMidGt->Signal;
pEndSig = pEndGt->Signal;
/* Предельные значения проекций */
y = (pRc[0].top + pRc[0].bottom + 1) / 2;
dx = ((-Skew * y + 0x200) >> 10);
xBeg = pRc[0].left;
xMid = (pRc[0].left + pRc[0].right + 1) / 2;
xEnd = pRc[0].right;
ddx = ((SkewSquar * xBeg + 0x100000) >> 21);
xBeg -= dx;
xBeg -= ddx;
ddx = ((SkewSquar * xMid + 0x100000) >> 21);
xMid -= dx;
xMid -= ddx;
ddx = ((SkewSquar * xEnd + 0x100000) >> 21);
xEnd -= dx;
xEnd -= ddx;
MinBeg = xBeg;
MaxBeg = xBeg;
MinMid = xMid;
MaxMid = xMid;
MinEnd = xEnd;
MaxEnd = xEnd;
for (i = 1; i < nRc; i++) {
y = (pRc[i].top + pRc[i].bottom + 1) / 2;
dx = ((-Skew * y + 0x200) >> 10);
xBeg = pRc[i].left;
xMid = (pRc[i].left + pRc[i].right + 1) / 2;
xEnd = pRc[i].right;
ddx = ((SkewSquar * xBeg + 0x100000) >> 21);
xBeg -= dx;
xBeg -= ddx;
ddx = ((SkewSquar * xMid + 0x100000) >> 21);
xMid -= dx;
xMid -= ddx;
ddx = ((SkewSquar * xEnd + 0x100000) >> 21);
xEnd -= dx;
xEnd -= ddx;
if (MinBeg > xBeg)
MinBeg = xBeg;
if (MaxBeg < xBeg)
MaxBeg = xBeg;
if (MinMid > xMid)
MinMid = xMid;
if (MaxMid < xMid)
MaxMid = xMid;
if (MinEnd > xEnd)
MinEnd = xEnd;
if (MaxEnd < xEnd)
MaxEnd = xEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxMid - MinMid >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
pBegGt->Shift = MinBeg;
pBegGt->End = MaxBeg - MinBeg;
pMidGt->Shift = MinMid;
pMidGt->End = MaxMid - MinMid;
pEndGt->Shift = MinEnd;
pEndGt->End = MaxEnd - MinEnd;
End = pBegGt->End;
if (End < pMidGt->End)
End = pMidGt->End;
if (End < pEndGt->End)
End = pEndGt->End;
for (i = 0; i <= End; i++) {
pBegSig[i] = 0;
pMidSig[i] = 0;
pEndSig[i] = 0;
}
for (i = 0; i < nRc; i++) {
y = (pRc[i].top + pRc[i].bottom + 1) / 2;
dx = ((-Skew * y + 0x200) >> 10);
xBeg = pRc[i].left;
xMid = (pRc[i].left + pRc[i].right + 1) / 2;
xEnd = pRc[i].right;
ddx = ((SkewSquar * xBeg + 0x100000) >> 21);
xBeg -= dx;
xBeg -= ddx;
ddx = ((SkewSquar * xMid + 0x100000) >> 21);
xMid -= dx;
xMid -= ddx;
ddx = ((SkewSquar * xEnd + 0x100000) >> 21);
xEnd -= dx;
xEnd -= ddx;
pBegSig[xBeg - MinBeg]++;
pMidSig[xMid - MinMid]++;
pEndSig[xEnd - MinEnd]++;
}
return TRUE;
}
int ScoreComp(const Rect16 *pRcReg, const int32_t Skew, const Rect16 *pRc,
const int nRc) {
int i, k;
Point PosIdeal;
k = 0;
for (i = 0; i < nRc; i++) {
if (pRc[i].right - pRc[i].left < 2)
continue;
if (pRc[i].right - pRc[i].left > 100)
continue;
if (pRc[i].bottom - pRc[i].top < 2)
continue;
if (pRc[i].bottom - pRc[i].top > 100)
continue;
PosIdeal.rx() = (int) (.5 * (pRc[i].left + pRc[i].right + 1));
PosIdeal.ry() = (int) (.5 * (pRc[i].top + pRc[i].bottom + 1));
PosIdeal.deskew(-Skew);
if (PosIdeal.x() > pRcReg->right)
continue;
if (PosIdeal.x() < pRcReg->left)
continue;
if (PosIdeal.y() > pRcReg->bottom)
continue;
if (PosIdeal.y() < pRcReg->top)
continue;
k++;
}
return k;
}
/*---------------------------------------------------------------------------*/
void MakeNormVertGyst(const Rect16 *pRcReg, const int32_t Skew,
const Rect16 *pRc, const int nRc, int *Sig) {
int i, k;
Point BegDirIdeal;
Point EndDirIdeal;
for (i = 0; i < nRc; i++) {
if (pRc[i].right - pRc[i].left < 2)
continue;
if (pRc[i].right - pRc[i].left > 100)
continue;
if (pRc[i].bottom - pRc[i].top < 2)
continue;
if (pRc[i].bottom - pRc[i].top > 100)
continue;
BegDirIdeal.rx() = (int) (.5 * (pRc[i].left + pRc[i].right + 1));
BegDirIdeal.ry() = pRc[i].top;
BegDirIdeal.deskew(-Skew);
if (BegDirIdeal.x() > pRcReg->right)
continue;
if (BegDirIdeal.x() < pRcReg->left)
continue;
if (BegDirIdeal.y() >= pRcReg->bottom)
continue;
if (BegDirIdeal.y() < pRcReg->top)
BegDirIdeal.ry() = pRcReg->top;
EndDirIdeal.rx() = (int) (.5 * (pRc[i].left + pRc[i].right + 1));
EndDirIdeal.ry() = pRc[i].bottom;
EndDirIdeal.deskew(-Skew);
if (EndDirIdeal.y() <= pRcReg->top)
continue;
if (EndDirIdeal.y() > pRcReg->bottom)
EndDirIdeal.ry() = pRcReg->bottom;
for (k = BegDirIdeal.y(); k <= EndDirIdeal.y(); k++)
Sig[k - pRcReg->top]++;
}
}
/*---------------------------------------------------------------------------*/
Bool MakeVertGysts(Rect16 *pRc, int nRc, int32_t Skew, int Amnist, int MaxSize,
Un_GYST *pVerGt, int *pWhatDo) {
int MinBeg, MaxBeg, MinEnd, MaxEnd, CurBeg, CurEnd, i, End, k, iFirst;
Point BegDirIdeal;
Point EndDirIdeal;
iFirst = -1;
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
iFirst = i;
break;
}
if (iFirst == -1)
return FALSE;
/* Предельные значения проекций */
BegDirIdeal.rx() = (int) (.5 * (pRc[iFirst].left + pRc[iFirst].right + 1));
BegDirIdeal.ry() = pRc[iFirst].top;
BegDirIdeal.deskew(-Skew);
MinBeg = BegDirIdeal.y();
MaxBeg = BegDirIdeal.y();
EndDirIdeal.rx() = (int) (.5 * (pRc[iFirst].left + pRc[iFirst].right + 1));
EndDirIdeal.ry() = pRc[iFirst].bottom;
EndDirIdeal.deskew(-Skew);
MinEnd = EndDirIdeal.y();
MaxEnd = EndDirIdeal.y();
for (i = iFirst + 1; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
BegDirIdeal.rx() = (int) (.5 * (pRc[i].left + pRc[i].right + 1));
BegDirIdeal.ry() = pRc[i].top;
BegDirIdeal.deskew(-Skew);
CurBeg = BegDirIdeal.y();
EndDirIdeal.rx() = (int) (.5 * (pRc[i].left + pRc[i].right + 1));
EndDirIdeal.ry() = pRc[i].bottom;
EndDirIdeal.deskew(-Skew);
CurEnd = EndDirIdeal.y();
if (MinBeg > CurBeg)
MinBeg = CurBeg;
if (MaxBeg < CurBeg)
MaxBeg = CurBeg;
if (MinEnd > CurEnd)
MinEnd = CurEnd;
if (MaxEnd < CurEnd)
MaxEnd = CurEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
if (MinBeg > MinEnd)
return FALSE;
if (MaxBeg > MaxEnd)
return FALSE;
pVerGt->Shift = MinBeg;
pVerGt->End = MaxEnd - MinBeg;
pVerGt->nElem = nRc;
End = pVerGt->End;
for (i = 0; i <= End; i++) {
pVerGt->Signal[i] = 0;
}
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
BegDirIdeal.rx() = (int) (.5 * (pRc[i].left + pRc[i].right + 1));
BegDirIdeal.ry() = pRc[i].top;
BegDirIdeal.deskew(-Skew);
CurBeg = BegDirIdeal.y();
EndDirIdeal.rx() = (int) (.5 * (pRc[i].left + pRc[i].right + 1));
EndDirIdeal.ry() = pRc[i].bottom;
EndDirIdeal.deskew(-Skew);
CurEnd = EndDirIdeal.y();
for (k = CurBeg + Amnist; k <= CurEnd - Amnist; k++)
pVerGt->Signal[k - MinBeg]++;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
void MakeNormHoriGyst(const Rect16 *pRcReg, const int32_t Skew,
const Rect16 *pRc, const int nRc, int *Sig) {
int i, k;
Point BegDirIdeal;
Point EndDirIdeal;
for (i = 0; i < nRc; i++) {
if (pRc[i].right - pRc[i].left < 2)
continue;
if (pRc[i].right - pRc[i].left > 100)
continue;
if (pRc[i].bottom - pRc[i].top < 2)
continue;
if (pRc[i].bottom - pRc[i].top > 100)
continue;
BegDirIdeal.rx() = pRc[i].left;
BegDirIdeal.ry() = (int) (.5 * (pRc[i].top + pRc[i].bottom + 1));
BegDirIdeal.deskew(-Skew);
if (BegDirIdeal.y() > pRcReg->bottom)
continue;
if (BegDirIdeal.y() < pRcReg->top)
continue;
if (BegDirIdeal.x() >= pRcReg->right)
continue;
if (BegDirIdeal.x() < pRcReg->left)
BegDirIdeal.rx() = pRcReg->left;
EndDirIdeal.rx() = pRc[i].right;
EndDirIdeal.ry() = (int) (.5 * (pRc[i].top + pRc[i].bottom + 1));
EndDirIdeal.deskew(-Skew);
if (EndDirIdeal.x() <= pRcReg->left)
continue;
if (EndDirIdeal.x() > pRcReg->right)
EndDirIdeal.rx() = pRcReg->right;
for (k = BegDirIdeal.x(); k <= EndDirIdeal.x(); k++)
Sig[k - pRcReg->left]++;
}
}
/*---------------------------------------------------------------------------*/
Bool MakeHoriGysts(Rect16 *pRc, int nRc, int32_t Skew, int MaxSize,
Un_GYST *pHorGt, int *pWhatDo) {
int MinBeg, MaxBeg, MinEnd, MaxEnd, CurBeg, CurEnd, i, End, k, iFirst;
Point BegDirIdeal;
Point EndDirIdeal;
iFirst = -1;
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
iFirst = i;
break;
}
if (iFirst == -1)
return FALSE;
/* Предельные значения проекций */
BegDirIdeal.rx() = pRc[iFirst].left;
BegDirIdeal.ry() = (int) (.5 * (pRc[iFirst].top + pRc[iFirst].bottom + 1));
BegDirIdeal.deskew(-Skew);
MinBeg = BegDirIdeal.x();
MaxBeg = BegDirIdeal.x();
EndDirIdeal.rx() = pRc[iFirst].right;
EndDirIdeal.ry() = (int) (.5 * (pRc[iFirst].top + pRc[iFirst].bottom + 1));
EndDirIdeal.deskew(-Skew);
MinEnd = EndDirIdeal.x();
MaxEnd = EndDirIdeal.x();
for (i = iFirst + 1; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
BegDirIdeal.rx() = pRc[i].left;
BegDirIdeal.ry() = (int) (.5 * (pRc[i].top + pRc[i].bottom + 1));
BegDirIdeal.deskew(-Skew);
CurBeg = BegDirIdeal.x();
EndDirIdeal.rx() = pRc[i].right;
EndDirIdeal.ry() = (int) (.5 * (pRc[i].top + pRc[i].bottom + 1));
EndDirIdeal.deskew(-Skew);
CurEnd = EndDirIdeal.x();
if (MinBeg > CurBeg)
MinBeg = CurBeg;
if (MaxBeg < CurBeg)
MaxBeg = CurBeg;
if (MinEnd > CurEnd)
MinEnd = CurEnd;
if (MaxEnd < CurEnd)
MaxEnd = CurEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
if (MinBeg > MinEnd)
return FALSE;
if (MaxBeg > MaxEnd)
return FALSE;
pHorGt->Shift = MinBeg;
pHorGt->End = MaxEnd - MinBeg;
pHorGt->nElem = nRc;
End = pHorGt->End;
for (i = 0; i <= End; i++) {
pHorGt->Signal[i] = 0;
}
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
BegDirIdeal.rx() = pRc[i].left;
BegDirIdeal.ry() = (int) (.5 * (pRc[i].top + pRc[i].bottom + 1));
BegDirIdeal.deskew(-Skew);
CurBeg = BegDirIdeal.x();
EndDirIdeal.rx() = pRc[i].right;
EndDirIdeal.ry() = (int) (.5 * (pRc[i].top + pRc[i].bottom + 1));
EndDirIdeal.deskew(-Skew);
CurEnd = EndDirIdeal.x();
for (k = CurBeg; k <= CurEnd; k++)
pHorGt->Signal[k - MinBeg]++;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
Bool MakeHoriSrez(Rect16 *pRcId, int nRc, int BegSrez, int EndSrez,
int MaxSize, Un_GYST *pHorGt, int *pWhatDo) {
int MinBeg, MaxBeg, MinEnd, MaxEnd, CurBeg, CurEnd, i, End, k, iFirst;
iFirst = -1;
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
iFirst = i;
break;
}
if (iFirst == -1)
return FALSE;
/* Предельные значения проекций */
MinBeg = pRcId[iFirst].left;
MaxBeg = MinBeg;
MinEnd = pRcId[iFirst].right;
MaxEnd = MinEnd;
for (i = iFirst + 1; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
CurBeg = pRcId[i].left;
CurEnd = pRcId[i].right;
if (MinBeg > CurBeg)
MinBeg = CurBeg;
if (MaxBeg < CurBeg)
MaxBeg = CurBeg;
if (MinEnd > CurEnd)
MinEnd = CurEnd;
if (MaxEnd < CurEnd)
MaxEnd = CurEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
if (MinBeg > MinEnd)
return FALSE;
if (MaxBeg > MaxEnd)
return FALSE;
pHorGt->Shift = MinBeg;
pHorGt->End = MaxEnd - MinBeg;
pHorGt->nElem = nRc;
End = pHorGt->End;
for (i = 0; i <= End; i++) {
pHorGt->Signal[i] = 0;
}
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
if (pRcId[i].top >= EndSrez)
continue;
if (pRcId[i].bottom <= BegSrez)
continue;
CurBeg = pRcId[i].left;
CurEnd = pRcId[i].right;
for (k = CurBeg; k <= CurEnd; k++)
pHorGt->Signal[k - MinBeg]++;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
Bool MakeVertSrez(Rect16 *pRcId, int nRc, int BegSrez, int EndSrez,
int MaxSize, Un_GYST *pVerGt, int *pWhatDo) {
int MinBeg, MaxBeg, MinEnd, MaxEnd, CurBeg, CurEnd, i, End, k, iFirst;
iFirst = -1;
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
iFirst = i;
break;
}
if (iFirst == -1)
return FALSE;
/* Предельные значения проекций */
MinBeg = pRcId[iFirst].top;
MaxBeg = MinBeg;
MinEnd = pRcId[iFirst].bottom;
MaxEnd = MinEnd;
for (i = iFirst + 1; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
CurBeg = pRcId[i].top;
CurEnd = pRcId[i].bottom;
if (MinBeg > CurBeg)
MinBeg = CurBeg;
if (MaxBeg < CurBeg)
MaxBeg = CurBeg;
if (MinEnd > CurEnd)
MinEnd = CurEnd;
if (MaxEnd < CurEnd)
MaxEnd = CurEnd;
}
if (MaxBeg - MinBeg >= MaxSize)
return FALSE;
if (MaxEnd - MinEnd >= MaxSize)
return FALSE;
if (MinBeg > MinEnd)
return FALSE;
if (MaxBeg > MaxEnd)
return FALSE;
pVerGt->Shift = MinBeg;
pVerGt->End = MaxEnd - MinBeg;
pVerGt->nElem = nRc;
End = pVerGt->End;
for (i = 0; i <= End; i++) {
pVerGt->Signal[i] = 0;
}
for (i = 0; i < nRc; i++) {
if (pWhatDo[i] != 1)
continue;
if (pRcId[i].left >= EndSrez)
continue;
if (pRcId[i].right <= BegSrez)
continue;
CurBeg = pRcId[i].top;
CurEnd = pRcId[i].bottom;
for (k = CurBeg; k <= CurEnd; k++)
pVerGt->Signal[k - MinBeg]++;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
Bool FindNextHole(Un_GYST *pDarkGt, int Beg, int End, int *NewBeg, int *NewEnd) {
int i;
Bool ret;
if (Beg > End)
return FALSE;
ret = FALSE;
for (i = Beg; i <= End; i++) {
if (i < pDarkGt->Shift)
continue;
if (i > pDarkGt->Shift + pDarkGt->End)
break;
if (pDarkGt->Signal[i - pDarkGt->Shift] > 0)
continue;
*NewBeg = i;
ret = TRUE;
break;
}
if (!ret)
return FALSE;
for (i = *NewBeg; i <= End; i++) {
if (i > pDarkGt->Shift + pDarkGt->End)
break;
if (pDarkGt->Signal[i - pDarkGt->Shift] > 0)
break;
*NewEnd = i;
continue;
}
return TRUE;
}
/*---------------------------------------------------------------------------*/
Bool FindNextHoleWithBound(int MaxSig, Un_GYST *pDarkGt, int Beg, int End,
int *NewBeg, int *NewEnd, int MinLent) {
int i, Beg_C, End_C;
Bool ret;
if (Beg > End)
return FALSE;
Beg_C = Beg;
if (Beg_C < pDarkGt->Shift)
Beg_C = pDarkGt->Shift;
End_C = End;
if (End_C > pDarkGt->Shift + pDarkGt->End)
End_C = pDarkGt->Shift + pDarkGt->End;
if (Beg_C > End_C)
return FALSE;
while (Beg_C <= End_C) {
ret = FALSE;
for (i = Beg_C; i <= End_C; i++) {
if (pDarkGt->Signal[i - pDarkGt->Shift] > MaxSig)
continue;
*NewBeg = i;
ret = TRUE;
break;
}
if (!ret)
return FALSE;
*NewEnd = *NewBeg;
for (i = *NewBeg; i <= End_C; i++) {
if (pDarkGt->Signal[i - pDarkGt->Shift] > MaxSig)
break;
*NewEnd = i;
continue;
}
if (*NewEnd - *NewBeg >= MinLent)
return TRUE;
Beg_C = *NewEnd + 1;
}
return FALSE;
}
/*---------------------------------------------------------------------------*/
Bool FindNormNextHoleWithBound(int *pSig, int LenSig, int Beg, int End,
int *NewBeg, int *NewEnd, int MaxSig, int MinLent) {
int i, Beg_C, End_C;
Bool ret;
if (Beg > End)
return FALSE;
Beg_C = Beg;
if (Beg_C < 0)
Beg_C = 0;
End_C = End;
if (End_C > LenSig - 1)
End_C = LenSig - 1;
if (Beg_C > End_C)
return FALSE;
while (Beg_C <= End_C) {
ret = FALSE;
for (i = Beg_C; i <= End_C; i++) {
if (pSig[i] > MaxSig)
continue;
*NewBeg = i;
ret = TRUE;
break;
}
if (!ret)
return FALSE;
*NewEnd = *NewBeg;
for (i = *NewBeg; i <= End_C; i++) {
if (pSig[i] > MaxSig)
break;
*NewEnd = i;
continue;
}
if (*NewEnd - *NewBeg >= MinLent)
return TRUE;
Beg_C = *NewEnd + 1;
}
return FALSE;
}
/*---------------------------------------------------------------------------*/
Bool FindMainHole(int Beg, int End, int MaxSig, Un_GYST *pOrtGt, int *NewBeg,
int *NewEnd, int *NewMax) {
int CurBeg, CurEnd, i, BegPos;
Bool ret;
ret = FindNextHoleWithBound(MaxSig, pOrtGt, Beg, End, &CurBeg, &CurEnd, 0);
if (!ret)
return FALSE;
*NewBeg = CurBeg;
*NewEnd = CurEnd;
BegPos = *NewEnd + 1;
while (1) {
ret = FindNextHoleWithBound(MaxSig, pOrtGt, BegPos, End, &CurBeg,
&CurEnd, 0);
if (!ret)
break;
BegPos = CurEnd + 1;
if (*NewEnd - *NewBeg > CurEnd - CurBeg)
continue;
*NewBeg = CurBeg;
*NewEnd = CurEnd;
}
*NewMax = pOrtGt->Signal[*NewBeg - pOrtGt->Shift];
for (i = *NewBeg; i <= *NewEnd; i++)
if (*NewMax < pOrtGt->Signal[i - pOrtGt->Shift])
*NewMax = pOrtGt->Signal[i - pOrtGt->Shift];
return TRUE;
}
/*---------------------------------------------------------------------------*/
| Java |
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2021 IntellectualSites
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.core.command;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.util.task.RunnableVal2;
import com.plotsquared.core.util.task.RunnableVal3;
import java.util.concurrent.CompletableFuture;
/**
* SubCommand class
*
* @see Command#Command(Command, boolean)
* @deprecated In favor of normal Command class
*/
public abstract class SubCommand extends Command {
public SubCommand() {
super(MainCommand.getInstance(), true);
}
public SubCommand(Argument<?>... arguments) {
this();
setRequiredArguments(arguments);
}
@Override
public CompletableFuture<Boolean> execute(
PlotPlayer<?> player, String[] args,
RunnableVal3<Command, Runnable, Runnable> confirm,
RunnableVal2<Command, CommandResult> whenDone
) {
return CompletableFuture.completedFuture(onCommand(player, args));
}
public abstract boolean onCommand(PlotPlayer<?> player, String[] args);
}
| Java |
package com.cloudera.cmf.service.yarn;
import com.cloudera.cmf.command.flow.CmdWorkCtx;
import com.cloudera.cmf.command.flow.WorkOutput;
import com.cloudera.cmf.command.flow.work.OneOffRoleProcCmdWork;
import com.cloudera.cmf.model.DbProcess;
import com.cloudera.cmf.model.DbRole;
import com.cloudera.cmf.model.RoleState;
import com.cloudera.cmf.service.ServiceDataProvider;
import com.cloudera.cmf.service.components.ProcessHelper;
import com.cloudera.enterprise.MessageWithArgs;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import java.util.List;
public class RmFormatStateStoreCmdWork extends OneOffRoleProcCmdWork
{
private RmFormatStateStoreCmdWork(@JsonProperty("roleId") Long roleId)
{
super(roleId);
}
public MessageWithArgs getDescription(CmdWorkCtx ctx)
{
return MessageWithArgs.of("message.command.rmFormatStateStoreCmdWork.desc", new String[0]);
}
public String getProcessName()
{
return "rm-format-state-store";
}
protected void beforeProcessCreation(CmdWorkCtx ctx, DbProcess proc, DbRole role)
{
ctx.getServiceDataProvider().getProcessHelper().runAsRole(proc, role);
List args = ImmutableList.of("resourcemanager", "-format-state-store");
proc.setProgram("yarn/yarn.sh");
proc.setArguments(args);
}
protected RoleState getRoleStateAfterProcess(WorkOutput output, CmdWorkCtx ctx)
{
return RoleState.STOPPED;
}
public static RmFormatStateStoreCmdWork of(DbRole r) {
Preconditions.checkNotNull(r);
Preconditions.checkNotNull(r.getId());
Preconditions.checkArgument(YarnServiceHandler.RoleNames.RESOURCEMANAGER.name().equals(r.getRoleType()));
return new RmFormatStateStoreCmdWork(r.getId());
}
} | Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_01) on Sun Jul 03 11:32:25 ICT 2005 -->
<TITLE>
com.golden.gamedev.engine.graphics Class Hierarchy (GTGE Add-Ons)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="com.golden.gamedev.engine.graphics Class Hierarchy (GTGE Add-Ons)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../com/golden/gamedev/engine/audio/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../../com/golden/gamedev/engine/jogl/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?com/golden/gamedev/engine/graphics/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
Hierarchy For Package com.golden.gamedev.engine.graphics
</H2>
</CENTER>
<DL>
<DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../overview-tree.html">All Packages</A></DL>
<HR>
<H2>
Class Hierarchy
</H2>
<UL>
<LI TYPE="circle">java.lang.<A HREF="http://java.sun.com/j2se/1.4/docs/api/java/lang/Object.html" title="class or interface in java.lang"><B>Object</B></A><UL>
<LI TYPE="circle">java.awt.<A HREF="http://java.sun.com/j2se/1.4/docs/api/java/awt/Graphics.html" title="class or interface in java.awt"><B>Graphics</B></A><UL>
<LI TYPE="circle">java.awt.<A HREF="http://java.sun.com/j2se/1.4/docs/api/java/awt/Graphics2D.html" title="class or interface in java.awt"><B>Graphics2D</B></A><UL>
<LI TYPE="circle">com.golden.gamedev.engine.graphics.<A HREF="../../../../../com/golden/gamedev/engine/graphics/NullGraphics.html" title="class in com.golden.gamedev.engine.graphics"><B>NullGraphics</B></A></UL>
</UL>
</UL>
</UL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../com/golden/gamedev/engine/audio/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../../com/golden/gamedev/engine/jogl/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?com/golden/gamedev/engine/graphics/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2003-2005 Golden T Studios. All rights reserved. Use is subject to <a href=http://creativecommons.org/licenses/by/2.0/>license terms<a/>.<br><a target=_blank href=http://www.goldenstudios.or.id/>GoldenStudios.or.id</a></i>
</BODY>
</HTML>
| Java |
package com.github.sandokandias.payments.interfaces.rest.model;
import com.github.sandokandias.payments.infrastructure.util.i18n.I18nMessage;
import lombok.Data;
import java.util.Set;
@Data
public class ErrorResponse {
private Set<I18nMessage> errors;
}
| Java |
package pt.uminho.sysbio.biosynthframework.integration.model;
import pt.uminho.sysbio.biosynth.integration.io.dao.neo4j.MetaboliteMajorLabel;
public interface IntegrationEngine {
public IntegrationMap<String, MetaboliteMajorLabel> integrate(IntegrationMap<String, MetaboliteMajorLabel> imap);
}
| Java |
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library 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 for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package api
import (
"math/big"
"github.com/ghostnetwrk/ghostnet/eth"
"github.com/ghostnetwrk/ghostnet/rpc/codec"
"github.com/ghostnetwrk/ghostnet/rpc/shared"
"github.com/ghostnetwrk/ghostnet/xeth"
)
const (
ShhApiVersion = "1.0"
)
var (
// mapping between methods and handlers
shhMapping = map[string]shhhandler{
"shh_version": (*shhApi).Version,
"shh_post": (*shhApi).Post,
"shh_hasIdentity": (*shhApi).HasIdentity,
"shh_newIdentity": (*shhApi).NewIdentity,
"shh_newFilter": (*shhApi).NewFilter,
"shh_uninstallFilter": (*shhApi).UninstallFilter,
"shh_getMessages": (*shhApi).GetMessages,
"shh_getFilterChanges": (*shhApi).GetFilterChanges,
}
)
func newWhisperOfflineError(method string) error {
return shared.NewNotAvailableError(method, "whisper offline")
}
// net callback handler
type shhhandler func(*shhApi, *shared.Request) (interface{}, error)
// shh api provider
type shhApi struct {
xeth *xeth.XEth
ethereum *eth.Ethereum
methods map[string]shhhandler
codec codec.ApiCoder
}
// create a new whisper api instance
func NewShhApi(xeth *xeth.XEth, eth *eth.Ethereum, coder codec.Codec) *shhApi {
return &shhApi{
xeth: xeth,
ethereum: eth,
methods: shhMapping,
codec: coder.New(nil),
}
}
// collection with supported methods
func (self *shhApi) Methods() []string {
methods := make([]string, len(self.methods))
i := 0
for k := range self.methods {
methods[i] = k
i++
}
return methods
}
// Execute given request
func (self *shhApi) Execute(req *shared.Request) (interface{}, error) {
if callback, ok := self.methods[req.Method]; ok {
return callback(self, req)
}
return nil, shared.NewNotImplementedError(req.Method)
}
func (self *shhApi) Name() string {
return shared.ShhApiName
}
func (self *shhApi) ApiVersion() string {
return ShhApiVersion
}
func (self *shhApi) Version(req *shared.Request) (interface{}, error) {
w := self.xeth.Whisper()
if w == nil {
return nil, newWhisperOfflineError(req.Method)
}
return w.Version(), nil
}
func (self *shhApi) Post(req *shared.Request) (interface{}, error) {
w := self.xeth.Whisper()
if w == nil {
return nil, newWhisperOfflineError(req.Method)
}
args := new(WhisperMessageArgs)
if err := self.codec.Decode(req.Params, &args); err != nil {
return nil, err
}
err := w.Post(args.Payload, args.To, args.From, args.Topics, args.Priority, args.Ttl)
if err != nil {
return false, err
}
return true, nil
}
func (self *shhApi) HasIdentity(req *shared.Request) (interface{}, error) {
w := self.xeth.Whisper()
if w == nil {
return nil, newWhisperOfflineError(req.Method)
}
args := new(WhisperIdentityArgs)
if err := self.codec.Decode(req.Params, &args); err != nil {
return nil, err
}
return w.HasIdentity(args.Identity), nil
}
func (self *shhApi) NewIdentity(req *shared.Request) (interface{}, error) {
w := self.xeth.Whisper()
if w == nil {
return nil, newWhisperOfflineError(req.Method)
}
return w.NewIdentity(), nil
}
func (self *shhApi) NewFilter(req *shared.Request) (interface{}, error) {
args := new(WhisperFilterArgs)
if err := self.codec.Decode(req.Params, &args); err != nil {
return nil, err
}
id := self.xeth.NewWhisperFilter(args.To, args.From, args.Topics)
return newHexNum(big.NewInt(int64(id)).Bytes()), nil
}
func (self *shhApi) UninstallFilter(req *shared.Request) (interface{}, error) {
args := new(FilterIdArgs)
if err := self.codec.Decode(req.Params, &args); err != nil {
return nil, err
}
return self.xeth.UninstallWhisperFilter(args.Id), nil
}
func (self *shhApi) GetFilterChanges(req *shared.Request) (interface{}, error) {
w := self.xeth.Whisper()
if w == nil {
return nil, newWhisperOfflineError(req.Method)
}
// Retrieve all the new messages arrived since the last request
args := new(FilterIdArgs)
if err := self.codec.Decode(req.Params, &args); err != nil {
return nil, err
}
return self.xeth.WhisperMessagesChanged(args.Id), nil
}
func (self *shhApi) GetMessages(req *shared.Request) (interface{}, error) {
w := self.xeth.Whisper()
if w == nil {
return nil, newWhisperOfflineError(req.Method)
}
// Retrieve all the cached messages matching a specific, existing filter
args := new(FilterIdArgs)
if err := self.codec.Decode(req.Params, &args); err != nil {
return nil, err
}
return self.xeth.WhisperMessages(args.Id), nil
}
| Java |
package vrml.external.field;
import vrml.external.field.FieldTypes;
import vrml.external.Browser;
import java.awt.*;
import java.math.BigInteger;
public class EventInSFImage extends EventIn {
public EventInSFImage() { EventType = FieldTypes.SFIMAGE; }
public void setValue(int width, int height, int components, byte[] pixels) throws IllegalArgumentException {
int count;
int pixcount;
String val;
BigInteger newval;
byte xx[];
if (pixels.length != (width*height*components)) {
throw new IllegalArgumentException();
}
if ((components < 1) || (components > 4)) {
throw new IllegalArgumentException();
}
// use BigInt to ensure sign bit does not frick us up.
xx = new byte[components+1];
xx[0] = (byte) 0; // no sign bit here!
val = new String("" + width + " " + height + " " + components);
if (pixels== null) { pixcount = 0;} else {pixcount=pixels.length;}
if (components == 1) {
for (count = 0; count < pixcount; count++) {
xx[1] = pixels[count];
newval = new BigInteger(xx);
//System.out.println ("Big int " + newval.toString(16));
val = val.concat(" 0x" + newval.toString(16));
}
}
if (components == 2) {
for (count = 0; count < pixcount; count+=2) {
xx[1] = pixels[count]; xx[2] = pixels[count+1];
newval = new BigInteger(xx);
//System.out.println ("Big int " + newval.toString(16));
val = val.concat(" 0x" + newval.toString(16));
}
}
if (components == 3) {
for (count = 0; count < pixcount; count+=3) {
xx[1] = pixels[count]; xx[2] = pixels[count+1]; xx[3]=pixels[count+2];
newval = new BigInteger(xx);
//System.out.println ("Big int " + newval.toString(16));
val = val.concat(" 0x" + newval.toString(16));
}
}
if (components == 4) {
for (count = 0; count < pixcount; count+=4) {
xx[1] = pixels[count]; xx[2] = pixels[count+1]; xx[3]=pixels[count+2]; xx[4]=pixels[count+3];
newval = new BigInteger(xx);
//System.out.println ("Big int " + newval.toString(16));
val = val.concat(" 0x" + newval.toString(16));
}
}
//System.out.println ("sending " + val);
Browser.newSendEvent (this, val.length() + ":" + val + " ");
return;
}
}
| Java |
#include <cstdio>
template<typename T>
auto kitten(T x) __attribute__((noinline));
template<class T>
auto kitten(T t)
{
static T x = 0;
return (x += 1) + t;
}
int main()
{
printf("%d\n", kitten(1));
printf("%g\n", kitten(3.14));
}
| Java |
#ifndef __BUF_H
#define __BUF_H
#include <const.h>
struct buf {
uint flag;
struct buf *prev;
struct buf *next;
struct buf *io_prev;
struct buf *io_next;
uint dev;
uint sector;
uchar data[BLK_SIZE];
};
struct dev {
uint active;
struct buf *prev;
struct buf *next;
struct buf *io_prev;
struct buf *io_next;
};
#define B_BUSY 0b1
#define B_VALID 0b10
#define B_DIRTY 0b100
#define B_ERROR 0b1000
extern struct buf buffer[NBUF];
extern struct buf bfreelist;
extern struct dev hd_dev;
void buf_init();
struct buf* buf_get(uint dev, uint sector);
int buf_relse(struct buf* bp);
struct buf* buf_read(uint dev, uint sector);
int buf_write(struct buf* b);
void dump_buf(struct buf* buf);
void hexdump_buf(struct buf* buf);
void dump_buffer_freelist();
#endif
| Java |
import subprocess
import time
import sys
import re
class checkIfUp:
__shellPings = []
__shell2Nbst = []
__ipsToCheck = []
checkedIps = 0
onlineIps = 0
unreachable = 0
timedOut = 0
upIpsAddress = []
computerName = []
completeMacAddress = []
executionTime = 0
def __init__(self,fromIp,toIp):
startTime = time.time()
self.fromIp = fromIp # from 192.168.1.x
self.toIp = toIp # to 192.168.x.x
self.__checkIfIpIsValid(fromIp)
self.__checkIfIpIsValid(toIp)
self.__getRange(fromIp,toIp)
self.__shellToQueue()
#self.__checkIfUp() # run by the shellToQueue queue organizer
self.__computerInfoInQueue()
endTime = time.time()
self.executionTime = round(endTime - startTime,3)
def __checkIfIpIsValid(self,ip):
def validateRange(val):
# valid range => 1 <-> 255
try:
val = int(val)
if val < 0 or val > 255:
print "Invalid IP Range ("+str(val)+")"
sys.exit(0)
except:
print "Invalid IP"
sys.exit(0)
ip = ip.split(".")
firstVal = validateRange(ip[0])
secondVal = validateRange(ip[1])
thirdVal = validateRange(ip[2])
fourthVal = validateRange(ip[3])
return True
def __getRange(self,fromIp,toIp):
fromIp = fromIp.split(".")
toIp = toIp.split(".")
# toIp must be > fromIp
def ip3chars(ipBlock):
# input 1; output 001
ipBlock = str(ipBlock)
while len(ipBlock) != 3:
ipBlock = "0"+ipBlock
return ipBlock
fromIpRaw = ip3chars(fromIp[0])+ip3chars(fromIp[1])+ip3chars(fromIp[2])+ip3chars(fromIp[3])
toIpRaw = ip3chars(toIp[0])+ip3chars(toIp[1])+ip3chars(toIp[2])+ip3chars(toIp[3])
if fromIpRaw > toIpRaw:
# if from is bigger switch the order
temp = fromIp
fromIp = toIp
toIp = temp
currentIp = [0,0,0,0]
# all to integers
currentIp0 = int(fromIp[0])
currentIp1 = int(fromIp[1])
currentIp2 = int(fromIp[2])
currentIp3 = int(fromIp[3])
toIp0 = int(toIp[0])
toIp1 = int(toIp[1])
toIp2 = int(toIp[2])
toIp3 = int(toIp[3])
firstIp = str(currentIp0)+"."+str(currentIp1)+"."+str(currentIp2)+"."+str(currentIp3)
self.__ipsToCheck = [firstIp]
while currentIp3 != toIp3 or currentIp2 != toIp2 or currentIp1 != toIp1 or currentIp0 != toIp0:
currentIp3 += 1
if currentIp3 > 255:
currentIp3 = 0
currentIp2 += 1
if currentIp2 > 255:
currentIp2 = 0
currentIp1 += 1
if currentIp1 > 255:
currentIp1 = 0
currentIp0 += 1
addIp = str(currentIp0)+"."+str(currentIp1)+"."+str(currentIp2)+"."+str(currentIp3)
self.__ipsToCheck.append(addIp)
def __shellToQueue(self):
# write them in the shell queue
maxPingsAtOnce = 200
currentQueuedPings = 0
for pingIp in self.__ipsToCheck:
proc = subprocess.Popen(['ping','-n','1',pingIp],stdout=subprocess.PIPE,shell=True)
self.__shellPings.append(proc)
currentQueuedPings += 1
if currentQueuedPings >= maxPingsAtOnce:
#execute shells
self.__checkIfUp()
currentQueuedPings = 0
self.__shellPings = []
self.__checkIfUp() # execute last queue
def __checkIfUp(self):
# execute the shells & determine whether the host is up or not
for shellInQueue in self.__shellPings:
pingResult = ""
shellInQueue.wait()
while True:
line = shellInQueue.stdout.readline()
if line != "":
pingResult += line
else:
break;
self.checkedIps += 1
if 'unreachable' in pingResult:
self.unreachable += 1
elif 'timed out' in pingResult:
self.timedOut += 1
else:
self.onlineIps += 1
currentIp = self.__ipsToCheck[self.checkedIps-1]
self.upIpsAddress.append(currentIp)
def __computerInfoInQueue(self):
# shell queue for online hosts
maxShellsAtOnce = 255
currentQueuedNbst = 0
for onlineIp in self.upIpsAddress:
proc = subprocess.Popen(['\\Windows\\sysnative\\nbtstat.exe','-a',onlineIp],stdout=subprocess.PIPE,shell=True)
self.__shell2Nbst.append(proc)
currentQueuedNbst += 1
if currentQueuedNbst >= maxShellsAtOnce:
# execute shells
self.__gatherComputerInfo()
currentQueuedNbst = 0
self.__shell2Nbst = []
self.__gatherComputerInfo() # execute last queue
def __gatherComputerInfo(self):
# execute the shells and find host Name and MAC
for shellInQueue in self.__shell2Nbst:
nbstResult = ""
shellInQueue.wait()
computerNameLine = ""
macAddressLine = ""
computerName = ""
macAddress = ""
while True:
line = shellInQueue.stdout.readline()
if line != "":
if '<00>' in line and 'UNIQUE' in line:
computerNameLine = line
if 'MAC Address' in line:
macAddressLine = line
else:
break;
computerName = re.findall('([ ]+)(.*?)([ ]+)<00>', computerNameLine)
macAddress = re.findall('([A-Z0-9]+)-([A-Z0-9]+)-([A-Z0-9]+)-([A-Z0-9]+)-([A-Z0-9]+)-([A-Z0-9]+)',macAddressLine)
try:
self.computerName.append(computerName[0][1])
except:
self.computerName.append("")
completeMacAddress = ""
firstMacElement = 0
try:
for macEach in macAddress[0]:
if firstMacElement == 0:
firstMacElement += 1
else:
completeMacAddress += ":"
completeMacAddress += macEach
firstMacElement = 0
except:
completeMacAddress = ""
self.completeMacAddress.append(completeMacAddress)
def readValue(self):
# debugging use only
ips = []
for ip in self.completeMacAddress:
ips.append(ip)
return ips
print "\t\t---LANScanner v1.0---\n"
# brief tutorial
print "Sample input data:"
print "FromIP: 192.168.1.50"
print "ToIP: 192.168.1.20"
print "---"
# input
fromIp = raw_input("From: ")
toIp = raw_input("To: ")
# enter values to class
userRange = checkIfUp(fromIp,toIp)
# read class values
print ""
#print userRange.readValue() # debugging use only
print "Checked",userRange.checkedIps,"IPs"
print ""
print "Online:",str(userRange.onlineIps)+"/"+str(userRange.checkedIps)
print "Unreachable:",userRange.unreachable,"Timed out:",userRange.timedOut
print "" # newline
print "Online IPs:"
print "IP\t\tNAME\t\tMAC"
counter = 0
for onlineIp in userRange.upIpsAddress:
print onlineIp+"\t"+userRange.computerName[counter]+"\t"+userRange.completeMacAddress[counter]
counter += 1
print ""
print "Took",userRange.executionTime,"seconds" | Java |
/*
* AJDebug.java
*
* This file is part of Tritonus: http://www.tritonus.org/
*/
/*
* Copyright (c) 1999 - 2002 by Matthias Pfisterer
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as published
* by the Free Software Foundation; either version 2 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
|<--- this code is formatted to fit into 80 columns --->|
*/
package org.tritonus.debug;
import org.aspectj.lang.JoinPoint;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Synthesizer;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.SourceDataLine;
import org.tritonus.core.TMidiConfig;
import org.tritonus.core.TInit;
import org.tritonus.share.TDebug;
import org.tritonus.share.midi.TSequencer;
import org.tritonus.midi.device.alsa.AlsaSequencer;
import org.tritonus.midi.device.alsa.AlsaSequencer.PlaybackAlsaMidiInListener;
import org.tritonus.midi.device.alsa.AlsaSequencer.RecordingAlsaMidiInListener;
import org.tritonus.midi.device.alsa.AlsaSequencer.AlsaSequencerReceiver;
import org.tritonus.midi.device.alsa.AlsaSequencer.AlsaSequencerTransmitter;
import org.tritonus.midi.device.alsa.AlsaSequencer.LoaderThread;
import org.tritonus.midi.device.alsa.AlsaSequencer.MasterSynchronizer;
import org.tritonus.share.sampled.convert.TAsynchronousFilteredAudioInputStream;
/** Debugging output aspect.
*/
public aspect AJDebug
extends Utils
{
pointcut allExceptions(): handler(Throwable+);
// TAudioConfig, TMidiConfig, TInit
pointcut TMidiConfigCalls(): execution(* TMidiConfig.*(..));
pointcut TInitCalls(): execution(* TInit.*(..));
// share
// midi
pointcut MidiSystemCalls(): execution(* MidiSystem.*(..));
pointcut Sequencer(): execution(TSequencer+.new(..)) ||
execution(* TSequencer+.*(..)) ||
execution(* PlaybackAlsaMidiInListener.*(..)) ||
execution(* RecordingAlsaMidiInListener.*(..)) ||
execution(* AlsaSequencerReceiver.*(..)) ||
execution(* AlsaSequencerTransmitter.*(..)) ||
execution(LoaderThread.new(..)) ||
execution(* LoaderThread.*(..)) ||
execution(MasterSynchronizer.new(..)) ||
execution(* MasterSynchronizer.*(..));
// audio
pointcut AudioSystemCalls(): execution(* AudioSystem.*(..));
pointcut sourceDataLine():
call(* SourceDataLine+.*(..));
// OLD
// pointcut playerStates():
// execution(private void TPlayer.setState(int));
// currently not used
pointcut printVelocity(): execution(* JavaSoundToneGenerator.playTone(..)) && call(JavaSoundToneGenerator.ToneThread.new(..));
// pointcut tracedCall(): execution(protected void JavaSoundAudioPlayer.doRealize() throws Exception);
///////////////////////////////////////////////////////
//
// ACTIONS
//
///////////////////////////////////////////////////////
before(): MidiSystemCalls()
{
if (TDebug.TraceMidiSystem) outEnteringJoinPoint(thisJoinPoint);
}
after(): MidiSystemCalls()
{
if (TDebug.TraceSequencer) outLeavingJoinPoint(thisJoinPoint);
}
before(): Sequencer()
{
if (TDebug.TraceSequencer) outEnteringJoinPoint(thisJoinPoint);
}
after(): Sequencer()
{
if (TDebug.TraceSequencer) outLeavingJoinPoint(thisJoinPoint);
}
before(): TInitCalls()
{
if (TDebug.TraceInit) outEnteringJoinPoint(thisJoinPoint);
}
after(): TInitCalls()
{
if (TDebug.TraceInit) outLeavingJoinPoint(thisJoinPoint);
}
before(): TMidiConfigCalls()
{
if (TDebug.TraceMidiConfig) outEnteringJoinPoint(thisJoinPoint);
}
after(): TMidiConfigCalls()
{
if (TDebug.TraceMidiConfig) outLeavingJoinPoint(thisJoinPoint);
}
// execution(* TAsynchronousFilteredAudioInputStream.read(..))
before(): execution(* TAsynchronousFilteredAudioInputStream.read())
{
if (TDebug.TraceAudioConverter) outEnteringJoinPoint(thisJoinPoint);
}
after(): execution(* TAsynchronousFilteredAudioInputStream.read())
{
if (TDebug.TraceAudioConverter) outLeavingJoinPoint(thisJoinPoint);
}
before(): execution(* TAsynchronousFilteredAudioInputStream.read(byte[]))
{
if (TDebug.TraceAudioConverter) outEnteringJoinPoint(thisJoinPoint);
}
after(): execution(* TAsynchronousFilteredAudioInputStream.read(byte[]))
{
if (TDebug.TraceAudioConverter) outLeavingJoinPoint(thisJoinPoint);
}
before(): execution(* TAsynchronousFilteredAudioInputStream.read(byte[], int, int))
{
if (TDebug.TraceAudioConverter) outEnteringJoinPoint(thisJoinPoint);
}
after(): execution(* TAsynchronousFilteredAudioInputStream.read(byte[], int, int))
{
if (TDebug.TraceAudioConverter) outLeavingJoinPoint(thisJoinPoint);
}
after() returning(int nBytes): call(* TAsynchronousFilteredAudioInputStream.read(byte[], int, int))
{
if (TDebug.TraceAudioConverter) TDebug.out("returning bytes: " + nBytes);
}
// before(int nState): playerStates() && args(nState)
// {
// // if (TDebug.TracePlayerStates)
// // {
// // TDebug.out("TPlayer.setState(): " + nState);
// // }
// }
// before(): playerStateTransitions()
// {
// // if (TDebug.TracePlayerStateTransitions)
// // {
// // TDebug.out("Entering: " + thisJoinPoint);
// // }
// }
// Synthesizer around(): call(* MidiSystem.getSynthesizer())
// {
// // Synthesizer s = proceed();
// // if (TDebug.TraceToneGenerator)
// // {
// // TDebug.out("MidiSystem.getSynthesizer() gives: " + s);
// // }
// // return s;
// // only to get no compilation errors
// return null;
// }
// TODO: v gives an error; find out what to do
// before(int v): printVelocity() && args(nVelocity)
// {
// if (TDebug.TraceToneGenerator)
// {
// TDebug.out("velocity: " + v);
// }
// }
before(Throwable t): allExceptions() && args(t)
{
if (TDebug.TraceAllExceptions) TDebug.out(t);
}
}
/*** AJDebug.java ***/
| Java |
{"exchange_info":[{"onclick":null,"link":null,"value":"+34 943 018 705"},{"onclick":null,"link":"mailto:noc@i2basque.es","value":"noc@i2basque.es"},{"onclick":"window.open(this.href,'ix-new-window');return false;","link":"http://www.euskonix.com/principal.html","value":"Website"}],"address":["EuskoNIX (Bilbao, Spain)","\u003Caddress not available\u003E","Bilbao, Spain"],"name":"EuskoNIX (Bilbao, Spain)","id":"euskonix-bilbao-spain","buildings":[{"latitude":"43.268582","address":["\u003Caddress not available\u003E","Bilbao, Spain"],"longitude":"-2.946141","offset":"background:url('images/markers.png') no-repeat -22px 0;","id":18821}]} | Java |
# Game
class GameResult < ActiveRecord::Base
attr_accessible :question, :question_id, :user, :issues, :answer, :same, :skip
belongs_to :user
belongs_to :question
has_and_belongs_to_many :issues, :join_table => "game_results_issues", :autosave => true
after_initialize :default_values
private
def default_values
self.skip = false if (self.has_attribute? :skip) && self.skip.nil?
self.same = false if (self.has_attribute? :same) && self.same.nil?
end
def self.pick_result(uId)
@game_result = GameResult.new
question_randomizing_prob = 0.70
problem_randomizing_prob = 0.70
epsilon = 0.00000001
played_games = GameResult.select{|g| g.user_id == uId && g.skip == false}
#played_games = GameResult.select{|g| g.user_id == uId && g.skip == false}
if rand() < question_randomizing_prob && played_games != nil
question_list = Question.all.map{|q| q.id}
next_question_id = question_list.sort_by{|q| played_games.select{|g| g.question_id == q}.count}.first
else
question_list = Question.all.map{|q| q.id}
next_question_id = question_list[rand(question_list.size)]
end
# TODO: This needs to be modified at some point to not only ask a single question excessively/heavily when a new one is added to the mix
@game_result.question = Question.offset(next_question_id-1).first
game_info_for_single_question = played_games.select{|pg| pg.question_id == next_question_id}
problem_pairs = game_info_for_single_question.map{|pg| pg.issue_ids.sort}.uniq.sort
game_results_with_flags = FlaggedIssues.select{|f| f.issue_id > 0}
remove_flags = []
game_results_with_flags.select{|grwf| GameResult.find{|g| g.user_id == uId && g.id == grwf.game_result_id }}.each do |gr|
remove_flags << gr.issue_id
end
remove_same = played_games.select{|g| g.same }.map{|q| q.issue_ids-[q.answer]}.flatten
#Probs is all of the problems that we could potentially ask the user
probs = Issue.all.map{|r| r.id} - remove_flags - remove_same
probs_focus = probs.sort_by{|p| -problem_pairs.flatten.count(p)}[0..14]
probs_left = probs - probs_focus
#TODO: FIX this code to accommodate more than 2 problems
choice = rand()+epsilon
if choice < problem_randomizing_prob || probs_left == [] || probs_left == nil
problem_choices = probs_focus.combination(2).to_a.map{|a| a.sort}-problem_pairs
if problem_choices == []
remove_same_flag_problems = probs_focus.combination(2).to_a.map{|a| a.sort}
next_issues = remove_same_flag_problems[rand(remove_same_flag_problems.length)]
else
next_issues = problem_choices[rand(problem_choices.length)]
end
else
problem_choices = probs_left.combination(2).to_a.map{|a| a.sort}-problem_pairs
if problem_choices == []
remove_same_flag_problems = probs_focus.combination(2).to_a.map{|a| a.sort}
next_issues = remove_same_flag_problems[rand(remove_same_flag_problems.length)]
else
next_issues = problem_choices[rand(problem_choices.length)]
end
end
#puts next_issues
a = next_issues[0]-1
b = next_issues[1]-1
if rand(2).to_i == 1
@game_result.issues << Issue.offset(a).first
@game_result.issues << Issue.offset(b).first
else
@game_result.issues << Issue.offset(b).first
@game_result.issues << Issue.offset(a).first
end
return @game_result
end
end
| Java |
<?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2012 Zurmo Inc.
*
* Zurmo is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* Zurmo 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 or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Zurmo, Inc. with a mailing address at 113 McHenry Road Suite 207,
* Buffalo Grove, IL 60089, USA. or at email address contact@zurmo.com.
********************************************************************************/
class SavedWorkflowsUtilTest extends WorkflowBaseTest
{
public $freeze = false;
public function setup()
{
parent::setUp();
$freeze = false;
if (RedBeanDatabase::isFrozen())
{
RedBeanDatabase::unfreeze();
$freeze = true;
}
$this->freeze = $freeze;
}
public function teardown()
{
if ($this->freeze)
{
RedBeanDatabase::freeze();
}
parent::teardown();
}
public function testResolveProcessDateTimeByWorkflowAndModel()
{
//Test Date
$model = new WorkflowModelTestItem();
$model->date = '2007-02-02';
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('date', 'Is Time For', null, 86400);
$processDateTime = SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
$this->assertEquals('2007-02-03 00:00:00', $processDateTime);
//Test Date with negative duration
$model = new WorkflowModelTestItem();
$model->date = '2007-02-02';
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('date', 'Is Time For', null, -86400);
$processDateTime = SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
$this->assertEquals('2007-02-01 00:00:00', $processDateTime);
//Test DateTime
$model = new WorkflowModelTestItem();
$model->dateTime = '2007-05-02 04:00:02';
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('dateTime', 'Is Time For', null, 86400);
$processDateTime = SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
$this->assertEquals('2007-05-03 04:00:02', $processDateTime);
//Test DateTime with negative duration
$model = new WorkflowModelTestItem();
$model->dateTime = '2007-05-02 04:00:02';
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('dateTime', 'Is Time For', null, -86400);
$processDateTime = SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
$this->assertEquals('2007-05-01 04:00:02', $processDateTime);
}
/**
* @depends testResolveProcessDateTimeByWorkflowAndModel
* @expectedException ValueForProcessDateTimeIsNullException
*/
public function testResolveProcessDateTimeByWorkflowAndModelWithNullDate()
{
$model = new WorkflowModelTestItem();
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('date', 'Is Time For', null, 86400);
SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
}
/**
* @depends testResolveProcessDateTimeByWorkflowAndModelWithNullDate
* @expectedException ValueForProcessDateTimeIsNullException
*/
public function testResolveProcessDateTimeByWorkflowAndModelWithPseudoNullDate()
{
$model = new WorkflowModelTestItem();
$model->dateTime = '0000-00-00';
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('date', 'Is Time For', null, 86400);
SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
}
/**
* @depends testResolveProcessDateTimeByWorkflowAndModelWithPseudoNullDate
* @expectedException ValueForProcessDateTimeIsNullException
*/
public function testResolveProcessDateTimeByWorkflowAndModelWithNullDateTime()
{
$model = new WorkflowModelTestItem();
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('dateTime', 'Is Time For', null, 86400);
SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
}
/**
* @depends testResolveProcessDateTimeByWorkflowAndModelWithNullDateTime
* @expectedException ValueForProcessDateTimeIsNullException
*/
public function testResolveProcessDateTimeByWorkflowAndModelWithPseudoNullDateTime()
{
$model = new WorkflowModelTestItem();
$model->dateTime = '0000-00-00 00:00:00';
$workflow = WorkflowTriggersUtilBaseTest::
makeOnSaveWorkflowAndTimeTriggerForDateOrDateTime('dateTime', 'Is Time For', null, 86400);
SavedWorkflowsUtil::resolveProcessDateTimeByWorkflowAndModel($workflow, $model);
}
/**
* @depends testResolveProcessDateTimeByWorkflowAndModelWithPseudoNullDateTime
*/
public function testResolveOrder()
{
$this->assertCount(0, SavedWorkflow::getAll());
$savedWorkflow = new SavedWorkflow();
$savedWorkflow->name = 'the name';
$savedWorkflow->moduleClassName = 'AccountsModule';
$savedWorkflow->serializedData = serialize(array('some data'));
$savedWorkflow->triggerOn = Workflow::TRIGGER_ON_NEW;
$savedWorkflow->type = Workflow::TYPE_ON_SAVE;
$this->assertNull($savedWorkflow->order);
SavedWorkflowsUtil::resolveOrder($savedWorkflow);
$this->assertEquals(1, $savedWorkflow->order);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$savedWorkflowId1 = $savedWorkflow->id;
$savedWorkflow = new SavedWorkflow();
$savedWorkflow->name = 'the name 2';
$savedWorkflow->moduleClassName = 'AccountsModule';
$savedWorkflow->serializedData = serialize(array('some data 2'));
$savedWorkflow->triggerOn = Workflow::TRIGGER_ON_NEW;
$savedWorkflow->type = Workflow::TYPE_ON_SAVE;
$this->assertNull($savedWorkflow->order);
SavedWorkflowsUtil::resolveOrder($savedWorkflow);
$this->assertEquals(2, $savedWorkflow->order);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$savedWorkflowId2 = $savedWorkflow->id;
$savedWorkflow = new SavedWorkflow();
$savedWorkflow->name = 'the name 3';
$savedWorkflow->moduleClassName = 'AccountsModule';
$savedWorkflow->serializedData = serialize(array('some data 2'));
$savedWorkflow->triggerOn = Workflow::TRIGGER_ON_NEW;
$savedWorkflow->type = Workflow::TYPE_ON_SAVE;
$this->assertNull($savedWorkflow->order);
SavedWorkflowsUtil::resolveOrder($savedWorkflow);
$this->assertEquals(3, $savedWorkflow->order);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$savedWorkflowId3 = $savedWorkflow->id;
$savedWorkflow = new SavedWorkflow();
$savedWorkflow->name = 'the name 4';
$savedWorkflow->moduleClassName = 'ContactsModule';
$savedWorkflow->serializedData = serialize(array('some data'));
$savedWorkflow->triggerOn = Workflow::TRIGGER_ON_NEW;
$savedWorkflow->type = Workflow::TYPE_ON_SAVE;
$this->assertNull($savedWorkflow->order);
SavedWorkflowsUtil::resolveOrder($savedWorkflow);
$this->assertEquals(1, $savedWorkflow->order);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$savedWorkflowId4 = $savedWorkflow->id;
$savedWorkflow = SavedWorkflow::getById($savedWorkflowId2);
$this->assertEquals(2, $savedWorkflow->order);
SavedWorkflowsUtil::resolveOrder($savedWorkflow);
$this->assertEquals(2, $savedWorkflow->order);
//Change the moduleClassName to opportunities, it should show 1
$savedWorkflow->moduleClassName = 'OpportunitiesModule';
SavedWorkflowsUtil::resolveOrder($savedWorkflow);
$this->assertEquals(1, $savedWorkflow->order);
//Delete the workflow. When creating a new AccountsWorkflow, it should show order 4 since the max
//is still 3.
$deleted = $savedWorkflow->delete();
$this->assertTrue($deleted);
$savedWorkflow = new SavedWorkflow();
$savedWorkflow->name = 'the name 5';
$savedWorkflow->moduleClassName = 'AccountsModule';
$savedWorkflow->serializedData = serialize(array('some data 2'));
$savedWorkflow->triggerOn = Workflow::TRIGGER_ON_NEW;
$savedWorkflow->type = Workflow::TYPE_ON_SAVE;
$this->assertNull($savedWorkflow->order);
SavedWorkflowsUtil::resolveOrder($savedWorkflow);
$this->assertEquals(4, $savedWorkflow->order);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
}
/**
* @depends testResolveOrder
*/
public function testResolveBeforeSaveByModel()
{
//Create workflow
$workflow = new Workflow();
$workflow->setDescription ('aDescription');
$workflow->setIsActive (true);
$workflow->setOrder (5);
$workflow->setModuleClassName('WorkflowsTestModule');
$workflow->setName ('myFirstWorkflow');
$workflow->setTriggerOn (Workflow::TRIGGER_ON_NEW_AND_EXISTING);
$workflow->setType (Workflow::TYPE_ON_SAVE);
$workflow->setTriggersStructure('1');
//Add trigger
$trigger = new TriggerForWorkflowForm('WorkflowsTestModule', 'WorkflowModelTestItem', $workflow->getType());
$trigger->attributeIndexOrDerivedType = 'string';
$trigger->value = 'aValue';
$trigger->operator = 'equals';
$workflow->addTrigger($trigger);
//Add action
$action = new ActionForWorkflowForm('WorkflowModelTestItem', Workflow::TYPE_ON_SAVE);
$action->type = ActionForWorkflowForm::TYPE_UPDATE_SELF;
$attributes = array('string' => array('shouldSetValue' => '1',
'type' => WorkflowActionAttributeForm::TYPE_STATIC,
'value' => 'jason'));
$action->setAttributes(array(ActionForWorkflowForm::ACTION_ATTRIBUTES => $attributes));
$workflow->addAction($action);
//Create the saved Workflow
$savedWorkflow = new SavedWorkflow();
SavedWorkflowToWorkflowAdapter::resolveWorkflowToSavedWorkflow($workflow, $savedWorkflow);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
//Confirm that the workflow processes and the attribute gets updated
$model = new WorkflowModelTestItem();
$model->string = 'aValue';
SavedWorkflowsUtil::resolveBeforeSaveByModel($model, Yii::app()->user->userModel);
$this->assertEquals('jason', $model->string);
$this->assertTrue($model->id < 0);
//Change the workflow to inactive
$savedWorkflow->isActive = false;
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$model = new WorkflowModelTestItem();
$model->string = 'aValue';
SavedWorkflowsUtil::resolveBeforeSaveByModel($model, Yii::app()->user->userModel);
$this->assertEquals('aValue', $model->string);
$this->assertTrue($model->id < 0);
}
/**
* @depends testResolveBeforeSaveByModel
*/
public function testResolveBeforeSaveByModelForByTime()
{
//Create workflow
$workflow = new Workflow();
$workflow->setDescription ('aDescription');
$workflow->setIsActive (true);
$workflow->setOrder (5);
$workflow->setModuleClassName('WorkflowsTestModule');
$workflow->setName ('myFirstWorkflow');
$workflow->setTriggerOn (Workflow::TRIGGER_ON_NEW_AND_EXISTING);
$workflow->setType (Workflow::TYPE_BY_TIME);
$workflow->setTriggersStructure('1');
$workflow->setIsActive(true);
//Add time trigger
$trigger = new TimeTriggerForWorkflowForm('WorkflowsTestModule', 'WorkflowModelTestItem', $workflow->getType());
$trigger->attributeIndexOrDerivedType = 'date';
$trigger->durationSeconds = '500';
$trigger->valueType = 'Is Time For';
$workflow->setTimeTrigger($trigger);
//Create the saved Workflow
$savedWorkflow = new SavedWorkflow();
SavedWorkflowToWorkflowAdapter::resolveWorkflowToSavedWorkflow($workflow, $savedWorkflow);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
//Confirm that the workflow processes and the attribute gets updated
$model = new WorkflowModelTestItem();
$model->string = 'aValue';
$model->date = '2013-02-02';
$this->assertEquals(0, count($model->getWorkflowsToProcessAfterSave()));
SavedWorkflowsUtil::resolveBeforeSaveByModel($model, Yii::app()->user->userModel);
$this->assertEquals(1, count($model->getWorkflowsToProcessAfterSave()));
$this->assertTrue($model->id < 0);
}
/**
* @depends testResolveBeforeSaveByModelForByTime
*/
public function testResolveAfterSaveByModel()
{
//Create workflow
$workflow = new Workflow();
$workflow->setDescription ('aDescription');
$workflow->setIsActive (true);
$workflow->setOrder (5);
$workflow->setModuleClassName('WorkflowsTestModule');
$workflow->setName ('myFirstWorkflow');
$workflow->setTriggerOn (Workflow::TRIGGER_ON_NEW_AND_EXISTING);
$workflow->setType (Workflow::TYPE_ON_SAVE);
$workflow->setTriggersStructure('1');
$workflow->setIsActive(true);
//Add trigger
$trigger = new TriggerForWorkflowForm('WorkflowsTestModule', 'WorkflowModelTestItem', $workflow->getType());
$trigger->attributeIndexOrDerivedType = 'string';
$trigger->value = 'aValue';
$trigger->operator = 'equals';
$workflow->addTrigger($trigger);
//Add action
$action = new ActionForWorkflowForm('WorkflowModelTestItem', Workflow::TYPE_ON_SAVE);
$action->type = ActionForWorkflowForm::TYPE_CREATE;
$action->relation = 'hasOne';
$attributes = array('name' => array('shouldSetValue' => '1',
'type' => WorkflowActionAttributeForm::TYPE_STATIC,
'value' => 'jason'));
$action->setAttributes(array(ActionForWorkflowForm::ACTION_ATTRIBUTES => $attributes));
$workflow->addAction($action);
//Create the saved Workflow
$savedWorkflow = new SavedWorkflow();
SavedWorkflowToWorkflowAdapter::resolveWorkflowToSavedWorkflow($workflow, $savedWorkflow);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$model = new WorkflowModelTestItem();
$model->string = 'aValue';
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$model->addWorkflowToProcessAfterSave($workflow);
$this->assertEquals(0, count(WorkflowModelTestItem2::getAll()));
SavedWorkflowsUtil::resolveAfterSaveByModel($model, Yii::app()->user->userModel);
$this->assertEquals(1, count(WorkflowModelTestItem2::getAll()));
}
/**
* @depends testResolveAfterSaveByModel
*/
public function testResolveAfterSaveByModelForByTime()
{
//Create workflow
$workflow = new Workflow();
$workflow->setDescription ('aDescription');
$workflow->setIsActive (true);
$workflow->setOrder (5);
$workflow->setModuleClassName('WorkflowsTestModule');
$workflow->setName ('myFirstWorkflow');
$workflow->setTriggerOn (Workflow::TRIGGER_ON_NEW_AND_EXISTING);
$workflow->setType (Workflow::TYPE_BY_TIME);
$workflow->setTriggersStructure('1');
$workflow->setIsActive(true);
//Add time trigger
$trigger = new TimeTriggerForWorkflowForm('WorkflowsTestModule', 'WorkflowModelTestItem', $workflow->getType());
$trigger->attributeIndexOrDerivedType = 'date';
$trigger->durationSeconds = '500';
$trigger->valueType = 'Is Time For';
$workflow->setTimeTrigger($trigger);
//Create the saved Workflow
$savedWorkflow = new SavedWorkflow();
SavedWorkflowToWorkflowAdapter::resolveWorkflowToSavedWorkflow($workflow, $savedWorkflow);
$saved = $savedWorkflow->save();
$this->assertTrue($saved);
$workflow->setId($savedWorkflow->id); //set Id back.
$model = new WorkflowModelTestItem();
$model->lastName = 'something';
$model->string = 'aValue';
$model->date = '2013-03-03';
$saved = $model->save();
$this->assertTrue($saved);
$model->addWorkflowToProcessAfterSave($workflow);
$this->assertEquals(0, count(ByTimeWorkflowInQueue::getAll()));
SavedWorkflowsUtil::resolveAfterSaveByModel($model, Yii::app()->user->userModel);
$this->assertEquals(1, count(ByTimeWorkflowInQueue::getAll()));
}
}
?> | Java |
## ubuntu下安装OpenGL并搭建OpenGL开发环境
1.安装IDE: 这里使用的是codeblocks
sudo apt-get install codeblocks
2.配置linux下的openGL
下载并安装openGL所需要的库
sudo apt-get install mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev
sudo apt-get install freeglut3-dev
sudo apt-get install build-essential gdb subversion
sudo apt-get install automake autoconf libtool
sudo apt-get install libgtk2.0-dev libxmu-dev libxxf86vm-dev
3.配置codeblocks IDE
在Settings->compiler and debugger settings->link settings
添加:
/usr/lib/libGL.so
/usr/lib/libGLU.so
/usr/lib/libglut.so
4. 开发
开发的时候,新建GLUT工程,在main.cpp里面编写代码即可
新建后,自带有一个openGL的例子
| Java |
Ragnarok | Java |
# discourse-hot-topics
A plugin for Discourse. Adds ranking to topics ala Hacker News.
Translated to English, French and Russian.
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>GNU Radio 3.6.1 C++ API: gr_tagged_file_sink.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">GNU Radio 3.6.1 C++ API
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.7.6.1 -->
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('gr__tagged__file__sink_8h.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="headertitle">
<div class="title">gr_tagged_file_sink.h</div> </div>
</div><!--header-->
<div class="contents">
<a href="gr__tagged__file__sink_8h.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/* -*- c++ -*- */</span>
<a name="l00002"></a>00002 <span class="comment">/*</span>
<a name="l00003"></a>00003 <span class="comment"> * Copyright 2010 Free Software Foundation, Inc.</span>
<a name="l00004"></a>00004 <span class="comment"> *</span>
<a name="l00005"></a>00005 <span class="comment"> * This file is part of GNU Radio</span>
<a name="l00006"></a>00006 <span class="comment"> *</span>
<a name="l00007"></a>00007 <span class="comment"> * GNU Radio is free software; you can redistribute it and/or modify</span>
<a name="l00008"></a>00008 <span class="comment"> * it under the terms of the GNU General Public License as published by</span>
<a name="l00009"></a>00009 <span class="comment"> * the Free Software Foundation; either version 3, or (at your option)</span>
<a name="l00010"></a>00010 <span class="comment"> * any later version.</span>
<a name="l00011"></a>00011 <span class="comment"> *</span>
<a name="l00012"></a>00012 <span class="comment"> * GNU Radio is distributed in the hope that it will be useful,</span>
<a name="l00013"></a>00013 <span class="comment"> * but WITHOUT ANY WARRANTY; without even the implied warranty of</span>
<a name="l00014"></a>00014 <span class="comment"> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the</span>
<a name="l00015"></a>00015 <span class="comment"> * GNU General Public License for more details.</span>
<a name="l00016"></a>00016 <span class="comment"> *</span>
<a name="l00017"></a>00017 <span class="comment"> * You should have received a copy of the GNU General Public License</span>
<a name="l00018"></a>00018 <span class="comment"> * along with GNU Radio; see the file COPYING. If not, write to</span>
<a name="l00019"></a>00019 <span class="comment"> * the Free Software Foundation, Inc., 51 Franklin Street,</span>
<a name="l00020"></a>00020 <span class="comment"> * Boston, MA 02110-1301, USA.</span>
<a name="l00021"></a>00021 <span class="comment"> */</span>
<a name="l00022"></a>00022
<a name="l00023"></a>00023 <span class="preprocessor">#ifndef INCLUDED_GR_TAGGED_FILE_SINK_H</span>
<a name="l00024"></a>00024 <span class="preprocessor"></span><span class="preprocessor">#define INCLUDED_GR_TAGGED_FILE_SINK_H</span>
<a name="l00025"></a>00025 <span class="preprocessor"></span>
<a name="l00026"></a>00026 <span class="preprocessor">#include <<a class="code" href="gr__core__api_8h.html">gr_core_api.h</a>></span>
<a name="l00027"></a>00027 <span class="preprocessor">#include <<a class="code" href="gr__sync__block_8h.html">gr_sync_block.h</a>></span>
<a name="l00028"></a>00028 <span class="preprocessor">#include <cstdio></span> <span class="comment">// for FILE</span>
<a name="l00029"></a>00029
<a name="l00030"></a>00030 <span class="keyword">class </span><a class="code" href="classgr__tagged__file__sink.html" title="Write stream to file descriptor.">gr_tagged_file_sink</a>;
<a name="l00031"></a>00031 <span class="keyword">typedef</span> <a class="code" href="classboost_1_1shared__ptr.html" title="shared_ptr documentation stub">boost::shared_ptr<gr_tagged_file_sink></a> <a class="code" href="classboost_1_1shared__ptr.html" title="shared_ptr documentation stub">gr_tagged_file_sink_sptr</a>;
<a name="l00032"></a>00032
<a name="l00033"></a>00033 <a class="code" href="gr__core__api_8h.html#a8b8937b0c61edd85ab57ce8203543248">GR_CORE_API</a> <a class="code" href="classboost_1_1shared__ptr.html" title="shared_ptr documentation stub">gr_tagged_file_sink_sptr</a> <a class="code" href="gr__tagged__file__sink_8h.html#ae1631ce4f07efffc69d7f72c76e78190">gr_make_tagged_file_sink</a> (<span class="keywordtype">size_t</span> itemsize,
<a name="l00034"></a>00034 <span class="keywordtype">double</span> samp_rate);
<a name="l00035"></a>00035 <span class="comment"></span>
<a name="l00036"></a>00036 <span class="comment">/*!</span>
<a name="l00037"></a>00037 <span class="comment"> * \brief Write stream to file descriptor.</span>
<a name="l00038"></a>00038 <span class="comment"> * \ingroup sink_blk</span>
<a name="l00039"></a>00039 <span class="comment"> */</span>
<a name="l00040"></a>00040
<a name="l00041"></a><a class="code" href="classgr__tagged__file__sink.html">00041</a> <span class="keyword">class </span><a class="code" href="gr__core__api_8h.html#a8b8937b0c61edd85ab57ce8203543248">GR_CORE_API</a> <a class="code" href="classgr__tagged__file__sink.html" title="Write stream to file descriptor.">gr_tagged_file_sink</a> : <span class="keyword">public</span> <a class="code" href="classgr__sync__block.html" title="synchronous 1:1 input to output with historyOverride work to provide the signal processing implementa...">gr_sync_block</a>
<a name="l00042"></a>00042 {
<a name="l00043"></a>00043 <span class="keyword">friend</span> <a class="code" href="gr__core__api_8h.html#a8b8937b0c61edd85ab57ce8203543248">GR_CORE_API</a> <a class="code" href="classboost_1_1shared__ptr.html" title="shared_ptr documentation stub">gr_tagged_file_sink_sptr</a> <a class="code" href="gr__tagged__file__sink_8h.html#ae1631ce4f07efffc69d7f72c76e78190">gr_make_tagged_file_sink</a> (<span class="keywordtype">size_t</span> itemsize,
<a name="l00044"></a>00044 <span class="keywordtype">double</span> samp_rate);
<a name="l00045"></a>00045
<a name="l00046"></a>00046 <span class="keyword">private</span>:
<a name="l00047"></a>00047 <span class="keyword">enum</span> {
<a name="l00048"></a>00048 NOT_IN_BURST = 0,
<a name="l00049"></a>00049 IN_BURST
<a name="l00050"></a>00050 };
<a name="l00051"></a>00051
<a name="l00052"></a>00052 <span class="keywordtype">size_t</span> d_itemsize;
<a name="l00053"></a>00053 <span class="keywordtype">int</span> d_state;
<a name="l00054"></a>00054 FILE *d_handle;
<a name="l00055"></a>00055 <span class="keywordtype">int</span> d_n;
<a name="l00056"></a>00056 <span class="keywordtype">double</span> d_sample_rate;
<a name="l00057"></a>00057 <a class="code" href="stdint_8h.html#aec6fcb673ff035718c238c8c9d544c47">uint64_t</a> d_last_N;
<a name="l00058"></a>00058 <span class="keywordtype">double</span> d_timeval;
<a name="l00059"></a>00059
<a name="l00060"></a>00060 <span class="keyword">protected</span>:
<a name="l00061"></a>00061 <a class="code" href="classgr__tagged__file__sink.html" title="Write stream to file descriptor.">gr_tagged_file_sink</a> (<span class="keywordtype">size_t</span> itemsize, <span class="keywordtype">double</span> samp_rate);
<a name="l00062"></a>00062
<a name="l00063"></a>00063 <span class="keyword">public</span>:
<a name="l00064"></a>00064 ~<a class="code" href="classgr__tagged__file__sink.html" title="Write stream to file descriptor.">gr_tagged_file_sink</a> ();
<a name="l00065"></a>00065
<a name="l00066"></a>00066 <span class="keywordtype">int</span> <a class="code" href="classgr__sync__block.html#a0c523f4285a6eb690f677ee6295ab117" title="just like gr_block::general_work, only this arranges to call consume_each for you">work</a> (<span class="keywordtype">int</span> noutput_items,
<a name="l00067"></a>00067 <a class="code" href="gr__types_8h.html#a9852a3d906d823cb70eb9c29e7f2a43d">gr_vector_const_void_star</a> &input_items,
<a name="l00068"></a>00068 <a class="code" href="gr__types_8h.html#acd3f499576e769966ea44554b359d949">gr_vector_void_star</a> &output_items);
<a name="l00069"></a>00069 };
<a name="l00070"></a>00070
<a name="l00071"></a>00071
<a name="l00072"></a>00072 <span class="preprocessor">#endif </span><span class="comment">/* INCLUDED_GR_TAGGED_FILE_SINK_H */</span>
</pre></div></div><!-- contents -->
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="gr__tagged__file__sink_8h.html">gr_tagged_file_sink.h</a> </li>
<li class="footer">Generated on Wed Jun 13 2012 21:29:00 for GNU Radio 3.6.1 C++ API by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.6.1 </li>
</ul>
</div>
</body>
</html>
| Java |
/*
* Project: N|Watch
* Author: Zak Kemble, contact@zakkemble.co.uk
* Copyright: (C) 2014 by Zak Kemble
* License: GNU GPL v3 (see License.txt)
* Web: http://blog.zakkemble.co.uk/diy-digital-wristwatch/
*/
#ifndef ENGLISH_H_
#define ENGLISH_H_
// String buffer sizes
// Don't forget to add 1 for null terminator
#define BUFFSIZE_STR_MENU 24
#define BUFFSIZE_STR_DAYS 4
#define BUFFSIZE_STR_MONTHS 4
#define BUFFSIZE_DATE_FORMAT ((BUFFSIZE_STR_DAYS - 1) + (BUFFSIZE_STR_MONTHS - 1) + 12)
#define BUFFSIZE_TIME_FORMAT_SMALL 9
// String formats
#define DATE_FORMAT ("%s %02hhu %s 20%02hhu")
#define TIME_FORMAT_SMALL ("%02hhu:%02hhu%c")
#define CHAR_DEGREES 127
#define CHAR_TICK 128
#define CHAR_AM 'A'
#define CHAR_PM 'P'
#define CHAR_24 ' '
#define CHAR_YES 'Y'
#define CHAR_NO 'N'
#define STR_DOWCHARS "MTWTFSS"
// Days
// Also see BUFFSIZE_STR_DAYS
#define STR_MON "Mon"
#define STR_TUE "Tue"
#define STR_WED "Wed"
#define STR_THU "Thu"
#define STR_FRI "Fri"
#define STR_SAT "Sat"
#define STR_SUN "Sun"
// Months
// Also see BUFFSIZE_STR_MONTHS
#define STR_JAN "Jan"
#define STR_FEB "Feb"
#define STR_MAR "Mar"
#define STR_APR "Apr"
#define STR_MAY "May"
#define STR_JUN "Jun"
#define STR_JUL "Jul"
#define STR_AUG "Aug"
#define STR_SEP "Sep"
#define STR_OCT "Oct"
#define STR_NOV "Nov"
#define STR_DEC "Dec"
// Menu strings
// Also see BUFFSIZE_STR_MENU
#define STR_MAINMENU "< MAIN MENU >"
#define STR_ALARMS "Alarms"
#define STR_FLASHLIGHT "Flashlight"
#define STR_STOPWATCH "Stopwatch"
#define STR_STOP "Stop"
#define STR_SPLIT "Split"
#define STR_RUN "Run"
#define STR_RESET "Reset"
#define STR_GAMES "Games"
#define STR_SETTINGS "Settings"
#define STR_DIAGNOSTICS "Diagnostics"
//#define STR_BTRCCAR "BT RC Car"
//#define STR_TUNEMAKER "Tune maker"
//#define STR_CALCULATORS "Calculators"
#define STR_ALARMSMENU "< ALARMS >"
#define STR_TIMEDATEMENU "< TIME & DATE >"
#define STR_SAVE "Save"
#define STR_SAVED "Saved"
#define STR_DIAGNOSTICSMENU "< DIAGNOSTICS >"
#define STR_TEMPERATURE "Temperature %hhd.%hhuC"
#define STR_BATTERY "Battery %umV"
#define STR_SHOWFPS "Show FPS%9c"
#define STR_DISPLAYMENU "< DISPLAY >"
#define STR_BRIGHTNESS "Brightness"
#define STR_INVERT "Invert"
#define STR_ROTATE "Rotate"
#define STR_ANIMATIONS "Animations"
#define STR_GAMESMENU "< GAMES >"
#define STR_SOUNDMENU "< SOUND >"
#define STR_UI "UI"
#define STR_HOURBEEPS "Hour beeps"
#define STR_SLEEPMENU "< SLEEP >"
#define STR_TIMEOUT "Timeout"
//#define STR_CLOCKMODE "Clock mode"
#define STR_SETTINGSMENU "< SETTINGS >"
#define STR_TIMEDATE "Time & date"
#define STR_SLEEP "Sleep"
#define STR_SOUND "Sound"
#define STR_DISPLAY "Display"
#define STR_LEDS "LEDs"
//#define STR_RCSETTINGS "RC Settings"
#define STR_BACK "Back"
#define STR_EXIT "Exit"
// Game strings
#define STR_GAME1 "Breakout"
#define STR_GAME2 "Car Dodge"
#define STR_WIN "WIN!"
#define STR_GAMEOVER "GAMEOVER!"
#define STR_SCORE "Score:"
#define STR_HIGHSCORE "Highscore:"
#define STR_NEWHIGHSCORE "!NEW HIGHSCORE!"
// Little images (8x8) for showing day of week of next alarm on main screen
#define DOWIMG_MON 0x0F,0x01,0x02,0x01,0x6F,0x90,0x90,0x60
#define DOWIMG_TUE 0x01,0x1F,0x01,0x00,0x78,0x80,0x80,0x78
#define DOWIMG_WED 0x0F,0x04,0x02,0x04,0x0F,0xF8,0xA8,0xA8
#define DOWIMG_THU 0x01,0x1F,0x01,0x00,0xF8,0x20,0x20,0xF8
#define DOWIMG_FRI 0x1F,0x05,0x05,0x00,0xF8,0x28,0x68,0x90
#define DOWIMG_SAT 0x12,0x15,0x09,0x00,0xF0,0x28,0x28,0xF0
#define DOWIMG_SUN 0x12,0x15,0x09,0x00,0x78,0x80,0x80,0x78
// Character set for this language
#define CHARACTER_SET \
{0x00,0x00,0x00,0x00,0x00},/* space */ \
{0x00,0x5F,0x00,0x00,0x00},/* ! */ \
{0x00,0x07,0x00,0x07,0x00},/* " */ \
{0x14,0x7F,0x14,0x7F,0x14},/* # */ \
{0x24,0x2A,0x7F,0x2A,0x12},/* $ */ \
{0x23,0x13,0x08,0x64,0x62},/* % */ \
{0x36,0x49,0x55,0x22,0x50},/* & */ \
{0x00,0x05,0x03,0x00,0x00},/* ' */ \
{0x1C,0x22,0x41,0x00,0x00},/* ( */ \
{0x41,0x22,0x1C,0x00,0x00},/* ) */ \
{0x08,0x2A,0x1C,0x2A,0x08},/* * */ \
{0x08,0x08,0x3E,0x08,0x08},/* + */ \
{0xA0,0x60,0x00,0x00,0x00},/* , */ \
{0x08,0x08,0x08,0x08,0x08},/* - */ \
{0x60,0x60,0x00,0x00,0x00},/* . */ \
{0x20,0x10,0x08,0x04,0x02},/* / */ \
{0x3E,0x51,0x49,0x45,0x3E},/* 0 */ \
{0x00,0x42,0x7F,0x40,0x00},/* 1 */ \
{0x62,0x51,0x49,0x49,0x46},/* 2 */ \
{0x22,0x41,0x49,0x49,0x36},/* 3 */ \
{0x18,0x14,0x12,0x7F,0x10},/* 4 */ \
{0x27,0x45,0x45,0x45,0x39},/* 5 */ \
{0x3C,0x4A,0x49,0x49,0x30},/* 6 */ \
{0x01,0x71,0x09,0x05,0x03},/* 7 */ \
{0x36,0x49,0x49,0x49,0x36},/* 8 */ \
{0x06,0x49,0x49,0x29,0x1E},/* 9 */ \
{0x00,0x36,0x36,0x00,0x00},/* : */ \
{0x00,0xAC,0x6C,0x00,0x00},/* ; */ \
{0x08,0x14,0x22,0x41,0x00},/* < */ \
{0x14,0x14,0x14,0x14,0x14},/* = */ \
{0x41,0x22,0x14,0x08,0x00},/* > */ \
{0x02,0x01,0x51,0x09,0x06},/* ? */ \
{0x32,0x49,0x79,0x41,0x3E},/* @ */ \
{0x7E,0x09,0x09,0x09,0x7E},/* A */ \
{0x7F,0x49,0x49,0x49,0x36},/* B */ \
{0x3E,0x41,0x41,0x41,0x22},/* C */ \
{0x7F,0x41,0x41,0x22,0x1C},/* D */ \
{0x7F,0x49,0x49,0x49,0x41},/* E */ \
{0x7F,0x09,0x09,0x09,0x01},/* F */ \
{0x3E,0x41,0x41,0x51,0x72},/* G */ \
{0x7F,0x08,0x08,0x08,0x7F},/* H */ \
{0x41,0x7F,0x41,0x00,0x00},/* I */ \
{0x20,0x40,0x41,0x3F,0x01},/* J */ \
{0x7F,0x08,0x14,0x22,0x41},/* K */ \
{0x7F,0x40,0x40,0x40,0x40},/* L */ \
{0x7F,0x02,0x0C,0x02,0x7F},/* M */ \
{0x7F,0x04,0x08,0x10,0x7F},/* N */ \
{0x3E,0x41,0x41,0x41,0x3E},/* O */ \
{0x7F,0x09,0x09,0x09,0x06},/* P */ \
{0x3E,0x41,0x51,0x21,0x5E},/* Q */ \
{0x7F,0x09,0x19,0x29,0x46},/* R */ \
{0x26,0x49,0x49,0x49,0x32},/* S */ \
{0x01,0x01,0x7F,0x01,0x01},/* T */ \
{0x3F,0x40,0x40,0x40,0x3F},/* U */ \
{0x1F,0x20,0x40,0x20,0x1F},/* V */ \
{0x3F,0x40,0x38,0x40,0x3F},/* W */ \
{0x63,0x14,0x08,0x14,0x63},/* X */ \
{0x03,0x04,0x78,0x04,0x03},/* Y */ \
{0x61,0x51,0x49,0x45,0x43},/* Z */ \
{0x7F,0x41,0x41,0x00,0x00},/* [ */ \
{0x02,0x04,0x08,0x10,0x20},/* \ */ \
{0x41,0x41,0x7F,0x00,0x00},/* ] */ \
{0x04,0x02,0x01,0x02,0x04},/* ^ */ \
{0x80,0x80,0x80,0x80,0x80},/* _ */ \
{0x01,0x02,0x04,0x00,0x00},/* ' */ \
{0x20,0x54,0x54,0x54,0x78},/* a */ \
{0x7F,0x48,0x44,0x44,0x38},/* b */ \
{0x38,0x44,0x44,0x28,0x00},/* c */ \
{0x38,0x44,0x44,0x48,0x7F},/* d */ \
{0x38,0x54,0x54,0x54,0x18},/* e */ \
{0x08,0x7E,0x09,0x02,0x00},/* f */ \
{0x18,0xA4,0xA4,0xA4,0x7C},/* g */ \
{0x7F,0x08,0x04,0x04,0x78},/* h */ \
{0x00,0x7D,0x00,0x00,0x00},/* i */ \
{0x80,0x84,0x7D,0x00,0x00},/* j */ \
{0x7F,0x10,0x28,0x44,0x00},/* k */ \
{0x41,0x7F,0x40,0x00,0x00},/* l */ \
{0x7C,0x04,0x18,0x04,0x78},/* m */ \
{0x7C,0x08,0x04,0x7C,0x00},/* n */ \
{0x38,0x44,0x44,0x38,0x00},/* o */ \
{0xFC,0x24,0x24,0x18,0x00},/* p */ \
{0x18,0x24,0x24,0xFC,0x00},/* q */ \
{0x00,0x7C,0x08,0x04,0x00},/* r */ \
{0x48,0x54,0x54,0x24,0x00},/* s */ \
{0x04,0x7F,0x44,0x00,0x00},/* t */ \
{0x3C,0x40,0x40,0x7C,0x00},/* u */ \
{0x1C,0x20,0x40,0x20,0x1C},/* v */ \
{0x3C,0x40,0x30,0x40,0x3C},/* w */ \
{0x44,0x28,0x10,0x28,0x44},/* x */ \
{0x1C,0xA0,0xA0,0x7C,0x00},/* y */ \
{0x44,0x64,0x54,0x4C,0x44},/* z */ \
{0x08,0x36,0x41,0x00,0x00},/* { */ \
{0x00,0x7F,0x00,0x00,0x00},/* | */ \
{0x41,0x36,0x08,0x00,0x00},/* } */ \
{0x02,0x01,0x01,0x02,0x01},/* ~ */ \
{0x02,0x05,0x05,0x02,0x00},/* degrees (non-standard, normally DEL) */ \
{0x60,0xC0,0xF0,0x38,0x1C},/* tick (non-standard) */ \
#endif /* ENGLISH_H_ */
| Java |
////////////////////////////////////////////////////////////////////////////
// Atol file manager project <http://atol.sf.net>
//
// This code is licensed under BSD license.See "license.txt" for more details.
//
// File: TOFIX
////////////////////////////////////////////////////////////////////////////
/*
* console.c: various interactive-prompt routines shared between
* the console PuTTY tools
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "putty.h"
#include "storage.h"
#include "ssh.h"
int console_batch_mode = FALSE;
/*
* Clean up and exit.
*/
void cleanup_exit(int code)
{
/*
* Clean up.
*/
//TOFIX
//sk_cleanup();
//WSACleanup();
if (cfg.protocol == PROT_SSH) {
random_save_seed();
#ifdef MSCRYPTOAPI
crypto_wrapup();
#endif
}
//exit(code);
}
void verify_ssh_host_key(CSshSession &session, char *host, int port, char *keytype, char *keystr, char *fingerprint)
{
int ret, choice = 0;
//HANDLE hin;
//DWORD savemode, i;
static const char absentmsg_batch[] =
"The server's host key is not cached in the registry. You\n"
"have no guarantee that the server is the computer you\n"
"think it is.\n"
"The server's key fingerprint is:\n"
"%s\n"
"Connection abandoned.\n";
static const char absentmsg[] =
"The server's host key is not cached in the registry. You\n"
"have no guarantee that the server is the computer you\n"
"think it is.\n"
"The server's key fingerprint is:\n"
"%s\n"
"If you trust this host, press \"Yes\" to add the key to\n"
"PuTTY's cache and carry on connecting.\n"
"If you want to carry on connecting just once, without\n"
"adding the key to the cache, press \"No\".\n"
"If you do not trust this host, press \"Cancel\" to abandon the\n"
"connection.\n"
"Store key in cache? (y/n) ";
static const char wrongmsg_batch[] =
"WARNING - POTENTIAL SECURITY BREACH!\n"
"The server's host key does not match the one PuTTY has\n"
"cached in the registry. This means that either the\n"
"server administrator has changed the host key, or you\n"
"have actually connected to another computer pretending\n"
"to be the server.\n"
"The new key fingerprint is:\n"
"%s\n"
"Connection abandoned.\n";
static const char wrongmsg[] =
"WARNING - POTENTIAL SECURITY BREACH!\n"
"The server's host key does not match the one PuTTY has\n"
"cached in the registry. This means that either the\n"
"server administrator has changed the host key, or you\n"
"have actually connected to another computer pretending\n"
"to be the server.\n"
"The new key fingerprint is:\n"
"%s\n"
"If you were expecting this change and trust the new key,\n"
"press \"Yes\" to update Atol cache and continue connecting.\n"
"If you want to carry on connecting but without updating\n"
"the cache, press \"No\".\n"
"If you want to abandon the connection completely, press\n"
"\"Cancel\". Pressing \"Cancel\" is the ONLY guaranteed\n"
"safe choice.\n"
"Update cached key? (y/n, \"Cancel\" cancels connection) ";
static const char abandoned[] = "Connection abandoned.\n";
// char line[32];
/*
* Verify the key against the registry.
*/
ret = verify_host_key(host, port, keytype, keystr);
if (ret == 0) /* success - key matched OK */
return;
char szBuffer[512];
if (ret == 2) { /* key was different */
if (console_batch_mode) {
//TOFIX fprintf(stderr, wrongmsg_batch, fingerprint);
sprintf(szBuffer, wrongmsg_batch, fingerprint);
if(session.m_fnKeyWarning)
session.m_fnKeyWarning(szBuffer, 0, session.m_fnKeyData);
cleanup_exit(1);
}
//TOFIX fprintf(stderr, wrongmsg, fingerprint);
//TOFIX fflush(stderr);
sprintf(szBuffer, wrongmsg, fingerprint);
if(session.m_fnKeyWarning)
choice = session.m_fnKeyWarning(szBuffer, 1, session.m_fnKeyData);
}
if (ret == 1) { /* key was absent */
if (console_batch_mode) {
//TOFIX fprintf(stderr, absentmsg_batch, fingerprint);
sprintf(szBuffer, absentmsg_batch, fingerprint);
if(session.m_fnKeyWarning)
session.m_fnKeyWarning(szBuffer, 0, session.m_fnKeyData);
cleanup_exit(1);
}
//TOFIX fprintf(stderr, absentmsg, fingerprint);
//TOFIX fflush(stderr);
sprintf(szBuffer, absentmsg, fingerprint);
if(session.m_fnKeyWarning)
choice = session.m_fnKeyWarning(szBuffer, 1, session.m_fnKeyData);
}
//hin = GetStdHandle(STD_INPUT_HANDLE);
//if(hin)
{
//GetConsoleMode(hin, &savemode);
//SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT |
// ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT));
//ReadFile(hin, line, sizeof(line) - 1, &i, NULL);
//SetConsoleMode(hin, savemode);
//if (line[0] != '\0' && line[0] != '\r' && line[0] != '\n') {
if(choice > 0){
//if (line[0] == 'y' || line[0] == 'Y')
if(1 == choice)
store_host_key(host, port, keytype, keystr);
} else {
//TOFIX fprintf(stderr, abandoned);
sprintf(szBuffer, abandoned, fingerprint);
if(session.m_fnKeyWarning)
session.m_fnKeyWarning(szBuffer, 0, session.m_fnKeyData);
cleanup_exit(0);
}
}
}
/*
* Ask whether the selected cipher is acceptable (since it was
* below the configured 'warn' threshold).
* cs: 0 = both ways, 1 = client->server, 2 = server->client
*/
void askcipher(char *ciphername, int cs)
{
HANDLE hin;
DWORD savemode, i;
static const char msg[] =
"The first %scipher supported by the server is\n"
"%s, which is below the configured warning threshold.\n"
"Continue with connection? (y/n) ";
static const char msg_batch[] =
"The first %scipher supported by the server is\n"
"%s, which is below the configured warning threshold.\n"
"Connection abandoned.\n";
static const char abandoned[] = "Connection abandoned.\n";
char line[32];
if (console_batch_mode) {
//TOFIX fprintf(stderr, msg_batch,
//TOFIX (cs == 0) ? "" :
//TOFIX (cs == 1) ? "client-to-server " : "server-to-client ",
//TOFIX ciphername);
cleanup_exit(1);
}
//TOFIX fprintf(stderr, msg,
//TOFIX (cs == 0) ? "" :
//TOFIX (cs == 1) ? "client-to-server " : "server-to-client ",
//TOFIX ciphername);
//fflush(stderr);
hin = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(hin, &savemode);
SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT |
ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT));
ReadFile(hin, line, sizeof(line) - 1, &i, NULL);
SetConsoleMode(hin, savemode);
if (line[0] == 'y' || line[0] == 'Y') {
return;
} else {
//TOFIX fprintf(stderr, abandoned);
cleanup_exit(0);
}
}
/*
* Ask whether to wipe a session log file before writing to it.
* Returns 2 for wipe, 1 for append, 0 for cancel (don't log).
*/
int askappend(char *filename)
{
HANDLE hin;
DWORD savemode, i;
static const char msgtemplate[] =
"The session log file \"%.*s\" already exists.\n"
"You can overwrite it with a new session log,\n"
"append your session log to the end of it,\n"
"or disable session logging for this session.\n"
"Enter \"y\" to wipe the file, \"n\" to append to it,\n"
"or just press Return to disable logging.\n"
"Wipe the log file? (y/n, Return cancels logging) ";
static const char msgtemplate_batch[] =
"The session log file \"%.*s\" already exists.\n"
"Logging will not be enabled.\n";
char line[32];
if (cfg.logxfovr != LGXF_ASK) {
return ((cfg.logxfovr == LGXF_OVR) ? 2 : 1);
}
if (console_batch_mode) {
//TOFIX fprintf(stderr, msgtemplate_batch, FILENAME_MAX, filename);
//TOFIX fflush(stderr);
return 0;
}
//TOFIX fprintf(stderr, msgtemplate, FILENAME_MAX, filename);
//fflush(stderr);
hin = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(hin, &savemode);
SetConsoleMode(hin, (savemode | ENABLE_ECHO_INPUT |
ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT));
ReadFile(hin, line, sizeof(line) - 1, &i, NULL);
SetConsoleMode(hin, savemode);
if (line[0] == 'y' || line[0] == 'Y')
return 2;
else if (line[0] == 'n' || line[0] == 'N')
return 1;
else
return 0;
}
/*
* Warn about the obsolescent key file format.
*/
void old_keyfile_warning(void)
{
static const char message[] =
"You are loading an SSH 2 private key which has an\n"
"old version of the file format. This means your key\n"
"file is not fully tamperproof. Future versions of\n"
"PuTTY may stop supporting this private key format,\n"
"so we recommend you convert your key to the new\n"
"format.\n"
"\n"
"Once the key is loaded into PuTTYgen, you can perform\n"
"this conversion simply by saving it again.\n";
fputs(message, stderr);
}
//TOFIX move to CSshSession
void logevent(CSshSession &session, char *string)
{
if(session.m_dbgFn)
session.m_dbgFn(string, session.m_dwDbgData);
}
char *console_password = NULL;
int console_get_line(const char *prompt, char *str,
int maxlen, int is_pw)
{
HANDLE hin, hout;
DWORD savemode, newmode, i;
if (is_pw && console_password) {
static int tried_once = 0;
if (tried_once) {
return 0;
} else {
strncpy(str, console_password, maxlen);
str[maxlen - 1] = '\0';
tried_once = 1;
return 1;
}
}
if (console_batch_mode) {
if (maxlen > 0)
str[0] = '\0';
} else {
hin = GetStdHandle(STD_INPUT_HANDLE);
hout = GetStdHandle(STD_OUTPUT_HANDLE);
if (hin == INVALID_HANDLE_VALUE || hout == INVALID_HANDLE_VALUE) {
//TOFIX fprintf(stderr, "Cannot get standard input/output handles\n");
cleanup_exit(1);
}
if (hin == NULL || hout == NULL)
return 1;
GetConsoleMode(hin, &savemode);
newmode = savemode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT;
if (is_pw)
newmode &= ~ENABLE_ECHO_INPUT;
else
newmode |= ENABLE_ECHO_INPUT;
SetConsoleMode(hin, newmode);
WriteFile(hout, prompt, strlen(prompt), &i, NULL);
ReadFile(hin, str, maxlen - 1, &i, NULL);
SetConsoleMode(hin, savemode);
if ((int) i > maxlen)
i = maxlen - 1;
else
i = i - 2;
str[i] = '\0';
if (is_pw)
WriteFile(hout, "\r\n", 2, &i, NULL);
}
return 1;
}
| Java |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>ActiveJob::Core::ClassMethods</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/github.css" type="text/css" media="screen" />
<script src="../../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/main.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="banner">
<span>Ruby on Rails 4.2.6</span><br />
<h1>
<span class="type">Module</span>
ActiveJob::Core::ClassMethods
</h1>
<ul class="files">
<li><a href="../../../files/__/__/_rbenv/versions/2_4_0/lib/ruby/gems/2_4_0/gems/activejob-4_2_6/lib/active_job/core_rb.html">/home/user/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activejob-4.2.6/lib/active_job/core.rb</a></li>
</ul>
</div>
<div id="bodyContent">
<div id="content">
<div class="description">
<p>These methods will be included into any Active Job object, adding helpers
for de/serialization and creation of job instances.</p>
</div>
<!-- Method ref -->
<div class="sectiontitle">Methods</div>
<dl class="methods">
<dt>D</dt>
<dd>
<ul>
<li>
<a href="#method-i-deserialize">deserialize</a>
</li>
</ul>
</dd>
<dt>S</dt>
<dd>
<ul>
<li>
<a href="#method-i-set">set</a>
</li>
</ul>
</dd>
</dl>
<!-- Methods -->
<div class="sectiontitle">Instance Public methods</div>
<div class="method">
<div class="title method-title" id="method-i-deserialize">
<b>deserialize</b>(job_data)
<a href="../../../classes/ActiveJob/Core/ClassMethods.html#method-i-deserialize" name="method-i-deserialize" class="permalink">Link</a>
</div>
<div class="description">
<p>Creates a new job instance from a hash created with <code>serialize</code></p>
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-deserialize_source')" id="l_method-i-deserialize_source">show</a>
</p>
<div id="method-i-deserialize_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activejob-4.2.6/lib/active_job/core.rb, line 27</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">deserialize</span>(<span class="ruby-identifier">job_data</span>)
<span class="ruby-identifier">job</span> = <span class="ruby-identifier">job_data</span>[<span class="ruby-string">'job_class'</span>].<span class="ruby-identifier">constantize</span>.<span class="ruby-identifier">new</span>
<span class="ruby-identifier">job</span>.<span class="ruby-identifier">job_id</span> = <span class="ruby-identifier">job_data</span>[<span class="ruby-string">'job_id'</span>]
<span class="ruby-identifier">job</span>.<span class="ruby-identifier">queue_name</span> = <span class="ruby-identifier">job_data</span>[<span class="ruby-string">'queue_name'</span>]
<span class="ruby-identifier">job</span>.<span class="ruby-identifier">serialized_arguments</span> = <span class="ruby-identifier">job_data</span>[<span class="ruby-string">'arguments'</span>]
<span class="ruby-identifier">job</span>.<span class="ruby-identifier">locale</span> = <span class="ruby-identifier">job_data</span>[<span class="ruby-string">'locale'</span>] <span class="ruby-operator">||</span> <span class="ruby-constant">I18n</span>.<span class="ruby-identifier">locale</span>
<span class="ruby-identifier">job</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-set">
<b>set</b>(options={})
<a href="../../../classes/ActiveJob/Core/ClassMethods.html#method-i-set" name="method-i-set" class="permalink">Link</a>
</div>
<div class="description">
<p>Creates a job preconfigured with the given options. You can call
perform_later with the job arguments to enqueue the job with the
preconfigured options</p>
<h4 id="method-i-set-label-Options">Options</h4>
<ul><li>
<p><code>:wait</code> - Enqueues the job with the specified delay</p>
</li><li>
<p><code>:wait_until</code> - Enqueues the job at the time specified</p>
</li><li>
<p><code>:queue</code> - Enqueues the job on the specified queue</p>
</li></ul>
<h4 id="method-i-set-label-Examples">Examples</h4>
<pre><code>VideoJob.set(queue: :some_queue).perform_later(Video.last)
VideoJob.set(wait: 5.minutes).perform_later(Video.last)
VideoJob.set(wait_until: Time.now.tomorrow).perform_later(Video.last)
VideoJob.set(queue: :some_queue, wait: 5.minutes).perform_later(Video.last)
VideoJob.set(queue: :some_queue, wait_until: Time.now.tomorrow).perform_later(Video.last)
</code></pre>
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-set_source')" id="l_method-i-set_source">show</a>
</p>
<div id="method-i-set_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/activejob-4.2.6/lib/active_job/core.rb, line 52</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">set</span>(<span class="ruby-identifier">options</span>={})
<span class="ruby-constant">ConfiguredJob</span>.<span class="ruby-identifier">new</span>(<span class="ruby-keyword">self</span>, <span class="ruby-identifier">options</span>)
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
| Java |
/*
Copyright 2011-2014 Red Hat, Inc
This file is part of PressGang CCMS.
PressGang CCMS is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PressGang CCMS 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 for more details.
You should have received a copy of the GNU Lesser General Public License
along with PressGang CCMS. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jboss.pressgang.ccms.rest.v1.query;
import java.util.ArrayList;
import java.util.List;
import org.jboss.pressgang.ccms.rest.v1.constants.CommonFilterConstants;
import org.jboss.pressgang.ccms.rest.v1.query.base.RESTBaseQueryBuilderV1;
import org.jboss.pressgang.ccms.utils.structures.Pair;
public class RESTPropertyCategoryQueryBuilderV1 extends RESTBaseQueryBuilderV1 {
private static List<Pair<String, String>> filterPairs = new ArrayList<Pair<String, String>>() {
private static final long serialVersionUID = -8638470044710698912L;
{
add(new Pair<String, String>(CommonFilterConstants.PROP_CATEGORY_IDS_FILTER_VAR,
CommonFilterConstants.PROP_CATEGORY_IDS_FILTER_VAR_DESC));
add(new Pair<String, String>(CommonFilterConstants.PROP_CATEGORY_NAME_FILTER_VAR,
CommonFilterConstants.PROP_CATEGORY_NAME_FILTER_VAR_DESC));
add(new Pair<String, String>(CommonFilterConstants.PROP_CATEGORY_DESCRIPTION_FILTER_VAR,
CommonFilterConstants.PROP_CATEGORY_DESCRIPTION_FILTER_VAR_DESC));
}
};
public static List<Pair<String, String>> getFilterInfo() {
return filterPairs;
}
public static String getFilterDesc(final String varName) {
if (varName == null) return null;
final List<Pair<String, String>> filterInfo = getFilterInfo();
for (final Pair<String, String> varInfo : filterInfo) {
if (varInfo.getFirst().equals(varName)) {
return varInfo.getSecond();
}
}
return null;
}
public List<Integer> getPropertyCategoryIds() {
final String propertyCategoryIdsString = get(CommonFilterConstants.PROP_CATEGORY_IDS_FILTER_VAR);
return getIntegerList(propertyCategoryIdsString);
}
public void setPropertyCategoryIds(final List<Integer> propertyCategoryIds) {
put(CommonFilterConstants.PROP_CATEGORY_IDS_FILTER_VAR, propertyCategoryIds);
}
public String getPropertyCategoryName() {
return get(CommonFilterConstants.PROP_CATEGORY_NAME_FILTER_VAR);
}
public void setPropertyCategoryName(final String propertyCategoryName) {
put(CommonFilterConstants.PROP_CATEGORY_NAME_FILTER_VAR, propertyCategoryName);
}
public String getPropertyCategoryDescription() {
return get(CommonFilterConstants.PROP_CATEGORY_DESCRIPTION_FILTER_VAR);
}
public void setPropertyCategoryDescription(final String propertyCategoryDescription) {
put(CommonFilterConstants.PROP_CATEGORY_DESCRIPTION_FILTER_VAR, propertyCategoryDescription);
}
} | Java |
<?php
/**
* This file is part of OXID eShop Community Edition.
*
* OXID eShop Community Edition 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.
*
* OXID eShop Community Edition 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 OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>.
*
* @link http://www.oxid-esales.com
* @package core
* @copyright (C) OXID eSales AG 2003-2013
* @version OXID eShop CE
* @version SVN: $Id: oxnews.php 48786 2012-08-17 10:20:42Z tomas $
*/
/**
* News manager.
* Performs news text collection. News may be sorted by user categories (only
* these user may read news), etc.
*
* @package model
*/
class oxNews extends oxI18n
{
/**
* User group object (default null).
*
* @var object
*/
protected $_oGroups = null;
/**
* Current class name
*
* @var string
*/
protected $_sClassName = 'oxnews';
/**
* Class constructor, initiates parent constructor (parent::oxI18n()).
*
* @return null
*/
public function __construct()
{
parent::__construct();
$this->init('oxnews');
}
/**
* Assigns object data.
*
* @param string $dbRecord database record to be assigned
*
* @return null
*/
public function assign( $dbRecord )
{
parent::assign( $dbRecord );
// convert date's to international format
if ($this->oxnews__oxdate) {
$this->oxnews__oxdate->setValue( oxRegistry::get("oxUtilsDate")->formatDBDate( $this->oxnews__oxdate->value ) );
}
}
/**
* Returns list of user groups assigned to current news object
*
* @return oxlist
*/
public function getGroups()
{
if ( $this->_oGroups == null && $sOxid = $this->getId() ) {
// usergroups
$this->_oGroups = oxNew( 'oxlist', 'oxgroups' );
$sViewName = getViewName( "oxgroups", $this->getLanguage() );
$sSelect = "select {$sViewName}.* from {$sViewName}, oxobject2group ";
$sSelect .= "where oxobject2group.oxobjectid='$sOxid' ";
$sSelect .= "and oxobject2group.oxgroupsid={$sViewName}.oxid ";
$this->_oGroups->selectString( $sSelect );
}
return $this->_oGroups;
}
/**
* Checks if this object is in group, returns true on success.
*
* @param string $sGroupID user group ID
*
* @return bool
*/
public function inGroup( $sGroupID )
{
$blResult = false;
$aGroups = $this->getGroups();
foreach ( $aGroups as $oObject ) {
if ( $oObject->_sOXID == $sGroupID ) {
$blResult = true;
break;
}
}
return $blResult;
}
/**
* Deletes object information from DB, returns true on success.
*
* @param string $sOxid Object ID (default null)
*
* @return bool
*/
public function delete( $sOxid = null )
{
if ( !$sOxid ) {
$sOxid = $this->getId();
}
if ( !$sOxid ) {
return false;
}
if ( $blDelete = parent::delete( $sOxid ) ) {
$oDb = oxDb::getDb();
$oDb->execute( "delete from oxobject2group where oxobject2group.oxobjectid = ".$oDb->quote( $sOxid ) );
}
return $blDelete;
}
/**
* Updates object information in DB.
*
* @return null
*/
protected function _update()
{
$this->oxnews__oxdate->setValue( oxRegistry::get("oxUtilsDate")->formatDBDate( $this->oxnews__oxdate->value, true ) );
parent::_update();
}
/**
* Inserts object details to DB, returns true on success.
*
* @return bool
*/
protected function _insert()
{
if ( !$this->oxnews__oxdate || oxRegistry::get("oxUtilsDate")->isEmptyDate( $this->oxnews__oxdate->value ) ) {
// if date field is empty, assigning current date
$this->oxnews__oxdate = new oxField( date( 'Y-m-d' ) );
} else {
$this->oxnews__oxdate = new oxField( oxRegistry::get("oxUtilsDate")->formatDBDate( $this->oxnews__oxdate->value, true ) );
}
return parent::_insert();
}
/**
* Sets data field value
*
* @param string $sFieldName index OR name (eg. 'oxarticles__oxtitle') of a data field to set
* @param string $sValue value of data field
* @param int $iDataType field type
*
* @return null
*/
protected function _setFieldData( $sFieldName, $sValue, $iDataType = oxField::T_TEXT)
{
switch (strtolower($sFieldName)) {
case 'oxlongdesc':
case 'oxnews__oxlongdesc':
$iDataType = oxField::T_RAW;
break;
}
return parent::_setFieldData($sFieldName, $sValue, $iDataType);
}
/**
* get long description, parsed through smarty
*
* @return string
*/
public function getLongDesc()
{
return oxRegistry::get("oxUtilsView")->parseThroughSmarty( $this->oxnews__oxlongdesc->getRawValue(), $this->getId().$this->getLanguage() );
}
}
| Java |
<?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2011 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
*/
$language_array = Array(
/* do not edit above this line */
'del_from_mail_list'=>'Izbriši sa newsletter liste',
'del_key'=>'Kod za brisanje',
'delete'=>'Izbriši',
'deletion_key'=>'Kod za brisanje',
'email_not_valid'=>'Vaš e-mail nije ispravno upisan!',
'lost_deletion_key'=>'Izgubili ste kod za brisanje?',
'mail_adress'=>'E-mail adresa',
'mail_pw_didnt_match'=>'E-mail/lozinka se ne podudaraju.',
'mail_not_in_db'=>'Upisana e-mail adresa ne postoji u našoj bazi.',
'newsletter'=>'newsletter',
'newsletter_registration'=>'Registracija za newsletter',
'no_such_mail_adress'=>'Ne postoji takva e-mail adresa.',
'password_had_been_send'=>'Lozinka je poslana.',
'register_newsletter'=>'Registriraj se za newsletter',
'request_mail'=>'<b>Treba Vam vaš kod za brisanje!</b><br /><br />Da bi maknuli Vaš e-mail sa liste mailova za newsletter kliknite <a href="http://%homepage_url%/index.php?site=newsletter&mail=%mail%&pass=%delete_key%">ovdje</a><br />Vaša lozinka za brisanje s liste: %delete_key%<br /><br />Vidimo se na %homepage_url%',
'send'=>'Pošalji',
'submit'=>'Spremi',
'success_mail'=>'<b>Hvala Vam na registraciji!</b><br /><br />Da bi maknuli Vaš e-mail sa liste mailova za newsletter kliknite <a href="http://%homepage_url%/index.php?site=newsletter&mail=%mail%&pass=%delete_key%">ovdje</a><br />Vaša lozinka za brisanje s liste: %delete_key%<br /><br />Vidimo se na %homepage_url%',
'thank_you_for_registration'=>'Hvala Vam na registraciji.',
'you_are_already_registered'=>'Već ste registrirani.',
'your_mail_adress'=>'Vaš e-mail',
'your_mail_adress_deleted'=>'Vaš e-mail je maknut s liste.'
);
?> | Java |
CREATE TABLE "south_boston_planning_district_2010_census_population" (
);
| Java |
/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana
*
* Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA.
*
* For more information, contact:
*
* Generalitat Valenciana
* Conselleria d'Infraestructures i Transport
* Av. Blasco Ibáñez, 50
* 46010 VALENCIA
* SPAIN
*
* +34 963862235
* gvsig@gva.es
* www.gvsig.gva.es
*
* or
*
* IVER T.I. S.A
* Salamanca 50
* 46005 Valencia
* Spain
*
* +34 963163400
* dac@iver.es
*/
package com.iver.cit.gvsig.fmap.layers;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.PrintQuality;
import org.apache.log4j.Logger;
import org.cresques.cts.ICoordTrans;
import org.gvsig.tools.file.PathGenerator;
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
import com.hardcode.gdbms.engine.data.DataSourceFactory;
import com.hardcode.gdbms.engine.data.NoSuchTableException;
import com.hardcode.gdbms.engine.data.driver.DriverException;
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
import com.iver.cit.gvsig.exceptions.layers.LegendLayerException;
import com.iver.cit.gvsig.exceptions.layers.ReloadLayerException;
import com.iver.cit.gvsig.exceptions.layers.ReprojectLayerException;
import com.iver.cit.gvsig.exceptions.layers.StartEditionLayerException;
import com.iver.cit.gvsig.exceptions.visitors.StartWriterVisitorException;
import com.iver.cit.gvsig.exceptions.visitors.VisitorException;
import com.iver.cit.gvsig.fmap.MapContext;
import com.iver.cit.gvsig.fmap.MapControl;
import com.iver.cit.gvsig.fmap.ViewPort;
import com.iver.cit.gvsig.fmap.core.CartographicSupport;
import com.iver.cit.gvsig.fmap.core.FPoint2D;
import com.iver.cit.gvsig.fmap.core.FShape;
import com.iver.cit.gvsig.fmap.core.IFeature;
import com.iver.cit.gvsig.fmap.core.IGeometry;
import com.iver.cit.gvsig.fmap.core.ILabelable;
import com.iver.cit.gvsig.fmap.core.IRow;
import com.iver.cit.gvsig.fmap.core.symbols.IMultiLayerSymbol;
import com.iver.cit.gvsig.fmap.core.symbols.ISymbol;
import com.iver.cit.gvsig.fmap.core.symbols.SimpleLineSymbol;
import com.iver.cit.gvsig.fmap.core.v02.FConverter;
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
import com.iver.cit.gvsig.fmap.drivers.featureiterators.JoinFeatureIterator;
import com.iver.cit.gvsig.fmap.edition.AfterFieldEditEvent;
import com.iver.cit.gvsig.fmap.edition.AfterRowEditEvent;
import com.iver.cit.gvsig.fmap.edition.AnnotationEditableAdapter;
import com.iver.cit.gvsig.fmap.edition.BeforeFieldEditEvent;
import com.iver.cit.gvsig.fmap.edition.BeforeRowEditEvent;
import com.iver.cit.gvsig.fmap.edition.EditionEvent;
import com.iver.cit.gvsig.fmap.edition.IEditionListener;
import com.iver.cit.gvsig.fmap.edition.ISpatialWriter;
import com.iver.cit.gvsig.fmap.edition.IWriteable;
import com.iver.cit.gvsig.fmap.edition.IWriter;
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
import com.iver.cit.gvsig.fmap.edition.VectorialEditableDBAdapter;
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
import com.iver.cit.gvsig.fmap.layers.layerOperations.RandomVectorialData;
import com.iver.cit.gvsig.fmap.layers.layerOperations.SingleLayer;
import com.iver.cit.gvsig.fmap.layers.layerOperations.VectorialData;
import com.iver.cit.gvsig.fmap.layers.layerOperations.VectorialXMLItem;
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
import com.iver.cit.gvsig.fmap.operations.strategies.FeatureVisitor;
import com.iver.cit.gvsig.fmap.operations.strategies.Strategy;
import com.iver.cit.gvsig.fmap.operations.strategies.StrategyManager;
import com.iver.cit.gvsig.fmap.rendering.IClassifiedVectorLegend;
import com.iver.cit.gvsig.fmap.rendering.ILegend;
import com.iver.cit.gvsig.fmap.rendering.IVectorLegend;
import com.iver.cit.gvsig.fmap.rendering.LegendClearEvent;
import com.iver.cit.gvsig.fmap.rendering.LegendContentsChangedListener;
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
import com.iver.cit.gvsig.fmap.rendering.SingleSymbolLegend;
import com.iver.cit.gvsig.fmap.rendering.SymbolLegendEvent;
import com.iver.cit.gvsig.fmap.rendering.ZSort;
import com.iver.cit.gvsig.fmap.rendering.styling.labeling.AttrInTableLabelingStrategy;
import com.iver.cit.gvsig.fmap.rendering.styling.labeling.ILabelingStrategy;
import com.iver.cit.gvsig.fmap.rendering.styling.labeling.LabelingFactory;
import com.iver.cit.gvsig.fmap.spatialindex.IPersistentSpatialIndex;
import com.iver.cit.gvsig.fmap.spatialindex.ISpatialIndex;
import com.iver.cit.gvsig.fmap.spatialindex.QuadtreeGt2;
import com.iver.cit.gvsig.fmap.spatialindex.QuadtreeJts;
import com.iver.cit.gvsig.fmap.spatialindex.SpatialIndexException;
import com.iver.utiles.FileUtils;
import com.iver.utiles.IPersistence;
import com.iver.utiles.NotExistInXMLEntity;
import com.iver.utiles.PostProcessSupport;
import com.iver.utiles.XMLEntity;
import com.iver.utiles.swing.threads.Cancellable;
import com.iver.utiles.swing.threads.CancellableMonitorable;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.TopologyException;
/**
* Capa básica Vectorial.
*
* @author Fernando González Cortés
*/
public class FLyrVect extends FLyrDefault implements ILabelable,
ClassifiableVectorial, SingleLayer, VectorialData, RandomVectorialData,
AlphanumericData, InfoByPoint, SelectionListener, IEditionListener, LegendContentsChangedListener {
private static Logger logger = Logger.getLogger(FLyrVect.class.getName());
/** Leyenda de la capa vectorial */
private IVectorLegend legend;
private int typeShape = -1;
private ReadableVectorial source;
private SelectableDataSource sds;
private SpatialCache spatialCache = new SpatialCache();
private boolean spatialCacheEnabled = false;
/**
* An implementation of gvSIG spatial index
*/
protected ISpatialIndex spatialIndex = null;
private boolean bHasJoin = false;
private XMLEntity orgXMLEntity = null;
private XMLEntity loadSelection = null;
private IVectorLegend loadLegend = null;
//Lo añado. Características de HyperEnlace (LINK)
private FLyrVectLinkProperties linkProperties=new FLyrVectLinkProperties();
//private ArrayList linkProperties=null;
private boolean waitTodraw=false;
private static PathGenerator pathGenerator=PathGenerator.getInstance();
public boolean isWaitTodraw() {
return waitTodraw;
}
public void setWaitTodraw(boolean waitTodraw) {
this.waitTodraw = waitTodraw;
}
/**
* Devuelve el VectorialAdapater de la capa.
*
* @return VectorialAdapter.
*/
public ReadableVectorial getSource() {
if (!this.isAvailable()) return null;
return source;
}
/**
* If we use a persistent spatial index associated with this layer, and the
* index is not intrisic to the layer (for example spatial databases) this
* method looks for existent spatial index, and loads it.
*
*/
private void loadSpatialIndex() {
//FIXME: Al abrir el indice en fichero...
//¿Cómo lo liberamos? un metodo Layer.shutdown()
ReadableVectorial source = getSource();
//REVISAR QUE PASA CON LOS DRIVERS DXF, DGN, etc.
//PUES SON VECTORIALFILEADAPTER
if (!(source instanceof VectorialFileAdapter)) {
// we are not interested in db adapters
return;
}
VectorialDriver driver = source.getDriver();
if (!(driver instanceof BoundedShapes)) {
// we dont spatially index layers that are not bounded
return;
}
File file = ((VectorialFileAdapter) source).getFile();
String fileName = file.getAbsolutePath();
File sptFile = new File(fileName + ".qix");
if (!sptFile.exists() || (!(sptFile.length() > 0))) {
// before to exit, look for it in temp path
String tempPath = System.getProperty("java.io.tmpdir");
fileName = tempPath + File.separator + sptFile.getName();
sptFile = new File(fileName);
// it doesnt exists, must to create
if (!sptFile.exists() || (!(sptFile.length() > 0))) {
return;
}// if
}// if
try {
source.start();
spatialIndex = new QuadtreeGt2(FileUtils.getFileWithoutExtension(sptFile),
"NM", source.getFullExtent(), source.getShapeCount(), false);
source.setSpatialIndex(spatialIndex);
} catch (SpatialIndexException e) {
spatialIndex = null;
e.printStackTrace();
return;
} catch (ReadDriverException e) {
spatialIndex = null;
e.printStackTrace();
return;
}
}
/**
* Checks if it has associated an external spatial index
* (an spatial index file).
*
* It looks for it in main file path, or in temp system path.
* If main file is rivers.shp, it looks for a file called
* rivers.shp.qix.
* @return
*/
public boolean isExternallySpatiallyIndexed() {
/*
* FIXME (AZABALA): Independizar del tipo de fichero de índice
* con el que se trabaje (ahora mismo considera la extension .qix,
* pero esto dependerá del tipo de índice)
* */
ReadableVectorial source = getSource();
if (!(source instanceof VectorialFileAdapter)) {
// we are not interested in db adapters.
// think in non spatial dbs, like HSQLDB
return false;
}
File file = ((VectorialFileAdapter) source).getFile();
String fileName = file.getAbsolutePath();
File sptFile = new File(fileName + ".qix");
if (!sptFile.exists() || (!(sptFile.length() > 0))) {
// before to exit, look for it in temp path
// it doesnt exists, must to create
String tempPath = System.getProperty("java.io.tmpdir");
fileName = tempPath + File.separator + sptFile.getName();
sptFile = new File(fileName);
if (!sptFile.exists() || (!(sptFile.length() > 0))) {
return false;
}// if
}// if
return true;
}
/**
* Inserta el VectorialAdapter a la capa.
*
* @param va
* VectorialAdapter.
*/
public void setSource(ReadableVectorial rv) {
source = rv;
// azabala: we check if this layer could have a file spatial index
// and load it if it exists
loadSpatialIndex();
}
public Rectangle2D getFullExtent() throws ReadDriverException, ExpansionFileReadException {
Rectangle2D rAux;
source.start();
rAux = (Rectangle2D)source.getFullExtent().clone();
source.stop();
// Si existe reproyección, reproyectar el extent
if (!(this.getProjection()!=null &&
this.getMapContext().getProjection()!=null &&
this.getProjection().getAbrev().equals(this.getMapContext().getProjection().getAbrev()))){
ICoordTrans ct = getCoordTrans();
try{
if (ct != null) {
Point2D pt1 = new Point2D.Double(rAux.getMinX(), rAux.getMinY());
Point2D pt2 = new Point2D.Double(rAux.getMaxX(), rAux.getMaxY());
pt1 = ct.convert(pt1, null);
pt2 = ct.convert(pt2, null);
rAux = new Rectangle2D.Double();
rAux.setFrameFromDiagonal(pt1, pt2);
}
}catch (IllegalStateException e) {
this.setAvailable(false);
this.addError(new ReprojectLayerException(getName(), e));
}
}
//Esto es para cuando se crea una capa nueva con el fullExtent de ancho y alto 0.
if (rAux.getWidth()==0 && rAux.getHeight()==0) {
rAux=new Rectangle2D.Double(0,0,100,100);
}
return rAux;
}
/**
* Draws using IFeatureIterator. This method will replace the old draw(...) one.
* @autor jaume dominguez faus - jaume.dominguez@iver.es
* @param image
* @param g
* @param viewPort
* @param cancel
* @param scale
* @throws ReadDriverException
*/
private void _draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
Cancellable cancel, double scale) throws ReadDriverException {
boolean bDrawShapes = true;
if (legend instanceof SingleSymbolLegend) {
bDrawShapes = legend.getDefaultSymbol().isShapeVisible();
}
Point2D offset = viewPort.getOffset();
double dpi = MapContext.getScreenDPI();
if (bDrawShapes) {
boolean cacheFeatures = isSpatialCacheEnabled();
SpatialCache cache = null;
if (cacheFeatures) {
getSpatialCache().clearAll();
cache = getSpatialCache();
}
try {
ArrayList<String> fieldList = new ArrayList<String>();
// fields from legend
String[] aux = null;
if (legend instanceof IClassifiedVectorLegend) {
aux = ((IClassifiedVectorLegend) legend).getClassifyingFieldNames();
if (aux!=null) {
for (int i = 0; i < aux.length; i++) {
// check fields exists
if (sds.getFieldIndexByName(aux[i]) == -1) {
logger.warn("Error en leyenda de " + getName() +
". El campo " + aux[i] + " no está.");
legend = LegendFactory.createSingleSymbolLegend(getShapeType());
break;
}
fieldList.add(aux[i]);
}
}
}
// Get the iterator over the visible features
IFeatureIterator it = null;
if (isJoined()) {
it = new JoinFeatureIterator(this, viewPort,
fieldList.toArray(new String[fieldList.size()]));
}
else {
ReadableVectorial rv=getSource();
// rv.start();
it = rv.getFeatureIterator(
viewPort.getAdjustedExtent(),
fieldList.toArray(new String[fieldList.size()]),
viewPort.getProjection(),
true);
// rv.stop();
}
ZSort zSort = ((IVectorLegend) getLegend()).getZSort();
boolean bSymbolLevelError = false;
// if layer has map levels it will use a ZSort
boolean useZSort = zSort != null && zSort.isUsingZSort();
// -- visual FX stuff
long time = System.currentTimeMillis();
BufferedImage virtualBim;
Graphics2D virtualGraphics;
// render temporary map each screenRefreshRate milliseconds;
int screenRefreshDelay = (int) ((1D/MapControl.getDrawFrameRate())*3*1000);
BufferedImage[] imageLevels = null;
Graphics2D[] graphics = null;
if (useZSort) {
imageLevels = new BufferedImage[zSort.getLevelCount()];
graphics = new Graphics2D[imageLevels.length];
for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
imageLevels[i] = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
graphics[i] = imageLevels[i].createGraphics();
graphics[i].setTransform(g.getTransform());
graphics[i].setRenderingHints(g.getRenderingHints());
}
}
// -- end visual FX stuff
boolean isInMemory = false;
if (getSource().getDriverAttributes() != null){
isInMemory = getSource().getDriverAttributes().isLoadedInMemory();
}
SelectionSupport selectionSupport=getSelectionSupport();
// Iteration over each feature
while ( !cancel.isCanceled() && it.hasNext()) {
IFeature feat = it.next();
IGeometry geom = null;
if (isInMemory){
geom = feat.getGeometry().cloneGeometry();
}else{
geom = feat.getGeometry();
}
if (cacheFeatures) {
if (cache.getMaxFeatures() >= cache.size()) {
// already reprojected
cache.insert(geom.getBounds2D(), geom);
}
}
// retrieve the symbol associated to such feature
ISymbol sym = legend.getSymbolByFeature(feat);
if (sym == null) continue;
//Código para poder acceder a los índices para ver si está seleccionado un Feature
ReadableVectorial rv=getSource();
int selectionIndex=-1;
if (rv instanceof ISpatialDB){
selectionIndex = ((ISpatialDB)rv).getRowIndexByFID(feat);
}else{
selectionIndex = Integer.parseInt(feat.getID());
}
if (selectionIndex!=-1) {
if (selectionSupport.isSelected(selectionIndex)) {
sym = sym.getSymbolForSelection();
}
}
// Check if this symbol is sized with CartographicSupport
CartographicSupport csSym = null;
int symbolType = sym.getSymbolType();
boolean bDrawCartographicSupport = false;
if ( symbolType == FShape.POINT
|| symbolType == FShape.LINE
|| sym instanceof CartographicSupport) {
// patch
if (!sym.getClass().equals(FSymbol.class)) {
csSym = (CartographicSupport) sym;
bDrawCartographicSupport = (csSym.getUnit() != -1);
}
}
int x = -1;
int y = -1;
int[] xyCoords = new int[2];
// Check if size is a pixel
boolean onePoint = bDrawCartographicSupport ?
isOnePoint(g.getTransform(), viewPort, MapContext.getScreenDPI(), csSym, geom, xyCoords) :
isOnePoint(g.getTransform(), viewPort, geom, xyCoords);
// Avoid out of bounds exceptions
if (onePoint) {
x = xyCoords[0];
y = xyCoords[1];
if (x<0 || y<0 || x>= viewPort.getImageWidth() || y>=viewPort.getImageHeight()) continue;
}
if (useZSort) {
// Check if this symbol is a multilayer
int[] symLevels = zSort.getLevels(sym);
if (sym instanceof IMultiLayerSymbol) {
// if so, treat each of its layers as a single symbol
// in its corresponding map level
IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
for (int i = 0; !cancel.isCanceled() && i < mlSym.getLayerCount(); i++) {
ISymbol mySym = mlSym.getLayer(i);
int symbolLevel = 0;
if (symLevels != null) {
symbolLevel = symLevels[i];
} else {
/* an error occured when managing symbol levels.
* some of the legend changed events regarding the
* symbols did not finish satisfactory and the legend
* is now inconsistent. For this drawing, it will finish
* as it was at the bottom (level 0) but, when done, the
* ZSort will be reset to avoid app crashes. This is
* a bug that has to be fixed.
*/
bSymbolLevelError = true;
}
if (onePoint) {
if (x<0 || y<0 || x>= imageLevels[symbolLevel].getWidth() || y>=imageLevels[symbolLevel].getHeight()) continue;
imageLevels[symbolLevel].setRGB(x, y, mySym.getOnePointRgb());
} else {
if (!bDrawCartographicSupport) {
geom.drawInts(graphics[symbolLevel], viewPort, mySym, cancel);
} else {
geom.drawInts(graphics[symbolLevel], viewPort, dpi, (CartographicSupport) mySym, cancel);
}
}
}
} else {
// else, just draw the symbol in its level
int symbolLevel = 0;
if (symLevels != null) {
symbolLevel=symLevels[0];
} else {
/* If symLevels == null
* an error occured when managing symbol levels.
* some of the legend changed events regarding the
* symbols did not finish satisfactory and the legend
* is now inconsistent. For this drawing, it will finish
* as it was at the bottom (level 0). This is
* a bug that has to be fixed.
*/
// bSymbolLevelError = true;
}
if (!bDrawCartographicSupport) {
geom.drawInts(graphics[symbolLevel], viewPort, sym, cancel);
} else {
geom.drawInts(graphics[symbolLevel], viewPort, dpi, csSym, cancel);
}
}
// -- visual FX stuff
// Cuando el offset!=0 se está dibujando sobre el Layout y por tanto no tiene que ejecutar el siguiente código.
if (offset.getX()==0 && offset.getY()==0)
if ((System.currentTimeMillis() - time) > screenRefreshDelay) {
virtualBim = new BufferedImage(image.getWidth(),image.getHeight(),BufferedImage.TYPE_INT_ARGB);
virtualGraphics = virtualBim.createGraphics();
virtualGraphics.drawImage(image,0,0, null);
for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
virtualGraphics.drawImage(imageLevels[i],0,0, null);
}
g.clearRect(0, 0, image.getWidth(), image.getHeight());
g.drawImage(virtualBim, 0, 0, null);
time = System.currentTimeMillis();
}
// -- end visual FX stuff
} else {
// no ZSort, so there is only a map level, symbols are
// just drawn.
if (onePoint) {
if (x<0 || y<0 || x>= image.getWidth() || y>=image.getHeight()) continue;
image.setRGB(x, y, sym.getOnePointRgb());
} else {
if (!bDrawCartographicSupport) {
geom.drawInts(g, viewPort, sym, cancel);
} else {
geom.drawInts(g, viewPort, dpi, csSym,
cancel);
}
}
}
}
if (useZSort) {
g.drawImage(image, (int)offset.getX(), (int)offset.getY(), null);
g.translate(offset.getX(), offset.getY());
for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
g.drawImage(imageLevels[i],0,0, null);
imageLevels[i] = null;
graphics[i] = null;
}
g.translate(-offset.getX(), -offset.getY());
imageLevels = null;
graphics = null;
}
it.closeIterator();
if (bSymbolLevelError) {
((IVectorLegend) getLegend()).setZSort(null);
}
} catch (ReadDriverException e) {
this.setVisible(false);
this.setActive(false);
throw e;
}
}
}
public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
Cancellable cancel, double scale) throws ReadDriverException {
if (isWaitTodraw()) {
return;
}
if (getStrategy() != null) {
getStrategy().draw(image, g, viewPort, cancel);
}
else {
_draw(image, g, viewPort, cancel, scale);
}
}
public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
double scale, PrintRequestAttributeSet properties, boolean highlight) throws ReadDriverException {
boolean bDrawShapes = true;
boolean cutGeom = true;
if (legend instanceof SingleSymbolLegend) {
bDrawShapes = legend.getDefaultSymbol().isShapeVisible();
}
if (bDrawShapes) {
try {
double dpi = 72;
PrintQuality resolution=(PrintQuality)properties.get(PrintQuality.class);
if (resolution.equals(PrintQuality.NORMAL)){
dpi = 300;
} else if (resolution.equals(PrintQuality.HIGH)){
dpi = 600;
} else if (resolution.equals(PrintQuality.DRAFT)){
dpi = 72;
}
ArrayList<String> fieldList = new ArrayList<String>();
String[] aux;
// fields from legend
if (legend instanceof IClassifiedVectorLegend) {
aux = ((IClassifiedVectorLegend) legend).getClassifyingFieldNames();
for (int i = 0; i < aux.length; i++) {
fieldList.add(aux[i]);
}
}
//
// // fields from labeling
// if (isLabeled()) {
// aux = getLabelingStrategy().getUsedFields();
// for (int i = 0; i < aux.length; i++) {
// fieldList.add(aux[i]);
// }
// }
ZSort zSort = ((IVectorLegend) getLegend()).getZSort();
// if layer has map levels it will use a ZSort
boolean useZSort = zSort != null && zSort.isUsingZSort();
int mapLevelCount = (useZSort) ? zSort.getLevelCount() : 1;
for (int mapPass = 0; mapPass < mapLevelCount; mapPass++) {
// Get the iterator over the visible features
// IFeatureIterator it = getSource().getFeatureIterator(
// viewPort.getAdjustedExtent(),
// fieldList.toArray(new String[fieldList.size()]),
// viewPort.getProjection(),
// true);
IFeatureIterator it = null;
if (isJoined()) {
it = new JoinFeatureIterator(this, viewPort,
fieldList.toArray(new String[fieldList.size()]));
}
else {
it = getSource().getFeatureIterator(
viewPort.getAdjustedExtent(),
fieldList.toArray(new String[fieldList.size()]),
viewPort.getProjection(),
true);
}
// Iteration over each feature
while ( !cancel.isCanceled() && it.hasNext()) {
IFeature feat = it.next();
IGeometry geom = feat.getGeometry();
// retreive the symbol associated to such feature
ISymbol sym = legend.getSymbolByFeature(feat);
if (sym == null) {
continue;
}
SelectionSupport selectionSupport=getSelectionSupport();
if (highlight) {
//Código para poder acceder a los índices para ver si está seleccionado un Feature
ReadableVectorial rv=getSource();
int selectionIndex=-1;
if (rv instanceof ISpatialDB){
selectionIndex = ((ISpatialDB)rv).getRowIndexByFID(feat);
} else {
selectionIndex = Integer.parseInt(feat.getID());
}
if (selectionIndex!=-1) {
if (selectionSupport.isSelected(selectionIndex)) {
sym = sym.getSymbolForSelection();
}
}
}
if (useZSort) {
int[] symLevels = zSort.getLevels(sym);
if(symLevels != null){
// Check if this symbol is a multilayer
if (sym instanceof IMultiLayerSymbol) {
// if so, get the layer corresponding to the current
// level. If none, continue to next iteration
IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
for (int i = 0; i < mlSym.getLayerCount(); i++) {
ISymbol mySym = mlSym.getLayer(i);
if (symLevels[i] == mapPass) {
sym = mySym;
break;
}
System.out.println("avoided layer "+i+"of symbol '"+mlSym.getDescription()+"' (pass "+mapPass+")");
}
} else {
// else, just draw the symbol in its level
if (symLevels[0] != mapPass) {
System.out.println("avoided single layer symbol '"+sym.getDescription()+"' (pass "+mapPass+")");
continue;
}
}
}
}
// Check if this symbol is sized with CartographicSupport
CartographicSupport csSym = null;
int symbolType = sym.getSymbolType();
if (symbolType == FShape.POINT
|| symbolType == FShape.LINE
|| sym instanceof CartographicSupport) {
csSym = (CartographicSupport) sym;
if (sym instanceof SimpleLineSymbol) {
SimpleLineSymbol lineSym = new SimpleLineSymbol();
lineSym.setXMLEntity(sym.getXMLEntity());
if (((SimpleLineSymbol) sym).getLineStyle()
.getArrowDecorator() != null) {
// Lines with decorators should not be cut
// because the decorators would be drawn in
// the wrong places
cutGeom = false;
if (!((SimpleLineSymbol) sym)
.getLineStyle().getArrowDecorator()
.isScaleArrow()) {
// Hack for increasing non-scaled arrow
// marker size, which usually looks
// smaller when printing
lineSym.getLineStyle()
.getArrowDecorator()
.getMarker()
.setSize(
lineSym.getLineStyle()
.getArrowDecorator()
.getMarker()
.getSize() * 3);
}
} else {
// Make default lines slightly thinner when
// printing
lineSym.setLineWidth(lineSym.getLineWidth() * 0.75);
}
csSym = lineSym;
}
}
//System.err.println("passada "+mapPass+" pinte símboll "+sym.getDescription());
// We check if the geometry seems to intersect with the
// view extent
Rectangle2D extent = viewPort.getExtent();
IGeometry geomToPrint = null;
if (cutGeom) {
try {
if (geom.fastIntersects(extent.getX(),
extent.getY(), extent.getWidth(),
extent.getHeight())) {
// If it does, then we create a rectangle
// based on
// the view extent and cut the geometries by
// it
// before drawing them
GeometryFactory geomF = new GeometryFactory();
Geometry intersection = geom
.toJTSGeometry()
.intersection(
new Polygon(
geomF.createLinearRing(new Coordinate[] {
new Coordinate(
extent.getMinX(),
extent.getMaxY()),
new Coordinate(
extent.getMaxX(),
extent.getMaxY()),
new Coordinate(
extent.getMaxX(),
extent.getMinY()),
new Coordinate(
extent.getMinX(),
extent.getMinY()),
new Coordinate(
extent.getMinX(),
extent.getMaxY()) }),
null, geomF));
if (!intersection.isEmpty()) {
geomToPrint = FConverter
.jts_to_igeometry(intersection);
}
}
} catch (TopologyException e) {
logger.warn(
"Some error happened while trying to cut a polygon with the view extent before printing (layer '"
+ this.getName()
+ "' / feature id "
+ feat.getID()
+ "). The whole polygon will be drawn. ",
e);
geomToPrint = geom;
}
} else {
geomToPrint = geom;
}
if (geomToPrint != null) {
if (csSym == null) {
geomToPrint.drawInts(g, viewPort, sym, null);
} else {
geomToPrint.drawInts(g, viewPort, dpi, csSym,
cancel);
}
}
}
it.closeIterator();
}
} catch (ReadDriverException e) {
this.setVisible(false);
this.setActive(false);
throw e;
}
}
}
public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
double scale, PrintRequestAttributeSet properties) throws ReadDriverException {
print(g, viewPort, cancel, scale, properties, false);
}
public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
double scale, PrintRequestAttributeSet properties, boolean highlight) throws ReadDriverException {
if (isVisible() && isWithinScale(scale)) {
_print(g, viewPort, cancel, scale, properties, highlight);
}
}
public void deleteSpatialIndex() {
//must we delete possible spatial indexes files?
spatialIndex = null;
}
/**
* <p>
* Creates an spatial index associated to this layer.
* The spatial index will used
* the native projection of the layer, so if the layer is reprojected, it will
* be ignored.
* </p>
* @param cancelMonitor instance of CancellableMonitorable that allows
* to monitor progress of spatial index creation, and cancel the process
*/
public void createSpatialIndex(CancellableMonitorable cancelMonitor){
// FJP: ESTO HABRÁ QUE CAMBIARLO. PARA LAS CAPAS SECUENCIALES, TENDREMOS
// QUE ACCEDER CON UN WHILE NEXT. (O mejorar lo de los FeatureVisitor
// para que acepten recorrer sin geometria, solo con rectangulos.
//If this vectorial layer is based in a spatial database, the spatial
//index is already implicit. We only will index file drivers
ReadableVectorial va = getSource();
//We must think in non spatial databases, like HSQLDB
if(!(va instanceof VectorialFileAdapter)){
return;
}
if (!(va.getDriver() instanceof BoundedShapes)) {
return;
}
File file = ((VectorialFileAdapter) va).getFile();
String fileName = file.getAbsolutePath();
ISpatialIndex localCopy = null;
try {
va.start();
localCopy = new QuadtreeGt2(fileName, "NM", va.getFullExtent(),
va.getShapeCount(), true);
} catch (SpatialIndexException e1) {
// Probably we dont have writing permissions
String directoryName = System.getProperty("java.io.tmpdir");
File newFile = new File(directoryName +
File.separator +
file.getName());
String newFileName = newFile.getName();
try {
localCopy = new QuadtreeGt2(newFileName, "NM", va.getFullExtent(),
va.getShapeCount(), true);
} catch (SpatialIndexException e) {
// if we cant build a file based spatial index, we'll build
// a pure memory spatial index
localCopy = new QuadtreeJts();
} catch (ReadDriverException e) {
localCopy = new QuadtreeJts();
}
} catch(Exception e){
e.printStackTrace();
}//try
BoundedShapes shapeBounds = (BoundedShapes) va.getDriver();
try {
for (int i=0; i < va.getShapeCount(); i++)
{
if(cancelMonitor != null){
if(cancelMonitor.isCanceled())
return;
cancelMonitor.reportStep();
}
Rectangle2D r = shapeBounds.getShapeBounds(i);
if(r != null)
localCopy.insert(r, i);
} // for
va.stop();
if(localCopy instanceof IPersistentSpatialIndex)
((IPersistentSpatialIndex) localCopy).flush();
spatialIndex = localCopy;
//vectorial adapter needs a reference to the spatial index, to solve
//request for feature iteration based in spatial queries
source.setSpatialIndex(spatialIndex);
} catch (ReadDriverException e) {
e.printStackTrace();
}
}
public void createSpatialIndex() {
createSpatialIndex(null);
}
public void process(FeatureVisitor visitor, FBitSet subset)
throws ReadDriverException, ExpansionFileReadException, VisitorException {
Strategy s = StrategyManager.getStrategy(this);
s.process(visitor, subset);
}
public void process(FeatureVisitor visitor) throws ReadDriverException, VisitorException {
Strategy s = StrategyManager.getStrategy(this);
s.process(visitor);
}
public void process(FeatureVisitor visitor, Rectangle2D rect)
throws ReadDriverException, ExpansionFileReadException, VisitorException {
Strategy s = StrategyManager.getStrategy(this);
s.process(visitor, rect);
}
public FBitSet queryByRect(Rectangle2D rect) throws ReadDriverException, VisitorException {
Strategy s = StrategyManager.getStrategy(this);
return s.queryByRect(rect);
}
public FBitSet queryByPoint(Point2D p, double tolerance)
throws ReadDriverException, VisitorException {
Strategy s = StrategyManager.getStrategy(this);
return s.queryByPoint(p, tolerance);
}
public FBitSet queryByShape(IGeometry g, int relationship)
throws ReadDriverException, VisitorException {
Strategy s = StrategyManager.getStrategy(this);
return s.queryByShape(g, relationship);
}
public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws ReadDriverException, VisitorException {
Point2D pReal = this.getMapContext().getViewPort().toMapPoint(p);
FBitSet bs = queryByPoint(pReal, tolerance);
VectorialXMLItem[] item = new VectorialXMLItem[1];
item[0] = new VectorialXMLItem(bs, this);
return item;
}
public void setLegend(IVectorLegend r) throws LegendLayerException {
if (this.legend == r){
return;
}
if (this.legend != null && this.legend.equals(r)){
return;
}
IVectorLegend oldLegend = legend;
/*
* Parche para discriminar las leyendas clasificadas cuyos campos de
* clasificación no están en la fuente de la capa.
*
* Esto puede ocurrir porque en versiones anteriores se admitían
* leyendas clasificadas en capas que se han unido a una tabla
* por campos que pertenecían a la tabla y no sólo a la capa.
*
*/
// if(r instanceof IClassifiedVectorLegend){
// IClassifiedVectorLegend classifiedLegend = (IClassifiedVectorLegend)r;
// String[] fieldNames = classifiedLegend.getClassifyingFieldNames();
//
// for (int i = 0; i < fieldNames.length; i++) {
// try {
// if(this.getRecordset().getFieldIndexByName(fieldNames[i]) == -1){
//// if(this.getSource().getRecordset().getFieldIndexByName(fieldNames[i]) == -1){
// logger.warn("Some fields of the classification of the legend doesn't belong with the source of the layer.");
// if (this.legend == null){
// r = LegendFactory.createSingleSymbolLegend(this.getShapeType());
// } else {
// return;
// }
// }
// } catch (ReadDriverException e1) {
// throw new LegendLayerException(getName(),e1);
// }
// }
// }
/* Fin del parche */
legend = r;
try {
legend.setDataSource(getRecordset());
} catch (FieldNotFoundException e1) {
throw new LegendLayerException(getName(),e1);
} catch (ReadDriverException e1) {
throw new LegendLayerException(getName(),e1);
} finally{
this.updateDrawVersion();
}
if (oldLegend != null){
oldLegend.removeLegendListener(this);
}
if (legend != null){
legend.addLegendListener(this);
}
LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent(
oldLegend, legend);
e.setLayer(this);
callLegendChanged(e);
}
/**
* Devuelve la Leyenda de la capa.
*
* @return Leyenda.
*/
public ILegend getLegend() {
return legend;
}
/**
* Devuelve el tipo de shape que contiene la capa.
*
* @return tipo de shape.
*
* @throws DriverException
*/
public int getShapeType() throws ReadDriverException {
if (typeShape == -1) {
getSource().start();
typeShape = getSource().getShapeType();
getSource().stop();
}
return typeShape;
}
public XMLEntity getXMLEntity() throws XMLException {
if (!this.isAvailable() && this.orgXMLEntity != null) {
return this.orgXMLEntity;
}
XMLEntity xml = super.getXMLEntity();
if (getLegend()!=null)
xml.addChild(getLegend().getXMLEntity());
try {
if (getRecordset()!=null)
xml.addChild(getRecordset().getSelectionSupport().getXMLEntity());
} catch (ReadDriverException e1) {
e1.printStackTrace();
throw new XMLException(e1);
}
// Repongo el mismo ReadableVectorial más abajo para cuando se guarda el proyecto.
ReadableVectorial rv=getSource();
xml.putProperty("type", "vectorial");
if (source instanceof VectorialEditableAdapter) {
setSource(((VectorialEditableAdapter) source).getOriginalAdapter());
}
if (source instanceof VectorialFileAdapter) {
xml.putProperty("type", "vectorial");
xml.putProperty("absolutePath",((VectorialFileAdapter) source)
.getFile().getAbsolutePath());
xml.putProperty("file", pathGenerator.getPath(((VectorialFileAdapter) source)
.getFile().getAbsolutePath()));
try {
xml.putProperty("recordset-name", source.getRecordset()
.getName());
} catch (ReadDriverException e) {
throw new XMLException(e);
} catch (RuntimeException e) {
e.printStackTrace();
}
} else if (source instanceof VectorialDBAdapter) {
xml.putProperty("type", "vectorial");
IVectorialDatabaseDriver dbDriver = (IVectorialDatabaseDriver) source
.getDriver();
// Guardamos el nombre del driver para poder recuperarlo
// con el DriverManager de Fernando.
xml.putProperty("db", dbDriver.getName());
try {
xml.putProperty("recordset-name", source.getRecordset()
.getName());
} catch (ReadDriverException e) {
throw new XMLException(e);
} catch (RuntimeException e) {
e.printStackTrace();
}
xml.addChild(dbDriver.getXMLEntity()); // Tercer child. Antes hemos
// metido la leyenda y el
// selection support
} else if (source instanceof VectorialAdapter) {
// Se supone que hemos hecho algo genérico.
xml.putProperty("type", "vectorial");
VectorialDriver driver = source.getDriver();
// Guardamos el nombre del driver para poder recuperarlo
// con el DriverManager de Fernando.
xml.putProperty("other", driver.getName());
// try {
try {
xml.putProperty("recordset-name", source.getRecordset()
.getName());
} catch (ReadDriverException e) {
throw new XMLException(e);
} catch (RuntimeException e) {
e.printStackTrace();
}
if (driver instanceof IPersistence) {
// xml.putProperty("className", driver.getClass().getName());
IPersistence persist = (IPersistence) driver;
xml.addChild(persist.getXMLEntity()); // Tercer child. Antes
// hemos metido la
// leyenda y el
// selection support
}
}
if (rv!=null)
setSource(rv);
xml.putProperty("driverName", source.getDriver().getName());
if (bHasJoin)
xml.putProperty("hasJoin", "true");
// properties from ILabelable
xml.putProperty("isLabeled", isLabeled);
if (strategy != null) {
XMLEntity strategyXML = strategy.getXMLEntity();
strategyXML.putProperty("Strategy", strategy.getClassName());
xml.addChild(strategy.getXMLEntity());
}
xml.addChild(getLinkProperties().getXMLEntity());
return xml;
}
/*
* @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setXMLEntity(com.iver.utiles.XMLEntity)
*/
public void setXMLEntity(XMLEntity xml) throws XMLException {
try {
super.setXMLEntity(xml);
XMLEntity legendXML = xml.getChild(0);
IVectorLegend leg = LegendFactory.createFromXML(legendXML);
try {
getRecordset().getSelectionSupport().setXMLEntity(xml.getChild(1));
// JMVIVO: Esto sirve para algo????
/*
* Jaume: si, para restaurar el selectable datasource cuando se
* clona la capa, cuando se carga de un proyecto. Si no esta ya
* no se puede ni hacer consultas sql, ni hacer selecciones,
* ni usar la mayor parte de las herramientas.
*
* Lo vuelvo a poner.
*/
String recordsetName = xml.getStringProperty("recordset-name");
LayerFactory.getDataSourceFactory().changeDataSourceName(
getSource().getRecordset().getName(), recordsetName);
SelectableDataSource sds = new SelectableDataSource(LayerFactory
.getDataSourceFactory().createRandomDataSource(
recordsetName, DataSourceFactory.AUTOMATIC_OPENING));
} catch (NoSuchTableException e1) {
this.setAvailable(false);
throw new XMLException(e1);
} catch (ReadDriverException e1) {
this.setAvailable(false);
throw new XMLException(e1);
}
// Si tiene una unión, lo marcamos para que no se cree la leyenda hasta
// el final
// de la lectura del proyecto
if (xml.contains("hasJoin")) {
setIsJoined(true);
PostProcessSupport.addToPostProcess(this, "setLegend", leg, 1);
} else {
try {
setLegend(leg);
} catch (LegendLayerException e) {
throw new XMLException(e);
}
}
//Por compatibilidad con proyectos anteriores a la 1.0
boolean containsIsLabeled = xml.contains("isLabeled");
if (containsIsLabeled){
isLabeled = xml.getBooleanProperty("isLabeled");
}
// set properties for ILabelable
XMLEntity labelingXML = xml.firstChild("labelingStrategy", "labelingStrategy");
if (labelingXML!= null) {
if(!containsIsLabeled){
isLabeled = true;
}
try {
ILabelingStrategy labeling = LabelingFactory.createStrategyFromXML(labelingXML, this);
if (isJoined()) {
PostProcessSupport.addToPostProcess(this, "setLabelingStrategy", labeling, 1);
}
else
this.setLabelingStrategy(labeling);
} catch (NotExistInXMLEntity neXMLEX) {
// no strategy was set, just continue;
logger.warn("Reached what should be unreachable code");
}
} else if (legendXML.contains("labelFieldName")|| legendXML.contains("labelfield")) {
/* (jaume) begin patch;
* for backward compatibility purposes. Since gvSIG v1.1 labeling is
* no longer managed by the Legend but by the ILabelingStrategy. The
* following allows restoring older projects' labelings.
*/
String labelTextField = null;
if (legendXML.contains("labelFieldName")){
labelTextField = legendXML.getStringProperty("labelFieldName");
if (labelTextField != null) {
AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
labeling.setLayer(this);
int unit = 1;
boolean useFixedSize = false;
String labelFieldHeight = legendXML.getStringProperty("labelHeightFieldName");
labeling.setTextField(labelTextField);
if(labelFieldHeight!=null){
labeling.setHeightField(labelFieldHeight);
} else {
double size = -1;
for(int i=0; i<legendXML.getChildrenCount();i++){
XMLEntity xmlChild = legendXML.getChild(i);
if(xmlChild.contains("m_FontSize")){
double childFontSize = xmlChild.getDoubleProperty("m_FontSize");
if(size<0){
size = childFontSize;
useFixedSize = true;
} else {
useFixedSize = useFixedSize && (size==childFontSize);
}
if(xmlChild.contains("m_bUseFontSize")){
if(xmlChild.getBooleanProperty("m_bUseFontSize")){
unit = -1;
} else {
unit = 1;
}
}
}
}
labeling.setFixedSize(size/1.4);//Factor de corrección que se aplicaba antes en el etiquetado
}
labeling.setUsesFixedSize(useFixedSize);
labeling.setUnit(unit);
labeling.setRotationField(legendXML.getStringProperty("labelRotationFieldName"));
if (isJoined()) {
PostProcessSupport.addToPostProcess(this, "setLabelingStrategy", labeling, 1);
}
else
this.setLabelingStrategy(labeling);
this.setIsLabeled(true);
}
}else{
labelTextField = legendXML.getStringProperty("labelfield");
if (labelTextField != null) {
AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
labeling.setLayer(this);
int unit = 1;
boolean useFixedSize = false;
String labelFieldHeight = legendXML.getStringProperty("labelFieldHeight");
labeling.setTextField(labelTextField);
if(labelFieldHeight!=null){
labeling.setHeightField(labelFieldHeight);
} else {
double size = -1;
for(int i=0; i<legendXML.getChildrenCount();i++){
XMLEntity xmlChild = legendXML.getChild(i);
if(xmlChild.contains("m_FontSize")){
double childFontSize = xmlChild.getDoubleProperty("m_FontSize");
if(size<0){
size = childFontSize;
useFixedSize = true;
} else {
useFixedSize = useFixedSize && (size==childFontSize);
}
if(xmlChild.contains("m_bUseFontSize")){
if(xmlChild.getBooleanProperty("m_bUseFontSize")){
unit = -1;
} else {
unit = 1;
}
}
}
}
labeling.setFixedSize(size/1.4);//Factor de corrección que se aplicaba antes en el etiquetado
}
labeling.setUsesFixedSize(useFixedSize);
labeling.setUnit(unit);
labeling.setRotationField(legendXML.getStringProperty("labelFieldRotation"));
if (isJoined()) {
PostProcessSupport.addToPostProcess(this, "setLabelingStrategy", labeling, 1);
}
else
this.setLabelingStrategy(labeling);
this.setIsLabeled(true);
}
}
}else if(!containsIsLabeled){
isLabeled = false;
}
// compatibility with hyperlink from 1.9 alpha version... do we really need to be compatible with alpha versions??
XMLEntity xmlLinkProperties=xml.firstChild("typeChild", "linkProperties");
if (xmlLinkProperties != null){
try {
String fieldName=xmlLinkProperties.getStringProperty("fieldName");
xmlLinkProperties.remove("fieldName");
String extName = xmlLinkProperties.getStringProperty("extName");
xmlLinkProperties.remove("extName");
int typeLink = xmlLinkProperties.getIntProperty("typeLink");
xmlLinkProperties.remove("typeLink");
if (fieldName!=null) {
setProperty("legacy.hyperlink.selectedField", fieldName);
setProperty("legacy.hyperlink.type", new Integer(typeLink));
if (extName!=null) {
setProperty("legacy.hyperlink.extension", extName);
}
}
}
catch (NotExistInXMLEntity ex) {
logger.warn("Error getting old hyperlink configuration", ex);
}
}
} catch (XMLException e) {
this.setAvailable(false);
this.orgXMLEntity = xml;
} catch (Exception e) {
e.printStackTrace();
this.setAvailable(false);
this.orgXMLEntity = xml;
}
}
public void setXMLEntityNew(XMLEntity xml) throws XMLException {
try {
super.setXMLEntity(xml);
XMLEntity legendXML = xml.getChild(0);
IVectorLegend leg = LegendFactory.createFromXML(legendXML);
/* (jaume) begin patch;
* for backward compatibility purposes. Since gvSIG v1.1 labeling is
* no longer managed by the Legend but by the ILabelingStrategy. The
* following allows restoring older projects' labelings.
*/
if (legendXML.contains("labelFieldHeight")) {
AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
labeling.setLayer(this);
labeling.setTextField(legendXML.getStringProperty("labelFieldHeight"));
labeling.setRotationField(legendXML.getStringProperty("labelFieldRotation"));
this.setLabelingStrategy(labeling);
this.setIsLabeled(true);
}
/* end patch */
try {
getRecordset().getSelectionSupport().setXMLEntity(xml.getChild(1));
this.setLoadSelection(xml.getChild(1));
} catch (ReadDriverException e1) {
this.setAvailable(false);
throw new XMLException(e1);
}
// Si tiene una unión, lo marcamos para que no se cree la leyenda hasta
// el final
// de la lectura del proyecto
if (xml.contains("hasJoin")) {
setIsJoined(true);
PostProcessSupport.addToPostProcess(this, "setLegend", leg, 1);
} else {
this.setLoadLegend(leg);
}
} catch (XMLException e) {
this.setAvailable(false);
this.orgXMLEntity = xml;
} catch (Exception e) {
this.setAvailable(false);
this.orgXMLEntity = xml;
}
}
/**
* Sobreimplementación del método toString para que las bases de datos
* identifiquen la capa.
*
* @return DOCUMENT ME!
*/
public String toString() {
/*
* Se usa internamente para que la parte de datos identifique de forma
* unívoca las tablas
*/
String ret = super.toString();
return "layer" + ret.substring(ret.indexOf('@') + 1);
}
public boolean isJoined() {
return bHasJoin;
}
/**
* Returns if a layer is spatially indexed
*
* @return if this layer has the ability to proces spatial queries without
* secuential scans.
*/
public boolean isSpatiallyIndexed() {
ReadableVectorial source = getSource();
if (source instanceof ISpatialDB)
return true;
//FIXME azabala
/*
* Esto es muy dudoso, y puede cambiar.
* Estoy diciendo que las que no son fichero o no son
* BoundedShapes estan indexadas. Esto es mentira, pero
* así quien pregunte no querrá generar el indice.
* Esta por ver si interesa generar el indice para capas
* HSQLDB, WFS, etc.
*/
if(!(source instanceof VectorialFileAdapter)){
return true;
}
if (!(source.getDriver() instanceof BoundedShapes)) {
return true;
}
if (getISpatialIndex() != null)
return true;
return false;
}
public void setIsJoined(boolean hasJoin) {
bHasJoin = hasJoin;
}
/**
* @return Returns the spatialIndex.
*/
public ISpatialIndex getISpatialIndex() {
return spatialIndex;
}
/**
* Sets the spatial index. This could be useful if, for some
* reasons, you want to work with a distinct spatial index
* (for example, a spatial index which could makes nearest
* neighbour querys)
* @param spatialIndex
*/
public void setISpatialIndex(ISpatialIndex spatialIndex){
this.spatialIndex = spatialIndex;
}
public SelectableDataSource getRecordset() throws ReadDriverException {
if (!this.isAvailable()) return null;
if (sds == null) {
SelectableDataSource ds = source.getRecordset();
if (ds == null) {
return null;
}
sds = ds;
getSelectionSupport().addSelectionListener(this);
}
return sds;
}
public void setEditing(boolean b) throws StartEditionLayerException {
super.setEditing(b);
try {
if (b) {
VectorialEditableAdapter vea = null;
// TODO: Qué pasa si hay más tipos de adapters?
// FJP: Se podría pasar como argumento el
// VectorialEditableAdapter
// que se quiera usar para evitar meter código aquí de este
// estilo.
if (getSource() instanceof VectorialDBAdapter) {
vea = new VectorialEditableDBAdapter();
} else if (this instanceof FLyrAnnotation) {
vea = new AnnotationEditableAdapter(
(FLyrAnnotation) this);
} else {
vea = new VectorialEditableAdapter();
}
vea.addEditionListener(this);
vea.setOriginalVectorialAdapter(getSource());
// azo: implementations of readablevectorial need
//references of projection and spatial index
vea.setProjection(getProjection());
vea.setSpatialIndex(spatialIndex);
// /vea.setSpatialIndex(getSpatialIndex());
// /vea.setFullExtent(getFullExtent());
vea.setCoordTrans(getCoordTrans());
vea.startEdition(EditionEvent.GRAPHIC);
setSource(vea);
getRecordset().setSelectionSupport(
vea.getOriginalAdapter().getRecordset()
.getSelectionSupport());
} else {
VectorialEditableAdapter vea = (VectorialEditableAdapter) getSource();
vea.removeEditionListener(this);
setSource(vea.getOriginalAdapter());
}
// Si tenemos una leyenda, hay que pegarle el cambiazo a su
// recordset
setRecordset(getSource().getRecordset());
if (getLegend() instanceof IVectorLegend) {
IVectorLegend ley = (IVectorLegend) getLegend();
ley.setDataSource(getSource().getRecordset());
// Esto lo pongo para evitar que al dibujar sobre un
// dxf, dwg, o dgn no veamos nada. Es debido al checkbox
// de la leyenda de textos "dibujar solo textos".
//jaume
// if (!(getSource().getDriver() instanceof IndexedShpDriver)){
// FSymbol symbol=new FSymbol(getShapeType());
// symbol.setFontSizeInPixels(false);
// symbol.setFont(new Font("SansSerif", Font.PLAIN, 9));
// Color color=symbol.getColor();
// int alpha=symbol.getColor().getAlpha();
// if (alpha>250) {
// symbol.setColor(new Color(color.getRed(),color.getGreen(),color.getBlue(),100));
// }
// ley.setDefaultSymbol(symbol);
// }
//jaume//
ley.useDefaultSymbol(true);
}
} catch (ReadDriverException e) {
throw new StartEditionLayerException(getName(),e);
} catch (FieldNotFoundException e) {
throw new StartEditionLayerException(getName(),e);
} catch (StartWriterVisitorException e) {
throw new StartEditionLayerException(getName(),e);
}
setSpatialCacheEnabled(b);
callEditionChanged(LayerEvent
.createEditionChangedEvent(this, "edition"));
}
/**
* Para cuando haces una unión, sustituyes el recorset por el nuevo. De esta
* forma, podrás poner leyendas basadas en el nuevo recordset
*
* @param newSds
*/
public void setRecordset(SelectableDataSource newSds) {
// TODO: Deberiamos hacer comprobaciones del cambio
sds = newSds;
getSelectionSupport().addSelectionListener(this);
this.updateDrawVersion();
}
public void clearSpatialCache()
{
spatialCache.clearAll();
}
public boolean isSpatialCacheEnabled() {
return spatialCacheEnabled;
}
public void setSpatialCacheEnabled(boolean spatialCacheEnabled) {
this.spatialCacheEnabled = spatialCacheEnabled;
}
public SpatialCache getSpatialCache() {
return spatialCache;
}
/**
* Siempre es un numero mayor de 1000
* @param maxFeatures
*/
public void setMaxFeaturesInEditionCache(int maxFeatures) {
if (maxFeatures > spatialCache.maxFeatures)
spatialCache.setMaxFeatures(maxFeatures);
}
/**
* This method returns a boolean that is used by the FPopMenu
* to make visible the properties menu or not. It is visible by
* default, and if a later don't have to show this menu only
* has to override this method.
* @return
* If the properties menu is visible (or not)
*/
public boolean isPropertiesMenuVisible(){
return true;
}
public void reload() throws ReloadLayerException {
if(this.isEditing()){
throw new ReloadLayerException(getName());
}
this.setAvailable(true);
super.reload();
this.updateDrawVersion();
try {
this.source.getDriver().reload();
if (this.getLegend() == null) {
if (this.getRecordset().getDriver() instanceof WithDefaultLegend) {
WithDefaultLegend aux = (WithDefaultLegend) this.getRecordset().getDriver();
this.setLegend((IVectorLegend) aux.getDefaultLegend());
this.setLabelingStrategy(aux.getDefaultLabelingStrategy());
} else {
this.setLegend(LegendFactory.createSingleSymbolLegend(
this.getShapeType()));
}
}
} catch (LegendLayerException e) {
this.setAvailable(false);
throw new ReloadLayerException(getName(),e);
} catch (ReadDriverException e) {
this.setAvailable(false);
throw new ReloadLayerException(getName(),e);
}
}
protected void setLoadSelection(XMLEntity xml) {
this.loadSelection = xml;
}
protected void setLoadLegend(IVectorLegend legend) {
this.loadLegend = legend;
}
protected void putLoadSelection() throws XMLException {
if (this.loadSelection == null) return;
try {
this.getRecordset().getSelectionSupport().setXMLEntity(this.loadSelection);
} catch (ReadDriverException e) {
throw new XMLException(e);
}
this.loadSelection = null;
}
protected void putLoadLegend() throws LegendLayerException {
if (this.loadLegend == null) return;
this.setLegend(this.loadLegend);
this.loadLegend = null;
}
protected void cleanLoadOptions() {
this.loadLegend = null;
this.loadSelection = null;
}
public boolean isWritable() {
VectorialDriver drv = getSource().getDriver();
if (!drv.isWritable())
return false;
if (drv instanceof IWriteable)
{
IWriter writer = ((IWriteable)drv).getWriter();
if (writer != null)
{
if (writer instanceof ISpatialWriter)
return true;
}
}
return false;
}
public FLayer cloneLayer() throws Exception {
FLyrVect clonedLayer = new FLyrVect();
clonedLayer.setSource(getSource());
if (isJoined()) {
clonedLayer.setIsJoined(true);
clonedLayer.setRecordset(getRecordset());
}
clonedLayer.setVisible(isVisible());
clonedLayer.setISpatialIndex(getISpatialIndex());
clonedLayer.setName(getName());
clonedLayer.setCoordTrans(getCoordTrans());
clonedLayer.setLegend((IVectorLegend)getLegend().cloneLegend());
clonedLayer.setIsLabeled(isLabeled());
ILabelingStrategy labelingStrategy=getLabelingStrategy();
if (labelingStrategy!=null)
clonedLayer.setLabelingStrategy(labelingStrategy);
return clonedLayer;
}
public SelectionSupport getSelectionSupport() {
try {
return getRecordset().getSelectionSupport();
} catch (ReadDriverException e) {
e.printStackTrace();
}
return null;
}
protected boolean isOnePoint(AffineTransform graphicsTransform, ViewPort viewPort, double dpi, CartographicSupport csSym, IGeometry geom, int[] xyCoords) {
return isOnePoint(graphicsTransform, viewPort, geom, xyCoords) && csSym.getCartographicSize(viewPort, dpi, (FShape)geom.getInternalShape()) <= 1;
}
protected boolean isOnePoint(AffineTransform graphicsTransform, ViewPort viewPort, IGeometry geom, int[] xyCoords) {
boolean onePoint = false;
int type=geom.getGeometryType() % FShape.Z;
if (type!=FShape.POINT && type!=FShape.MULTIPOINT && type!=FShape.NULL) {
Rectangle2D geomBounds = geom.getBounds2D();
// ICoordTrans ct = getCoordTrans();
// Se supone que la geometria ya esta
// repoyectada y no hay que hacer
// ninguna transformacion
// if (ct!=null) {
//// geomBounds = ct.getInverted().convert(geomBounds);
// geomBounds = ct.convert(geomBounds);
// }
double dist1Pixel = viewPort.getDist1pixel();
onePoint = (geomBounds.getWidth() <= dist1Pixel
&& geomBounds.getHeight() <= dist1Pixel);
if (onePoint) {
// avoid out of range exceptions
FPoint2D p = new FPoint2D(geomBounds.getMinX(), geomBounds.getMinY());
p.transform(viewPort.getAffineTransform());
p.transform(graphicsTransform);
xyCoords[0] = (int) p.getX();
xyCoords[1] = (int) p.getY();
}
}
return onePoint;
}
/*
* jaume. Stuff from ILabeled.
*/
private boolean isLabeled;
private ILabelingStrategy strategy;
public boolean isLabeled() {
return isLabeled;
}
public void setIsLabeled(boolean isLabeled) {
this.isLabeled = isLabeled;
}
public ILabelingStrategy getLabelingStrategy() {
return strategy;
}
public void setLabelingStrategy(ILabelingStrategy strategy) {
this.strategy = strategy;
try {
strategy.setLayer(this);
} catch (ReadDriverException e) {
e.printStackTrace();
}
}
public void drawLabels(BufferedImage image, Graphics2D g, ViewPort viewPort,
Cancellable cancel, double scale, double dpi) throws ReadDriverException {
if (strategy!=null && isWithinScale(scale)) {
strategy.draw(image, g, viewPort, cancel, dpi);
}
}
public void printLabels(Graphics2D g, ViewPort viewPort,
Cancellable cancel, double scale, PrintRequestAttributeSet properties) throws ReadDriverException {
if (strategy!=null) {
strategy.print(g, viewPort, cancel, properties);
}
}
//Métodos para el uso de HyperLinks en capas FLyerVect
/**
* Return true, because a Vectorial Layer supports HyperLink
*/
public boolean allowLinks()
{
return true;
}
/**
* Returns an instance of AbstractLinkProperties that contains the information
* of the HyperLink
* @return Abstra
*/
public AbstractLinkProperties getLinkProperties()
{
return linkProperties;
}
/**
* Provides an array with URIs. Returns one URI by geometry that includes the point
* in its own geometry limits with a allowed tolerance.
* @param layer, the layer
* @param point, the point to check that is contained or not in the geometries in the layer
* @param tolerance, the tolerance allowed. Allowed margin of error to detect if the point
* is contained in some geometries of the layer
* @return
*/
public URI[] getLink(Point2D point, double tolerance)
{
//return linkProperties.getLink(this)
return linkProperties.getLink(this,point,tolerance);
}
public void selectionChanged(SelectionEvent e) {
this.updateDrawVersion();
}
public void afterFieldEditEvent(AfterFieldEditEvent e) {
this.updateDrawVersion();
}
public void afterRowEditEvent(IRow feat, AfterRowEditEvent e) {
this.updateDrawVersion();
}
public void beforeFieldEditEvent(BeforeFieldEditEvent e) {
}
public void beforeRowEditEvent(IRow feat, BeforeRowEditEvent e) {
}
public void processEvent(EditionEvent e) {
if (e.getChangeType()== e.ROW_EDITION){
this.updateDrawVersion();
}
}
public void legendCleared(LegendClearEvent event) {
this.updateDrawVersion();
LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent(
legend, legend);
this.callLegendChanged(e);
}
public boolean symbolChanged(SymbolLegendEvent e) {
this.updateDrawVersion();
LegendChangedEvent event = LegendChangedEvent.createLegendChangedEvent(
legend, legend);
this.callLegendChanged(event);
return true;
}
public String getTypeStringVectorLayer() throws ReadDriverException {
String typeString="";
int typeShape=this.getShapeType();
if (FShape.MULTI==typeShape){
ReadableVectorial rv=this.getSource();
int i=0;
boolean isCorrect=false;
while(rv.getShapeCount()>i && !isCorrect){
IGeometry geom=rv.getShape(i);
if (geom==null){
i++;
continue;
}
isCorrect=true;
if ((geom.getGeometryType() & FShape.Z) == FShape.Z){
typeString="Geometries3D";
}else{
typeString="Geometries2D";
}
}
}else{
ReadableVectorial rv=this.getSource();
int i=0;
boolean isCorrect=false;
while(rv.getShapeCount()>i && !isCorrect){
IGeometry geom=rv.getShape(i);
if (geom==null){
i++;
continue;
}
isCorrect=true;
int type=geom.getGeometryType();
if (FShape.POINT == type){
typeString="Point2D";
} else if (FShape.LINE == type){
typeString="Line2D";
} else if (FShape.POLYGON == type){
typeString="Polygon2D";
} else if (FShape.MULTIPOINT == type){
typeString="MultiPint2D";
} else if ((FShape.POINT | FShape.Z) == type ){
typeString="Point3D";
} else if ((FShape.LINE | FShape.Z) == type ){
typeString="Line3D";
} else if ((FShape.POLYGON | FShape.Z) == type ){
typeString="Polygon3D";
} else if ((FShape.MULTIPOINT | FShape.Z) == type ){
typeString="MultiPoint3D";
} else if ((FShape.POINT | FShape.M) == type ){
typeString="PointM";
} else if ((FShape.LINE | FShape.M) == type ){
typeString="LineM";
} else if ((FShape.POLYGON | FShape.M) == type ){
typeString="PolygonM";
} else if ((FShape.MULTIPOINT | FShape.M) == type ){
typeString="MultiPointM";
} else if ((FShape.MULTI | FShape.M) == type ){
typeString="M";
}
}
return typeString;
}
return "";
}
public int getTypeIntVectorLayer() throws ReadDriverException {
int typeInt=0;
int typeShape=this.getShapeType();
if (FShape.MULTI==typeShape){
ReadableVectorial rv=this.getSource();
int i=0;
boolean isCorrect=false;
while(rv.getShapeCount()>i && !isCorrect){
IGeometry geom=rv.getShape(i);
if (geom==null){
i++;
continue;
}
isCorrect=true;
if ((geom.getGeometryType() & FShape.Z) == FShape.Z){
typeInt=FShape.MULTI | FShape.Z;
}else{
typeInt=FShape.MULTI;
}
}
}else{
ReadableVectorial rv=this.getSource();
int i=0;
boolean isCorrect=false;
while(rv.getShapeCount()>i && !isCorrect){
IGeometry geom=rv.getShape(i);
if (geom==null){
i++;
continue;
}
isCorrect=true;
int type=geom.getGeometryType();
typeInt=type;
}
return typeInt;
}
return typeInt;
}
} | Java |
/* This file is part of the hkl library.
*
* The hkl library 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.
*
* The hkl library 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 the hkl library. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2003-2015 Synchrotron SOLEIL
* L'Orme des Merisiers Saint-Aubin
* BP 48 91192 GIF-sur-YVETTE CEDEX
*
* Authors: Picca Frédéric-Emmanuel <picca@synchrotron-soleil.fr>
*/
#include "hkl.h"
#include <tap/basic.h>
#include <tap/float.h>
#include "hkl-vector-private.h"
#include "hkl-matrix-private.h" /* we will check also the private API */
static void init(void)
{
HklMatrix m;
hkl_matrix_init(&m, 1, 1, 0, 0, 1, 0, 0, 0, 1);
is_double(1., m.data[0][0], HKL_EPSILON, __func__);
is_double(1., m.data[0][1], HKL_EPSILON, __func__);
is_double(0., m.data[0][2], HKL_EPSILON, __func__);
is_double(0., m.data[1][0], HKL_EPSILON, __func__);
is_double(1., m.data[1][1], HKL_EPSILON, __func__);
is_double(0., m.data[1][2], HKL_EPSILON, __func__);
is_double(0., m.data[2][0], HKL_EPSILON, __func__);
is_double(0., m.data[2][1], HKL_EPSILON, __func__);
is_double(1., m.data[2][2], HKL_EPSILON, __func__);
}
static void cmp(void)
{
HklMatrix m1 = {{{0.0, 1.0, 2.0},
{3.0, 4.0, 5.0},
{6.0, 7.0, 8.0}}};
HklMatrix m2 = {{{1.0, 1.0, 2.0},
{3.0, 4.0, 5.0},
{6.0, 7.0, 8.0}}};
ok(TRUE == hkl_matrix_cmp(&m1, &m1), __func__);
ok(FALSE == hkl_matrix_cmp(&m1, &m2), __func__);
}
static void assignement(void)
{
HklMatrix m1 = {{{0.0, 1.0, 2.0},
{3.0, 4.0, 5.0},
{6.0, 7.0, 8.0}}};
HklMatrix m;
m = m1;
ok(TRUE == hkl_matrix_cmp(&m1, &m), __func__);
}
static void init_from_euler(void)
{
HklMatrix m_ref = {{{ 1./2., -1./2., sqrt(2)/2.},
{ sqrt(2.)/4.+1./2., -sqrt(2.)/4.+1./2., -1./2.},
{-sqrt(2.)/4.+1./2., sqrt(2.)/4.+1./2., 1./2.}}};
HklMatrix m;
hkl_matrix_init_from_euler(&m, 45.*HKL_DEGTORAD, 45.*HKL_DEGTORAD, 45.*HKL_DEGTORAD);
ok(TRUE == hkl_matrix_cmp(&m_ref, &m), __func__);
}
static void init_from_two_vector(void)
{
HklVector v1 = {{0.0, 1.0, 2.0}};
HklVector v2 = {{1.0, 2.0, 3.0}};
HklMatrix m_ref = {{{0.0, 5.0 / sqrt(30.0), -1.0 / sqrt(6.0)},
{1.0 / sqrt(5.0), 2.0 / sqrt(30.0), 2.0 / sqrt(6.0)},
{2.0 / sqrt(5.0),-1.0 / sqrt(30.0), -1.0 / sqrt(6.0)}}
};
HklMatrix m;
hkl_matrix_init_from_two_vector(&m, &v1, &v2);
ok(TRUE == hkl_matrix_cmp(&m_ref, &m), __func__);
}
static void times_vector(void)
{
HklMatrix m = {{{ 1.0, 3.0,-2.0},
{10.0, 5.0, 5.0},
{-3.0, 2.0, 0.0}}
};
HklVector v = {{1, 2, 3}};
HklVector v_ref = {{1, 35, 1}};
hkl_matrix_times_vector(&m, &v);
ok(0 == hkl_vector_cmp(&v_ref, &v), __func__);
}
static void times_matrix(void)
{
HklMatrix m_ref = {{{37., 14., 13.},
{45., 65., 5.},
{17., 1., 16.}}
};
HklMatrix m = {{{ 1., 3.,-2.},
{10., 5., 5.},
{-3., 2., 0.}}
};
hkl_matrix_times_matrix(&m, &m);
ok(TRUE == hkl_matrix_cmp(&m_ref, &m), __func__);
}
static void transpose(void)
{
HklMatrix m_ref = {{{37., 14., 13.},
{45., 65., 5.},
{17., 1., 16.}}
};
HklMatrix m = {{{37., 45., 17.},
{14., 65., 1.},
{13., 5., 16.}}
};
hkl_matrix_transpose(&m);
ok(TRUE == hkl_matrix_cmp(&m_ref, &m), __func__);
}
int main(void)
{
plan(17);
init();
cmp();
assignement();
init_from_euler();
init_from_two_vector();
times_vector();
times_matrix();
transpose();
return 0;
}
| Java |
{{ define "main" }}
<main>
<h1>{{ .Title }}</h1>
{{ if .Content }}
<article>
{{ .Content }}
</article>
{{ end }}
<hr />
<ul class="font-sans-title">
{{- range .Data.Pages -}}
<li>{{ .Date.Format "2006-01-02" }} — <a href="{{ .URL }}">{{ .Title }}</a></li>
{{ end }}
</ul>
</main>
{{ end }}
| Java |
@echo off
%~d0
cd "%~dp0"
call rebuild_orca.bat 105 TreeList105
| Java |
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
import re
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtWidgets import (
QPushButton,
QLineEdit,
QVBoxLayout,
QGridLayout,
QDialog,
QTableView,
QAbstractItemView,
QSpacerItem,
QSizePolicy,
QHeaderView,
)
from .exclude_list_table import ExcludeListTable
from core.exclude import AlreadyThereException
from hscommon.trans import trget
tr = trget("ui")
class ExcludeListDialog(QDialog):
def __init__(self, app, parent, model, **kwargs):
flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
super().__init__(parent, flags, **kwargs)
self.app = app
self.specific_actions = frozenset()
self._setupUI()
self.model = model # ExcludeListDialogCore
self.model.view = self
self.table = ExcludeListTable(app, view=self.tableView) # Qt ExcludeListTable
self._row_matched = False # test if at least one row matched our test string
self._input_styled = False
self.buttonAdd.clicked.connect(self.addStringFromLineEdit)
self.buttonRemove.clicked.connect(self.removeSelected)
self.buttonRestore.clicked.connect(self.restoreDefaults)
self.buttonClose.clicked.connect(self.accept)
self.buttonHelp.clicked.connect(self.display_help_message)
self.buttonTestString.clicked.connect(self.onTestStringButtonClicked)
self.inputLine.textEdited.connect(self.reset_input_style)
self.testLine.textEdited.connect(self.reset_input_style)
self.testLine.textEdited.connect(self.reset_table_style)
def _setupUI(self):
layout = QVBoxLayout(self)
gridlayout = QGridLayout()
self.buttonAdd = QPushButton(tr("Add"))
self.buttonRemove = QPushButton(tr("Remove Selected"))
self.buttonRestore = QPushButton(tr("Restore defaults"))
self.buttonTestString = QPushButton(tr("Test string"))
self.buttonClose = QPushButton(tr("Close"))
self.buttonHelp = QPushButton(tr("Help"))
self.inputLine = QLineEdit()
self.testLine = QLineEdit()
self.tableView = QTableView()
triggers = (
QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed | QAbstractItemView.SelectedClicked
)
self.tableView.setEditTriggers(triggers)
self.tableView.setSelectionMode(QTableView.ExtendedSelection)
self.tableView.setSelectionBehavior(QTableView.SelectRows)
self.tableView.setShowGrid(False)
vheader = self.tableView.verticalHeader()
vheader.setSectionsMovable(True)
vheader.setVisible(False)
hheader = self.tableView.horizontalHeader()
hheader.setSectionsMovable(False)
hheader.setSectionResizeMode(QHeaderView.Fixed)
hheader.setStretchLastSection(True)
hheader.setHighlightSections(False)
hheader.setVisible(True)
gridlayout.addWidget(self.inputLine, 0, 0)
gridlayout.addWidget(self.buttonAdd, 0, 1, Qt.AlignLeft)
gridlayout.addWidget(self.buttonRemove, 1, 1, Qt.AlignLeft)
gridlayout.addWidget(self.buttonRestore, 2, 1, Qt.AlignLeft)
gridlayout.addWidget(self.buttonHelp, 3, 1, Qt.AlignLeft)
gridlayout.addWidget(self.buttonClose, 4, 1)
gridlayout.addWidget(self.tableView, 1, 0, 6, 1)
gridlayout.addItem(QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding), 4, 1)
gridlayout.addWidget(self.buttonTestString, 6, 1)
gridlayout.addWidget(self.testLine, 6, 0)
layout.addLayout(gridlayout)
self.inputLine.setPlaceholderText(tr("Type a python regular expression here..."))
self.inputLine.setFocus()
self.testLine.setPlaceholderText(tr("Type a file system path or filename here..."))
self.testLine.setClearButtonEnabled(True)
# --- model --> view
def show(self):
super().show()
self.inputLine.setFocus()
@pyqtSlot()
def addStringFromLineEdit(self):
text = self.inputLine.text()
if not text:
return
try:
self.model.add(text)
except AlreadyThereException:
self.app.show_message("Expression already in the list.")
return
except Exception as e:
self.app.show_message(f"Expression is invalid: {e}")
return
self.inputLine.clear()
def removeSelected(self):
self.model.remove_selected()
def restoreDefaults(self):
self.model.restore_defaults()
def onTestStringButtonClicked(self):
input_text = self.testLine.text()
if not input_text:
self.reset_input_style()
return
# If at least one row matched, we know whether table is highlighted or not
self._row_matched = self.model.test_string(input_text)
self.table.refresh()
# Test the string currently in the input text box as well
input_regex = self.inputLine.text()
if not input_regex:
self.reset_input_style()
return
compiled = None
try:
compiled = re.compile(input_regex)
except re.error:
self.reset_input_style()
return
if self.model.is_match(input_text, compiled):
self.inputLine.setStyleSheet("background-color: rgb(10, 200, 10);")
self._input_styled = True
else:
self.reset_input_style()
def reset_input_style(self):
"""Reset regex input line background"""
if self._input_styled:
self.inputLine.setStyleSheet(self.styleSheet())
self._input_styled = False
def reset_table_style(self):
if self._row_matched:
self._row_matched = False
self.model.reset_rows_highlight()
self.table.refresh()
def display_help_message(self):
self.app.show_message(
tr(
"""\
These (case sensitive) python regular expressions will filter out files during scans.<br>\
Directores will also have their <strong>default state</strong> set to Excluded \
in the Directories tab if their name happens to match one of the selected regular expressions.<br>\
For each file collected, two tests are performed to determine whether or not to completely ignore it:<br>\
<li>1. Regular expressions with no path separator in them will be compared to the file name only.</li>
<li>2. Regular expressions with at least one path separator in them will be compared to the full path to the file.</li><br>
Example: if you want to filter out .PNG files from the "My Pictures" directory only:<br>\
<code>.*My\\sPictures\\\\.*\\.png</code><br><br>\
You can test the regular expression with the "test string" button after pasting a fake path in the test field:<br>\
<code>C:\\\\User\\My Pictures\\test.png</code><br><br>
Matching regular expressions will be highlighted.<br>\
If there is at least one highlight, the path or filename tested will be ignored during scans.<br><br>\
Directories and files starting with a period '.' are filtered out by default.<br><br>"""
)
)
| Java |
<meta name="viewport" content="user-scalable=no, width=device-width" />
<body>
<h3>276</h3>
<p>
Until you make up your mind on them, your beliefs that were brought
and injected to you by your family, religion or society will keep on
changing. Actually this kind of creative adaptiveness will help to
keep you away from egoistic worries, and channel your energies in the
direction of good. There is a strong possibility you will have
artistic and spiritual skills.
</p>
</body>
| Java |
#ifndef PLUGINMANAGER_H
#define PLUGINMANAGER_H
#include <QDialog>
#include <QIcon>
#include <QString>
#include <QHash>
#include <QList>
#include <SPlugin>
#include "spluginengine.h"
#include "perconf.h"
namespace Ui {
class LoadedPlugins;
}
class PluginManager : public QObject
{
Q_OBJECT
public:
PluginManager( PerConf *conf , const QString & pluginsDirectory , QWidget *parent = 0 );
~PluginManager();
void refreshUI();
void detect();
void setStyleSheet( const QString & style );
public slots:
void show();
void hide();
void pluginStarted( SPlugin *plugin );
void pluginStopped( SPlugin *plugin );
private slots:
void currentCellChanged( int row , int col );
void stop_start_CurrentItem();
private:
void save();
void loadSaved();
bool defaultActived( const QString & name ) const;
private:
Ui::LoadedPlugins *ui;
QDialog *dialog;
QList<SPlugin *> startedPlugins;
QHash<QString,SPlugin *> loadedPlugins;
QHash<QString,SPluginEngine *> plugins_hash;
QString plugin_dir_str;
PerConf *prc;
QString style_sheet;
};
#endif // PLUGINMANAGER_H
| Java |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2019 Evan Debenham
*
* 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.shatteredpixel.shatteredpixeldungeon.items.weapon.missiles.darts;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Adrenaline;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet;
public class AdrenalineDart extends TippedDart {
{
image = ItemSpriteSheet.ADRENALINE_DART;
}
@Override
public int proc(Char attacker, Char defender, int damage) {
Buff.prolong( defender, Adrenaline.class, Adrenaline.DURATION);
if (attacker.alignment == defender.alignment){
return 0;
}
return super.proc(attacker, defender, damage);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.