code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\db\pgsql;
use yii\base\InvalidArgumentException;
use yii\db\Constraint;
use yii\db\Expression;
use yii\db\ExpressionInterface;
use yii\db\Query;
use yii\db\PdoValue;
use yii\helpers\StringHelper;
/**
* QueryBuilder is the query builder for PostgreSQL databases.
*
* @author Gevik Babakhani <gevikb@gmail.com>
* @since 2.0
*/
class QueryBuilder extends \yii\db\QueryBuilder
{
/**
* Defines a UNIQUE index for [[createIndex()]].
* @since 2.0.6
*/
const INDEX_UNIQUE = 'unique';
/**
* Defines a B-tree index for [[createIndex()]].
* @since 2.0.6
*/
const INDEX_B_TREE = 'btree';
/**
* Defines a hash index for [[createIndex()]].
* @since 2.0.6
*/
const INDEX_HASH = 'hash';
/**
* Defines a GiST index for [[createIndex()]].
* @since 2.0.6
*/
const INDEX_GIST = 'gist';
/**
* Defines a GIN index for [[createIndex()]].
* @since 2.0.6
*/
const INDEX_GIN = 'gin';
/**
* @var array mapping from abstract column types (keys) to physical column types (values).
*/
public $typeMap = [
Schema::TYPE_PK => 'serial NOT NULL PRIMARY KEY',
Schema::TYPE_UPK => 'serial NOT NULL PRIMARY KEY',
Schema::TYPE_BIGPK => 'bigserial NOT NULL PRIMARY KEY',
Schema::TYPE_UBIGPK => 'bigserial NOT NULL PRIMARY KEY',
Schema::TYPE_CHAR => 'char(1)',
Schema::TYPE_STRING => 'varchar(255)',
Schema::TYPE_TEXT => 'text',
Schema::TYPE_TINYINT => 'smallint',
Schema::TYPE_SMALLINT => 'smallint',
Schema::TYPE_INTEGER => 'integer',
Schema::TYPE_BIGINT => 'bigint',
Schema::TYPE_FLOAT => 'double precision',
Schema::TYPE_DOUBLE => 'double precision',
Schema::TYPE_DECIMAL => 'numeric(10,0)',
Schema::TYPE_DATETIME => 'timestamp(0)',
Schema::TYPE_TIMESTAMP => 'timestamp(0)',
Schema::TYPE_TIME => 'time(0)',
Schema::TYPE_DATE => 'date',
Schema::TYPE_BINARY => 'bytea',
Schema::TYPE_BOOLEAN => 'boolean',
Schema::TYPE_MONEY => 'numeric(19,4)',
Schema::TYPE_JSON => 'jsonb',
];
/**
* {@inheritdoc}
*/
protected function defaultConditionClasses()
{
return array_merge(parent::defaultConditionClasses(), [
'ILIKE' => 'yii\db\conditions\LikeCondition',
'NOT ILIKE' => 'yii\db\conditions\LikeCondition',
'OR ILIKE' => 'yii\db\conditions\LikeCondition',
'OR NOT ILIKE' => 'yii\db\conditions\LikeCondition',
]);
}
/**
* {@inheritdoc}
*/
protected function defaultExpressionBuilders()
{
return array_merge(parent::defaultExpressionBuilders(), [
'yii\db\ArrayExpression' => 'yii\db\pgsql\ArrayExpressionBuilder',
'yii\db\JsonExpression' => 'yii\db\pgsql\JsonExpressionBuilder',
]);
}
/**
* Builds a SQL statement for creating a new index.
* @param string $name the name of the index. The name will be properly quoted by the method.
* @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
* @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
* separate them with commas or use an array to represent them. Each column name will be properly quoted
* by the method, unless a parenthesis is found in the name.
* @param bool|string $unique whether to make this a UNIQUE index constraint. You can pass `true` or [[INDEX_UNIQUE]] to create
* a unique index, `false` to make a non-unique index using the default index type, or one of the following constants to specify
* the index method to use: [[INDEX_B_TREE]], [[INDEX_HASH]], [[INDEX_GIST]], [[INDEX_GIN]].
* @return string the SQL statement for creating a new index.
* @see http://www.postgresql.org/docs/8.2/static/sql-createindex.html
*/
public function createIndex($name, $table, $columns, $unique = false)
{
if ($unique === self::INDEX_UNIQUE || $unique === true) {
$index = false;
$unique = true;
} else {
$index = $unique;
$unique = false;
}
return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ') .
$this->db->quoteTableName($name) . ' ON ' .
$this->db->quoteTableName($table) .
($index !== false ? " USING $index" : '') .
' (' . $this->buildColumns($columns) . ')';
}
/**
* Builds a SQL statement for dropping an index.
* @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
* @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
* @return string the SQL statement for dropping an index.
*/
public function dropIndex($name, $table)
{
if (strpos($table, '.') !== false && strpos($name, '.') === false) {
if (strpos($table, '{{') !== false) {
$table = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $table);
list($schema, $table) = explode('.', $table);
if (strpos($schema, '%') === false)
$name = $schema.'.'.$name;
else
$name = '{{'.$schema.'.'.$name.'}}';
} else {
list($schema) = explode('.', $table);
$name = $schema.'.'.$name;
}
}
return 'DROP INDEX ' . $this->db->quoteTableName($name);
}
/**
* Builds a SQL statement for renaming a DB table.
* @param string $oldName the table to be renamed. The name will be properly quoted by the method.
* @param string $newName the new table name. The name will be properly quoted by the method.
* @return string the SQL statement for renaming a DB table.
*/
public function renameTable($oldName, $newName)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($oldName) . ' RENAME TO ' . $this->db->quoteTableName($newName);
}
/**
* Creates a SQL statement for resetting the sequence value of a table's primary key.
* The sequence will be reset such that the primary key of the next new row inserted
* will have the specified value or 1.
* @param string $tableName the name of the table whose primary key sequence will be reset
* @param mixed $value the value for the primary key of the next new row inserted. If this is not set,
* the next new row's primary key will have a value 1.
* @return string the SQL statement for resetting sequence
* @throws InvalidArgumentException if the table does not exist or there is no sequence associated with the table.
*/
public function resetSequence($tableName, $value = null)
{
$table = $this->db->getTableSchema($tableName);
if ($table !== null && $table->sequenceName !== null) {
// c.f. http://www.postgresql.org/docs/8.1/static/functions-sequence.html
$sequence = $this->db->quoteTableName($table->sequenceName);
$tableName = $this->db->quoteTableName($tableName);
if ($value === null) {
$key = $this->db->quoteColumnName(reset($table->primaryKey));
$value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1";
} else {
$value = (int) $value;
}
return "SELECT SETVAL('$sequence',$value,false)";
} elseif ($table === null) {
throw new InvalidArgumentException("Table not found: $tableName");
}
throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
}
/**
* Builds a SQL statement for enabling or disabling integrity check.
* @param bool $check whether to turn on or off the integrity check.
* @param string $schema the schema of the tables.
* @param string $table the table name.
* @return string the SQL statement for checking integrity
*/
public function checkIntegrity($check = true, $schema = '', $table = '')
{
$enable = $check ? 'ENABLE' : 'DISABLE';
$schema = $schema ?: $this->db->getSchema()->defaultSchema;
$tableNames = $table ? [$table] : $this->db->getSchema()->getTableNames($schema);
$viewNames = $this->db->getSchema()->getViewNames($schema);
$tableNames = array_diff($tableNames, $viewNames);
$command = '';
foreach ($tableNames as $tableName) {
$tableName = $this->db->quoteTableName("{$schema}.{$tableName}");
$command .= "ALTER TABLE $tableName $enable TRIGGER ALL; ";
}
// enable to have ability to alter several tables
$this->db->getMasterPdo()->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
return $command;
}
/**
* Builds a SQL statement for truncating a DB table.
* Explicitly restarts identity for PGSQL to be consistent with other databases which all do this by default.
* @param string $table the table to be truncated. The name will be properly quoted by the method.
* @return string the SQL statement for truncating a DB table.
*/
public function truncateTable($table)
{
return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table) . ' RESTART IDENTITY';
}
/**
* Builds a SQL statement for changing the definition of a column.
* @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
* @param string $column the name of the column to be changed. The name will be properly quoted by the method.
* @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
* column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
* in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
* will become 'varchar(255) not null'. You can also use PostgreSQL-specific syntax such as `SET NOT NULL`.
* @return string the SQL statement for changing the definition of a column.
*/
public function alterColumn($table, $column, $type)
{
$columnName = $this->db->quoteColumnName($column);
$tableName = $this->db->quoteTableName($table);
// https://github.com/yiisoft/yii2/issues/4492
// http://www.postgresql.org/docs/9.1/static/sql-altertable.html
if (preg_match('/^(DROP|SET|RESET)\s+/i', $type)) {
return "ALTER TABLE {$tableName} ALTER COLUMN {$columnName} {$type}";
}
$type = 'TYPE ' . $this->getColumnType($type);
$multiAlterStatement = [];
$constraintPrefix = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column);
if (preg_match('/\s+DEFAULT\s+(["\']?\w+["\']?)/i', $type, $matches)) {
$type = preg_replace('/\s+DEFAULT\s+(["\']?\w+["\']?)/i', '', $type);
$multiAlterStatement[] = "ALTER COLUMN {$columnName} SET DEFAULT {$matches[1]}";
} else {
// safe to drop default even if there was none in the first place
$multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP DEFAULT";
}
$type = preg_replace('/\s+NOT\s+NULL/i', '', $type, -1, $count);
if ($count) {
$multiAlterStatement[] = "ALTER COLUMN {$columnName} SET NOT NULL";
} else {
// remove additional null if any
$type = preg_replace('/\s+NULL/i', '', $type);
// safe to drop not null even if there was none in the first place
$multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP NOT NULL";
}
if (preg_match('/\s+CHECK\s+\((.+)\)/i', $type, $matches)) {
$type = preg_replace('/\s+CHECK\s+\((.+)\)/i', '', $type);
$multiAlterStatement[] = "ADD CONSTRAINT {$constraintPrefix}_check CHECK ({$matches[1]})";
}
$type = preg_replace('/\s+UNIQUE/i', '', $type, -1, $count);
if ($count) {
$multiAlterStatement[] = "ADD UNIQUE ({$columnName})";
}
// add what's left at the beginning
array_unshift($multiAlterStatement, "ALTER COLUMN {$columnName} {$type}");
return 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $multiAlterStatement);
}
/**
* {@inheritdoc}
*/
public function insert($table, $columns, &$params)
{
return parent::insert($table, $this->normalizeTableRowData($table, $columns), $params);
}
/**
* {@inheritdoc}
* @see https://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT
* @see https://stackoverflow.com/questions/1109061/insert-on-duplicate-update-in-postgresql/8702291#8702291
*/
public function upsert($table, $insertColumns, $updateColumns, &$params)
{
$insertColumns = $this->normalizeTableRowData($table, $insertColumns);
if (!is_bool($updateColumns)) {
$updateColumns = $this->normalizeTableRowData($table, $updateColumns);
}
if (version_compare($this->db->getServerVersion(), '9.5', '<')) {
return $this->oldUpsert($table, $insertColumns, $updateColumns, $params);
}
return $this->newUpsert($table, $insertColumns, $updateColumns, $params);
}
/**
* [[upsert()]] implementation for PostgreSQL 9.5 or higher.
* @param string $table
* @param array|Query $insertColumns
* @param array|bool $updateColumns
* @param array $params
* @return string
*/
private function newUpsert($table, $insertColumns, $updateColumns, &$params)
{
$insertSql = $this->insert($table, $insertColumns, $params);
list($uniqueNames, , $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns);
if (empty($uniqueNames)) {
return $insertSql;
}
if ($updateNames === []) {
// there are no columns to update
$updateColumns = false;
}
if ($updateColumns === false) {
return "$insertSql ON CONFLICT DO NOTHING";
}
if ($updateColumns === true) {
$updateColumns = [];
foreach ($updateNames as $name) {
$updateColumns[$name] = new Expression('EXCLUDED.' . $this->db->quoteColumnName($name));
}
}
list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
return $insertSql . ' ON CONFLICT (' . implode(', ', $uniqueNames) . ') DO UPDATE SET ' . implode(', ', $updates);
}
/**
* [[upsert()]] implementation for PostgreSQL older than 9.5.
* @param string $table
* @param array|Query $insertColumns
* @param array|bool $updateColumns
* @param array $params
* @return string
*/
private function oldUpsert($table, $insertColumns, $updateColumns, &$params)
{
/** @var Constraint[] $constraints */
list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints);
if (empty($uniqueNames)) {
return $this->insert($table, $insertColumns, $params);
}
if ($updateNames === []) {
// there are no columns to update
$updateColumns = false;
}
/** @var Schema $schema */
$schema = $this->db->getSchema();
if (!$insertColumns instanceof Query) {
$tableSchema = $schema->getTableSchema($table);
$columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
foreach ($insertColumns as $name => $value) {
// NULLs and numeric values must be type hinted in order to be used in SET assigments
// NVM, let's cast them all
if (isset($columnSchemas[$name])) {
$phName = self::PARAM_PREFIX . count($params);
$params[$phName] = $value;
$insertColumns[$name] = new Expression("CAST($phName AS {$columnSchemas[$name]->dbType})");
}
}
}
list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params);
$updateCondition = ['or'];
$insertCondition = ['or'];
$quotedTableName = $schema->quoteTableName($table);
foreach ($constraints as $constraint) {
$constraintUpdateCondition = ['and'];
$constraintInsertCondition = ['and'];
foreach ($constraint->columnNames as $name) {
$quotedName = $schema->quoteColumnName($name);
$constraintUpdateCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
$constraintInsertCondition[] = "\"upsert\".$quotedName=\"EXCLUDED\".$quotedName";
}
$updateCondition[] = $constraintUpdateCondition;
$insertCondition[] = $constraintInsertCondition;
}
$withSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames)
. ') AS (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ')';
if ($updateColumns === false) {
$selectSubQuery = (new Query())
->select(new Expression('1'))
->from($table)
->where($updateCondition);
$insertSelectSubQuery = (new Query())
->select($insertNames)
->from('EXCLUDED')
->where(['not exists', $selectSubQuery]);
$insertSql = $this->insert($table, $insertSelectSubQuery, $params);
return "$withSql $insertSql";
}
if ($updateColumns === true) {
$updateColumns = [];
foreach ($updateNames as $name) {
$quotedName = $this->db->quoteColumnName($name);
if (strrpos($quotedName, '.') === false) {
$quotedName = '"EXCLUDED".' . $quotedName;
}
$updateColumns[$name] = new Expression($quotedName);
}
}
list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
$updateSql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $updates)
. ' FROM "EXCLUDED" ' . $this->buildWhere($updateCondition, $params)
. ' RETURNING ' . $this->db->quoteTableName($table) .'.*';
$selectUpsertSubQuery = (new Query())
->select(new Expression('1'))
->from('upsert')
->where($insertCondition);
$insertSelectSubQuery = (new Query())
->select($insertNames)
->from('EXCLUDED')
->where(['not exists', $selectUpsertSubQuery]);
$insertSql = $this->insert($table, $insertSelectSubQuery, $params);
return "$withSql, \"upsert\" AS ($updateSql) $insertSql";
}
/**
* {@inheritdoc}
*/
public function update($table, $columns, $condition, &$params)
{
return parent::update($table, $this->normalizeTableRowData($table, $columns), $condition, $params);
}
/**
* Normalizes data to be saved into the table, performing extra preparations and type converting, if necessary.
*
* @param string $table the table that data will be saved into.
* @param array|Query $columns the column data (name => value) to be saved into the table or instance
* of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
* Passing of [[yii\db\Query|Query]] is available since version 2.0.11.
* @return array normalized columns
* @since 2.0.9
*/
private function normalizeTableRowData($table, $columns)
{
if ($columns instanceof Query) {
return $columns;
}
if (($tableSchema = $this->db->getSchema()->getTableSchema($table)) !== null) {
$columnSchemas = $tableSchema->columns;
foreach ($columns as $name => $value) {
if (isset($columnSchemas[$name]) && $columnSchemas[$name]->type === Schema::TYPE_BINARY && is_string($value)) {
$columns[$name] = new PdoValue($value, \PDO::PARAM_LOB); // explicitly setup PDO param type for binary column
}
}
}
return $columns;
}
/**
* {@inheritdoc}
*/
public function batchInsert($table, $columns, $rows, &$params = [])
{
if (empty($rows)) {
return '';
}
$schema = $this->db->getSchema();
if (($tableSchema = $schema->getTableSchema($table)) !== null) {
$columnSchemas = $tableSchema->columns;
} else {
$columnSchemas = [];
}
$values = [];
foreach ($rows as $row) {
$vs = [];
foreach ($row as $i => $value) {
if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
$value = $columnSchemas[$columns[$i]]->dbTypecast($value);
}
if (is_string($value)) {
$value = $schema->quoteValue($value);
} elseif (is_float($value)) {
// ensure type cast always has . as decimal separator in all locales
$value = StringHelper::floatToString($value);
} elseif ($value === true) {
$value = 'TRUE';
} elseif ($value === false) {
$value = 'FALSE';
} elseif ($value === null) {
$value = 'NULL';
} elseif ($value instanceof ExpressionInterface) {
$value = $this->buildExpression($value, $params);
}
$vs[] = $value;
}
$values[] = '(' . implode(', ', $vs) . ')';
}
if (empty($values)) {
return '';
}
foreach ($columns as $i => $name) {
$columns[$i] = $schema->quoteColumnName($name);
}
return 'INSERT INTO ' . $schema->quoteTableName($table)
. ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
}
}
| Pgans/yii2a-devices | vendor/yiisoft/yiisoft/yii2/db/pgsql/QueryBuilder.php | PHP | gpl-3.0 | 22,618 |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the COPYING file, which can be found at the root of the source code *
* distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. *
* If you do not have access to either file, you may request a copy from *
* help@hdfgroup.org. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*
* Serial tests for encoding/decoding plists
*/
#include "h5test.h"
#include "H5ACprivate.h"
#include "H5Pprivate.h"
static int
test_encode_decode(hid_t orig_pl)
{
hid_t pl = (-1); /* Decoded property list */
void *temp_buf = NULL; /* Pointer to encoding buffer */
size_t temp_size = 0; /* Size of encoding buffer */
/* first call to encode returns only the size of the buffer needed */
if(H5Pencode(orig_pl, NULL, &temp_size) < 0)
STACK_ERROR
if(NULL == (temp_buf = (void *)HDmalloc(temp_size)))
TEST_ERROR
if(H5Pencode(orig_pl, temp_buf, &temp_size) < 0)
STACK_ERROR
if((pl = H5Pdecode(temp_buf)) < 0)
STACK_ERROR
if(!H5Pequal(orig_pl, pl))
PUTS_ERROR("encoding-decoding cycle failed\n")
if((H5Pclose(pl)) < 0)
STACK_ERROR
HDfree(temp_buf);
/* Success */
return(0);
error:
if(pl > 0)
H5Pclose(pl);
if(temp_buf)
HDfree(temp_buf);
return(-1);
} /* end test_encode_decode() */
int
main(void)
{
hid_t dcpl; /* dataset create prop. list */
hid_t dapl; /* dataset access prop. list */
hid_t dxpl; /* dataset xfer prop. list */
hid_t gcpl; /* group create prop. list */
hid_t ocpypl; /* object copy prop. list */
hid_t ocpl; /* object create prop. list */
hid_t lcpl; /* link create prop. list */
hid_t lapl; /* link access prop. list */
hid_t fapl; /* file access prop. list */
hid_t fcpl; /* file create prop. list */
hid_t strcpl; /* string create prop. list */
hid_t acpl; /* attribute create prop. list */
hsize_t chunk_size[2] = {16384, 4}; /* chunk size */
double fill = 2.7f; /* Fill value */
hsize_t max_size[1]; /* data space maximum size */
size_t nslots = 521 * 2;
size_t nbytes = 1048576 * 10;
double w0 = 0.5f;
unsigned max_compact;
unsigned min_dense;
const char* c_to_f = "x+32";
H5AC_cache_config_t my_cache_config = {
H5AC__CURR_CACHE_CONFIG_VERSION,
TRUE,
FALSE,
FALSE,
"temp",
TRUE,
FALSE,
( 2 * 2048 * 1024),
0.3f,
(64 * 1024 * 1024),
(4 * 1024 * 1024),
60000,
H5C_incr__threshold,
0.8f,
3.0f,
TRUE,
(8 * 1024 * 1024),
H5C_flash_incr__add_space,
2.0f,
0.25f,
H5C_decr__age_out_with_threshold,
0.997f,
0.8f,
TRUE,
(3 * 1024 * 1024),
3,
FALSE,
0.2f,
(256 * 2048),
H5AC__DEFAULT_METADATA_WRITE_STRATEGY};
H5AC_cache_image_config_t my_cache_image_config = {
H5AC__CURR_CACHE_IMAGE_CONFIG_VERSION,
TRUE,
FALSE,
-1};
if(VERBOSE_MED)
printf("Encode/Decode DCPLs\n");
/******* ENCODE/DECODE DCPLS *****/
TESTING("Default DCPL Encoding/Decoding");
if((dcpl = H5Pcreate(H5P_DATASET_CREATE)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding default property list */
if(test_encode_decode(dcpl) < 0)
FAIL_PUTS_ERROR("Default DCPL encoding/decoding failed\n")
PASSED();
TESTING("DCPL Encoding/Decoding");
if((H5Pset_chunk(dcpl, 2, chunk_size)) < 0)
FAIL_STACK_ERROR
if((H5Pset_alloc_time(dcpl, H5D_ALLOC_TIME_LATE)) < 0)
FAIL_STACK_ERROR
if((H5Pset_fill_value(dcpl, H5T_NATIVE_DOUBLE, &fill)) < 0)
FAIL_STACK_ERROR
max_size[0] = 100;
if((H5Pset_external(dcpl, "ext1.data", (off_t)0,
(hsize_t)(max_size[0] * sizeof(int)/4))) < 0)
FAIL_STACK_ERROR
if((H5Pset_external(dcpl, "ext2.data", (off_t)0,
(hsize_t)(max_size[0] * sizeof(int)/4))) < 0)
FAIL_STACK_ERROR
if((H5Pset_external(dcpl, "ext3.data", (off_t)0,
(hsize_t)(max_size[0] * sizeof(int)/4))) < 0)
FAIL_STACK_ERROR
if((H5Pset_external(dcpl, "ext4.data", (off_t)0,
(hsize_t)(max_size[0] * sizeof(int)/4))) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding property list */
if(test_encode_decode(dcpl) < 0)
FAIL_PUTS_ERROR("DCPL encoding/decoding failed\n")
/* release resource */
if((H5Pclose(dcpl)) < 0)
FAIL_STACK_ERROR
PASSED();
/******* ENCODE/DECODE DAPLS *****/
TESTING("Default DAPL Encoding/Decoding");
if((dapl = H5Pcreate(H5P_DATASET_ACCESS)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding default property list */
if(test_encode_decode(dapl) < 0)
FAIL_PUTS_ERROR("Default DAPL encoding/decoding failed\n")
PASSED();
TESTING("DAPL Encoding/Decoding");
if((H5Pset_chunk_cache(dapl, nslots, nbytes, w0)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding property list */
if(test_encode_decode(dapl) < 0)
FAIL_PUTS_ERROR("DAPL encoding/decoding failed\n")
/* release resource */
if((H5Pclose(dapl)) < 0)
FAIL_STACK_ERROR
PASSED();
/******* ENCODE/DECODE OCPLS *****/
TESTING("Default OCPL Encoding/Decoding");
if((ocpl = H5Pcreate(H5P_OBJECT_CREATE)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding default property list */
if(test_encode_decode(ocpl) < 0)
FAIL_PUTS_ERROR("Default OCPL encoding/decoding failed\n")
PASSED();
TESTING("OCPL Encoding/Decoding");
if((H5Pset_attr_creation_order(ocpl, (H5P_CRT_ORDER_TRACKED | H5P_CRT_ORDER_INDEXED))) < 0)
FAIL_STACK_ERROR
if((H5Pset_attr_phase_change (ocpl, 110, 105)) < 0)
FAIL_STACK_ERROR
if((H5Pset_filter (ocpl, H5Z_FILTER_FLETCHER32, 0, (size_t)0, NULL)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding property list */
if(test_encode_decode(ocpl) < 0)
FAIL_PUTS_ERROR("OCPL encoding/decoding failed\n")
/* release resource */
if((H5Pclose(ocpl)) < 0)
FAIL_STACK_ERROR
PASSED();
/******* ENCODE/DECODE DXPLS *****/
TESTING("Default DXPL Encoding/Decoding");
if((dxpl = H5Pcreate(H5P_DATASET_XFER)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding default property list */
if(test_encode_decode(dxpl) < 0)
FAIL_PUTS_ERROR("Default DXPL encoding/decoding failed\n")
PASSED();
TESTING("DXPL Encoding/Decoding");
if((H5Pset_btree_ratios(dxpl, 0.2f, 0.6f, 0.2f)) < 0)
FAIL_STACK_ERROR
if((H5Pset_hyper_vector_size(dxpl, 5)) < 0)
FAIL_STACK_ERROR
#ifdef H5_HAVE_PARALLEL
if((H5Pset_dxpl_mpio(dxpl, H5FD_MPIO_COLLECTIVE)) < 0)
FAIL_STACK_ERROR
if((H5Pset_dxpl_mpio_collective_opt(dxpl, H5FD_MPIO_INDIVIDUAL_IO)) < 0)
FAIL_STACK_ERROR
if((H5Pset_dxpl_mpio_chunk_opt(dxpl, H5FD_MPIO_CHUNK_MULTI_IO)) < 0)
FAIL_STACK_ERROR
if((H5Pset_dxpl_mpio_chunk_opt_ratio(dxpl, 30)) < 0)
FAIL_STACK_ERROR
if((H5Pset_dxpl_mpio_chunk_opt_num(dxpl, 40)) < 0)
FAIL_STACK_ERROR
#endif/* H5_HAVE_PARALLEL */
if((H5Pset_edc_check(dxpl, H5Z_DISABLE_EDC)) < 0)
FAIL_STACK_ERROR
if((H5Pset_data_transform(dxpl, c_to_f)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding property list */
if(test_encode_decode(dxpl) < 0)
FAIL_PUTS_ERROR("DXPL encoding/decoding failed\n")
/* release resource */
if((H5Pclose(dxpl)) < 0)
FAIL_STACK_ERROR
PASSED();
/******* ENCODE/DECODE GCPLS *****/
TESTING("Default GCPL Encoding/Decoding");
if((gcpl = H5Pcreate(H5P_GROUP_CREATE)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding default property list */
if(test_encode_decode(gcpl) < 0)
FAIL_PUTS_ERROR("Default GCPL encoding/decoding failed\n")
PASSED();
TESTING("GCPL Encoding/Decoding");
if((H5Pset_local_heap_size_hint(gcpl, 256)) < 0)
FAIL_STACK_ERROR
if((H5Pset_link_phase_change(gcpl, 2, 2)) < 0)
FAIL_STACK_ERROR
/* Query the group creation properties */
if((H5Pget_link_phase_change(gcpl, &max_compact, &min_dense)) < 0)
FAIL_STACK_ERROR
if((H5Pset_est_link_info(gcpl, 3, 9)) < 0)
FAIL_STACK_ERROR
if((H5Pset_link_creation_order(gcpl, (H5P_CRT_ORDER_TRACKED | H5P_CRT_ORDER_INDEXED))) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding property list */
if(test_encode_decode(gcpl) < 0)
FAIL_PUTS_ERROR("GCPL encoding/decoding failed\n")
/* release resource */
if((H5Pclose(gcpl)) < 0)
FAIL_STACK_ERROR
PASSED();
/******* ENCODE/DECODE LCPLS *****/
TESTING("Default LCPL Encoding/Decoding");
if((lcpl = H5Pcreate(H5P_LINK_CREATE)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding default property list */
if(test_encode_decode(lcpl) < 0)
FAIL_PUTS_ERROR("Default LCPL encoding/decoding failed\n")
PASSED();
TESTING("LCPL Encoding/Decoding");
if((H5Pset_create_intermediate_group(lcpl, TRUE)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding property list */
if(test_encode_decode(lcpl) < 0)
FAIL_PUTS_ERROR("LCPL encoding/decoding failed\n")
/* release resource */
if((H5Pclose(lcpl)) < 0)
FAIL_STACK_ERROR
PASSED();
/******* ENCODE/DECODE LAPLS *****/
TESTING("Default LAPL Encoding/Decoding");
if((lapl = H5Pcreate(H5P_LINK_ACCESS)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding default property list */
if(test_encode_decode(lapl) < 0)
FAIL_PUTS_ERROR("Default LAPL encoding/decoding failed\n")
PASSED();
TESTING("LAPL Encoding/Decoding");
if((H5Pset_nlinks(lapl, (size_t)134)) < 0)
FAIL_STACK_ERROR
if((H5Pset_elink_acc_flags(lapl, H5F_ACC_RDONLY)) < 0)
FAIL_STACK_ERROR
if((H5Pset_elink_prefix(lapl, "/tmpasodiasod")) < 0)
FAIL_STACK_ERROR
/* Create FAPL for the elink FAPL */
if((fapl = H5Pcreate(H5P_FILE_ACCESS)) < 0)
FAIL_STACK_ERROR
if((H5Pset_alignment(fapl, 2, 1024)) < 0)
FAIL_STACK_ERROR
if((H5Pset_elink_fapl(lapl, fapl)) < 0)
FAIL_STACK_ERROR
/* Close the elink's FAPL */
if((H5Pclose(fapl)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding property list */
if(test_encode_decode(lapl) < 0)
FAIL_PUTS_ERROR("LAPL encoding/decoding failed\n")
/* release resource */
if((H5Pclose(lapl)) < 0)
FAIL_STACK_ERROR
PASSED();
/******* ENCODE/DECODE OCPYPLS *****/
TESTING("Default OCPYPL Encoding/Decoding");
if((ocpypl = H5Pcreate(H5P_OBJECT_COPY)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding default property list */
if(test_encode_decode(ocpypl) < 0)
FAIL_PUTS_ERROR("Default OCPYPL encoding/decoding failed\n")
PASSED();
TESTING("OCPYPL Encoding/Decoding");
if((H5Pset_copy_object(ocpypl, H5O_COPY_EXPAND_EXT_LINK_FLAG)) < 0)
FAIL_STACK_ERROR
if((H5Padd_merge_committed_dtype_path(ocpypl, "foo")) < 0)
FAIL_STACK_ERROR
if((H5Padd_merge_committed_dtype_path(ocpypl, "bar")) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding property list */
if(test_encode_decode(ocpypl) < 0)
FAIL_PUTS_ERROR("OCPYPL encoding/decoding failed\n")
/* release resource */
if((H5Pclose(ocpypl)) < 0)
FAIL_STACK_ERROR
PASSED();
/******* ENCODE/DECODE FAPLS *****/
TESTING("Default FAPL Encoding/Decoding");
if((fapl = H5Pcreate(H5P_FILE_ACCESS)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding default property list */
if(test_encode_decode(fapl) < 0)
FAIL_PUTS_ERROR("Default FAPL encoding/decoding failed\n")
PASSED();
TESTING("FAPL Encoding/Decoding");
if((H5Pset_family_offset(fapl, 1024)) < 0)
FAIL_STACK_ERROR
if((H5Pset_meta_block_size(fapl, 2098452)) < 0)
FAIL_STACK_ERROR
if((H5Pset_sieve_buf_size(fapl, 1048576)) < 0)
FAIL_STACK_ERROR
if((H5Pset_alignment(fapl, 2, 1024)) < 0)
FAIL_STACK_ERROR
if((H5Pset_cache(fapl, 1024, 128, 10485760, 0.3f)) < 0)
FAIL_STACK_ERROR
if((H5Pset_elink_file_cache_size(fapl, 10485760)) < 0)
FAIL_STACK_ERROR
if((H5Pset_gc_references(fapl, 1)) < 0)
FAIL_STACK_ERROR
if((H5Pset_small_data_block_size(fapl, 2048)) < 0)
FAIL_STACK_ERROR
if((H5Pset_libver_bounds(fapl, H5F_LIBVER_LATEST, H5F_LIBVER_LATEST)) < 0)
FAIL_STACK_ERROR
if((H5Pset_fclose_degree(fapl, H5F_CLOSE_WEAK)) < 0)
FAIL_STACK_ERROR
if((H5Pset_multi_type(fapl, H5FD_MEM_GHEAP)) < 0)
FAIL_STACK_ERROR
if((H5Pset_mdc_config(fapl, &my_cache_config)) < 0)
FAIL_STACK_ERROR
if((H5Pset_mdc_image_config(fapl, &my_cache_image_config)) < 0)
FAIL_STACK_ERROR
if((H5Pset_core_write_tracking(fapl, TRUE, 1024 * 1024)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding property list */
if(test_encode_decode(fapl) < 0)
FAIL_PUTS_ERROR("FAPL encoding/decoding failed\n")
/* release resource */
if((H5Pclose(fapl)) < 0)
FAIL_STACK_ERROR
PASSED();
/******* ENCODE/DECODE FCPLS *****/
TESTING("Default FCPL Encoding/Decoding");
if((fcpl = H5Pcreate(H5P_FILE_CREATE)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding default property list */
if(test_encode_decode(fcpl) < 0)
FAIL_PUTS_ERROR("Default FCPL encoding/decoding failed\n")
PASSED();
TESTING("FCPL Encoding/Decoding");
if((H5Pset_userblock(fcpl, 1024) < 0))
FAIL_STACK_ERROR
if((H5Pset_istore_k(fcpl, 3) < 0))
FAIL_STACK_ERROR
if((H5Pset_sym_k(fcpl, 4, 5) < 0))
FAIL_STACK_ERROR
if((H5Pset_shared_mesg_nindexes(fcpl, 8) < 0))
FAIL_STACK_ERROR
if((H5Pset_shared_mesg_index(fcpl, 1, H5O_SHMESG_SDSPACE_FLAG, 32) < 0))
FAIL_STACK_ERROR
if((H5Pset_shared_mesg_phase_change(fcpl, 60, 20) < 0))
FAIL_STACK_ERROR
if((H5Pset_sizes(fcpl, 8, 4) < 0))
FAIL_STACK_ERROR
/* Test encoding & decoding property list */
if(test_encode_decode(fcpl) < 0)
FAIL_PUTS_ERROR("FCPL encoding/decoding failed\n")
/* release resource */
if((H5Pclose(fcpl)) < 0)
FAIL_STACK_ERROR
PASSED();
/******* ENCODE/DECODE STRCPLS *****/
TESTING("Default STRCPL Encoding/Decoding");
if((strcpl = H5Pcreate(H5P_STRING_CREATE)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding default property list */
if(test_encode_decode(strcpl) < 0)
FAIL_PUTS_ERROR("Default STRCPL encoding/decoding failed\n")
PASSED();
TESTING("STRCPL Encoding/Decoding");
if((H5Pset_char_encoding(strcpl, H5T_CSET_UTF8) < 0))
FAIL_STACK_ERROR
/* Test encoding & decoding property list */
if(test_encode_decode(strcpl) < 0)
FAIL_PUTS_ERROR("STRCPL encoding/decoding failed\n")
/* release resource */
if((H5Pclose(strcpl)) < 0)
FAIL_STACK_ERROR
PASSED();
/******* ENCODE/DECODE ACPLS *****/
TESTING("Default ACPL Encoding/Decoding");
if((acpl = H5Pcreate(H5P_ATTRIBUTE_CREATE)) < 0)
FAIL_STACK_ERROR
/* Test encoding & decoding default property list */
if(test_encode_decode(acpl) < 0)
FAIL_PUTS_ERROR("Default ACPL encoding/decoding failed\n")
PASSED();
TESTING("ACPL Encoding/Decoding");
if((H5Pset_char_encoding(acpl, H5T_CSET_UTF8) < 0))
FAIL_STACK_ERROR
/* Test encoding & decoding property list */
if(test_encode_decode(acpl) < 0)
FAIL_PUTS_ERROR("ACPL encoding/decoding failed\n")
/* release resource */
if((H5Pclose(acpl)) < 0)
FAIL_STACK_ERROR
PASSED();
return 0;
error:
printf("***** Plist Encode/Decode tests FAILED! *****\n");
return 1;
}
| ngcurrier/ProteusCFD | TPLs/hdf5/hdf5-1.10.2/test/enc_dec_plist.c | C | gpl-3.0 | 16,932 |
package org.triplea.modules.game.lobby.watcher;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.function.BiPredicate;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.triplea.db.dao.lobby.games.LobbyGameDao;
import org.triplea.domain.data.ApiKey;
import org.triplea.http.client.lobby.game.lobby.watcher.ChatMessageUpload;
@ExtendWith(MockitoExtension.class)
class ChatUploadModuleTest {
private static final ChatMessageUpload CHAT_MESSAGE_UPLOAD =
ChatMessageUpload.builder()
.gameId("game-id")
.apiKey("api-key")
.chatMessage("message")
.fromPlayer("player")
.build();
@Mock private LobbyGameDao lobbyGameDao;
@Mock private BiPredicate<ApiKey, String> gameIdValidator;
@InjectMocks private ChatUploadModule chatUploadModule;
@Test
void validApiAndGameIdPair() {
givenApiKeyIsValid(true);
final boolean result = chatUploadModule.upload(CHAT_MESSAGE_UPLOAD);
assertThat(result, is(true));
verify(lobbyGameDao).recordChat(CHAT_MESSAGE_UPLOAD);
}
@Test
void inValidApiAndGameIdPair() {
givenApiKeyIsValid(false);
final boolean result = chatUploadModule.upload(CHAT_MESSAGE_UPLOAD);
assertThat(result, is(false));
verify(lobbyGameDao, never()).recordChat(any());
}
private void givenApiKeyIsValid(final boolean isValid) {
when(gameIdValidator.test(
ApiKey.of(CHAT_MESSAGE_UPLOAD.getApiKey()), CHAT_MESSAGE_UPLOAD.getGameId()))
.thenReturn(isValid);
}
}
| triplea-game/triplea | spitfire-server/lobby-module/src/test/java/org/triplea/modules/game/lobby/watcher/ChatUploadModuleTest.java | Java | gpl-3.0 | 1,885 |
package us.talabrek.ultimateskyblock.handler;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.item.ItemInfo;
import net.milkbowl.vault.item.Items;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.RegisteredServiceProvider;
import us.talabrek.ultimateskyblock.uSkyBlock;
public enum VaultHandler {;
private static Permission perms;
private static Economy econ;
static {
perms = null;
econ = null;
}
public static void addPermission(final Player player, final String perk) {
perms.playerAdd(player, perk);
}
public static void addPermission(final OfflinePlayer player, final String perk) {
perms.playerAdd(null, player, perk);
}
public static void removePermission(final OfflinePlayer player, final String perk) {
perms.playerRemove(null, player, perk);
}
public static boolean hasPermission(OfflinePlayer player, String perk) {
return perms.playerHas(null, player, perk);
}
public static boolean setupPermissions() {
final RegisteredServiceProvider<Permission> rsp = (RegisteredServiceProvider<Permission>) uSkyBlock.getInstance().getServer().getServicesManager().getRegistration((Class) Permission.class);
if (rsp.getProvider() != null) {
perms = rsp.getProvider();
}
return perms != null;
}
public static boolean setupEconomy() {
if (uSkyBlock.getInstance().getServer().getPluginManager().getPlugin("Vault") == null) {
return false;
}
final RegisteredServiceProvider<Economy> rsp = (RegisteredServiceProvider<Economy>) uSkyBlock.getInstance().getServer().getServicesManager().getRegistration((Class) Economy.class);
if (rsp == null) {
return false;
}
econ = rsp.getProvider();
return econ != null;
}
public static String getItemName(ItemStack stack) {
if (stack != null) {
if (stack.getItemMeta() != null && stack.getItemMeta().getDisplayName() != null) {
return stack.getItemMeta().getDisplayName();
}
ItemInfo itemInfo = Items.itemByStack(stack);
return itemInfo != null ? itemInfo.getName() : "" + stack.getType();
}
return null;
}
public static boolean hasEcon() {
return econ != null;
}
public static void depositPlayer(Player player, double v) {
econ.depositPlayer(player, v);
}
public static Economy getEcon() {
return econ;
}
}
| swan201/uSkyBlock | uSkyBlock-Core/src/main/java/us/talabrek/ultimateskyblock/handler/VaultHandler.java | Java | gpl-3.0 | 2,682 |
C
C
C Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
C
C This program is free software; you can redistribute it and/or modify it
C under the terms of version 2.1 of the GNU Lesser General Public License
C as published by the Free Software Foundation.
C
C This program is distributed in the hope that it would be useful, but
C WITHOUT ANY WARRANTY; without even the implied warranty of
C MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
C
C Further, this software is distributed without any warranty that it is
C free of the rightful claim of any third person regarding infringement
C or the like. Any license provided herein, whether implied or
C otherwise, applies only to this software file. Patent licenses, if
C any, provided herein do not apply to combinations of this program with
C other software, or any other product whatsoever.
C
C You should have received a copy of the GNU Lesser General Public
C License along with this program; if not, write the Free Software
C Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307,
C USA.
C
C Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
C Mountain View, CA 94043, or:
C
C http://www.sgi.com
C
C For further information regarding this notice, see:
C
C http://oss.sgi.com/projects/GenInfo/NoticeExplan
C
C
SUBROUTINE XPFMT(ADDRESS,IN,OUT,MODE)
IMPLICIT INTEGER (A-Z)
C
C +----------------------------------------------------------------+
C | |
C | X P F M T |
C | |
C | PURPOSE: |
C | XPFMT transforms a binary image of an exchange package into |
C | a printable integer array. The printable result is 64 |
C | characters wide (including a leading 9 character address |
C | field) by 24 lines. (The first line contains a ruler and |
C | is intended for debugging.) |
C | |
C | ENTRY: |
C | The subroutine requires four parameters: |
C | ADDRESS: The nominal address of the exchange package in CRAY|
C | memory, given as a binary number. (If you are |
C | not going to print the first 8 characters of each |
C | line, this parameter need not have a meaningful |
C | value.) |
C | |
C | IN: A sixteen word integer array containing the |
C | binary representation of the exchange package. |
C | |
C | OUT: An integer array, nominally dimensioned (8,0:23) |
C | into which the character representation of the |
C | exchange package will be stored. The input value |
C | of the array is without significance. |
C | |
C | MODE: An integer word indicating the mode in which the |
C | exchange package is to be printed: |
C | ZERO - use internal evidence |
C | 'X'L - print as an X-MP exchange package |
C | 'S'L - print as a 1-S exchange package |
C | |
C | EXIT: |
C | Upon return to the user, OUT contains a printable |
C | representation of the exchange package. (The format of |
C | this representation is shown in comment statements below.) |
C | |
C | Translation of non-printable characters is not done by this |
C | routine. It is the responsibility of the calling program to |
C | process these characters as required. |
C | |
C +----------------------------------------------------------------+
INTEGER IN(0:15)
INTEGER OUT(8,0:23)
INTEGER XPBLANK(8,0:23)
SAVE XPBLANK
PARAMETER (NMODES=23)
INTEGER MODES(NMODES)
SAVE MODES
INTEGER ETYPE(2,0:3)
SAVE ETYPE
INTEGER SRMODE(0:3)
SAVE SRMODE
INTEGER XRMODE(0:3)
SAVE XRMODE
INTEGER BLANKS
SAVE BLANKS
DATA BLANKS/' '/
CDIR$ EJECT
C
C The following comments show the initialization of XPBLANK done
C by awkward-looking data statements following.
C
C |...+....1....+....2....+....3....+....4....+....5....+....6....
C oooooooo P ooooooooa A0 oooooooo aaa MODES FLAGS
C oooooooo IBA oooooooo A1 oooooooo aaa OFF ON OFF ON
C oooooooo ILA oooooooo A2 oooooooo aaa MM MM PCI PCI
C oooooooo XA oooo VL ooo A3 oooooooo aaa ICM ICM MCU MCU
C oooooooo DBA oooooooo A4 oooooooo aaa IFP IFP FPE FPE
C oooooooo DLA oooooooo A5 oooooooo aaa IUM IUM ORE ORE
C oooooooo A6 oooooooo aaa IMM IMM PRE PRE
C oooooooo A7 oooooooo aaa SEI SEI ME ME
C BDM BDM IOI IOI
C oooooooo S0 ooooooooooooooooooooooo aaaaaaaa FPS FPS EEX EEX
C oooooooo S1 ooooooooooooooooooooooo aaaaaaaa WS WS NEX NEX
C oooooooo S2 ooooooooooooooooooooooo aaaaaaaa IOR IOR DL DL
C oooooooo S3 ooooooooooooooooooooooo aaaaaaaa EMA EMA ICP ICP
C oooooooo S4 ooooooooooooooooooooooo aaaaaaaa SVL SVL
C oooooooo S5 ooooooooooooooooooooooo aaaaaaaa
C oooooooo S6 ooooooooooooooooooooooo aaaaaaaa
C oooooooo S7 ooooooooooooooooooooooo aaaaaaaa
C
C PROCESSOR = o CLUSTER = o PS = o
C ERROR TYPE = aaaaaaaaaaaaaaaa VNU= o
C CHIP SLCT = oooooo BANK = oo
C READ MODE = aaaaaa SYNDROME = ooo
C
DATA ((XPBLANK(K1,K2),K1=1,5),K2=0,15)/
$ '|...+...','.1....+.','...2....','+....3..','..+....4',
$ 'oooooooo',' P ooo','oooooa ',' A0 ','oooooooo',
$ 'oooooooo',' IBA ooo','ooooo ',' A1 ','oooooooo',
$ 'oooooooo',' ILA ooo','ooooo ',' A2 ','oooooooo',
$ 'oooooooo',' XA ',' oooo VL',' ooo A3 ','oooooooo',
$ 'oooooooo',' DBA ooo','ooooo ',' A4 ','oooooooo',
$ 'oooooooo',' DLA ooo','ooooo ',' A5 ','oooooooo',
$ 'oooooooo',' ',' ',' A6 ','oooooooo',
$ 'oooooooo',' ',' ',' A7 ','oooooooo',
$ ' ',' ',' ',' ',' ',
$ 'oooooooo',' S0 oooo','oooooooo','oooooooo','ooo aaaa',
$ 'oooooooo',' S1 oooo','oooooooo','oooooooo','ooo aaaa',
$ 'oooooooo',' S2 oooo','oooooooo','oooooooo','ooo aaaa',
$ 'oooooooo',' S3 oooo','oooooooo','oooooooo','ooo aaaa',
$ 'oooooooo',' S4 oooo','oooooooo','oooooooo','ooo aaaa',
$ 'oooooooo',' S5 oooo','oooooooo','oooooooo','ooo aaaa'/
C
DATA ((XPBLANK(K1,K2),K1=1,5),K2=16,23)/
$ 'oooooooo',' S6 oooo','oooooooo','oooooooo','ooo aaaa',
$ 'oooooooo',' S7 oooo','oooooooo','oooooooo','ooo aaaa',
$ ' ',' ',' ',' ',' ',
$ ' ',' PROCESS','OR = o ',' CLUST','ER = o P',
$ ' ',' ERROR T','YPE = aa','aaaaaaaa','aaaaaa V',
$ ' ',' CHIP SL','CT = oo','oooo BAN','K = oo ',
$ ' ',' READ MO','DE = aa','aaaa SYN','DROME = ',
$ ' ',' ',' ',' ',' '/
DATA ((XPBLANK(K1,K2),K1=6,8),K2=0,15)/
$ '....+...','.5....+.','...6....',
$ ' aaa MO','DES ','FLAGS ',
$ ' aaa OFF',' ON OF','F ON ',
$ ' aaa MM ',' MM PC','I PCI ',
$ ' aaa ICM',' ICM MC','U MCU ',
$ ' aaa IFP',' IFP FP','E FPE ',
$ ' aaa IUM',' IUM OR','E ORE ',
$ ' aaa IMM',' IMM PR','E PRE ',
$ ' aaa SEI',' SEI ME',' ME ',
$ ' BDM',' BDM IO','I IOI ',
$ 'aaaa FPS',' FPS EE','X EEX ',
$ 'aaaa WS ',' WS NE','X NEX ',
$ 'aaaa IOR',' IOR DL',' DL ',
$ 'aaaa EMA',' EMA IC','P ICP ',
$ 'aaaa SVL',' SVL ',' ',
$ 'aaaa ',' ',' '/
C
DATA ((XPBLANK(K1,K2),K1=6,8),K2=16,23)/
$ 'aaaa ',' ',' ',
$ 'aaaa ',' ',' ',
$ ' ',' ',' ',
$ 'S = o ',' ',' ',
$ 'NU= o ',' ',' ',
$ ' ',' ',' ',
$ 'ooo ',' ',' ',
$ ' ',' ',' '/
C
C MODES
C
C The array controlling mode bits is packed:
C
C Bits Meaning
C 0-3 0=Skip the entry
C 1=CRAY-1S
C 2=CRAY X-MP
C 3=CRAY-1S and CRAY X-MP
C
C 4-18 Output word
C 19-33 Output character position
C 34-48 Input word
C 49-63 Input bit position
C
DATA MODES( 1)/ 03 00003 00056 00002 00047B/
DATA MODES( 2)/ 03 00004 00056 00002 00044B/
DATA MODES( 3)/ 03 00005 00056 00002 00045B/
DATA MODES( 4)/ 03 00006 00056 00002 00046B/
DATA MODES( 5)/ 03 00007 00056 00001 00047B/
DATA MODES( 6)/ 02 00010 00056 00001 00046B/
DATA MODES( 7)/ 02 00011 00056 00001 00045B/
DATA MODES( 8)/ 02 00012 00056 00001 00044B/
DATA MODES( 9)/ 02 00013 00056 00001 00043B/
DATA MODES(10)/ 02 00014 00056 00002 00043B/
DATA MODES(11)/ 03 00003 00067 00003 00037B/
DATA MODES(12)/ 03 00004 00067 00003 00040B/
DATA MODES(13)/ 03 00005 00067 00003 00041B/
DATA MODES(14)/ 03 00006 00067 00003 00042B/
DATA MODES(15)/ 03 00007 00067 00003 00043B/
DATA MODES(16)/ 03 00010 00067 00003 00044B/
DATA MODES(17)/ 03 00011 00067 00003 00045B/
DATA MODES(18)/ 03 00012 00067 00003 00046B/
DATA MODES(19)/ 03 00013 00067 00003 00047B/
DATA MODES(20)/ 02 00014 00067 00003 00017B/
DATA MODES(21)/ 02 00015 00067 00003 00016B/
DATA MODES(22)/ 02 00015 00056 00004 00000B/
DATA MODES(23)/ 02 00016 00056 00003 00000B/
DATA ETYPE/'NONE ',' ',
$ 'CORRECTA','BLE ',
$ 'UNCORREC','TABLE ',
$ 'INVALID ','VALUE-11'/
C
DATA SRMODE/'SCALAR ','I/O ','VECTOR ','FETCH '/
DATA XRMODE/'I/O ','SCALAR ','VECTOR ','FETCH '/
CDIR$ EJECT
C
C Stetement function definitions
C
INTEGER GET, PUT
GET(W,SS,N) = AND(MASK(128-N),SHIFTR(W,64-SS-N))
PUT(W,SS,N,V) = CSMG(SHIFTL(V,64-SS-N),W,SHIFTR(MASK(N),SS))
CDIR$ EJECT
IF (MODE .EQ. 0) THEN
IF (GET(IN(4),16,19) .EQ. 0 .AND. GET(IN(5),16,19) .EQ. 0) THEN
MACHINE = 'S'L
ELSE
MACHINE = 'X'L
ENDIF
ELSE
MACHINE = MODE
ENDIF
DO 80 J = 0,23
DO 80 I = 1,8
OUT(I,J) = XPBLANK(I,J)
80 CONTINUE
C
C We will fill in the easy stuff first: octal address, A-registers,
C S-registers.
C
C Fill in the octal address
C
DO 100 I = 1,8
CALL B2OCT(OUT(1,I),1,8,ADDRESS+I-1,24)
100 CONTINUE
DO 120 I = 10,17
CALL B2OCT(OUT(1,I),1,8,ADDRESS+I-2,24)
120 CONTINUE
C
C Fill in the A-registers
C
DO 140 I = 1,8
CALL B2OCT(OUT(1,I),33,8,AND(IN(I-1),MASK(128-24)),24)
CALL MVC(IN(I-1),6,OUT(1,I),42,3)
140 CONTINUE
C
C Fill in the S-registers
C
DO 160 I = 8,15
CALL B2OCT(OUT(1,I+2),13,23,IN(I),64)
CALL MVC(IN(I),1,OUT(1,I+2),37,8)
160 CONTINUE
C
C Fill in the stuff common to both breeds of machine
C
C The P-register
C
C What about the PARCEAL ADDRESS.
C ALSO get bits 38,39 and decode it to A B C or D
C
CALL B2OCT(OUT(1,1),14,8,GET(IN(0),16,22),22)
CALL PUTBYT(OUT(1,1),22,GET(IN(0),38,2)+141B)
C
C The 1S base/limit or the X-MP instruction base/limit
C
IF (MACHINE .EQ. 'X'L) THEN
IBITS = 16
IBITL = 19
ISHFL = 5
ELSE
IBITS = 18
IBITL = 18
ISHFL = 4
ENDIF
CALL B2OCT(OUT(1,2),14,8,SHIFTL(GET(IN(1),IBITS,IBITL),ISHFL),24)
CALL B2OCT(OUT(1,3),14,8,SHIFTL(GET(IN(2),IBITS,IBITL),ISHFL),24)
C
C The exchange address and vector length
C
CALL B2OCT(OUT(1,4),18,4,SHIFTL(GET(IN(3),16,8),4),12)
CALL B2OCT(OUT(1,4),26,3,GET(IN(3),24,7),7)
C
C Fill in the modes and flag bits
C
DO 200 I = 1,NMODES
TEMP = MODES(I)
MT = GET(TEMP,0,4)
OW = GET(TEMP,4,15)
OC = GET(TEMP,19,15)
IW = GET(TEMP,34,15)
IB = GET(TEMP,49,15)
C
C Blank inapplicable fields
C
IF ((MT .EQ. 0) .OR.
$ (MT .EQ. 1 .AND. MACHINE .EQ. 'X'L) .OR.
$ (MT .EQ. 2 .AND. MACHINE .EQ. 'S'L)) THEN
CALL MVC(BLANKS,1,OUT(1,OW),OC,8)
ELSE
IF (GET(IN(IW),IB,1) .EQ. 0) THEN
CALL MVC(BLANKS,1,OUT(1,OW),OC+4,4)
ELSE
CALL MVC(BLANKS,1,OUT(1,OW),OC,4)
ENDIF
ENDIF
200 CONTINUE
C
C Fill in the rest of the exchange package depending on machine
C type.
C
IF (MACHINE .EQ. 'X'L) THEN
C
C Data base/limit addresses
C
CALL B2OCT(OUT(1,5),14,8,SHIFTL(GET(IN(4),16,19),5),24)
CALL B2OCT(OUT(1,6),14,8,SHIFTL(GET(IN(5),16,19),5),24)
C
C Processor
C
CALL B2OCT(OUT(1,19),23,1,GET(IN(0),0,2),2)
C
C Cluster
C
CALL B2OCT(OUT(1,19),38,1,GET(IN(4),37,3),3)
C
C Program state
C
CALL B2OCT(OUT(1,19),45,1,GET(IN(4),35,1),1)
C
C Error type
C
CALL MVC(ETYPE(1,GET(IN(0),2,2)),1,OUT(1,20),23,16)
C
C Vectors not used
C
CALL B2OCT(OUT(1,20),45,1,GET(IN(2),0,1),1)
C
C Chip select
C
CALL B2OCT(OUT(1,21),23,6,GET(IN(1),2,5),5)
C
C Bank
C
CALL B2OCT(OUT(1,21),37,2,GET(IN(1),7,5),5)
C
C Read mode
C
CALL MVC(XRMODE(GET(IN(1),0,2)),1,OUT(1,22),23,6)
C
C Syndrome
C
CALL B2OCT(OUT(1,22),41,3,GET(IN(0),4,8),8)
ELSE
C
C For the 1S, blank out the DBA, DLA fields and change IBA
C and ILA to BA and LA
C
CALL MVC('BA',1,OUT(1,2),10,3)
CALL MVC('LA',1,OUT(1,3),10,3)
CALL MVC(BLANKS,1,OUT(1,5),10,8)
CALL MVC(BLANKS,1,OUT(1,6),10,8)
CALL MVC(BLANKS,1,OUT(1,5),18,8)
CALL MVC(BLANKS,1,OUT(1,6),18,8)
C
C Blank out the multi-processor stuff
C
CALL PUTBYT(OUT(1,19),1,' 'R)
CALL MVC (OUT(1,19),1,OUT(1,19),2,63)
C
C Blank out VU
C
CALL MVC(BLANKS,1,OUT(1,20),40,6)
C
C Read mode
C
CALL MVC(SRMODE(GET(IN(0),10,2)),1,OUT(1,22),23,6)
C
C Error type
C
CALL MVC(ETYPE(1,GET(IN(0),00,2)),1,OUT(1,20),23,16)
C
C Syndrome
C
CALL B2OCT(OUT(1,22),41,3,GET(IN(0),2,8),8)
C
C Blank out line 21
C
CALL PUTBYT(OUT(1,21),1,' 'R)
CALL MVC (OUT(1,21),1,OUT(1,21),2,63)
C
C Insert text
C
CALL MVC ('ERROR AD',1,OUT(1,21),10,8)
CALL MVC ('DRESS = ',1,OUT(1,21),18,8)
CALL MVC (' ',1,OUT(1,21),26,2)
TEMP = 0
TEMP = PUT(TEMP,42, 2,GET(IN(2),14, 2))
TEMP = PUT(TEMP,44,16,GET(IN(1), 0,16))
TEMP = PUT(TEMP,60, 4,GET(IN(0),12, 4))
CALL B2OCT(OUT(1,21),28,8,TEMP,24)
ENDIF
RETURN
END
SUBROUTINE B2OCT(S,J,K,V,N)
IMPLICIT INTEGER (A-Z)
INTEGER S(8)
C
C +----------------------------------------------------------------+
C | |
C | B 2 O C T |
C | |
C | PURPOSE: |
C | B2OCT places the low order N bits of the full CRAY word V |
C | as octal characters into the low-order positions of the |
C | string defined by S, J, and K. The string will be padded |
C | with blanks on the left. |
C | |
C | |
C | |
C +----------------------------------------------------------------+
C
C Stetement function definitions
C
INTEGER GET, PUT
GET(W,SS,N) = AND(MASK(128-N),SHIFTR(W,64-SS-N))
PUT(W,SS,N,V) = CSMG(SHIFTL(V,64-SS-N),W,SHIFTR(MASK(N),SS))
C
C Clear the destination string to blanks
C
CALL PUTBYT(S,J,' 'R)
CALL MVC(S,J,S,J+1,K-1)
C
C At the high-order end, there may be a partial octal character.
C How many characters are required?
C
NCH = ICEIL(N,3)
C
C If there are not enough characters in the substring, then
C
IF (NCH .GT. K) THEN
C
C Fill the substring with asterisks to show an error
C
CALL PUTBYT(S,J,'*'R)
CALL MVC(S,J,S,J+1,K-1)
ELSE
C
C Process the high-order octal digit
C
JN = J+K-NCH
BN = 64-N
BL = MOD(N,3)
IF (BL .EQ. 0) BL = 3
CALL PUTBYT(S,JN,GET(V,BN,BL)+'0'R)
100 CONTINUE
C
C Check for loop termination
C
JN = JN + 1
BN = BN + BL
BL = 3
IF (BN+BL .GT. 64) GO TO 200
CALL PUTBYT(S,JN,GET(V,BN,BL)+'0'R)
GO TO 100
200 CONTINUE
ENDIF
RETURN
CDIR$ ID "@(#) libu/util/c1/xpfmt.f 92.0 10/08/98 14:57:41"
END
| pumpkin83/OpenUH-OpenACC | osprey/libu/util/c1/xpfmt.f | FORTRAN | gpl-3.0 | 34,802 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NeoComp.LogicalEvolution
{
public abstract class LogicalNetworkGene
{
protected LogicalNetworkGene(int index)
{
Index = index;
}
public int Index { get; private set; }
}
}
| unbornchikken/Neuroflow | _vault/NFBak/Neuroflow_vsonline/Neuroflow/OldStuff/NeoComp/Neocomp Framework/NeoComp/LogicalEvolution/LogicalNetworkGene.cs | C# | gpl-3.0 | 337 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_socket::assign</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../basic_socket.html" title="basic_socket">
<link rel="prev" href="../basic_socket.html" title="basic_socket">
<link rel="next" href="assign/overload1.html" title="basic_socket::assign (1 of 2 overloads)">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../basic_socket.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="assign/overload1.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.reference.basic_socket.assign"></a><a class="link" href="assign.html" title="basic_socket::assign">basic_socket::assign</a>
</h4></div></div></div>
<p>
<a class="indexterm" name="idm45773651652016"></a>
Assign an existing native socket to the socket.
</p>
<pre class="programlisting"><span class="keyword">void</span> <a class="link" href="assign/overload1.html" title="basic_socket::assign (1 of 2 overloads)">assign</a><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">protocol_type</span> <span class="special">&</span> <span class="identifier">protocol</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">native_handle_type</span> <span class="special">&</span> <span class="identifier">native_socket</span><span class="special">);</span>
<span class="emphasis"><em>» <a class="link" href="assign/overload1.html" title="basic_socket::assign (1 of 2 overloads)">more...</a></em></span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <a class="link" href="assign/overload2.html" title="basic_socket::assign (2 of 2 overloads)">assign</a><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">protocol_type</span> <span class="special">&</span> <span class="identifier">protocol</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">native_handle_type</span> <span class="special">&</span> <span class="identifier">native_socket</span><span class="special">,</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&</span> <span class="identifier">ec</span><span class="special">);</span>
<span class="emphasis"><em>» <a class="link" href="assign/overload2.html" title="basic_socket::assign (2 of 2 overloads)">more...</a></em></span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2015 Christopher M.
Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../basic_socket.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="assign/overload1.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| gwq5210/litlib | thirdparty/sources/boost_1_60_0/doc/html/boost_asio/reference/basic_socket/assign.html | HTML | gpl-3.0 | 4,940 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com>
#
# This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# the additional special exception to link portions of this program with the OpenSSL library.
# See LICENSE for more details.
#
import copy
import logging
import deluge.component as component
from deluge.common import TORRENT_STATE
log = logging.getLogger(__name__)
STATE_SORT = ["All", "Active"] + TORRENT_STATE
# Special purpose filters:
def filter_keywords(torrent_ids, values):
# Cleanup
keywords = ",".join([v.lower() for v in values])
keywords = keywords.split(",")
for keyword in keywords:
torrent_ids = filter_one_keyword(torrent_ids, keyword)
return torrent_ids
def filter_one_keyword(torrent_ids, keyword):
"""
search torrent on keyword.
searches title,state,tracker-status,tracker,files
"""
all_torrents = component.get("TorrentManager").torrents
for torrent_id in torrent_ids:
torrent = all_torrents[torrent_id]
if keyword in torrent.filename.lower():
yield torrent_id
elif keyword in torrent.state.lower():
yield torrent_id
elif torrent.trackers and keyword in torrent.trackers[0]["url"]:
yield torrent_id
elif keyword in torrent_id:
yield torrent_id
# Want to find broken torrents (search on "error", or "unregistered")
elif keyword in torrent.tracker_status.lower():
yield torrent_id
else:
for t_file in torrent.get_files():
if keyword in t_file["path"].lower():
yield torrent_id
break
def filter_by_name(torrent_ids, search_string):
all_torrents = component.get("TorrentManager").torrents
try:
search_string, match_case = search_string[0].split('::match')
except ValueError:
search_string = search_string[0]
match_case = False
if match_case is False:
search_string = search_string.lower()
for torrent_id in torrent_ids:
torrent_name = all_torrents[torrent_id].get_name()
if match_case is False:
torrent_name = all_torrents[torrent_id].get_name().lower()
else:
torrent_name = all_torrents[torrent_id].get_name()
if search_string in torrent_name:
yield torrent_id
def tracker_error_filter(torrent_ids, values):
filtered_torrent_ids = []
tm = component.get("TorrentManager")
# If this is a tracker_host, then we need to filter on it
if values[0] != "Error":
for torrent_id in torrent_ids:
if values[0] == tm[torrent_id].get_status(["tracker_host"])["tracker_host"]:
filtered_torrent_ids.append(torrent_id)
return filtered_torrent_ids
# Check torrent's tracker_status for 'Error:' and return those torrent_ids
for torrent_id in torrent_ids:
if "Error:" in tm[torrent_id].get_status(["tracker_status"])["tracker_status"]:
filtered_torrent_ids.append(torrent_id)
return filtered_torrent_ids
class FilterManager(component.Component):
"""FilterManager
"""
def __init__(self, core):
component.Component.__init__(self, "FilterManager")
log.debug("FilterManager init..")
self.core = core
self.torrents = core.torrentmanager
self.registered_filters = {}
self.register_filter("keyword", filter_keywords)
self.register_filter("name", filter_by_name)
self.tree_fields = {}
self.prev_filter_tree_keys = None
self.filter_tree_items = None
self.register_tree_field("state", self._init_state_tree)
def _init_tracker_tree():
return {"Error": 0}
self.register_tree_field("tracker_host", _init_tracker_tree)
self.register_filter("tracker_host", tracker_error_filter)
def _init_users_tree():
return {"": 0}
self.register_tree_field("owner", _init_users_tree)
def filter_torrent_ids(self, filter_dict):
"""
returns a list of torrent_id's matching filter_dict.
core filter method
"""
if not filter_dict:
return self.torrents.get_torrent_list()
# Sanitize input: filter-value must be a list of strings
for key, value in filter_dict.items():
if isinstance(value, basestring):
filter_dict[key] = [value]
# Optimized filter for id
if "id" in filter_dict:
torrent_ids = list(filter_dict["id"])
del filter_dict["id"]
else:
torrent_ids = self.torrents.get_torrent_list()
# Return if there's nothing more to filter
if not filter_dict:
return torrent_ids
# Special purpose, state=Active.
if "state" in filter_dict:
# We need to make sure this is a list for the logic below
filter_dict["state"] = list(filter_dict["state"])
if "state" in filter_dict and "Active" in filter_dict["state"]:
filter_dict["state"].remove("Active")
if not filter_dict["state"]:
del filter_dict["state"]
torrent_ids = self.filter_state_active(torrent_ids)
if not filter_dict:
return torrent_ids
# Registered filters
for field, values in filter_dict.items():
if field in self.registered_filters:
# Filters out doubles
torrent_ids = list(set(self.registered_filters[field](torrent_ids, values)))
del filter_dict[field]
if not filter_dict:
return torrent_ids
torrent_keys, plugin_keys = self.torrents.separate_keys(filter_dict.keys(), torrent_ids)
# Leftover filter arguments, default filter on status fields.
for torrent_id in list(torrent_ids):
status = self.core.create_torrent_status(torrent_id, torrent_keys, plugin_keys)
for field, values in filter_dict.iteritems():
if (not status[field] in values) and torrent_id in torrent_ids:
torrent_ids.remove(torrent_id)
return torrent_ids
def get_filter_tree(self, show_zero_hits=True, hide_cat=None):
"""
returns {field: [(value,count)] }
for use in sidebar.
"""
torrent_ids = self.torrents.get_torrent_list()
tree_keys = list(self.tree_fields.keys())
if hide_cat:
for cat in hide_cat:
tree_keys.remove(cat)
torrent_keys, plugin_keys = self.torrents.separate_keys(tree_keys, torrent_ids)
# Keys are the same, so use previous items
if self.prev_filter_tree_keys != tree_keys:
self.filter_tree_items = dict((field, self.tree_fields[field]()) for field in tree_keys)
self.prev_filter_tree_keys = tree_keys
items = copy.deepcopy(self.filter_tree_items)
for torrent_id in list(torrent_ids):
status = self.core.create_torrent_status(torrent_id, torrent_keys, plugin_keys) # status={key:value}
for field in tree_keys:
value = status[field]
items[field][value] = items[field].get(value, 0) + 1
if "tracker_host" in items:
items["tracker_host"]["All"] = len(torrent_ids)
items["tracker_host"]["Error"] = len(tracker_error_filter(torrent_ids, ("Error",)))
if not show_zero_hits:
for cat in ["state", "owner", "tracker_host"]:
if cat in tree_keys:
self._hide_state_items(items[cat])
# Return a dict of tuples:
sorted_items = {}
for field in tree_keys:
sorted_items[field] = sorted(items[field].iteritems())
if "state" in tree_keys:
sorted_items["state"].sort(self._sort_state_items)
return sorted_items
def _init_state_tree(self):
init_state = {}
init_state["All"] = len(self.torrents.get_torrent_list())
for state in TORRENT_STATE:
init_state[state] = 0
init_state["Active"] = len(self.filter_state_active(self.torrents.get_torrent_list()))
return init_state
def register_filter(self, id, filter_func, filter_value=None):
self.registered_filters[id] = filter_func
def deregister_filter(self, id):
del self.registered_filters[id]
def register_tree_field(self, field, init_func=lambda: {}):
self.tree_fields[field] = init_func
def deregister_tree_field(self, field):
if field in self.tree_fields:
del self.tree_fields[field]
def filter_state_active(self, torrent_ids):
for torrent_id in list(torrent_ids):
status = self.torrents[torrent_id].get_status(["download_payload_rate", "upload_payload_rate"])
if status["download_payload_rate"] or status["upload_payload_rate"]:
pass
else:
torrent_ids.remove(torrent_id)
return torrent_ids
def _hide_state_items(self, state_items):
"for hide(show)-zero hits"
for (value, count) in state_items.items():
if value != "All" and count == 0:
del state_items[value]
def _sort_state_items(self, x, y):
""
if x[0] in STATE_SORT:
ix = STATE_SORT.index(x[0])
else:
ix = 99
if y[0] in STATE_SORT:
iy = STATE_SORT.index(y[0])
else:
iy = 99
return ix - iy
| rkokkelk/Gulliver | deluge/core/filtermanager.py | Python | gpl-3.0 | 9,642 |
/* Set file access and modification times.
Copyright (C) 2003-2021 Free Software Foundation, Inc.
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 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/>. */
/* Written by Paul Eggert. */
/* derived from a function in touch.c */
#include <config.h>
#define _GL_UTIMENS_INLINE _GL_EXTERN_INLINE
#include "utimens.h"
#include <errno.h>
#include <fcntl.h>
#include <stdbool.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <utime.h>
#include "stat-time.h"
#include "timespec.h"
/* On native Windows, use SetFileTime; but avoid this when compiling
GNU Emacs, which arranges for this in some other way and which
defines WIN32_LEAN_AND_MEAN itself. */
#if defined _WIN32 && ! defined __CYGWIN__ && ! defined EMACS_CONFIGURATION
# define USE_SETFILETIME
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# if GNULIB_MSVC_NOTHROW
# include "msvc-nothrow.h"
# else
# include <io.h>
# endif
#endif
/* Avoid recursion with rpl_futimens or rpl_utimensat. */
#undef futimens
#undef utimensat
/* Solaris 9 mistakenly succeeds when given a non-directory with a
trailing slash. Force the use of rpl_stat for a fix. */
#ifndef REPLACE_FUNC_STAT_FILE
# define REPLACE_FUNC_STAT_FILE 0
#endif
#if HAVE_UTIMENSAT || HAVE_FUTIMENS
/* Cache variables for whether the utimensat syscall works; used to
avoid calling the syscall if we know it will just fail with ENOSYS,
and to avoid unnecessary work in massaging timestamps if the
syscall will work. Multiple variables are needed, to distinguish
between the following scenarios on Linux:
utimensat doesn't exist, or is in glibc but kernel 2.6.18 fails with ENOSYS
kernel 2.6.22 and earlier rejects AT_SYMLINK_NOFOLLOW
kernel 2.6.25 and earlier reject UTIME_NOW/UTIME_OMIT with non-zero tv_sec
kernel 2.6.32 used with xfs or ntfs-3g fail to honor UTIME_OMIT
utimensat completely works
For each cache variable: 0 = unknown, 1 = yes, -1 = no. */
static int utimensat_works_really;
static int lutimensat_works_really;
#endif /* HAVE_UTIMENSAT || HAVE_FUTIMENS */
/* Validate the requested timestamps. Return 0 if the resulting
timespec can be used for utimensat (after possibly modifying it to
work around bugs in utimensat). Return a positive value if the
timespec needs further adjustment based on stat results: 1 if any
adjustment is needed for utimes, and 2 if any adjustment is needed
for Linux utimensat. Return -1, with errno set to EINVAL, if
timespec is out of range. */
static int
validate_timespec (struct timespec timespec[2])
{
int result = 0;
int utime_omit_count = 0;
if ((timespec[0].tv_nsec != UTIME_NOW
&& timespec[0].tv_nsec != UTIME_OMIT
&& ! (0 <= timespec[0].tv_nsec
&& timespec[0].tv_nsec < TIMESPEC_HZ))
|| (timespec[1].tv_nsec != UTIME_NOW
&& timespec[1].tv_nsec != UTIME_OMIT
&& ! (0 <= timespec[1].tv_nsec
&& timespec[1].tv_nsec < TIMESPEC_HZ)))
{
errno = EINVAL;
return -1;
}
/* Work around Linux kernel 2.6.25 bug, where utimensat fails with
EINVAL if tv_sec is not 0 when using the flag values of tv_nsec.
Flag a Linux kernel 2.6.32 bug, where an mtime of UTIME_OMIT
fails to bump ctime. */
if (timespec[0].tv_nsec == UTIME_NOW
|| timespec[0].tv_nsec == UTIME_OMIT)
{
timespec[0].tv_sec = 0;
result = 1;
if (timespec[0].tv_nsec == UTIME_OMIT)
utime_omit_count++;
}
if (timespec[1].tv_nsec == UTIME_NOW
|| timespec[1].tv_nsec == UTIME_OMIT)
{
timespec[1].tv_sec = 0;
result = 1;
if (timespec[1].tv_nsec == UTIME_OMIT)
utime_omit_count++;
}
return result + (utime_omit_count == 1);
}
/* Normalize any UTIME_NOW or UTIME_OMIT values in *TS, using stat
buffer STATBUF to obtain the current timestamps of the file. If
both times are UTIME_NOW, set *TS to NULL (as this can avoid some
permissions issues). If both times are UTIME_OMIT, return true
(nothing further beyond the prior collection of STATBUF is
necessary); otherwise return false. */
static bool
update_timespec (struct stat const *statbuf, struct timespec *ts[2])
{
struct timespec *timespec = *ts;
if (timespec[0].tv_nsec == UTIME_OMIT
&& timespec[1].tv_nsec == UTIME_OMIT)
return true;
if (timespec[0].tv_nsec == UTIME_NOW
&& timespec[1].tv_nsec == UTIME_NOW)
{
*ts = NULL;
return false;
}
if (timespec[0].tv_nsec == UTIME_OMIT)
timespec[0] = get_stat_atime (statbuf);
else if (timespec[0].tv_nsec == UTIME_NOW)
gettime (×pec[0]);
if (timespec[1].tv_nsec == UTIME_OMIT)
timespec[1] = get_stat_mtime (statbuf);
else if (timespec[1].tv_nsec == UTIME_NOW)
gettime (×pec[1]);
return false;
}
/* Set the access and modification timestamps of FD (a.k.a. FILE) to be
TIMESPEC[0] and TIMESPEC[1], respectively.
FD must be either negative -- in which case it is ignored --
or a file descriptor that is open on FILE.
If FD is nonnegative, then FILE can be NULL, which means
use just futimes (or equivalent) instead of utimes (or equivalent),
and fail if on an old system without futimes (or equivalent).
If TIMESPEC is null, set the timestamps to the current time.
Return 0 on success, -1 (setting errno) on failure. */
int
fdutimens (int fd, char const *file, struct timespec const timespec[2])
{
struct timespec adjusted_timespec[2];
struct timespec *ts = timespec ? adjusted_timespec : NULL;
int adjustment_needed = 0;
struct stat st;
if (ts)
{
adjusted_timespec[0] = timespec[0];
adjusted_timespec[1] = timespec[1];
adjustment_needed = validate_timespec (ts);
}
if (adjustment_needed < 0)
return -1;
/* Require that at least one of FD or FILE are potentially valid, to avoid
a Linux bug where futimens (AT_FDCWD, NULL) changes "." rather
than failing. */
if (fd < 0 && !file)
{
errno = EBADF;
return -1;
}
/* Some Linux-based NFS clients are buggy, and mishandle timestamps
of files in NFS file systems in some cases. We have no
configure-time test for this, but please see
<https://bugs.gentoo.org/show_bug.cgi?id=132673> for references to
some of the problems with Linux 2.6.16. If this affects you,
compile with -DHAVE_BUGGY_NFS_TIME_STAMPS; this is reported to
help in some cases, albeit at a cost in performance. But you
really should upgrade your kernel to a fixed version, since the
problem affects many applications. */
#if HAVE_BUGGY_NFS_TIME_STAMPS
if (fd < 0)
sync ();
else
fsync (fd);
#endif
/* POSIX 2008 added two interfaces to set file timestamps with
nanosecond resolution; newer Linux implements both functions via
a single syscall. We provide a fallback for ENOSYS (for example,
compiling against Linux 2.6.25 kernel headers and glibc 2.7, but
running on Linux 2.6.18 kernel). */
#if HAVE_UTIMENSAT || HAVE_FUTIMENS
if (0 <= utimensat_works_really)
{
int result;
# if __linux__ || __sun
/* As recently as Linux kernel 2.6.32 (Dec 2009), several file
systems (xfs, ntfs-3g) have bugs with a single UTIME_OMIT,
but work if both times are either explicitly specified or
UTIME_NOW. Work around it with a preparatory [f]stat prior
to calling futimens/utimensat; fortunately, there is not much
timing impact due to the extra syscall even on file systems
where UTIME_OMIT would have worked.
The same bug occurs in Solaris 11.1 (Apr 2013).
FIXME: Simplify this for Linux in 2016 and for Solaris in
2024, when file system bugs are no longer common. */
if (adjustment_needed == 2)
{
if (fd < 0 ? stat (file, &st) : fstat (fd, &st))
return -1;
if (ts[0].tv_nsec == UTIME_OMIT)
ts[0] = get_stat_atime (&st);
else if (ts[1].tv_nsec == UTIME_OMIT)
ts[1] = get_stat_mtime (&st);
/* Note that st is good, in case utimensat gives ENOSYS. */
adjustment_needed++;
}
# endif
# if HAVE_UTIMENSAT
if (fd < 0)
{
result = utimensat (AT_FDCWD, file, ts, 0);
# ifdef __linux__
/* Work around a kernel bug:
https://bugzilla.redhat.com/show_bug.cgi?id=442352
https://bugzilla.redhat.com/show_bug.cgi?id=449910
It appears that utimensat can mistakenly return 280 rather
than -1 upon ENOSYS failure.
FIXME: remove in 2010 or whenever the offending kernels
are no longer in common use. */
if (0 < result)
errno = ENOSYS;
# endif /* __linux__ */
if (result == 0 || errno != ENOSYS)
{
utimensat_works_really = 1;
return result;
}
}
# endif /* HAVE_UTIMENSAT */
# if HAVE_FUTIMENS
if (0 <= fd)
{
result = futimens (fd, ts);
# ifdef __linux__
/* Work around the same bug as above. */
if (0 < result)
errno = ENOSYS;
# endif /* __linux__ */
if (result == 0 || errno != ENOSYS)
{
utimensat_works_really = 1;
return result;
}
}
# endif /* HAVE_FUTIMENS */
}
utimensat_works_really = -1;
lutimensat_works_really = -1;
#endif /* HAVE_UTIMENSAT || HAVE_FUTIMENS */
#ifdef USE_SETFILETIME
/* On native Windows, use SetFileTime(). See
<https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-setfiletime>
<https://docs.microsoft.com/en-us/windows/desktop/api/minwinbase/ns-minwinbase-filetime> */
if (0 <= fd)
{
HANDLE handle;
FILETIME current_time;
FILETIME last_access_time;
FILETIME last_write_time;
handle = (HANDLE) _get_osfhandle (fd);
if (handle == INVALID_HANDLE_VALUE)
{
errno = EBADF;
return -1;
}
if (ts == NULL || ts[0].tv_nsec == UTIME_NOW || ts[1].tv_nsec == UTIME_NOW)
{
/* GetSystemTimeAsFileTime
<https://docs.microsoft.com/en-us/windows/desktop/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime>.
It would be overkill to use
GetSystemTimePreciseAsFileTime
<https://docs.microsoft.com/en-us/windows/desktop/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime>. */
GetSystemTimeAsFileTime (¤t_time);
}
if (ts == NULL || ts[0].tv_nsec == UTIME_NOW)
{
last_access_time = current_time;
}
else if (ts[0].tv_nsec == UTIME_OMIT)
{
last_access_time.dwLowDateTime = 0;
last_access_time.dwHighDateTime = 0;
}
else
{
ULONGLONG time_since_16010101 =
(ULONGLONG) ts[0].tv_sec * 10000000 + ts[0].tv_nsec / 100 + 116444736000000000LL;
last_access_time.dwLowDateTime = (DWORD) time_since_16010101;
last_access_time.dwHighDateTime = time_since_16010101 >> 32;
}
if (ts == NULL || ts[1].tv_nsec == UTIME_NOW)
{
last_write_time = current_time;
}
else if (ts[1].tv_nsec == UTIME_OMIT)
{
last_write_time.dwLowDateTime = 0;
last_write_time.dwHighDateTime = 0;
}
else
{
ULONGLONG time_since_16010101 =
(ULONGLONG) ts[1].tv_sec * 10000000 + ts[1].tv_nsec / 100 + 116444736000000000LL;
last_write_time.dwLowDateTime = (DWORD) time_since_16010101;
last_write_time.dwHighDateTime = time_since_16010101 >> 32;
}
if (SetFileTime (handle, NULL, &last_access_time, &last_write_time))
return 0;
else
{
DWORD sft_error = GetLastError ();
#if 0
fprintf (stderr, "fdutimens SetFileTime error 0x%x\n", (unsigned int) sft_error);
#endif
switch (sft_error)
{
case ERROR_ACCESS_DENIED: /* fd was opened without O_RDWR */
errno = EACCES; /* not specified by POSIX */
break;
default:
errno = EINVAL;
break;
}
return -1;
}
}
#endif
/* The platform lacks an interface to set file timestamps with
nanosecond resolution, so do the best we can, discarding any
fractional part of the timestamp. */
if (adjustment_needed || (REPLACE_FUNC_STAT_FILE && fd < 0))
{
if (adjustment_needed != 3
&& (fd < 0 ? stat (file, &st) : fstat (fd, &st)))
return -1;
if (ts && update_timespec (&st, &ts))
return 0;
}
{
#if HAVE_FUTIMESAT || HAVE_WORKING_UTIMES
struct timeval timeval[2];
struct timeval *t;
if (ts)
{
timeval[0].tv_sec = ts[0].tv_sec;
timeval[0].tv_usec = ts[0].tv_nsec / 1000;
timeval[1].tv_sec = ts[1].tv_sec;
timeval[1].tv_usec = ts[1].tv_nsec / 1000;
t = timeval;
}
else
t = NULL;
if (fd < 0)
{
# if HAVE_FUTIMESAT
return futimesat (AT_FDCWD, file, t);
# endif
}
else
{
/* If futimesat or futimes fails here, don't try to speed things
up by returning right away. glibc can incorrectly fail with
errno == ENOENT if /proc isn't mounted. Also, Mandrake 10.0
in high security mode doesn't allow ordinary users to read
/proc/self, so glibc incorrectly fails with errno == EACCES.
If errno == EIO, EPERM, or EROFS, it's probably safe to fail
right away, but these cases are rare enough that they're not
worth optimizing, and who knows what other messed-up systems
are out there? So play it safe and fall back on the code
below. */
# if (HAVE_FUTIMESAT && !FUTIMESAT_NULL_BUG) || HAVE_FUTIMES
# if HAVE_FUTIMESAT && !FUTIMESAT_NULL_BUG
# undef futimes
# define futimes(fd, t) futimesat (fd, NULL, t)
# endif
if (futimes (fd, t) == 0)
{
# if __linux__ && __GLIBC__
/* Work around a longstanding glibc bug, still present as
of 2010-12-27. On older Linux kernels that lack both
utimensat and utimes, glibc's futimes rounds instead of
truncating when falling back on utime. The same bug
occurs in futimesat with a null 2nd arg. */
if (t)
{
bool abig = 500000 <= t[0].tv_usec;
bool mbig = 500000 <= t[1].tv_usec;
if ((abig | mbig) && fstat (fd, &st) == 0)
{
/* If these two subtractions overflow, they'll
track the overflows inside the buggy glibc. */
time_t adiff = st.st_atime - t[0].tv_sec;
time_t mdiff = st.st_mtime - t[1].tv_sec;
struct timeval *tt = NULL;
struct timeval truncated_timeval[2];
truncated_timeval[0] = t[0];
truncated_timeval[1] = t[1];
if (abig && adiff == 1 && get_stat_atime_ns (&st) == 0)
{
tt = truncated_timeval;
tt[0].tv_usec = 0;
}
if (mbig && mdiff == 1 && get_stat_mtime_ns (&st) == 0)
{
tt = truncated_timeval;
tt[1].tv_usec = 0;
}
if (tt)
futimes (fd, tt);
}
}
# endif
return 0;
}
# endif
}
#endif /* HAVE_FUTIMESAT || HAVE_WORKING_UTIMES */
if (!file)
{
#if ! ((HAVE_FUTIMESAT && !FUTIMESAT_NULL_BUG) \
|| (HAVE_WORKING_UTIMES && HAVE_FUTIMES))
errno = ENOSYS;
#endif
return -1;
}
#ifdef USE_SETFILETIME
return _gl_utimens_windows (file, ts);
#elif HAVE_WORKING_UTIMES
return utimes (file, t);
#else
{
struct utimbuf utimbuf;
struct utimbuf *ut;
if (ts)
{
utimbuf.actime = ts[0].tv_sec;
utimbuf.modtime = ts[1].tv_sec;
ut = &utimbuf;
}
else
ut = NULL;
return utime (file, ut);
}
#endif /* !HAVE_WORKING_UTIMES */
}
}
/* Set the access and modification timestamps of FILE to be
TIMESPEC[0] and TIMESPEC[1], respectively. */
int
utimens (char const *file, struct timespec const timespec[2])
{
return fdutimens (-1, file, timespec);
}
/* Set the access and modification timestamps of FILE to be
TIMESPEC[0] and TIMESPEC[1], respectively, without dereferencing
symlinks. Fail with ENOSYS if the platform does not support
changing symlink timestamps, but FILE was a symlink. */
int
lutimens (char const *file, struct timespec const timespec[2])
{
struct timespec adjusted_timespec[2];
struct timespec *ts = timespec ? adjusted_timespec : NULL;
int adjustment_needed = 0;
struct stat st;
if (ts)
{
adjusted_timespec[0] = timespec[0];
adjusted_timespec[1] = timespec[1];
adjustment_needed = validate_timespec (ts);
}
if (adjustment_needed < 0)
return -1;
/* The Linux kernel did not support symlink timestamps until
utimensat, in version 2.6.22, so we don't need to mimic
fdutimens' worry about buggy NFS clients. But we do have to
worry about bogus return values. */
#if HAVE_UTIMENSAT
if (0 <= lutimensat_works_really)
{
int result;
# if __linux__ || __sun
/* As recently as Linux kernel 2.6.32 (Dec 2009), several file
systems (xfs, ntfs-3g) have bugs with a single UTIME_OMIT,
but work if both times are either explicitly specified or
UTIME_NOW. Work around it with a preparatory lstat prior to
calling utimensat; fortunately, there is not much timing
impact due to the extra syscall even on file systems where
UTIME_OMIT would have worked.
The same bug occurs in Solaris 11.1 (Apr 2013).
FIXME: Simplify this for Linux in 2016 and for Solaris in
2024, when file system bugs are no longer common. */
if (adjustment_needed == 2)
{
if (lstat (file, &st))
return -1;
if (ts[0].tv_nsec == UTIME_OMIT)
ts[0] = get_stat_atime (&st);
else if (ts[1].tv_nsec == UTIME_OMIT)
ts[1] = get_stat_mtime (&st);
/* Note that st is good, in case utimensat gives ENOSYS. */
adjustment_needed++;
}
# endif
result = utimensat (AT_FDCWD, file, ts, AT_SYMLINK_NOFOLLOW);
# ifdef __linux__
/* Work around a kernel bug:
https://bugzilla.redhat.com/show_bug.cgi?id=442352
https://bugzilla.redhat.com/show_bug.cgi?id=449910
It appears that utimensat can mistakenly return 280 rather
than -1 upon ENOSYS failure.
FIXME: remove in 2010 or whenever the offending kernels
are no longer in common use. */
if (0 < result)
errno = ENOSYS;
# endif
if (result == 0 || errno != ENOSYS)
{
utimensat_works_really = 1;
lutimensat_works_really = 1;
return result;
}
}
lutimensat_works_really = -1;
#endif /* HAVE_UTIMENSAT */
/* The platform lacks an interface to set file timestamps with
nanosecond resolution, so do the best we can, discarding any
fractional part of the timestamp. */
if (adjustment_needed || REPLACE_FUNC_STAT_FILE)
{
if (adjustment_needed != 3 && lstat (file, &st))
return -1;
if (ts && update_timespec (&st, &ts))
return 0;
}
/* On Linux, lutimes is a thin wrapper around utimensat, so there is
no point trying lutimes if utimensat failed with ENOSYS. */
#if HAVE_LUTIMES && !HAVE_UTIMENSAT
{
struct timeval timeval[2];
struct timeval *t;
int result;
if (ts)
{
timeval[0].tv_sec = ts[0].tv_sec;
timeval[0].tv_usec = ts[0].tv_nsec / 1000;
timeval[1].tv_sec = ts[1].tv_sec;
timeval[1].tv_usec = ts[1].tv_nsec / 1000;
t = timeval;
}
else
t = NULL;
result = lutimes (file, t);
if (result == 0 || errno != ENOSYS)
return result;
}
#endif /* HAVE_LUTIMES && !HAVE_UTIMENSAT */
/* Out of luck for symlinks, but we still handle regular files. */
if (!(adjustment_needed || REPLACE_FUNC_STAT_FILE) && lstat (file, &st))
return -1;
if (!S_ISLNK (st.st_mode))
return fdutimens (-1, file, ts);
errno = ENOSYS;
return -1;
}
| nanasess/emacs | lib/utimens.c | C | gpl-3.0 | 21,338 |
/*
This project 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.
Deviation 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 Deviation. If not, see <http://www.gnu.org/licenses/>.
*/
#include "common.h"
#include "pages.h"
#include "gui/gui.h"
#include "config/model.h"
#include "config/ini.h"
#include <stdlib.h>
#include "../common/_model_loadsave.c"
static u8 list_selected = 0;
static void icon_notify_cb(guiObject_t *obj)
{
int idx = GUI_ScrollableGetObjRowOffset(&gui->scrollable, obj);
if (idx < 0)
return;
int absrow = (idx >> 8) + (idx & 0xff);
list_selected = absrow;
change_icon(absrow);
}
static void ok_cb(guiObject_t *obj, const void *data)
{
(void)obj;
(void)data;
press_cb(NULL, -1, (void *)(long)list_selected);
}
static void press1_cb(guiObject_t *obj, s8 press_type, const void *data)
{
list_selected = (long)data;
if (HAS_TOUCH && OBJ_IS_USED(&gui->image)) {
//differentiate between touch and button
static int is_touch = 0;
if (press_type >= 0) {
u32 buttons = ScanButtons();
is_touch = 0;
if(! CHAN_ButtonIsPressed(buttons, BUT_ENTER)) {
is_touch = 1;
}
return;
}
if (press_type == -1 && is_touch) {
is_touch = -1;
icon_notify_cb(obj);
return;
}
}
press_cb(obj, press_type, data);
}
static int row_cb(int absrow, int relrow, int y, void *data)
{
(void)data;
if (absrow >= mp->total_items) {
GUI_CreateLabelBox(&gui->label[relrow], 8 + ((LCD_WIDTH - 320) / 2), y,
200 - ARROW_WIDTH, 24, &LISTBOX_FONT, NULL, NULL, "");
} else {
GUI_CreateLabelBox(&gui->label[relrow], 8 + ((LCD_WIDTH - 320) / 2), y,
200 - ARROW_WIDTH, 24, &LISTBOX_FONT, name_cb, press1_cb, (void *)(long)absrow);
}
return 0;
}
void PAGE_LoadSaveInit(int page)
{
int num_models;
int selected;
const char * name = NULL;
enum loadSaveType menu_type = page;
memset(mp, 0, sizeof(struct model_page)); // Bug fix: must initialize this
mp->menu_type = page;
mp->modeltype = Model.type;
OBJ_SET_USED(&gui->image, 0);
selected = get_scroll_count(page);
switch(menu_type) {
case LOAD_MODEL: name = _tr_noop("Load Model"); break;
case SAVE_MODEL: name = _tr_noop("Save Model as..."); break;
case LOAD_TEMPLATE: name = _tr_noop("Load Model Template"); break;
case LOAD_ICON: name = _tr_noop("Select Icon"); break;
case LOAD_LAYOUT: name = _tr_noop("Load Layout"); break;
}
//PAGE_ShowHeader(name);
num_models = mp->total_items;
if (num_models < LISTBOX_ITEMS)
num_models = LISTBOX_ITEMS;
if (page != LOAD_TEMPLATE && page != LOAD_LAYOUT) {
PAGE_ShowHeaderWithSize(name, LCD_WIDTH - 88, 0);
u16 w = 0, h = 0;
char *img = mp->iconstr;
if(! fexists(img))
img = UNKNOWN_ICON;
LCD_ImageDimensions(img, &w, &h);
GUI_CreateImage(&gui->image, 212 + ((LCD_WIDTH - 320) / 2), 88, w, h, mp->iconstr);
PAGE_CreateOkButton(LCD_WIDTH - 48, 4, ok_cb);
GUI_SelectionNotify(icon_notify_cb);
}
else
PAGE_ShowHeader(name);
GUI_CreateScrollable(&gui->scrollable, 8 + ((LCD_WIDTH - 320) / 2), 40, 200, LISTBOX_ITEMS * 24,
24, num_models, row_cb, NULL, NULL, NULL);
GUI_SetSelected(GUI_ShowScrollableRowCol(&gui->scrollable, selected, 0));
list_selected = selected;
}
| TheRealMoeder/deviation | src/pages/320x240x16/model_loadsave.c | C | gpl-3.0 | 4,003 |
#
# BioPerl module for Bio::Seq::RichSeqI
#
# Please direct questions and support issues to <bioperl-l@bioperl.org>
#
# Cared for by Ewan Birney <birney@ebi.ac.uk>
#
# Copyright Ewan Birney
#
# You may distribute this module under the same terms as perl itself
# POD documentation - main docs before the code
=head1 NAME
Bio::Seq::RichSeqI - interface for sequences from rich data sources, mostly databases
=head1 SYNOPSIS
@secondary = $richseq->get_secondary_accessions;
$division = $richseq->division;
$mol = $richseq->molecule;
@dates = $richseq->get_dates;
$seq_version = $richseq->seq_version;
$pid = $richseq->pid;
@keywords = $richseq->get_keywords;
=head1 DESCRIPTION
This interface extends the L<Bio::SeqI> interface to give additional
functionality to sequences with richer data sources, in particular from database
sequences (EMBL, GenBank and Swissprot). For a general implementation, please
see the documentation for L<Bio::Seq::RichSeq>.
=head1 FEEDBACK
=head2 Mailing Lists
User feedback is an integral part of the evolution of this
and other Bioperl modules. Send your comments and suggestions preferably
to one of the Bioperl mailing lists.
Your participation is much appreciated.
bioperl-l@bioperl.org - General discussion
http://bioperl.org/wiki/Mailing_lists - About the mailing lists
=head2 Support
Please direct usage questions or support issues to the mailing list:
I<bioperl-l@bioperl.org>
rather than to the module maintainer directly. Many experienced and
reponsive experts will be able look at the problem and quickly
address it. Please include a thorough description of the problem
with code and data examples if at all possible.
=head2 Reporting Bugs
Report bugs to the Bioperl bug tracking system to help us keep track
the bugs and their resolution. Bug reports can be submitted via the
web:
https://github.com/bioperl/bioperl-live/issues
=head1 AUTHOR - Ewan Birney
Email birney@ebi.ac.uk
=head1 APPENDIX
The rest of the documentation details each of the object methods. Internal
methods are usually preceded with a _
=cut
# Let the code begin...
package Bio::Seq::RichSeqI;
use strict;
use base qw(Bio::SeqI);
=head2 get_secondary_accessions
Title : get_secondary_accessions
Usage :
Function: Get the secondary accessions for a sequence.
An implementation that allows modification of this array
property should provide the methods add_secondary_accession
and remove_secondary_accessions, with obvious purpose.
Example :
Returns : an array of strings
Args : none
=cut
sub get_secondary_accessions{
my ($self,@args) = @_;
$self->throw("hit get_secondary_accessions in interface definition - error");
}
=head2 division
Title : division
Usage :
Function: Get (and set, depending on the implementation) the divison for
a sequence.
Examples from GenBank are PLN (plants), PRI (primates), etc.
Example :
Returns : a string
Args :
=cut
sub division{
my ($self,@args) = @_;
$self->throw("hit division in interface definition - error");
}
=head2 molecule
Title : molecule
Usage :
Function: Get (and set, depending on the implementation) the molecule
type for the sequence.
This is not necessarily the same as Bio::PrimarySeqI::alphabet(),
because it is databank-specific.
Example :
Returns : a string
Args :
=cut
sub molecule{
my ($self,@args) = @_;
$self->throw("hit molecule in interface definition - error");
}
=head2 pid
Title : pid
Usage :
Function: Get (and set, depending on the implementation) the PID property
for the sequence.
Example :
Returns : a string
Args :
=cut
sub pid {
my ($self,@args) = @_;
$self->throw("hit pid in interface definition - error");
}
=head2 get_dates
Title : get_dates
Usage :
Function: Get (and set, depending on the implementation) the dates the
databank entry specified for the sequence
An implementation that allows modification of this array
property should provide the methods add_date and
remove_dates, with obvious purpose.
Example :
Returns : an array of strings
Args :
=cut
sub get_dates{
my ($self,@args) = @_;
$self->throw("hit get_dates in interface definition - error");
}
=head2 seq_version
Title : seq_version
Usage :
Function: Get (and set, depending on the implementation) the version string
of the sequence.
Example :
Returns : a string
Args :
Note : this differs from Bio::PrimarySeq version() in that this explicitly
refers to the sequence record version one would find in a typical
sequence file. It is up to the implementation whether this is set
separately or falls back to the more generic Bio::Seq::version()
=cut
sub seq_version{
my ($self,@args) = @_;
$self->throw("hit seq_version in interface definition - error");
}
=head2 get_keywords
Title : get_keywords
Usage : $obj->get_keywords()
Function: Get the keywords for this sequence object.
An implementation that allows modification of this array
property should provide the methods add_keyword and
remove_keywords, with obvious purpose.
Returns : an array of strings
Args :
=cut
sub get_keywords {
my ($self) = @_;
$self->throw("hit keywords in interface definition - error");
}
1;
| pcantalupo/bioperl-live | Bio/Seq/RichSeqI.pm | Perl | gpl-3.0 | 5,554 |
/*
* This file is part of Cleanflight.
*
* Cleanflight 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.
*
* Cleanflight 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 Cleanflight. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#define TARGET_BOARD_IDENTIFIER "ANY7"
#define USBD_PRODUCT_STRING "AnyFCF7"
#define LED0_PIN PB7
#define LED1_PIN PB6
#define BEEPER PB2 // Unused pin, can be mapped to elsewhere
#define BEEPER_INVERTED
#define MPU6000_CS_PIN PA4
#define MPU6000_SPI_INSTANCE SPI1
#define USE_ACC
#define USE_ACC_SPI_MPU6000
#define ACC_MPU6000_ALIGN CW270_DEG
#define USE_GYRO
#define USE_GYRO_SPI_MPU6000
#define GYRO_MPU6000_ALIGN CW270_DEG
// MPU6000 interrupts
#define USE_MPU_DATA_READY_SIGNAL
#define MPU_INT_EXTI PC4
#define USE_EXTI
#define USE_MAG
#define USE_MAG_HMC5883
#define MAG_I2C_INSTANCE (I2CDEV_2)
//#define MAG_HMC5883_ALIGN CW270_DEG_FLIP
//#define MAG_HMC5883_ALIGN CW90_DEG
#define USE_BARO
#define USE_BARO_MS5611
#define USE_BARO_BMP280
#define BARO_I2C_INSTANCE (I2CDEV_2)
#define USABLE_TIMER_CHANNEL_COUNT 16
#define USE_VCP
#define VBUS_SENSING_PIN PA8
#define USE_UART1
#define UART1_RX_PIN PA10
#define UART1_TX_PIN PA9
#define USE_UART2
#define UART2_RX_PIN PD6
#define UART2_TX_PIN PD5
#define USE_UART3
#define UART3_RX_PIN PD9
#define UART3_TX_PIN PD8
#define USE_UART4
#define UART4_RX_PIN PC11
#define UART4_TX_PIN PC10
#define USE_UART5
#define UART5_RX_PIN PD2
#define UART5_TX_PIN PC12
#define USE_UART6
#define UART6_RX_PIN PC7
#define UART6_TX_PIN PC6
#define USE_UART7
#define UART7_RX_PIN PE7
#define UART7_TX_PIN PE8
#define USE_UART8
#define UART8_RX_PIN PE0
#define UART8_TX_PIN PE1
#define USE_SOFTSERIAL1
#define USE_SOFTSERIAL2
#define SERIAL_PORT_COUNT 11 //VCP, USART1, USART2, USART3, UART4, UART5, USART6, USART7, USART8, SOFTSERIAL x 2
#define USE_ESCSERIAL
#define ESCSERIAL_TIMER_TX_PIN PB14 // (Hardware=0, PPM)
#define USE_SPI
#define USE_SPI_DEVICE_1
#define USE_SPI_DEVICE_3
#define USE_SPI_DEVICE_4
#define SPI1_NSS_PIN PA4
#define SPI1_SCK_PIN PA5
#define SPI1_MISO_PIN PA6
#define SPI1_MOSI_PIN PA7
#define SPI3_NSS_PIN PD2
#define SPI3_SCK_PIN PC10
#define SPI3_MISO_PIN PC11
#define SPI3_MOSI_PIN PC12
#define SPI4_NSS_PIN PE11
#define SPI4_SCK_PIN PE12
#define SPI4_MISO_PIN PE13
#define SPI4_MOSI_PIN PE14
#define USE_MAX7456
#define MAX7456_SPI_INSTANCE SPI3
#define MAX7456_SPI_CS_PIN SPI3_NSS_PIN
#define MAX7456_SPI_CLK (SPI_CLOCK_STANDARD) // 10MHz
#define MAX7456_RESTORE_CLK (SPI_CLOCK_FAST)
#define USE_SDCARD
#define SDCARD_DETECT_INVERTED
#define SDCARD_DETECT_PIN PD3
#define SDCARD_SPI_INSTANCE SPI4
#define SDCARD_SPI_CS_PIN SPI4_NSS_PIN
#define SDCARD_SPI_INITIALIZATION_CLOCK_DIVIDER 256 // 422kHz
// Divide to under 25MHz for normal operation:
#define SDCARD_SPI_FULL_SPEED_CLOCK_DIVIDER 8 // 27MHz
#define SDCARD_DMA_STREAM_TX_FULL DMA2_Stream1
#define SDCARD_DMA_CHANNEL 4
#define USE_I2C
#define USE_I2C_DEVICE_2 // External I2C
#define USE_I2C_DEVICE_4 // Onboard I2C
#define I2C_DEVICE (I2CDEV_2)
#define USE_ADC
#define VBAT_ADC_PIN PC0
#define CURRENT_METER_ADC_PIN PC1
#define RSSI_ADC_GPIO_PIN PC2
#define ENABLE_BLACKBOX_LOGGING_ON_SDCARD_BY_DEFAULT
#define DEFAULT_RX_FEATURE FEATURE_RX_SERIAL
#define SERIALRX_PROVIDER SERIALRX_SBUS
#define USE_SERIAL_4WAY_BLHELI_INTERFACE
#define TARGET_IO_PORTA 0xffff
#define TARGET_IO_PORTB 0xffff
#define TARGET_IO_PORTC 0xffff
#define TARGET_IO_PORTD 0xffff
#define TARGET_IO_PORTE 0xffff
#define USED_TIMERS ( TIM_N(2) | TIM_N(3) | TIM_N(4) | TIM_N(5) | TIM_N(12) | TIM_N(8) | TIM_N(9) | TIM_N(10) | TIM_N(11))
| jirif/betaflight | src/main/target/ANYFCF7/target.h | C | gpl-3.0 | 4,399 |
// David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2017
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 3.0.2 (2016/11/14)
#include <GTEnginePCH.h>
#include <Applications/GLX/GteWindow.h>
#include <X11/Xlib.h>
namespace gte
{
Window::Parameters::Parameters()
:
display(nullptr),
window(0),
deviceCreationFlags(0)
{
}
Window::Parameters::Parameters(std::wstring const& inTitle,
int inXOrigin, int inYOrigin, int inXSize, int inYSize)
:
WindowBase::Parameters(inTitle, inXOrigin, inYOrigin, inXSize, inYSize),
display(nullptr),
window(0),
deviceCreationFlags(0)
{
}
Window::~Window()
{
}
Window::Window(Parameters& parameters)
:
WindowBase(parameters),
mDisplay(parameters.display),
mWindow(parameters.window),
mButtonDown{false, false, false, false, false, false, false, false},
mShiftDown(false),
mControlDown(false),
mAltDown(false),
mCommandDown(false),
mEngine(std::static_pointer_cast<GraphicsEngine>(mBaseEngine))
{
}
void Window::ShowWindow()
{
XMapWindow(mDisplay, mWindow);
}
void Window::SetMousePosition(int x, int y)
{
XWarpPointer(mDisplay, 0, mWindow, 0, 0, 0, 0, x, y);
XFlush(mDisplay);
}
void Window::GetMousePosition(int& x, int& y) const
{
XID rootWindow, childWindow;
int rootX, rootY;
unsigned int modifier;
XQueryPointer(mDisplay, mWindow, &rootWindow, &childWindow,
&rootX, &rootY, &x, &y, &modifier);
}
void Window::OnClose()
{
XDestroyWindow(mDisplay, mWindow);
}
int Window::ProcessedEvent()
{
if (!XPending(mDisplay))
{
return EVT_NONE_PENDING;
}
XEvent evt;
XNextEvent(mDisplay, &evt);
int index;
bool state;
if (evt.type == ButtonPress || evt.type == ButtonRelease)
{
OnMouseClick(evt.xbutton.button, evt.xbutton.type,
evt.xbutton.x, evt.xbutton.y, evt.xbutton.state);
mButtonDown[evt.xbutton.button] = (evt.type == ButtonPress);
return EVT_PROCESSED;
}
if (evt.type == MotionNotify)
{
int button = MOUSE_NONE;
for (int i = MOUSE_LEFT; i <= MOUSE_RIGHT; ++i)
{
if (mButtonDown[i])
{
button = i;
break;
}
}
OnMouseMotion(button, evt.xmotion.x, evt.xmotion.y, evt.xmotion.state);
return EVT_PROCESSED;
}
if (evt.type == KeyPress || evt.type == KeyRelease)
{
int keysyms_per_keycode_return;
KeySym* pKeySym = XGetKeyboardMapping(mDisplay,
evt.xkey.keycode, 1, &keysyms_per_keycode_return);
KeySym& keySym = *pKeySym;
int key = (keySym & 0x00FF);
// Quit application if the KEY_ESCAPE key is pressed.
if (key == KEY_ESCAPE)
{
XFree(pKeySym);
return EVT_QUIT;
}
// Adjust for special keys from the key pad or the number pad.
if ((keySym & 0xFF00) != 0)
{
if (0x50 <= key && key <= 0x57)
{
// keypad Home, {L,U,R,D}Arrow, Pg{Up,Dn}, End
key += 0x45;
}
else if (key == 0x63)
{
// keypad Insert
key = 0x9e;
}
else if (key == 0xFF)
{
// keypad Delete
key = 0x9f;
}
else if (key == 0xE1 || key == 0xE2)
{
// L-shift or R-shift
key = KEY_SHIFT;
mShiftDown = (evt.type == KeyPress);
}
else if (key == 0xE3 || key == 0xE4)
{
// L-ctrl or R-ctrl
key = KEY_CONTROL;
mControlDown = (evt.type == KeyPress);
}
else if (key == 0xE9 || key == 0xEA)
{
// L-alt or R-alt
key = KEY_ALT;
mAltDown = (evt.type == KeyPress);
}
else if (key == 0xEB || key == 0xEC)
{
key = KEY_COMMAND;
mCommandDown = (evt.type == KeyPress);
}
}
if ((KEY_HOME <= key && key <= KEY_END)
|| (KEY_F1 <= key && key <= KEY_F12)
|| (KEY_SHIFT <= key && key <= KEY_COMMAND))
{
if (evt.type == KeyPress)
{
OnKeyDown(key, evt.xbutton.x, evt.xbutton.y);
}
else
{
OnKeyUp(key, evt.xbutton.x, evt.xbutton.y);
}
}
else
{
if (evt.type == KeyPress)
{
// Get key-modifier state. Adjust for shift state.
unsigned char ucKey = static_cast<unsigned char>(key);
if (mShiftDown && 'a' <= ucKey && ucKey <= 'z')
{
ucKey = static_cast<unsigned char>(key - 32);
}
OnCharPress(ucKey, evt.xbutton.x, evt.xbutton.y);
}
}
XFree(pKeySym);
return EVT_PROCESSED;
}
if (evt.type == Expose)
{
OnDisplay();
return EVT_PROCESSED;
}
if (evt.type == ConfigureNotify)
{
OnMove(evt.xconfigure.x, evt.xconfigure.y);
OnResize(evt.xconfigure.width, evt.xconfigure.height);
return EVT_PROCESSED;
}
if (evt.type == ClientMessage)
{
Atom* wmDelete = nullptr;
int count;
if (XGetWMProtocols(mDisplay, mWindow, &wmDelete, &count))
{
if (evt.xclient.data.l[0] == *wmDelete)
{
return EVT_QUIT;
}
}
}
return EVT_NONE_PENDING;
}
int const WindowBase::KEY_ESCAPE = 0x1B;
int const WindowBase::KEY_HOME = 0x95;
int const WindowBase::KEY_LEFT = 0x96;
int const WindowBase::KEY_UP = 0x97;
int const WindowBase::KEY_RIGHT = 0x98;
int const WindowBase::KEY_DOWN = 0x99;
int const WindowBase::KEY_PAGE_UP = 0x9A;
int const WindowBase::KEY_PAGE_DOWN = 0x9B;
int const WindowBase::KEY_END = 0x9C;
int const WindowBase::KEY_INSERT = 0x9E;
int const WindowBase::KEY_DELETE = 0x9F;
int const WindowBase::KEY_F1 = 0xBE;
int const WindowBase::KEY_F2 = 0xBF;
int const WindowBase::KEY_F3 = 0xC0;
int const WindowBase::KEY_F4 = 0xC1;
int const WindowBase::KEY_F5 = 0xC2;
int const WindowBase::KEY_F6 = 0xC3;
int const WindowBase::KEY_F7 = 0xC4;
int const WindowBase::KEY_F8 = 0xC5;
int const WindowBase::KEY_F9 = 0xC6;
int const WindowBase::KEY_F10 = 0xC7;
int const WindowBase::KEY_F11 = 0xC8;
int const WindowBase::KEY_F12 = 0xC9;
int const WindowBase::KEY_BACKSPACE = 0x08;
int const WindowBase::KEY_TAB = 0x09;
int const WindowBase::KEY_ENTER = 0x0D;
int const WindowBase::KEY_RETURN = 0x0D;
int const WindowBase::KEY_SHIFT = 0xE1; // L-shift
int const WindowBase::KEY_CONTROL = 0xE3; // L-ctrl
int const WindowBase::KEY_ALT = 0xE9; // L-alt
int const WindowBase::KEY_COMMAND = 0xEB; // L-command
int const WindowBase::MOUSE_NONE = 0x0000;
int const WindowBase::MOUSE_LEFT = 0x0001;
int const WindowBase::MOUSE_MIDDLE = 0x0002;
int const WindowBase::MOUSE_RIGHT = 0x0003;
int const WindowBase::MOUSE_DOWN = 0x0004;
int const WindowBase::MOUSE_UP = 0x0005;
int const WindowBase::MODIFIER_CONTROL = 0x0004;
int const WindowBase::MODIFIER_LBUTTON = 0x0001;
int const WindowBase::MODIFIER_MBUTTON = 0x0002;
int const WindowBase::MODIFIER_RBUTTON = 0x0003;
int const WindowBase::MODIFIER_SHIFT = 0x0001;
}
| yijiangh/FrameFab | ext/GTEngine/Source/Applications/GLX/GteWindow.cpp | C++ | gpl-3.0 | 7,631 |
#!/usr/bin/env python
# encoding: utf-8
"""A ${VISUAL} placeholder that will use the text that was last visually
selected and insert it here. If there was no text visually selected, this will
be the empty string. """
import re
import textwrap
from UltiSnips import _vim
from UltiSnips.indent_util import IndentUtil
from UltiSnips.text_objects._transformation import TextObjectTransformation
from UltiSnips.text_objects._base import NoneditableTextObject
_REPLACE_NON_WS = re.compile(r"[^ \t]")
class Visual(NoneditableTextObject, TextObjectTransformation):
"""See module docstring."""
def __init__(self, parent, token):
# Find our containing snippet for visual_content
snippet = parent
while snippet:
try:
self._text = snippet.visual_content.text
self._mode = snippet.visual_content.mode
break
except AttributeError:
snippet = snippet._parent # pylint:disable=protected-access
if not self._text:
self._text = token.alternative_text
self._mode = "v"
NoneditableTextObject.__init__(self, parent, token)
TextObjectTransformation.__init__(self, token)
def _update(self, done):
if self._mode == "v": # Normal selection.
text = self._text
else: # Block selection or line selection.
text_before = _vim.buf[self.start.line][:self.start.col]
indent = _REPLACE_NON_WS.sub(" ", text_before)
iu = IndentUtil()
indent = iu.indent_to_spaces(indent)
indent = iu.spaces_to_indent(indent)
text = ""
for idx, line in enumerate(textwrap.dedent(
self._text).splitlines(True)):
if idx != 0:
text += indent
text += line
text = text[:-1] # Strip final '\n'
text = self._transform(text)
self.overwrite(text)
self._parent._del_child(self) # pylint:disable=protected-access
return True
| eduardomallmann/vim-and-bash | pythonx/UltiSnips/text_objects/_visual.py | Python | gpl-3.0 | 2,074 |
import { Observable } from 'rxjs';
import { each, filter, has, isUndefined, isFunction } from 'lodash';
import { IFilter, Filter } from '../filter';
export interface IFilterGroupSettings<TItemType> {
label: string;
type: string;
options: IFilterOption<TItemType>[];
serialize?: {( activeOption: IFilterOption<TItemType> ): any};
}
export interface IFilterOption<TItemType> {
active?: boolean;
label: string;
type?: string;
value?: any;
predicate: { (item: TItemType): boolean };
serialize?: {(): any};
}
interface IConfiguredFilterOption<TItemType> extends IFilterOption<TItemType> {
count?: number;
}
export interface IFilterGroup<TItemType> extends IFilter<TItemType, any> {
label: string;
type: string;
options: IFilterOption<TItemType>[];
activeOption: IFilterOption<TItemType>;
setActiveOption(index: number): void;
setOptionCounts(counts: number[]): void;
}
export class FilterGroup<TItemType> extends Filter<TItemType, any> implements IFilterGroup<TItemType> {
label: string;
type: string;
options: IFilterOption<TItemType>[];
settings: IFilterGroupSettings<TItemType>;
private _activeOption: IFilterOption<TItemType>;
constructor(settings: IFilterGroupSettings<TItemType>) {
super();
this.settings = settings;
this.label = settings.label;
this.type = settings.type != null ? settings.type : settings.label;
this.initOptions();
}
initOptions():void {
this.options = this.settings.options;
this.activeOption = this.setDefaultOption();
each(this.options, (option: IFilterOption<TItemType>): void => {
if (isUndefined(option.type)) {
option.type = option.label;
}
option.type = (option.type || '').toString().toLowerCase();
});
}
get activeOption(): IFilterOption<TItemType> {
return this._activeOption;
}
set activeOption(value: IFilterOption<TItemType>) {
this._activeOption = value;
this.value$.next(value);
}
private setDefaultOption(): IFilterOption<TItemType> {
let defaultOption: IFilterOption<TItemType> = this.options[0];
each(this.options, (item: IFilterOption<TItemType>): void => {
if (item.active != null && item.active === true) {
defaultOption = item;
}
});
return defaultOption;
}
predicate = (item: any): boolean => {
return this.activeOption.predicate(item);
}
serialize(): Observable<any> {
return this.value$.asObservable().map(activeOption => {
if (isFunction(this.settings.serialize)) {
return this.settings.serialize(activeOption);
}
if (isFunction(activeOption.serialize)) {
return activeOption.serialize();
}
return activeOption.value;
});
}
setActiveOption(index: number): void {
if (index >= 0 && index < this.options.length) {
this.activeOption = this.options[index];
}
}
// filter counts not yet supported in the new card container
setOptionCounts(counts: number[]): void {
each(this.options, (option: IConfiguredFilterOption<TItemType>): void => {
if (has(counts, option.type)) {
option.count = counts[option.type];
}
});
}
updateOptionCounts<TDataType>(filteredDataSet: TDataType[]): void {
each(this.options, (option: IConfiguredFilterOption<TItemType>): void => {
option.count = filter(filteredDataSet, option.predicate.bind(option)).length;
});
}
}
| TheOriginalJosh/TypeScript-Angular-Components | source/components/cardContainer/filters/filterGroup/filterGroup.service.ts | TypeScript | gpl-3.0 | 3,263 |
/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the Clear BSD license.
* See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* @requires OpenLayers/Tile/WFS.js
* @requires OpenLayers/Layer/Vector.js
* @requires OpenLayers/Layer/Markers.js
* @requires OpenLayers/Console.js
* @requires OpenLayers/Lang.js
*/
/**
* Class: OpenLayers.Layer.WFS
* *Deprecated*. To be removed in 3.0. Instead use OpenLayers.Layer.Vector
* with a Protocol.WFS and one or more Strategies.
*
* Inherits from:
* - <OpenLayers.Layer.Vector>
* - <OpenLayers.Layer.Markers>
*/
OpenLayers.Layer.WFS = OpenLayers.Class(
OpenLayers.Layer.Vector, OpenLayers.Layer.Markers, {
/**
* APIProperty: isBaseLayer
* {Boolean} WFS layer is not a base layer by default.
*/
isBaseLayer: false,
/**
* Property: tile
* {<OpenLayers.Tile.WFS>}
*/
tile: null,
/**
* APIProperty: ratio
* {Float} The ratio property determines the size of the serverside query
* relative to the map viewport size. By default, we load an area twice
* as big as the map, to allow for panning without immediately reload.
* Setting this to 1 will cause the area of the WFS request to match
* the map area exactly. It is recommended to set this to some number
* at least slightly larger than 1, otherwise accidental clicks can
* cause a data reload, by moving the map only 1 pixel.
*/
ratio: 2,
/**
* Property: DEFAULT_PARAMS
* {Object} Hashtable of default key/value parameters
*/
DEFAULT_PARAMS: { service: "WFS",
version: "1.0.0",
request: "GetFeature"
},
/**
* APIProperty: featureClass
* {<OpenLayers.Feature>} If featureClass is defined, an old-style markers
* based WFS layer is created instead of a new-style vector layer. If
* sent, this should be a subclass of OpenLayers.Feature
*/
featureClass: null,
/**
* APIProperty: format
* {<OpenLayers.Format>} The format you want the data to be parsed with.
* Must be passed in the constructor. Should be a class, not an instance.
* This option can only be used if no featureClass is passed / vectorMode
* is false: if a featureClass is passed, then this parameter is ignored.
*/
format: null,
/**
* Property: formatObject
* {<OpenLayers.Format>} Internally created/managed format object, used by
* the Tile to parse data.
*/
formatObject: null,
/**
* APIProperty: formatOptions
* {Object} Hash of options which should be passed to the format when it is
* created. Must be passed in the constructor.
*/
formatOptions: null,
/**
* Property: vectorMode
* {Boolean} Should be calculated automatically. Determines whether the
* layer is in vector mode or marker mode.
*/
vectorMode: true,
/**
* APIProperty: encodeBBOX
* {Boolean} Should the BBOX commas be encoded? The WMS spec says 'no',
* but some services want it that way. Default false.
*/
encodeBBOX: false,
/**
* APIProperty: extractAttributes
* {Boolean} Should the WFS layer parse attributes from the retrieved
* GML? Defaults to false. If enabled, parsing is slower, but
* attributes are available in the attributes property of
* layer features.
*/
extractAttributes: false,
/**
* Constructor: OpenLayers.Layer.WFS
*
* Parameters:
* name - {String}
* url - {String}
* params - {Object}
* options - {Object} Hashtable of extra options to tag onto the layer
*/
initialize: function(name, url, params, options) {
if (options == undefined) { options = {}; }
if (options.featureClass ||
!OpenLayers.Layer.Vector ||
!OpenLayers.Feature.Vector) {
this.vectorMode = false;
}
// Uppercase params
params = OpenLayers.Util.upperCaseObject(params);
// Turn off error reporting, browsers like Safari may work
// depending on the setup, and we don't want an unneccesary alert.
OpenLayers.Util.extend(options, {'reportError': false});
var newArguments = [];
newArguments.push(name, options);
OpenLayers.Layer.Vector.prototype.initialize.apply(this, newArguments);
if (!this.renderer || !this.vectorMode) {
this.vectorMode = false;
if (!options.featureClass) {
options.featureClass = OpenLayers.Feature.WFS;
}
OpenLayers.Layer.Markers.prototype.initialize.apply(this,
newArguments);
}
if (this.params && this.params.typename && !this.options.typename) {
this.options.typename = this.params.typename;
}
if (!this.options.geometry_column) {
this.options.geometry_column = "the_geom";
}
this.params = OpenLayers.Util.applyDefaults(
params,
OpenLayers.Util.upperCaseObject(this.DEFAULT_PARAMS)
);
this.url = url;
},
/**
* APIMethod: destroy
*/
destroy: function() {
if (this.vectorMode) {
OpenLayers.Layer.Vector.prototype.destroy.apply(this, arguments);
} else {
OpenLayers.Layer.Markers.prototype.destroy.apply(this, arguments);
}
if (this.tile) {
this.tile.destroy();
}
this.tile = null;
this.ratio = null;
this.featureClass = null;
this.format = null;
if (this.formatObject && this.formatObject.destroy) {
this.formatObject.destroy();
}
this.formatObject = null;
this.formatOptions = null;
this.vectorMode = null;
this.encodeBBOX = null;
this.extractAttributes = null;
},
/**
* Method: setMap
*
* Parameters:
* map - {<OpenLayers.Map>}
*/
setMap: function(map) {
if (this.vectorMode) {
OpenLayers.Layer.Vector.prototype.setMap.apply(this, arguments);
var options = {
'extractAttributes': this.extractAttributes
};
OpenLayers.Util.extend(options, this.formatOptions);
if (this.map && !this.projection.equals(this.map.getProjectionObject())) {
options.externalProjection = this.projection;
options.internalProjection = this.map.getProjectionObject();
}
this.formatObject = this.format ? new this.format(options) : new OpenLayers.Format.GML(options);
} else {
OpenLayers.Layer.Markers.prototype.setMap.apply(this, arguments);
}
},
/**
* Method: moveTo
*
* Parameters:
* bounds - {<OpenLayers.Bounds>}
* zoomChanged - {Boolean}
* dragging - {Boolean}
*/
moveTo:function(bounds, zoomChanged, dragging) {
if (this.vectorMode) {
OpenLayers.Layer.Vector.prototype.moveTo.apply(this, arguments);
} else {
OpenLayers.Layer.Markers.prototype.moveTo.apply(this, arguments);
}
// don't load wfs features while dragging, wait for drag end
if (dragging) {
// TBD try to hide the vector layer while dragging
// this.setVisibility(false);
// this will probably help for panning performances
return false;
}
if ( zoomChanged ) {
if (this.vectorMode) {
this.renderer.clear();
}
}
//DEPRECATED - REMOVE IN 3.0
// don't load data if current zoom level doesn't match
if (this.options.minZoomLevel) {
OpenLayers.Console.warn(OpenLayers.i18n('minZoomLevelError'));
if (this.map.getZoom() < this.options.minZoomLevel) {
return null;
}
}
if (bounds == null) {
bounds = this.map.getExtent();
}
var firstRendering = (this.tile == null);
//does the new bounds to which we need to move fall outside of the
// current tile's bounds?
var outOfBounds = (!firstRendering &&
!this.tile.bounds.containsBounds(bounds));
if (zoomChanged || firstRendering || (!dragging && outOfBounds)) {
//determine new tile bounds
var center = bounds.getCenterLonLat();
var tileWidth = bounds.getWidth() * this.ratio;
var tileHeight = bounds.getHeight() * this.ratio;
var tileBounds =
new OpenLayers.Bounds(center.lon - (tileWidth / 2),
center.lat - (tileHeight / 2),
center.lon + (tileWidth / 2),
center.lat + (tileHeight / 2));
//determine new tile size
var tileSize = this.map.getSize();
tileSize.w = tileSize.w * this.ratio;
tileSize.h = tileSize.h * this.ratio;
//determine new position (upper left corner of new bounds)
var ul = new OpenLayers.LonLat(tileBounds.left, tileBounds.top);
var pos = this.map.getLayerPxFromLonLat(ul);
//formulate request url string
var url = this.getFullRequestString();
var params = null;
// Cant combine "filter" and "BBOX". This is a cheap hack to help
// people out who can't migrate to the WFS protocol immediately.
var filter = this.params.filter || this.params.FILTER;
if (filter) {
params = {FILTER: filter};
}
else {
params = {BBOX: this.encodeBBOX ? tileBounds.toBBOX()
: tileBounds.toArray()};
}
if (this.map && !this.projection.equals(this.map.getProjectionObject())) {
var projectedBounds = tileBounds.clone();
projectedBounds.transform(this.map.getProjectionObject(),
this.projection);
if (!filter){
params.BBOX = this.encodeBBOX ? projectedBounds.toBBOX()
: projectedBounds.toArray();
}
}
url += "&" + OpenLayers.Util.getParameterString(params);
if (!this.tile) {
this.tile = new OpenLayers.Tile.WFS(this, pos, tileBounds,
url, tileSize);
this.addTileMonitoringHooks(this.tile);
this.tile.draw();
} else {
if (this.vectorMode) {
this.destroyFeatures();
this.renderer.clear();
} else {
this.clearMarkers();
}
this.removeTileMonitoringHooks(this.tile);
this.tile.destroy();
this.tile = null;
this.tile = new OpenLayers.Tile.WFS(this, pos, tileBounds,
url, tileSize);
this.addTileMonitoringHooks(this.tile);
this.tile.draw();
}
}
},
/**
* Method: addTileMonitoringHooks
* This function takes a tile as input and adds the appropriate hooks to
* the tile so that the layer can keep track of the loading tile
* (making sure to check that the tile is always the layer's current
* tile before taking any action).
*
* Parameters:
* tile - {<OpenLayers.Tile>}
*/
addTileMonitoringHooks: function(tile) {
tile.onLoadStart = function() {
//if this is the the layer's current tile, then trigger
// a 'loadstart'
if (this == this.layer.tile) {
this.layer.events.triggerEvent("loadstart");
}
};
tile.events.register("loadstart", tile, tile.onLoadStart);
tile.onLoadEnd = function() {
//if this is the the layer's current tile, then trigger
// a 'tileloaded' and 'loadend'
if (this == this.layer.tile) {
this.layer.events.triggerEvent("tileloaded");
this.layer.events.triggerEvent("loadend");
}
};
tile.events.register("loadend", tile, tile.onLoadEnd);
tile.events.register("unload", tile, tile.onLoadEnd);
},
/**
* Method: removeTileMonitoringHooks
* This function takes a tile as input and removes the tile hooks
* that were added in addTileMonitoringHooks()
*
* Parameters:
* tile - {<OpenLayers.Tile>}
*/
removeTileMonitoringHooks: function(tile) {
tile.unload();
tile.events.un({
"loadstart": tile.onLoadStart,
"loadend": tile.onLoadEnd,
"unload": tile.onLoadEnd,
scope: tile
});
},
/**
* Method: onMapResize
* Call the onMapResize method of the appropriate parent class.
*/
onMapResize: function() {
if(this.vectorMode) {
OpenLayers.Layer.Vector.prototype.onMapResize.apply(this,
arguments);
} else {
OpenLayers.Layer.Markers.prototype.onMapResize.apply(this,
arguments);
}
},
/**
* Method: display
* Call the display method of the appropriate parent class.
*/
display: function() {
if(this.vectorMode) {
OpenLayers.Layer.Vector.prototype.display.apply(this,
arguments);
} else {
OpenLayers.Layer.Markers.prototype.display.apply(this,
arguments);
}
},
/**
* APIMethod: mergeNewParams
* Modify parameters for the layer and redraw.
*
* Parameters:
* newParams - {Object}
*/
mergeNewParams:function(newParams) {
var upperParams = OpenLayers.Util.upperCaseObject(newParams);
var newArguments = [upperParams];
return OpenLayers.Layer.HTTPRequest.prototype.mergeNewParams.apply(this,
newArguments);
},
/**
* APIMethod: clone
*
* Parameters:
* obj - {Object}
*
* Returns:
* {<OpenLayers.Layer.WFS>} An exact clone of this OpenLayers.Layer.WFS
*/
clone: function (obj) {
if (obj == null) {
obj = new OpenLayers.Layer.WFS(this.name,
this.url,
this.params,
this.getOptions());
}
//get all additions from superclasses
if (this.vectorMode) {
obj = OpenLayers.Layer.Vector.prototype.clone.apply(this, [obj]);
} else {
obj = OpenLayers.Layer.Markers.prototype.clone.apply(this, [obj]);
}
// copy/set any non-init, non-simple values here
return obj;
},
/**
* APIMethod: getFullRequestString
* combine the layer's url with its params and these newParams.
*
* Add the SRS parameter from 'projection' -- this is probably
* more eloquently done via a setProjection() method, but this
* works for now and always.
*
* Parameters:
* newParams - {Object}
* altUrl - {String} Use this as the url instead of the layer's url
*/
getFullRequestString:function(newParams, altUrl) {
var projectionCode = this.projection.getCode() || this.map.getProjection();
this.params.SRS = (projectionCode == "none") ? null : projectionCode;
return OpenLayers.Layer.Grid.prototype.getFullRequestString.apply(
this, arguments);
},
/**
* APIMethod: commit
* Write out the data to a WFS server.
*/
commit: function() {
if (!this.writer) {
var options = {};
if (this.map && !this.projection.equals(this.map.getProjectionObject())) {
options.externalProjection = this.projection;
options.internalProjection = this.map.getProjectionObject();
}
this.writer = new OpenLayers.Format.WFS(options,this);
}
var data = this.writer.write(this.features);
OpenLayers.Request.POST({
url: this.url,
data: data,
success: this.commitSuccess,
failure: this.commitFailure,
scope: this
});
},
/**
* Method: commitSuccess
* Called when the Ajax request returns a response
*
* Parameters:
* response - {XmlNode} from server
*/
commitSuccess: function(request) {
var response = request.responseText;
if (response.indexOf('SUCCESS') != -1) {
this.commitReport(OpenLayers.i18n("commitSuccess", {'response':response}));
for(var i = 0; i < this.features.length; i++) {
this.features[i].state = null;
}
// TBD redraw the layer or reset the state of features
// foreach features: set state to null
} else if (response.indexOf('FAILED') != -1 ||
response.indexOf('Exception') != -1) {
this.commitReport(OpenLayers.i18n("commitFailed", {'response':response}));
}
},
/**
* Method: commitFailure
* Called when the Ajax request fails
*
* Parameters:
* response - {XmlNode} from server
*/
commitFailure: function(request) {},
/**
* APIMethod: commitReport
* Called with a 'success' message if the commit succeeded, otherwise
* a failure message, and the full request text as a second parameter.
* Override this function to provide custom transaction reporting.
*
* string - {String} reporting string
* response - {String} full XML response
*/
commitReport: function(string, response) {
OpenLayers.Console.userError(string);
},
/**
* APIMethod: refresh
* Refreshes all the features of the layer
*/
refresh: function() {
if (this.tile) {
if (this.vectorMode) {
this.renderer.clear();
this.features.length = 0;
} else {
this.clearMarkers();
this.markers.length = 0;
}
this.tile.draw();
}
},
/**
* APIMethod: getDataExtent
* Calculates the max extent which includes all of the layer data.
*
* Returns:
* {<OpenLayers.Bounds>}
*/
getDataExtent: function () {
var extent;
//get all additions from superclasses
if (this.vectorMode) {
extent = OpenLayers.Layer.Vector.prototype.getDataExtent.apply(this);
} else {
extent = OpenLayers.Layer.Markers.prototype.getDataExtent.apply(this);
}
return extent;
},
/**
* APIMethod: setOpacity
* Call the setOpacity method of the appropriate parent class to set the
* opacity.
*
* Parameter:
* opacity - {Float}
*/
setOpacity: function (opacity) {
if (this.vectorMode) {
OpenLayers.Layer.Vector.prototype.setOpacity.apply(this, [opacity]);
} else {
OpenLayers.Layer.Markers.prototype.setOpacity.apply(this, [opacity]);
}
},
CLASS_NAME: "OpenLayers.Layer.WFS"
});
| shamoxiaoniqiu2008/jeecg-framework | src/main/webapp/plug-in/OpenLayers-2.11/lib/OpenLayers/Layer/WFS.js | JavaScript | gpl-3.0 | 21,204 |
namespace WowPacketParser.Enums
{
public enum MailActionType
{
Send = 0,
MoneyTaken = 1,
AttachmentExpired = 2,
ReturnedToSender = 3,
Deleted = 4,
MadePermanent = 5
}
}
| DrEhsan/WowPacketParser | WowPacketParser/Enums/MailActionType.cs | C# | gpl-3.0 | 264 |
<?php
/**
* Kiwitrees: Web based Family History software
* Copyright (C) 2012 to 2022 kiwitrees.net
*
* Derived from webtrees (www.webtrees.net)
* Copyright (C) 2010 to 2012 webtrees development team
*
* Derived from PhpGedView (phpgedview.sourceforge.net)
* Copyright (C) 2002 to 2010 PGV Development Team
*
* Kiwitrees 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 Kiwitrees. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('KT_KIWITREES') || !defined('KT_SCRIPT_NAME') || KT_SCRIPT_NAME!='help_text.php') {
header('HTTP/1.0 403 Forbidden');
exit;
}
switch ($help) {
}
| kiwi3685/kiwitrees | modules_v4/yahrzeit/help_text.php | PHP | gpl-3.0 | 1,119 |
/*!
@file
@author Albert Semenov
@date 09/2009
*/
#include "Precompiled.h"
#include "InputManager.h"
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
#include <windows.h>
#endif
namespace input
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
MyGUI::Char translateWin32Text(MyGUI::KeyCode kc)
{
static WCHAR deadKey = 0;
BYTE keyState[256];
HKL layout = GetKeyboardLayout(0);
if ( GetKeyboardState(keyState) == 0 )
return 0;
int code = *((int*)&kc);
unsigned int vk = MapVirtualKeyEx((UINT)code, 3, layout);
if ( vk == 0 )
return 0;
WCHAR buff[3] = { 0, 0, 0 };
int ascii = ToUnicodeEx(vk, (UINT)code, keyState, buff, 3, 0, layout);
if (ascii == 1 && deadKey != '\0' )
{
// A dead key is stored and we have just converted a character key
// Combine the two into a single character
WCHAR wcBuff[3] = { buff[0], deadKey, '\0' };
WCHAR out[3];
deadKey = '\0';
if (FoldStringW(MAP_PRECOMPOSED, (LPWSTR)wcBuff, 3, (LPWSTR)out, 3))
return out[0];
}
else if (ascii == 1)
{
// We have a single character
deadKey = '\0';
return buff[0];
}
else if (ascii == 2)
{
// Convert a non-combining diacritical mark into a combining diacritical mark
// Combining versions range from 0x300 to 0x36F; only 5 (for French) have been mapped below
// http://www.fileformat.info/info/unicode/block/combining_diacritical_marks/images.htm
switch (buff[0])
{
case 0x5E: // Circumflex accent: â
deadKey = 0x302;
break;
case 0x60: // Grave accent: à
deadKey = 0x300;
break;
case 0xA8: // Diaeresis: ü
deadKey = 0x308;
break;
case 0xB4: // Acute accent: é
deadKey = 0x301;
break;
case 0xB8: // Cedilla: ç
deadKey = 0x327;
break;
default:
deadKey = buff[0];
break;
}
}
return 0;
}
#endif
InputManager::InputManager() :
mInputManager(0),
mKeyboard(0),
mMouse(0),
mCursorX(0),
mCursorY(0)
{
}
InputManager::~InputManager()
{
}
void InputManager::createInput(size_t _handle)
{
std::ostringstream windowHndStr;
windowHndStr << _handle;
OIS::ParamList pl;
pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
mInputManager = OIS::InputManager::createInputSystem(pl);
mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, true ));
mKeyboard->setEventCallback(this);
mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, true ));
mMouse->setEventCallback(this);
}
void InputManager::destroyInput()
{
if (mInputManager)
{
if (mMouse)
{
mInputManager->destroyInputObject( mMouse );
mMouse = nullptr;
}
if (mKeyboard)
{
mInputManager->destroyInputObject( mKeyboard );
mKeyboard = nullptr;
}
OIS::InputManager::destroyInputSystem(mInputManager);
mInputManager = nullptr;
}
}
bool InputManager::mouseMoved(const OIS::MouseEvent& _arg)
{
mCursorX += _arg.state.X.rel;
mCursorY += _arg.state.Y.rel;
checkPosition();
injectMouseMove(mCursorX, mCursorY, _arg.state.Z.abs);
return true;
}
bool InputManager::mousePressed(const OIS::MouseEvent& _arg, OIS::MouseButtonID _id)
{
injectMousePress(mCursorX, mCursorY, MyGUI::MouseButton::Enum(_id));
return true;
}
bool InputManager::mouseReleased(const OIS::MouseEvent& _arg, OIS::MouseButtonID _id)
{
injectMouseRelease(mCursorX, mCursorY, MyGUI::MouseButton::Enum(_id));
return true;
}
bool InputManager::keyPressed(const OIS::KeyEvent& _arg)
{
MyGUI::Char text = (MyGUI::Char)_arg.text;
MyGUI::KeyCode key = MyGUI::KeyCode::Enum(_arg.key);
int scan_code = key.toValue();
if (scan_code > 70 && scan_code < 84)
{
static MyGUI::Char nums[13] = { 55, 56, 57, 45, 52, 53, 54, 43, 49, 50, 51, 48, 46 };
text = nums[scan_code-71];
}
else if (key == MyGUI::KeyCode::Divide)
{
text = '/';
}
else
{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
text = translateWin32Text(key);
#endif
}
injectKeyPress(key, text);
return true;
}
bool InputManager::keyReleased(const OIS::KeyEvent& _arg)
{
injectKeyRelease(MyGUI::KeyCode::Enum(_arg.key));
return true;
}
void InputManager::captureInput()
{
if (mMouse) mMouse->capture();
mKeyboard->capture();
}
void InputManager::setInputViewSize(int _width, int _height)
{
if (mMouse)
{
const OIS::MouseState& ms = mMouse->getMouseState();
ms.width = _width;
ms.height = _height;
checkPosition();
}
}
void InputManager::setMousePosition(int _x, int _y)
{
//const OIS::MouseState &ms = mMouse->getMouseState();
mCursorX = _x;
mCursorY = _y;
checkPosition();
}
void InputManager::checkPosition()
{
const OIS::MouseState& ms = mMouse->getMouseState();
if (mCursorX < 0)
mCursorX = 0;
else if (mCursorX >= ms.width)
mCursorX = ms.width - 1;
if (mCursorY < 0)
mCursorY = 0;
else if (mCursorY >= ms.height)
mCursorY = ms.height - 1;
}
void InputManager::updateCursorPosition()
{
const OIS::MouseState& ms = mMouse->getMouseState();
injectMouseMove(mCursorX, mCursorY, ms.Z.abs);
}
} // namespace input
| tizbac/ror-ng | deps/MyGUI/Common/Input/OIS/InputManager.cpp | C++ | gpl-3.0 | 5,367 |
@SET WIRESHARKVERSION=1.4.4
@SET WIRESHARKSOURCEDIR=D:\workspace\wireshark-1.4.4
@SET WIRESHARKINSTALLDIR=C:\Program Files\Wireshark
@SET WIRESHARKDEFINITIONSDIR=D:\workspace\converter\install\asterix
@SET ASTERIXSOURCEDIR=D:\workspace\converter\src\asterix
@SET ASTERIXSOURCEDIR=D:\workspace\converter\src\asterix
cd /d %WIRESHARKSOURCEDIR%/plugins
mkdir asterix
cd asterix
cp %ASTERIXSOURCEDIR%/wireshark-plugin/* %WIRESHARKSOURCEDIR%/plugins/asterix
cp %ASTERIXSOURCEDIR%/expat/* %WIRESHARKSOURCEDIR%/plugins/asterix
cp %ASTERIXSOURCEDIR%/* %WIRESHARKSOURCEDIR%/plugins/asterix
rem call "C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\vcvars32.bat"
@SET VSINSTALLDIR=C:\Program Files\Microsoft Visual Studio 9.0
@SET VCINSTALLDIR=C:\Program Files\Microsoft Visual Studio 9.0\VC
@SET FrameworkDir=C:\WINDOWS\Microsoft.NET\Framework
@SET FrameworkVersion=v2.0.50727
@SET Framework35Version=v3.5
@if "%VSINSTALLDIR%"=="" goto error_no_VSINSTALLDIR
@if "%VCINSTALLDIR%"=="" goto error_no_VCINSTALLDIR
@echo Setting environment for using Microsoft Visual Studio 2008 x86 tools.
@call :GetWindowsSdkDir
@if not "%WindowsSdkDir%" == "" (
set "PATH=%WindowsSdkDir%bin;%PATH%"
set "INCLUDE=%WindowsSdkDir%include;%INCLUDE%"
set "LIB=%WindowsSdkDir%lib;%LIB%"
)
@rem
@rem Root of Visual Studio IDE installed files.
@rem
@set DevEnvDir=C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE
@set PATH=C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE;C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN;C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools;C:\WINDOWS\Microsoft.NET\Framework\v3.5;C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727;C:\Program Files\Microsoft Visual Studio 9.0\VC\VCPackages;%PATH%
@set INCLUDE=C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE;%INCLUDE%
@set LIB=C:\Program Files\Microsoft Visual Studio 9.0\VC\LIB;%LIB%
@set LIBPATH=C:\WINDOWS\Microsoft.NET\Framework\v3.5;C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727;C:\Program Files\Microsoft Visual Studio 9.0\VC\LIB;%LIBPATH%
@goto end
:GetWindowsSdkDir
@call :GetWindowsSdkDirHelper HKLM > nul 2>&1
@if errorlevel 1 call :GetWindowsSdkDirHelper HKCU > nul 2>&1
@if errorlevel 1 set WindowsSdkDir=%VCINSTALLDIR%\PlatformSDK\
@exit /B 0
:GetWindowsSdkDirHelper
@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Microsoft\Microsoft SDKs\Windows" /v "CurrentInstallFolder"') DO (
if "%%i"=="CurrentInstallFolder" (
SET "WindowsSdkDir=%%k"
)
)
@if "%WindowsSdkDir%"=="" exit /B 1
@exit /B 0
:error_no_VSINSTALLDIR
@echo ERROR: VSINSTALLDIR variable is not set.
@goto end
:error_no_VCINSTALLDIR
@echo ERROR: VCINSTALLDIR variable is not set.
@goto end
:end
nmake -f Makefile.nmake clean
nmake -f Makefile.nmake all
cp asterix.dll "%WIRESHARKINSTALLDIR%\plugins\%WIRESHARKVERSION%"
cp %WIRESHARKDEFINITIONSDIR%/asterix*.xml "%WIRESHARKINSTALLDIR%\plugins"
cp %WIRESHARKDEFINITIONSDIR%/asterix.ini "%WIRESHARKINSTALLDIR%\plugins"
pause | nabilbendafi/asterix | src/asterix/wireshark-plugin/1.8.4/copy_and_build.bat | Batchfile | gpl-3.0 | 2,961 |
/* -*- c++ -*- */
/*
* Copyright 2007,2008 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio 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, or (at your option)
* any later version.
*
* GNU Radio 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.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <mblock/mblock.h>
#include <mblock/runtime.h>
#include <mblock/protocol_class.h>
#include <mblock/exception.h>
#include <mblock/msg_queue.h>
#include <mblock/message.h>
#include <mblock/msg_accepter.h>
#include <mblock/class_registry.h>
#include <pmt.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <iostream>
#include <ui_nco.h>
// Include the symbols needed for communication with USRP server
#include <symbols_usrp_server_cs.h>
#include <symbols_usrp_channel.h>
#include <symbols_usrp_low_level_cs.h>
#include <symbols_usrp_tx.h>
#include <symbols_usrp_rx.h>
static bool verbose = true;
class test_usrp_inband_underrun : public mb_mblock
{
mb_port_sptr d_tx; // Ports connected to the USRP server
mb_port_sptr d_rx;
mb_port_sptr d_cs;
pmt_t d_tx_chan; // Returned channel from TX allocation
pmt_t d_rx_chan; // Returned channel from RX allocation
pmt_t d_which_usrp; // The USRP to use for the test
long d_warm_msgs; // The number of messages to 'warm' the USRP
long d_warm_recvd; // The number of msgs received in the 'warm' state
// Keep track of current state
enum state_t {
INIT,
OPENING_USRP,
ALLOCATING_CHANNELS,
WRITE_REGISTER,
READ_REGISTER,
TRANSMITTING,
CLOSING_CHANNELS,
CLOSING_USRP,
};
state_t d_state;
long d_nsamples_to_send;
long d_nsamples_xmitted;
long d_nframes_xmitted;
long d_samples_per_frame;
bool d_done_sending;
// for generating sine wave output
ui_nco<float,float> d_nco;
double d_amplitude;
long d_n_underruns;
public:
test_usrp_inband_underrun(mb_runtime *runtime, const std::string &instance_name, pmt_t user_arg);
~test_usrp_inband_underrun();
void initial_transition();
void handle_message(mb_message_sptr msg);
protected:
void opening_usrp();
void allocating_channels();
void write_register();
void read_register();
void closing_channels();
void closing_usrp();
void enter_receiving();
void enter_transmitting();
void build_and_send_ping();
void build_and_send_next_frame();
void handle_xmit_response(pmt_t handle);
void handle_recv_response(pmt_t dict);
};
int
main (int argc, char **argv)
{
// handle any command line args here
mb_runtime_sptr rt = mb_make_runtime();
pmt_t result = PMT_NIL;
rt->run("top", "test_usrp_inband_underrun", PMT_F, &result);
}
test_usrp_inband_underrun::test_usrp_inband_underrun(mb_runtime *runtime, const std::string &instance_name, pmt_t user_arg)
: mb_mblock(runtime, instance_name, user_arg),
d_tx_chan(PMT_NIL),
d_rx_chan(PMT_NIL),
d_which_usrp(pmt_from_long(0)),
d_state(INIT),
d_nsamples_to_send((long) 27e6),
d_nsamples_xmitted(0),
d_nframes_xmitted(0),
d_samples_per_frame(d_nsamples_to_send), // full packet
d_done_sending(false),
d_amplitude(16384),
d_n_underruns(0)
{
// A dictionary is used to pass parameters to the USRP
pmt_t usrp_dict = pmt_make_dict();
// Specify the RBF to use
pmt_dict_set(usrp_dict,
pmt_intern("rbf"),
pmt_intern("inband_1rxhb_1tx.rbf"));
// Set TX and RX interpolations
pmt_dict_set(usrp_dict,
pmt_intern("interp-tx"),
pmt_from_long(64));
pmt_dict_set(usrp_dict,
pmt_intern("decim-rx"),
pmt_from_long(128));
d_tx = define_port("tx0", "usrp-tx", false, mb_port::INTERNAL);
d_rx = define_port("rx0", "usrp-rx", false, mb_port::INTERNAL);
d_cs = define_port("cs", "usrp-server-cs", false, mb_port::INTERNAL);
// Create an instance of USRP server and connect ports
define_component("server", "usrp_server", usrp_dict);
connect("self", "tx0", "server", "tx0");
connect("self", "rx0", "server", "rx0");
connect("self", "cs", "server", "cs");
// initialize NCO
double freq = 100e3;
int interp = 32; // 32 -> 4MS/s
double sample_rate = 128e6 / interp;
d_nco.set_freq(2*M_PI * freq/sample_rate);
}
test_usrp_inband_underrun::~test_usrp_inband_underrun()
{
}
void
test_usrp_inband_underrun::initial_transition()
{
opening_usrp();
}
// Handle message reads all incoming messages from USRP server which will be
// initialization and ping responses. We perform actions based on the current
// state and the event (ie, ping response)
void
test_usrp_inband_underrun::handle_message(mb_message_sptr msg)
{
pmt_t event = msg->signal();
pmt_t data = msg->data();
pmt_t port_id = msg->port_id();
pmt_t handle = PMT_F;
pmt_t status = PMT_F;
pmt_t dict = PMT_NIL;
std::string error_msg;
// Check the recv sample responses for underruns and count
if(pmt_eq(event, s_response_recv_raw_samples)) {
handle = pmt_nth(0, data);
status = pmt_nth(1, data);
dict = pmt_nth(4, data);
if(pmt_eq(status, PMT_T)) {
handle_recv_response(dict);
return;
}
else {
error_msg = "error while receiving samples:";
goto bail;
}
}
// Dispatch based on state
switch(d_state) {
//----------------------------- OPENING_USRP ----------------------------//
// We only expect a response from opening the USRP which should be succesful
// or failed.
case OPENING_USRP:
if(pmt_eq(event, s_response_open)) {
status = pmt_nth(1, data); // failed/succes
if(pmt_eq(status, PMT_T)) {
allocating_channels();
return;
}
else {
error_msg = "failed to open usrp:";
goto bail;
}
}
goto unhandled; // all other messages not handled in this state
//----------------------- ALLOCATING CHANNELS --------------------//
// When allocating channels, we need to wait for 2 responses from
// USRP server: one for TX and one for RX. Both are initialized to
// NIL so we know to continue to the next state once both are set.
case ALLOCATING_CHANNELS:
// A TX allocation response
if(pmt_eq(event, s_response_allocate_channel)
&& pmt_eq(d_tx->port_symbol(), port_id))
{
status = pmt_nth(1, data);
// If successful response, extract the channel
if(pmt_eq(status, PMT_T)) {
d_tx_chan = pmt_nth(2, data);
if(verbose)
std::cout << "[TEST_USRP_INBAND_UNDERRUN] Received TX allocation"
<< " on channel " << d_tx_chan << std::endl;
// If the RX has also been allocated already, we can continue
if(!pmt_eqv(d_rx_chan, PMT_NIL)) {
enter_receiving();
enter_transmitting();
}
return;
}
else { // TX allocation failed
error_msg = "failed to allocate TX channel:";
goto bail;
}
}
// A RX allocation response
if(pmt_eq(event, s_response_allocate_channel)
&& pmt_eq(d_rx->port_symbol(), port_id))
{
status = pmt_nth(1, data);
// If successful response, extract the channel
if(pmt_eq(status, PMT_T)) {
d_rx_chan = pmt_nth(2, data);
if(verbose)
std::cout << "[TEST_USRP_INBAND_UNDERRUN] Received RX allocation"
<< " on channel " << d_rx_chan << std::endl;
// If the TX has also been allocated already, we can continue
if(!pmt_eqv(d_tx_chan, PMT_NIL)) {
enter_receiving();
enter_transmitting();
}
return;
}
else { // RX allocation failed
error_msg = "failed to allocate RX channel:";
goto bail;
}
}
goto unhandled;
case WRITE_REGISTER:
goto unhandled;
case READ_REGISTER:
goto unhandled;
//-------------------------- TRANSMITTING ----------------------------//
// In the transmit state we count the number of underruns received and
// ballpark the number with an expected count (something >1 for starters)
case TRANSMITTING:
// Check that the transmits are OK
if (pmt_eq(event, s_response_xmit_raw_frame)){
handle = pmt_nth(0, data);
status = pmt_nth(1, data);
if (pmt_eq(status, PMT_T)){
handle_xmit_response(handle);
return;
}
else {
error_msg = "bad response-xmit-raw-frame:";
goto bail;
}
}
goto unhandled;
//------------------------- CLOSING CHANNELS ----------------------------//
// Check deallocation responses, once the TX and RX channels are both
// deallocated then we close the USRP.
case CLOSING_CHANNELS:
if (pmt_eq(event, s_response_deallocate_channel)
&& pmt_eq(d_tx->port_symbol(), port_id))
{
status = pmt_nth(1, data);
// If successful, set the port to NIL
if(pmt_eq(status, PMT_T)) {
d_tx_chan = PMT_NIL;
if(verbose)
std::cout << "[TEST_USRP_INBAND_UNDERRUN] Received TX deallocation\n";
// If the RX is also deallocated, we can close the USRP
if(pmt_eq(d_rx_chan, PMT_NIL))
closing_usrp();
return;
} else {
error_msg = "failed to deallocate TX channel:";
goto bail;
}
}
if (pmt_eq(event, s_response_deallocate_channel)
&& pmt_eq(d_rx->port_symbol(), port_id))
{
status = pmt_nth(1, data);
// If successful, set the port to NIL
if(pmt_eq(status, PMT_T)) {
d_rx_chan = PMT_NIL;
if(verbose)
std::cout << "[TEST_USRP_INBAND_UNDERRUN] Received RX deallocation\n";
// If the TX is also deallocated, we can close the USRP
if(pmt_eq(d_tx_chan, PMT_NIL))
closing_usrp();
return;
} else {
error_msg = "failed to deallocate RX channel:";
goto bail;
}
}
goto unhandled;
//--------------------------- CLOSING USRP ------------------------------//
// Once we have received a successful USRP close response, we shutdown all
// mblocks and exit.
case CLOSING_USRP:
if (pmt_eq(event, s_response_close)) {
status = pmt_nth(1, data);
if(pmt_eq(status, PMT_T)) {
if(verbose)
std::cout << "[TEST_USRP_INBAND_UNDERRUN] Successfully closed USRP\n";
std::cout << "\nUnderruns: " << d_n_underruns << std::endl;
fflush(stdout);
shutdown_all(PMT_T);
return;
} else {
error_msg = "failed to close USRP:";
goto bail;
}
}
goto unhandled;
case INIT:
goto unhandled;
}
// An error occured, print it, and shutdown all m-blocks
bail:
std::cerr << error_msg << data
<< "status = " << status << std::endl;
shutdown_all(PMT_F);
return;
// Received an unhandled message for a specific state
unhandled:
if(verbose && !pmt_eq(event, pmt_intern("%shutdown")))
std::cout << "test_usrp_inband_tx: unhandled msg: " << msg
<< "in state "<< d_state << std::endl;
}
// Sends a command to USRP server to open up a connection to the
// specified USRP, which is defaulted to USRP 0 on the system
void
test_usrp_inband_underrun::opening_usrp()
{
if(verbose)
std::cout << "[TEST_USRP_INBAND_UNDERRUN] Opening USRP "
<< d_which_usrp << std::endl;
d_cs->send(s_cmd_open, pmt_list2(PMT_NIL, d_which_usrp));
d_state = OPENING_USRP;
}
// RX and TX channels must be allocated so that the USRP server can
// properly share bandwidth across multiple USRPs. No commands will be
// successful to the USRP through the USRP server on the TX or RX channels until
// a bandwidth allocation has been received.
void
test_usrp_inband_underrun::allocating_channels()
{
d_state = ALLOCATING_CHANNELS;
long capacity = (long) 16e6;
d_tx->send(s_cmd_allocate_channel, pmt_list2(PMT_T, pmt_from_long(capacity)));
d_rx->send(s_cmd_allocate_channel, pmt_list2(PMT_T, pmt_from_long(capacity)));
}
// After allocating the channels, a write register command will be sent to the
// USRP.
void
test_usrp_inband_underrun::write_register()
{
d_state = WRITE_REGISTER;
long reg = 0;
d_tx->send(s_cmd_to_control_channel, // C/S packet
pmt_list2(PMT_NIL, // invoc handle
pmt_list1(
pmt_list2(s_op_write_reg,
pmt_list2(
pmt_from_long(reg),
pmt_from_long(0xbeef))))));
if(verbose)
std::cout << "[TEST_USRP_INBAND_REGISTERS] Writing 0xbeef to "
<< reg << std::endl;
read_register(); // immediately transition to read the register
}
// Temporary: for testing pings
void
test_usrp_inband_underrun::build_and_send_ping()
{
d_tx->send(s_cmd_to_control_channel,
pmt_list2(PMT_NIL, pmt_list1(pmt_list2(s_op_ping_fixed,
pmt_list2(pmt_from_long(0),
pmt_from_long(0))))));
std::cout << "[TEST_USRP_INBAND_UNDERRUN] Ping sent" << std::endl;
}
// After writing to the register, we want to read the value back and ensure that
// it is the same value that we wrote.
void
test_usrp_inband_underrun::read_register()
{
d_state = READ_REGISTER;
long reg = 9;
d_tx->send(s_cmd_to_control_channel, // C/S packet
pmt_list2(PMT_NIL, // invoc handle
pmt_list1(
pmt_list2(s_op_read_reg,
pmt_list2(
pmt_from_long(0), // rid
pmt_from_long(reg))))));
if(verbose)
std::cout << "[TEST_USRP_INBAND_UNDERRUN] Reading from register "
<< reg << std::endl;
}
// Used to enter the receiving state
void
test_usrp_inband_underrun::enter_receiving()
{
d_rx->send(s_cmd_start_recv_raw_samples,
pmt_list2(PMT_F,
d_rx_chan));
if(verbose)
std::cout << "[TEST_USRP_INBAND_UNDERRUN] Started RX sample stream\n";
}
void
test_usrp_inband_underrun::enter_transmitting()
{
d_state = TRANSMITTING;
d_nsamples_xmitted = 0;
if(verbose)
std::cout << "[TEST_USRP_INBAND_UNDERRUN] Entering transmit state...\n";
build_and_send_next_frame(); // fire off 4 to start pipeline
build_and_send_next_frame();
build_and_send_next_frame();
build_and_send_next_frame();
}
void
test_usrp_inband_underrun::build_and_send_next_frame()
{
long nsamples_this_frame =
std::min(d_nsamples_to_send - d_nsamples_xmitted,
d_samples_per_frame);
if (nsamples_this_frame == 0){
d_done_sending = true;
return;
}
size_t nshorts = 2 * nsamples_this_frame; // 16-bit I & Q
pmt_t uvec = pmt_make_s16vector(nshorts, 0);
size_t ignore;
int16_t *samples = pmt_s16vector_writable_elements(uvec, ignore);
// fill in the complex sinusoid
for (int i = 0; i < nsamples_this_frame; i++){
if (1){
gr_complex s;
d_nco.sincos(&s, 1, d_amplitude);
// write 16-bit i & q
samples[2*i] = (int16_t) s.real();
samples[2*i+1] = (int16_t) s.imag();
}
else {
gr_complex s(d_amplitude, d_amplitude);
// write 16-bit i & q
samples[2*i] = (int16_t) s.real();
samples[2*i+1] = (int16_t) s.imag();
}
}
if(verbose)
std::cout << "[TEST_USRP_INBAND_TX] Transmitting frame...\n";
pmt_t timestamp = pmt_from_long(0xffffffff); // NOW
d_tx->send(s_cmd_xmit_raw_frame,
pmt_list4(pmt_from_long(d_nframes_xmitted), // invocation-handle
d_tx_chan, // channel
uvec, // the samples
timestamp));
d_nsamples_xmitted += nsamples_this_frame;
d_nframes_xmitted++;
if(verbose)
std::cout << "[TEST_USRP_INBAND_TX] Transmitted frame\n";
}
void
test_usrp_inband_underrun::handle_xmit_response(pmt_t handle)
{
if (d_done_sending &&
pmt_to_long(handle) == (d_nframes_xmitted - 1)){
// We're done sending and have received all responses
closing_channels();
return;
}
build_and_send_next_frame();
}
void
test_usrp_inband_underrun::handle_recv_response(pmt_t dict)
{
if(!pmt_is_dict(dict)) {
std::cout << "[TEST_USRP_INBAND_UNDERRUN] Recv samples dictionary is improper\n";
return;
}
// Read the TX interpolations
if(pmt_t underrun = pmt_dict_ref(dict,
pmt_intern("underrun"),
PMT_NIL)) {
if(pmt_eqv(underrun, PMT_T)) {
d_n_underruns++;
if(verbose && 0)
std::cout << "[TEST_USRP_INBAND_UNDERRUN] Underrun\n";
}
else {
if(verbose && 0)
std::cout << "[TEST_USRP_INBAND_UNDERRUN] No underrun\n" << underrun <<std::endl;
}
} else {
if(verbose && 0)
std::cout << "[TEST_USRP_INBAND_UNDERRUN] No underrun\n";
}
}
void
test_usrp_inband_underrun::closing_channels()
{
d_state = CLOSING_CHANNELS;
d_tx->send(s_cmd_deallocate_channel, pmt_list2(PMT_NIL, d_tx_chan));
d_rx->send(s_cmd_deallocate_channel, pmt_list2(PMT_NIL, d_rx_chan));
}
void
test_usrp_inband_underrun::closing_usrp()
{
d_state = CLOSING_USRP;
d_cs->send(s_cmd_close, pmt_list1(PMT_NIL));
}
REGISTER_MBLOCK_CLASS(test_usrp_inband_underrun);
| JohnOrlando/gnuradio-bitshark | usrp/limbo/apps-inband/test_usrp_inband_underrun.cc | C++ | gpl-3.0 | 18,388 |
#ifndef BOOST_GEOMETRY_PROJECTIONS_GSTMERC_HPP
#define BOOST_GEOMETRY_PROJECTIONS_GSTMERC_HPP
// Boost.Geometry - extensions-gis-projections (based on PROJ4)
// This file is automatically generated. DO NOT EDIT.
// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.
// This file was modified by Oracle on 2017.
// Modifications copyright (c) 2017, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// This file is converted from PROJ4, http://trac.osgeo.org/proj
// PROJ4 is originally written by Gerald Evenden (then of the USGS)
// PROJ4 is maintained by Frank Warmerdam
// PROJ4 is converted to Boost.Geometry by Barend Gehrels
// Last updated version of proj: 4.9.1
// Original copyright notice:
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include <boost/geometry/srs/projections/impl/base_static.hpp>
#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>
#include <boost/geometry/srs/projections/impl/projects.hpp>
#include <boost/geometry/srs/projections/impl/factory_entry.hpp>
#include <boost/geometry/srs/projections/impl/pj_phi2.hpp>
#include <boost/geometry/srs/projections/impl/pj_tsfn.hpp>
namespace boost { namespace geometry
{
namespace srs { namespace par4
{
struct gstmerc {};
}} //namespace srs::par4
namespace projections
{
#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace gstmerc
{
template <typename T>
struct par_gstmerc
{
T lamc;
T phic;
T c;
T n1;
T n2;
T XS;
T YS;
};
// template class, using CRTP to implement forward/inverse
template <typename CalculationType, typename Parameters>
struct base_gstmerc_spheroid : public base_t_fi<base_gstmerc_spheroid<CalculationType, Parameters>,
CalculationType, Parameters>
{
typedef CalculationType geographic_type;
typedef CalculationType cartesian_type;
par_gstmerc<CalculationType> m_proj_parm;
inline base_gstmerc_spheroid(const Parameters& par)
: base_t_fi<base_gstmerc_spheroid<CalculationType, Parameters>,
CalculationType, Parameters>(*this, par) {}
// FORWARD(s_forward) spheroid
// Project coordinates from geographic (lon, lat) to cartesian (x, y)
inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const
{
CalculationType L, Ls, sinLs1, Ls1;
L= this->m_proj_parm.n1*lp_lon;
Ls= this->m_proj_parm.c+this->m_proj_parm.n1*log(pj_tsfn(-1.0*lp_lat,-1.0*sin(lp_lat),this->m_par.e));
sinLs1= sin(L)/cosh(Ls);
Ls1= log(pj_tsfn(-1.0*asin(sinLs1),0.0,0.0));
xy_x= (this->m_proj_parm.XS + this->m_proj_parm.n2*Ls1)*this->m_par.ra;
xy_y= (this->m_proj_parm.YS + this->m_proj_parm.n2*atan(sinh(Ls)/cos(L)))*this->m_par.ra;
/*fprintf(stderr,"fwd:\nL =%16.13f\nLs =%16.13f\nLs1 =%16.13f\nLP(%16.13f,%16.13f)=XY(%16.4f,%16.4f)\n",L,Ls,Ls1,lp_lon+this->m_par.lam0,lp_lat,(xy_x*this->m_par.a + this->m_par.x0)*this->m_par.to_meter,(xy_y*this->m_par.a + this->m_par.y0)*this->m_par.to_meter);*/
}
// INVERSE(s_inverse) spheroid
// Project coordinates from cartesian (x, y) to geographic (lon, lat)
inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const
{
CalculationType L, LC, sinC;
L= atan(sinh((xy_x*this->m_par.a - this->m_proj_parm.XS)/this->m_proj_parm.n2)/cos((xy_y*this->m_par.a - this->m_proj_parm.YS)/this->m_proj_parm.n2));
sinC= sin((xy_y*this->m_par.a - this->m_proj_parm.YS)/this->m_proj_parm.n2)/cosh((xy_x*this->m_par.a - this->m_proj_parm.XS)/this->m_proj_parm.n2);
LC= log(pj_tsfn(-1.0*asin(sinC),0.0,0.0));
lp_lon= L/this->m_proj_parm.n1;
lp_lat= -1.0*pj_phi2(exp((LC-this->m_proj_parm.c)/this->m_proj_parm.n1),this->m_par.e);
/*fprintf(stderr,"inv:\nL =%16.13f\nsinC =%16.13f\nLC =%16.13f\nXY(%16.4f,%16.4f)=LP(%16.13f,%16.13f)\n",L,sinC,LC,((xy_x/this->m_par.ra)+this->m_par.x0)/this->m_par.to_meter,((xy_y/this->m_par.ra)+this->m_par.y0)/this->m_par.to_meter,lp_lon+this->m_par.lam0,lp_lat);*/
}
static inline std::string get_name()
{
return "gstmerc_spheroid";
}
};
// Gauss-Schreiber Transverse Mercator (aka Gauss-Laborde Reunion)
template <typename Parameters, typename T>
inline void setup_gstmerc(Parameters& par, par_gstmerc<T>& proj_parm)
{
proj_parm.lamc= par.lam0;
proj_parm.n1= sqrt(1.0+par.es*pow(cos(par.phi0),4.0)/(1.0-par.es));
proj_parm.phic= asin(sin(par.phi0)/proj_parm.n1);
proj_parm.c= log(pj_tsfn(-1.0*proj_parm.phic,0.0,0.0))
-proj_parm.n1*log(pj_tsfn(-1.0*par.phi0,-1.0*sin(par.phi0),par.e));
proj_parm.n2= par.k0*par.a*sqrt(1.0-par.es)/(1.0-par.es*sin(par.phi0)*sin(par.phi0));
proj_parm.XS= 0;/* -par.x0 */
proj_parm.YS= -1.0*proj_parm.n2*proj_parm.phic;/* -par.y0 */
/*fprintf(stderr,"a (m) =%16.4f\ne =%16.13f\nl0(rad)=%16.13f\np0(rad)=%16.13f\nk0 =%16.4f\nX0 (m)=%16.4f\nY0 (m)=%16.4f\n\nlC(rad)=%16.13f\npC(rad)=%16.13f\nc =%16.13f\nn1 =%16.13f\nn2 (m) =%16.4f\nXS (m) =%16.4f\nYS (m) =%16.4f\n", par.a, par.e, par.lam0, par.phi0, par.k0, par.x0, par.y0, proj_parm.lamc, proj_parm.phic, proj_parm.c, proj_parm.n1, proj_parm.n2, proj_parm.XS +par.x0, proj_parm.YS + par.y0);*/
}
}} // namespace detail::gstmerc
#endif // doxygen
/*!
\brief Gauss-Schreiber Transverse Mercator (aka Gauss-Laborde Reunion) projection
\ingroup projections
\tparam Geographic latlong point type
\tparam Cartesian xy point type
\tparam Parameters parameter type
\par Projection characteristics
- Cylindrical
- Spheroid
- Ellipsoid
\par Projection parameters
- lat_0: Latitude of origin
- lon_0: Central meridian
- k_0: Scale factor
\par Example
\image html ex_gstmerc.gif
*/
template <typename CalculationType, typename Parameters>
struct gstmerc_spheroid : public detail::gstmerc::base_gstmerc_spheroid<CalculationType, Parameters>
{
inline gstmerc_spheroid(const Parameters& par) : detail::gstmerc::base_gstmerc_spheroid<CalculationType, Parameters>(par)
{
detail::gstmerc::setup_gstmerc(this->m_par, this->m_proj_parm);
}
};
#ifndef DOXYGEN_NO_DETAIL
namespace detail
{
// Static projection
BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::gstmerc, gstmerc_spheroid, gstmerc_spheroid)
// Factory entry(s)
template <typename CalculationType, typename Parameters>
class gstmerc_entry : public detail::factory_entry<CalculationType, Parameters>
{
public :
virtual base_v<CalculationType, Parameters>* create_new(const Parameters& par) const
{
return new base_v_fi<gstmerc_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);
}
};
template <typename CalculationType, typename Parameters>
inline void gstmerc_init(detail::base_factory<CalculationType, Parameters>& factory)
{
factory.add_to_factory("gstmerc", new gstmerc_entry<CalculationType, Parameters>);
}
} // namespace detail
#endif // doxygen
} // namespace projections
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_PROJECTIONS_GSTMERC_HPP
| zcobell/MetOceanViewer | thirdparty/boost_1_67_0/boost/geometry/srs/projections/proj/gstmerc.hpp | C++ | gpl-3.0 | 9,523 |
<?php
/* Copyright (C) 2013-2016 Olivier Geffroy <jeff@jeffinfo.com>
* Copyright (C) 2013-2016 Alexandre Spangaro <aspangaro@zendsi.com>
* Copyright (C) 2014-2015 Ari Elbaz (elarifr) <github@accedinfo.com>
* Copyright (C) 2014-2016 Florian Henry <florian.henry@open-concept.pro>
* Copyright (C) 2014 Juanjo Menent <jmenent@2byte.es>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* \file htdocs/accountancy/customer/lines.php
* \ingroup Advanced accountancy
* \brief Page of detail of the lines of ventilation of invoices customers
*/
require '../../main.inc.php';
// Class
require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php';
require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
// Langs
$langs->load("bills");
$langs->load("compta");
$langs->load("main");
$langs->load("accountancy");
$langs->load("productbatch");
$account_parent = GETPOST('account_parent');
$changeaccount = GETPOST('changeaccount');
// Search Getpost
$search_lineid = GETPOST('search_lineid', 'int');
$search_ref = GETPOST('search_ref', 'alpha');
$search_invoice = GETPOST('search_invoice', 'alpha');
$search_label = GETPOST('search_label', 'alpha');
$search_desc = GETPOST('search_desc', 'alpha');
$search_amount = GETPOST('search_amount', 'alpha');
$search_account = GETPOST('search_account', 'alpha');
$search_vat = GETPOST('search_vat', 'alpha');
$search_day=GETPOST("search_day","int");
$search_month=GETPOST("search_month","int");
$search_year=GETPOST("search_year","int");
$search_country = GETPOST('search_country', 'alpha');
$search_tvaintra = GETPOST('search_tvaintra', 'alpha');
// Load variable for pagination
$limit = GETPOST('limit','int')?GETPOST('limit', 'int'):(empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)?$conf->liste_limit:$conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION);
$sortfield = GETPOST('sortfield', 'alpha');
$sortorder = GETPOST('sortorder', 'alpha');
$page = GETPOST('page', 'int');
if (empty($page) || $page < 0) $page = 0;
$pageprev = $page - 1;
$pagenext = $page + 1;
$offset = $limit * $page;
if (! $sortfield)
$sortfield = "f.datef, f.facnumber, fd.rowid";
if (! $sortorder) {
if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE > 0) {
$sortorder = "DESC";
}
}
// Security check
if ($user->societe_id > 0)
accessforbidden();
if (! $user->rights->accounting->bind->write)
accessforbidden();
$formaccounting = new FormAccounting($db);
/*
* Actions
*/
// Purge search criteria
if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers
{
$search_lineid = '';
$search_ref = '';
$search_invoice = '';
$search_label = '';
$search_desc = '';
$search_amount = '';
$search_account = '';
$search_vat = '';
$search_day = '';
$search_month = '';
$search_year = '';
$search_country = '';
$search_tvaintra = '';
}
if (is_array($changeaccount) && count($changeaccount) > 0) {
$error = 0;
if (! (GETPOST('account_parent','int') >= 0))
{
$error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Account")), null, 'errors');
}
$db->begin();
if (! $error)
{
$sql1 = "UPDATE " . MAIN_DB_PREFIX . "facturedet as l";
$sql1 .= " SET l.fk_code_ventilation=" . (GETPOST('account_parent','int') > 0 ? GETPOST('account_parent','int') : '0');
$sql1 .= ' WHERE l.rowid IN (' . implode(',', $changeaccount) . ')';
dol_syslog('accountancy/customer/lines.php::changeaccount sql= ' . $sql1);
$resql1 = $db->query($sql1);
if (! $resql1) {
$error ++;
setEventMessages($db->lasterror(), null, 'errors');
}
if (! $error) {
$db->commit();
setEventMessages($langs->trans('Save'), null, 'mesgs');
} else {
$db->rollback();
setEventMessages($db->lasterror(), null, 'errors');
}
$account_parent = ''; // Protection to avoid to mass apply it a second time
}
}
/*
* View
*/
$form = new Form($db);
$formother = new FormOther($db);
llxHeader('', $langs->trans("CustomersVentilation") . ' - ' . $langs->trans("Dispatched"));
print '<script type="text/javascript">
$(function () {
$(\'#select-all\').click(function(event) {
// Iterate each checkbox
$(\':checkbox\').each(function() {
this.checked = true;
});
});
$(\'#unselect-all\').click(function(event) {
// Iterate each checkbox
$(\':checkbox\').each(function() {
this.checked = false;
});
});
});
</script>';
/*
* Customer Invoice lines
*/
$sql = "SELECT f.rowid as facid, f.facnumber, f.type, f.datef, f.ref_client,";
$sql .= " fd.rowid, fd.description, fd.product_type, fd.total_ht, fd.total_tva, fd.tva_tx, fd.vat_src_code, fd.total_ttc,";
$sql .= " s.rowid as socid, s.nom as name, s.code_compta, s.code_client,";
$sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.accountancy_code_sell, aa.rowid as fk_compte, aa.account_number, aa.label as label_compte,";
$sql .= " fd.situation_percent, co.label as country, s.tva_intra";
$sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd";
$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = fd.fk_product";
$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture";
$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid = f.fk_soc";
$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as co ON co.rowid = s.fk_pays ";
$sql .= " WHERE fd.fk_code_ventilation > 0 ";
$sql .= " AND f.entity IN (" . getEntity('facture', 0) . ")"; // We don't share object for accountancy
$sql .= " AND f.fk_statut > 0";
if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
$sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_SITUATION . ")";
} else {
$sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_STANDARD . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_DEPOSIT . "," . Facture::TYPE_SITUATION . ")";
}
if ($search_lineid) {
$sql .= natural_search("fd.rowid", $search_lineid, 1);
}
if (strlen(trim($search_invoice))) {
$sql .= natural_search("f.facnumber", $search_invoice);
}
if (strlen(trim($search_ref))) {
$sql .= natural_search("p.ref", $search_ref);
}
if (strlen(trim($search_label))) {
$sql .= natural_search("p.label", $search_label);
}
if (strlen(trim($search_desc))) {
$sql .= natural_search("fd.description", $search_desc);
}
if (strlen(trim($search_amount))) {
$sql .= natural_search("fd.total_ht", $search_amount, 1);
}
if (strlen(trim($search_account))) {
$sql .= natural_search("aa.account_number", $search_account);
}
if (strlen(trim($search_vat))) {
$sql .= natural_search("fd.tva_tx", price2num($search_vat), 1);
}
if ($search_month > 0)
{
if ($search_year > 0 && empty($search_day))
$sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($search_year,$search_month,false))."' AND '".$db->idate(dol_get_last_day($search_year,$search_month,false))."'";
else if ($search_year > 0 && ! empty($search_day))
$sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $search_month, $search_day, $search_year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $search_month, $search_day, $search_year))."'";
else
$sql.= " AND date_format(f.datef, '%m') = '".$db->escape($search_month)."'";
}
else if ($search_year > 0)
{
$sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($search_year,1,false))."' AND '".$db->idate(dol_get_last_day($search_year,12,false))."'";
}
if (strlen(trim($search_country))) {
$sql .= natural_search("co.label", $search_country);
}
if (strlen(trim($search_tvaintra))) {
$sql .= natural_search("s.tva_intra", $search_tvaintra);
}
$sql .= " AND f.entity IN (" . getEntity('facture', 0) . ")"; // We don't share object for accountancy
$sql .= $db->order($sortfield, $sortorder);
// Count total nb of records
$nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
}
$sql .= $db->plimit($limit + 1, $offset);
dol_syslog("/accountancy/customer/lines.php", LOG_DEBUG);
$result = $db->query($sql);
if ($result) {
$num_lines = $db->num_rows($result);
$i = 0;
$param='';
if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
if ($search_invoice) $param .= "&search_invoice=" . urlencode($search_invoice);
if ($search_ref) $param .= "&search_ref=" . urlencode($search_ref);
if ($search_label) $param .= "&search_label=" . urlencode($search_label);
if ($search_desc) $param .= "&search_desc=" . urlencode($search_desc);
if ($search_account) $param .= "&search_account=" . urlencode($search_account);
if ($search_vat) $param .= "&search_vat=" . urlencode($search_vat);
if ($search_day) $param .= '&search_day='.urlencode($search_day);
if ($search_month) $param .= '&search_month='.urlencode($search_month);
if ($search_year) $param .= '&search_year='.urlencode($search_year);
if ($search_country) $param .= "&search_country=" . urlencode($search_country);
if ($search_tvaintra) $param .= "&search_tvaintra=" . urlencode($search_tvaintra);
print '<form action="' . $_SERVER["PHP_SELF"] . '" method="post">' . "\n";
print '<input type="hidden" name="action" value="ventil">';
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
print '<input type="hidden" name="page" value="'.$page.'">';
print_barre_liste($langs->trans("InvoiceLinesDone"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num_lines, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit);
print $langs->trans("DescVentilDoneCustomer") . '<br>';
print '<br><div class="inline-block divButAction">' . $langs->trans("ChangeAccount") . '<br>';
print $formaccounting->select_account($account_parent, 'account_parent', 2, array(), 0, 0, 'maxwidth300 maxwidthonsmartphone valignmiddle');
print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("ChangeBinding") . '"/></div>';
$moreforfilter = '';
print '<div class="div-table-responsive">';
print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
print '<tr class="liste_titre_filter">';
print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_lineid" value="' . dol_escape_htmltag($search_lineid) . '""></td>';
print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_invoice" value="' . dol_escape_htmltag($search_invoice) . '"></td>';
print '<td class="liste_titre center">';
if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="search_day" value="'.$search_day.'">';
print '<input class="flat" type="text" size="1" maxlength="2" name="search_month" value="'.$search_month.'">';
$formother->select_year($search_year,'search_year',1, 20, 5);
print '</td>';
print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_ref" value="' . dol_escape_htmltag($search_ref) . '"></td>';
//print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_label" value="' . dol_escape_htmltag($search_label) . '"></td>';
print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_desc" value="' . dol_escape_htmltag($search_desc) . '"></td>';
print '<td class="liste_titre" align="right"><input type="text" class="right flat maxwidth50" name="search_amount" value="' . dol_escape_htmltag($search_amount) . '"></td>';
print '<td class="liste_titre" align="right"><input type="text" class="right flat maxwidth50" placeholder="%" name="search_vat" size="1" value="' . dol_escape_htmltag($search_vat) . '"></td>';
print '<td class="liste_titre" align="center"><input type="text" class="flat maxwidth50" name="search_account" value="' . dol_escape_htmltag($search_account) . '"></td>';
print '<td class="liste_titre" align="center"><input type="text" class="flat maxwidth50" name="search_country" value="' . dol_escape_htmltag($search_country) . '"></td>';
print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_tavintra" value="' . dol_escape_htmltag($search_tavintra) . '"></td>';
print '<td class="liste_titre" align="center">';
$searchpicto=$form->showFilterButtons();
print $searchpicto;
print "</td></tr>\n";
print '<tr class="liste_titre">';
print_liste_field_titre("LineId", $_SERVER["PHP_SELF"], "fd.rowid", "", $param, '', $sortfield, $sortorder);
print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.facnumber", "", $param, '', $sortfield, $sortorder);
print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "f.datef, f.facnumber, fd.rowid", "", $param, 'align="center"', $sortfield, $sortorder);
print_liste_field_titre("ProductRef", $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder);
//print_liste_field_titre("ProductLabel", $_SERVER["PHP_SELF"], "p.label", "", $param, '', $sortfield, $sortorder);
print_liste_field_titre("Description", $_SERVER["PHP_SELF"], "fd.description", "", $param, '', $sortfield, $sortorder);
print_liste_field_titre("Amount", $_SERVER["PHP_SELF"], "fd.total_ht", "", $param, 'align="right"', $sortfield, $sortorder);
print_liste_field_titre("VATRate", $_SERVER["PHP_SELF"], "fd.tva_tx", "", $param, 'align="right"', $sortfield, $sortorder);
print_liste_field_titre("Account", $_SERVER["PHP_SELF"], "aa.account_number", "", $param, 'align="center"', $sortfield, $sortorder);
print_liste_field_titre("Country", $_SERVER["PHP_SELF"], "co.label", "", $param, 'align="center"', $sortfield, $sortorder);
print_liste_field_titre("VATIntra", $_SERVER["PHP_SELF"], "s.tva_intra", "", $param, '', $sortfield, $sortorder);
$clickpicto=$form->showCheckAddButtons();
print_liste_field_titre($clickpicto, '', '', '', '', 'align="center"');
print "</tr>\n";
$facture_static = new Facture($db);
$product_static = new Product($db);
while ( $objp = $db->fetch_object($result) ) {
$codecompta = length_accountg($objp->account_number) . ' - ' . $objp->label_compte;
$facture_static->ref = $objp->facnumber;
$facture_static->id = $objp->facid;
$product_static->ref = $objp->product_ref;
$product_static->id = $objp->product_id;
$product_static->type = $objp->product_type;
$product_static->label = $objp->product_label;
print '<tr class="oddeven">';
print '<td>' . $objp->rowid . '</td>';
// Ref Invoice
print '<td>' . $facture_static->getNomUrl(1) . '</td>';
print '<td align="center">' . dol_print_date($db->jdate($objp->datef), 'day') . '</td>';
// Ref Product
print '<td>';
if ($product_static->id)
print $product_static->getNomUrl(1);
if ($objp->product_label) print '<br>'.$objp->product_label;
print '</td>';
print '<td>';
$text = dolGetFirstLineOfText(dol_string_nohtmltag($objp->description));
$trunclength = empty($conf->global->ACCOUNTING_LENGTH_DESCRIPTION) ? 32 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION;
print $form->textwithtooltip(dol_trunc($text,$trunclength), $objp->description);
print '</td>';
print '<td align="right">' . price($objp->total_ht) . '</td>';
print '<td align="right">' . vatrate($objp->tva_tx.($objp->vat_src_code?' ('.$objp->vat_src_code.')':'')) . '</td>';
print '<td align="center">';
print $codecompta . ' <a href="./card.php?id=' . $objp->rowid . '&backtopage='.urlencode($_SERVER["PHP_SELF"].($param?'?'.$param:'')).'">';
print img_edit();
print '</a>';
print '</td>';
print '<td>' . $objp->country .'</td>';
print '<td>' . $objp->tva_intra . '</td>';
print '<td class="center"><input type="checkbox" class="checkforaction" name="changeaccount[]" value="' . $objp->rowid . '"/></td>';
print "</tr>";
$i ++;
}
print "</table>";
print "</div>";
if ($nbtotalofrecords > $limit) {
print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num_lines, $nbtotalofrecords, '', 0, '', '', $limit, 1);
}
print '</form>';
} else {
print $db->lasterror();
}
llxFooter();
$db->close();
| All-3kcis/dolibarr | htdocs/accountancy/customer/lines.php | PHP | gpl-3.0 | 17,729 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=../../../../../../../libc/constant.SYS_umount2.html">
</head>
<body>
<p>Redirecting to <a href="../../../../../../../libc/constant.SYS_umount2.html">../../../../../../../libc/constant.SYS_umount2.html</a>...</p>
<script>location.replace("../../../../../../../libc/constant.SYS_umount2.html" + location.search + location.hash);</script>
</body>
</html> | surrsurus/edgequest | doc/libc/unix/notbsd/linux/other/b64/not_x32/constant.SYS_umount2.html | HTML | mpl-2.0 | 445 |
// Constructing calls should throw if !callee->isInterpretedConstructor().
// This tests the polymorphic call path.
for (var i=0; i<20; i++)
Function.prototype();
var funs = [
function() { return 1; },
function() { return 2; },
function() { return 3; },
function() { return 4; },
function() { return 5; },
function() { return 6; },
function() { return 7; },
function() { return 8; },
function() { return 9; },
function() { return 10; },
Function.prototype
];
function f(callee) {
new callee;
}
function g() {
var c = 0;
for (var i=0; i<50; i++) {
try {
f(funs[i % funs.length]);
} catch (e) {
assertEq(e.message.contains("not a constructor"), true);
c++;
}
}
assertEq(c, 4);
}
g();
| kostaspl/SpiderMonkey38 | js/src/jit-test/tests/baseline/bug892787-2.js | JavaScript | mpl-2.0 | 771 |
/*
Copyright 2014 SAP SE
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package driver
import (
"context"
"crypto/tls"
"crypto/x509"
"database/sql/driver"
"fmt"
"io/ioutil"
"net/url"
"strconv"
"sync"
)
/*
A Connector represents a hdb driver in a fixed configuration.
A Connector can be passed to sql.OpenDB (starting from go 1.10) allowing users to bypass a string based data source name.
*/
type Connector struct {
mu sync.RWMutex
host, username, password string
locale string
bufferSize, fetchSize, timeout int
tlsConfig *tls.Config
}
func newConnector() *Connector {
return &Connector{
fetchSize: DefaultFetchSize,
timeout: DefaultTimeout,
}
}
// NewBasicAuthConnector creates a connector for basic authentication.
func NewBasicAuthConnector(host, username, password string) *Connector {
c := newConnector()
c.host = host
c.username = username
c.password = password
return c
}
// NewDSNConnector creates a connector from a data source name.
func NewDSNConnector(dsn string) (*Connector, error) {
c := newConnector()
url, err := url.Parse(dsn)
if err != nil {
return nil, err
}
c.host = url.Host
if url.User != nil {
c.username = url.User.Username()
c.password, _ = url.User.Password()
}
var certPool *x509.CertPool
for k, v := range url.Query() {
switch k {
default:
return nil, fmt.Errorf("URL parameter %s is not supported", k)
case DSNFetchSize:
if len(v) == 0 {
continue
}
fetchSize, err := strconv.Atoi(v[0])
if err != nil {
return nil, fmt.Errorf("failed to parse fetchSize: %s", v[0])
}
if fetchSize < minFetchSize {
c.fetchSize = minFetchSize
} else {
c.fetchSize = fetchSize
}
case DSNTimeout:
if len(v) == 0 {
continue
}
timeout, err := strconv.Atoi(v[0])
if err != nil {
return nil, fmt.Errorf("failed to parse timeout: %s", v[0])
}
if timeout < minTimeout {
c.timeout = minTimeout
} else {
c.timeout = timeout
}
case DSNLocale:
if len(v) == 0 {
continue
}
c.locale = v[0]
case DSNTLSServerName:
if len(v) == 0 {
continue
}
if c.tlsConfig == nil {
c.tlsConfig = &tls.Config{}
}
c.tlsConfig.ServerName = v[0]
case DSNTLSInsecureSkipVerify:
if len(v) == 0 {
continue
}
var err error
b := true
if v[0] != "" {
b, err = strconv.ParseBool(v[0])
if err != nil {
return nil, fmt.Errorf("failed to parse InsecureSkipVerify (bool): %s", v[0])
}
}
if c.tlsConfig == nil {
c.tlsConfig = &tls.Config{}
}
c.tlsConfig.InsecureSkipVerify = b
case DSNTLSRootCAFile:
for _, fn := range v {
rootPEM, err := ioutil.ReadFile(fn)
if err != nil {
return nil, err
}
if certPool == nil {
certPool = x509.NewCertPool()
}
if ok := certPool.AppendCertsFromPEM(rootPEM); !ok {
return nil, fmt.Errorf("failed to parse root certificate - filename: %s", fn)
}
}
if certPool != nil {
if c.tlsConfig == nil {
c.tlsConfig = &tls.Config{}
}
c.tlsConfig.RootCAs = certPool
}
}
}
return c, nil
}
// Host returns the host of the connector.
func (c *Connector) Host() string {
return c.host
}
// Username returns the username of the connector.
func (c *Connector) Username() string {
return c.username
}
// Password returns the password of the connector.
func (c *Connector) Password() string {
return c.password
}
// Locale returns the locale of the connector.
func (c *Connector) Locale() string {
c.mu.RLock()
defer c.mu.RUnlock()
return c.locale
}
/*
SetLocale sets the locale of the connector.
For more information please see DSNLocale.
*/
func (c *Connector) SetLocale(locale string) {
c.mu.Lock()
c.locale = locale
c.mu.Unlock()
}
// FetchSize returns the fetchSize of the connector.
func (c *Connector) FetchSize() int {
c.mu.RLock()
defer c.mu.RUnlock()
return c.fetchSize
}
/*
SetFetchSize sets the fetchSize of the connector.
For more information please see DSNFetchSize.
*/
func (c *Connector) SetFetchSize(fetchSize int) error {
c.mu.Lock()
defer c.mu.Unlock()
if fetchSize < minFetchSize {
fetchSize = minFetchSize
}
c.fetchSize = fetchSize
return nil
}
// Timeout returns the timeout of the connector.
func (c *Connector) Timeout() int {
c.mu.RLock()
defer c.mu.RUnlock()
return c.timeout
}
/*
SetTimeout sets the timeout of the connector.
For more information please see DSNTimeout.
*/
func (c *Connector) SetTimeout(timeout int) error {
c.mu.Lock()
defer c.mu.Unlock()
if timeout < minTimeout {
timeout = minTimeout
}
c.timeout = timeout
return nil
}
// TLSConfig returns the TLS configuration of the connector.
func (c *Connector) TLSConfig() *tls.Config {
c.mu.RLock()
defer c.mu.RUnlock()
return c.tlsConfig
}
// SetTLSConfig sets the TLS configuration of the connector.
func (c *Connector) SetTLSConfig(tlsConfig *tls.Config) error {
c.mu.Lock()
defer c.mu.Unlock()
c.tlsConfig = tlsConfig
return nil
}
// BasicAuthDSN return the connector DSN for basic authentication.
func (c *Connector) BasicAuthDSN() string {
values := url.Values{}
if c.locale != "" {
values.Set(DSNLocale, c.locale)
}
if c.fetchSize != 0 {
values.Set(DSNFetchSize, fmt.Sprintf("%d", c.fetchSize))
}
if c.timeout != 0 {
values.Set(DSNTimeout, fmt.Sprintf("%d", c.timeout))
}
return (&url.URL{
Scheme: DriverName,
User: url.UserPassword(c.username, c.password),
Host: c.host,
RawQuery: values.Encode(),
}).String()
}
// Connect implements the database/sql/driver/Connector interface.
func (c *Connector) Connect(ctx context.Context) (driver.Conn, error) {
return newConn(ctx, c)
}
// Driver implements the database/sql/driver/Connector interface.
func (c *Connector) Driver() driver.Driver {
return drv
}
| calgaryscientific/consul | vendor/github.com/SAP/go-hdb/driver/connector.go | GO | mpl-2.0 | 6,345 |
package lux.query.parser;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.queryparser.ext.ExtensionQuery;
import org.apache.lucene.queryparser.ext.ParserExtension;
import org.apache.lucene.queryparser.xml.ParserException;
import org.apache.lucene.queryparser.classic.ParseException;
class NodeParser extends ParserExtension {
private final String textFieldName;
private final String elementTextFieldName;
private final String attributeTextFieldName;
NodeQueryBuilder queryBuilder;
NodeParser (String textFieldName, String elementTextFieldName, String attributeTextFieldName, NodeQueryBuilder queryBuilder) {
this.queryBuilder = queryBuilder;
this.textFieldName = textFieldName;
this.elementTextFieldName = elementTextFieldName;
this.attributeTextFieldName = attributeTextFieldName;
}
@Override
public org.apache.lucene.search.Query parse(ExtensionQuery query) throws ParseException {
String field = query.getField();
String term = query.getRawQueryString();
// create either a term query or a phrase query (or a span?)
try {
if (StringUtils.isEmpty(field)) {
return queryBuilder.parseQueryTerm(textFieldName, field, term, 1.0f);
} else if (field.charAt(0) == '@') {
return queryBuilder.parseQueryTerm(attributeTextFieldName, field.substring(1), term, 1.0f);
} else {
return queryBuilder.parseQueryTerm(elementTextFieldName, field, term, 1.0f);
}
} catch (ParserException e) {
throw new ParseException (e.getMessage());
}
}
} | coyotesqrl/lux | src/main/java/lux/query/parser/NodeParser.java | Java | mpl-2.0 | 1,682 |
<?php
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* 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 Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
namespace Shopware\Bundle\StoreFrontBundle\Gateway\DBAL;
use Doctrine\DBAL\Connection;
use Shopware\Bundle\StoreFrontBundle\Gateway\ListProductQueryHelperInterface;
use Shopware\Bundle\StoreFrontBundle\Struct;
/**
* @category Shopware
*
* @copyright Copyright (c) shopware AG (http://www.shopware.de)
*/
class ListProductQueryHelper implements ListProductQueryHelperInterface
{
/**
* The FieldHelper class is used for the
* different table column definitions.
*
* This class helps to select each time all required
* table data for the store front.
*
* Additionally the field helper reduce the work, to
* select in a second step the different required
* attribute tables for a parent table.
*
* @var FieldHelper
*/
protected $fieldHelper;
/**
* @var \Shopware_Components_Config
*/
protected $config;
/**
* @var Connection
*/
protected $connection;
public function __construct(FieldHelper $fieldHelper, \Shopware_Components_Config $config, Connection $connection)
{
$this->fieldHelper = $fieldHelper;
$this->config = $config;
$this->connection = $connection;
}
/**
* @return \Doctrine\DBAL\Query\QueryBuilder
*/
public function getQuery(array $numbers, Struct\ShopContextInterface $context)
{
$esdQuery = $this->getEsdQuery();
$customerGroupQuery = $this->getCustomerGroupQuery();
$availableVariantQuery = $this->getHasAvailableVariantQuery();
$fallbackPriceQuery = $this->getPriceCountQuery(':fallback');
$query = $this->connection->createQueryBuilder();
$query->select($this->fieldHelper->getArticleFields())
->addSelect($this->fieldHelper->getTopSellerFields())
->addSelect($this->fieldHelper->getVariantFields())
->addSelect($this->fieldHelper->getUnitFields())
->addSelect($this->fieldHelper->getTaxFields())
->addSelect($this->fieldHelper->getPriceGroupFields())
->addSelect($this->fieldHelper->getManufacturerFields())
->addSelect($this->fieldHelper->getEsdFields())
->addSelect('(' . $esdQuery->getSQL() . ') as __product_has_esd')
->addSelect('(' . $customerGroupQuery->getSQL() . ') as __product_blocked_customer_groups')
->addSelect('(' . $availableVariantQuery->getSQL() . ') as __product_has_available_variants')
->addSelect('(' . $fallbackPriceQuery->getSQL() . ') as __product_fallback_price_count')
;
$query->setParameter(':fallback', $context->getFallbackCustomerGroup()->getKey());
if ($context->getCurrentCustomerGroup()->getId() !== $context->getFallbackCustomerGroup()->getId()) {
$customerPriceQuery = $this->getPriceCountQuery(':current');
$query->addSelect('(' . $customerPriceQuery->getSQL() . ') as __product_custom_price_count');
$query->setParameter(':current', $context->getCurrentCustomerGroup()->getKey());
}
$query->from('s_articles_details', 'variant')
->innerJoin('variant', 's_articles', 'product', 'product.id = variant.articleID')
->innerJoin('product', 's_core_tax', 'tax', 'tax.id = product.taxID')
->leftJoin('variant', 's_core_units', 'unit', 'unit.id = variant.unitID')
->leftJoin('product', 's_articles_supplier', 'manufacturer', 'manufacturer.id = product.supplierID')
->leftJoin('product', 's_core_pricegroups', 'priceGroup', 'priceGroup.id = product.pricegroupID')
->leftJoin('variant', 's_articles_attributes', 'productAttribute', 'productAttribute.articledetailsID = variant.id')
->leftJoin('product', 's_articles_supplier_attributes', 'manufacturerAttribute', 'manufacturerAttribute.supplierID = product.supplierID')
->leftJoin('product', 's_articles_top_seller_ro', 'topSeller', 'topSeller.article_id = product.id')
->leftJoin('variant', 's_articles_esd', 'esd', 'esd.articledetailsID = variant.id')
->leftJoin('esd', 's_articles_esd_attributes', 'esdAttribute', 'esdAttribute.esdID = esd.id')
->where('variant.ordernumber IN (:numbers)')
->andWhere('variant.active = 1')
->andWhere('product.active = 1')
->setParameter(':numbers', $numbers, Connection::PARAM_STR_ARRAY);
if ($this->config->get('hideNoInstock')) {
$query->andHaving('__product_has_available_variants >= 1');
}
$this->fieldHelper->addProductTranslation($query, $context);
$this->fieldHelper->addVariantTranslation($query, $context);
$this->fieldHelper->addManufacturerTranslation($query, $context);
$this->fieldHelper->addUnitTranslation($query, $context);
$this->fieldHelper->addEsdTranslation($query, $context);
return $query;
}
/**
* @param string $key
*
* @return \Doctrine\DBAL\Query\QueryBuilder
*/
private function getPriceCountQuery($key)
{
$query = $this->connection->createQueryBuilder();
if ($this->config->get('calculateCheapestPriceWithMinPurchase')) {
$query->addSelect('COUNT(DISTINCT ROUND(prices.price * priceVariant.minpurchase, 2)) as priceCount');
} else {
$query->addSelect('COUNT(DISTINCT ROUND(prices.price, 2)) as priceCount');
}
$query->from('s_articles_prices', 'prices')
->innerJoin(
'prices',
's_articles_details',
'priceVariant',
'priceVariant.id = prices.articledetailsID and priceVariant.active = 1'
)
->andWhere('prices.from = 1')
->andWhere('prices.pricegroup = ' . $key)
->andWhere('prices.articleID = product.id');
if ($this->config->get('hideNoInStock')) {
$query->andWhere('(priceVariant.laststock * priceVariant.instock) >= (priceVariant.laststock * priceVariant.minpurchase)');
}
return $query;
}
/**
* @return \Doctrine\DBAL\Query\QueryBuilder
*/
private function getEsdQuery()
{
$query = $this->connection->createQueryBuilder();
$query->select('1')
->from('s_articles_esd', 'variantEsd')
->where('variantEsd.articleID = product.id')
->setMaxResults(1);
return $query;
}
/**
* @return \Doctrine\DBAL\Query\QueryBuilder
*/
private function getCustomerGroupQuery()
{
$query = $this->connection->createQueryBuilder();
$query->select("GROUP_CONCAT(customerGroups.customergroupId SEPARATOR '|')")
->from('s_articles_avoid_customergroups', 'customerGroups')
->where('customerGroups.articleID = product.id');
return $query;
}
/**
* @return \Doctrine\DBAL\Query\QueryBuilder
*/
private function getHasAvailableVariantQuery()
{
$query = $this->connection->createQueryBuilder();
$query->select('COUNT(availableVariant.id)')
->from('s_articles_details', 'availableVariant')
->where('availableVariant.articleID = product.id')
->andWhere('availableVariant.active = 1')
->andWhere('(availableVariant.laststock * availableVariant.instock) >= (availableVariant.laststock * availableVariant.minpurchase)');
return $query;
}
}
| wlwwt/shopware | engine/Shopware/Bundle/StoreFrontBundle/Gateway/DBAL/ListProductQueryHelper.php | PHP | agpl-3.0 | 8,405 |
'use strict';
var mongoose = require('mongoose');
exports.register = function(server, options, next) {
server.route({
method: 'GET',
path: '/account',
handler: function(request, reply) {
var User = mongoose.model('User');
User.findById(request.auth.credentials.userId, function(err, user) {
if (err) {
return reply(err);
}
reply.view('account/index', {
user: user,
script: 'account/public'
});
});
}
});
next();
};
exports.register.attributes = {
name: 'web/account'
};
| Claw24/tutsoketio | server/web/account/index.js | JavaScript | agpl-3.0 | 581 |
/*
Released as open source by NCC Group Plc - http://www.nccgroup.com/
Developed by David.Middlehurst (@dtmsecurity), david dot middlehurst at nccgroup dot com
https://github.com/nccgroup/UPnP-Pentest-Toolkit
Released under AGPL see LICENSE for more information
This tool is a proof of concept and is intended to be used for research purposes in a trusted environment.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Xml;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Concurrent;
namespace WinUPnPFun
{
public partial class Learn : Form
{
BackgroundWorker bw = new BackgroundWorker();
BlockingCollection<Form1.Target> Targets = new BlockingCollection<Form1.Target>();
List<String> DeviceURLs = new List<String>();
Dictionary<String, Byte[]> downloadedURLs = new Dictionary<string, Byte[]>();
Dictionary<String, String> mimeTypes = new Dictionary<string, string>();
Dictionary<String, String> actions = new Dictionary<string, string>();
Dictionary<String, List<String>> actionDataTypes = new Dictionary<string, List<String>>();
Dictionary<String, String> requestActions = new Dictionary<string, string>();
string deviceDescString = "";
Dictionary<String, String> localResourceReplacements = new Dictionary<string, string>();
bool waitUntilSave = false;
public Learn(BlockingCollection<Form1.Target> existingTargets)
{
InitializeComponent();
Targets = existingTargets;
}
[System.Serializable]
public class device{
public string deviceName;
public string deviceDescription;
public Dictionary<String, Byte[]> downloadedURLs;
public Dictionary<String, String> mimeTypes;
public Dictionary<String, String> actions;
public Dictionary<String, List<String>> actionDataTypes;
public Dictionary<String, String> requestActions;
public List<String> serviceTypes;
public string UDN;
}
private void Learn_Load(object sender, EventArgs e)
{
bw.WorkerSupportsCancellation = true;
bw.WorkerReportsProgress = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
foreach (Form1.Target Target in Targets)
{
if (!DeviceURLs.Contains(Target.targetService.Device.DocumentURL))
{
DeviceURLs.Add(Target.targetService.Device.DocumentURL);
checkedListBox1.Items.Add(Target.targetService.Device.DocumentURL, CheckState.Unchecked);
}
}
}
private void TraverseNodes(XmlNodeList nodes,string deviceURL)
{
foreach (XmlNode node in nodes)
{
string nodeName = node.Name;
Regex regex = new Regex(@"URL$");
Match match = regex.Match(nodeName.ToUpper());
if(match.Success){
string localResourceID = Guid.NewGuid().ToString();
Uri uriResult;
bool result = Uri.TryCreate(node.InnerText, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
if (!result)
{
Uri baseURI = new Uri(deviceURL);
Uri actualURL = new Uri(baseURI, node.InnerText);
uriResult = actualURL;
}
try
{
WebRequest r = HttpWebRequest.Create(uriResult);
r.Timeout = 10000;
WebResponse wres = r.GetResponse();
string contentType = wres.ContentType;
Stream ress = wres.GetResponseStream();
MemoryStream streamReader = new MemoryStream();
ress.CopyTo(streamReader);
Byte[] saveData = streamReader.ToArray();
downloadedURLs.Add(localResourceID, saveData);
mimeTypes.Add(localResourceID, contentType);
deviceDescString = deviceDescString + "Saved:\r\n" + uriResult + "\r\nLocal Resource:\r\n" + localResourceID + "\r\nContent Type: "+ contentType + "\r\nSize:\r\n" + saveData.Count().ToString() + " bytes\r\n\r\n";
}
catch
{
}
if (node.InnerText.Length > 3)
{
if (!localResourceReplacements.ContainsKey(node.InnerText))
{
localResourceReplacements.Add(node.InnerText, "/resource/?localResourceID=" + localResourceID);
}
}
}
TraverseNodes(node.ChildNodes,deviceURL);
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemChecked(i))
{
downloadedURLs.Clear();
mimeTypes.Clear();
actions.Clear();
actionDataTypes.Clear();
requestActions.Clear();
string deviceURL = (string)checkedListBox1.Items[i];
string deviceName = "";
List<String> servceTypes = new List<String>();
string deviceUDN = "";
string sep = "--------------------------------------------------------------------------------------------------------------------------------\r\n";
deviceDescString = deviceDescString + sep + "Device:\r\n " + deviceURL + "\r\n" + sep + "\r\n";
foreach (Form1.Target Target in Targets)
{
if (Target.targetService.Device.DocumentURL == deviceURL)
{
deviceDescString = deviceDescString + "Action: " + Target.actionDesc.Name + "\r\n\r\n";
deviceDescString = deviceDescString + "Base SOAP Response:\r\n"+Target.soapResponse + "\r\n\r\n";
if (!actions.ContainsKey(Target.actionDesc.Name))
{
actions.Add(Target.actionDesc.Name, Target.soapResponse);
}
if (!actionDataTypes.ContainsKey(Target.actionDesc.Name))
{
actionDataTypes.Add(Target.actionDesc.Name, Target.dataTypes);
}
if (!requestActions.ContainsKey(Target.actionDesc.Name))
{
requestActions.Add(Target.actionDesc.Name, Target.soapRequest);
}
deviceName = Target.targetService.Device.FriendlyName;
deviceUDN = Target.targetService.Device.UniqueDeviceName;
servceTypes.Add(Target.targetService.Device.Type);
}
}
localResourceReplacements.Clear();
XmlDocument desc = new XmlDocument();
string newDeviceDesc = "";
try
{
WebRequest r = HttpWebRequest.Create(deviceURL);
r.Timeout = 10000;
WebResponse wres = r.GetResponse();
Stream ress = wres.GetResponseStream();
desc.Load(ress);
XmlElement root = desc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("*");
TraverseNodes(nodes,deviceURL);
newDeviceDesc = desc.InnerXml.ToString();
foreach(KeyValuePair<string, string> entry in localResourceReplacements)
{
newDeviceDesc = newDeviceDesc.Replace(entry.Key,entry.Value);
}
deviceDescString = deviceDescString + newDeviceDesc;
}
catch(Exception err)
{
MessageBox.Show(err.ToString());
}
device learnedDevice = new device();
learnedDevice.deviceDescription = newDeviceDesc;
learnedDevice.downloadedURLs = downloadedURLs;
learnedDevice.mimeTypes = mimeTypes;
learnedDevice.actions = actions;
learnedDevice.actionDataTypes = actionDataTypes;
learnedDevice.deviceName = deviceName;
learnedDevice.serviceTypes = servceTypes;
learnedDevice.UDN = deviceUDN;
bw.ReportProgress(1, learnedDevice);
waitUntilSave = true;
while (waitUntilSave == true)
{
System.Threading.Thread.Sleep(100);
}
deviceDescString = deviceDescString + "\r\n";
}
}
}
public static void saveDeviceToFile(string fileName, device saveDevice)
{
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, saveDevice);
memoryStream.Flush();
memoryStream.Position = 0;
string base64Device = Convert.ToBase64String(memoryStream.ToArray());
System.IO.StreamWriter resultsFile = new System.IO.StreamWriter(fileName);
resultsFile.WriteLine(base64Device);
resultsFile.Close();
}
public static device getDeviceFromFile(string fileName)
{
string base64Device = System.IO.File.ReadAllText(fileName);
MemoryStream deviceStream = new MemoryStream(Convert.FromBase64String(base64Device));
BinaryFormatter deviceBinary = new BinaryFormatter();
device outputDevice = (device)deviceBinary.Deserialize(deviceStream);
return outputDevice;
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
loadingImage.Visible = false;
textBox1.Text = deviceDescString;
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
device deviceReady = (device)e.UserState;
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
string safeDeviceFileName = rgx.Replace(deviceReady.deviceName, "");
saveFileDialog1.FileName = safeDeviceFileName + ".upt";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (saveFileDialog1.FileName != "")
{
saveDeviceToFile(saveFileDialog1.FileName, deviceReady);
}
}
waitUntilSave = false;
}
private void button1_Click(object sender, EventArgs e)
{
if (!bw.IsBusy)
{
loadingImage.Visible = true;
bw.RunWorkerAsync();
}
}
}
}
| Ike-Clinton/UPnP-Pentest-Toolkit | WinUPnPFun/Learn.cs | C# | agpl-3.0 | 12,208 |
#pragma once
// MESSAGE HIL_STATE_QUATERNION PACKING
#define MAVLINK_MSG_ID_HIL_STATE_QUATERNION 115
typedef struct __mavlink_hil_state_quaternion_t {
uint64_t time_usec; /*< [us] Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number.*/
float attitude_quaternion[4]; /*< Vehicle attitude expressed as normalized quaternion in w, x, y, z order (with 1 0 0 0 being the null-rotation)*/
float rollspeed; /*< [rad/s] Body frame roll / phi angular speed*/
float pitchspeed; /*< [rad/s] Body frame pitch / theta angular speed*/
float yawspeed; /*< [rad/s] Body frame yaw / psi angular speed*/
int32_t lat; /*< [degE7] Latitude*/
int32_t lon; /*< [degE7] Longitude*/
int32_t alt; /*< [mm] Altitude*/
int16_t vx; /*< [cm/s] Ground X Speed (Latitude)*/
int16_t vy; /*< [cm/s] Ground Y Speed (Longitude)*/
int16_t vz; /*< [cm/s] Ground Z Speed (Altitude)*/
uint16_t ind_airspeed; /*< [cm/s] Indicated airspeed*/
uint16_t true_airspeed; /*< [cm/s] True airspeed*/
int16_t xacc; /*< [mG] X acceleration*/
int16_t yacc; /*< [mG] Y acceleration*/
int16_t zacc; /*< [mG] Z acceleration*/
} mavlink_hil_state_quaternion_t;
#define MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN 64
#define MAVLINK_MSG_ID_HIL_STATE_QUATERNION_MIN_LEN 64
#define MAVLINK_MSG_ID_115_LEN 64
#define MAVLINK_MSG_ID_115_MIN_LEN 64
#define MAVLINK_MSG_ID_HIL_STATE_QUATERNION_CRC 4
#define MAVLINK_MSG_ID_115_CRC 4
#define MAVLINK_MSG_HIL_STATE_QUATERNION_FIELD_ATTITUDE_QUATERNION_LEN 4
#if MAVLINK_COMMAND_24BIT
#define MAVLINK_MESSAGE_INFO_HIL_STATE_QUATERNION { \
115, \
"HIL_STATE_QUATERNION", \
16, \
{ { "time_usec", NULL, MAVLINK_TYPE_UINT64_T, 0, 0, offsetof(mavlink_hil_state_quaternion_t, time_usec) }, \
{ "attitude_quaternion", NULL, MAVLINK_TYPE_FLOAT, 4, 8, offsetof(mavlink_hil_state_quaternion_t, attitude_quaternion) }, \
{ "rollspeed", NULL, MAVLINK_TYPE_FLOAT, 0, 24, offsetof(mavlink_hil_state_quaternion_t, rollspeed) }, \
{ "pitchspeed", NULL, MAVLINK_TYPE_FLOAT, 0, 28, offsetof(mavlink_hil_state_quaternion_t, pitchspeed) }, \
{ "yawspeed", NULL, MAVLINK_TYPE_FLOAT, 0, 32, offsetof(mavlink_hil_state_quaternion_t, yawspeed) }, \
{ "lat", NULL, MAVLINK_TYPE_INT32_T, 0, 36, offsetof(mavlink_hil_state_quaternion_t, lat) }, \
{ "lon", NULL, MAVLINK_TYPE_INT32_T, 0, 40, offsetof(mavlink_hil_state_quaternion_t, lon) }, \
{ "alt", NULL, MAVLINK_TYPE_INT32_T, 0, 44, offsetof(mavlink_hil_state_quaternion_t, alt) }, \
{ "vx", NULL, MAVLINK_TYPE_INT16_T, 0, 48, offsetof(mavlink_hil_state_quaternion_t, vx) }, \
{ "vy", NULL, MAVLINK_TYPE_INT16_T, 0, 50, offsetof(mavlink_hil_state_quaternion_t, vy) }, \
{ "vz", NULL, MAVLINK_TYPE_INT16_T, 0, 52, offsetof(mavlink_hil_state_quaternion_t, vz) }, \
{ "ind_airspeed", NULL, MAVLINK_TYPE_UINT16_T, 0, 54, offsetof(mavlink_hil_state_quaternion_t, ind_airspeed) }, \
{ "true_airspeed", NULL, MAVLINK_TYPE_UINT16_T, 0, 56, offsetof(mavlink_hil_state_quaternion_t, true_airspeed) }, \
{ "xacc", NULL, MAVLINK_TYPE_INT16_T, 0, 58, offsetof(mavlink_hil_state_quaternion_t, xacc) }, \
{ "yacc", NULL, MAVLINK_TYPE_INT16_T, 0, 60, offsetof(mavlink_hil_state_quaternion_t, yacc) }, \
{ "zacc", NULL, MAVLINK_TYPE_INT16_T, 0, 62, offsetof(mavlink_hil_state_quaternion_t, zacc) }, \
} \
}
#else
#define MAVLINK_MESSAGE_INFO_HIL_STATE_QUATERNION { \
"HIL_STATE_QUATERNION", \
16, \
{ { "time_usec", NULL, MAVLINK_TYPE_UINT64_T, 0, 0, offsetof(mavlink_hil_state_quaternion_t, time_usec) }, \
{ "attitude_quaternion", NULL, MAVLINK_TYPE_FLOAT, 4, 8, offsetof(mavlink_hil_state_quaternion_t, attitude_quaternion) }, \
{ "rollspeed", NULL, MAVLINK_TYPE_FLOAT, 0, 24, offsetof(mavlink_hil_state_quaternion_t, rollspeed) }, \
{ "pitchspeed", NULL, MAVLINK_TYPE_FLOAT, 0, 28, offsetof(mavlink_hil_state_quaternion_t, pitchspeed) }, \
{ "yawspeed", NULL, MAVLINK_TYPE_FLOAT, 0, 32, offsetof(mavlink_hil_state_quaternion_t, yawspeed) }, \
{ "lat", NULL, MAVLINK_TYPE_INT32_T, 0, 36, offsetof(mavlink_hil_state_quaternion_t, lat) }, \
{ "lon", NULL, MAVLINK_TYPE_INT32_T, 0, 40, offsetof(mavlink_hil_state_quaternion_t, lon) }, \
{ "alt", NULL, MAVLINK_TYPE_INT32_T, 0, 44, offsetof(mavlink_hil_state_quaternion_t, alt) }, \
{ "vx", NULL, MAVLINK_TYPE_INT16_T, 0, 48, offsetof(mavlink_hil_state_quaternion_t, vx) }, \
{ "vy", NULL, MAVLINK_TYPE_INT16_T, 0, 50, offsetof(mavlink_hil_state_quaternion_t, vy) }, \
{ "vz", NULL, MAVLINK_TYPE_INT16_T, 0, 52, offsetof(mavlink_hil_state_quaternion_t, vz) }, \
{ "ind_airspeed", NULL, MAVLINK_TYPE_UINT16_T, 0, 54, offsetof(mavlink_hil_state_quaternion_t, ind_airspeed) }, \
{ "true_airspeed", NULL, MAVLINK_TYPE_UINT16_T, 0, 56, offsetof(mavlink_hil_state_quaternion_t, true_airspeed) }, \
{ "xacc", NULL, MAVLINK_TYPE_INT16_T, 0, 58, offsetof(mavlink_hil_state_quaternion_t, xacc) }, \
{ "yacc", NULL, MAVLINK_TYPE_INT16_T, 0, 60, offsetof(mavlink_hil_state_quaternion_t, yacc) }, \
{ "zacc", NULL, MAVLINK_TYPE_INT16_T, 0, 62, offsetof(mavlink_hil_state_quaternion_t, zacc) }, \
} \
}
#endif
/**
* @brief Pack a hil_state_quaternion message
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
*
* @param time_usec [us] Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number.
* @param attitude_quaternion Vehicle attitude expressed as normalized quaternion in w, x, y, z order (with 1 0 0 0 being the null-rotation)
* @param rollspeed [rad/s] Body frame roll / phi angular speed
* @param pitchspeed [rad/s] Body frame pitch / theta angular speed
* @param yawspeed [rad/s] Body frame yaw / psi angular speed
* @param lat [degE7] Latitude
* @param lon [degE7] Longitude
* @param alt [mm] Altitude
* @param vx [cm/s] Ground X Speed (Latitude)
* @param vy [cm/s] Ground Y Speed (Longitude)
* @param vz [cm/s] Ground Z Speed (Altitude)
* @param ind_airspeed [cm/s] Indicated airspeed
* @param true_airspeed [cm/s] True airspeed
* @param xacc [mG] X acceleration
* @param yacc [mG] Y acceleration
* @param zacc [mG] Z acceleration
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_hil_state_quaternion_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
uint64_t time_usec, const float *attitude_quaternion, float rollspeed, float pitchspeed, float yawspeed, int32_t lat, int32_t lon, int32_t alt, int16_t vx, int16_t vy, int16_t vz, uint16_t ind_airspeed, uint16_t true_airspeed, int16_t xacc, int16_t yacc, int16_t zacc)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN];
_mav_put_uint64_t(buf, 0, time_usec);
_mav_put_float(buf, 24, rollspeed);
_mav_put_float(buf, 28, pitchspeed);
_mav_put_float(buf, 32, yawspeed);
_mav_put_int32_t(buf, 36, lat);
_mav_put_int32_t(buf, 40, lon);
_mav_put_int32_t(buf, 44, alt);
_mav_put_int16_t(buf, 48, vx);
_mav_put_int16_t(buf, 50, vy);
_mav_put_int16_t(buf, 52, vz);
_mav_put_uint16_t(buf, 54, ind_airspeed);
_mav_put_uint16_t(buf, 56, true_airspeed);
_mav_put_int16_t(buf, 58, xacc);
_mav_put_int16_t(buf, 60, yacc);
_mav_put_int16_t(buf, 62, zacc);
_mav_put_float_array(buf, 8, attitude_quaternion, 4);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN);
#else
mavlink_hil_state_quaternion_t packet;
packet.time_usec = time_usec;
packet.rollspeed = rollspeed;
packet.pitchspeed = pitchspeed;
packet.yawspeed = yawspeed;
packet.lat = lat;
packet.lon = lon;
packet.alt = alt;
packet.vx = vx;
packet.vy = vy;
packet.vz = vz;
packet.ind_airspeed = ind_airspeed;
packet.true_airspeed = true_airspeed;
packet.xacc = xacc;
packet.yacc = yacc;
packet.zacc = zacc;
mav_array_memcpy(packet.attitude_quaternion, attitude_quaternion, sizeof(float)*4);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_HIL_STATE_QUATERNION;
return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_MIN_LEN, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_CRC);
}
/**
* @brief Pack a hil_state_quaternion message on a channel
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param time_usec [us] Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number.
* @param attitude_quaternion Vehicle attitude expressed as normalized quaternion in w, x, y, z order (with 1 0 0 0 being the null-rotation)
* @param rollspeed [rad/s] Body frame roll / phi angular speed
* @param pitchspeed [rad/s] Body frame pitch / theta angular speed
* @param yawspeed [rad/s] Body frame yaw / psi angular speed
* @param lat [degE7] Latitude
* @param lon [degE7] Longitude
* @param alt [mm] Altitude
* @param vx [cm/s] Ground X Speed (Latitude)
* @param vy [cm/s] Ground Y Speed (Longitude)
* @param vz [cm/s] Ground Z Speed (Altitude)
* @param ind_airspeed [cm/s] Indicated airspeed
* @param true_airspeed [cm/s] True airspeed
* @param xacc [mG] X acceleration
* @param yacc [mG] Y acceleration
* @param zacc [mG] Z acceleration
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_hil_state_quaternion_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
mavlink_message_t* msg,
uint64_t time_usec,const float *attitude_quaternion,float rollspeed,float pitchspeed,float yawspeed,int32_t lat,int32_t lon,int32_t alt,int16_t vx,int16_t vy,int16_t vz,uint16_t ind_airspeed,uint16_t true_airspeed,int16_t xacc,int16_t yacc,int16_t zacc)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN];
_mav_put_uint64_t(buf, 0, time_usec);
_mav_put_float(buf, 24, rollspeed);
_mav_put_float(buf, 28, pitchspeed);
_mav_put_float(buf, 32, yawspeed);
_mav_put_int32_t(buf, 36, lat);
_mav_put_int32_t(buf, 40, lon);
_mav_put_int32_t(buf, 44, alt);
_mav_put_int16_t(buf, 48, vx);
_mav_put_int16_t(buf, 50, vy);
_mav_put_int16_t(buf, 52, vz);
_mav_put_uint16_t(buf, 54, ind_airspeed);
_mav_put_uint16_t(buf, 56, true_airspeed);
_mav_put_int16_t(buf, 58, xacc);
_mav_put_int16_t(buf, 60, yacc);
_mav_put_int16_t(buf, 62, zacc);
_mav_put_float_array(buf, 8, attitude_quaternion, 4);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN);
#else
mavlink_hil_state_quaternion_t packet;
packet.time_usec = time_usec;
packet.rollspeed = rollspeed;
packet.pitchspeed = pitchspeed;
packet.yawspeed = yawspeed;
packet.lat = lat;
packet.lon = lon;
packet.alt = alt;
packet.vx = vx;
packet.vy = vy;
packet.vz = vz;
packet.ind_airspeed = ind_airspeed;
packet.true_airspeed = true_airspeed;
packet.xacc = xacc;
packet.yacc = yacc;
packet.zacc = zacc;
mav_array_memcpy(packet.attitude_quaternion, attitude_quaternion, sizeof(float)*4);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_HIL_STATE_QUATERNION;
return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_MIN_LEN, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_CRC);
}
/**
* @brief Encode a hil_state_quaternion struct
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
* @param hil_state_quaternion C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_hil_state_quaternion_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_hil_state_quaternion_t* hil_state_quaternion)
{
return mavlink_msg_hil_state_quaternion_pack(system_id, component_id, msg, hil_state_quaternion->time_usec, hil_state_quaternion->attitude_quaternion, hil_state_quaternion->rollspeed, hil_state_quaternion->pitchspeed, hil_state_quaternion->yawspeed, hil_state_quaternion->lat, hil_state_quaternion->lon, hil_state_quaternion->alt, hil_state_quaternion->vx, hil_state_quaternion->vy, hil_state_quaternion->vz, hil_state_quaternion->ind_airspeed, hil_state_quaternion->true_airspeed, hil_state_quaternion->xacc, hil_state_quaternion->yacc, hil_state_quaternion->zacc);
}
/**
* @brief Encode a hil_state_quaternion struct on a channel
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param hil_state_quaternion C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_hil_state_quaternion_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, const mavlink_hil_state_quaternion_t* hil_state_quaternion)
{
return mavlink_msg_hil_state_quaternion_pack_chan(system_id, component_id, chan, msg, hil_state_quaternion->time_usec, hil_state_quaternion->attitude_quaternion, hil_state_quaternion->rollspeed, hil_state_quaternion->pitchspeed, hil_state_quaternion->yawspeed, hil_state_quaternion->lat, hil_state_quaternion->lon, hil_state_quaternion->alt, hil_state_quaternion->vx, hil_state_quaternion->vy, hil_state_quaternion->vz, hil_state_quaternion->ind_airspeed, hil_state_quaternion->true_airspeed, hil_state_quaternion->xacc, hil_state_quaternion->yacc, hil_state_quaternion->zacc);
}
/**
* @brief Send a hil_state_quaternion message
* @param chan MAVLink channel to send the message
*
* @param time_usec [us] Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number.
* @param attitude_quaternion Vehicle attitude expressed as normalized quaternion in w, x, y, z order (with 1 0 0 0 being the null-rotation)
* @param rollspeed [rad/s] Body frame roll / phi angular speed
* @param pitchspeed [rad/s] Body frame pitch / theta angular speed
* @param yawspeed [rad/s] Body frame yaw / psi angular speed
* @param lat [degE7] Latitude
* @param lon [degE7] Longitude
* @param alt [mm] Altitude
* @param vx [cm/s] Ground X Speed (Latitude)
* @param vy [cm/s] Ground Y Speed (Longitude)
* @param vz [cm/s] Ground Z Speed (Altitude)
* @param ind_airspeed [cm/s] Indicated airspeed
* @param true_airspeed [cm/s] True airspeed
* @param xacc [mG] X acceleration
* @param yacc [mG] Y acceleration
* @param zacc [mG] Z acceleration
*/
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
static inline void mavlink_msg_hil_state_quaternion_send(mavlink_channel_t chan, uint64_t time_usec, const float *attitude_quaternion, float rollspeed, float pitchspeed, float yawspeed, int32_t lat, int32_t lon, int32_t alt, int16_t vx, int16_t vy, int16_t vz, uint16_t ind_airspeed, uint16_t true_airspeed, int16_t xacc, int16_t yacc, int16_t zacc)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN];
_mav_put_uint64_t(buf, 0, time_usec);
_mav_put_float(buf, 24, rollspeed);
_mav_put_float(buf, 28, pitchspeed);
_mav_put_float(buf, 32, yawspeed);
_mav_put_int32_t(buf, 36, lat);
_mav_put_int32_t(buf, 40, lon);
_mav_put_int32_t(buf, 44, alt);
_mav_put_int16_t(buf, 48, vx);
_mav_put_int16_t(buf, 50, vy);
_mav_put_int16_t(buf, 52, vz);
_mav_put_uint16_t(buf, 54, ind_airspeed);
_mav_put_uint16_t(buf, 56, true_airspeed);
_mav_put_int16_t(buf, 58, xacc);
_mav_put_int16_t(buf, 60, yacc);
_mav_put_int16_t(buf, 62, zacc);
_mav_put_float_array(buf, 8, attitude_quaternion, 4);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_HIL_STATE_QUATERNION, buf, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_MIN_LEN, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_CRC);
#else
mavlink_hil_state_quaternion_t packet;
packet.time_usec = time_usec;
packet.rollspeed = rollspeed;
packet.pitchspeed = pitchspeed;
packet.yawspeed = yawspeed;
packet.lat = lat;
packet.lon = lon;
packet.alt = alt;
packet.vx = vx;
packet.vy = vy;
packet.vz = vz;
packet.ind_airspeed = ind_airspeed;
packet.true_airspeed = true_airspeed;
packet.xacc = xacc;
packet.yacc = yacc;
packet.zacc = zacc;
mav_array_memcpy(packet.attitude_quaternion, attitude_quaternion, sizeof(float)*4);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_HIL_STATE_QUATERNION, (const char *)&packet, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_MIN_LEN, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_CRC);
#endif
}
/**
* @brief Send a hil_state_quaternion message
* @param chan MAVLink channel to send the message
* @param struct The MAVLink struct to serialize
*/
static inline void mavlink_msg_hil_state_quaternion_send_struct(mavlink_channel_t chan, const mavlink_hil_state_quaternion_t* hil_state_quaternion)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
mavlink_msg_hil_state_quaternion_send(chan, hil_state_quaternion->time_usec, hil_state_quaternion->attitude_quaternion, hil_state_quaternion->rollspeed, hil_state_quaternion->pitchspeed, hil_state_quaternion->yawspeed, hil_state_quaternion->lat, hil_state_quaternion->lon, hil_state_quaternion->alt, hil_state_quaternion->vx, hil_state_quaternion->vy, hil_state_quaternion->vz, hil_state_quaternion->ind_airspeed, hil_state_quaternion->true_airspeed, hil_state_quaternion->xacc, hil_state_quaternion->yacc, hil_state_quaternion->zacc);
#else
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_HIL_STATE_QUATERNION, (const char *)hil_state_quaternion, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_MIN_LEN, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_CRC);
#endif
}
#if MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN <= MAVLINK_MAX_PAYLOAD_LEN
/*
This varient of _send() can be used to save stack space by re-using
memory from the receive buffer. The caller provides a
mavlink_message_t which is the size of a full mavlink message. This
is usually the receive buffer for the channel, and allows a reply to an
incoming message with minimum stack space usage.
*/
static inline void mavlink_msg_hil_state_quaternion_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan, uint64_t time_usec, const float *attitude_quaternion, float rollspeed, float pitchspeed, float yawspeed, int32_t lat, int32_t lon, int32_t alt, int16_t vx, int16_t vy, int16_t vz, uint16_t ind_airspeed, uint16_t true_airspeed, int16_t xacc, int16_t yacc, int16_t zacc)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char *buf = (char *)msgbuf;
_mav_put_uint64_t(buf, 0, time_usec);
_mav_put_float(buf, 24, rollspeed);
_mav_put_float(buf, 28, pitchspeed);
_mav_put_float(buf, 32, yawspeed);
_mav_put_int32_t(buf, 36, lat);
_mav_put_int32_t(buf, 40, lon);
_mav_put_int32_t(buf, 44, alt);
_mav_put_int16_t(buf, 48, vx);
_mav_put_int16_t(buf, 50, vy);
_mav_put_int16_t(buf, 52, vz);
_mav_put_uint16_t(buf, 54, ind_airspeed);
_mav_put_uint16_t(buf, 56, true_airspeed);
_mav_put_int16_t(buf, 58, xacc);
_mav_put_int16_t(buf, 60, yacc);
_mav_put_int16_t(buf, 62, zacc);
_mav_put_float_array(buf, 8, attitude_quaternion, 4);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_HIL_STATE_QUATERNION, buf, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_MIN_LEN, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_CRC);
#else
mavlink_hil_state_quaternion_t *packet = (mavlink_hil_state_quaternion_t *)msgbuf;
packet->time_usec = time_usec;
packet->rollspeed = rollspeed;
packet->pitchspeed = pitchspeed;
packet->yawspeed = yawspeed;
packet->lat = lat;
packet->lon = lon;
packet->alt = alt;
packet->vx = vx;
packet->vy = vy;
packet->vz = vz;
packet->ind_airspeed = ind_airspeed;
packet->true_airspeed = true_airspeed;
packet->xacc = xacc;
packet->yacc = yacc;
packet->zacc = zacc;
mav_array_memcpy(packet->attitude_quaternion, attitude_quaternion, sizeof(float)*4);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_HIL_STATE_QUATERNION, (const char *)packet, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_MIN_LEN, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_CRC);
#endif
}
#endif
#endif
// MESSAGE HIL_STATE_QUATERNION UNPACKING
/**
* @brief Get field time_usec from hil_state_quaternion message
*
* @return [us] Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude the number.
*/
static inline uint64_t mavlink_msg_hil_state_quaternion_get_time_usec(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint64_t(msg, 0);
}
/**
* @brief Get field attitude_quaternion from hil_state_quaternion message
*
* @return Vehicle attitude expressed as normalized quaternion in w, x, y, z order (with 1 0 0 0 being the null-rotation)
*/
static inline uint16_t mavlink_msg_hil_state_quaternion_get_attitude_quaternion(const mavlink_message_t* msg, float *attitude_quaternion)
{
return _MAV_RETURN_float_array(msg, attitude_quaternion, 4, 8);
}
/**
* @brief Get field rollspeed from hil_state_quaternion message
*
* @return [rad/s] Body frame roll / phi angular speed
*/
static inline float mavlink_msg_hil_state_quaternion_get_rollspeed(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 24);
}
/**
* @brief Get field pitchspeed from hil_state_quaternion message
*
* @return [rad/s] Body frame pitch / theta angular speed
*/
static inline float mavlink_msg_hil_state_quaternion_get_pitchspeed(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 28);
}
/**
* @brief Get field yawspeed from hil_state_quaternion message
*
* @return [rad/s] Body frame yaw / psi angular speed
*/
static inline float mavlink_msg_hil_state_quaternion_get_yawspeed(const mavlink_message_t* msg)
{
return _MAV_RETURN_float(msg, 32);
}
/**
* @brief Get field lat from hil_state_quaternion message
*
* @return [degE7] Latitude
*/
static inline int32_t mavlink_msg_hil_state_quaternion_get_lat(const mavlink_message_t* msg)
{
return _MAV_RETURN_int32_t(msg, 36);
}
/**
* @brief Get field lon from hil_state_quaternion message
*
* @return [degE7] Longitude
*/
static inline int32_t mavlink_msg_hil_state_quaternion_get_lon(const mavlink_message_t* msg)
{
return _MAV_RETURN_int32_t(msg, 40);
}
/**
* @brief Get field alt from hil_state_quaternion message
*
* @return [mm] Altitude
*/
static inline int32_t mavlink_msg_hil_state_quaternion_get_alt(const mavlink_message_t* msg)
{
return _MAV_RETURN_int32_t(msg, 44);
}
/**
* @brief Get field vx from hil_state_quaternion message
*
* @return [cm/s] Ground X Speed (Latitude)
*/
static inline int16_t mavlink_msg_hil_state_quaternion_get_vx(const mavlink_message_t* msg)
{
return _MAV_RETURN_int16_t(msg, 48);
}
/**
* @brief Get field vy from hil_state_quaternion message
*
* @return [cm/s] Ground Y Speed (Longitude)
*/
static inline int16_t mavlink_msg_hil_state_quaternion_get_vy(const mavlink_message_t* msg)
{
return _MAV_RETURN_int16_t(msg, 50);
}
/**
* @brief Get field vz from hil_state_quaternion message
*
* @return [cm/s] Ground Z Speed (Altitude)
*/
static inline int16_t mavlink_msg_hil_state_quaternion_get_vz(const mavlink_message_t* msg)
{
return _MAV_RETURN_int16_t(msg, 52);
}
/**
* @brief Get field ind_airspeed from hil_state_quaternion message
*
* @return [cm/s] Indicated airspeed
*/
static inline uint16_t mavlink_msg_hil_state_quaternion_get_ind_airspeed(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint16_t(msg, 54);
}
/**
* @brief Get field true_airspeed from hil_state_quaternion message
*
* @return [cm/s] True airspeed
*/
static inline uint16_t mavlink_msg_hil_state_quaternion_get_true_airspeed(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint16_t(msg, 56);
}
/**
* @brief Get field xacc from hil_state_quaternion message
*
* @return [mG] X acceleration
*/
static inline int16_t mavlink_msg_hil_state_quaternion_get_xacc(const mavlink_message_t* msg)
{
return _MAV_RETURN_int16_t(msg, 58);
}
/**
* @brief Get field yacc from hil_state_quaternion message
*
* @return [mG] Y acceleration
*/
static inline int16_t mavlink_msg_hil_state_quaternion_get_yacc(const mavlink_message_t* msg)
{
return _MAV_RETURN_int16_t(msg, 60);
}
/**
* @brief Get field zacc from hil_state_quaternion message
*
* @return [mG] Z acceleration
*/
static inline int16_t mavlink_msg_hil_state_quaternion_get_zacc(const mavlink_message_t* msg)
{
return _MAV_RETURN_int16_t(msg, 62);
}
/**
* @brief Decode a hil_state_quaternion message into a struct
*
* @param msg The message to decode
* @param hil_state_quaternion C-struct to decode the message contents into
*/
static inline void mavlink_msg_hil_state_quaternion_decode(const mavlink_message_t* msg, mavlink_hil_state_quaternion_t* hil_state_quaternion)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
hil_state_quaternion->time_usec = mavlink_msg_hil_state_quaternion_get_time_usec(msg);
mavlink_msg_hil_state_quaternion_get_attitude_quaternion(msg, hil_state_quaternion->attitude_quaternion);
hil_state_quaternion->rollspeed = mavlink_msg_hil_state_quaternion_get_rollspeed(msg);
hil_state_quaternion->pitchspeed = mavlink_msg_hil_state_quaternion_get_pitchspeed(msg);
hil_state_quaternion->yawspeed = mavlink_msg_hil_state_quaternion_get_yawspeed(msg);
hil_state_quaternion->lat = mavlink_msg_hil_state_quaternion_get_lat(msg);
hil_state_quaternion->lon = mavlink_msg_hil_state_quaternion_get_lon(msg);
hil_state_quaternion->alt = mavlink_msg_hil_state_quaternion_get_alt(msg);
hil_state_quaternion->vx = mavlink_msg_hil_state_quaternion_get_vx(msg);
hil_state_quaternion->vy = mavlink_msg_hil_state_quaternion_get_vy(msg);
hil_state_quaternion->vz = mavlink_msg_hil_state_quaternion_get_vz(msg);
hil_state_quaternion->ind_airspeed = mavlink_msg_hil_state_quaternion_get_ind_airspeed(msg);
hil_state_quaternion->true_airspeed = mavlink_msg_hil_state_quaternion_get_true_airspeed(msg);
hil_state_quaternion->xacc = mavlink_msg_hil_state_quaternion_get_xacc(msg);
hil_state_quaternion->yacc = mavlink_msg_hil_state_quaternion_get_yacc(msg);
hil_state_quaternion->zacc = mavlink_msg_hil_state_quaternion_get_zacc(msg);
#else
uint8_t len = msg->len < MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN? msg->len : MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN;
memset(hil_state_quaternion, 0, MAVLINK_MSG_ID_HIL_STATE_QUATERNION_LEN);
memcpy(hil_state_quaternion, _MAV_PAYLOAD(msg), len);
#endif
}
| diydrones/apm_planner | libs/mavlink/include/mavlink/v2.0/common/mavlink_msg_hil_state_quaternion.h | C | agpl-3.0 | 28,062 |
<?php
/**
* A collection of Event_Results.
*
* @since 4.9.13
*
* @package Tribe\Events\Views\V2\Repository
*/
namespace Tribe\Events\Views\V2\Repository;
use Tribe\Utils\Collection_Interface;
use Tribe\Utils\Collection_Trait;
use Tribe__Utils__Array as Arr;
/**
* Class Events_Result_Set
*
* @since 4.9.13
*
* @package Tribe\Events\Views\V2\Repository
*/
class Events_Result_Set implements Collection_Interface {
use Collection_Trait;
/**
* An array of event results in this result set.
*
* @since 4.9.13
*
* @var array
*/
protected $items;
/**
* Events_Result_Set constructor.
*
* @param Event_Result[]|array $event_results An array of event results.
*/
public function __construct( array $event_results = [] ) {
$this->items = $this->normalize_event_results( $event_results );
}
/**
* Returns whether a string represents a serialized instance of the class or not.
*
* @since 5.0.0
*
* @param mixed $value The value to test.
*
* @return bool Whether the input value is a string representing a serialized instance of the class or not.
*/
protected static function is_serialized( $value ) {
if ( ! is_string( $value ) ) {
return false;
}
$serialized_start = sprintf( 'C:%d:"%s"', strlen( __CLASS__ ), __CLASS__ );
return 0 === strpos( $value, $serialized_start );
}
/**
* Unserializes, with error handling, a result set to return a new instance of this class.
*
* @since 5.0.0
*
* @param string $value The serialized version of the result set.
*
* @return Events_Result_Set The unserialized result set, or an empty result set on failure.
*/
protected static function from_serialized( $value ) {
try {
$set = unserialize( $value );
if ( false === $set || ! $set instanceof static ) {
return new Events_Result_Set( [] );
}
return $set;
} catch ( \Exception $e ) {
return new Events_Result_Set( [] );
}
}
/**
* Builds a set from an array of event results.
*
* @since 5.0.0
*
* @param array<Event_Result> $event_results An array of event results.
*
* @return Events_Result_Set A new set, built from the input Event Results.
*/
protected static function from_array( $event_results ) {
try {
return new Events_Result_Set( $event_results );
} catch ( \Exception $e ) {
return new Events_Result_Set( [] );
}
}
/**
* Builds a result set from different type of values.
*
* @since 4.9.13
*
* @param mixed $value A result set, that will be returned intact, an array of event results
*
* @return Events_Result_Set The original set, a set built on an array of `Event_Result` instances, or a set
* built on an empty array if the set could not be built.
*/
public static function from_value( $value ) {
if ( $value instanceof Events_Result_Set ) {
return $value;
}
if ( is_array( $value ) ) {
return self::from_array( $value );
}
if ( self::is_serialized( $value ) ) {
return self::from_serialized( $value );
}
return new Events_Result_Set( [] );
}
/**
* Returns the number of Event Results in this set.
*
* @since 5.0.0
*
* @return int The number of Event Results in this set.
*/
public function count() {
return count( $this->items );
}
/**
* Orders the Event Results by a specified criteria.
*
* @since 5.0.0
*
* @param string $order_by The key to order the Event Results by, currently supported is only `start_date`.
* @param string $order The order direction, one of `ASC` or `DESC`.
*
* @return $this The current object, for chaining.
*/
public function order_by( $order_by, $order ) {
$order = strtoupper( $order );
if ( ! in_array( $order, [ 'ASC', 'DESC' ], true ) ) {
throw new \InvalidArgumentException( 'Order "' . $order . '" is not supported, only "ASC" and "DESC" are.' );
}
// @todo @be here support more ordering criteria than date.
$order_by_key_map = [
'event_date' => 'start_date',
];
$order_by_key = Arr::get( $order_by_key_map, $order_by, 'start_date' );
/*
* The `wp_list_sort` function will convert each element of the set in an array.
* Since we cannot control that `(array)$item` cast, we pre-convert each
* element into an array and convert it back to a set of `Event_Result` after the sorting.
*/
$this->items = static::from_value(
wp_list_sort(
$this->to_array(),
$order_by_key,
$order
)
);
return $this;
}
/**
* {@inheritDoc}
*/
public function all() {
return $this->items;
}
/**
* {@inheritDoc}
*/
public function jsonSerialize() {
return wp_json_encode( $this->items );
}
/**
* Plucks a key from all the event results in the collection.
*
* @since 4.9.13
*
* @param string $column The key to pluck.
*
* @return array An array of all the values associated to the key for each event result in the set.
*/
public function pluck( $column ) {
return wp_list_pluck( $this->items, $column );
}
/**
* Iterates over the result set and to return the array version of each result.
*
* @since 4.9.13
*
* @return array An array of arrays, each one the array version of an `Event_Result`.
*/
public function to_array() {
return array_map( static function ( Event_Result $event_result ) {
return $event_result->to_array();
}, $this->items );
}
/**
* Overrides the base `Collection_Trait` implementation to normalize all the items in the result set.
*
* @since 4.9.13
*
* @param string $data The serialized data.
*/
public function unserialize( $data ) {
$event_results = unserialize( $data );
$this->items = $this->normalize_event_results( $event_results );
}
/**
* Normalizes the event results in this set ensuring each one is an instance of `Event_Result`.
*
* @since 4.9.13
*
* @param array $event_results A set of event results in array or object format..
*
* @return Event_Result[] The normalized set of results.
*/
protected function normalize_event_results( array $event_results ) {
return array_map( static function ( $result ) {
return Event_Result::from_value( $result );
}, $event_results );
}
}
| akvo/akvo-sites-zz-template | code/wp-content/plugins/the-events-calendar/src/Tribe/Views/V2/Repository/Events_Result_Set.php | PHP | agpl-3.0 | 6,157 |
<?php
/**
* Generic_Sniffs_WhiteSpace_DisallowTabIndentSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version CVS: $Id: DisallowTabIndentSniff.php,v 1.3 2008/10/28 04:43:57 squiz Exp $
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Generic_Sniffs_WhiteSpace_DisallowTabIndentSniff.
*
* Throws errors if tabs are used for indentation.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <gsherwood@squiz.net>
* @author Marc McIntyre <mmcintyre@squiz.net>
* @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600)
* @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
* @version Release: @package_version@
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Generic_Sniffs_WhiteSpace_DisallowTabIndentSniff implements PHP_CodeSniffer_Sniff
{
/**
* A list of tokenizers this sniff supports.
*
* @var array
*/
public $supportedTokenizers = array(
'PHP',
'JS',
'CSS',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_WHITESPACE);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile All the tokens found in the document.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Make sure this is whitespace used for indentation.
$line = $tokens[$stackPtr]['line'];
if ($stackPtr > 0 && $tokens[($stackPtr - 1)]['line'] === $line) {
return;
}
if (strpos($tokens[$stackPtr]['content'], "\t") !== false) {
$error = 'Spaces must be used to indent lines; tabs are not allowed';
$phpcsFile->addError($error, $stackPtr);
}
}//end process()
}//end class
?>
| mikesname/ehri-ica-atom | plugins/sfAuditPlugin/lib/vendor/PHP/CodeSniffer/Standards/Generic/Sniffs/WhiteSpace/DisallowTabIndentSniff.php | PHP | agpl-3.0 | 2,562 |
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# ThinkOpen Solutions Brasil
# Copyright (C) Thinkopen Solutions <http://www.tkobr.com>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import purchase
| elego/tkobr-addons | unported/tko_purchase_show_only_supplier_products/__init__.py | Python | agpl-3.0 | 1,094 |
var path = require('path');
module.exports = function(project_dir){
return {
'cordova':
{ 'platform':'*', 'scriptSrc': path.join(project_dir,'cordova','version') },
'cordova-plugman':
{ 'platform':'*', 'currentVersion': require('../../../package.json').version },
'cordova-android':
{ 'platform':'android', 'scriptSrc': path.join(project_dir,'cordova','version') },
'cordova-ios':
{ 'platform':'ios', 'scriptSrc': path.join(project_dir,'cordova','version') },
'cordova-blackberry10':
{ 'platform':'blackberry10', 'scriptSrc': path.join(project_dir,'cordova','version') },
'cordova-wp7':
{ 'platform':'wp7', 'scriptSrc': path.join(project_dir,'cordova','version') },
'cordova-wp8':
{ 'platform':'wp8', 'scriptSrc': path.join(project_dir,'cordova','version') },
'cordova-windows8':
{ 'platform':'windows8', 'scriptSrc': path.join(project_dir,'cordova','version') },
'apple-xcode' :
{ 'platform':'ios', 'scriptSrc': path.join(project_dir,'cordova','apple_xcode_version') },
'apple-ios' :
{ 'platform':'ios', 'scriptSrc': path.join(project_dir,'cordova','apple_ios_version') },
'apple-osx' :
{ 'platform':'ios', 'scriptSrc': path.join(project_dir,'cordova','apple_osx_version') },
'blackberry-ndk' :
{ 'platform':'blackberry10', 'scriptSrc': path.join(project_dir,'cordova','bb10-ndk-version') },
'android-sdk' :
{ 'platform':'android', 'scriptSrc': path.join(project_dir,'cordova','android_sdk_version') },
'windows-os' :
{ 'platform':'wp7|wp8|windows8', 'scriptSrc': path.join(project_dir,'cordova','win_os_version') },
'windows-sdk' :
{ 'platform':'wp7|wp8|windows8', 'scriptSrc': path.join(project_dir,'cordova','win_sdk_version') }
}
};
| fau-amos-2014-team-2/root | phonegap/node_modules/cordova/node_modules/cordova-lib/src/plugman/util/default-engines.js | JavaScript | agpl-3.0 | 1,948 |
<?php $TRANSLATIONS = array(
"Welcome to ownCloud" => "Benvenite a ownCloud",
"Your personal web services. All your files, contacts, calendar and more, in one place." => "Tu servicios personal de web. Omne tu files, contactos, calendario e alteres, in un placia.",
"Get the apps to sync your files" => "Obtene le apps (applicationes) pro synchronizar tu files",
"Connect your desktop apps to ownCloud" => "Connecte tu apps de scriptorio a ownCloud",
"Connect your Calendar" => "Connecte tu calendario",
"Connect your Contacts" => "Connecte tu contactos",
"Access files via WebDAV" => "Accede a files via WebDAV",
"If you like ownCloud, <a href=\"mailto:?subject=ownCloud&body=ownCloud is a great open software to sync and share your files. You can freely get it from http://owncloud.org\">recommend it to your friends</a>!" => "Si tu place ownCloud, <a href=\"mailto:?subject=ownCloud&body=ownCloud is a great open software to sync and share your files. You can freely get it from http://owncloud.org\">recommenda lo a tu amicos </a>!"
);
| ipit-international/learning-environment | owncloud/apps/thirstrunwizard/l10n/ia.php | PHP | agpl-3.0 | 1,040 |
class EventPlugin::EventBlock < Block
attr_accessible :all_env_events, :limit, :future_only, :date_distance_limit, :display_as_calendar
settings_items :all_env_events, :type => :boolean, :default => false
settings_items :limit, :type => :integer, :default => 4
settings_items :future_only, :type => :boolean, :default => true
settings_items :date_distance_limit, :type => :integer, :default => 0
settings_items :display_as_calendar, :type => :boolean, :default => false
def self.description
_('Events')
end
def help
_('Show the profile events or all environment events.')
end
def events_source
return environment if all_env_events
if self.owner.kind_of? Environment
environment.portal_community ? environment.portal_community : environment
else
self.owner
end
end
def events(user = nil)
events = events_source.events.order('start_date')
events = user.nil? ? events.is_public : events.display_filter(user,nil)
if future_only
events = events.where('start_date >= ?', DateTime.now.beginning_of_day)
end
if date_distance_limit > 0
events = events.by_range([
DateTime.now.beginning_of_day - date_distance_limit,
DateTime.now.beginning_of_day + date_distance_limit
])
end
event_list = []
events.each do |event|
event_list << event if event.display_to? user
break if event_list.length >= limit
end
event_list
end
def cache_key language='en', user=nil
last_event = self.events_source.events.published.order('updated_at DESC').first
"#{super}-#{last_event.updated_at if last_event}"
end
def self.expire_on
{ :profile => [:article], :environment => [:article] }
end
def api_content(params = {})
content = []
events.each do |event|
content << { title: event.title, id: event.id, date: event.start_date.to_i * 1000, view_url: event.view_url }
end
{ events: content }
end
end
| coletivoEITA/noosfero-ecosol | plugins/event/lib/event_plugin/event_block.rb | Ruby | agpl-3.0 | 1,971 |
<div class="legend no-select" *ngIf="data">
<div class="legend-box"
*ngFor="let trace of data.series; index as i"
[style.backgroundColor]="backgroundColor"
[style.border]="'1px solid ' + borderColor"
[style.borderLeft]="'3px solid ' + trace.color"
[style.paddingRight]="closable && i !== 0 ? '15px' : '5px'">
<span class="label" (click)="select.emit(trace.label)">{{ trace.label }}</span>
<span class="yvalue" *ngIf="trace.yHTML">{{ trace.yHTML }}</span>
<div class="close-button"
*ngIf="closable && i !== 0"
(click)="close.emit(trace.label)">
<mat-icon class="icon12">close</mat-icon>
</div>
</div>
</div>
| fqqb/yamcs | yamcs-web/src/main/webapp/src/app/shared/widgets/ParameterLegend.html | HTML | agpl-3.0 | 687 |
#!/usr/bin/env node
/**
* Build script for /tg/station 13 codebase.
*
* This script uses Juke Build, read the docs here:
* https://github.com/stylemistake/juke-build
*
* @file
* @copyright 2021 Aleksej Komarov
* @license MIT
*/
import fs from 'fs';
import { DreamDaemon, DreamMaker } from './lib/byond.js';
import { yarn } from './lib/yarn.js';
import Juke from './juke/index.js';
Juke.chdir('../..', import.meta.url);
Juke.setup({ file: import.meta.url }).then((code) => process.exit(code));
const DME_NAME = 'tgstation';
export const DefineParameter = new Juke.Parameter({
type: 'string[]',
alias: 'D',
});
export const PortParameter = new Juke.Parameter({
type: 'string',
alias: 'p',
});
export const CiParameter = new Juke.Parameter({
type: 'boolean',
});
export const DmMapsIncludeTarget = new Juke.Target({
executes: async () => {
const folders = [
...Juke.glob('_maps/RandomRuins/**/*.dmm'),
...Juke.glob('_maps/RandomZLevels/**/*.dmm'),
...Juke.glob('_maps/shuttles/**/*.dmm'),
...Juke.glob('_maps/templates/**/*.dmm'),
];
const content = folders
.map((file) => file.replace('_maps/', ''))
.map((file) => `#include "${file}"`)
.join('\n') + '\n';
fs.writeFileSync('_maps/templates.dm', content);
},
});
export const DmTarget = new Juke.Target({
dependsOn: ({ get }) => [
get(DefineParameter).includes('ALL_MAPS') && DmMapsIncludeTarget,
],
inputs: [
'_maps/map_files/generic/**',
'code/**',
'goon/**',
'html/**',
'icons/**',
'interface/**',
`${DME_NAME}.dme`,
],
outputs: [
`${DME_NAME}.dmb`,
`${DME_NAME}.rsc`,
],
parameters: [DefineParameter],
executes: async ({ get }) => {
const defines = get(DefineParameter);
if (defines.length > 0) {
Juke.logger.info('Using defines:', defines.join(', '));
}
await DreamMaker(`${DME_NAME}.dme`, {
defines: ['CBT', ...defines],
});
},
});
export const DmTestTarget = new Juke.Target({
dependsOn: ({ get }) => [
get(DefineParameter).includes('ALL_MAPS') && DmMapsIncludeTarget,
],
executes: async ({ get }) => {
const defines = get(DefineParameter);
if (defines.length > 0) {
Juke.logger.info('Using defines:', defines.join(', '));
}
fs.copyFileSync(`${DME_NAME}.dme`, `${DME_NAME}.test.dme`);
await DreamMaker(`${DME_NAME}.test.dme`, {
defines: ['CBT', 'CIBUILDING', ...defines],
});
Juke.rm('data/logs/ci', { recursive: true });
await DreamDaemon(
`${DME_NAME}.test.dmb`,
'-close', '-trusted', '-verbose',
'-params', 'log-directory=ci'
);
Juke.rm('*.test.*');
try {
const cleanRun = fs.readFileSync('data/logs/ci/clean_run.lk', 'utf-8');
console.log(cleanRun);
}
catch (err) {
Juke.logger.error('Test run was not clean, exiting');
throw new Juke.ExitCode(1);
}
},
});
export const YarnTarget = new Juke.Target({
inputs: [
'tgui/.yarn/+(cache|releases|plugins|sdks)/**/*',
'tgui/**/package.json',
'tgui/yarn.lock',
],
outputs: [
'tgui/.yarn/install-target',
],
executes: async () => {
await yarn('install');
},
});
export const TgFontTarget = new Juke.Target({
dependsOn: [YarnTarget],
inputs: [
'tgui/.yarn/install-target',
'tgui/packages/tgfont/**/*.+(js|cjs|svg)',
'tgui/packages/tgfont/package.json',
],
outputs: [
'tgui/packages/tgfont/dist/tgfont.css',
'tgui/packages/tgfont/dist/tgfont.eot',
'tgui/packages/tgfont/dist/tgfont.woff2',
],
executes: async () => {
await yarn('workspace', 'tgfont', 'build');
},
});
export const TguiTarget = new Juke.Target({
dependsOn: [YarnTarget],
inputs: [
'tgui/.yarn/install-target',
'tgui/webpack.config.js',
'tgui/**/package.json',
'tgui/packages/**/*.+(js|cjs|ts|tsx|scss)',
],
outputs: [
'tgui/public/tgui.bundle.css',
'tgui/public/tgui.bundle.js',
'tgui/public/tgui-panel.bundle.css',
'tgui/public/tgui-panel.bundle.js',
],
executes: async () => {
await yarn('webpack-cli', '--mode=production');
},
});
export const TguiEslintTarget = new Juke.Target({
dependsOn: [YarnTarget],
executes: async ({ args }) => {
await yarn(
'eslint', 'packages',
'--fix', '--ext', '.js,.cjs,.ts,.tsx',
...args
);
},
});
export const TguiTscTarget = new Juke.Target({
dependsOn: [YarnTarget],
executes: async () => {
await yarn('tsc');
},
});
export const TguiTestTarget = new Juke.Target({
dependsOn: [YarnTarget],
executes: async ({ args }) => {
await yarn('jest', ...args);
},
});
export const TguiLintTarget = new Juke.Target({
dependsOn: [YarnTarget, TguiEslintTarget, TguiTscTarget, TguiTestTarget],
});
export const TguiDevTarget = new Juke.Target({
dependsOn: [YarnTarget],
executes: async ({ args }) => {
await yarn('node', 'packages/tgui-dev-server/index.js', ...args);
},
});
export const TguiAnalyzeTarget = new Juke.Target({
dependsOn: [YarnTarget],
executes: async () => {
await yarn('webpack-cli', '--mode=production', '--analyze');
},
});
export const TestTarget = new Juke.Target({
dependsOn: [DmTestTarget, TguiTestTarget],
});
export const LintTarget = new Juke.Target({
dependsOn: [TguiLintTarget],
});
export const BuildTarget = new Juke.Target({
dependsOn: [TguiTarget, TgFontTarget, DmTarget],
});
export const ServerTarget = new Juke.Target({
dependsOn: [BuildTarget],
executes: async ({ get }) => {
const port = get(PortParameter) || '1337';
await DreamDaemon(`${DME_NAME}.dmb`, port, '-trusted');
},
});
export const AllTarget = new Juke.Target({
dependsOn: [TestTarget, LintTarget, BuildTarget],
});
/**
* Removes the immediate build junk to produce clean builds.
*/
export const CleanTarget = new Juke.Target({
executes: async () => {
Juke.rm('*.dmb');
Juke.rm('*.rsc');
Juke.rm('*.mdme');
Juke.rm('*.mdme*');
Juke.rm('*.m.*');
Juke.rm('_maps/templates.dm');
Juke.rm('tgui/public/.tmp', { recursive: true });
Juke.rm('tgui/public/*.map');
Juke.rm('tgui/public/*.chunk.*');
Juke.rm('tgui/public/*.bundle.*');
Juke.rm('tgui/public/*.hot-update.*');
Juke.rm('tgui/packages/tgfont/dist', { recursive: true });
Juke.rm('tgui/.yarn/cache', { recursive: true });
Juke.rm('tgui/.yarn/unplugged', { recursive: true });
Juke.rm('tgui/.yarn/webpack', { recursive: true });
Juke.rm('tgui/.yarn/build-state.yml');
Juke.rm('tgui/.yarn/install-state.gz');
Juke.rm('tgui/.yarn/install-target');
Juke.rm('tgui/.pnp.*');
},
});
/**
* Removes more junk at expense of much slower initial builds.
*/
export const DistCleanTarget = new Juke.Target({
dependsOn: [CleanTarget],
executes: async () => {
Juke.logger.info('Cleaning up data/logs');
Juke.rm('data/logs', { recursive: true });
Juke.logger.info('Cleaning up bootstrap cache');
Juke.rm('tools/bootstrap/.cache', { recursive: true });
Juke.logger.info('Cleaning up global yarn cache');
await yarn('cache', 'clean', '--all');
},
});
/**
* Prepends the defines to the .dme.
* Does not clean them up, as this is intended for TGS which
* clones new copies anyway.
*/
const prependDefines = (...defines) => {
const dmeContents = fs.readFileSync(`${DME_NAME}.dme`);
const textToWrite = defines.map(define => `#define ${define}\n`);
fs.writeFileSync(`${DME_NAME}.dme`, `${textToWrite}\n${dmeContents}`);
};
export const TgsTarget = new Juke.Target({
dependsOn: [TguiTarget, TgFontTarget],
executes: async () => {
Juke.logger.info('Prepending TGS define');
prependDefines('TGS');
},
});
const TGS_MODE = process.env.CBT_BUILD_MODE === 'TGS';
export default TGS_MODE ? TgsTarget : BuildTarget;
| Citadel-Station-13/Citadel-Station-13 | tools/build/build.js | JavaScript | agpl-3.0 | 7,802 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Order.name'
db.add_column('valueaccounting_order', 'name',
self.gf('django.db.models.fields.CharField')(default='', max_length=255, blank=True),
keep_default=False)
# Adding field 'EconomicResource.independent_demand'
db.add_column('valueaccounting_economicresource', 'independent_demand',
self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='dependent_resources', null=True, to=orm['valueaccounting.Order']),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Order.name'
db.delete_column('valueaccounting_order', 'name')
# Deleting field 'EconomicResource.independent_demand'
db.delete_column('valueaccounting_economicresource', 'independent_demand_id')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'valueaccounting.agentassociation': {
'Meta': {'object_name': 'AgentAssociation'},
'association_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'associations'", 'to': "orm['valueaccounting.AssociationType']"}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'from_agent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'associations_from'", 'to': "orm['valueaccounting.EconomicAgent']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'to_agent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'associations_to'", 'to': "orm['valueaccounting.EconomicAgent']"})
},
'valueaccounting.agentresourcetype': {
'Meta': {'object_name': 'AgentResourceType'},
'agent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'resource_types'", 'to': "orm['valueaccounting.EconomicAgent']"}),
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'arts_changed'", 'null': 'True', 'to': "orm['auth.User']"}),
'changed_date': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'arts_created'", 'null': 'True', 'to': "orm['auth.User']"}),
'created_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'event_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'agent_resource_types'", 'to': "orm['valueaccounting.EventType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'lead_time': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'agents'", 'to': "orm['valueaccounting.EconomicResourceType']"}),
'score': ('django.db.models.fields.DecimalField', [], {'default': "'0.0'", 'max_digits': '8', 'decimal_places': '2'}),
'unit_of_value': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'agent_resource_value_units'", 'null': 'True', 'to': "orm['valueaccounting.Unit']"}),
'value': ('django.db.models.fields.DecimalField', [], {'default': "'0.0'", 'max_digits': '8', 'decimal_places': '2'})
},
'valueaccounting.agenttype': {
'Meta': {'ordering': "('name',)", 'object_name': 'AgentType'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'member_type': ('django.db.models.fields.CharField', [], {'default': "'active'", 'max_length': '12'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'sub-agents'", 'null': 'True', 'to': "orm['valueaccounting.AgentType']"}),
'party_type': ('django.db.models.fields.CharField', [], {'default': "'individual'", 'max_length': '12'})
},
'valueaccounting.agentuser': {
'Meta': {'object_name': 'AgentUser'},
'agent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'users'", 'to': "orm['valueaccounting.EconomicAgent']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'agent'", 'unique': 'True', 'to': "orm['auth.User']"})
},
'valueaccounting.associationtype': {
'Meta': {'object_name': 'AssociationType'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'})
},
'valueaccounting.cachedeventsummary': {
'Meta': {'ordering': "('agent', 'project', 'resource_type')", 'object_name': 'CachedEventSummary'},
'agent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'cached_events'", 'null': 'True', 'to': "orm['valueaccounting.EconomicAgent']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'importance': ('django.db.models.fields.DecimalField', [], {'default': "'1'", 'max_digits': '3', 'decimal_places': '0'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'cached_events'", 'null': 'True', 'to': "orm['valueaccounting.Project']"}),
'quantity': ('django.db.models.fields.DecimalField', [], {'default': "'0.0'", 'max_digits': '8', 'decimal_places': '2'}),
'reputation': ('django.db.models.fields.DecimalField', [], {'default': "'1.00'", 'max_digits': '8', 'decimal_places': '2'}),
'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'cached_events'", 'null': 'True', 'to': "orm['valueaccounting.EconomicResourceType']"}),
'resource_type_rate': ('django.db.models.fields.DecimalField', [], {'default': "'1.0'", 'max_digits': '8', 'decimal_places': '2'}),
'value': ('django.db.models.fields.DecimalField', [], {'default': "'0.0'", 'max_digits': '8', 'decimal_places': '2'})
},
'valueaccounting.commitment': {
'Meta': {'ordering': "('due_date',)", 'object_name': 'Commitment'},
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'commitments_changed'", 'null': 'True', 'to': "orm['auth.User']"}),
'changed_date': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'commitment_date': ('django.db.models.fields.DateField', [], {'default': 'datetime.date.today'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'commitments_created'", 'null': 'True', 'to': "orm['auth.User']"}),
'created_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'due_date': ('django.db.models.fields.DateField', [], {}),
'event_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'commitments'", 'to': "orm['valueaccounting.EventType']"}),
'exchange': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'commitments'", 'null': 'True', 'to': "orm['valueaccounting.Exchange']"}),
'finished': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'from_agent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'given_commitments'", 'null': 'True', 'to': "orm['valueaccounting.EconomicAgent']"}),
'from_agent_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'given_commitments'", 'null': 'True', 'to': "orm['valueaccounting.AgentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'independent_demand': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'dependent_commitments'", 'null': 'True', 'to': "orm['valueaccounting.Order']"}),
'order': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'commitments'", 'null': 'True', 'to': "orm['valueaccounting.Order']"}),
'process': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'commitments'", 'null': 'True', 'to': "orm['valueaccounting.Process']"}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'commitments'", 'null': 'True', 'to': "orm['valueaccounting.Project']"}),
'quality': ('django.db.models.fields.DecimalField', [], {'default': "'0'", 'max_digits': '3', 'decimal_places': '0'}),
'quantity': ('django.db.models.fields.DecimalField', [], {'max_digits': '8', 'decimal_places': '2'}),
'resource': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'commitments'", 'null': 'True', 'to': "orm['valueaccounting.EconomicResource']"}),
'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'commitments'", 'null': 'True', 'to': "orm['valueaccounting.EconomicResourceType']"}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
'start_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'to_agent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'taken_commitments'", 'null': 'True', 'to': "orm['valueaccounting.EconomicAgent']"}),
'unit_of_quantity': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'commitment_qty_units'", 'null': 'True', 'to': "orm['valueaccounting.Unit']"}),
'unit_of_value': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'commitment_value_units'", 'null': 'True', 'to': "orm['valueaccounting.Unit']"}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'value': ('django.db.models.fields.DecimalField', [], {'default': "'0.0'", 'max_digits': '8', 'decimal_places': '2'})
},
'valueaccounting.compensation': {
'Meta': {'ordering': "('compensation_date',)", 'object_name': 'Compensation'},
'compensating_event': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'compensations'", 'to': "orm['valueaccounting.EconomicEvent']"}),
'compensating_value': ('django.db.models.fields.DecimalField', [], {'max_digits': '8', 'decimal_places': '2'}),
'compensation_date': ('django.db.models.fields.DateField', [], {'default': 'datetime.date.today'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'initiating_event': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'initiated_compensations'", 'to': "orm['valueaccounting.EconomicEvent']"})
},
'valueaccounting.economicagent': {
'Meta': {'ordering': "('nick',)", 'object_name': 'EconomicAgent'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'agent_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'agents'", 'to': "orm['valueaccounting.AgentType']"}),
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'agents_changed'", 'null': 'True', 'to': "orm['auth.User']"}),
'changed_date': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'agents_created'", 'null': 'True', 'to': "orm['auth.User']"}),
'created_date': ('django.db.models.fields.DateField', [], {'default': 'datetime.date.today'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '96', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'latitude': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'longitude': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'nick': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}),
'photo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'photo_url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'reputation': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'max_digits': '8', 'decimal_places': '2'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
},
'valueaccounting.economicevent': {
'Meta': {'ordering': "('-event_date',)", 'object_name': 'EconomicEvent'},
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'events_changed'", 'null': 'True', 'to': "orm['auth.User']"}),
'commitment': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'fulfillment_events'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': "orm['valueaccounting.Commitment']"}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'events_created'", 'null': 'True', 'to': "orm['auth.User']"}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'event_date': ('django.db.models.fields.DateField', [], {}),
'event_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'events'", 'to': "orm['valueaccounting.EventType']"}),
'exchange': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'events'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': "orm['valueaccounting.Exchange']"}),
'from_agent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'given_events'", 'null': 'True', 'to': "orm['valueaccounting.EconomicAgent']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_contribution': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'process': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'events'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': "orm['valueaccounting.Process']"}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'events'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': "orm['valueaccounting.Project']"}),
'quality': ('django.db.models.fields.DecimalField', [], {'default': "'0'", 'max_digits': '3', 'decimal_places': '0'}),
'quantity': ('django.db.models.fields.DecimalField', [], {'max_digits': '8', 'decimal_places': '2'}),
'resource': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'events'", 'null': 'True', 'to': "orm['valueaccounting.EconomicResource']"}),
'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'events'", 'to': "orm['valueaccounting.EconomicResourceType']"}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
'to_agent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'taken_events'", 'null': 'True', 'to': "orm['valueaccounting.EconomicAgent']"}),
'unit_of_quantity': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'event_qty_units'", 'null': 'True', 'to': "orm['valueaccounting.Unit']"}),
'unit_of_value': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'event_value_units'", 'null': 'True', 'to': "orm['valueaccounting.Unit']"}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'value': ('django.db.models.fields.DecimalField', [], {'default': "'0.0'", 'max_digits': '8', 'decimal_places': '2'})
},
'valueaccounting.economicresource': {
'Meta': {'ordering': "('resource_type', 'identifier')", 'object_name': 'EconomicResource'},
'author': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'authored_resources'", 'null': 'True', 'to': "orm['valueaccounting.EconomicAgent']"}),
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'resources_changed'", 'null': 'True', 'to': "orm['auth.User']"}),
'changed_date': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'resources_created'", 'null': 'True', 'to': "orm['auth.User']"}),
'created_date': ('django.db.models.fields.DateField', [], {'default': 'datetime.date.today'}),
'custodian': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'custody_resources'", 'null': 'True', 'to': "orm['valueaccounting.EconomicAgent']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'identifier': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
'independent_demand': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'dependent_resources'", 'null': 'True', 'to': "orm['valueaccounting.Order']"}),
'notes': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'owned_resources'", 'null': 'True', 'to': "orm['valueaccounting.EconomicAgent']"}),
'photo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'photo_url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'quality': ('django.db.models.fields.DecimalField', [], {'default': "'0'", 'null': 'True', 'max_digits': '3', 'decimal_places': '0', 'blank': 'True'}),
'quantity': ('django.db.models.fields.DecimalField', [], {'default': "'1.00'", 'max_digits': '8', 'decimal_places': '2'}),
'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'resources'", 'to': "orm['valueaccounting.EconomicResourceType']"}),
'unit_of_quantity': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'resource_qty_units'", 'null': 'True', 'to': "orm['valueaccounting.Unit']"}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
},
'valueaccounting.economicresourcetype': {
'Meta': {'ordering': "('name',)", 'object_name': 'EconomicResourceType'},
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'resource_types_changed'", 'null': 'True', 'to': "orm['auth.User']"}),
'changed_date': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'resource_types_created'", 'null': 'True', 'to': "orm['auth.User']"}),
'created_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['valueaccounting.EconomicResourceType']"}),
'photo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'photo_url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'rate': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'max_digits': '6', 'decimal_places': '2'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
'substitutable': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'unit': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'resource_units'", 'null': 'True', 'to': "orm['valueaccounting.Unit']"}),
'unit_of_use': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'units_of_use'", 'null': 'True', 'to': "orm['valueaccounting.Unit']"}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
},
'valueaccounting.eventtype': {
'Meta': {'ordering': "('label',)", 'object_name': 'EventType'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'inverse_label': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}),
'label': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'related_to': ('django.db.models.fields.CharField', [], {'default': "'process'", 'max_length': '12'}),
'relationship': ('django.db.models.fields.CharField', [], {'default': "'in'", 'max_length': '12'}),
'resource_effect': ('django.db.models.fields.CharField', [], {'max_length': '12'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
'unit_type': ('django.db.models.fields.CharField', [], {'max_length': '12', 'blank': 'True'})
},
'valueaccounting.exchange': {
'Meta': {'object_name': 'Exchange'},
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'exchanges_changed'", 'null': 'True', 'to': "orm['auth.User']"}),
'changed_date': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'exchanges_created'", 'null': 'True', 'to': "orm['auth.User']"}),
'created_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'notes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'process_pattern': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'exchanges'", 'null': 'True', 'to': "orm['valueaccounting.ProcessPattern']"}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'exchanges'", 'null': 'True', 'to': "orm['valueaccounting.Project']"}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
'start_date': ('django.db.models.fields.DateField', [], {}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'use_case': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'exchanges'", 'null': 'True', 'to': "orm['valueaccounting.UseCase']"})
},
'valueaccounting.facet': {
'Meta': {'ordering': "('name',)", 'object_name': 'Facet'},
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'})
},
'valueaccounting.facetvalue': {
'Meta': {'ordering': "('facet', 'value')", 'unique_together': "(('facet', 'value'),)", 'object_name': 'FacetValue'},
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'facet': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'values'", 'to': "orm['valueaccounting.Facet']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '32'})
},
'valueaccounting.feature': {
'Meta': {'ordering': "('name',)", 'object_name': 'Feature'},
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'features_changed'", 'null': 'True', 'to': "orm['auth.User']"}),
'changed_date': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'features_created'", 'null': 'True', 'to': "orm['auth.User']"}),
'created_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'event_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'features'", 'to': "orm['valueaccounting.EventType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'process_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'features'", 'null': 'True', 'to': "orm['valueaccounting.ProcessType']"}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'features'", 'to': "orm['valueaccounting.EconomicResourceType']"}),
'quantity': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'max_digits': '8', 'decimal_places': '2'}),
'unit_of_quantity': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'feature_units'", 'null': 'True', 'to': "orm['valueaccounting.Unit']"})
},
'valueaccounting.help': {
'Meta': {'ordering': "('page',)", 'object_name': 'Help'},
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'page': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '16'})
},
'valueaccounting.option': {
'Meta': {'ordering': "('component',)", 'object_name': 'Option'},
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'options_changed'", 'null': 'True', 'to': "orm['auth.User']"}),
'changed_date': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'component': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'options'", 'to': "orm['valueaccounting.EconomicResourceType']"}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'options_created'", 'null': 'True', 'to': "orm['auth.User']"}),
'created_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'feature': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'options'", 'to': "orm['valueaccounting.Feature']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'valueaccounting.order': {
'Meta': {'ordering': "('due_date',)", 'object_name': 'Order'},
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'orders_changed'", 'null': 'True', 'to': "orm['auth.User']"}),
'changed_date': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'orders_created'", 'null': 'True', 'to': "orm['auth.User']"}),
'created_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'due_date': ('django.db.models.fields.DateField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'order_date': ('django.db.models.fields.DateField', [], {'default': 'datetime.date.today'}),
'order_type': ('django.db.models.fields.CharField', [], {'default': "'customer'", 'max_length': '12'}),
'provider': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'sales_orders'", 'null': 'True', 'to': "orm['valueaccounting.EconomicAgent']"}),
'receiver': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'purchase_orders'", 'null': 'True', 'to': "orm['valueaccounting.EconomicAgent']"})
},
'valueaccounting.patternfacetvalue': {
'Meta': {'ordering': "('pattern', 'event_type', 'facet_value')", 'unique_together': "(('pattern', 'facet_value', 'event_type'),)", 'object_name': 'PatternFacetValue'},
'event_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'patterns'", 'to': "orm['valueaccounting.EventType']"}),
'facet_value': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'patterns'", 'to': "orm['valueaccounting.FacetValue']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'pattern': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'facets'", 'to': "orm['valueaccounting.ProcessPattern']"})
},
'valueaccounting.patternusecase': {
'Meta': {'object_name': 'PatternUseCase'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'pattern': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'use_cases'", 'to': "orm['valueaccounting.ProcessPattern']"}),
'use_case': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'patterns'", 'null': 'True', 'to': "orm['valueaccounting.UseCase']"})
},
'valueaccounting.process': {
'Meta': {'ordering': "('end_date',)", 'object_name': 'Process'},
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'processes_changed'", 'null': 'True', 'to': "orm['auth.User']"}),
'changed_date': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'processes_created'", 'null': 'True', 'to': "orm['auth.User']"}),
'created_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'finished': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'managed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'managed_processes'", 'null': 'True', 'to': "orm['valueaccounting.EconomicAgent']"}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'notes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'owned_processes'", 'null': 'True', 'to': "orm['valueaccounting.EconomicAgent']"}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'sub_processes'", 'null': 'True', 'to': "orm['valueaccounting.Process']"}),
'process_pattern': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'processes'", 'null': 'True', 'to': "orm['valueaccounting.ProcessPattern']"}),
'process_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'processes'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': "orm['valueaccounting.ProcessType']"}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'processes'", 'null': 'True', 'to': "orm['valueaccounting.Project']"}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
'start_date': ('django.db.models.fields.DateField', [], {}),
'started': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
},
'valueaccounting.processpattern': {
'Meta': {'ordering': "('name',)", 'object_name': 'ProcessPattern'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '32'})
},
'valueaccounting.processtype': {
'Meta': {'ordering': "('name',)", 'object_name': 'ProcessType'},
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'process_types_changed'", 'null': 'True', 'to': "orm['auth.User']"}),
'changed_date': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'process_types_created'", 'null': 'True', 'to': "orm['auth.User']"}),
'created_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'estimated_duration': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'sub_process_types'", 'null': 'True', 'to': "orm['valueaccounting.ProcessType']"}),
'process_pattern': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'process_types'", 'null': 'True', 'to': "orm['valueaccounting.ProcessPattern']"}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'process_types'", 'null': 'True', 'to': "orm['valueaccounting.Project']"}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
},
'valueaccounting.processtyperesourcetype': {
'Meta': {'ordering': "('resource_type',)", 'object_name': 'ProcessTypeResourceType'},
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'ptrts_changed'", 'null': 'True', 'to': "orm['auth.User']"}),
'changed_date': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'ptrts_created'", 'null': 'True', 'to': "orm['auth.User']"}),
'created_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'event_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'process_resource_types'", 'to': "orm['valueaccounting.EventType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'process_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'resource_types'", 'to': "orm['valueaccounting.ProcessType']"}),
'quantity': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'max_digits': '8', 'decimal_places': '2'}),
'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'process_types'", 'to': "orm['valueaccounting.EconomicResourceType']"}),
'unit_of_quantity': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'process_resource_qty_units'", 'null': 'True', 'to': "orm['valueaccounting.Unit']"})
},
'valueaccounting.project': {
'Meta': {'ordering': "('name',)", 'object_name': 'Project'},
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'projects_changed'", 'null': 'True', 'to': "orm['auth.User']"}),
'changed_date': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'projects_created'", 'null': 'True', 'to': "orm['auth.User']"}),
'created_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'importance': ('django.db.models.fields.DecimalField', [], {'default': "'0'", 'max_digits': '3', 'decimal_places': '0'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'sub_projects'", 'null': 'True', 'to': "orm['valueaccounting.Project']"}),
'project_team': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'project_team'", 'null': 'True', 'to': "orm['valueaccounting.EconomicAgent']"}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'})
},
'valueaccounting.reciprocity': {
'Meta': {'ordering': "('reciprocity_date',)", 'object_name': 'Reciprocity'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'initiating_commitment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'initiated_commitments'", 'to': "orm['valueaccounting.Commitment']"}),
'reciprocal_commitment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'reciprocal_commitments'", 'to': "orm['valueaccounting.Commitment']"}),
'reciprocity_date': ('django.db.models.fields.DateField', [], {'default': 'datetime.date.today'})
},
'valueaccounting.resourcetypefacetvalue': {
'Meta': {'ordering': "('resource_type', 'facet_value')", 'unique_together': "(('resource_type', 'facet_value'),)", 'object_name': 'ResourceTypeFacetValue'},
'facet_value': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'resource_types'", 'to': "orm['valueaccounting.FacetValue']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'resource_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'facets'", 'to': "orm['valueaccounting.EconomicResourceType']"})
},
'valueaccounting.selectedoption': {
'Meta': {'ordering': "('commitment', 'option')", 'object_name': 'SelectedOption'},
'commitment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'options'", 'to': "orm['valueaccounting.Commitment']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'option': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'commitments'", 'to': "orm['valueaccounting.Option']"})
},
'valueaccounting.unit': {
'Meta': {'ordering': "('name',)", 'object_name': 'Unit'},
'abbrev': ('django.db.models.fields.CharField', [], {'max_length': '8'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'symbol': ('django.db.models.fields.CharField', [], {'max_length': '1', 'blank': 'True'}),
'unit_type': ('django.db.models.fields.CharField', [], {'max_length': '12'})
},
'valueaccounting.usecase': {
'Meta': {'object_name': 'UseCase'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'identifier': ('django.db.models.fields.CharField', [], {'max_length': '12'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'restrict_to_one_pattern': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
}
}
complete_apps = ['valueaccounting'] | thierrymarianne/valuenetwork | valuenetwork/valueaccounting/migrations/0003_auto__add_field_order_name__add_field_economicresource_independent_dem.py | Python | agpl-3.0 | 47,400 |
<?php
// lib/php/init.php 20150101 - 20170305
// Copyright (C) 2015-2017 Mark Constable <markc@renta.net> (AGPL-3.0)
class Init
{
private $t = null;
public function __construct($g)
{
error_log(__METHOD__);
$g->self = str_replace('index.php', '', $_SERVER['PHP_SELF']);
foreach ($g->in as $k => $v)
$g->in[$k] = isset($_REQUEST[$k])
? htmlentities(trim($_REQUEST[$k])) : $v;
$p = 'plugins_' . $g->in['o'];
$t = 'themes_' . $g->in['t'] . '_' . $g->in['o'];
$tt = 'themes_' . $g->in['t'] . '_theme';
$this->t = $thm = class_exists($t) ? new $t($g)
: (class_exists($tt) ? new $tt($g) : new Theme($g));
if (class_exists($p)) $g->out['main'] = (string) new $p($thm);
else $g->out['main'] = "Error: no plugin object!";
foreach ($g->out as $k => $v)
$g->out[$k] = method_exists($thm, $k) ? $thm->$k() : $v;
}
public function __toString() : string
{
error_log(__METHOD__);
$g = $this->t->g;
if ($g->in['x']) {
$xhr = $g->out[$g->in['x']] ?? '';
if ($xhr) return $xhr;
header('Content-Type: application/json');
return json_encode($g->out, JSON_PRETTY_PRINT);
}
return $this->t->html();
}
}
?>
| markc/spe | 05-Autoload/lib/php/init.php | PHP | agpl-3.0 | 1,329 |
package rocks.inspectit.agent.java.proxy;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation for methods which will be proxied.
*
* For every method of a {@link IProxySubject} with this annotation, a delegation method will be placed in the proxy class.
* Methods without this annotation will not be proxied!
*
* @author Jonas Kunz
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ProxyMethod {
//NOCHKON
/**
* @return the full qualified return type of the proxied method. Defaults to the return type of the annotated method.
*/
//NOCHKOFF
String returnType() default "";
//NOCHKON
/**
* @return the name of the proxied method. Defaults to the name of the annotated method.
*/
//NOCHKOFF
String methodName() default "";
//NOCHKON
/**
* @return a list of the full qualified names of all parameter types of the proxied method.
* The types must be subtypes of the annotated Methods types.
* If left empty, this defaults to the annotated methods parameter types.
*/
//NOCHKOFF
String[] parameterTypes() default { };
//NOCHKON
/**
* @return @{code true}, if this method is optional.
* If a method is optional, the proxy generator will silently ignore missing parameter types (specified by {@link #parameterTypes})
* and the method will just not be proxied.
* If a method is not optional (which is the default), the proxy generation will fail in the case of missing depedencies.
*/
//NOCHKOFF
boolean isOptional() default false;
}
| inspectIT/inspectIT | inspectit.agent.java/src/main/java/rocks/inspectit/agent/java/proxy/ProxyMethod.java | Java | agpl-3.0 | 1,651 |
<!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>
<title>SFML - Simple and Fast Multimedia Library</title>
<meta http-equiv="Content-Type" content="text/html;"/>
<meta charset="utf-8"/>
<!--<link rel='stylesheet' type='text/css' href="http://fonts.googleapis.com/css?family=Ubuntu:400,700,400italic"/>-->
<link rel="stylesheet" type="text/css" href="doxygen.css" title="default" media="screen,print" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
</head>
<body>
<div id="banner-container">
<div id="banner">
<span id="sfml">SFML 2.4.0</span>
</div>
</div>
<div id="content">
<!-- Generated by Doxygen 1.8.8 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li class="current"><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="navrow3" class="tabs2">
<ul class="tablist">
<li><a href="functions.html"><span>All</span></a></li>
<li><a href="functions_func.html"><span>Functions</span></a></li>
<li><a href="functions_vars.html"><span>Variables</span></a></li>
<li><a href="functions_type.html"><span>Typedefs</span></a></li>
<li><a href="functions_enum.html"><span>Enumerations</span></a></li>
<li class="current"><a href="functions_eval.html"><span>Enumerator</span></a></li>
<li><a href="functions_rela.html"><span>Related Functions</span></a></li>
</ul>
</div>
<div id="navrow4" class="tabs3">
<ul class="tablist">
<li><a href="functions_eval.html#index_a"><span>a</span></a></li>
<li><a href="functions_eval_b.html#index_b"><span>b</span></a></li>
<li><a href="functions_eval_c.html#index_c"><span>c</span></a></li>
<li><a href="functions_eval_d.html#index_d"><span>d</span></a></li>
<li><a href="functions_eval_e.html#index_e"><span>e</span></a></li>
<li><a href="functions_eval_f.html#index_f"><span>f</span></a></li>
<li><a href="functions_eval_g.html#index_g"><span>g</span></a></li>
<li><a href="functions_eval_h.html#index_h"><span>h</span></a></li>
<li><a href="functions_eval_i.html#index_i"><span>i</span></a></li>
<li><a href="functions_eval_j.html#index_j"><span>j</span></a></li>
<li><a href="functions_eval_k.html#index_k"><span>k</span></a></li>
<li><a href="functions_eval_l.html#index_l"><span>l</span></a></li>
<li><a href="functions_eval_m.html#index_m"><span>m</span></a></li>
<li><a href="functions_eval_n.html#index_n"><span>n</span></a></li>
<li><a href="functions_eval_o.html#index_o"><span>o</span></a></li>
<li><a href="functions_eval_p.html#index_p"><span>p</span></a></li>
<li><a href="functions_eval_q.html#index_q"><span>q</span></a></li>
<li><a href="functions_eval_r.html#index_r"><span>r</span></a></li>
<li><a href="functions_eval_s.html#index_s"><span>s</span></a></li>
<li><a href="functions_eval_t.html#index_t"><span>t</span></a></li>
<li><a href="functions_eval_u.html#index_u"><span>u</span></a></li>
<li><a href="functions_eval_v.html#index_v"><span>v</span></a></li>
<li><a href="functions_eval_w.html#index_w"><span>w</span></a></li>
<li><a href="functions_eval_x.html#index_x"><span>x</span></a></li>
<li><a href="functions_eval_y.html#index_y"><span>y</span></a></li>
<li class="current"><a href="functions_eval_z.html#index_z"><span>z</span></a></li>
</ul>
</div>
</div><!-- top -->
<div class="contents">
 
<h3><a class="anchor" id="index_z"></a>- z -</h3><ul>
<li>Z
: <a class="el" href="classsf_1_1Joystick.html#a48db337092c2e263774f94de6d50baa7a7c37a1240b2dafbbfc5c1a0e23911315">sf::Joystick</a>
, <a class="el" href="classsf_1_1Keyboard.html#acb4cacd7cc5802dec45724cf3314a142a4e12efd6478a2d174264f29b0b41ab43">sf::Keyboard</a>
</li>
<li>Zero
: <a class="el" href="structsf_1_1BlendMode.html#afb9852caf356b53bb0de460c58a9ebbbafda2d66c3c3da15cd3b42338fbf6d2ba">sf::BlendMode</a>
</li>
</ul>
</div><!-- contents -->
</div>
<div id="footer-container">
<div id="footer">
SFML is licensed under the terms and conditions of the <a href="http://www.sfml-dev.org/license.php">zlib/png license</a>.<br>
Copyright © Laurent Gomila ::
Documentation generated by <a href="http://www.doxygen.org/" title="doxygen website">doxygen</a> ::
</div>
</div>
</body>
</html>
| S4m41/WorldMaker | WorldMaker/External/SFML-2.4.0/doc/html/functions_eval_z.html | HTML | agpl-3.0 | 5,475 |
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Collision/b2BroadPhase.h>
b2BroadPhase::b2BroadPhase()
{
m_proxyCount = 0;
m_pairCapacity = 16;
m_pairCount = 0;
m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair));
m_moveCapacity = 16;
m_moveCount = 0;
m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32));
}
b2BroadPhase::~b2BroadPhase()
{
b2Free(m_moveBuffer);
b2Free(m_pairBuffer);
}
int32 b2BroadPhase::CreateProxy(const b2AABB& aabb, void* userData)
{
int32 proxyId = m_tree.CreateProxy(aabb, userData);
++m_proxyCount;
BufferMove(proxyId);
return proxyId;
}
void b2BroadPhase::DestroyProxy(int32 proxyId)
{
UnBufferMove(proxyId);
--m_proxyCount;
m_tree.DestroyProxy(proxyId);
}
void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement)
{
bool buffer = m_tree.MoveProxy(proxyId, aabb, displacement);
if (buffer)
{
BufferMove(proxyId);
}
}
void b2BroadPhase::TouchProxy(int32 proxyId)
{
BufferMove(proxyId);
}
void b2BroadPhase::BufferMove(int32 proxyId)
{
if (m_moveCount == m_moveCapacity)
{
int32* oldBuffer = m_moveBuffer;
m_moveCapacity *= 2;
m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32));
memcpy(m_moveBuffer, oldBuffer, m_moveCount * sizeof(int32));
b2Free(oldBuffer);
}
m_moveBuffer[m_moveCount] = proxyId;
++m_moveCount;
}
void b2BroadPhase::UnBufferMove(int32 proxyId)
{
for (int32 i = 0; i < m_moveCount; ++i)
{
if (m_moveBuffer[i] == proxyId)
{
m_moveBuffer[i] = e_nullProxy;
}
}
}
// This is called from b2DynamicTree::Query when we are gathering pairs.
bool b2BroadPhase::QueryCallback(int32 proxyId)
{
// A proxy cannot form a pair with itself.
if (proxyId == m_queryProxyId)
{
return true;
}
// Grow the pair buffer as needed.
if (m_pairCount == m_pairCapacity)
{
b2Pair* oldBuffer = m_pairBuffer;
m_pairCapacity *= 2;
m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair));
memcpy(m_pairBuffer, oldBuffer, m_pairCount * sizeof(b2Pair));
b2Free(oldBuffer);
}
m_pairBuffer[m_pairCount].proxyIdA = b2Min(proxyId, m_queryProxyId);
m_pairBuffer[m_pairCount].proxyIdB = b2Max(proxyId, m_queryProxyId);
++m_pairCount;
return true;
}
b2BroadPhase& b2BroadPhase::operator=(const b2BroadPhase& b) {
m_proxyCount = b.m_proxyCount;
m_moveCapacity = b.m_moveCapacity;
m_moveCount = b.m_moveCount;
m_pairCapacity = b.m_pairCapacity;
m_pairCount = b.m_pairCount;
m_queryProxyId = b.m_queryProxyId;
m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair));
m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32));
memcpy(m_pairBuffer, b.m_pairBuffer, m_pairCount * sizeof(b2Pair));
memcpy(m_moveBuffer, b.m_moveBuffer, m_moveCount * sizeof(int32));
m_tree = b.m_tree;
return *this;
} | DaTa-/Hypersomnia | src/3rdparty/Box2D/Collision/b2BroadPhase.cpp | C++ | agpl-3.0 | 3,661 |
<?php
App::uses('ImageStorage', 'FileStorage.Model');
App::uses('FileStorageTestCase', 'FileStorage.TestSuite');
/**
* Image Storage Test
*
* @author Florian Krämer
* @copyright 2012 Florian Krämer
* @license MIT
*/
class ImageStorageTest extends FileStorageTestCase {
/**
* Fixtures
*
* @var array
*/
public $fixtures = array(
'plugin.FileStorage.FileStorage'
);
/**
* setUp
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->Image = new ImageStorage();
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Image);
ClassRegistry::flush();
}
/**
* testProcessVersion
*
* @return void
*/
public function testProcessVersion() {
$this->Image->create();
$result = $this->Image->save(array(
'foreign_key' => 'test-1',
'model' => 'Test',
'file' => array(
'name' => 'titus.jpg',
'size' => 332643,
'tmp_name' => CakePlugin::path('FileStorage') . DS . 'Test' . DS . 'Fixture' . DS . 'File' . DS . 'titus.jpg',
'error' => 0)));
$result = $this->Image->find('first', array(
'conditions' => array(
'id' => $this->Image->getLastInsertId())));
$this->assertTrue(!empty($result) && is_array($result));
$this->assertTrue(file_exists($this->testPath . $result['ImageStorage']['path']));
$path = $this->testPath . $result['ImageStorage']['path'];
$Folder = new Folder($path);
$folderResult = $Folder->read();
$this->assertEqual(count($folderResult[1]), 3);
Configure::write('Media.imageSizes.Test', array(
't200' => array(
'thumbnail' => array(
'mode' => 'outbound',
'width' => 200, 'height' => 200))));
ClassRegistry::init('FileStorage.ImageStorage')->generateHashes();
$Event = new CakeEvent('ImageVersion.createVersion', $this->Image, array(
'record' => $result,
'storage' => StorageManager::adapter('Local'),
'operations' => array(
't200' => array(
'thumbnail' => array(
'mode' => 'outbound',
'width' => 200, 'height' => 200)))));
CakeEventManager::instance()->dispatch($Event);
$path = $this->testPath . $result['ImageStorage']['path'];
$Folder = new Folder($path);
$folderResult = $Folder->read();
$this->assertEqual(count($folderResult[1]), 4);
$Event = new CakeEvent('ImageVersion.removeVersion', $this->Image, array(
'record' => $result,
'storage' => StorageManager::adapter('Local'),
'operations' => array(
't200' => array(
'thumbnail' => array(
'mode' => 'outbound',
'width' => 200, 'height' => 200)))));
CakeEventManager::instance()->dispatch($Event);
$path = $this->testPath . $result['ImageStorage']['path'];
$Folder = new Folder($path);
$folderResult = $Folder->read();
$this->assertEqual(count($folderResult[1]), 3);
}
/**
* testValidateImazeSize
*
* @return void
*/
public function testValidateImazeSize() {
$this->Image->Behaviors->unload('FileStorage.UploadValidator');
$this->Image->validate = array(
'file' => array(
'image' => array(
'rule' => array(
'validateImageSize', array(
'height' => array('>=', 1000),
'width' => array('<=', 1000))),
'message' => 'Invalid image size')));
$this->Image->set(array(
'file' => array(
'tmp_name' => CakePlugin::path('FileStorage') . DS . 'Test' . DS . 'Fixture' . DS . 'File' . DS . 'titus.jpg')));
$this->assertFalse($this->Image->validates());
$this->Image->validate = array(
'file' => array(
'image' => array(
'rule' => array(
'validateImageSize', array(
'height' => array('<=', 1000),
'width' => array('<=', 1000))),
'message' => 'Invalid image size')));
$this->Image->set(array(
'file' => array(
'tmp_name' => CakePlugin::path('FileStorage') . DS . 'Test' . DS . 'Fixture' . DS . 'File' . DS . 'titus.jpg')));
$this->assertTrue($this->Image->validates());
$this->Image->validate = array(
'file' => array(
'image' => array(
'rule' => array(
'validateImageSize', array(
'height' => array('>=', 100),
'width' => array('>=', 100))),
'message' => 'Invalid image size')));
$this->Image->set(array(
'file' => array(
'tmp_name' => CakePlugin::path('FileStorage') . DS . 'Test' . DS . 'Fixture' . DS . 'File' . DS . 'titus.jpg')));
$this->assertTrue($this->Image->validates());
$this->Image->validate = array(
'file' => array(
'image' => array(
'rule' => array(
'validateImageSize', array(
'width' => array('>=', 100))),
'message' => 'Invalid image size')));
$this->Image->set(array(
'file' => array(
'tmp_name' => CakePlugin::path('FileStorage') . DS . 'Test' . DS . 'Fixture' . DS . 'File' . DS . 'titus.jpg')));
$this->assertTrue($this->Image->validates());
$this->Image->validate = array(
'file' => array(
'image' => array(
'rule' => array(
'validateImageSize', array(
'width' => array('==', 512))),
'message' => 'Invalid image size')));
$this->Image->set(array(
'file' => array(
'tmp_name' => CakePlugin::path('FileStorage') . DS . 'Test' . DS . 'Fixture' . DS . 'File' . DS . 'titus.jpg')));
$this->assertTrue($this->Image->validates());
}
} | et304383/passbolt_api | app/Plugin/FileStorage/Test/Case/Model/ImageStorageTest.php | PHP | agpl-3.0 | 5,227 |
var rpc = require('../src/jsonrpc');
/*
Each uses a different syntax
Responses can not be assigned to a source request if the socket version
... it sucks
Moreover jsonrpc2 knows no stream ... it may be helpful, but it is not JSON-RPC2
Michal <misablaha@gmail.com>
*/
/*
Connect to HTTP server
*/
var client = rpc.Client.create(8088, 'localhost');
client.stream('listen', [], function (err, connection){
if (err) {
return printError(err);
}
var counter = 0;
connection.expose('event', function (params){
console.log('Streaming #' + counter + ': ' + params[0]);
counter++;
if (counter > 4) {
connection.end();
}
});
console.log('start listening');
});
/*
Connect to Raw socket server
*/
var socketClient = rpc.Client.create(8089, 'localhost');
socketClient.connectSocket(function (err, conn){
if (err) {
return printError(err);
}
var counter = 0;
socketClient.expose('event', function (params){
console.log('Streaming (socket) #' + counter + ': ' + params[0]);
counter++;
if (counter > 4) {
conn.end();
}
});
conn.call('listen', [], function (err){
if (err) {
return printError(err);
}
});
});
function printError(err){
console.error('RPC Error: ' + err.toString());
}
| gandalfleal/coin | node_modules/json-rpc2/examples/stream-client.js | JavaScript | agpl-3.0 | 1,279 |
/********
* This file is part of Ext.NET.
*
* Ext.NET is free software: you can redistribute it and/or modify
* it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Ext.NET 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 AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
* along with Ext.NET. If not, see <http://www.gnu.org/licenses/>.
*
*
* @version : 1.2.0 - Ext.NET Pro License
* @author : Ext.NET, Inc. http://www.ext.net/
* @date : 2011-09-12
* @copyright : Copyright (c) 2006-2011, Ext.NET, Inc. (http://www.ext.net/). All rights reserved.
* @license : GNU AFFERO GENERAL PUBLIC LICENSE (AGPL) 3.0.
* See license.txt and http://www.ext.net/license/.
* See AGPL License at http://www.gnu.org/licenses/agpl-3.0.txt
********/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Ext.Net
{
public partial class FadeOut
{
/// <summary>
///
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[XmlIgnore]
[JsonIgnore]
public override ConfigOptionsCollection ConfigOptions
{
get
{
ConfigOptionsCollection list = base.ConfigOptions;
list.Add("fxName", new ConfigOption("fxName", null, null, this.FxName ));
return list;
}
}
}
} | daowzq/ExtNet | ext.net.community/Ext.Net/Factory/ConfigOptions/FadeOutConfigOptions.cs | C# | agpl-3.0 | 2,006 |
# -*- coding: utf-8 -*-
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class IRActionsWindow(models.Model):
_inherit = 'ir.actions.act_window'
@api.multi
def read(self, fields=None, context=None, load='_classic_read'):
actions = super(IRActionsWindow, self).read(fields=fields, load=load)
for action in actions:
if action.get('res_model', '') == 'res.partner':
# By default, only show standalone contact
action_context = action.get('context', '{}') or '{}'
if 'search_show_all_positions' not in action_context:
action['context'] = action_context.replace(
'{',
("{'search_show_all_positions': "
"{'is_set': True, 'set_value': False},"),
1)
return actions
| brain-tec/partner-contact | partner_contact_in_several_companies/models/ir_actions.py | Python | agpl-3.0 | 922 |
"""
Logistration API View Tests
"""
from unittest.mock import patch
from urllib.parse import urlencode
import socket
import ddt
from django.conf import settings
from django.urls import reverse
from rest_framework.test import APITestCase
from common.djangoapps.student.models import Registration
from common.djangoapps.student.tests.factories import UserFactory
from openedx.core.djangoapps.user_api.tests.test_views import UserAPITestCase
from openedx.core.djangolib.testing.utils import skip_unless_lms
from common.djangoapps.third_party_auth import pipeline
from common.djangoapps.third_party_auth.tests.testutil import ThirdPartyAuthTestMixin, simulate_running_pipeline
from openedx.core.djangoapps.geoinfo.api import country_code_from_ip
@skip_unless_lms
@ddt.ddt
class MFEContextViewTest(ThirdPartyAuthTestMixin, APITestCase):
"""
MFE context tests
"""
def setUp(self): # pylint: disable=arguments-differ
"""
Test Setup
"""
super().setUp()
self.url = reverse('mfe_context')
self.query_params = {'next': '/dashboard'}
hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)
self.country_code = country_code_from_ip(ip_address)
# Several third party auth providers are created for these tests:
self.configure_google_provider(enabled=True, visible=True)
self.configure_facebook_provider(enabled=True, visible=True)
self.hidden_enabled_provider = self.configure_linkedin_provider(
visible=False,
enabled=True,
)
def _third_party_login_url(self, backend_name, auth_entry, params):
"""
Construct the login URL to start third party authentication
"""
return '{url}?auth_entry={auth_entry}&{param_str}'.format(
url=reverse('social:begin', kwargs={'backend': backend_name}),
auth_entry=auth_entry,
param_str=urlencode(params)
)
def get_provider_data(self, params):
"""
Returns the expected provider data based on providers enabled in test setup
"""
return [
{
'id': 'oa2-facebook',
'name': 'Facebook',
'iconClass': 'fa-facebook',
'iconImage': None,
'skipHintedLogin': False,
'loginUrl': self._third_party_login_url('facebook', 'login', params),
'registerUrl': self._third_party_login_url('facebook', 'register', params)
},
{
'id': 'oa2-google-oauth2',
'name': 'Google',
'iconClass': 'fa-google-plus',
'iconImage': None,
'skipHintedLogin': False,
'loginUrl': self._third_party_login_url('google-oauth2', 'login', params),
'registerUrl': self._third_party_login_url('google-oauth2', 'register', params)
},
]
def get_context(self, params=None, current_provider=None, backend_name=None, add_user_details=False):
"""
Returns the MFE context
"""
return {
'currentProvider': current_provider,
'platformName': settings.PLATFORM_NAME,
'providers': self.get_provider_data(params) if params else [],
'secondaryProviders': [],
'finishAuthUrl': pipeline.get_complete_url(backend_name) if backend_name else None,
'errorMessage': None,
'registerFormSubmitButtonText': 'Create Account',
'syncLearnerProfileData': False,
'pipeline_user_details': {'email': 'test@test.com'} if add_user_details else {},
'countryCode': self.country_code
}
@patch.dict(settings.FEATURES, {'ENABLE_THIRD_PARTY_AUTH': False})
def test_no_third_party_auth_providers(self):
"""
Test that if third party auth is enabled, context returned by API contains
the provider information
"""
response = self.client.get(self.url, self.query_params)
assert response.status_code == 200
assert response.data == self.get_context()
def test_third_party_auth_providers(self):
"""
Test that api returns details of currently enabled third party auth providers
"""
response = self.client.get(self.url, self.query_params)
params = {
'next': self.query_params['next']
}
assert response.status_code == 200
assert response.data == self.get_context(params)
@ddt.data(
('google-oauth2', 'Google', False),
('facebook', 'Facebook', False),
('google-oauth2', 'Google', True)
)
@ddt.unpack
def test_running_pipeline(self, current_backend, current_provider, add_user_details):
"""
Test that when third party pipeline is running, the api returns details
of current provider
"""
email = 'test@test.com' if add_user_details else None
params = {
'next': self.query_params['next']
}
# Simulate a running pipeline
pipeline_target = 'openedx.core.djangoapps.user_authn.views.login_form.third_party_auth.pipeline'
with simulate_running_pipeline(pipeline_target, current_backend, email=email):
response = self.client.get(self.url, self.query_params)
assert response.status_code == 200
assert response.data == self.get_context(params, current_provider, current_backend, add_user_details)
def test_tpa_hint(self):
"""
Test that if tpa_hint is provided, the context returns the third party auth provider
even if it is not visible on the login page
"""
params = {
'next': self.query_params['next']
}
tpa_hint = self.hidden_enabled_provider.provider_id
self.query_params.update({'tpa_hint': tpa_hint})
provider_data = self.get_provider_data(params)
provider_data.append({
'id': self.hidden_enabled_provider.provider_id,
'name': 'LinkedIn',
'iconClass': 'fa-linkedin',
'iconImage': None,
'skipHintedLogin': False,
'loginUrl': self._third_party_login_url('linkedin-oauth2', 'login', params),
'registerUrl': self._third_party_login_url('linkedin-oauth2', 'register', params)
})
response = self.client.get(self.url, self.query_params)
assert response.data['providers'] == provider_data
def test_user_country_code(self):
"""
Test api that returns country code of user
"""
response = self.client.get(self.url, self.query_params)
assert response.status_code == 200
assert response.data['countryCode'] == self.country_code
@skip_unless_lms
class SendAccountActivationEmail(UserAPITestCase):
"""
Test for send activation email view
"""
def setUp(self):
"""
Create a user, then log in.
"""
super().setUp()
self.user = UserFactory()
Registration().register(self.user)
result = self.client.login(username=self.user.username, password="test")
assert result, 'Could not log in'
self.path = reverse('send_account_activation_email')
@patch('common.djangoapps.student.views.management.compose_activation_email')
def test_send_email_to_inactive_user_via_cta_dialog(self, email):
"""
Tests when user clicks on resend activation email on CTA dialog box, system
sends an activation email to the user.
"""
self.user.is_active = False
self.user.save()
self.client.post(self.path)
assert email.called is True, 'method should have been called'
| edx/edx-platform | openedx/core/djangoapps/user_authn/api/tests/test_views.py | Python | agpl-3.0 | 7,808 |
// Copyright 2020 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package azure_test
import (
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-08-01/network"
"github.com/Azure/go-autorest/autorest/to"
"github.com/juju/errors"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"github.com/juju/juju/core/instance"
corenetwork "github.com/juju/juju/core/network"
"github.com/juju/juju/environs"
"github.com/juju/juju/provider/azure/internal/azuretesting"
)
func (s *environSuite) TestSubnetsInstanceIDError(c *gc.C) {
env := s.openEnviron(c)
netEnv, ok := environs.SupportsNetworking(env)
c.Assert(ok, jc.IsTrue)
_, err := netEnv.Subnets(s.callCtx, "some-ID", nil)
c.Assert(err, jc.Satisfies, errors.IsNotSupported)
}
func (s *environSuite) TestSubnetsSuccess(c *gc.C) {
env := s.openEnviron(c)
// We wait for common resource creation, then query subnets
// in the default virtual network created for every model.
s.sender = azuretesting.Senders{
makeSender("/deployments/common", s.commonDeployment),
makeSender("/virtualNetworks/juju-internal-network/subnets", network.SubnetListResult{
Value: &[]network.Subnet{
{
ID: to.StringPtr("provider-sub-id"),
SubnetPropertiesFormat: &network.SubnetPropertiesFormat{
AddressPrefix: to.StringPtr("10.0.0.0/24"),
},
},
{
// Result without an address prefix is ignored.
SubnetPropertiesFormat: &network.SubnetPropertiesFormat{},
},
},
}),
}
netEnv, ok := environs.SupportsNetworking(env)
c.Assert(ok, jc.IsTrue)
subs, err := netEnv.Subnets(s.callCtx, instance.UnknownId, nil)
c.Assert(err, jc.ErrorIsNil)
c.Assert(subs, gc.HasLen, 1)
c.Check(subs[0].ProviderId, gc.Equals, corenetwork.Id("provider-sub-id"))
c.Check(subs[0].CIDR, gc.Equals, "10.0.0.0/24")
}
| freyes/juju | provider/azure/environ_network_test.go | GO | agpl-3.0 | 1,844 |
/*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- 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 ANY
- 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.
*====================================================================*/
/*
* fmorphauto_reg.c
*
* Basic regression test for erosion & dilation: rasterops & dwa.
*
* Tests erosion and dilation from 58 structuring elements
* by comparing the full image rasterop results with the
* automatically generated dwa results.
*
* Results must be identical for all operations.
*/
#ifdef HAVE_CONFIG_H
#include <config_auto.h>
#endif /* HAVE_CONFIG_H */
#include "allheaders.h"
/* defined in morph.c */
LEPT_DLL extern l_int32 MORPH_BC;
int main(int argc,
char **argv)
{
l_int32 i, nsels, same, xorcount;
char *filein, *selname;
PIX *pixs, *pixs1, *pixt1, *pixt2, *pixt3, *pixt4;
SEL *sel;
SELA *sela;
static char mainName[] = "fmorphauto_reg";
if (argc != 2)
return ERROR_INT(" Syntax: fmorphauto_reg filein", mainName, 1);
filein = argv[1];
setLeptDebugOK(1);
if ((pixs = pixRead(filein)) == NULL)
return ERROR_INT("pix not made", mainName, 1);
sela = selaAddBasic(NULL);
nsels = selaGetCount(sela);
for (i = 0; i < nsels; i++)
{
sel = selaGetSel(sela, i);
selname = selGetName(sel);
/* --------- dilation ----------*/
pixt1 = pixDilate(NULL, pixs, sel);
pixs1 = pixAddBorder(pixs, 32, 0);
pixt2 = pixFMorphopGen_1(NULL, pixs1, L_MORPH_DILATE, selname);
pixt3 = pixRemoveBorder(pixt2, 32);
pixt4 = pixXor(NULL, pixt1, pixt3);
pixZero(pixt4, &same);
if (same == 1) {
lept_stderr("dilations are identical for sel %d (%s)\n",
i, selname);
} else {
lept_stderr("dilations differ for sel %d (%s)\n", i, selname);
pixCountPixels(pixt4, &xorcount, NULL);
lept_stderr("Number of pixels in XOR: %d\n", xorcount);
}
pixDestroy(&pixt1);
pixDestroy(&pixt2);
pixDestroy(&pixt3);
pixDestroy(&pixt4);
pixDestroy(&pixs1);
/* --------- erosion with asymmetric b.c ----------*/
resetMorphBoundaryCondition(ASYMMETRIC_MORPH_BC);
lept_stderr("MORPH_BC = %d ... ", MORPH_BC);
pixt1 = pixErode(NULL, pixs, sel);
if (MORPH_BC == ASYMMETRIC_MORPH_BC)
pixs1 = pixAddBorder(pixs, 32, 0); /* OFF border pixels */
else
pixs1 = pixAddBorder(pixs, 32, 1); /* ON border pixels */
pixt2 = pixFMorphopGen_1(NULL, pixs1, L_MORPH_ERODE, selname);
pixt3 = pixRemoveBorder(pixt2, 32);
pixt4 = pixXor(NULL, pixt1, pixt3);
pixZero(pixt4, &same);
if (same == 1) {
lept_stderr("erosions are identical for sel %d (%s)\n", i, selname);
} else {
lept_stderr("erosions differ for sel %d (%s)\n", i, selname);
pixCountPixels(pixt4, &xorcount, NULL);
lept_stderr("Number of pixels in XOR: %d\n", xorcount);
}
pixDestroy(&pixt1);
pixDestroy(&pixt2);
pixDestroy(&pixt3);
pixDestroy(&pixt4);
pixDestroy(&pixs1);
/* --------- erosion with symmetric b.c ----------*/
resetMorphBoundaryCondition(SYMMETRIC_MORPH_BC);
lept_stderr("MORPH_BC = %d ... ", MORPH_BC);
pixt1 = pixErode(NULL, pixs, sel);
if (MORPH_BC == ASYMMETRIC_MORPH_BC)
pixs1 = pixAddBorder(pixs, 32, 0); /* OFF border pixels */
else
pixs1 = pixAddBorder(pixs, 32, 1); /* ON border pixels */
pixt2 = pixFMorphopGen_1(NULL, pixs1, L_MORPH_ERODE, selname);
pixt3 = pixRemoveBorder(pixt2, 32);
pixt4 = pixXor(NULL, pixt1, pixt3);
pixZero(pixt4, &same);
if (same == 1) {
lept_stderr("erosions are identical for sel %d (%s)\n", i, selname);
} else {
lept_stderr("erosions differ for sel %d (%s)\n", i, selname);
pixCountPixels(pixt4, &xorcount, NULL);
lept_stderr("Number of pixels in XOR: %d\n", xorcount);
}
pixDestroy(&pixt1);
pixDestroy(&pixt2);
pixDestroy(&pixt3);
pixDestroy(&pixt4);
pixDestroy(&pixs1);
}
return 0;
}
| papyrussolution/OpenPapyrus | Src/OSF/leptonica/prog/fmorphauto_reg.c | C | agpl-3.0 | 5,692 |
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from erpnext.accounts.report.accounts_receivable.accounts_receivable import ReceivablePayableReport
def execute(filters=None):
args = {
"party_type": "Supplier",
"naming_by": ["Buying Settings", "supp_master_name"],
}
return ReceivablePayableReport(filters).run(args)
| gangadharkadam/v5_erp | erpnext/accounts/report/accounts_payable/accounts_payable.py | Python | agpl-3.0 | 461 |
require 'rails_helper'
feature 'Valuation budgets' do
background do
@valuator = create(:valuator, user: create(:user, username: 'Rachel', email: 'rachel@valuators.org'))
login_as(@valuator.user)
end
scenario 'Disabled with a feature flag' do
Setting['feature.budgets'] = nil
expect{ visit valuation_budgets_path }.to raise_exception(FeatureFlags::FeatureDisabled)
Setting['feature.budgets'] = true
end
context 'Index' do
scenario 'Displaying budgets' do
budget = create(:budget)
visit valuation_budgets_path
expect(page).to have_content(budget.name)
end
scenario 'Filters by phase' do
budget1 = create(:budget)
budget2 = create(:budget, :accepting)
budget3 = create(:budget, :selecting)
budget4 = create(:budget, :balloting)
budget5 = create(:budget, :finished)
visit valuation_budgets_path
expect(page).to have_content(budget1.name)
expect(page).to have_content(budget2.name)
expect(page).to have_content(budget3.name)
expect(page).to have_content(budget4.name)
expect(page).to_not have_content(budget5.name)
end
end
end
| artofhuman/consul | spec/features/valuation/budgets_spec.rb | Ruby | agpl-3.0 | 1,165 |
'use strict';
var _ = require('lodash');
module.exports = function calcDelta (oldData, newData) {
var delta = {'delta': true};
var changesFound = false;
// if there's no updates done so far, just return the full set
if (!oldData.sgvs) { return newData; }
function nsArrayTreatments(oldArray, newArray) {
var result = [];
// check for add, change
var l = newArray.length;
var m = oldArray.length;
var found, founddiff, no, oo, i, j;
for (i = 0; i < l; i++) {
no = newArray[i];
found = false;
founddiff = false;
for (j = 0; j < m; j++) {
oo = oldArray[j];
no._id = no._id.toString();
if (no._id === oo._id) {
found = true;
var oo_copy = _.clone(oo);
var no_copy = _.clone(no);
delete oo_copy.mgdl;
delete no_copy.mgdl;
if (!_.isEqual(oo_copy, no_copy)) {
founddiff = true;
}
break;
}
}
if (founddiff) {
var nno = _.clone(no);
nno.action = 'update';
result.push(nno);
}
if (!found) {
result.push(no);
}
}
//check for delete
for (j = 0; j < m; j++) {
oo = oldArray[j];
found = false;
for (i = 0; i < l; i++) {
no = newArray[i];
if (no._id === oo._id) {
found = true;
break;
}
}
if (!found) {
result.push({ _id: oo._id, action: 'remove' });
}
}
return result;
}
function nsArrayDiff(oldArray, newArray) {
var seen = {};
var l = oldArray.length;
for (var i = 0; i < l; i++) {
seen[oldArray[i].mills] = true;
}
var result = [];
l = newArray.length;
for (var j = 0; j < l; j++) {
if (!seen.hasOwnProperty(newArray[j].mills)) {
result.push(newArray[j]);
}
}
return result;
}
function sort(values) {
values.sort(function sorter(a, b) {
return a.mills - b.mills;
});
}
function compressArrays(delta, newData) {
// array compression
var compressibleArrays = ['sgvs', 'treatments', 'mbgs', 'cals', 'devicestatus'];
var changesFound = false;
for (var array in compressibleArrays) {
if (compressibleArrays.hasOwnProperty(array)) {
var a = compressibleArrays[array];
if (newData.hasOwnProperty(a)) {
// if previous data doesn't have the property (first time delta?), just assign data over
if (!oldData.hasOwnProperty(a)) {
delta[a] = newData[a];
changesFound = true;
continue;
}
// Calculate delta and assign delta over if changes were found
var deltaData = (a === 'treatments' ? nsArrayTreatments(oldData[a], newData[a]) : nsArrayDiff(oldData[a], newData[a]));
if (deltaData.length > 0) {
console.log('delta changes found on', a);
changesFound = true;
sort(deltaData);
delta[a] = deltaData;
}
}
}
}
return {'delta': delta, 'changesFound': changesFound};
}
function deleteSkippables(delta,newData) {
// objects
var skippableObjects = ['profiles'];
var changesFound = false;
for (var object in skippableObjects) {
if (skippableObjects.hasOwnProperty(object)) {
var o = skippableObjects[object];
if (newData.hasOwnProperty(o)) {
if (JSON.stringify(newData[o]) !== JSON.stringify(oldData[o])) {
console.log('delta changes found on', o);
changesFound = true;
delta[o] = newData[o];
}
}
}
}
return {'delta': delta, 'changesFound': changesFound};
}
delta.lastUpdated = newData.lastUpdated;
var compressedDelta = compressArrays(delta, newData);
delta = compressedDelta.delta;
if (compressedDelta.changesFound) { changesFound = true; }
var skippedDelta = deleteSkippables(delta, newData);
delta = skippedDelta.delta;
if (skippedDelta.changesFound) { changesFound = true; }
if (changesFound) { return delta; }
return newData;
};
| ramstrand/cgm-remote-monitor | lib/data/calcdelta.js | JavaScript | agpl-3.0 | 4,119 |
//
//
// Description: This file is part of FET
//
//
// Author: Lalescu Liviu <Please see http://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)>
// Copyright (C) 2003 Liviu Lalescu <http://lalescu.ro/liviu/>
//
/***************************************************************************
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
***************************************************************************/
#include "savetimetableconfirmationform.h"
#include "timetable_defs.h"
SaveTimetableConfirmationForm::SaveTimetableConfirmationForm(QWidget* parent): QDialog(parent)
{
setupUi(this);
continuePushButton->setDefault(true);
connect(continuePushButton, SIGNAL(clicked()), this, SLOT(accept()));
connect(cancelPushButton, SIGNAL(clicked()), this, SLOT(reject()));
connect(dontShowAgainCheckBox, SIGNAL(stateChanged(int)), this, SLOT(dontShowAgainCheckBoxToggled()));
dontShowAgain=dontShowAgainCheckBox->isChecked();
plainTextEdit->setReadOnly(true);
centerWidgetOnScreen(this);
restoreFETDialogGeometry(this);
QString s;
s+=tr("Please read carefully the description below:");
s+="\n\n";
s+=tr("This option is only useful if you need to lock current timetable into a file."
" Locking means that there will be added constraints activity preferred starting time and"
" activity preferred room with 100% importance for each activity to fix it at current place in current timetable."
" You can save this timetable as an ordinary .fet file; when you'll open it, you'll see all old inputted data (activities, teachers, etc.)"
" and the locking constraints as the last time/space constraints."
" You can unlock some of these activities (by removing constraints) if small changes appear in the configuration, and generate again"
" and the remaining locking constraints will be respected.");
s+="\n\n";
s+=tr("The added constraints will have the 'permanently locked' tag set to false, so you can also unlock the activities from the "
"'Timetable' menu, without interfering with the initial constraints which are made by you 'permanently locked'");
s+="\n\n";
s+=tr("This option is useful for institutions where you obtain a timetable, then some small changes appear,"
" and you need to regenerate timetable, but respecting in a large proportion the old timetable");
s+="\n\n";
s+=tr("Current data file will not be affected by anything, locking constraints will only be added to the file you select to save"
" (you can save current datafile and open saved timetable file after that to check it)");
plainTextEdit->setPlainText(s);
}
SaveTimetableConfirmationForm::~SaveTimetableConfirmationForm()
{
saveFETDialogGeometry(this);
}
void SaveTimetableConfirmationForm::dontShowAgainCheckBoxToggled()
{
dontShowAgain=dontShowAgainCheckBox->isChecked();
}
| fet-project/fet | src/interface/savetimetableconfirmationform.cpp | C++ | agpl-3.0 | 3,292 |
shared_examples_for 'Delayed::Worker' do
def job_create(opts = {})
Delayed::Job.create({:payload_object => SimpleJob.new, :queue => Delayed::Worker.queue}.merge(opts))
end
def worker_create(opts = {})
Delayed::Worker.new(opts.merge(:max_priority => nil, :min_priority => nil, :quiet => true))
end
before(:each) do
@worker = worker_create
SimpleJob.runs = 0
Delayed::Worker.on_max_failures = nil
Setting.set('delayed_jobs_sleep_delay', '0.01')
end
describe "running a job" do
it "should not fail when running a job with a % in the name" do
@job = User.send_later_enqueue_args(:name_parts, { no_delay: true }, "Some % Name")
@worker.perform(@job)
end
end
describe "running a batch" do
context "serially" do
it "should run each job in order" do
bar = "bar"
seq = sequence("bar")
bar.expects(:scan).with("b").in_sequence(seq)
bar.expects(:scan).with("a").in_sequence(seq)
bar.expects(:scan).with("r").in_sequence(seq)
batch = Delayed::Batch::PerformableBatch.new(:serial, [
{ :payload_object => Delayed::PerformableMethod.new(bar, :scan, ["b"]) },
{ :payload_object => Delayed::PerformableMethod.new(bar, :scan, ["a"]) },
{ :payload_object => Delayed::PerformableMethod.new(bar, :scan, ["r"]) },
])
batch_job = Delayed::Job.create :payload_object => batch
Delayed::Stats.expects(:job_complete).times(4) # batch, plus all jobs
@worker.perform(batch_job).should == 3
end
it "should succeed regardless of the success/failure of its component jobs" do
batch = Delayed::Batch::PerformableBatch.new(:serial, [
{ :payload_object => Delayed::PerformableMethod.new("foo", :reverse, []) },
{ :payload_object => Delayed::PerformableMethod.new(1, :/, [0]) },
{ :payload_object => Delayed::PerformableMethod.new("bar", :scan, ["r"]) },
])
batch_job = Delayed::Job.create :payload_object => batch
Delayed::Stats.expects(:job_complete).times(3) # batch, plus two successful jobs
@worker.perform(batch_job).should == 3
to_retry = Delayed::Job.list_jobs(:future, 100)
to_retry.size.should eql 1
to_retry[0].payload_object.method.should eql :/
to_retry[0].last_error.should =~ /divided by 0/
to_retry[0].attempts.should == 1
end
it "should retry a failed individual job" do
batch = Delayed::Batch::PerformableBatch.new(:serial, [
{ :payload_object => Delayed::PerformableMethod.new(1, :/, [0]) },
])
batch_job = Delayed::Job.create :payload_object => batch
Delayed::Job.any_instance.expects(:reschedule).once
Delayed::Stats.expects(:job_complete).times(1) # just the batch
@worker.perform(batch_job).should == 1
end
end
end
context "worker prioritization" do
before(:each) do
@worker = Delayed::Worker.new(:max_priority => 5, :min_priority => 2, :quiet => true)
end
it "should only run jobs that are >= min_priority" do
SimpleJob.runs.should == 0
job_create(:priority => 1)
job_create(:priority => 3)
@worker.run
SimpleJob.runs.should == 1
end
it "should only run jobs that are <= max_priority" do
SimpleJob.runs.should == 0
job_create(:priority => 10)
job_create(:priority => 4)
@worker.run
SimpleJob.runs.should == 1
end
end
context "while running with locked jobs" do
before(:each) do
@worker.name = 'worker1'
end
it "should not run jobs locked by another worker" do
job_create(:locked_by => 'other_worker', :locked_at => (Delayed::Job.db_time_now - 1.minutes))
lambda { @worker.run }.should_not change { SimpleJob.runs }
end
it "should run open jobs" do
job_create
lambda { @worker.run }.should change { SimpleJob.runs }.from(0).to(1)
end
end
describe "failed jobs" do
before do
# reset defaults
Delayed::Worker.max_attempts = 25
@job = Delayed::Job.enqueue ErrorJob.new
end
it "should record last_error when destroy_failed_jobs = false, max_attempts = 1" do
Delayed::Worker.on_max_failures = proc { false }
@job.max_attempts = 1
@job.save!
(job = Delayed::Job.get_and_lock_next_available('w1')).should == @job
@worker.perform(job)
old_id = @job.id
@job = Delayed::Job.list_jobs(:failed, 1).first
@job.original_job_id.should == old_id
@job.last_error.should =~ /did not work/
@job.last_error.should =~ /worker_spec.rb/
@job.attempts.should == 1
@job.failed_at.should_not be_nil
@job.run_at.should > Delayed::Job.db_time_now - 10.minutes
@job.run_at.should < Delayed::Job.db_time_now + 10.minutes
# job stays locked after failing, for record keeping of time/worker
@job.should be_locked
Delayed::Job.find_available(100, @job.queue).should == []
end
it "should re-schedule jobs after failing" do
@worker.perform(@job)
@job = Delayed::Job.find(@job.id)
@job.last_error.should =~ /did not work/
@job.last_error.should =~ /sample_jobs.rb:8:in `perform'/
@job.attempts.should == 1
@job.run_at.should > Delayed::Job.db_time_now - 10.minutes
@job.run_at.should < Delayed::Job.db_time_now + 10.minutes
end
it "should notify jobs on failure" do
ErrorJob.failure_runs = 0
@worker.perform(@job)
ErrorJob.failure_runs.should == 1
end
it "should notify jobs on permanent failure" do
(Delayed::Worker.max_attempts - 1).times { @job.reschedule }
ErrorJob.permanent_failure_runs = 0
@worker.perform(@job)
ErrorJob.permanent_failure_runs.should == 1
end
end
context "reschedule" do
before do
@job = Delayed::Job.create :payload_object => SimpleJob.new
end
context "and we want to destroy jobs" do
it "should be destroyed if it failed more than Worker.max_attempts times" do
@job.expects(:destroy)
Delayed::Worker.max_attempts.times { @job.reschedule }
end
it "should not be destroyed if failed fewer than Worker.max_attempts times" do
@job.expects(:destroy).never
(Delayed::Worker.max_attempts - 1).times { @job.reschedule }
end
it "should be destroyed if failed more than Job#max_attempts times" do
Delayed::Worker.max_attempts = 25
@job.expects(:destroy)
@job.max_attempts = 2
@job.save!
2.times { @job.reschedule }
end
end
context "and we don't want to destroy jobs" do
before do
Delayed::Worker.on_max_failures = proc { false }
end
after do
Delayed::Worker.on_max_failures = nil
end
it "should be failed if it failed more than Worker.max_attempts times" do
@job.failed_at.should == nil
Delayed::Worker.max_attempts.times { @job.reschedule }
Delayed::Job.list_jobs(:failed, 100).size.should == 1
end
it "should not be failed if it failed fewer than Worker.max_attempts times" do
(Delayed::Worker.max_attempts - 1).times { @job.reschedule }
@job = Delayed::Job.find(@job.id)
@job.failed_at.should == nil
end
end
context "and we give an on_max_failures callback" do
it "should be failed max_attempts times and cb is false" do
Delayed::Worker.on_max_failures = proc do |job, ex|
job.should == @job
false
end
@job.expects(:fail!)
Delayed::Worker.max_attempts.times { @job.reschedule }
end
it "should be destroyed if it failed max_attempts times and cb is true" do
Delayed::Worker.on_max_failures = proc do |job, ex|
job.should == @job
true
end
@job.expects(:destroy)
Delayed::Worker.max_attempts.times { @job.reschedule }
end
end
end
context "Queue workers" do
before :each do
Delayed::Worker.queue = "Queue workers test"
job_create(:queue => 'queue1')
job_create(:queue => 'queue2')
end
it "should only work off jobs assigned to themselves" do
worker = worker_create(:queue=>'queue1')
SimpleJob.runs.should == 0
worker.run
SimpleJob.runs.should == 1
SimpleJob.runs = 0
worker = worker_create(:queue=>'queue2')
SimpleJob.runs.should == 0
worker.run
SimpleJob.runs.should == 1
end
it "should not work off jobs not assigned to themselves" do
worker = worker_create(:queue=>'queue3')
SimpleJob.runs.should == 0
worker.run
SimpleJob.runs.should == 0
end
it "should get the default queue if none is set" do
queue_name = "default_queue"
Delayed::Worker.queue = queue_name
worker = worker_create(:queue=>nil)
worker.queue.should == queue_name
end
it "should override default queue name if specified in initialize" do
queue_name = "my_queue"
Delayed::Worker.queue = "default_queue"
worker = worker_create(:queue=>queue_name)
worker.queue.should == queue_name
end
end
end
| moh-alsheikh/canvas-lms | vendor/plugins/delayed_job/spec_canvas/worker_spec.rb | Ruby | agpl-3.0 | 9,288 |
default_app_config = 'apps.datasetmanager.apps.datasetmanagerConfig'
| almey/policycompass-services | apps/datasetmanager/__init__.py | Python | agpl-3.0 | 69 |
/*
Copyright <SWGEmu>
See file COPYING for copying conditions.*/
#ifndef FORAGINGEVENT_H_
#define FORAGINGEVENT_H_
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/Zone.h"
#include "server/zone/managers/minigames/ForageManager.h"
namespace server {
namespace zone {
namespace managers {
namespace minigames {
namespace events {
class ForagingEvent : public Task {
ManagedReference<CreatureObject*> player;
int forageType;
float forageX;
float forageY;
String zoneName;
public:
ForagingEvent(CreatureObject* player, int type, float playerX, float playerY, const String& planet) : Task() {
this->player = player;
this->forageType = type;
this->forageX = playerX;
this->forageY = playerY;
this->zoneName = planet;
}
void run() {
ManagedReference<ForageManager*> forageManager = player->getZoneProcessServer()->getForageManager();
if (forageManager != NULL)
forageManager->finishForaging(player, forageType, forageX, forageY, zoneName);
}
};
}
}
}
}
}
using namespace server::zone::managers::minigames::events;
#endif /*FORAGINGEVENT_H_*/
| Chilastra-Reborn/Chilastra-source-code | src/server/zone/managers/minigames/events/ForagingEvent.h | C | agpl-3.0 | 1,108 |
/*
* DataImportOptionsUiMongo.java
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.environment.dataimport;
import org.rstudio.studio.client.workbench.views.environment.dataimport.model.DataImportAssembleResponse;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
public class DataImportOptionsUiMongo extends DataImportOptionsUi
{
private static DataImportOptionsUiMongoUiBinder uiBinder = GWT
.create(DataImportOptionsUiMongoUiBinder.class);
interface DataImportOptionsUiMongoUiBinder
extends UiBinder<Widget, DataImportOptionsUiMongo>
{
}
public DataImportOptionsUiMongo()
{
initWidget(uiBinder.createAndBindUi(this));
}
@Override
public DataImportOptionsMongo getOptions()
{
return DataImportOptionsMongo.create(
nameTextBox_.getValue()
);
}
@Override
public void setAssembleResponse(DataImportAssembleResponse response)
{
nameTextBox_.setText(response.getDataName());
}
@Override
public void clearOptions()
{
nameTextBox_.setText("");
}
@UiField
TextBox nameTextBox_;
}
| jar1karp/rstudio | src/gwt/src/org/rstudio/studio/client/workbench/views/environment/dataimport/DataImportOptionsUiMongo.java | Java | agpl-3.0 | 1,851 |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
* SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
* Copyright (C) 2011 - 2014 Salesagility Ltd.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero 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 SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero 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 SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
********************************************************************************/
/*********************************************************************************
* Description: view handler for step 3 of the import process
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
* All Rights Reserved.
********************************************************************************/
require_once('modules/Import/views/ImportView.php');
require_once('modules/Import/sources/ImportFile.php');
require_once('modules/Import/ImportFileSplitter.php');
require_once('modules/Import/ImportCacheFiles.php');
require_once('modules/Import/ImportDuplicateCheck.php');
require_once('include/upload_file.php');
class ImportViewStep3 extends ImportView
{
protected $pageTitleKey = 'LBL_STEP_3_TITLE';
protected $currentFormID = 'importstep3';
protected $previousAction = 'Confirm';
protected $nextAction = 'dupcheck';
/**
* @see SugarView::display()
*/
public function display()
{
global $mod_strings, $app_strings, $current_user, $sugar_config, $app_list_strings, $locale;
$this->ss->assign("IMPORT_MODULE", $_REQUEST['import_module']);
$has_header = ( isset( $_REQUEST['has_header']) ? 1 : 0 );
$sugar_config['import_max_records_per_file'] = ( empty($sugar_config['import_max_records_per_file']) ? 1000 : $sugar_config['import_max_records_per_file'] );
$this->ss->assign("CURRENT_STEP", $this->currentStep);
// attempt to lookup a preexisting field map
// use the custom one if specfied to do so in step 1
$mapping_file = new ImportMap();
$field_map = $mapping_file->set_get_import_wizard_fields();
$default_values = array();
$ignored_fields = array();
if ( !empty( $_REQUEST['source_id']))
{
$GLOBALS['log']->fatal("Loading import map properties.");
$mapping_file = new ImportMap();
$mapping_file->retrieve( $_REQUEST['source_id'],false);
$_REQUEST['source'] = $mapping_file->source;
$has_header = $mapping_file->has_header;
if (isset($mapping_file->delimiter))
$_REQUEST['custom_delimiter'] = $mapping_file->delimiter;
if (isset($mapping_file->enclosure))
$_REQUEST['custom_enclosure'] = htmlentities($mapping_file->enclosure);
$field_map = $mapping_file->getMapping();
//print_r($field_map);die();
$default_values = $mapping_file->getDefaultValues();
$this->ss->assign("MAPNAME",$mapping_file->name);
$this->ss->assign("CHECKMAP",'checked="checked" value="on"');
}
else
{
$classname = $this->getMappingClassName(ucfirst($_REQUEST['source']));
//Set the $_REQUEST['source'] to be 'other' for ImportMapOther special case
if($classname == 'ImportMapOther')
{
$_REQUEST['source'] = 'other';
}
if (class_exists($classname))
{
$mapping_file = new $classname;
$ignored_fields = $mapping_file->getIgnoredFields($_REQUEST['import_module']);
$field_map2 = $mapping_file->getMapping($_REQUEST['import_module']);
$field_map = array_merge($field_map,$field_map2);
}
}
$delimiter = $this->getRequestDelimiter();
$this->ss->assign("CUSTOM_DELIMITER", $delimiter);
$this->ss->assign("CUSTOM_ENCLOSURE", ( !empty($_REQUEST['custom_enclosure']) ? $_REQUEST['custom_enclosure'] : "" ));
//populate import locale values from import mapping if available, these values will be used througout the rest of the code path
$uploadFileName = $_REQUEST['file_name'];
// Now parse the file and look for errors
$importFile = new ImportFile( $uploadFileName, $delimiter, html_entity_decode($_REQUEST['custom_enclosure'],ENT_QUOTES), FALSE);
if ( !$importFile->fileExists() ) {
$this->_showImportError($mod_strings['LBL_CANNOT_OPEN'],$_REQUEST['import_module'],'Step2');
return;
}
$charset = $importFile->autoDetectCharacterSet();
// retrieve first 3 rows
$rows = array();
//Keep track of the largest row count found.
$maxFieldCount = 0;
for ( $i = 0; $i < 3; $i++ )
{
$rows[] = $importFile->getNextRow();
$maxFieldCount = $importFile->getFieldCount() > $maxFieldCount ? $importFile->getFieldCount() : $maxFieldCount;
}
$ret_field_count = $maxFieldCount;
// Bug 14689 - Parse the first data row to make sure it has non-empty data in it
$isempty = true;
if ( $rows[(int)$has_header] != false ) {
foreach ( $rows[(int)$has_header] as $value ) {
if ( strlen(trim($value)) > 0 ) {
$isempty = false;
break;
}
}
}
if ($isempty || $rows[(int)$has_header] == false) {
$this->_showImportError($mod_strings['LBL_NO_LINES'],$_REQUEST['import_module'],'Step2');
return;
}
// save first row to send to step 4
$this->ss->assign("FIRSTROW", htmlentities(json_encode($rows[0])));
// Now build template
$this->ss->assign("TMP_FILE", $uploadFileName );
$this->ss->assign("SOURCE", $_REQUEST['source'] );
$this->ss->assign("TYPE", $_REQUEST['type'] );
$this->ss->assign("DELETE_INLINE_PNG", SugarThemeRegistry::current()->getImage('basic_search','align="absmiddle" alt="'.$app_strings['LNK_DELETE'].'" border="0"'));
$this->ss->assign("PUBLISH_INLINE_PNG", SugarThemeRegistry::current()->getImage('advanced_search','align="absmiddle" alt="'.$mod_strings['LBL_PUBLISH'].'" border="0"'));
$this->instruction = 'LBL_SELECT_MAPPING_INSTRUCTION';
$this->ss->assign('INSTRUCTION', $this->getInstruction());
$this->ss->assign("MODULE_TITLE", $this->getModuleTitle(false));
$this->ss->assign("STEP4_TITLE",
strip_tags(str_replace("\n","",getClassicModuleTitle(
$mod_strings['LBL_MODULE_NAME'],
array($mod_strings['LBL_MODULE_NAME'],$mod_strings['LBL_STEP_4_TITLE']),
false
)))
);
$this->ss->assign("HEADER", $app_strings['LBL_IMPORT']." ". $mod_strings['LBL_MODULE_NAME']);
// we export it as email_address, but import as email1
$field_map['email_address'] = 'email1';
// build each row; row count is determined by the the number of fields in the import file
$columns = array();
$mappedFields = array();
// this should be populated if the request comes from a 'Back' button click
$importColumns = $this->getImportColumns();
$column_sel_from_req = false;
if (!empty($importColumns)) {
$column_sel_from_req = true;
}
for($field_count = 0; $field_count < $ret_field_count; $field_count++) {
// See if we have any field map matches
$defaultValue = "";
// Bug 31260 - If the data rows have more columns than the header row, then just add a new header column
if ( !isset($rows[0][$field_count]) )
$rows[0][$field_count] = '';
// See if we can match the import row to a field in the list of fields to import
$firstrow_name = trim(str_replace(":","",$rows[0][$field_count]));
if ($has_header && isset( $field_map[$firstrow_name] ) ) {
$defaultValue = $field_map[$firstrow_name];
}
elseif (isset($field_map[$field_count])) {
$defaultValue = $field_map[$field_count];
}
elseif (empty( $_REQUEST['source_id'])) {
$defaultValue = trim($rows[0][$field_count]);
}
// build string of options
$fields = $this->bean->get_importable_fields();
$options = array();
$defaultField = '';
global $current_language;
$moduleStrings = return_module_language($current_language, $this->bean->module_dir);
foreach ( $fields as $fieldname => $properties ) {
// get field name
if (!empty($moduleStrings['LBL_EXPORT_'.strtoupper($fieldname)]) )
{
$displayname = str_replace(":","", $moduleStrings['LBL_EXPORT_'.strtoupper($fieldname)] );
}
else if (!empty ($properties['vname']))
{
$displayname = str_replace(":","",translate($properties['vname'] ,$this->bean->module_dir));
}
else
$displayname = str_replace(":","",translate($properties['name'] ,$this->bean->module_dir));
// see if this is required
$req_mark = "";
$req_class = "";
if ( array_key_exists($fieldname, $this->bean->get_import_required_fields()) ) {
$req_mark = ' ' . $app_strings['LBL_REQUIRED_SYMBOL'];
$req_class = ' class="required" ';
}
// see if we have a match
$selected = '';
if ($column_sel_from_req && isset($importColumns[$field_count])) {
if ($fieldname == $importColumns[$field_count]) {
$selected = ' selected="selected" ';
$defaultField = $fieldname;
$mappedFields[] = $fieldname;
}
} else {
if ( !empty($defaultValue) && !in_array($fieldname,$mappedFields)
&& !in_array($fieldname,$ignored_fields) )
{
if ( strtolower($fieldname) == strtolower($defaultValue)
|| strtolower($fieldname) == str_replace(" ","_",strtolower($defaultValue))
|| strtolower($displayname) == strtolower($defaultValue)
|| strtolower($displayname) == str_replace(" ","_",strtolower($defaultValue)) )
{
$selected = ' selected="selected" ';
$defaultField = $fieldname;
$mappedFields[] = $fieldname;
}
}
}
// get field type information
$fieldtype = '';
if ( isset($properties['type'])
&& isset($mod_strings['LBL_IMPORT_FIELDDEF_' . strtoupper($properties['type'])]) )
$fieldtype = ' [' . $mod_strings['LBL_IMPORT_FIELDDEF_' . strtoupper($properties['type'])] . '] ';
if ( isset($properties['comment']) )
$fieldtype .= ' - ' . $properties['comment'];
$options[$displayname.$fieldname] = '<option value="'.$fieldname.'" title="'. $displayname . htmlentities($fieldtype) . '"'
. $selected . $req_class . '>' . $displayname . $req_mark . '</option>\n';
}
// get default field value
$defaultFieldHTML = '';
if ( !empty($defaultField) ) {
$defaultFieldHTML = getControl(
$_REQUEST['import_module'],
$defaultField,
$fields[$defaultField],
( isset($default_values[$defaultField]) ? $default_values[$defaultField] : '' )
);
}
if ( isset($default_values[$defaultField]) )
unset($default_values[$defaultField]);
// Bug 27046 - Sort the column name picker alphabetically
ksort($options);
// to be displayed in UTF-8 format
if (!empty($charset) && $charset != 'UTF-8') {
if (isset($rows[1][$field_count])) {
$rows[1][$field_count] = $locale->translateCharset($rows[1][$field_count], $charset);
}
}
$cellOneData = isset($rows[0][$field_count]) ? $rows[0][$field_count] : '';
$cellTwoData = isset($rows[1][$field_count]) ? $rows[1][$field_count] : '';
$cellThreeData = isset($rows[2][$field_count]) ? $rows[2][$field_count] : '';
$columns[] = array(
'field_choices' => implode('',$options),
'default_field' => $defaultFieldHTML,
'cell1' => strip_tags($cellOneData),
'cell2' => strip_tags($cellTwoData),
'cell3' => strip_tags($cellThreeData),
'show_remove' => false,
);
}
// add in extra defaulted fields if they are in the mapping record
if ( count($default_values) > 0 ) {
foreach ( $default_values as $field_name => $default_value ) {
// build string of options
$fields = $this->bean->get_importable_fields();
$options = array();
$defaultField = '';
foreach ( $fields as $fieldname => $properties ) {
// get field name
if (!empty ($properties['vname']))
$displayname = str_replace(":","",translate($properties['vname'] ,$this->bean->module_dir));
else
$displayname = str_replace(":","",translate($properties['name'] ,$this->bean->module_dir));
// see if this is required
$req_mark = "";
$req_class = "";
if ( array_key_exists($fieldname, $this->bean->get_import_required_fields()) ) {
$req_mark = ' ' . $app_strings['LBL_REQUIRED_SYMBOL'];
$req_class = ' class="required" ';
}
// see if we have a match
$selected = '';
if ( strtolower($fieldname) == strtolower($field_name)
&& !in_array($fieldname,$mappedFields)
&& !in_array($fieldname,$ignored_fields) ) {
$selected = ' selected="selected" ';
$defaultField = $fieldname;
$mappedFields[] = $fieldname;
}
// get field type information
$fieldtype = '';
if ( isset($properties['type'])
&& isset($mod_strings['LBL_IMPORT_FIELDDEF_' . strtoupper($properties['type'])]) )
$fieldtype = ' [' . $mod_strings['LBL_IMPORT_FIELDDEF_' . strtoupper($properties['type'])] . '] ';
if ( isset($properties['comment']) )
$fieldtype .= ' - ' . $properties['comment'];
$options[$displayname.$fieldname] = '<option value="'.$fieldname.'" title="'. $displayname . $fieldtype . '"' . $selected . $req_class . '>'
. $displayname . $req_mark . '</option>\n';
}
// get default field value
$defaultFieldHTML = '';
if ( !empty($defaultField) ) {
$defaultFieldHTML = getControl(
$_REQUEST['import_module'],
$defaultField,
$fields[$defaultField],
$default_value
);
}
// Bug 27046 - Sort the column name picker alphabetically
ksort($options);
$columns[] = array(
'field_choices' => implode('',$options),
'default_field' => $defaultFieldHTML,
'show_remove' => true,
);
$ret_field_count++;
}
}
$this->ss->assign("COLUMNCOUNT",$ret_field_count);
$this->ss->assign("rows",$columns);
$this->ss->assign('datetimeformat', $GLOBALS['timedate']->get_cal_date_time_format());
// handle building index selector
global $dictionary, $current_language;
// show notes
if ( $this->bean instanceof Person )
$module_key = "LBL_CONTACTS_NOTE_";
elseif ( $this->bean instanceof Company )
$module_key = "LBL_ACCOUNTS_NOTE_";
else
$module_key = "LBL_".strtoupper($_REQUEST['import_module'])."_NOTE_";
$notetext = '';
for ($i = 1;isset($mod_strings[$module_key.$i]);$i++) {
$notetext .= '<li>' . $mod_strings[$module_key.$i] . '</li>';
}
$this->ss->assign("NOTETEXT",$notetext);
$this->ss->assign("HAS_HEADER",($has_header ? 'on' : 'off' ));
// get list of required fields
$required = array();
foreach ( array_keys($this->bean->get_import_required_fields()) as $name ) {
$properties = $this->bean->getFieldDefinition($name);
if (!empty ($properties['vname']))
$required[$name] = str_replace(":","",translate($properties['vname'] ,$this->bean->module_dir));
else
$required[$name] = str_replace(":","",translate($properties['name'] ,$this->bean->module_dir));
}
// include anything needed for quicksearch to work
require_once("include/TemplateHandler/TemplateHandler.php");
// Bug #46879 : createQuickSearchCode() function in IBM RTC call function getQuickSearchDefaults() to get instance and then getQSDLookup() function
// if we call this function as static it replaces context and use ImportViewStep3 as $this in getQSDLookup()
$template_handler = new TemplateHandler();
$quicksearch_js = $template_handler->createQuickSearchCode($fields,$fields,'importstep3');
$this->ss->assign("QS_JS", $quicksearch_js);
$this->ss->assign("JAVASCRIPT", $this->_getJS($required));
$this->ss->assign('required_fields',implode(', ',$required));
$this->ss->assign('CSS', $this->_getCSS());
$content = $this->ss->fetch($this->getCustomFilePathIfExists('modules/Import/tpls/step3.tpl'));
$this->ss->assign("CONTENT",$content);
$this->ss->display($this->getCustomFilePathIfExists('modules/Import/tpls/wizardWrapper.tpl'));
}
/**
* getMappingClassName
*
* This function returns the name of a mapping class used to generate the mapping of an import source.
* It first checks to see if an equivalent custom source map exists in custom/modules/Imports/maps directory
* and returns this class name if found. Searches are made for sources with a ImportMapCustom suffix first
* and then ImportMap suffix.
*
* If no such custom file is found, the method then checks the modules/Imports/maps directory for a source
* mapping file.
*
* Lastly, if a source mapping file is still not located, it checks in
* custom/modules/Import/maps/ImportMapOther.php file exists, it uses the ImportMapOther class.
*
* @see display()
* @param string $source String name of the source mapping prefix
* @return string name of the mapping class name
*/
protected function getMappingClassName($source)
{
// Try to see if we have a custom mapping we can use
// based upon the where the records are coming from
// and what module we are importing into
$name = 'ImportMap' . $source;
$customName = 'ImportMapCustom' . $source;
if (file_exists("custom/modules/Import/maps/{$customName}.php"))
{
require_once("custom/modules/Import/maps/{$customName}.php");
return $customName;
} else if (file_exists("custom/modules/Import/maps/{$name}.php")) {
require_once("custom/modules/Import/maps/{$name}.php");
} else if (file_exists("modules/Import/maps/{$name}.php")) {
require_once("modules/Import/maps/{$name}.php");
} else if (file_exists('custom/modules/Import/maps/ImportMapOther.php')) {
require_once('custom/modules/Import/maps/ImportMapOther.php');
return 'ImportMapOther';
}
return $name;
}
protected function getRequestDelimiter()
{
$delimiter = !empty($_REQUEST['custom_delimiter']) ? $_REQUEST['custom_delimiter'] : ",";
switch ($delimiter)
{
case "other":
$delimiter = $_REQUEST['custom_delimiter_other'];
break;
case '\t':
$delimiter = "\t";
break;
}
return $delimiter;
}
protected function getImportColumns()
{
$importColumns = array();
foreach ($_REQUEST as $name => $value)
{
// only look for var names that start with "fieldNum"
if (strncasecmp($name, "colnum_", 7) != 0)
continue;
// pull out the column position for this field name
$pos = substr($name, 7);
// now mark that we've seen this field
$importColumns[$pos] = $value;
}
return $importColumns;
}
protected function _getCSS()
{
return <<<EOCSS
<style>
textarea { width: 20em }
.detail tr td[scope="row"] {
text-align:left
}
span.collapse{
background: transparent url('index.php?entryPoint=getImage&themeName=Sugar&themeName=Sugar&imageName=sugar-yui-sprites.png') no-repeat 0 -90px;
padding-left: 10px;
cursor: pointer;
display: inline;
}
span.expand{
background: transparent url('index.php?entryPoint=getImage&themeName=Sugar&themeName=Sugar&imageName=sugar-yui-sprites.png') no-repeat -0 -110px;
padding-left: 10px;
cursor: pointer;
}
.removeButton{
border: none !important;
background-image: none !important;
background-color: transparent;
padding: 0px;
}
#importNotes ul{
margin: 0px;
margin-top: 10px;
padding-left: 20px;
}
</style>
EOCSS;
}
/**
* Returns JS used in this view
*
* @param array $required fields that are required for the import
* @return string HTML output with JS code
*/
protected function _getJS($required)
{
global $mod_strings;
$print_required_array = "";
foreach ($required as $name=>$display) {
$print_required_array .= "required['$name'] = '". sanitize($display) . "';\n";
}
$sqsWaitImage = SugarThemeRegistry::current()->getImageURL('sqsWait.gif');
return <<<EOJAVASCRIPT
document.getElementById('goback').onclick = function()
{
document.getElementById('{$this->currentFormID}').action.value = '{$this->previousAction}';
//bug #48960: CSS didn't load when use click back in the step2 (external sources are selected for contacts)
//need to unset 'to_pdf' in extstep1.tpl
if (document.getElementById('{$this->currentFormID}').to_pdf)
{
document.getElementById('{$this->currentFormID}').to_pdf.value = '';
}
return true;
}
ImportView = {
validateMappings : function()
{
// validate form
clear_all_errors();
var form = document.getElementById('{$this->currentFormID}');
var hash = new Object();
var required = new Object();
$print_required_array
var isError = false;
for ( i = 0; i < form.length; i++ ) {
if ( form.elements[i].name.indexOf("colnum",0) == 0) {
if ( form.elements[i].value == "-1") {
continue;
}
if ( hash[ form.elements[i].value ] == 1) {
isError = true;
add_error_style('{$this->currentFormID}',form.elements[i].name,"{$mod_strings['ERR_MULTIPLE']}");
}
hash[form.elements[i].value] = 1;
}
}
// check for required fields
for(var field_name in required) {
// contacts hack to bypass errors if full_name is set
if (field_name == 'last_name' &&
hash['full_name'] == 1) {
continue;
}
if ( hash[ field_name ] != 1 ) {
isError = true;
add_error_style('{$this->currentFormID}',form.colnum_0.name,
"{$mod_strings['ERR_MISSING_REQUIRED_FIELDS']} " + required[field_name]);
}
}
// return false if we got errors
if (isError == true) {
return false;
}
return true;
}
}
if( document.getElementById('gonext') )
{
document.getElementById('gonext').onclick = function(){
if( ImportView.validateMappings() )
{
// Move on to next step
document.getElementById('{$this->currentFormID}').action.value = '{$this->nextAction}';
return true;
}
else
return false;
}
}
// handle adding new row
document.getElementById('addrow').onclick = function(){
toggleDefaultColumnVisibility(false);
rownum = document.getElementById('{$this->currentFormID}').columncount.value;
newrow = document.createElement("tr");
column0 = document.getElementById('row_0_col_0').cloneNode(true);
column0.id = 'row_' + rownum + '_col_0';
for ( i = 0; i < column0.childNodes.length; i++ ) {
if ( column0.childNodes[i].name == 'colnum_0' ) {
column0.childNodes[i].name = 'colnum_' + rownum;
column0.childNodes[i].onchange = function(){
var module = document.getElementById('{$this->currentFormID}').import_module.value;
var fieldname = this.value;
var matches = /colnum_([0-9]+)/i.exec(this.name);
var fieldnum = matches[1];
if ( fieldname == -1 ) {
document.getElementById('defaultvaluepicker_'+fieldnum).innerHTML = '';
return;
}
document.getElementById('defaultvaluepicker_'+fieldnum).innerHTML = '<img src="{$sqsWaitImage}" />'
YAHOO.util.Connect.asyncRequest('GET', 'index.php?module=Import&action=GetControl&import_module='+module+'&field_name='+fieldname,
{
success: function(o)
{
document.getElementById('defaultvaluepicker_'+fieldnum).innerHTML = o.responseText;
SUGAR.util.evalScript(o.responseText);
enableQS(true);
},
failure: function(o) {/*failure handler code*/}
});
}
}
}
var removeButton = document.createElement("button");
removeButton.title = "{$mod_strings['LBL_REMOVE_ROW']}";
removeButton.id = 'deleterow_' + rownum;
removeButton.className = "removeButton";
var imgButton = document.createElement("img");
imgButton.src = "index.php?entryPoint=getImage&themeName=Sugar&imageName=id-ff-remove.png";
removeButton.appendChild(imgButton);
if ( document.getElementById('row_0_header') ) {
column1 = document.getElementById('row_0_header').cloneNode(true);
column1.innerHTML = ' ';
column1.style.textAlign = "right";
newrow.appendChild(column1);
column1.appendChild(removeButton);
}
newrow.appendChild(column0);
column3 = document.createElement('td');
column3.className = 'tabDetailViewDL';
if ( !document.getElementById('row_0_header') ) {
column3.colSpan = 2;
}
newrow.appendChild(column3);
column2 = document.getElementById('defaultvaluepicker_0').cloneNode(true);
column2.id = 'defaultvaluepicker_' + rownum;
newrow.appendChild(column2);
document.getElementById('{$this->currentFormID}').columncount.value = parseInt(document.getElementById('{$this->currentFormID}').columncount.value) + 1;
document.getElementById('row_0_col_0').parentNode.parentNode.insertBefore(newrow,this.parentNode.parentNode);
document.getElementById('deleterow_' + rownum).onclick = function(){
this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
}
}
function toggleDefaultColumnVisibility(hide)
{
if( typeof(hide) != 'undefined' && typeof(hide) == 'boolean')
{
var currentStyle = hide ? '' : 'none';
}
else
{
var currentStyle = YAHOO.util.Dom.getStyle('default_column_header_span', 'display');
}
if(currentStyle == 'none')
{
var newStyle = '';
var bgColor = '#eeeeee';
YAHOO.util.Dom.addClass('hide_default_link', 'collapse');
YAHOO.util.Dom.removeClass('hide_default_link', 'expand');
var col2Rowspan = "1";
}
else
{
var newStyle = 'none';
var bgColor = '#dddddd';
YAHOO.util.Dom.addClass('hide_default_link', 'expand');
YAHOO.util.Dom.removeClass('hide_default_link', 'collapse');
var col2Rowspan = "2";
}
YAHOO.util.Dom.setStyle('default_column_header_span', 'display', newStyle);
YAHOO.util.Dom.setStyle('default_column_header', 'backgroundColor', bgColor);
//Toggle all rows.
var columnCount = document.getElementById('{$this->currentFormID}').columncount.value;
for(i=0;i<columnCount;i++)
{
YAHOO.util.Dom.setStyle('defaultvaluepicker_' + i, 'display', newStyle);
YAHOO.util.Dom.setAttribute('row_'+i+'_col_2', 'colspan', col2Rowspan);
}
}
var notesEl = document.getElementById('toggleNotes');
if(notesEl)
{
notesEl.onclick = function() {
if (document.getElementById('importNotes').style.display == 'none'){
document.getElementById('importNotes').style.display = '';
document.getElementById('toggleNotes').value='{$mod_strings['LBL_HIDE_NOTES']}';
}
else {
document.getElementById('importNotes').style.display = 'none';
document.getElementById('toggleNotes').value='{$mod_strings['LBL_SHOW_NOTES']}';
}
}
}
YAHOO.util.Event.onDOMReady(function(){
toggleDefaultColumnVisibility();
YAHOO.util.Event.addListener('hide_default_link', "click", toggleDefaultColumnVisibility);
var selects = document.getElementsByTagName('select');
for (var i = 0; i < selects.length; ++i ){
if (selects[i].name.indexOf("colnum_") != -1 ) {
// fetch the field input control via ajax
selects[i].onchange = function(){
var module = document.getElementById('{$this->currentFormID}').import_module.value;
var fieldname = this.value;
var matches = /colnum_([0-9]+)/i.exec(this.name);
var fieldnum = matches[1];
if ( fieldname == -1 ) {
document.getElementById('defaultvaluepicker_'+fieldnum).innerHTML = '';
return;
}
document.getElementById('defaultvaluepicker_'+fieldnum).innerHTML = '<img src="{$sqsWaitImage}" />'
YAHOO.util.Connect.asyncRequest('GET', 'index.php?module=Import&action=GetControl&import_module='+module+'&field_name='+fieldname,
{
success: function(o)
{
document.getElementById('defaultvaluepicker_'+fieldnum).innerHTML = o.responseText;
SUGAR.util.evalScript(o.responseText);
enableQS(true);
},
failure: function(o) {/*failure handler code*/}
});
}
}
}
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i ){
if (inputs[i].id.indexOf("deleterow_") != -1 ) {
inputs[i].onclick = function(){
this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode);
}
}
}
});
enableQS(false);
EOJAVASCRIPT;
}
}
| noelhunter/SuiteCRM | modules/Import/views/view.step3.php | PHP | agpl-3.0 | 34,985 |
/****************************************************************
* *
* Copyright 2001 Sanchez Computer Associates, Inc. *
* *
* This source code contains the intellectual property *
* of its copyright holder(s), and is made available *
* under a license. If you do not know the terms of *
* the license, please stop and do not read further. *
* *
****************************************************************/
/* This routine takes a pointer to a sgmnt_data struct with space for the BTs and
locks attached. The BTs and the lock space are initialized and then written
to disk to the file specified by channel.
*/
#include "mdef.h"
#include <rms.h>
#include "gdsroot.h"
#include "gtm_facility.h"
#include "fileinfo.h"
#include "gdsbt.h"
#include "gdsblk.h"
#include "gdsfhead.h"
#include <ssdef.h>
#include <iodef.h>
#include <efndef.h>
#include "mlk_shr_init.h"
#include "dbcx_ref.h"
int dbcx_ref(sgmnt_data *sd, int chan)
{
char *qio_ptr, *qio_top;
short iosb[4];
int block, status;
sgmnt_addrs sa;
sa.hdr = sd;
bt_malloc(&sa);
mlk_shr_init((char *)sd + (LOCK_BLOCK(sd) * DISK_BLOCK_SIZE), sd->lock_space_size, &sa, TRUE);
qio_ptr = (char *)sd;
qio_top = qio_ptr + (LOCK_BLOCK(sd) * DISK_BLOCK_SIZE) + LOCK_SPACE_SIZE(sd);
for ( block = 1; qio_ptr < qio_top; block++, qio_ptr += DISK_BLOCK_SIZE)
{
if (SS$_NORMAL != (status = sys$qiow(EFN$C_ENF, chan, IO$_WRITEVBLK, iosb,
0, 0, qio_ptr, DISK_BLOCK_SIZE, block, 0, 0, 0)))
return status;
if (!(iosb[0] & 1))
return iosb[0];
}
return SS$_NORMAL;
}
| CoherentLogic/fis-gtm-netbsd | sr_vvms/dbcx_ref.c | C | agpl-3.0 | 1,575 |
'use strict';
var expect = require('chai').expect;
var bitcore = require('bitcore-lib');
var Message = require('bitcore-message');
var secp256k1 = require('secp256k1');
var KeyPair = require('../../lib/crypto-tools/keypair');
var prvk = '4d548b387bed22aff9ca560416d7b13ecbad16f28bc41ef5acaff3019bfa5134';
var prvk2 = '00008b387bed22aff9ca560416d7b13ecbad16f28bc41ef5acaff3019bfa5134';
var pubk = '02ad47e0d4896cd794f5296a953f897c426b3f9a58f5203b8baace8952a291cf6b';
describe('KeyPair', function() {
describe('@constructor', function() {
it('should work without the new keyword', function() {
expect(KeyPair()).to.be.instanceOf(KeyPair);
});
});
describe('#getPrivateKey', function() {
it('should use the private key supplied if provided', function() {
var kp = KeyPair(prvk);
expect(kp.getPrivateKey()).to.be.equal(prvk);
});
});
describe('#getPrivateKeyPadded', function() {
it('should use the private key supplied if provided', function() {
var kp = KeyPair(prvk2);
expect(kp.getPrivateKeyPadded()).to.be.equal(prvk2);
expect(kp.getPrivateKeyPadded().length).to.equal(64);
});
});
describe('#getPublicKey', function() {
it('should use the private key supplied if provided', function() {
var kp = KeyPair(prvk);
expect(kp.getPublicKey()).to.be.equal(pubk);
});
});
describe('#getNodeID', function() {
it('should return a bitcoin compatible address', function() {
var addr = KeyPair().getNodeID();
expect(addr.length).to.equal(40);
});
});
describe('#getAddress', function() {
it('should return a bitcoin compatible address', function() {
var addr = KeyPair().getAddress();
expect(addr.length).to.be.lte(35);
expect(addr.length).to.be.gte(26);
expect(['1', '3']).to.include(addr.charAt(0));
});
});
describe('#sign', function() {
var k = 'd1b1d083ddbcf92aa665a77379a0e32ef7cc5a4ccfc4b2a30214ebcdfd34d846';
var m = 'a test message';
it('should return a bitcoin-style compact signature', function() {
var keypair = new KeyPair(k);
var signature = keypair.sign(m, { compact: true });
expect(signature).to.have.lengthOf(88);
});
it('should return valid compact signature', function() {
var keypair = new KeyPair(k);
var signature = keypair.sign(m, { compact: true });
expect(signature).to.have.lengthOf(88);
// recover the public key and check the signature
var hash = Message(m).magicHash();
var sigbuf = new Buffer(signature, 'base64');
var sigobj = bitcore.crypto.Signature.fromCompact(sigbuf);
var sigimp = secp256k1.signatureImport(sigobj.toBuffer());
var pubkey = secp256k1.recover(hash, sigimp, sigobj.i, true);
var res = secp256k1.verify(hash, sigimp, pubkey);
expect(res).to.equal(true);
});
it('should return a regular hex signature from string', function() {
var keypair = new KeyPair(k);
var signature = keypair.sign(m, { compact: false });
expect(signature).to.equal(
'3045022100fc2cc9dcfa01fef0c8c78942f057f6d2930e9308bd5e43072c56098' +
'34d938cad022007f1179aace5810c9c4ba0461980aa2bcdfac6a40a900443b018' +
'b09e5ced5e1f'
);
});
it('should return a regular hex signature from buffer', function() {
var keypair = new KeyPair(k);
var signature = keypair.sign(Buffer(m), { compact: false });
expect(signature).to.equal(
'3045022100fc2cc9dcfa01fef0c8c78942f057f6d2930e9308bd5e43072c56098' +
'34d938cad022007f1179aace5810c9c4ba0461980aa2bcdfac6a40a900443b018' +
'b09e5ced5e1f'
);
});
});
});
| Storj/core | test/crypto-tools/keypair.unit.js | JavaScript | agpl-3.0 | 3,706 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Schedulers determine how worker's queues get filled. They control which
locations get scanned, in what order, at what time. This allows further
optimizations to be easily added, without having to modify the existing
overseer and worker thread code.
Schedulers will recieve:
queues - A list of queues for the workers they control. For now, this is a
list containing a single queue.
status - A list of status dicts for the workers. Schedulers can use this
information to make more intelligent scheduling decisions.
Useful values include:
- last_scan_date: unix timestamp of when the last scan was
completed
- location: [lat,lng,alt] of the last scan
args - The configuration arguments. This may not include all of the arguments,
just ones that are relevant to this scheduler instance (eg. if
multiple locations become supported, the args passed to the
scheduler will only contain the parameters for the location
it handles)
Schedulers must fill the queues with items to search.
Queue items are a list containing:
[step, (latitude, longitude, altitude),
appears_seconds, disappears_seconds)]
Where:
- step is the step number. Used only for display purposes.
- (latitude, longitude, altitude) is the location to be scanned.
- appears_seconds is the unix timestamp of when the pokemon next appears
- disappears_seconds is the unix timestamp of when the
pokemon next disappears
appears_seconds and disappears_seconds are used to skip scans that are too
late, and wait for scans the worker is early for. If a scheduler doesn't
have a specific time a location needs to be scanned, it should set
both to 0.
If implementing a new scheduler, place it before SchedulerFactory, and
add it to __scheduler_classes
'''
import itertools
import logging
import math
import geopy
import json
import time
import sys
from timeit import default_timer
from threading import Lock
from copy import deepcopy
import traceback
from collections import Counter
from queue import Empty
from operator import itemgetter
from datetime import datetime, timedelta
from .transform import get_new_coords
from .models import (hex_bounds, Pokemon, SpawnPoint, ScannedLocation,
ScanSpawnPoint)
from .utils import now, cur_sec, cellid, date_secs, equi_rect_distance
from .altitude import get_altitude
log = logging.getLogger(__name__)
# Simple base class that all other schedulers inherit from.
# Most of these functions should be overridden in the actual scheduler classes.
# Not all scheduler methods will need to use all of the functions.
class BaseScheduler(object):
def __init__(self, queues, status, args):
self.queues = queues
self.status = status
self.args = args
self.scan_location = False
self.size = None
self.ready = False
# Schedule function fills the queues with data.
def schedule(self):
log.warning('BaseScheduler does not schedule any items')
# location_changed function is called whenever the location being
# scanned changes.
# scan_location = (lat, lng, alt)
def location_changed(self, scan_location, dbq):
self.scan_location = scan_location
self.empty_queues()
# scanning_pause function is called when scanning is paused from the UI.
# The default function will empty all the queues.
# Note: This function is called repeatedly while scanning is paused!
def scanning_paused(self):
self.empty_queues()
def getsize(self):
return self.size
def get_overseer_message(self):
nextitem = self.queues[0].queue[0]
message = 'Processing search queue, next item is {:6f},{:6f}'.format(
nextitem[1][0], nextitem[1][1])
# If times are specified, print the time of the next queue item, and
# how many seconds ahead/behind realtime
if nextitem[2]:
message += ' @ {}'.format(
time.strftime('%H:%M:%S', time.localtime(nextitem[2])))
if nextitem[2] > now():
message += ' ({}s ahead)'.format(nextitem[2] - now())
else:
message += ' ({}s behind)'.format(now() - nextitem[2])
return message
# check if time to refresh queue
def time_to_refresh_queue(self):
return self.queues[0].empty()
def task_done(self, *args):
return self.queues[0].task_done()
# Return the next item in the queue
def next_item(self, search_items_queue):
step, step_location, appears, leaves = self.queues[0].get()
remain = appears - now() + 10
messages = {
'wait': 'Waiting for item from queue.',
'early': 'Early for {:6f},{:6f}; waiting {}s...'.format(
step_location[0], step_location[1], remain),
'late': 'Too late for location {:6f},{:6f}; skipping.'.format(
step_location[0], step_location[1]),
'search': 'Searching at {:6f},{:6f},{:6f}.'.format(
step_location[0], step_location[1], step_location[2]),
'invalid': ('Invalid response at {:6f},{:6f}, ' +
'abandoning location.').format(step_location[0],
step_location[1])
}
return step, step_location, appears, leaves, messages
# How long to delay since last action
def delay(self, *args):
return self.args.scan_delay # always scan delay time
# Function to empty all queues in the queues list
def empty_queues(self):
self.ready = False
for queue in self.queues:
if not queue.empty():
try:
while True:
queue.get_nowait()
except Empty:
pass
# Hex Search is the classic search method, with the pokepath modification,
# searching in a hex grid around the center location.
class HexSearch(BaseScheduler):
# Call base initialization, set step_distance.
def __init__(self, queues, status, args):
BaseScheduler.__init__(self, queues, status, args)
# If we are only scanning for pokestops/gyms, the scan radius can be
# 450m. Otherwise 70m.
if self.args.no_pokemon:
self.step_distance = 0.450
else:
self.step_distance = 0.070
self.step_limit = args.step_limit
# This will hold the list of locations to scan so it can be reused,
# instead of recalculating on each loop.
self.locations = False
# On location change, empty the current queue and the locations list
def location_changed(self, scan_location, dbq):
self.scan_location = scan_location
self.empty_queues()
self.locations = False
# Generates the list of locations to scan.
def _generate_locations(self):
NORTH = 0
EAST = 90
SOUTH = 180
WEST = 270
# Dist between column centers.
xdist = math.sqrt(3) * self.step_distance
ydist = 3 * (self.step_distance / 2) # Dist between row centers.
results = []
results.append((self.scan_location[0], self.scan_location[1], 0))
if self.step_limit > 1:
loc = self.scan_location
# Upper part.
ring = 1
while ring < self.step_limit:
loc = get_new_coords(
loc, xdist, WEST if ring % 2 == 1 else EAST)
results.append((loc[0], loc[1], 0))
for i in range(ring):
loc = get_new_coords(loc, ydist, NORTH)
loc = get_new_coords(
loc, xdist / 2, EAST if ring % 2 == 1 else WEST)
results.append((loc[0], loc[1], 0))
for i in range(ring):
loc = get_new_coords(
loc, xdist, EAST if ring % 2 == 1 else WEST)
results.append((loc[0], loc[1], 0))
for i in range(ring):
loc = get_new_coords(loc, ydist, SOUTH)
loc = get_new_coords(
loc, xdist / 2, EAST if ring % 2 == 1 else WEST)
results.append((loc[0], loc[1], 0))
ring += 1
# Lower part.
ring = self.step_limit - 1
loc = get_new_coords(loc, ydist, SOUTH)
loc = get_new_coords(
loc, xdist / 2, WEST if ring % 2 == 1 else EAST)
results.append((loc[0], loc[1], 0))
while ring > 0:
if ring == 1:
loc = get_new_coords(loc, xdist, WEST)
results.append((loc[0], loc[1], 0))
else:
for i in range(ring - 1):
loc = get_new_coords(loc, ydist, SOUTH)
loc = get_new_coords(
loc, xdist / 2, WEST if ring % 2 == 1 else EAST)
results.append((loc[0], loc[1], 0))
for i in range(ring):
loc = get_new_coords(
loc, xdist, WEST if ring % 2 == 1 else EAST)
results.append((loc[0], loc[1], 0))
for i in range(ring - 1):
loc = get_new_coords(loc, ydist, NORTH)
loc = get_new_coords(
loc, xdist / 2, WEST if ring % 2 == 1 else EAST)
results.append((loc[0], loc[1], 0))
loc = get_new_coords(
loc, xdist, EAST if ring % 2 == 1 else WEST)
results.append((loc[0], loc[1], 0))
ring -= 1
# This will pull the last few steps back to the front of the list,
# so you get a "center nugget" at the beginning of the scan, instead
# of the entire nothern area before the scan spots 70m to the south.
if self.step_limit >= 3:
if self.step_limit == 3:
results = results[-2:] + results[:-2]
else:
results = results[-7:] + results[:-7]
# Add the required appear and disappear times.
locationsZeroed = []
for step, location in enumerate(results, 1):
altitude = get_altitude(self.args, location)
locationsZeroed.append(
(step, (location[0], location[1], altitude), 0, 0))
return locationsZeroed
# Schedule the work to be done.
def schedule(self):
if not self.scan_location:
log.warning(
'Cannot schedule work until scan location has been set')
return
# Only generate the list of locations if we don't have it already
# calculated.
if not self.locations:
self.locations = self._generate_locations()
for location in self.locations:
# FUTURE IMPROVEMENT - For now, queues is assumed to have a single
# queue.
self.queues[0].put(location)
log.debug("Added location {}".format(location))
self.size = len(self.locations)
self.ready = True
# Spawn Only Hex Search works like Hex Search, but skips locations that
# have no known spawnpoints.
class HexSearchSpawnpoint(HexSearch):
def _any_spawnpoints_in_range(self, coords, spawnpoints):
return any(
geopy.distance.distance(coords, x).meters <= 70
for x in spawnpoints)
# Extend the generate_locations function to remove locations with no
# spawnpoints.
def _generate_locations(self):
n, e, s, w = hex_bounds(self.scan_location, self.step_limit)
spawnpoints = set((d['latitude'], d['longitude'])
for d in Pokemon.get_spawnpoints(s, w, n, e))
if len(spawnpoints) == 0:
log.warning('No spawnpoints found in the specified area! (Did ' +
'you forget to run a normal scan in this area first?)')
# Call the original _generate_locations.
locations = super(HexSearchSpawnpoint, self)._generate_locations()
# Remove items with no spawnpoints in range.
locations = [
coords for coords in locations
if self._any_spawnpoints_in_range(coords[1], spawnpoints)]
return locations
# Spawn Scan searches known spawnpoints at the specific time they spawn.
class SpawnScan(BaseScheduler):
def __init__(self, queues, status, args):
BaseScheduler.__init__(self, queues, status, args)
# On the first scan, we want to search the last 15 minutes worth of
# spawns to get existing pokemon onto the map.
self.firstscan = True
# If we are only scanning for pokestops/gyms, the scan radius can be
# 450m. Otherwise 70m.
if self.args.no_pokemon:
self.step_distance = 0.450
else:
self.step_distance = 0.070
self.step_limit = args.step_limit
self.locations = False
# Generate locations is called when the locations list is cleared - the
# first time it scans or after a location change.
def _generate_locations(self):
# Attempt to load spawns from file.
if self.args.spawnpoint_scanning != 'nofile':
log.debug('Loading spawn points from json file @ %s',
self.args.spawnpoint_scanning)
try:
with open(self.args.spawnpoint_scanning) as file:
self.locations = json.load(file)
except ValueError as e:
log.error('JSON error: %s; will fallback to database', repr(e))
except IOError as e:
log.error(
'Error opening json file: %s; will fallback to database',
repr(e))
# No locations yet? Try the database!
if not self.locations:
log.debug('Loading spawn points from database')
self.locations = Pokemon.get_spawnpoints_in_hex(
self.scan_location, self.args.step_limit)
# Well shit...
# if not self.locations:
# raise Exception('No availabe spawn points!')
# locations[]:
# {"lat": 37.53079079414139, "lng": -122.28811690874117,
# "spawnpoint_id": "808f9f1601d", "time": 511
log.info('Total of %d spawns to track', len(self.locations))
# locations.sort(key=itemgetter('time'))
if self.args.very_verbose:
for i in self.locations:
sec = i['time'] % 60
minute = (i['time'] / 60) % 60
m = 'Scan [{:02}:{:02}] ({}) @ {},{}'.format(
minute, sec, i['time'], i['lat'], i['lng'])
log.debug(m)
# 'time' from json and db alike has been munged to appearance time as
# seconds after the hour.
# Here we'll convert that to a real timestamp.
for location in self.locations:
# For a scan which should cover all CURRENT pokemon, we can offset
# the comparison time by 15 minutes so that the "appears" time
# won't be rolled over to the next hour.
# TODO: Make it work. The original logic (commented out) was
# producing bogus results if your first scan was in the last
# 15 minute of the hour. Wrapping my head around this isn't
# work right now, so I'll just drop the feature for the time
# being. It does need to come back so that
# repositioning/pausing works more nicely, but we can live
# without it too.
# if sps_scan_current:
# cursec = (location['time'] + 900) % 3600
# else:
cursec = location['time']
if cursec > cur_sec():
# Hasn't spawn in the current hour.
from_now = location['time'] - cur_sec()
appears = now() + from_now
else:
# Won't spawn till next hour.
late_by = cur_sec() - location['time']
appears = now() + 3600 - late_by
location['appears'] = appears
location['leaves'] = appears + 900
# Put the spawn points in order of next appearance time.
self.locations.sort(key=itemgetter('appears'))
# Match expected structure:
# locations = [((lat, lng, alt), ts_appears, ts_leaves),...]
retset = []
for step, location in enumerate(self.locations, 1):
altitude = get_altitude(self.args, [location['lat'],
location['lng']])
retset.append((step, (location['lat'], location['lng'], altitude),
location['appears'], location['leaves']))
return retset
# Schedule the work to be done.
def schedule(self):
if not self.scan_location:
log.warning(
'Cannot schedule work until scan location has been set')
return
# SpawnScan needs to calculate the list every time, since the times
# will change.
self.locations = self._generate_locations()
for location in self.locations:
# FUTURE IMPROVEMENT - For now, queues is assumed to have a single
# queue.
self.queues[0].put(location)
log.debug("Added location {}".format(location))
# Clear the locations list so it gets regenerated next cycle.
self.size = len(self.locations)
self.locations = None
self.ready = True
# SpeedScan is a complete search method that initially does a spawnpoint
# search in each scan location by scanning five two-minute bands within
# an hour and ten minute intervals between bands.
# After finishing the spawnpoint search or if timing isn't right for any of
# the remaining search bands, workers will search the nearest scan location
# that has a new spawn.
class SpeedScan(HexSearch):
# Call base initialization, set step_distance
def __init__(self, queues, status, args):
super(SpeedScan, self).__init__(queues, status, args)
self.refresh_date = datetime.utcnow() - timedelta(days=1)
self.next_band_date = self.refresh_date
self.queues = [[]]
self.ready = False
self.spawns_found = 0
self.spawns_missed_delay = {}
self.scans_done = 0
self.scans_missed = 0
self.scans_missed_list = []
# Minutes between queue refreshes. Should be less than 10 to allow for
# new bands during Initial scan
self.minutes = 5
self.found_percent = []
self.scan_percent = []
self.spawn_percent = []
self.status_message = []
self.tth_found = 0
# Initiate special types.
self._stat_init()
self._locks_init()
def _stat_init(self):
self.spawns_found = 0
self.spawns_missed_delay = {}
self.scans_done = 0
self.scans_missed = 0
self.scans_missed_list = []
def _locks_init(self):
self.lock_next_item = Lock()
# On location change, empty the current queue and the locations list
def location_changed(self, scan_location, db_update_queue):
super(SpeedScan, self).location_changed(scan_location, db_update_queue)
self.locations = self._generate_locations()
scans = {}
initial = {}
all_scans = {}
for sl in ScannedLocation.select_in_hex(self.scan_location,
self.args.step_limit):
all_scans[cellid((sl['latitude'], sl['longitude']))] = sl
for i, e in enumerate(self.locations):
cell = cellid(e[1])
scans[cell] = {'loc': e[1], # Lat/long pair
'step': e[0]}
initial[cell] = all_scans[cell] if cell in all_scans.keys(
) else ScannedLocation.new_loc(e[1])
self.scans = scans
db_update_queue.put((ScannedLocation, initial))
log.info('%d steps created', len(scans))
self.band_spacing = int(10 * 60 / len(scans))
self.band_status()
spawnpoints = SpawnPoint.select_in_hex(
self.scan_location, self.args.step_limit)
if not spawnpoints:
log.info('No spawnpoints in hex found in SpawnPoint table. ' +
'Doing initial scan.')
log.info('Found %d spawn points within hex', len(spawnpoints))
log.info('Doing %s distance calcs to assign spawn points to scans',
"{:,}".format(len(spawnpoints) * len(scans)))
scan_spawn_point = {}
ScannedLocation.link_spawn_points(scans, initial, spawnpoints,
self.step_distance, scan_spawn_point,
force=True)
if len(scan_spawn_point):
log.info('%d relations found between the spawn points and steps',
len(scan_spawn_point))
db_update_queue.put((ScanSpawnPoint, scan_spawn_point))
else:
log.info('Spawn points assigned')
# Generates the list of locations to scan
# Created a new function, because speed scan requires fixed locations,
# even when increasing -st. With HexSearch locations, the location of
# inner rings would change if -st was increased requiring rescanning
# since it didn't recognize the location in the ScannedLocation table
def _generate_locations(self):
NORTH = 0
EAST = 90
SOUTH = 180
WEST = 270
# dist between column centers
xdist = math.sqrt(3) * self.step_distance
ydist = 3 * (self.step_distance / 2) # dist between row centers
results = []
loc = self.scan_location
results.append((loc[0], loc[1], 0))
# upper part
for ring in range(1, self.step_limit):
for i in range(max(ring - 1, 1)):
if ring > 1:
loc = get_new_coords(loc, ydist, NORTH)
loc = get_new_coords(loc, xdist / (1 + (ring > 1)), WEST)
results.append((loc[0], loc[1], 0))
for i in range(ring):
loc = get_new_coords(loc, ydist, NORTH)
loc = get_new_coords(loc, xdist / 2, EAST)
results.append((loc[0], loc[1], 0))
for i in range(ring):
loc = get_new_coords(loc, xdist, EAST)
results.append((loc[0], loc[1], 0))
for i in range(ring):
loc = get_new_coords(loc, ydist, SOUTH)
loc = get_new_coords(loc, xdist / 2, EAST)
results.append((loc[0], loc[1], 0))
for i in range(ring):
loc = get_new_coords(loc, ydist, SOUTH)
loc = get_new_coords(loc, xdist / 2, WEST)
results.append((loc[0], loc[1], 0))
for i in range(ring + (ring + 1 < self.step_limit)):
loc = get_new_coords(loc, xdist, WEST)
results.append((loc[0], loc[1], 0))
generated_locations = []
for step, location in enumerate(results):
altitude = get_altitude(self.args, location)
generated_locations.append(
(step, (location[0], location[1], altitude), 0, 0))
return generated_locations
def getsize(self):
return len(self.queues[0])
def get_overseer_message(self):
n = 0
ms = (datetime.utcnow() - self.refresh_date).total_seconds() + \
self.refresh_ms
counter = {
'TTH': 0,
'spawn': 0,
'band': 0,
}
for item in self.queues[0]:
if item.get('done', False):
continue
if ms > item['end']:
continue
if ms < item['start']:
break
n += 1
counter[item['kind']] += 1
message = ('Scanning status: {} total waiting, {} initial bands, ' +
'{} TTH searches, and {} new spawns').format(
n, counter['band'], counter['TTH'], counter['spawn'])
if self.status_message:
message += '\n' + self.status_message
return message
# Refresh queue every 5 minutes
# the first band of a scan is done
def time_to_refresh_queue(self):
return ((datetime.utcnow() - self.refresh_date).total_seconds() >
self.minutes * 60 or self.queues == [[]])
# Function to empty all queues in the queues list
def empty_queues(self):
self.queues = [[]]
# How long to delay since last action
def delay(self, last_scan_date):
return max(
((last_scan_date - datetime.utcnow()).total_seconds() +
self.args.scan_delay),
2)
def band_status(self):
try:
bands_total = len(self.locations) * 5
bands_filled = ScannedLocation.get_bands_filled_by_cellids(
self.scans.keys())
percent = bands_filled * 100.0 / bands_total
if bands_total == bands_filled:
log.info('Initial spawnpoint scan is complete')
else:
log.info('Initial spawnpoint scan, %d of %d bands are done ' +
'or %.1f%% complete', bands_filled, bands_total,
percent)
return percent
except Exception as e:
log.error(
'Exception in band_status: Exception message: {}'.format(
repr(e)))
# Update the queue, and provide a report on performance of last minutes
def schedule(self):
log.info('Refreshing queue')
self.ready = False
now_date = datetime.utcnow()
self.refresh_date = now_date
self.refresh_ms = now_date.minute * 60 + now_date.second
old_q = deepcopy(self.queues[0])
queue = []
# Measure the time it takes to refresh the queue
start = time.time()
# prefetch all scanned locations
scanned_locations = ScannedLocation.get_by_cellids(self.scans.keys())
# extract all spawnpoints into a dict with spawnpoint
# id -> spawnpoint for easy access later
cell_to_linked_spawn_points = (
ScannedLocation.get_cell_to_linked_spawn_points(self.scans.keys()))
sp_by_id = {}
for sps in cell_to_linked_spawn_points.itervalues():
for sp in sps:
sp_by_id[sp['id']] = sp
for cell, scan in self.scans.iteritems():
queue += ScannedLocation.get_times(scan, now_date,
scanned_locations)
queue += SpawnPoint.get_times(cell, scan, now_date,
self.args.spawn_delay,
cell_to_linked_spawn_points,
sp_by_id)
end = time.time()
queue.sort(key=itemgetter('start'))
self.queues[0] = queue
self.ready = True
log.info('New queue created with %d entries in %f seconds', len(queue),
(end - start))
if old_q:
# Enclosing in try: to avoid divide by zero exceptions from
# killing overseer
try:
# Possible 'done' values are 'Missed', 'Scanned', None, or
# number
Not_none_list = filter(lambda e: e.get(
'done', None) is not None, old_q)
Missed_list = filter(lambda e: e.get(
'done', None) == 'Missed', Not_none_list)
Scanned_list = filter(lambda e: e.get(
'done', None) == 'Scanned', Not_none_list)
Timed_list = filter(lambda e: type(
e['done']) is not str, Not_none_list)
spawns_timed_list = filter(
lambda e: e['kind'] == 'spawn', Timed_list)
spawns_timed = len(spawns_timed_list)
bands_timed = len(
filter(lambda e: e['kind'] == 'band', Timed_list))
spawns_all = spawns_timed + \
len(filter(lambda e: e['kind'] == 'spawn', Scanned_list))
spawns_missed = len(
filter(lambda e: e['kind'] == 'spawn', Missed_list))
band_percent = self.band_status()
kinds = {}
tth_ranges = {}
self.tth_found = 0
self.active_sp = 0
found_percent = 100.0
good_percent = 100.0
spawns_reached = 100.0
spawnpoints = SpawnPoint.select_in_hex(
self.scan_location, self.args.step_limit)
for sp in spawnpoints:
if sp['missed_count'] > 5:
continue
self.active_sp += 1
self.tth_found += (sp['earliest_unseen'] ==
sp['latest_seen'])
kind = sp['kind']
kinds[kind] = kinds.get(kind, 0) + 1
tth_range = str(int(round(
((sp['earliest_unseen'] - sp['latest_seen']) % 3600) /
60.0)))
tth_ranges[tth_range] = tth_ranges.get(tth_range, 0) + 1
tth_ranges['0'] = tth_ranges.get('0', 0) - self.tth_found
len_spawnpoints = len(spawnpoints) + (not len(spawnpoints))
log.info('Total Spawn Points found in hex: %d',
len(spawnpoints))
log.info('Inactive Spawn Points found in hex: %d or %.1f%%',
len(spawnpoints) - self.active_sp,
(len(spawnpoints) -
self.active_sp) * 100.0 / len_spawnpoints)
log.info('Active Spawn Points found in hex: %d or %.1f%%',
self.active_sp,
self.active_sp * 100.0 / len_spawnpoints)
self.active_sp += self.active_sp == 0
for k in sorted(kinds.keys()):
log.info('%s kind spawns: %d or %.1f%%', k,
kinds[k], kinds[k] * 100.0 / self.active_sp)
log.info('Spawns with found TTH: %d or %.1f%% [%d missing]',
self.tth_found,
self.tth_found * 100.0 / self.active_sp,
self.active_sp - self.tth_found)
for k in sorted(tth_ranges.keys(), key=int):
log.info('Spawnpoints with a %sm range to find TTH: %d', k,
tth_ranges[k])
log.info('Over last %d minutes: %d new bands, %d Pokemon ' +
'found', self.minutes, bands_timed, spawns_all)
log.info('Of the %d total spawns, %d were targeted, and %d ' +
'found scanning for others', spawns_all, spawns_timed,
spawns_all - spawns_timed)
scan_total = spawns_timed + bands_timed
spm = scan_total / self.minutes
seconds_per_scan = self.minutes * 60 * \
self.args.workers / scan_total if scan_total else 0
log.info('%d scans over %d minutes, %d scans per minute, %d ' +
'secs per scan per worker', scan_total, self.minutes,
spm, seconds_per_scan)
sum = spawns_all + spawns_missed
if sum:
spawns_reached = spawns_all * 100.0 / \
(spawns_all + spawns_missed)
log.info('%d Pokemon found, and %d were not reached in ' +
'time for %.1f%% found', spawns_all,
spawns_missed, spawns_reached)
if spawns_timed:
average = reduce(
lambda x, y: x + y['done'],
spawns_timed_list,
0) / spawns_timed
log.info('%d Pokemon found, %d were targeted, with an ' +
'average delay of %d sec', spawns_all,
spawns_timed, average)
spawns_missed = reduce(
lambda x, y: x + len(y),
self.spawns_missed_delay.values(), 0)
sum = spawns_missed + self.spawns_found
found_percent = (
self.spawns_found * 100.0 / sum if sum else 0)
log.info('%d spawns scanned and %d spawns were not ' +
'there when expected for %.1f%%',
self.spawns_found, spawns_missed, found_percent)
self.spawn_percent.append(round(found_percent, 1))
if self.spawns_missed_delay:
log.warning('Missed spawn IDs with times after spawn:')
log.warning(self.spawns_missed_delay)
log.info('History: %s', str(
self.spawn_percent).strip('[]'))
sum = self.scans_done + len(self.scans_missed_list)
good_percent = self.scans_done * 100.0 / sum if sum else 0
log.info(
'%d scans successful and %d scans missed for %.1f%% found',
self.scans_done, len(self.scans_missed_list), good_percent)
self.scan_percent.append(round(good_percent, 1))
if self.scans_missed_list:
log.warning('Missed scans: %s', Counter(
self.scans_missed_list).most_common(3))
log.info('History: %s', str(self.scan_percent).strip('[]'))
self.status_message = ('Initial scan: {:.2f}%, TTH found: ' +
'{:.2f}% [{} missing], ').format(
band_percent, self.tth_found * 100.0 / self.active_sp,
self.active_sp - self.tth_found)
self.status_message += ('Spawns reached: {:.2f}%, Spawns ' +
'found: {:.2f}%, Good scans ' +
'{:.2f}%').format(spawns_reached,
found_percent,
good_percent)
self._stat_init()
except Exception as e:
log.error(
'Performance statistics had an Exception: {}'.format(
repr(e)))
traceback.print_exc(file=sys.stdout)
# Find the best item to scan next
def next_item(self, status):
# Thread safety: don't let multiple threads get the same "best item".
with self.lock_next_item:
# Score each item in the queue by # of due spawns or scan time
# bands can be filled.
while not self.ready:
time.sleep(1)
now_date = datetime.utcnow()
now_time = time.time()
n = 0 # count valid scans reviewed
q = self.queues[0]
ms = ((now_date - self.refresh_date).total_seconds() +
self.refresh_ms)
best = {'score': 0}
cant_reach = False
worker_loc = [status['latitude'], status['longitude']]
last_action = status['last_scan_date']
# Check all scan locations possible in the queue.
for i, item in enumerate(q):
# If already claimed by another worker or done, pass.
if item.get('done', False):
continue
# If the item is parked by a different thread (or by a
# different account, which should be on that one thread),
# pass.
our_parked_name = status['username']
if 'parked_name' in item:
# We use 'parked_last_update' to determine when the
# last time was since the thread passed the item with the
# same thread name & username. If it's been too long, unset
# the park so another worker can pick it up.
now = default_timer()
max_parking_idle_seconds = 3 * 60
if (now - item.get('parked_last_update', now)
> max_parking_idle_seconds):
# Unpark & don't skip it.
item.pop('parked_name', None)
item.pop('parked_last_update', None)
else:
# Still parked and not our item. Skip it.
if item.get('parked_name') != our_parked_name:
continue
# If already timed out, mark it as Missed and check next.
if ms > item['end']:
item['done'] = 'Missed' if not item.get(
'done', False) else item['done']
continue
# If we just did a fresh band recently, wait a few seconds to
# space out the band scans.
if now_date < self.next_band_date:
continue
# If the start time isn't yet, don't bother looking further,
# since queue sorted by start time.
if ms < item['start']:
break
loc = item['loc']
distance = equi_rect_distance(loc, worker_loc)
secs_to_arrival = distance / self.args.kph * 3600
# If we can't make it there before it disappears, don't bother
# trying.
if ms + secs_to_arrival > item['end']:
cant_reach = True
continue
n += 1
# Bands are top priority to find new spawns first
score = 1e12 if item['kind'] == 'band' else (
1e6 if item['kind'] == 'TTH' else 1)
# For spawns, score is purely based on how close they are to
# last worker position
score = score / (distance + .01)
if score > best['score']:
best = {'score': score, 'i': i}
best.update(item)
prefix = 'Calc %.2f for %d scans:' % (time.time() - now_time, n)
loc = best.get('loc', [])
step = best.get('step', 0)
i = best.get('i', 0)
messages = {
'wait': 'Nothing to scan.',
'early': 'Early for step {}; waiting a few seconds...'.format(
step),
'late': ('API response on step {} delayed by {} seconds. ' +
'Possible causes: slow proxies, internet, or ' +
'Niantic servers.').format(
step,
int((now_date - last_action).total_seconds())),
'search': 'Searching at step {}.'.format(step),
'invalid': ('Invalid response at step {}, abandoning ' +
'location.').format(step)
}
try:
item = q[i]
except IndexError:
messages['wait'] = ('Search aborting.'
+ ' Overseer refreshing queue.')
return -1, 0, 0, 0, messages
if best['score'] == 0:
if cant_reach:
messages['wait'] = ('Not able to reach any scan'
+ ' under the speed limit.')
return -1, 0, 0, 0, messages
distance = equi_rect_distance(loc, worker_loc)
if (distance >
(now_date - last_action).total_seconds() *
self.args.kph / 3600):
# Flag item as "parked" by a specific thread, because
# we're waiting for it. This will avoid all threads "walking"
# to the same item.
our_parked_name = status['username']
item['parked_name'] = our_parked_name
# CTRL+F 'parked_last_update' in this file for more info.
item['parked_last_update'] = default_timer()
messages['wait'] = 'Moving {}m to step {} for a {}.'.format(
int(distance * 1000), step,
best['kind'])
return -1, 0, 0, 0, messages
prefix += ' Step %d,' % (step)
# Check again if another worker heading there.
# TODO: Check if this is still necessary. I believe this was
# originally a failed attempt at thread safety, which still
# resulted in a race condition (multiple workers heading to the
# same spot). A thread Lock has since been added.
if item.get('done', False):
messages['wait'] = ('Skipping step {}. Other worker already ' +
'scanned.').format(step)
return -1, 0, 0, 0, messages
if not self.ready:
messages['wait'] = ('Search aborting.'
+ ' Overseer refreshing queue.')
return -1, 0, 0, 0, messages
# If a new band, set the date to wait until for the next band.
if best['kind'] == 'band' and best['end'] - best['start'] > 5 * 60:
self.next_band_date = datetime.utcnow() + timedelta(
seconds=self.band_spacing)
# Mark scanned
item['done'] = 'Scanned'
status['index_of_queue_item'] = i
messages['search'] = 'Scanning step {} for a {}.'.format(
best['step'], best['kind'])
return best['step'], best['loc'], 0, 0, messages
def task_done(self, status, parsed=False):
if parsed:
# Record delay between spawn time and scanning for statistics
now_secs = date_secs(datetime.utcnow())
item = self.queues[0][status['index_of_queue_item']]
seconds_within_band = (
int((datetime.utcnow() - self.refresh_date).total_seconds()) +
self.refresh_ms)
enforced_delay = (self.args.spawn_delay if item['kind'] == 'spawn'
else 0)
start_delay = seconds_within_band - item['start'] + enforced_delay
safety_buffer = item['end'] - seconds_within_band
if safety_buffer < 0:
log.warning('Too late by %d sec for a %s at step %d', -
safety_buffer, item['kind'], item['step'])
# If we had a 0/0/0 scan, then unmark as done so we can retry, and
# save for Statistics
elif parsed['bad_scan']:
self.scans_missed_list.append(cellid(item['loc']))
# Only try for a set amount of times (BAD_SCAN_RETRY)
if self.args.bad_scan_retry > 0 and (
self.scans_missed_list.count(cellid(item['loc'])) >
self.args.bad_scan_retry):
log.info('Step %d failed scan for %d times! Giving up...',
item['step'], self.args.bad_scan_retry + 1)
else:
item['done'] = None
log.info('Putting back step %d in queue', item['step'])
else:
# Scan returned data
self.scans_done += 1
item['done'] = start_delay
# Were we looking for spawn?
if item['kind'] == 'spawn':
sp_id = item['sp']
# Did we find the spawn?
if sp_id in parsed['sp_id_list']:
self.spawns_found += 1
elif start_delay > 0: # not sure why this could be
# negative, but sometimes it is
# if not, record ID and put back in queue
self.spawns_missed_delay[
sp_id] = self.spawns_missed_delay.get(sp_id, [])
self.spawns_missed_delay[sp_id].append(start_delay)
item['done'] = 'Scanned'
# For existing spawn points, if in any other queue items, mark
# 'scanned'
for sp_id in parsed['sp_id_list']:
for item in self.queues[0]:
if (sp_id == item.get('sp', None) and
item.get('done', None) is None and
now_secs > item['start'] and
now_secs < item['end']):
item['done'] = 'Scanned'
# The SchedulerFactory returns an instance of the correct type of scheduler.
class SchedulerFactory():
__schedule_classes = {
"hexsearch": HexSearch,
"hexsearchspawnpoint": HexSearchSpawnpoint,
"spawnscan": SpawnScan,
"speedscan": SpeedScan,
}
@staticmethod
def get_scheduler(name, *args, **kwargs):
scheduler_class = SchedulerFactory.__schedule_classes.get(
name.lower(), None)
if scheduler_class:
return scheduler_class(*args, **kwargs)
raise NotImplementedError(
"The requested scheduler has not been implemented")
# The KeyScheduler returns a scheduler that cycles through the given hash
# server keys.
class KeyScheduler(object):
def __init__(self, keys):
self.keys = {}
for key in keys:
self.keys[key] = {
'remaining': 0,
'maximum': 0,
'peak': 0
}
self.key_cycle = itertools.cycle(keys)
self.curr_key = ''
def keys(self):
return self.keys
def current(self):
return self.curr_key
def next(self):
self.curr_key = self.key_cycle.next()
return self.curr_key
| slgphantom/RocketMap | pogom/schedulers.py | Python | agpl-3.0 | 46,757 |
# -*- coding: utf-8 -*-
#
# privacyIDEA is a fork of LinOTP
# May 08, 2014 Cornelius Kölbel
# License: AGPLv3
# contact: http://www.privacyidea.org
#
# 2014-10-17 Fix the empty result problem
# Cornelius Kölbel, <cornelius@privacyidea.org>
#
# Copyright (C) 2010 - 2014 LSE Leading Security Experts GmbH
# License: AGPLv3
# contact: http://www.linotp.org
# http://www.lsexperts.de
# linotp@lsexperts.de
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# License as published by the Free Software Foundation; either
# version 3 of the License, or any later version.
#
# This code 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 AFFERO GENERAL PUBLIC LICENSE for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program. If not, see <http://www.gnu.org/licenses/>.
#
__doc__="""This is the BaseClass for audit trails
The audit is supposed to work like this. First we need to create an audit
object. E.g. this can be done in the before_request:
g.audit_object = getAudit(file_config)
During the request, the g.audit_object can be used to add audit information:
g.audit_object.log({"client": "123.2.3.4", "action": "validate/check"})
Thus at many different places in the code, audit information can be added to
the audit object.
Finally the audit_object needs to be stored to the audit storage. So we call:
g.audit_object.finalize_log()
which creates a signature of the audit data and writes the data to the audit
storage.
"""
import logging
log = logging.getLogger(__name__)
from privacyidea.lib.log import log_with
import socket
from datetime import datetime, timedelta
class Paginate(object):
"""
This is a pagination object, that is used for searching audit trails.
"""
def __init__(self):
# The audit data
self.auditdata = []
# The number of the previous page
self.prev = None
# the number of the next page
self.next = None
# the number of the current page
self.current = 1
# the total entry numbers
self.total = 0
class Audit(object): # pragma: no cover
def __init__(self, config=None):
"""
Create a new audit object.
:param config: The web config is passed to the audit module, so that
the special module implementation can get its configuration.
:type config: dict
:return:
"""
self.name = "AuditBase"
self.audit_data = {}
self.private = ""
self.public = ""
@log_with(log)
def initialize(self):
# defaults
self.audit_data = {'action_detail': '',
'info': '',
'log_level': 'INFO',
'administrator': '',
'value': '',
'key': '',
'serial': '',
'token_type': '',
'clearance_level': 0,
'privacyidea_server': socket.gethostname(),
'realm': '',
'user': '',
'client': ''
}
#controller = request.environ['pylons.routes_dict']['controller']
#action = request.environ['pylons.routes_dict']['action']
#c.audit['action'] = "%s/%s" % (controller, action)
def log_token_num(self, count):
"""
Log the number of the tokens.
Can be passed like
log_token_num(get_tokens(count=True))
:param count: Number of tokens
:type count: int
:return:
"""
self.audit_data['action_detail'] = "tokennum = %s" % str(count)
@log_with(log)
def read_keys(self, pub, priv):
"""
Set the private and public key for the audit class. This is achieved by
passing the entries.
#priv = config.get("privacyideaAudit.key.private")
#pub = config.get("privacyideaAudit.key.public")
:param pub: Public key, used for verifying the signature
:type pub: string with filename
:param priv: Private key, used to sign the audit entry
:type priv: string with filename
:return: None
"""
try:
f = open(priv, "r")
self.private = f.read()
f.close()
except Exception as e:
log.error("Error reading private key %s: (%r)" % (priv, e))
raise e
try:
f = open(pub, "r")
self.public = f.read()
f.close()
except Exception as e:
log.error("Error reading public key %s: (%r)" % (pub, e))
raise e
def get_audit_id(self):
return self.name
def get_total(self, param, AND=True, display_error=True):
"""
This method returns the total number of audit entries
in the audit store
"""
return None
@log_with(log)
def log(self, param): # pragma: no cover
"""
This method is used to log the data.
During a request this method can be called several times to fill the
internal audit_data dictionary.
"""
pass
def add_to_log(self, param):
"""
Add to existing log entry
:param param:
:return:
"""
pass
def finalize_log(self):
"""
This method is called to finalize the audit_data. I.e. sign the data
and write it to the database.
It should hash the data and do a hash chain and sign the data
"""
pass
def initialize_log(self, param):
"""
This method initialized the log state.
The fact, that the log state was initialized, also needs to be logged.
Therefor the same params are passed as i the log method.
"""
pass
def set(self):
"""
This function could be used to set certain things like the signing key.
But maybe it should only be read from privacyidea.ini?
"""
pass
def search(self, param, display_error=True, rp_dict=None):
"""
This function is used to search audit events.
param: Search parameters can be passed.
return: A pagination object
This function is deprecated.
"""
return Paginate()
def csv_generator(self, param):
"""
A generator that can be used to stream the audit log
:param param:
:return:
"""
pass
def search_query(self, search_dict, rp_dict):
"""
This function returns the audit log as an iterator on the result
"""
return None
def audit_entry_to_dict(self, audit_entry):
"""
If the search_query returns an iterator with elements that are not a
dictionary, the audit module needs
to provide this function, to convert the audit entry to a dictionary.
"""
return {}
def get_dataframe(self, start_time=datetime.now()-timedelta(days=7),
end_time=datetime.now()):
"""
The Audit module can handle its data the best. This function is used
to return a pandas.dataframe with all audit data in the given time
frame.
This dataframe then can be used for extracting statistics.
:param start_time: The start time of the data
:type start_time: datetime
:param end_time: The end time of the data
:type end_time: datetime
:return: Audit data
:rtype: dataframe
"""
return None
| woddx/privacyidea | privacyidea/lib/auditmodules/base.py | Python | agpl-3.0 | 7,831 |
<!-- $Id$ -->
<!-- PARAGRAPHE 1 -->
<p class="help_title">{t}Administration tab allows you to do the following operations{/t}:</p>
<ul>
<li><strong>{t}Import data{/t},</strong></li>
<li><strong>{t}manage user accounts{/t},</strong></li>
<li><strong>{t}customise alerts emitted by Onlogistics and assign them to users{/t},</strong></li>
<li><strong>{t}customise product types{/t},</strong></li>
<li><strong>{t}manage catalogues{/t}</strong></li>
</ul> | danilo-cesar/onlogistics | lib/templates/HelpPage/Administration.html | HTML | agpl-3.0 | 456 |
/*
* MobileV2.java
*
* Tigase Jabber/XMPP Server
* Copyright (C) 2004-2013 "Tigase, Inc." <office@tigase.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. Look for COPYING file in the top folder.
* If not, see http://www.gnu.org/licenses/.
*
*/
package tigase.xmpp.impl;
//~--- non-JDK imports --------------------------------------------------------
import tigase.db.NonAuthUserRepository;
import tigase.db.TigaseDBException;
import tigase.server.Iq;
import tigase.server.Packet;
import tigase.xml.Element;
import tigase.xmpp.*;
//~--- JDK imports ------------------------------------------------------------
import java.util.concurrent.ConcurrentHashMap;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Map;
import java.util.Queue;
/**
* Class responsible for queuing packets (usable in connections from mobile
* clients - power usage optimization) version 2
*
* @author andrzej
*/
public class MobileV2
extends XMPPProcessor
implements XMPPProcessorIfc, XMPPPacketFilterIfc {
// default values
private static final int DEF_MAX_QUEUE_SIZE_VAL = 50;
private static final String ID = "mobile_v2";
private static final Logger log = Logger.getLogger(MobileV2.class.getCanonicalName());
// keys
private static final String MAX_QUEUE_SIZE_KEY = "max-queue-size";
private static final String MOBILE_EL_NAME = "mobile";
private static final String XMLNS = "http://tigase.org/protocol/mobile#v2";
private static final String[][] ELEMENT_PATHS = {
{ Iq.ELEM_NAME, MOBILE_EL_NAME }
};
private static final String[] XMLNSS = { XMLNS };
private static final Element[] SUP_FEATURES = { new Element(MOBILE_EL_NAME,
new String[] { "xmlns" }, new String[] { XMLNS }) };
private static final String QUEUE_KEY = ID + "-queue";
//~--- fields ---------------------------------------------------------------
private int maxQueueSize = DEF_MAX_QUEUE_SIZE_VAL;
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
*
*/
@Override
public String id() {
return ID;
}
/**
* Method description
*
*
* @param settings
*
* @throws TigaseDBException
*/
@Override
public void init(Map<String, Object> settings) throws TigaseDBException {
super.init(settings);
Integer maxQueueSizeVal = (Integer) settings.get(MAX_QUEUE_SIZE_KEY);
if (maxQueueSizeVal != null) {
maxQueueSize = maxQueueSizeVal;
}
}
/**
* Method description
*
*
* @param packet
* @param session
* @param repo
* @param results
* @param settings
*/
@Override
public void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings) {
if (session == null) {
return;
}
if (!session.isAuthorized()) {
try {
results.offer(session.getAuthState().getResponseMessage(packet,
"Session is not yet authorized.", false));
} catch (PacketErrorTypeException ex) {
log.log(Level.FINEST,
"ignoring packet from not authorized session which is already of type error");
}
return;
}
try {
StanzaType type = packet.getType();
switch (type) {
case set :
Element el = packet.getElement().getChild(MOBILE_EL_NAME);
String valueStr = el.getAttributeStaticStr("enable");
// if value is true queuing will be enabled
boolean value = (valueStr != null) && ("true".equals(valueStr) || "1".equals(
valueStr));
if (session.getSessionData(QUEUE_KEY) == null) {
// session.putSessionData(QUEUE_KEY, new
// LinkedBlockingQueue<Packet>());
session.putSessionData(QUEUE_KEY, new ConcurrentHashMap<JID, Packet>());
}
session.putSessionData(XMLNS, value);
results.offer(packet.okResult((Element) null, 0));
break;
default :
results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet,
"Mobile processing type is incorrect", false));
}
} catch (PacketErrorTypeException ex) {
Logger.getLogger(MobileV2.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Method description
*
*
*
*/
@Override
public String[][] supElementNamePaths() {
return ELEMENT_PATHS;
}
/**
* Method description
*
*
*
*/
@Override
public String[] supNamespaces() {
return XMLNSS;
}
/**
* Method description
*
*
* @param session
*
*
*/
@Override
public Element[] supStreamFeatures(XMPPResourceConnection session) {
if (session == null) {
return null;
}
if (!session.isAuthorized()) {
return null;
}
return SUP_FEATURES;
}
/**
* Method description
*
*
* @param _packet
* @param sessionFromSM
* @param repo
* @param results
*/
@Override
@SuppressWarnings("unchecked")
public void filter(Packet _packet, XMPPResourceConnection sessionFromSM,
NonAuthUserRepository repo, Queue<Packet> results) {
if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) ||
(results.size() == 0)) {
return;
}
for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) {
Packet res = it.next();
// check if packet contains destination
if ((res == null) || (res.getPacketTo() == null)) {
if (log.isLoggable(Level.FINEST)) {
log.finest("packet without destination");
}
continue;
}
// get resource connection for destination
XMPPResourceConnection session = sessionFromSM.getParentSession()
.getResourceForConnectionId(res.getPacketTo());
if (session == null) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "no session for destination {0} for packet {1}",
new Object[] { res.getPacketTo().toString(),
res.toString() });
}
// if there is no session we should not queue
continue;
}
Map<JID, Packet> queue = (Map<JID, Packet>) session.getSessionData(QUEUE_KEY);
// if queue is not enabled we do nothing
if (!isQueueEnabled(session)) {
if (log.isLoggable(Level.FINEST)) {
log.finest("queue is no enabled");
}
if ((queue != null) &&!queue.isEmpty()) {
if (log.isLoggable(Level.FINEST)) {
log.finest("sending packets from queue (DISABLED)");
}
for (Packet p : queue.values()) {
results.offer(p);
}
queue.clear();
}
continue;
}
// lets check if packet should be queued
if (filter(session, res, queue)) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "queuing packet = {0}", res.toString());
}
it.remove();
if (queue.size() > maxQueueSize) {
if (log.isLoggable(Level.FINEST)) {
log.finest("sending packets from queue (OVERFLOW)");
}
for (Packet p : queue.values()) {
results.offer(res);
}
queue.clear();
// we are sending all items from map so there is no need
// to filter it (fix for ConcurrentModificationException)
break;
}
}
}
}
/**
* Method description
*
*
* @param session
* @param res
* @param queue
*
*
*/
public boolean filter(XMPPResourceConnection session, Packet res, Map<JID,
Packet> queue) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "checking if packet should be queued {0}", res.toString());
}
if (res.getElemName() != "presence") {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "ignoring packet, packet is not presence: {0}", res
.toString());
}
return false;
}
StanzaType type = res.getType();
if ((type != null) && (type != StanzaType.unavailable) && (type != StanzaType
.available)) {
return false;
}
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "queuing packet {0}", res.toString());
}
queue.put(res.getStanzaFrom(), res);
return true;
}
//~--- get methods ----------------------------------------------------------
/**
* Check if queuing is enabled
*
* @param session
*
*/
protected boolean isQueueEnabled(XMPPResourceConnection session) {
Boolean enabled = (Boolean) session.getSessionData(XMLNS);
return (enabled != null) && enabled;
}
}
//~ Formatted in Tigase Code Convention on 13/03/16
| wangningbo/tigase-server | src/main/java/tigase/xmpp/impl/MobileV2.java | Java | agpl-3.0 | 8,860 |
"""
Django Admin pages for DiscountRestrictionConfig.
"""
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from openedx.core.djangoapps.config_model_utils.admin import StackedConfigModelAdmin
from .models import DiscountPercentageConfig, DiscountRestrictionConfig
class DiscountRestrictionConfigAdmin(StackedConfigModelAdmin):
"""
Admin to configure discount restrictions
"""
fieldsets = (
('Context', {
'fields': DiscountRestrictionConfig.KEY_FIELDS,
'description': _(
'These define the context to disable lms-controlled discounts on. '
'If no values are set, then the configuration applies globally. '
'If a single value is set, then the configuration applies to all courses '
'within that context. At most one value can be set at a time.<br>'
'If multiple contexts apply to a course (for example, if configuration '
'is specified for the course specifically, and for the org that the course '
'is in, then the more specific context overrides the more general context.'
),
}),
('Configuration', {
'fields': ('disabled',),
'description': _(
'If any of these values is left empty or "Unknown", then their value '
'at runtime will be retrieved from the next most specific context that applies. '
'For example, if "Disabled" is left as "Unknown" in the course context, then that '
'course will be Disabled only if the org that it is in is Disabled.'
),
})
)
raw_id_fields = ('course',)
admin.site.register(DiscountRestrictionConfig, DiscountRestrictionConfigAdmin)
class DiscountPercentageConfigAdmin(StackedConfigModelAdmin):
"""
Admin to configure discount percentage
"""
fieldsets = (
('Context', {
'fields': DiscountRestrictionConfig.KEY_FIELDS,
'description': _(
'These define the context to configure the percentage for the first purchase discount.'
'If multiple contexts apply to a course (for example, if configuration '
'is specified for the course specifically, and for the org that the course '
'is in, then the more specific context overrides the more general context.'
),
}),
('Configuration', {
'fields': ('percentage',),
})
)
raw_id_fields = ('course',)
admin.site.register(DiscountPercentageConfig, DiscountPercentageConfigAdmin)
| edx/edx-platform | openedx/features/discounts/admin.py | Python | agpl-3.0 | 2,665 |
@CHARSET "UTF-8";
body {
background-color: #f0f0f0;
}
#wrapper {
margin: 100px auto;
width: 310px;
}
#email {
width: 248px;
}
#text {
width: 248px;
height: 70px;
}
#waiting {
color: #767676;
text-align: center;
}
fieldset {
margin-top: 10px;
background: #fff;
border: 1px solid #c8c8c8;
background-color: #fff;
}
legend {
background-color: #fff;
border-top: 1px solid #c8c8c8;
border-right: 1px solid #c8c8c8;
border-left: 1px solid #c8c8c8;
font-size: 1.2em;
padding: 0px 7px;
}
label {
display: inline-block;
width: 50px;
}
.success {
width: 298px;
background: #a5e283;
border: #337f09 1px solid;
padding: 5px;
}
.error {
width: 298px;
background: #ea7e7e;
border: #a71010 1px solid;
padding: 5px;
}
| kuali/kc | coeus-webapp/src/main/webapp/scripts/jquery/css/main.css | CSS | agpl-3.0 | 825 |
require File.expand_path(File.dirname(__FILE__) + '/../common')
require File.expand_path(File.dirname(__FILE__) + '/../helpers/users_common')
require File.expand_path(File.dirname(__FILE__) + '/../helpers/basic/users_specs')
describe "admin courses tab" do
include_context "in-process server selenium tests"
include UsersCommon
context "add user basic" do
describe "shared users specs" do
let(:account) { Account.default }
let(:url) { "/accounts/#{account.id}/users" }
let(:opts) { {:name => 'student'} }
include_examples "users basic tests"
end
end
context "add users" do
before(:each) do
course_with_admin_logged_in
get "/accounts/#{Account.default.id}/users"
end
it "should add an new user with a sortable name" do
add_user({:sortable_name => "sortable name"})
end
it "should add an new user with a short name" do
add_user({:short_name => "short name"})
end
it "should add a new user with confirmation disabled" do
add_user({:confirmation => 0})
end
it "should search for a user and should go to it" do
skip('disabled until we can fix performance')
name = "user_1"
add_user({:name => name})
f("#right-side #user_name").send_keys(name)
ff(".ui-menu-item .ui-corner-all").count > 0
wait_for_ajax_requests
expect(fj(".ui-menu-item .ui-corner-all:visible")).to include_text(name)
fj(".ui-menu-item .ui-corner-all:visible").click
wait_for_ajax_requests
expect(f("#content h2")).to include_text name
end
it "should search for a bogus user" do
name = "user_1"
add_user({:name => name})
bogus_name = "ser 1"
f("#right-side #user_name").send_keys(bogus_name)
ff(".ui-menu-item .ui-corner-all").count == 0
end
end
end | narigone/canvas | spec/selenium/admin/admin_users_spec.rb | Ruby | agpl-3.0 | 1,831 |
<?php
/*
* Copyright (C) 2021 Xibo Signage Ltd
*
* Xibo - Digital Signage - http://www.xibo.org.uk
*
* This file is part of Xibo.
*
* Xibo is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Xibo 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Xibo. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Xibo\Tests\integration;
use Xibo\Helper\Random;
use Xibo\OAuth2\Client\Exception\XiboApiException;
use Xibo\Tests\LocalWebTestCase;
/**
* Class UserGroupTest
* @package Xibo\Tests\integration
*/
class UserGroupTest extends LocalWebTestCase
{
/**
* Add a new group and then check it was added correctly.
*/
public function testAdd()
{
$params = [
'group' => Random::generateString(),
'description' => Random::generateString()
];
$response = $this->sendRequest('POST', '/group', $params);
$this->assertSame(200, $response->getStatusCode(), $response->getBody());
$object = json_decode($response->getBody());
$this->assertObjectHasAttribute('data', $object, $response->getBody());
$this->assertObjectHasAttribute('id', $object, $response->getBody());
// Use the API to get it out again
try {
//$group = (new XiboUserGroup($this->getEntityProvider()))->getById($object->id);
$group = $this->getEntityProvider()->get('/group', ['userGroupId' => $object->id])[0];
// Check our key parts match.
$this->assertSame($params['group'], $group['group'], 'Name does not match');
$this->assertSame($params['description'], $group['description'], 'Description does not match');
} catch (XiboApiException $e) {
$this->fail('Group not found. e = ' . $e->getMessage());
}
}
}
| xibosignage/xibo-cms | tests/integration/UserGroupTest.php | PHP | agpl-3.0 | 2,253 |
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2013-2014 OpenVPN Technologies, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
#ifndef OPENVPN_CLIENT_CLICONSTANTS_H
#define OPENVPN_CLIENT_CLICONSTANTS_H
// Various sanity checks for different limits on OpenVPN clients
namespace openvpn {
namespace ProfileParseLimits {
enum {
MAX_PROFILE_SIZE=262144, // maximum size of an OpenVPN configuration file
MAX_PUSH_SIZE=65536, // maximum size of aggregate data that can be pushed to a client
MAX_LINE_SIZE=512, // maximum size of an OpenVPN configuration file line
MAX_DIRECTIVE_SIZE=64, // maximum number of chars in an OpenVPN directive
OPT_OVERHEAD=64, // bytes overhead of one option/directive, for accounting purposes
TERM_OVERHEAD=16, // bytes overhead of one argument in an option, for accounting purposes
};
}
}
#endif
| jmaurice/openvpn3 | openvpn/client/cliconstants.hpp | C++ | agpl-3.0 | 1,779 |
##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# 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) version 2.1, February 1999.
#
# 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 terms and
# conditions of 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
"""
This module contains external, potentially separately licensed,
packages that are included in spack.
So far:
argparse: We include our own version to be Python 2.6 compatible.
distro: Provides a more stable linux distribution detection.
functools: Used for implementation of total_ordering.
jinja2: A modern and designer-friendly templating language for Python
jsonschema: An implementation of JSON Schema for Python.
ordereddict: We include our own version to be Python 2.6 compatible.
py: Needed by pytest. Library with cross-python path,
ini-parsing, io, code, and log facilities.
pyqver2: External script to query required python version of
python source code. Used for ensuring 2.6 compatibility.
pytest: Testing framework used by Spack.
yaml: Used for config files.
"""
| TheTimmy/spack | lib/spack/external/__init__.py | Python | lgpl-2.1 | 2,139 |
var classambhas_1_1stats_1_1SpatOutlier =
[
[ "__init__", "classambhas_1_1stats_1_1SpatOutlier.html#ae600249e9fcbda069e9fbad0ba6983ef", null ],
[ "fill_with_nan", "classambhas_1_1stats_1_1SpatOutlier.html#a826d8579b25e76a53c18617ff226f575", null ],
[ "index", "classambhas_1_1stats_1_1SpatOutlier.html#a4b5bb747042f8c4e0228afa60c358bbb", null ],
[ "outliers", "classambhas_1_1stats_1_1SpatOutlier.html#a212e9d519dd3efa62ed8467d0f77c8cf", null ],
[ "rain", "classambhas_1_1stats_1_1SpatOutlier.html#aec2b15b0062794eee851810e08fdd99a", null ]
]; | tectronics/ambhas | docs/html/classambhas_1_1stats_1_1SpatOutlier.js | JavaScript | lgpl-2.1 | 563 |
package test.beast.evolution.alignment;
import java.util.List;
import org.junit.Test;
import beast.evolution.alignment.Alignment;
import beast.evolution.alignment.Sequence;
import beast.evolution.datatype.DataType;
import beast.evolution.tree.Tree;
import beast.util.TreeParser;
import junit.framework.TestCase;
public class UncertainAlignmentTest extends TestCase {
static public Tree getTreeB(Alignment data) throws Exception {
TreeParser tree = new TreeParser();
tree.initByName("taxa", data,
"newick", "(seq1:2,(seq2:1,seq3:1):1);",
"IsLabelledNewick", true);
return tree;
}
static public Tree getTreeA(Alignment data) throws Exception {
TreeParser tree = new TreeParser();
tree.initByName("taxa", data,
"newick", "((seq1:1,seq2:1):1,seq3:2);",
"IsLabelledNewick", true);
return tree;
}
static public Alignment getUncertainAlignment() throws Exception {
return getUncertainAlignment(false);
}
static public Alignment getUncertainAlignmentDoubled() throws Exception {
return getUncertainAlignment(true);
}
static public Alignment getUncertainAlignment(boolean duplicate) throws Exception {
String seq1Probs = new String("0.7,0.0,0.3,0.0; 0.0,0.3,0.0,0.7; 0.0,0.0,0.0,1.0;");
String seq2Probs = new String("0.7,0.0,0.3,0.0; 0.0,0.3,0.0,0.7; 0.0,1.0,0.0,0.0;");
String seq3Probs = new String("0.4,0.0,0.6,0.0; 0.0,0.6,0.0,0.4; 0.0,1.0,0.0,0.0;");
if (duplicate) {
seq1Probs += seq1Probs;
seq2Probs += seq2Probs;
seq3Probs += seq3Probs;
}
Sequence seq1 = new Sequence();
seq1.initByName("taxon","seq1","value",seq1Probs,"uncertain",true);
Sequence seq2 = new Sequence();
seq2.initByName("taxon","seq2","value",seq2Probs,"uncertain",true);
Sequence seq3 = new Sequence();
seq3.initByName("taxon","seq3","value",seq3Probs,"uncertain",true);
Alignment data = new Alignment();
data.initByName("sequence", seq1, "sequence", seq2, "sequence", seq3,
"dataType", "nucleotide"
);
DataType dataType = data.getDataType();
System.out.println("Most probable sequences:");
for (List<Integer> seq : data.getCounts()) {
System.out.println(dataType.encodingToString(seq));
}
return data;
}
static public Alignment getAlignment() throws Exception {
// The sequences now denote the most likely annotation
Sequence seq1 = new Sequence("seq1", "ATT");
Sequence seq2 = new Sequence("seq2", "ATC");
Sequence seq3 = new Sequence("seq3", "GCC");
Alignment data = new Alignment();
data.initByName("sequence", seq1, "sequence", seq2, "sequence", seq3,
"dataType", "nucleotide"
);
return data;
}
@Test
public void testUncertainAlignment() throws Exception {
Alignment data = getUncertainAlignment();
DataType dataType = data.getDataType();
System.out.println("Tip likelihoods:");
int sites = data.getCounts().get(0).size();
for (int taxon=0; taxon<data.getTaxonCount(); taxon++) {
for (int i=0; i<sites; i++) {
double[] probs = data.getTipLikelihoods(taxon,i);
for (int j=0; j<probs.length; j++) {
System.out.print(probs[j]+" ");
}
System.out.print("; ");
}
System.out.println();
}
System.out.println("Most likely sequences:");
for (List<Integer> seq : data.getCounts()) {
System.out.println(dataType.encodingToString(seq));
}
Alignment data2 = getAlignment();
for (int taxon=0; taxon<data.getTaxonCount(); taxon++) {
assertEquals(data.getCounts().get(taxon),data2.getCounts().get(taxon));
}
}
}
| tgvaughan/beast2 | src/test/beast/evolution/alignment/UncertainAlignmentTest.java | Java | lgpl-2.1 | 4,019 |
/* **********************************************************
* Copyright (c) 2012 Google, Inc. All rights reserved.
* Copyright (c) 2007-2009 VMware, Inc. All rights reserved.
* **********************************************************/
/*
* 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 VMware, Inc. nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. 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.
*/
#ifndef _NUDGE_H_
#define _NUDGE_H_
#include "dr_config.h"
/* Tiggers a nudge targeting this process. nudge_action_mask should be drawn from the
* NUDGE_GENERIC(***) values. client_id is only relevant for client nudges. */
dr_config_status_t
nudge_internal(process_id_t pid, uint nudge_action_mask, uint64 client_arg,
client_id_t client_id, uint timeout_ms);
#ifdef WINDOWS /* only Windows uses threads for nudges */
/* The following are exported only so other routines can check their addresses for
* nudge threads. They are not meant to be called internally. */
void
generic_nudge_target(nudge_arg_t *arg);
bool
generic_nudge_handler(nudge_arg_t *arg);
/* exit_process is only honored if dcontext != NULL, and exit_code is only honored
* if exit_process is true
*/
bool
nudge_thread_cleanup(dcontext_t *dcontext, bool exit_process, uint exit_code);
#else
/* This routine may not return */
void
handle_nudge(dcontext_t *dcontext, nudge_arg_t *arg);
/* Only touches thread-private data and acquires no lock */
void
nudge_add_pending(dcontext_t *dcontext, nudge_arg_t *nudge_arg);
#endif
#endif /* _NUDGE_H_ */
| AmesianX/dynamorio | core/nudge.h | C | lgpl-2.1 | 2,881 |
/*
* JBoss, Home of Professional Open Source
* Copyright 2017, Red Hat, Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.test.integration.management.api;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.security.SecureRandom;
import java.util.Random;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.Operation;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.as.controller.client.helpers.Operations;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.model.test.ChildFirstClassLoaderBuilder;
import org.jboss.as.process.protocol.StreamUtils;
import org.jboss.as.test.integration.management.ManagementOperations;
import org.jboss.as.test.integration.management.util.ServerReload;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.ByteArrayAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Base class to test supported remoting libraries combinations. It is in the shared module so it can be overridden
* in both fill and core.
*
* @author Emanuel Muckenhuber
*/
public abstract class ClientCompatibilityUnitTestBase {
protected abstract static class ClientCompatibilityServerSetup {
public void setup(final ModelControllerClient client) throws Exception {
ModelNode socketBindingOp = Util.createAddOperation(PathAddress.parseCLIStyleAddress("/socket-binding-group=standard-sockets/socket-binding=management-native"));
socketBindingOp.get("interface").set("management");
socketBindingOp.get("port").set("9999");
ManagementOperations.executeOperation(client, socketBindingOp);
// Determine the we should be using a security-realm or SASL
String securityRealm = "ManagementRealm";
String saslAuthFactory = null;
ModelNode op = Operations.createReadResourceOperation(Operations.createAddress("core-service", "management", "management-interface", "http-interface"));
ModelNode result = ManagementOperations.executeOperation(client, op);
if (result.hasDefined("security-realm")) {
securityRealm = result.get("security-realm").asString();
} else if (result.hasDefined("http-upgrade")) {
final ModelNode httpUpgrade = result.get("http-upgrade");
if (httpUpgrade.hasDefined("sasl-authentication-factory")) {
saslAuthFactory = httpUpgrade.get("sasl-authentication-factory").asString();
}
}
op = new ModelNode();
op.get(ModelDescriptionConstants.OP_ADDR).set(address());
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.ADD);
op.get(ModelDescriptionConstants.SOCKET_BINDING).set("management-native");
if (saslAuthFactory != null) {
op.get("sasl-authentication-factory").set(saslAuthFactory);
} else {
op.get(ModelDescriptionConstants.SECURITY_REALM).set(securityRealm);
}
ManagementOperations.executeOperation(client, op);
}
public void tearDown(final ModelControllerClient client) throws Exception {
ModelNode op = new ModelNode();
op.get(ModelDescriptionConstants.OP_ADDR).set(address());
op.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.REMOVE);
ManagementOperations.executeOperation(client, op);
ManagementOperations.executeOperation(client,
Util.createRemoveOperation(PathAddress.parseCLIStyleAddress("/socket-binding-group=standard-sockets/socket-binding=management-native")));
ServerReload.executeReloadAndWaitForCompletion(client);
}
private ModelNode address() {
return PathAddress.pathAddress()
.append(ModelDescriptionConstants.CORE_SERVICE, ModelDescriptionConstants.MANAGEMENT)
.append(ModelDescriptionConstants.MANAGEMENT_INTERFACE, ModelDescriptionConstants.NATIVE_INTERFACE).toModelNode();
}
}
protected static final String CONTROLLER_ADDRESS = System.getProperty("node0", "localhost");
protected static final String WF_CLIENT = "org.wildfly:wildfly-controller-client";
protected static final String WFCORE_CLIENT = "org.wildfly.core:wildfly-controller-client";
protected static final String AS7_CLIENT = "org.jboss.as:jboss-as-controller-client";
protected static final String[] excludes = new String[]{"org.jboss.threads:jboss-threads", "org.jboss:jboss-dmr", "org.jboss.logging:jboss-logging"};
protected static final Archive deployment;
static {
final WebArchive archive = ShrinkWrap.create(WebArchive.class);
// Create basic archive which exceeds the remoting window size
for (int i = 0; i < 10; i++) {
final byte[] data = new byte[8096];
new Random(new SecureRandom().nextLong()).nextBytes(data);
archive.add(new ByteArrayAsset(data), "data" + i);
}
deployment = archive;
}
@Test
public void test711Final() throws Exception {
testAS7("7.1.1.Final");
}
@Test
public void test720Final() throws Exception {
testAS7("7.2.0.Final");
}
@Test
public void test800Final() throws Exception {
test(createClient(WF_CLIENT, "8.0.0.Final", CONTROLLER_ADDRESS, 9999));
}
@Ignore("http upgrade compat issue")
@Test
public void test800FinalHttp() throws Exception {
test(createClient(WF_CLIENT, "8.0.0.Final", CONTROLLER_ADDRESS, 9990));
}
@Test
public void test810Final() throws Exception {
test(createClient(WF_CLIENT, "8.1.0.Final", CONTROLLER_ADDRESS, 9999));
}
@Ignore("http upgrade compat issue")
@Test
public void test810FinalHttp() throws Exception {
test(createClient(WF_CLIENT, "8.1.0.Final", CONTROLLER_ADDRESS, 9990));
}
@Test
public void test820Final() throws Exception {
test(createClient(WF_CLIENT, "8.2.0.Final", CONTROLLER_ADDRESS, 9999));
}
@Ignore("http upgrade compat issue")
@Test
public void test820FinalHttp() throws Exception {
test(createClient(WF_CLIENT, "8.2.0.Final", CONTROLLER_ADDRESS, 9990));
}
@Test
public void test821Final() throws Exception {
test(createClient(WF_CLIENT, "8.2.1.Final", CONTROLLER_ADDRESS, 9999));
}
@Ignore("http upgrade compat issue")
@Test
public void test821FinalHttp() throws Exception {
test(createClient(WF_CLIENT, "8.2.1.Final", CONTROLLER_ADDRESS, 9990));
}
@Test
public void testCore100Final() throws Exception {
testWF("1.0.0.Final", 9999);
}
@Test
public void testCore100FinalHttp() throws Exception {
testWF("1.0.0.Final", 9990);
}
@Test
public void testCore101Final() throws Exception {
testWF("1.0.1.Final", 9999);
}
@Test
public void testCore101FinalHttp() throws Exception {
testWF("1.0.1.Final", 9990);
}
@Test
public void testCore210Final() throws Exception {
testWF("2.1.0.Final", 9999);
}
@Test
public void testCore210FinalHttp() throws Exception {
testWF("2.1.0.Final", 9990);
}
@Test
public void testCore221Final() throws Exception {
testWF("2.2.1.Final", 9999);
}
@Test
public void testCore221FinalHttp() throws Exception {
testWF("2.2.1.Final", 9990);
}
@Test
public void testCore3010Final() throws Exception {
testWF("3.0.10.Final", 9999);
}
@Test
public void testCore3010FinalHttp() throws Exception {
testWF("3.0.10.Final", 9990);
}
@Test
public void testCurrent() throws Exception {
test(ModelControllerClient.Factory.create(CONTROLLER_ADDRESS, 9999));
}
@Test
public void testCurrentHttp() throws Exception {
test(ModelControllerClient.Factory.create(CONTROLLER_ADDRESS, 9990));
}
protected void testAS7(final String version) throws Exception {
test(createClient(AS7_CLIENT, version, CONTROLLER_ADDRESS, 9999));
}
protected void testWF(final String version, int port) throws Exception {
test(createClient(WFCORE_CLIENT, version, CONTROLLER_ADDRESS, port));
}
protected void test(final ModelControllerClient client) throws Exception {
try {
final ModelNode operation = new ModelNode();
operation.get(ModelDescriptionConstants.OP).set(ModelDescriptionConstants.READ_RESOURCE_OPERATION);
operation.get(ModelDescriptionConstants.OP_ADDR).setEmptyList();
// include a lot of garbage
operation.get(ModelDescriptionConstants.RECURSIVE).set(true);
operation.get(ModelDescriptionConstants.INCLUDE_RUNTIME).set(true);
operation.get(ModelDescriptionConstants.INCLUDE_DEFAULTS).set(true);
final ModelNode result = client.execute(operation);
Assert.assertEquals(operation.toString(), ModelDescriptionConstants.SUCCESS, result.get(ModelDescriptionConstants.OUTCOME).asString());
final ModelNode deploy = new ModelNode();
deploy.get(ModelDescriptionConstants.OP).set("add");
deploy.get(ModelDescriptionConstants.OP_ADDR).add("deployment", "compat-test.war");
deploy.get("content").get(0).get("input-stream-index").set(0);
deploy.get("auto-start").set(true);
final Operation o = OperationBuilder.create(deploy)
.addInputStream(deployment.as(ZipExporter.class).exportAsInputStream()).build();
try {
final ModelNode deployResult = client.execute(o);
Assert.assertEquals(deployResult.toString(), ModelDescriptionConstants.SUCCESS, deployResult.get(ModelDescriptionConstants.OUTCOME).asString());
} finally {
final ModelNode undeploy = new ModelNode();
undeploy.get(ModelDescriptionConstants.OP).set("remove");
undeploy.get(ModelDescriptionConstants.OP_ADDR).add("deployment", "compat-test.war");
try {
client.execute(undeploy);
} catch (IOException ignore) {
ignore.printStackTrace();
}
}
} finally {
StreamUtils.safeClose(client);
}
}
protected static ModelControllerClient createClient(final String artifact, final String version, final String host, final int port) throws Exception {
final ChildFirstClassLoaderBuilder classLoaderBuilder = new ChildFirstClassLoaderBuilder(false);
classLoaderBuilder.addRecursiveMavenResourceURL(artifact + ":" + version, excludes);
classLoaderBuilder.addParentFirstClassPattern("org.jboss.as.controller.client.ModelControllerClient");
classLoaderBuilder.addParentFirstClassPattern("org.jboss.as.controller.client.OperationMessageHandler");
classLoaderBuilder.addParentFirstClassPattern("org.jboss.as.controller.client.Operation");
classLoaderBuilder.addParentFirstClassPattern("org.jboss.as.controller.client.OperationResponse*");
classLoaderBuilder.addParentFirstClassPattern("org.jboss.as.protocol.logging.ProtocolLogger*");
final ClassLoader classLoader = classLoaderBuilder.build();
final Class<?> factoryClass = classLoader.loadClass("org.jboss.as.controller.client.ModelControllerClient$Factory");
final Method factory = factoryClass.getMethod("create", String.class, int.class);
try {
final Object client = factory.invoke(null, host, port);
final InvocationHandler invocationHandler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(client, args);
}
};
final Class<?>[] interfaces = new Class<?>[]{ModelControllerClient.class};
return (ModelControllerClient) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t == null) {
throw e;
}
throw t instanceof Exception ? (Exception) t : new RuntimeException(t);
}
}
}
| darranl/wildfly-core | testsuite/shared/src/main/java/org/jboss/as/test/integration/management/api/ClientCompatibilityUnitTestBase.java | Java | lgpl-2.1 | 13,609 |
#include <string.h>
#include "utest_helper.hpp"
static void compiler_fill_image_1d(void)
{
const size_t w = 2048;
cl_image_format format;
cl_image_desc desc;
memset(&desc, 0x0, sizeof(cl_image_desc));
memset(&format, 0x0, sizeof(cl_image_format));
format.image_channel_order = CL_RGBA;
format.image_channel_data_type = CL_UNSIGNED_INT8;
desc.image_type = CL_MEM_OBJECT_IMAGE1D;
desc.image_width = w;
desc.image_row_pitch = 0;
// Setup kernel and images
OCL_CREATE_KERNEL("test_fill_image_1d");
OCL_CREATE_IMAGE(buf[0], 0, &format, &desc, NULL);
OCL_MAP_BUFFER_GTT(0);
for (uint32_t i = 0; i < w; i++) {
((uint32_t*)buf_data[0])[i] = 0;
}
OCL_UNMAP_BUFFER_GTT(0);
// Run the kernel
OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]);
globals[0] = w/2;
locals[0] = 16;
OCL_NDRANGE(1);
// Check result
OCL_MAP_BUFFER_GTT(0);
//printf("------ The image result is: -------\n");
for (uint32_t i = 0; i < w/2; i++) {
//printf(" %2x", ((uint32_t *)buf_data[0])[i]);
OCL_ASSERT(((uint32_t*)buf_data[0])[i] == 0x03020100);
}
for (uint32_t i = w/2; i < w; i++) {
//printf(" %2x", ((uint32_t *)buf_data[0])[i]);
OCL_ASSERT(((uint32_t*)buf_data[0])[i] == 0);
}
OCL_UNMAP_BUFFER_GTT(0);
}
MAKE_UTEST_FROM_FUNCTION(compiler_fill_image_1d);
| wdv4758h/beignet | utests/compiler_fill_image_1d.cpp | C++ | lgpl-2.1 | 1,313 |
#wowslider-container$GallerySuffix$ .ws_thumbs a.ws_selthumb{
background-color: #f5b50c;
}
#wowslider-container$GallerySuffix$ .ws_thumbs a{
-moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
border-radius:5px;
-moz-border-radius:5px;
background-color: #4e463f;
}
| dingdong2310/sir | adm/extend/wowslider/templates/backgnd/dominion/style-thumb.css | CSS | lgpl-2.1 | 326 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!--
This library is part of OpenCms -
the Open Source Content Management System
Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
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.
For further information about Alkacon Software GmbH & Co. KG, please see the
company website: http://www.alkacon.com
For further information about OpenCms, please see the
project website: http://www.opencms.org
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-->
</head>
<body bgcolor="white">
The implementations of the core resource types for the VFS are located here.<p>
<!-- Put @see and @since tags down here. -->
@since 6.0.0
@see org.opencms.file.types.I_CmsResourceType
</body>
</html>
| ggiudetti/opencms-core | src/org/opencms/file/types/package.html | HTML | lgpl-2.1 | 1,395 |
/*****************************************************************************
* dialog.c: User dialog functions
*****************************************************************************
* Copyright © 2009 Rémi Denis-Courmont
* Copyright © 2016 VLC authors and VideoLAN
*
* 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 2.1 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, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
/** @ingroup vlc_dialog */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdarg.h>
#include <vlc_common.h>
#include <vlc_dialog.h>
#include <vlc_interrupt.h>
#include <vlc_extensions.h>
#include <assert.h>
#include "libvlc.h"
struct vlc_dialog_provider
{
vlc_mutex_t lock;
vlc_array_t dialog_array;
vlc_dialog_cbs cbs;
void * p_cbs_data;
vlc_dialog_ext_update_cb pf_ext_update;
void * p_ext_data;
};
enum dialog_type
{
VLC_DIALOG_ERROR,
VLC_DIALOG_LOGIN,
VLC_DIALOG_QUESTION,
VLC_DIALOG_PROGRESS,
};
struct dialog_answer
{
enum dialog_type i_type;
union
{
struct
{
char *psz_username;
char *psz_password;
bool b_store;
} login;
struct
{
int i_action;
} question;
} u;
};
struct dialog
{
enum dialog_type i_type;
const char *psz_title;
const char *psz_text;
union
{
struct
{
const char *psz_default_username;
bool b_ask_store;
} login;
struct
{
vlc_dialog_question_type i_type;
const char *psz_cancel;
const char *psz_action1;
const char *psz_action2;
} question;
struct
{
bool b_indeterminate;
float f_position;
const char *psz_cancel;
} progress;
} u;
};
struct vlc_dialog_id
{
vlc_mutex_t lock;
vlc_cond_t wait;
enum dialog_type i_type;
void * p_context;
int i_refcount;
bool b_cancelled;
bool b_answered;
bool b_progress_indeterminate;
char * psz_progress_text;
struct dialog_answer answer;
};
struct dialog_i11e_context
{
vlc_dialog_provider * p_provider;
vlc_dialog_id * p_id;
};
static inline vlc_dialog_provider *
get_dialog_provider(vlc_object_t *p_obj, bool b_check_interact)
{
if (b_check_interact && p_obj->obj.flags & OBJECT_FLAGS_NOINTERACT)
return NULL;
vlc_dialog_provider *p_provider =
libvlc_priv(p_obj->obj.libvlc)->p_dialog_provider;
assert(p_provider != NULL);
return p_provider;
}
static void
dialog_id_release(vlc_dialog_id *p_id)
{
if (p_id->answer.i_type == VLC_DIALOG_LOGIN)
{
free(p_id->answer.u.login.psz_username);
free(p_id->answer.u.login.psz_password);
}
free(p_id->psz_progress_text);
vlc_mutex_destroy(&p_id->lock);
vlc_cond_destroy(&p_id->wait);
free(p_id);
}
int
libvlc_InternalDialogInit(libvlc_int_t *p_libvlc)
{
assert(p_libvlc != NULL);
vlc_dialog_provider *p_provider = malloc(sizeof(*p_provider));
if (p_provider == NULL)
return VLC_EGENERIC;
vlc_mutex_init(&p_provider->lock);
vlc_array_init(&p_provider->dialog_array);
memset(&p_provider->cbs, 0, sizeof(p_provider->cbs));
p_provider->p_cbs_data = NULL;
p_provider->pf_ext_update = NULL;
p_provider->p_ext_data = NULL;
libvlc_priv(p_libvlc)->p_dialog_provider = p_provider;
return VLC_SUCCESS;
}
static int
dialog_get_idx_locked(vlc_dialog_provider *p_provider, vlc_dialog_id *p_id)
{
for (int i = 0; i < vlc_array_count(&p_provider->dialog_array); ++i)
{
if (p_id == vlc_array_item_at_index(&p_provider->dialog_array, i))
return i;
}
return -1;
}
static void
dialog_cancel_locked(vlc_dialog_provider *p_provider, vlc_dialog_id *p_id)
{
vlc_mutex_lock(&p_id->lock);
if (p_id->b_cancelled || p_id->b_answered)
{
vlc_mutex_unlock(&p_id->lock);
return;
}
p_id->b_cancelled = true;
vlc_mutex_unlock(&p_id->lock);
p_provider->cbs.pf_cancel(p_provider->p_cbs_data, p_id);
}
static vlc_dialog_id *
dialog_add_locked(vlc_dialog_provider *p_provider, enum dialog_type i_type)
{
vlc_dialog_id *p_id = calloc(1, sizeof(*p_id));
if (p_id == NULL)
return NULL;
vlc_mutex_init(&p_id->lock);
vlc_cond_init(&p_id->wait);
p_id->i_type = i_type;
p_id->i_refcount = 2; /* provider and callbacks */
vlc_array_append(&p_provider->dialog_array, p_id);
return p_id;
}
static void
dialog_remove_locked(vlc_dialog_provider *p_provider, vlc_dialog_id *p_id)
{
int i_array_idx = dialog_get_idx_locked(p_provider, p_id);
assert(i_array_idx >= 0);
vlc_array_remove(&p_provider->dialog_array, i_array_idx);
vlc_mutex_lock(&p_id->lock);
p_id->i_refcount--;
if (p_id->i_refcount == 0)
{
vlc_mutex_unlock(&p_id->lock);
dialog_id_release(p_id);
}
else
vlc_mutex_unlock(&p_id->lock);
}
static void
dialog_clear_all_locked(vlc_dialog_provider *p_provider)
{
for (int i = 0; i < vlc_array_count(&p_provider->dialog_array); ++i)
{
vlc_dialog_id *p_id =
vlc_array_item_at_index(&p_provider->dialog_array, i);
dialog_cancel_locked(p_provider, p_id);
}
}
void
libvlc_InternalDialogClean(libvlc_int_t *p_libvlc)
{
assert(p_libvlc != NULL);
vlc_dialog_provider *p_provider = libvlc_priv(p_libvlc)->p_dialog_provider;
if (p_provider == NULL)
return;
vlc_mutex_lock(&p_provider->lock);
dialog_clear_all_locked(p_provider);
vlc_mutex_unlock(&p_provider->lock);
vlc_mutex_destroy(&p_provider->lock);
free(p_provider);
libvlc_priv(p_libvlc)->p_dialog_provider = NULL;
}
#undef vlc_dialog_provider_set_callbacks
void
vlc_dialog_provider_set_callbacks(vlc_object_t *p_obj,
const vlc_dialog_cbs *p_cbs, void *p_data)
{
assert(p_obj != NULL);
vlc_dialog_provider *p_provider = get_dialog_provider(p_obj, false);
vlc_mutex_lock(&p_provider->lock);
dialog_clear_all_locked(p_provider);
if (p_cbs == NULL)
{
memset(&p_provider->cbs, 0, sizeof(p_provider->cbs));
p_provider->p_cbs_data = NULL;
}
else
{
p_provider->cbs = *p_cbs;
p_provider->p_cbs_data = p_data;
}
vlc_mutex_unlock(&p_provider->lock);
}
static void
dialog_wait_interrupted(void *p_data)
{
struct dialog_i11e_context *p_context = p_data;
vlc_dialog_provider *p_provider = p_context->p_provider;
vlc_dialog_id *p_id = p_context->p_id;
vlc_mutex_lock(&p_provider->lock);
dialog_cancel_locked(p_provider, p_id);
vlc_mutex_unlock(&p_provider->lock);
vlc_mutex_lock(&p_id->lock);
vlc_cond_signal(&p_id->wait);
vlc_mutex_unlock(&p_id->lock);
}
static int
dialog_wait(vlc_dialog_provider *p_provider, vlc_dialog_id *p_id,
enum dialog_type i_type, struct dialog_answer *p_answer)
{
struct dialog_i11e_context context = {
.p_provider = p_provider,
.p_id = p_id,
};
vlc_interrupt_register(dialog_wait_interrupted, &context);
vlc_mutex_lock(&p_id->lock);
/* Wait for the dialog to be dismissed, interrupted or answered */
while (!p_id->b_cancelled && !p_id->b_answered)
vlc_cond_wait(&p_id->wait, &p_id->lock);
int i_ret;
if (p_id->b_cancelled)
i_ret = 0;
else if (p_id->answer.i_type != i_type)
i_ret = VLC_EGENERIC;
else
{
i_ret = 1;
memcpy(p_answer, &p_id->answer, sizeof(p_id->answer));
memset(&p_id->answer, 0, sizeof(p_id->answer));
}
vlc_mutex_unlock(&p_id->lock);
vlc_interrupt_unregister();
vlc_mutex_lock(&p_provider->lock);
dialog_remove_locked(p_provider, p_id);
vlc_mutex_unlock(&p_provider->lock);
return i_ret;
}
static int
dialog_display_error_va(vlc_dialog_provider *p_provider, const char *psz_title,
const char *psz_fmt, va_list ap)
{
vlc_mutex_lock(&p_provider->lock);
if (p_provider->cbs.pf_display_error == NULL)
{
vlc_mutex_unlock(&p_provider->lock);
return VLC_EGENERIC;
}
char *psz_text;
if (vasprintf(&psz_text, psz_fmt, ap) == -1)
{
vlc_mutex_unlock(&p_provider->lock);
return VLC_ENOMEM;
}
p_provider->cbs.pf_display_error(p_provider->p_cbs_data, psz_title, psz_text);
free(psz_text);
vlc_mutex_unlock(&p_provider->lock);
return VLC_SUCCESS;
}
int
vlc_dialog_display_error_va(vlc_object_t *p_obj, const char *psz_title,
const char *psz_fmt, va_list ap)
{
assert(p_obj != NULL && psz_title != NULL && psz_fmt != NULL);
int i_ret;
vlc_dialog_provider *p_provider = get_dialog_provider(p_obj, true);
if (p_provider != NULL)
i_ret = dialog_display_error_va(p_provider, psz_title, psz_fmt, ap);
else
i_ret = VLC_EGENERIC;
if (i_ret != VLC_SUCCESS)
{
msg_Err(p_obj, "%s", psz_title);
msg_GenericVa(p_obj, VLC_MSG_ERR, psz_fmt, ap);
}
return i_ret;
}
#undef vlc_dialog_display_error
int
vlc_dialog_display_error(vlc_object_t *p_obj, const char *psz_title,
const char *psz_fmt, ...)
{
assert(psz_fmt != NULL);
va_list ap;
va_start(ap, psz_fmt);
int i_ret = vlc_dialog_display_error_va(p_obj, psz_title, psz_fmt, ap);
va_end(ap);
return i_ret;
}
static int
dialog_display_login_va(vlc_dialog_provider *p_provider, vlc_dialog_id **pp_id,
const char *psz_default_username, bool b_ask_store,
const char *psz_title, const char *psz_fmt, va_list ap)
{
vlc_mutex_lock(&p_provider->lock);
if (p_provider->cbs.pf_display_login == NULL
|| p_provider->cbs.pf_cancel == NULL)
{
vlc_mutex_unlock(&p_provider->lock);
return VLC_EGENERIC;
}
char *psz_text;
if (vasprintf(&psz_text, psz_fmt, ap) == -1)
{
vlc_mutex_unlock(&p_provider->lock);
return VLC_ENOMEM;
}
vlc_dialog_id *p_id = dialog_add_locked(p_provider, VLC_DIALOG_LOGIN);
if (p_id == NULL)
{
free(psz_text);
vlc_mutex_unlock(&p_provider->lock);
return VLC_ENOMEM;
}
p_provider->cbs.pf_display_login(p_provider->p_cbs_data, p_id, psz_title,
psz_text, psz_default_username, b_ask_store);
free(psz_text);
vlc_mutex_unlock(&p_provider->lock);
*pp_id = p_id;
return VLC_SUCCESS;
}
int
vlc_dialog_wait_login_va(vlc_object_t *p_obj, char **ppsz_username,
char **ppsz_password, bool *p_store,
const char *psz_default_username,
const char *psz_title, const char *psz_fmt, va_list ap)
{
assert(p_obj != NULL && ppsz_username != NULL && ppsz_password != NULL
&& psz_fmt != NULL && psz_title != NULL);
vlc_dialog_provider *p_provider = get_dialog_provider(p_obj, true);
if (p_provider == NULL)
return VLC_EGENERIC;
vlc_dialog_id *p_id;
int i_ret = dialog_display_login_va(p_provider, &p_id, psz_default_username,
p_store != NULL, psz_title, psz_fmt, ap);
if (i_ret < 0 || p_id == NULL)
return i_ret;
struct dialog_answer answer;
i_ret = dialog_wait(p_provider, p_id, VLC_DIALOG_LOGIN, &answer);
if (i_ret <= 0)
return i_ret;
*ppsz_username = answer.u.login.psz_username;
*ppsz_password = answer.u.login.psz_password;
if (p_store != NULL)
*p_store = answer.u.login.b_store;
return 1;
}
#undef vlc_dialog_wait_login
int
vlc_dialog_wait_login(vlc_object_t *p_obj, char **ppsz_username,
char **ppsz_password, bool *p_store,
const char *psz_default_username, const char *psz_title,
const char *psz_fmt, ...)
{
assert(psz_fmt != NULL);
va_list ap;
va_start(ap, psz_fmt);
int i_ret = vlc_dialog_wait_login_va(p_obj, ppsz_username, ppsz_password,
p_store,psz_default_username,
psz_title, psz_fmt, ap);
va_end(ap);
return i_ret;
}
static int
dialog_display_question_va(vlc_dialog_provider *p_provider, vlc_dialog_id **pp_id,
vlc_dialog_question_type i_type,
const char *psz_cancel, const char *psz_action1,
const char *psz_action2, const char *psz_title,
const char *psz_fmt, va_list ap)
{
vlc_mutex_lock(&p_provider->lock);
if (p_provider->cbs.pf_display_question == NULL
|| p_provider->cbs.pf_cancel == NULL)
{
vlc_mutex_unlock(&p_provider->lock);
return VLC_EGENERIC;
}
char *psz_text;
if (vasprintf(&psz_text, psz_fmt, ap) == -1)
{
vlc_mutex_unlock(&p_provider->lock);
return VLC_ENOMEM;
}
vlc_dialog_id *p_id = dialog_add_locked(p_provider, VLC_DIALOG_QUESTION);
if (p_id == NULL)
{
free(psz_text);
vlc_mutex_unlock(&p_provider->lock);
return VLC_ENOMEM;
}
p_provider->cbs.pf_display_question(p_provider->p_cbs_data, p_id, psz_title,
psz_text, i_type, psz_cancel, psz_action1,
psz_action2);
free(psz_text);
vlc_mutex_unlock(&p_provider->lock);
*pp_id = p_id;
return VLC_SUCCESS;
}
int
vlc_dialog_wait_question_va(vlc_object_t *p_obj,
vlc_dialog_question_type i_type,
const char *psz_cancel, const char *psz_action1,
const char *psz_action2, const char *psz_title,
const char *psz_fmt, va_list ap)
{
assert(p_obj != NULL && psz_fmt != NULL && psz_title != NULL
&& psz_cancel != NULL);
vlc_dialog_provider *p_provider = get_dialog_provider(p_obj, true);
if (p_provider == NULL)
return VLC_EGENERIC;
vlc_dialog_id *p_id;
int i_ret = dialog_display_question_va(p_provider, &p_id, i_type,
psz_cancel, psz_action1,
psz_action2, psz_title, psz_fmt, ap);
if (i_ret < 0 || p_id == NULL)
return i_ret;
struct dialog_answer answer;
i_ret = dialog_wait(p_provider, p_id, VLC_DIALOG_QUESTION, &answer);
if (i_ret <= 0)
return i_ret;
if (answer.u.question.i_action != 1 && answer.u.question.i_action != 2)
return VLC_EGENERIC;
return answer.u.question.i_action;
}
#undef vlc_dialog_wait_question
int
vlc_dialog_wait_question(vlc_object_t *p_obj,
vlc_dialog_question_type i_type,
const char *psz_cancel, const char *psz_action1,
const char *psz_action2, const char *psz_title,
const char *psz_fmt, ...)
{
assert(psz_fmt != NULL);
va_list ap;
va_start(ap, psz_fmt);
int i_ret = vlc_dialog_wait_question_va(p_obj, i_type, psz_cancel,
psz_action1, psz_action2, psz_title,
psz_fmt, ap);
va_end(ap);
return i_ret;
}
static int
display_progress_va(vlc_dialog_provider *p_provider, vlc_dialog_id **pp_id,
bool b_indeterminate, float f_position,
const char *psz_cancel, const char *psz_title,
const char *psz_fmt, va_list ap)
{
vlc_mutex_lock(&p_provider->lock);
if (p_provider->cbs.pf_display_progress == NULL
|| p_provider->cbs.pf_update_progress == NULL
|| p_provider->cbs.pf_cancel == NULL)
{
vlc_mutex_unlock(&p_provider->lock);
return VLC_EGENERIC;
}
char *psz_text;
if (vasprintf(&psz_text, psz_fmt, ap) == -1)
{
vlc_mutex_unlock(&p_provider->lock);
return VLC_ENOMEM;
}
vlc_dialog_id *p_id = dialog_add_locked(p_provider, VLC_DIALOG_PROGRESS);
if (p_id == NULL)
{
free(psz_text);
vlc_mutex_unlock(&p_provider->lock);
return VLC_ENOMEM;
}
p_id->b_progress_indeterminate = b_indeterminate;
p_id->psz_progress_text = psz_text;
p_provider->cbs.pf_display_progress(p_provider->p_cbs_data, p_id, psz_title,
psz_text, b_indeterminate, f_position,
psz_cancel);
vlc_mutex_unlock(&p_provider->lock);
*pp_id = p_id;
return VLC_SUCCESS;
}
vlc_dialog_id *
vlc_dialog_display_progress_va(vlc_object_t *p_obj, bool b_indeterminate,
float f_position, const char *psz_cancel,
const char *psz_title, const char *psz_fmt,
va_list ap)
{
assert(p_obj != NULL && psz_title != NULL && psz_fmt != NULL);
vlc_dialog_provider *p_provider = get_dialog_provider(p_obj, true);
if (p_provider == NULL)
return NULL;
vlc_dialog_id *p_id;
int i_ret = display_progress_va(p_provider, &p_id, b_indeterminate,
f_position, psz_cancel, psz_title, psz_fmt,
ap);
return i_ret == VLC_SUCCESS ? p_id : NULL;
}
#undef vlc_dialog_display_progress
vlc_dialog_id *
vlc_dialog_display_progress(vlc_object_t *p_obj, bool b_indeterminate,
float f_position, const char *psz_cancel,
const char *psz_title, const char *psz_fmt, ...)
{
assert(psz_fmt != NULL);
va_list ap;
va_start(ap, psz_fmt);
vlc_dialog_id *p_id =
vlc_dialog_display_progress_va(p_obj, b_indeterminate, f_position,
psz_cancel, psz_title, psz_fmt, ap);
va_end(ap);
return p_id;
}
static int
dialog_update_progress(vlc_object_t *p_obj, vlc_dialog_id *p_id, float f_value,
char *psz_text)
{
assert(p_obj != NULL && p_id != NULL);
vlc_dialog_provider *p_provider = get_dialog_provider(p_obj, false);
vlc_mutex_lock(&p_provider->lock);
if (p_provider->cbs.pf_update_progress == NULL ||
vlc_dialog_is_cancelled(p_obj, p_id))
{
vlc_mutex_unlock(&p_provider->lock);
free(psz_text);
return VLC_EGENERIC;
}
if (p_id->b_progress_indeterminate)
{
vlc_mutex_unlock(&p_provider->lock);
free(psz_text);
return VLC_EGENERIC;
}
if (psz_text != NULL)
{
free(p_id->psz_progress_text);
p_id->psz_progress_text = psz_text;
}
p_provider->cbs.pf_update_progress(p_provider->p_cbs_data, p_id, f_value,
p_id->psz_progress_text);
vlc_mutex_unlock(&p_provider->lock);
return VLC_SUCCESS;
}
#undef vlc_dialog_update_progress
int
vlc_dialog_update_progress(vlc_object_t *p_obj, vlc_dialog_id *p_id,
float f_value)
{
return dialog_update_progress(p_obj, p_id, f_value, NULL);
}
int
vlc_dialog_update_progress_text_va(vlc_object_t *p_obj, vlc_dialog_id *p_id,
float f_value, const char *psz_fmt,
va_list ap)
{
assert(psz_fmt != NULL);
char *psz_text;
if (vasprintf(&psz_text, psz_fmt, ap) == -1)
return VLC_ENOMEM;
return dialog_update_progress(p_obj, p_id, f_value, psz_text);
}
#undef vlc_dialog_update_progress_text
int
vlc_dialog_update_progress_text(vlc_object_t *p_obj, vlc_dialog_id *p_id,
float f_value, const char *psz_fmt, ...)
{
assert(psz_fmt != NULL);
va_list ap;
va_start(ap, psz_fmt);
int i_ret = vlc_dialog_update_progress_text_va(p_obj, p_id, f_value,
psz_fmt, ap);
va_end(ap);
return i_ret;
}
#undef vlc_dialog_release
void
vlc_dialog_release(vlc_object_t *p_obj, vlc_dialog_id *p_id)
{
assert(p_obj != NULL && p_id != NULL);
vlc_dialog_provider *p_provider = get_dialog_provider(p_obj, false);
vlc_mutex_lock(&p_provider->lock);
dialog_cancel_locked(p_provider, p_id);
dialog_remove_locked(p_provider, p_id);
vlc_mutex_unlock(&p_provider->lock);
}
#undef vlc_dialog_is_cancelled
bool
vlc_dialog_is_cancelled(vlc_object_t *p_obj, vlc_dialog_id *p_id)
{
(void) p_obj;
assert(p_id != NULL);
vlc_mutex_lock(&p_id->lock);
bool b_cancelled = p_id->b_cancelled;
vlc_mutex_unlock(&p_id->lock);
return b_cancelled;
}
void
vlc_dialog_id_set_context(vlc_dialog_id *p_id, void *p_context)
{
vlc_mutex_lock(&p_id->lock);
p_id->p_context = p_context;
vlc_mutex_unlock(&p_id->lock);
}
void *
vlc_dialog_id_get_context(vlc_dialog_id *p_id)
{
assert(p_id != NULL);
vlc_mutex_lock(&p_id->lock);
void *p_context = p_id->p_context;
vlc_mutex_unlock(&p_id->lock);
return p_context;
}
static int
dialog_id_post(vlc_dialog_id *p_id, struct dialog_answer *p_answer)
{
vlc_mutex_lock(&p_id->lock);
if (p_answer == NULL)
{
p_id->b_cancelled = true;
}
else
{
p_id->answer = *p_answer;
p_id->b_answered = true;
}
p_id->i_refcount--;
if (p_id->i_refcount > 0)
{
vlc_cond_signal(&p_id->wait);
vlc_mutex_unlock(&p_id->lock);
}
else
{
vlc_mutex_unlock(&p_id->lock);
dialog_id_release(p_id);
}
return VLC_SUCCESS;
}
int
vlc_dialog_id_post_login(vlc_dialog_id *p_id, const char *psz_username,
const char *psz_password, bool b_store)
{
assert(p_id != NULL && psz_username != NULL && psz_password != NULL);
struct dialog_answer answer = {
.i_type = VLC_DIALOG_LOGIN,
.u.login = {
.b_store = b_store,
.psz_username = strdup(psz_username),
.psz_password = strdup(psz_password),
},
};
if (answer.u.login.psz_username == NULL
|| answer.u.login.psz_password == NULL)
{
free(answer.u.login.psz_username);
free(answer.u.login.psz_password);
dialog_id_post(p_id, NULL);
return VLC_ENOMEM;
}
return dialog_id_post(p_id, &answer);
}
int
vlc_dialog_id_post_action(vlc_dialog_id *p_id, int i_action)
{
assert(p_id != NULL);
struct dialog_answer answer = {
.i_type = VLC_DIALOG_QUESTION,
.u.question = { .i_action = i_action },
};
return dialog_id_post(p_id, &answer);
}
int
vlc_dialog_id_dismiss(vlc_dialog_id *p_id)
{
return dialog_id_post(p_id, NULL);
}
#undef vlc_dialog_provider_set_ext_callback
void
vlc_dialog_provider_set_ext_callback(vlc_object_t *p_obj,
vlc_dialog_ext_update_cb pf_update,
void *p_data)
{
assert(p_obj != NULL);
vlc_dialog_provider *p_provider = get_dialog_provider(p_obj, false);
vlc_mutex_lock(&p_provider->lock);
p_provider->pf_ext_update = pf_update;
p_provider->p_ext_data = p_data;
vlc_mutex_unlock(&p_provider->lock);
}
#undef vlc_ext_dialog_update
int
vlc_ext_dialog_update(vlc_object_t *p_obj, extension_dialog_t *p_ext_dialog)
{
assert(p_obj != NULL);
vlc_dialog_provider *p_provider = get_dialog_provider(p_obj, false);
vlc_mutex_lock(&p_provider->lock);
if (p_provider->pf_ext_update == NULL)
{
vlc_mutex_unlock(&p_provider->lock);
return VLC_EGENERIC;
}
p_provider->pf_ext_update(p_ext_dialog, p_provider->p_ext_data);
vlc_mutex_unlock(&p_provider->lock);
return VLC_SUCCESS;
}
| xkfz007/vlc | src/interface/dialog.c | C | lgpl-2.1 | 24,677 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<!--
// =========================================================================
//
// sampleApplications-sax.html - The SAX sample applications included with XML for <SCRIPT>
//
// =========================================================================
//
// Copyright (C) 2001, 2002, 2003 - David Joham (djoham@yahoo.com)
//
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-->
<head>
<title>
XML for <SCRIPT> Cross Platform XML Parsing in JavaScript - SAX Sample Applications
</title>
<meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="./stylesheets/styles.css">
</head>
<body onload="configureJSNavigation()">
<form name="frmForm" id="frmForm" method="get" action="noaction">
<!-- logo -->
<div id="logo" class="titleLogo">
<img src="./images/titleImage.jpg" width="459" height="75" alt="XML for <SCRIPT> logo">
</div>
<!-- main page square -->
<div class="mainContentArea">
<br>
</div>
<!-- navigation bar -->
<div class="leftImage"></div>
<!-- credit where credit is due -->
<p>
<a href="http://validator.w3.org/check/referer"><img src="./images/valid-html401.png" class="validHTMLImage" alt="HTML 4.01 strict HTML" /></a><br />
<a href="http://www.sourceforge.net"><img src="http://sourceforge.net/sflogo.php?group_id=14016&type=1" class="sourceForgeImage" alt="Visit Sourceforge.net" title="Visit Sourceforge.net"/></a><br>
</p>
<p>
<div class="linkBar">
<div class="hoverNavigation"><a class="navigation" href="./../index.html">Home</a></div>
<div class="hoverNavigation"><a class="navigation" href="./documentation.html">Documentation</a></div>
<div class="hoverNavigation"><a class="navigation" href="./caseStudies.html">Case Studies</a></div>
<div class="currentLocation">Sample Code (Parsers)</div>
<div class="hoverNavigationIndent"><a class="navigation" href="./sampleApplications.html">Overview</a></div>
<div class="hoverNavigationIndent"><a class="navigation" href="./sampleApplications-w3cdom.html">W3C DOM</a></div>
<div class="hoverNavigationIndent"><a class="navigation" href="./sampleApplications-classicdom.html">Classic DOM</a></div>
<div class="lastHoverNavigationCurrentLocationIndent">SAX</div>
<div class="hoverNavigation"><a class="navigation" href="./tools.html">Sample Code (Tools)</a></div>
<div class="hoverNavigation"><a class="navigation" href="./contributedAddOns.html">Contributed Add-ons</a></div>
<div class="hoverNavigation"><a class="navigation" href="./testSuites.html">Test Suites</a></div>
<div class="hoverNavigation"><a class="navigation" href="./history.html">History</a></div>
<div class="hoverNavigation"><a class="navigation" href="./mailingLists.html">Mailing Lists</a></div>
<div class="hoverNavigation"><a class="navigation" href="./download.html">Download</a></div>
</div>
<div class="contentDiv">
<div class="contentDivBackground">
<div class="pageHeader">
Parser Sample Code - SAX
</div>
<div>
<div class="accent" style="margin-top: 10px">
SAX Sample Application 1
</div>
<p>
This sample application demonstrates how to use the SAX parser to build your own object capable of returning information
about the XML data passed in.
</p>
<p>
NOTE: If you are using Konqueror, this sample application requires version 3.0 or higher.
</p>
<p>
NOTE: If you are using Opera, this sample application requires version 7.0 or higher.
</p>
<div style="text-align: right">
<input type="button" class="launchButton" onclick="launchSAXSample1()" value="Launch">
</div>
<br>
<div class="accent">
SAX Tree View Sample
</div>
<p>
This sample application builds on the sample above to demonstrate how an DHTML tree view can be constructed from XML using
the SAX Parser.
</p>
<p>
NOTE: If you are using Konqueror, this sample application requires version 3.0 or higher.
</p>
<p>
NOTE: If you are using Opera, this sample application requires version 7.0 or higher.
</p>
<div style="text-align: right">
<input type="button" class="launchButton" onclick="launchSAXTreeViewSample()" value="Launch">
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript" src="./scripts/scripts.js"></script>
</body>
</html>
| inswave/xmljs | website/sampleApplications-sax.html | HTML | lgpl-2.1 | 6,138 |
/* ----------------------------------------------------------------------
* Project: CMSIS DSP Library
* Title: arm_scale_f16.c
* Description: Multiplies a floating-point vector by a scalar
*
* $Date: 23 April 2021
* $Revision: V1.9.0
*
* Target Processor: Cortex-M and Cortex-A cores
* -------------------------------------------------------------------- */
/*
* Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the License); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dsp/basic_math_functions_f16.h"
/**
@ingroup groupMath
*/
/**
@defgroup BasicScale Vector Scale
Multiply a vector by a scalar value. For floating-point data, the algorithm used is:
<pre>
pDst[n] = pSrc[n] * scale, 0 <= n < blockSize.
</pre>
In the fixed-point Q7, Q15, and Q31 functions, <code>scale</code> is represented by
a fractional multiplication <code>scaleFract</code> and an arithmetic shift <code>shift</code>.
The shift allows the gain of the scaling operation to exceed 1.0.
The algorithm used with fixed-point data is:
<pre>
pDst[n] = (pSrc[n] * scaleFract) << shift, 0 <= n < blockSize.
</pre>
The overall scale factor applied to the fixed-point data is
<pre>
scale = scaleFract * 2^shift.
</pre>
The functions support in-place computation allowing the source and destination
pointers to reference the same memory buffer.
*/
/**
@addtogroup BasicScale
@{
*/
/**
@brief Multiplies a floating-point vector by a scalar.
@param[in] pSrc points to the input vector
@param[in] scale scale factor to be applied
@param[out] pDst points to the output vector
@param[in] blockSize number of samples in each vector
@return none
*/
#if defined(ARM_MATH_MVE_FLOAT16) && !defined(ARM_MATH_AUTOVECTORIZE)
#include "arm_helium_utils.h"
void arm_scale_f16(
const float16_t * pSrc,
float16_t scale,
float16_t * pDst,
uint32_t blockSize)
{
uint32_t blkCnt; /* Loop counter */
f16x8_t vec1;
f16x8_t res;
/* Compute 4 outputs at a time */
blkCnt = blockSize >> 3U;
while (blkCnt > 0U)
{
/* C = A + offset */
/* Add offset and then store the results in the destination buffer. */
vec1 = vld1q(pSrc);
res = vmulq(vec1,scale);
vst1q(pDst, res);
/* Increment pointers */
pSrc += 8;
pDst += 8;
/* Decrement the loop counter */
blkCnt--;
}
/* Tail */
blkCnt = blockSize & 0x7;
if (blkCnt > 0U)
{
mve_pred16_t p0 = vctp16q(blkCnt);
vec1 = vld1q((float16_t const *) pSrc);
vstrhq_p(pDst, vmulq(vec1, scale), p0);
}
}
#else
#if defined(ARM_FLOAT16_SUPPORTED)
void arm_scale_f16(
const float16_t *pSrc,
float16_t scale,
float16_t *pDst,
uint32_t blockSize)
{
uint32_t blkCnt; /* Loop counter */
#if defined (ARM_MATH_LOOPUNROLL)
/* Loop unrolling: Compute 4 outputs at a time */
blkCnt = blockSize >> 2U;
while (blkCnt > 0U)
{
/* C = A * scale */
/* Scale input and store result in destination buffer. */
*pDst++ = (*pSrc++) * scale;
*pDst++ = (*pSrc++) * scale;
*pDst++ = (*pSrc++) * scale;
*pDst++ = (*pSrc++) * scale;
/* Decrement loop counter */
blkCnt--;
}
/* Loop unrolling: Compute remaining outputs */
blkCnt = blockSize % 0x4U;
#else
/* Initialize blkCnt with number of samples */
blkCnt = blockSize;
#endif /* #if defined (ARM_MATH_LOOPUNROLL) */
while (blkCnt > 0U)
{
/* C = A * scale */
/* Scale input and store result in destination buffer. */
*pDst++ = (*pSrc++) * scale;
/* Decrement loop counter */
blkCnt--;
}
}
#endif
#endif /* defined(ARM_MATH_MVEF) && !defined(ARM_MATH_AUTOVECTORIZE) */
/**
@} end of BasicScale group
*/
| prefetchnta/crhack | src/naked/cmsis/DSP/Source/BasicMathFunctions/arm_scale_f16.c | C | lgpl-2.1 | 4,523 |
FROM base/archlinux
MAINTAINER Omar Padron <omar.padron@kitware.com>
ENV SPACK_ROOT=/spack \
FORCE_UNSAFE_CONFIGURE=1 \
DISTRO=arch
RUN pacman -Sy --noconfirm \
base-devel \
ca-certificates \
curl \
gcc \
gcc-fortran \
git \
gnupg2 \
iproute2 \
make \
openssh \
python \
sudo \
tcl && \
git clone --depth 1 git://github.com/spack/spack.git /spack && \
echo 'nobody ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/nobody-sudo && \
sudo -u nobody git clone --depth 1 \
https://aur.archlinux.org/lua-posix.git /tmp/lua-posix && \
sudo -u nobody git clone --depth 1 \
https://aur.archlinux.org/lmod.git /tmp/lmod && \
( cd /tmp/lua-posix ; sudo -u nobody makepkg -si --asdeps --noconfirm ) && \
( cd /tmp/lmod ; sudo -u nobody makepkg -si --noconfirm ) && \
rm -rf /tmp/lua-posix /tmp/lmod /spack/.git /etc/sudoers.d/nobody-sudo
RUN ( cd /usr/share/lmod ; ln -s $( ls -d ./* | head -n 1 ) ./lmod )
RUN echo "source /usr/share/lmod/lmod/init/bash" \
> /etc/profile.d/spack.sh
RUN echo "source /spack/share/spack/setup-env.sh" \
>> /etc/profile.d/spack.sh
RUN echo "source /spack/share/spack/spack-completion.bash" \
>> /etc/profile.d/spack.sh
COPY common/handle-ssh.sh /etc/profile.d/handle-ssh.sh
COPY common/handle-prompt.sh /etc/profile.d/handle-prompt.sh.source
RUN ( \
echo "export DISTRO=$DISTRO" ; \
echo "if [ x\$PROMPT '!=' 'x' -a x\$PROMPT '!=' 'x0' ]" ; \
echo "then" ; \
echo "source /etc/profile.d/handle-prompt.sh.source" ; \
echo "fi" ; \
) > /etc/profile.d/handle-prompt.sh
RUN mkdir -p /root/.spack
COPY common/modules.yaml /root/.spack/modules.yaml
RUN rm -rf /root/*.*
WORKDIR /root
ENTRYPOINT ["bash"]
CMD ["-l"]
| mfherbst/spack | share/spack/docker/build/arch.dockerfile | Dockerfile | lgpl-2.1 | 2,310 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="ru">
<context>
<name>AnimationSaveWidget</name>
<message>
<location filename="../tools/qvfb/qvfb.cpp" line="+850"/>
<location line="+204"/>
<source>Record</source>
<translation>Записать</translation>
</message>
<message>
<location line="-202"/>
<source>Reset</source>
<translation>Сбросить</translation>
</message>
<message>
<location line="+2"/>
<source>Save</source>
<translation>Сохранить</translation>
</message>
<message>
<location line="+18"/>
<source>Save in MPEG format (requires netpbm package installed)</source>
<translation>Сохранить в формат MPEG (требуется установленный пакет netpbm)</translation>
</message>
<message>
<location line="+8"/>
<location line="+206"/>
<source>Click record to begin recording.</source>
<translation>Нажмите "Записать" для начала записи.</translation>
</message>
<message>
<location line="-115"/>
<location line="+147"/>
<source>Finished saving.</source>
<translation>Сохранение завершено.</translation>
</message>
<message>
<location line="-63"/>
<source>Paused. Click record to resume, or save if done.</source>
<translation>Приостановлено. Нажмите "Записать" для продолжения или "Сохранить", если готово.</translation>
</message>
<message>
<location line="+6"/>
<source>Pause</source>
<translation>Пауза</translation>
</message>
<message>
<location line="+1"/>
<source>Recording...</source>
<translation>Идёт запись...</translation>
</message>
<message>
<location line="+40"/>
<source>Saving... </source>
<translation>Сохранение... </translation>
</message>
<message>
<location line="+4"/>
<location line="+4"/>
<source>Save animation...</source>
<translation>Сохранение анимации...</translation>
</message>
<message>
<location line="+2"/>
<source>Save canceled.</source>
<translation>Сохранение отменено.</translation>
</message>
<message>
<location line="+9"/>
<source>Save failed!</source>
<translation>Сохранение не удалось!</translation>
</message>
</context>
<context>
<name>Config</name>
<message>
<location filename="../tools/qvfb/config.ui" line="+53"/>
<source>Configure</source>
<translation>Настройка</translation>
</message>
<message>
<location line="+47"/>
<source>Size</source>
<translation>Размер</translation>
</message>
<message>
<location line="+21"/>
<source>176x220 "SmartPhone"</source>
<translation>176x220 "SmartPhone"</translation>
</message>
<message>
<location line="+7"/>
<source>240x320 "PDA"</source>
<translation>240x320 "PDA"</translation>
</message>
<message>
<location line="+7"/>
<source>320x240 "TV" / "QVGA"</source>
<translation>320x240 "TV" / "QVGA"</translation>
</message>
<message>
<location line="+7"/>
<source>640x480 "VGA"</source>
<translation>640x480 "VGA"</translation>
</message>
<message>
<location line="+7"/>
<source>800x600</source>
<translation>800x600</translation>
</message>
<message>
<location line="+7"/>
<source>1024x768</source>
<translation>1024x768</translation>
</message>
<message>
<location line="+30"/>
<source>Custom</source>
<translation>Особый</translation>
</message>
<message>
<location line="+44"/>
<source>Depth</source>
<translation>Глубина</translation>
</message>
<message>
<location line="+21"/>
<source>1 bit monochrome</source>
<translation>1 бит (монохромный)</translation>
</message>
<message>
<location line="+7"/>
<source>4 bit grayscale</source>
<translation>4 бита (градации серого)</translation>
</message>
<message>
<location line="+7"/>
<source>8 bit</source>
<translation>8 бит</translation>
</message>
<message>
<location line="+7"/>
<source>12 (16) bit</source>
<translation>12 (16) бит</translation>
</message>
<message>
<location line="+7"/>
<source>15 bit</source>
<translation>15 бит</translation>
</message>
<message>
<location line="+7"/>
<source>16 bit</source>
<translation>16 бит</translation>
</message>
<message>
<location line="+7"/>
<source>18 bit</source>
<translation>18 бит</translation>
</message>
<message>
<location line="+7"/>
<source>24 bit</source>
<translation>24 бита</translation>
</message>
<message>
<location line="+7"/>
<source>32 bit</source>
<translation>32 бита</translation>
</message>
<message>
<location line="+7"/>
<source>32 bit ARGB</source>
<translation>32 бита (ARGB)</translation>
</message>
<message>
<location line="+29"/>
<source>Skin</source>
<translation>Обложка</translation>
</message>
<message>
<location line="+14"/>
<source>None</source>
<translation>Нет</translation>
</message>
<message>
<location line="+10"/>
<source>Emulate touch screen (no mouse move)</source>
<translatorcomment>указателя?</translatorcomment>
<translation>Эмулировать тачскрин (без перемещения мыши)</translation>
</message>
<message>
<location line="+7"/>
<source>Emulate LCD screen (Only with fixed zoom of 3.0 times magnification)</source>
<translation>Эмулировать ж/к экран (только с 3-х кратным увеличением)</translation>
</message>
<message>
<location line="+26"/>
<source><p>Note that any applications using the virtual framebuffer will be terminated if you change the Size or Depth <i>above</i>. You may freely modify the Gamma <i>below</i>.</source>
<translation><p>Имейте в виду, что программы, использующие фрэймбуфер, будут завершены, если изменится <i>размер</i> и/или <i>глубина</i> экрана.</translation>
</message>
<message>
<location line="+10"/>
<source>Gamma</source>
<translation>Гамма</translation>
</message>
<message>
<location line="+24"/>
<source>Blue</source>
<translation>Синий</translation>
</message>
<message>
<location line="+489"/>
<location line="+496"/>
<location line="+14"/>
<location line="+496"/>
<source>1.0</source>
<translation>1.0</translation>
</message>
<message>
<location line="-999"/>
<source>Green</source>
<translation>Зеленый</translation>
</message>
<message>
<location line="+496"/>
<source>All</source>
<translation>Все</translation>
</message>
<message>
<location line="+496"/>
<source>Red</source>
<translation>Красный</translation>
</message>
<message>
<location line="+496"/>
<source>Set all to 1.0</source>
<translation>Выставить все в 1.0</translation>
</message>
<message>
<location line="+43"/>
<source>&OK</source>
<translation>&ОК</translation>
</message>
<message>
<location line="+13"/>
<source>&Cancel</source>
<translation>От&мена</translation>
</message>
</context>
<context>
<name>DeviceSkin</name>
<message>
<location filename="../tools/shared/deviceskin/deviceskin.cpp" line="+79"/>
<source>The image file '%1' could not be loaded.</source>
<translation>Не удалось загрузить изображение '%1'.</translation>
</message>
<message>
<location line="+64"/>
<source>The skin directory '%1' does not contain a configuration file.</source>
<translation>Каталог обложки '%1' не содержит файла настроек.</translation>
</message>
<message>
<location line="+5"/>
<source>The skin configuration file '%1' could not be opened.</source>
<translation>Не удалось открыть файл настроек обложки '%1'.</translation>
</message>
<message>
<location line="+6"/>
<source>The skin configuration file '%1' could not be read: %2</source>
<translation>Не удалось прочитать файл настроек обложки '%1': %2</translation>
</message>
<message>
<location line="+70"/>
<source>Syntax error: %1</source>
<translation>Синтаксическая ошибка: %1</translation>
</message>
<message>
<location line="+21"/>
<source>The skin "up" image file '%1' does not exist.</source>
<translation>Файл изображения "up" '%1' не существует.</translation>
</message>
<message>
<location line="+10"/>
<source>The skin "down" image file '%1' does not exist.</source>
<translation>Файл изображения "down" '%1' не существует.</translation>
</message>
<message>
<location line="+11"/>
<source>The skin "closed" image file '%1' does not exist.</source>
<translation>Файл изображения "closed" '%1' не существует.</translation>
</message>
<message>
<location line="+12"/>
<source>The skin cursor image file '%1' does not exist.</source>
<translation>Файл изображения курсора '%1' не существует.</translation>
</message>
<message>
<location line="+25"/>
<source>Syntax error in area definition: %1</source>
<translation>Синтаксическая ошибка в определении области: %1</translation>
</message>
<message>
<location line="+38"/>
<source>Mismatch in number of areas, expected %1, got %2.</source>
<translation>Несовпадение количества зон: ожидается %1, указано %2.</translation>
</message>
</context>
<context>
<name>QVFb</name>
<message>
<location filename="../tools/qvfb/qvfb.cpp" line="-487"/>
<source>Browse...</source>
<translation>Обзор...</translation>
</message>
<message>
<location line="+126"/>
<source>Load Custom Skin...</source>
<translation>Загрузить обложку пользователя...</translation>
</message>
<message>
<location line="+1"/>
<source>All QVFB Skins (*.skin)</source>
<translation>Все обложки QVFB (*.skin)</translation>
</message>
</context>
</TS>
| RLovelett/qt | translations/qvfb_ru.ts | TypeScript | lgpl-2.1 | 12,255 |
/*
* gnome-keyring
*
* Copyright (C) 2008 Stefan Walter
*
* 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 2.1 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/>.
*/
#ifndef EGG_PADDING_H_
#define EGG_PADDING_H_
#include <glib.h>
#ifndef HAVE_EGG_ALLOCATOR
typedef void* (*EggAllocator) (void* p, gsize);
#define HAVE_EGG_ALLOCATOR
#endif
typedef gboolean (*EggPadding) (EggAllocator alloc,
gsize n_block,
gconstpointer input,
gsize n_input,
gpointer *output,
gsize *n_output);
gboolean egg_padding_zero_pad (EggAllocator alloc,
gsize n_block,
gconstpointer raw,
gsize n_raw,
gpointer *padded,
gsize *n_padded);
gboolean egg_padding_pkcs1_pad_01 (EggAllocator alloc,
gsize n_block,
gconstpointer raw,
gsize n_raw,
gpointer *padded,
gsize *n_padded);
gboolean egg_padding_pkcs1_pad_02 (EggAllocator alloc,
gsize n_block,
gconstpointer raw,
gsize n_raw,
gpointer *padded,
gsize *n_padded);
gboolean egg_padding_pkcs1_unpad_01 (EggAllocator alloc,
gsize n_block,
gconstpointer padded,
gsize n_padded,
gpointer *raw,
gsize *n_raw);
gboolean egg_padding_pkcs1_unpad_02 (EggAllocator alloc,
gsize n_block,
gconstpointer padded,
gsize n_padded,
gpointer *raw,
gsize *n_raw);
gboolean egg_padding_pkcs7_pad (EggAllocator alloc,
gsize n_block,
gconstpointer raw,
gsize n_raw,
gpointer *padded,
gsize *n_padded);
gboolean egg_padding_pkcs7_unpad (EggAllocator alloc,
gsize n_block,
gconstpointer raw,
gsize n_raw,
gpointer *padded,
gsize *n_padded);
#endif /* EGG_PADDING_H_ */
| Distrotech/gcr | egg/egg-padding.h | C | lgpl-2.1 | 5,231 |
/*
* Pooling Allocator
* (C) 1999-2008 Jack Lloyd
* 2005 Matthew Gregan
* 2005-2006 Matt Johnston
*
* Distributed under the terms of the Botan license
*/
#include <botan/mem_pool.h>
#include <botan/util.h>
#include <botan/mem_ops.h>
#include <algorithm>
#include <exception>
namespace Botan {
namespace {
/*
* Memory Allocation Exception
*/
struct Memory_Exhaustion : public std::bad_alloc
{
const char* what() const throw()
{ return "Ran out of memory, allocation failed"; }
};
}
/*
* Memory_Block Constructor
*/
Pooling_Allocator::Memory_Block::Memory_Block(void* buf)
{
buffer = static_cast<byte*>(buf);
bitmap = 0;
buffer_end = buffer + (BLOCK_SIZE * BITMAP_SIZE);
}
/*
* See if ptr is contained by this block
*/
bool Pooling_Allocator::Memory_Block::contains(void* ptr,
u32bit length) const throw()
{
return ((buffer <= ptr) &&
(buffer_end >= static_cast<byte*>(ptr) + length * BLOCK_SIZE));
}
/*
* Allocate some memory, if possible
*/
byte* Pooling_Allocator::Memory_Block::alloc(u32bit n) throw()
{
if(n == 0 || n > BITMAP_SIZE)
return 0;
if(n == BITMAP_SIZE)
{
if(bitmap)
return 0;
else
{
bitmap = ~bitmap;
return buffer;
}
}
bitmap_type mask = (static_cast<bitmap_type>(1) << n) - 1;
u32bit offset = 0;
while(bitmap & mask)
{
mask <<= 1;
++offset;
if((bitmap & mask) == 0)
break;
if(mask >> 63)
break;
}
if(bitmap & mask)
return 0;
bitmap |= mask;
return buffer + offset * BLOCK_SIZE;
}
/*
* Mark this memory as free, if we own it
*/
void Pooling_Allocator::Memory_Block::free(void* ptr, u32bit blocks) throw()
{
clear_mem(static_cast<byte*>(ptr), blocks * BLOCK_SIZE);
const u32bit offset = (static_cast<byte*>(ptr) - buffer) / BLOCK_SIZE;
if(offset == 0 && blocks == BITMAP_SIZE)
bitmap = ~bitmap;
else
{
for(u32bit j = 0; j != blocks; ++j)
bitmap &= ~(static_cast<bitmap_type>(1) << (j+offset));
}
}
/*
* Pooling_Allocator Constructor
*/
Pooling_Allocator::Pooling_Allocator(Mutex* m) : mutex(m)
{
last_used = blocks.begin();
}
/*
* Pooling_Allocator Destructor
*/
Pooling_Allocator::~Pooling_Allocator()
{
delete mutex;
if(blocks.size())
throw Invalid_State("Pooling_Allocator: Never released memory");
}
/*
* Free all remaining memory
*/
void Pooling_Allocator::destroy()
{
Mutex_Holder lock(mutex);
blocks.clear();
for(u32bit j = 0; j != allocated.size(); ++j)
dealloc_block(allocated[j].first, allocated[j].second);
allocated.clear();
}
/*
* Allocation
*/
void* Pooling_Allocator::allocate(u32bit n)
{
const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
const u32bit BLOCK_SIZE = Memory_Block::block_size();
Mutex_Holder lock(mutex);
if(n <= BITMAP_SIZE * BLOCK_SIZE)
{
const u32bit block_no = round_up(n, BLOCK_SIZE) / BLOCK_SIZE;
byte* mem = allocate_blocks(block_no);
if(mem)
return mem;
get_more_core(BOTAN_MEM_POOL_CHUNK_SIZE);
mem = allocate_blocks(block_no);
if(mem)
return mem;
throw Memory_Exhaustion();
}
void* new_buf = alloc_block(n);
if(new_buf)
return new_buf;
throw Memory_Exhaustion();
}
/*
* Deallocation
*/
void Pooling_Allocator::deallocate(void* ptr, u32bit n)
{
const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
const u32bit BLOCK_SIZE = Memory_Block::block_size();
if(ptr == 0 && n == 0)
return;
Mutex_Holder lock(mutex);
if(n > BITMAP_SIZE * BLOCK_SIZE)
dealloc_block(ptr, n);
else
{
const u32bit block_no = round_up(n, BLOCK_SIZE) / BLOCK_SIZE;
std::vector<Memory_Block>::iterator i =
std::lower_bound(blocks.begin(), blocks.end(), Memory_Block(ptr));
if(i == blocks.end() || !i->contains(ptr, block_no))
throw Invalid_State("Pointer released to the wrong allocator");
i->free(ptr, block_no);
}
}
/*
* Try to get some memory from an existing block
*/
byte* Pooling_Allocator::allocate_blocks(u32bit n)
{
if(blocks.empty())
return 0;
std::vector<Memory_Block>::iterator i = last_used;
do
{
byte* mem = i->alloc(n);
if(mem)
{
last_used = i;
return mem;
}
++i;
if(i == blocks.end())
i = blocks.begin();
}
while(i != last_used);
return 0;
}
/*
* Allocate more memory for the pool
*/
void Pooling_Allocator::get_more_core(u32bit in_bytes)
{
const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
const u32bit BLOCK_SIZE = Memory_Block::block_size();
const u32bit TOTAL_BLOCK_SIZE = BLOCK_SIZE * BITMAP_SIZE;
// upper bound on allocation is 1 MiB
in_bytes = std::min<u32bit>(in_bytes, 1024 * 1024);
const u32bit in_blocks = round_up(in_bytes, BLOCK_SIZE) / TOTAL_BLOCK_SIZE;
const u32bit to_allocate = in_blocks * TOTAL_BLOCK_SIZE;
void* ptr = alloc_block(to_allocate);
if(ptr == 0)
throw Memory_Exhaustion();
allocated.push_back(std::make_pair(ptr, to_allocate));
for(u32bit j = 0; j != in_blocks; ++j)
{
byte* byte_ptr = static_cast<byte*>(ptr);
blocks.push_back(Memory_Block(byte_ptr + j * TOTAL_BLOCK_SIZE));
}
std::sort(blocks.begin(), blocks.end());
last_used = std::lower_bound(blocks.begin(), blocks.end(),
Memory_Block(ptr));
}
}
| enricoros/k-qt-creator-inspector | src/libs/3rdparty/botan/src/alloc/mem_pool/mem_pool.cpp | C++ | lgpl-2.1 | 5,618 |
from __future__ import absolute_import, unicode_literals
from case import Mock, patch
from amqp.five import text_t
from amqp.utils import (NullHandler, bytes_to_str, coro, get_errno, get_logger,
str_to_bytes)
class test_get_errno:
def test_has_attr(self):
exc = KeyError('foo')
exc.errno = 23
assert get_errno(exc) == 23
def test_in_args(self):
exc = KeyError(34, 'foo')
exc.args = (34, 'foo')
assert get_errno(exc) == 34
def test_args_short(self):
exc = KeyError(34)
assert not get_errno(exc)
def test_no_args(self):
assert not get_errno(object())
class test_coro:
def test_advances(self):
@coro
def x():
yield 1
yield 2
it = x()
assert next(it) == 2
class test_str_to_bytes:
def test_from_unicode(self):
assert isinstance(str_to_bytes(u'foo'), bytes)
def test_from_bytes(self):
assert isinstance(str_to_bytes(b'foo'), bytes)
def test_supports_surrogates(self):
bytes_with_surrogates = '\ud83d\ude4f'.encode('utf-8', 'surrogatepass')
assert str_to_bytes(u'\ud83d\ude4f') == bytes_with_surrogates
class test_bytes_to_str:
def test_from_unicode(self):
assert isinstance(bytes_to_str(u'foo'), text_t)
def test_from_bytes(self):
assert bytes_to_str(b'foo')
def test_support_surrogates(self):
assert bytes_to_str(u'\ud83d\ude4f') == u'\ud83d\ude4f'
class test_NullHandler:
def test_emit(self):
NullHandler().emit(Mock(name='record'))
class test_get_logger:
def test_as_str(self):
with patch('logging.getLogger') as getLogger:
x = get_logger('foo.bar')
getLogger.assert_called_with('foo.bar')
assert x is getLogger()
def test_as_logger(self):
with patch('amqp.utils.NullHandler') as _NullHandler:
m = Mock(name='logger')
m.handlers = None
x = get_logger(m)
assert x is m
x.addHandler.assert_called_with(_NullHandler())
| pexip/os-python-amqp | t/unit/test_utils.py | Python | lgpl-2.1 | 2,126 |
##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# 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) version 2.1, February 1999.
#
# 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 terms and
# conditions of 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Lzma(AutotoolsPackage):
"""LZMA Utils are legacy data compression software with high compression
ratio. LZMA Utils are no longer developed, although critical bugs may be
fixed as long as fixing them doesn't require huge changes to the code.
Users of LZMA Utils should move to XZ Utils. XZ Utils support the legacy
.lzma format used by LZMA Utils, and can also emulate the command line
tools of LZMA Utils. This should make transition from LZMA Utils to XZ
Utils relatively easy."""
homepage = "http://tukaani.org/lzma/"
url = "http://tukaani.org/lzma/lzma-4.32.7.tar.gz"
version('4.32.7', '2a748b77a2f8c3cbc322dbd0b4c9d06a')
| wscullin/spack | var/spack/repos/builtin/packages/lzma/package.py | Python | lgpl-2.1 | 1,935 |
/* XMMS2 - X Music Multiplexer System
* Copyright (C) 2003-2012 XMMS2 Team
*
* PLUGINS ARE NOT CONSIDERED TO BE DERIVED WORK !!!
*
* 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.
*/
#ifndef __XMMS_CLIENT_H__
#define __XMMS_CLIENT_H__
#include "xmmsc/xmmsc_compiler.h"
#include "xmmsc/xmmsc_stdint.h"
#include "xmmsc/xmmsc_ipc_msg.h"
#include "xmmsc/xmmsc_idnumbers.h"
#include "xmmsc/xmmsv.h"
#include "xmmsc/xmmsv_coll.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct xmmsc_connection_St xmmsc_connection_t;
typedef struct xmmsc_result_St xmmsc_result_t;
typedef enum {
XMMSC_RESULT_CLASS_DEFAULT,
XMMSC_RESULT_CLASS_SIGNAL,
XMMSC_RESULT_CLASS_BROADCAST
} xmmsc_result_type_t;
typedef void (*xmmsc_disconnect_func_t) (void *user_data);
typedef void (*xmmsc_user_data_free_func_t) (void *user_data);
typedef void (*xmmsc_io_need_out_callback_func_t) (int, void*);
xmmsc_connection_t *xmmsc_init (const char *clientname);
int xmmsc_connect (xmmsc_connection_t *, const char *);
xmmsc_connection_t *xmmsc_ref (xmmsc_connection_t *c);
void xmmsc_unref (xmmsc_connection_t *c);
void xmmsc_lock_set (xmmsc_connection_t *conn, void *lock, void (*lockfunc)(void *), void (*unlockfunc)(void *));
void xmmsc_disconnect_callback_set (xmmsc_connection_t *c, xmmsc_disconnect_func_t disconnect_func, void *userdata);
void xmmsc_disconnect_callback_set_full (xmmsc_connection_t *c, xmmsc_disconnect_func_t disconnect_func, void *userdata, xmmsc_user_data_free_func_t free_func);
void xmmsc_io_need_out_callback_set (xmmsc_connection_t *c, xmmsc_io_need_out_callback_func_t callback, void *userdata);
void xmmsc_io_need_out_callback_set_full (xmmsc_connection_t *c, xmmsc_io_need_out_callback_func_t callback, void *userdata, xmmsc_user_data_free_func_t free_func);
void xmmsc_io_disconnect (xmmsc_connection_t *c);
int xmmsc_io_want_out (xmmsc_connection_t *c);
int xmmsc_io_out_handle (xmmsc_connection_t *c);
int xmmsc_io_in_handle (xmmsc_connection_t *c);
int xmmsc_io_fd_get (xmmsc_connection_t *c);
char *xmmsc_get_last_error (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_quit(xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_broadcast_quit (xmmsc_connection_t *c);
/* get user config dir */
const char *xmmsc_userconfdir_get (char *buf, int len);
/* Encoding of urls */
char *xmmsc_medialib_encode_url_full (const char *url, xmmsv_t *args);
char *xmmsc_medialib_encode_url (const char *url);
/*
* PLAYLIST ************************************************
*/
/* commands */
xmmsc_result_t *xmmsc_playlist_list (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_playlist_create (xmmsc_connection_t *c, const char *playlist);
xmmsc_result_t *xmmsc_playlist_shuffle (xmmsc_connection_t *c, const char *playlist);
xmmsc_result_t *xmmsc_playlist_add_args (xmmsc_connection_t *c, const char *playlist, const char *, int, const char **) XMMS_DEPRECATED;
xmmsc_result_t *xmmsc_playlist_add_full (xmmsc_connection_t *c, const char *playlist, const char *, xmmsv_t *);
xmmsc_result_t *xmmsc_playlist_add_url (xmmsc_connection_t *c, const char *playlist, const char *url);
xmmsc_result_t *xmmsc_playlist_add_id (xmmsc_connection_t *c, const char *playlist, int id);
xmmsc_result_t *xmmsc_playlist_add_encoded (xmmsc_connection_t *c, const char *playlist, const char *url);
xmmsc_result_t *xmmsc_playlist_add_idlist (xmmsc_connection_t *c, const char *playlist, xmmsv_coll_t *coll);
xmmsc_result_t *xmmsc_playlist_add_collection (xmmsc_connection_t *c, const char *playlist, xmmsv_coll_t *coll, xmmsv_t *order);
xmmsc_result_t *xmmsc_playlist_remove_entry (xmmsc_connection_t *c, const char *playlist, int);
xmmsc_result_t *xmmsc_playlist_clear (xmmsc_connection_t *c, const char *playlist);
xmmsc_result_t *xmmsc_playlist_replace (xmmsc_connection_t *c, const char *playlist, xmmsv_coll_t *coll, xmms_playlist_position_action_t action);
xmmsc_result_t *xmmsc_playlist_remove (xmmsc_connection_t *c, const char *playlist);
xmmsc_result_t *xmmsc_playlist_list_entries (xmmsc_connection_t *c, const char *playlist);
xmmsc_result_t *xmmsc_playlist_sort (xmmsc_connection_t *c, const char *playlist, xmmsv_t *properties);
xmmsc_result_t *xmmsc_playlist_set_next (xmmsc_connection_t *c, int32_t);
xmmsc_result_t *xmmsc_playlist_set_next_rel (xmmsc_connection_t *c, int32_t);
xmmsc_result_t *xmmsc_playlist_move_entry (xmmsc_connection_t *c, const char *playlist, int, int);
xmmsc_result_t *xmmsc_playlist_current_pos (xmmsc_connection_t *c, const char *playlist);
xmmsc_result_t *xmmsc_playlist_current_active (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_playlist_insert_args (xmmsc_connection_t *c, const char *playlist, int pos, const char *url, int numargs, const char **args) XMMS_DEPRECATED;
xmmsc_result_t *xmmsc_playlist_insert_full (xmmsc_connection_t *c, const char *playlist, int pos, const char *url, xmmsv_t *args);
xmmsc_result_t *xmmsc_playlist_insert_url (xmmsc_connection_t *c, const char *playlist, int pos, const char *url);
xmmsc_result_t *xmmsc_playlist_insert_id (xmmsc_connection_t *c, const char *playlist, int pos, int32_t id);
xmmsc_result_t *xmmsc_playlist_insert_encoded (xmmsc_connection_t *c, const char *playlist, int pos, const char *url);
xmmsc_result_t *xmmsc_playlist_insert_collection (xmmsc_connection_t *c, const char *playlist, int pos, xmmsv_coll_t *coll, xmmsv_t *order);
xmmsc_result_t *xmmsc_playlist_load (xmmsc_connection_t *c, const char *playlist);
xmmsc_result_t *xmmsc_playlist_radd (xmmsc_connection_t *c, const char *playlist, const char *url);
xmmsc_result_t *xmmsc_playlist_radd_encoded (xmmsc_connection_t *c, const char *playlist, const char *url);
xmmsc_result_t *xmmsc_playlist_rinsert (xmmsc_connection_t *c, const char *playlist, int pos, const char *url);
xmmsc_result_t *xmmsc_playlist_rinsert_encoded (xmmsc_connection_t *c, const char *playlist, int pos, const char *url);
/* broadcasts */
xmmsc_result_t *xmmsc_broadcast_playlist_changed (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_broadcast_playlist_current_pos (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_broadcast_playlist_loaded (xmmsc_connection_t *c);
/*
* PLAYBACK ************************************************
*/
/* commands */
xmmsc_result_t *xmmsc_playback_stop (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_playback_tickle (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_playback_start (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_playback_pause (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_playback_current_id (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_playback_seek_ms (xmmsc_connection_t *c, int milliseconds, xmms_playback_seek_mode_t whence);
xmmsc_result_t *xmmsc_playback_seek_samples (xmmsc_connection_t *c, int samples, xmms_playback_seek_mode_t whence);
xmmsc_result_t *xmmsc_playback_playtime (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_playback_status (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_playback_volume_set (xmmsc_connection_t *c, const char *channel, int volume);
xmmsc_result_t *xmmsc_playback_volume_get (xmmsc_connection_t *c);
/* broadcasts */
xmmsc_result_t *xmmsc_broadcast_playback_volume_changed (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_broadcast_playback_status (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_broadcast_playback_current_id (xmmsc_connection_t *c);
/* signals */
xmmsc_result_t *xmmsc_signal_playback_playtime (xmmsc_connection_t *c);
/*
* CONFIG **************************************************
*/
/* commands */
xmmsc_result_t *xmmsc_config_set_value (xmmsc_connection_t *c, const char *key, const char *val);
xmmsc_result_t *xmmsc_config_list_values (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_config_get_value (xmmsc_connection_t *c, const char *key);
xmmsc_result_t *xmmsc_config_register_value (xmmsc_connection_t *c, const char *valuename, const char *defaultvalue);
/* broadcasts */
xmmsc_result_t *xmmsc_broadcast_config_value_changed (xmmsc_connection_t *c);
/*
* STATS **************************************************
*/
/* commands */
xmmsc_result_t *xmmsc_main_list_plugins (xmmsc_connection_t *c, xmms_plugin_type_t type);
xmmsc_result_t *xmmsc_main_stats (xmmsc_connection_t *c);
/* broadcasts */
xmmsc_result_t *xmmsc_broadcast_mediainfo_reader_status (xmmsc_connection_t *c);
/* signals */
xmmsc_result_t *xmmsc_signal_mediainfo_reader_unindexed (xmmsc_connection_t *c);
/*
* VISUALIZATION **************************************************
*/
/* commands */
xmmsc_result_t *xmmsc_visualization_version (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_visualization_init (xmmsc_connection_t *c);
/* Returns 1 on success, 0 on failure. In that case, see xmmsc_get_last_error() */
int xmmsc_visualization_init_handle (xmmsc_result_t *res);
xmmsc_result_t *xmmsc_visualization_start (xmmsc_connection_t *c, int vv);
void xmmsc_visualization_start_handle (xmmsc_connection_t *c, xmmsc_result_t *res);
bool xmmsc_visualization_started (xmmsc_connection_t *c, int vv);
bool xmmsc_visualization_errored (xmmsc_connection_t *c, int vv);
xmmsc_result_t *xmmsc_visualization_property_set (xmmsc_connection_t *c, int v, const char *key, const char *value);
xmmsc_result_t *xmmsc_visualization_properties_set (xmmsc_connection_t *c, int v, xmmsv_t *props);
/*
* drawtime: expected time needed to process the data in milliseconds after collecting it
if >= 0, the data is returned as soon as currenttime >= (playtime - drawtime);
data is thrown away if playtime < currenttime, but not if playtime < currenttime - drawtime
if < 0, the data is returned as soon as available, and no old data is thrown away
* blocking: time limit given in ms to wait for data. The process will sleep until new data is available, or the
limit is reached. But if data is found, it could still wait until it is current (see drawtime).
* returns size read on success, -1 on failure (server killed!) and 0 if no data is available yet (retry later)
* if a signal is received while waiting for data, 0 is returned, even before time ran out
* Note: the size read can be less than expected (for example, on song end). Check it!
*/
int xmmsc_visualization_chunk_get (xmmsc_connection_t *c, int vv, short *buffer, int drawtime, unsigned int blocking);
void xmmsc_visualization_shutdown (xmmsc_connection_t *c, int v);
/*
* MEDIALIB ***********************************************
*/
/* commands */
xmmsc_result_t *xmmsc_medialib_add_entry (xmmsc_connection_t *conn, const char *url);
xmmsc_result_t *xmmsc_medialib_add_entry_args (xmmsc_connection_t *conn, const char *url, int numargs, const char **args) XMMS_DEPRECATED;
xmmsc_result_t *xmmsc_medialib_add_entry_full (xmmsc_connection_t *conn, const char *url, xmmsv_t *args);
xmmsc_result_t *xmmsc_medialib_add_entry_encoded (xmmsc_connection_t *conn, const char *url);
xmmsc_result_t *xmmsc_medialib_get_info (xmmsc_connection_t *, int);
xmmsc_result_t *xmmsc_medialib_path_import (xmmsc_connection_t *conn, const char *path) XMMS_DEPRECATED;
xmmsc_result_t *xmmsc_medialib_path_import_encoded (xmmsc_connection_t *conn, const char *path) XMMS_DEPRECATED;
xmmsc_result_t *xmmsc_medialib_import_path (xmmsc_connection_t *conn, const char *path);
xmmsc_result_t *xmmsc_medialib_import_path_encoded (xmmsc_connection_t *conn, const char *path);
xmmsc_result_t *xmmsc_medialib_rehash (xmmsc_connection_t *conn, int id);
xmmsc_result_t *xmmsc_medialib_get_id (xmmsc_connection_t *conn, const char *url);
xmmsc_result_t *xmmsc_medialib_get_id_encoded (xmmsc_connection_t *conn, const char *url);
xmmsc_result_t *xmmsc_medialib_remove_entry (xmmsc_connection_t *conn, int entry);
xmmsc_result_t *xmmsc_medialib_move_entry (xmmsc_connection_t *conn, int entry, const char *url);
xmmsc_result_t *xmmsc_medialib_entry_property_set_int (xmmsc_connection_t *c, int id, const char *key, int32_t value);
xmmsc_result_t *xmmsc_medialib_entry_property_set_int_with_source (xmmsc_connection_t *c, int id, const char *source, const char *key, int32_t value);
xmmsc_result_t *xmmsc_medialib_entry_property_set_str (xmmsc_connection_t *c, int id, const char *key, const char *value);
xmmsc_result_t *xmmsc_medialib_entry_property_set_str_with_source (xmmsc_connection_t *c, int id, const char *source, const char *key, const char *value);
xmmsc_result_t *xmmsc_medialib_entry_property_remove (xmmsc_connection_t *c, int id, const char *key);
xmmsc_result_t *xmmsc_medialib_entry_property_remove_with_source (xmmsc_connection_t *c, int id, const char *source, const char *key);
/* XForm object */
xmmsc_result_t *xmmsc_xform_media_browse (xmmsc_connection_t *c, const char *url);
xmmsc_result_t *xmmsc_xform_media_browse_encoded (xmmsc_connection_t *c, const char *url);
/* Bindata object */
xmmsc_result_t *xmmsc_bindata_add (xmmsc_connection_t *c, const unsigned char *data, unsigned int len);
xmmsc_result_t *xmmsc_bindata_retrieve (xmmsc_connection_t *c, const char *hash);
xmmsc_result_t *xmmsc_bindata_remove (xmmsc_connection_t *c, const char *hash);
xmmsc_result_t *xmmsc_bindata_list (xmmsc_connection_t *c);
/* broadcasts */
xmmsc_result_t *xmmsc_broadcast_medialib_entry_changed (xmmsc_connection_t *c);
xmmsc_result_t *xmmsc_broadcast_medialib_entry_added (xmmsc_connection_t *c);
/*
* COLLECTION ***********************************************
*/
xmmsc_result_t* xmmsc_coll_get (xmmsc_connection_t *conn, const char *collname, xmmsv_coll_namespace_t ns);
xmmsc_result_t* xmmsc_coll_list (xmmsc_connection_t *conn, xmmsv_coll_namespace_t ns);
xmmsc_result_t* xmmsc_coll_save (xmmsc_connection_t *conn, xmmsv_coll_t *coll, const char* name, xmmsv_coll_namespace_t ns);
xmmsc_result_t* xmmsc_coll_remove (xmmsc_connection_t *conn, const char* name, xmmsv_coll_namespace_t ns);
xmmsc_result_t* xmmsc_coll_find (xmmsc_connection_t *conn, int mediaid, xmmsv_coll_namespace_t ns);
xmmsc_result_t* xmmsc_coll_rename (xmmsc_connection_t *conn, const char* from_name, const char* to_name, xmmsv_coll_namespace_t ns);
xmmsc_result_t *xmmsc_coll_idlist_from_playlist_file (xmmsc_connection_t *conn, const char *path);
xmmsc_result_t* xmmsc_coll_sync (xmmsc_connection_t *conn);
xmmsc_result_t* xmmsc_coll_query_ids (xmmsc_connection_t *conn, xmmsv_coll_t *coll, xmmsv_t *order, int limit_start, int limit_len);
xmmsc_result_t* xmmsc_coll_query_infos (xmmsc_connection_t *conn, xmmsv_coll_t *coll, xmmsv_t *order, int limit_start, int limit_len, xmmsv_t *fetch, xmmsv_t *group) XMMS_DEPRECATED;
xmmsc_result_t* xmmsc_coll_query (xmmsc_connection_t *conn, xmmsv_coll_t *coll, xmmsv_t *fetch);
/* string-to-collection parser */
typedef enum {
XMMS_COLLECTION_TOKEN_INVALID,
XMMS_COLLECTION_TOKEN_GROUP_OPEN,
XMMS_COLLECTION_TOKEN_GROUP_CLOSE,
XMMS_COLLECTION_TOKEN_REFERENCE,
XMMS_COLLECTION_TOKEN_SYMBOL_ID,
XMMS_COLLECTION_TOKEN_STRING,
XMMS_COLLECTION_TOKEN_PATTERN,
XMMS_COLLECTION_TOKEN_INTEGER,
XMMS_COLLECTION_TOKEN_SEQUENCE,
XMMS_COLLECTION_TOKEN_PROP_LONG,
XMMS_COLLECTION_TOKEN_PROP_SHORT,
XMMS_COLLECTION_TOKEN_OPSET_UNION,
XMMS_COLLECTION_TOKEN_OPSET_INTERSECTION,
XMMS_COLLECTION_TOKEN_OPSET_COMPLEMENT,
XMMS_COLLECTION_TOKEN_OPFIL_HAS,
XMMS_COLLECTION_TOKEN_OPFIL_EQUALS,
XMMS_COLLECTION_TOKEN_OPFIL_MATCH,
XMMS_COLLECTION_TOKEN_OPFIL_SMALLER,
XMMS_COLLECTION_TOKEN_OPFIL_GREATER,
XMMS_COLLECTION_TOKEN_OPFIL_SMALLEREQ,
XMMS_COLLECTION_TOKEN_OPFIL_GREATEREQ
} xmmsv_coll_token_type_t;
#define XMMS_COLLECTION_TOKEN_CUSTOM 32
typedef struct xmmsv_coll_token_St xmmsv_coll_token_t;
struct xmmsv_coll_token_St {
xmmsv_coll_token_type_t type;
char *string;
xmmsv_coll_token_t *next;
};
typedef xmmsv_coll_token_t* (*xmmsv_coll_parse_tokens_f) (const char *str, const char **newpos);
typedef xmmsv_coll_t* (*xmmsv_coll_parse_build_f) (xmmsv_coll_token_t *tokens);
int xmmsv_coll_parse (const char *pattern, xmmsv_coll_t** coll);
int xmmsv_coll_parse_custom (const char *pattern, xmmsv_coll_parse_tokens_f parse_f, xmmsv_coll_parse_build_f build_f, xmmsv_coll_t** coll);
xmmsv_coll_t *xmmsv_coll_default_parse_build (xmmsv_coll_token_t *tokens);
xmmsv_coll_token_t *xmmsv_coll_default_parse_tokens (const char *str, const char **newpos);
/* broadcasts */
xmmsc_result_t *xmmsc_broadcast_collection_changed (xmmsc_connection_t *c);
/*
* MACROS
*/
#define XMMS_CALLBACK_SET(conn,meth,callback,udata) \
XMMS_CALLBACK_SET_FULL(conn,meth,callback,udata,NULL);
#define XMMS_CALLBACK_SET_FULL(conn,meth,callback,udata,free_func) {\
xmmsc_result_t *res = meth (conn); \
xmmsc_result_notifier_set_full (res, callback, udata, free_func);\
xmmsc_result_unref (res);\
}
/*
* RESULTS
*/
typedef int (*xmmsc_result_notifier_t) (xmmsv_t *val, void *user_data);
xmmsc_result_type_t xmmsc_result_get_class (xmmsc_result_t *res);
void xmmsc_result_disconnect (xmmsc_result_t *res);
xmmsc_result_t *xmmsc_result_ref (xmmsc_result_t *res);
void xmmsc_result_unref (xmmsc_result_t *res);
void xmmsc_result_notifier_set (xmmsc_result_t *res, xmmsc_result_notifier_t func, void *user_data);
void xmmsc_result_notifier_set_full (xmmsc_result_t *res, xmmsc_result_notifier_t func, void *user_data, xmmsc_user_data_free_func_t free_func);
void xmmsc_result_wait (xmmsc_result_t *res);
xmmsv_t *xmmsc_result_get_value (xmmsc_result_t *res);
/* Legacy aliases for convenience. */
#define xmmsc_result_iserror(res) xmmsv_is_error(xmmsc_result_get_value(res))
/* compability */
typedef xmmsv_coll_token_type_t xmmsc_coll_token_type_t;
typedef xmmsv_coll_token_t xmmsc_coll_token_t;
typedef xmmsv_coll_parse_tokens_f xmmsc_coll_parse_tokens_f;
typedef xmmsv_coll_parse_build_f xmmsc_coll_parse_build_f;
#define xmmsc_coll_parse xmmsv_coll_parse
#define xmmsc_coll_parse_custom xmmsv_coll_parse_custom
#define xmmsc_coll_default_parse_build xmmsv_coll_default_parse_build
#define xmmsc_coll_default_parse_tokens xmmsv_coll_default_parse_tokens
#ifdef __cplusplus
}
#endif
#endif
| krad-radio/xmms2-krad | src/include/xmmsclient/xmmsclient.h | C | lgpl-2.1 | 18,288 |
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import "MITMappedObject.h"
#import "MITManagedObject.h"
#import "CoreLocation+MITAdditions.h"
@class MITToursDirectionsToStop, MITToursImage, MITToursTour;
@interface MITToursStop : MITManagedObject <MITMappedObject>
@property (nonatomic, retain) NSString * bodyHTML;
@property (nonatomic, retain) id coordinates;
@property (nonatomic, retain) NSString * identifier;
@property (nonatomic, retain) NSString * stopType;
@property (nonatomic, retain) NSString * title;
@property (nonatomic, retain) MITToursDirectionsToStop *directionsToNextStop;
@property (nonatomic, retain) NSOrderedSet *images;
@property (nonatomic, retain) MITToursTour *tour;
@property (nonatomic, readonly) CLLocation *locationForStop;
@property (nonatomic, readonly) BOOL isMainLoopStop;
- (NSString *)thumbnailURL;
- (NSString *)fullImageURL;
@end
@interface MITToursStop (CoreDataGeneratedAccessors)
- (void)insertObject:(MITToursImage *)value inImagesAtIndex:(NSUInteger)idx;
- (void)removeObjectFromImagesAtIndex:(NSUInteger)idx;
- (void)insertImages:(NSArray *)value atIndexes:(NSIndexSet *)indexes;
- (void)removeImagesAtIndexes:(NSIndexSet *)indexes;
- (void)replaceObjectInImagesAtIndex:(NSUInteger)idx withObject:(MITToursImage *)value;
- (void)replaceImagesAtIndexes:(NSIndexSet *)indexes withImages:(NSArray *)values;
- (void)addImagesObject:(MITToursImage *)value;
- (void)removeImagesObject:(MITToursImage *)value;
- (void)addImages:(NSOrderedSet *)values;
- (void)removeImages:(NSOrderedSet *)values;
@end
| smartcop/MIT-Mobile-for-iOS | Modules/Tours/MITToursStop.h | C | lgpl-2.1 | 1,566 |
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt3Support module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "q3socketdevice.h"
#ifndef QT_NO_NETWORK
#include "qwindowdefs.h"
#include <string.h>
QT_BEGIN_NAMESPACE
//#define Q3SOCKETDEVICE_DEBUG
class Q3SocketDevicePrivate
{
public:
Q3SocketDevicePrivate( Q3SocketDevice::Protocol p )
: protocol(p)
{ }
Q3SocketDevice::Protocol protocol;
};
/*!
\class Q3SocketDevice
\brief The Q3SocketDevice class provides a platform-independent low-level socket API.
\compat
\reentrant
This class provides a low level API for working with sockets. Users of
this class are assumed to have networking experience. For most users the
Q3Socket class provides a much easier and high level alternative, but
certain things (like UDP) can't be done with Q3Socket and if you need a
platform-independent API for those, Q3SocketDevice is the right choice.
The essential purpose of the class is to provide a QIODevice that
works on sockets, wrapped in a platform-independent API.
When calling connect() or bind(), Q3SocketDevice detects the
protocol family (IPv4, IPv6) automatically. Passing the protocol
family to Q3SocketDevice's constructor or to setSocket() forces
creation of a socket device of a specific protocol. If not set, the
protocol will be detected at the first call to connect() or bind().
\sa Q3Socket, QSocketNotifier, QHostAddress
*/
/*!
\enum Q3SocketDevice::Protocol
This enum type describes the protocol family of the socket. Possible values
are:
\value IPv4 The socket is an IPv4 socket.
\value IPv6 The socket is an IPv6 socket.
\value Unknown The protocol family of the socket is not known. This can
happen if you use Q3SocketDevice with an already existing socket; it
tries to determine the protocol family, but this can fail if the
protocol family is not known to Q3SocketDevice.
\sa protocol() setSocket()
*/
/*!
\enum Q3SocketDevice::Error
This enum type describes the error states of Q3SocketDevice.
\value NoError No error has occurred.
\value AlreadyBound The device is already bound, according to bind().
\value Inaccessible The operating system or firewall prohibited
the action.
\value NoResources The operating system ran out of a resource.
\value InternalError An internal error occurred in Q3SocketDevice.
\value Impossible An attempt was made to do something which makes
no sense. For example:
\snippet doc/src/snippets/code/src_qt3support_network_q3socketdevice.cpp 0
The libc ::close() closes the socket, but Q3SocketDevice is not aware
of this. So when you call writeBlock(), the impossible happens.
\value NoFiles The operating system will not let Q3SocketDevice open
another file.
\value ConnectionRefused A connection attempt was rejected by the
peer.
\value NetworkFailure There is a network failure.
\value UnknownError The operating system did something
unexpected.
\omitvalue Bug
*/
/*!
\enum Q3SocketDevice::Type
This enum type describes the type of the socket:
\value Stream a stream socket (TCP, usually)
\value Datagram a datagram socket (UDP, usually)
*/
/*!
Creates a Q3SocketDevice object for the existing socket \a socket.
The \a type argument must match the actual socket type; use \c
Q3SocketDevice::Stream for a reliable, connection-oriented TCP
socket, or Q3SocketDevice::Datagram for an unreliable,
connectionless UDP socket.
*/
Q3SocketDevice::Q3SocketDevice( int socket, Type type )
: fd( socket ), t( type ), p( 0 ), pp( 0 ), e( NoError ),
d(new Q3SocketDevicePrivate(Unknown))
{
#if defined(Q3SOCKETDEVICE_DEBUG)
qDebug( "Q3SocketDevice: Created Q3SocketDevice %p (socket %x, type %d)",
this, socket, type );
#endif
init();
setSocket( socket, type );
}
/*!
Creates a Q3SocketDevice object for a stream or datagram socket.
The \a type argument must be either Q3SocketDevice::Stream for a
reliable, connection-oriented TCP socket, or \c
Q3SocketDevice::Datagram for an unreliable UDP socket.
The socket is created as an IPv4 socket.
\sa blocking() protocol()
*/
Q3SocketDevice::Q3SocketDevice( Type type )
: fd( -1 ), t( type ), p( 0 ), pp( 0 ), e( NoError ),
d(new Q3SocketDevicePrivate(IPv4))
{
#if defined(Q3SOCKETDEVICE_DEBUG)
qDebug( "Q3SocketDevice: Created Q3SocketDevice object %p, type %d",
this, type );
#endif
init();
setSocket( createNewSocket(), type );
}
/*!
Creates a Q3SocketDevice object for a stream or datagram socket.
The \a type argument must be either Q3SocketDevice::Stream for a
reliable, connection-oriented TCP socket, or \c
Q3SocketDevice::Datagram for an unreliable UDP socket.
The \a protocol indicates whether the socket should be of type IPv4
or IPv6. Passing \c Unknown is not meaningful in this context and you
should avoid using (it creates an IPv4 socket, but your code is not easily
readable).
The argument \a dummy is necessary for compatibility with some
compilers.
\sa blocking() protocol()
*/
Q3SocketDevice::Q3SocketDevice( Type type, Protocol protocol, int )
: fd( -1 ), t( type ), p( 0 ), pp( 0 ), e( NoError ),
d(new Q3SocketDevicePrivate(protocol))
{
#if defined(Q3SOCKETDEVICE_DEBUG)
qDebug( "Q3SocketDevice: Created Q3SocketDevice object %p, type %d",
this, type );
#endif
init();
setSocket( createNewSocket(), type );
}
/*!
Destroys the socket device and closes the socket if it is open.
*/
Q3SocketDevice::~Q3SocketDevice()
{
close();
delete d;
d = 0;
#if defined(Q3SOCKETDEVICE_DEBUG)
qDebug( "Q3SocketDevice: Destroyed Q3SocketDevice %p", this );
#endif
}
/*!
Returns true if this is a valid socket; otherwise returns false.
\sa socket()
*/
bool Q3SocketDevice::isValid() const
{
return fd != -1;
}
/*!
\fn Type Q3SocketDevice::type() const
Returns the socket type which is either Q3SocketDevice::Stream
or Q3SocketDevice::Datagram.
\sa socket()
*/
Q3SocketDevice::Type Q3SocketDevice::type() const
{
return t;
}
/*!
Returns the socket's protocol family, which is one of \c Unknown, \c IPv4,
or \c IPv6.
Q3SocketDevice either creates a socket with a well known protocol family or
it uses an already existing socket. In the first case, this function
returns the protocol family it was constructed with. In the second case, it
tries to determine the protocol family of the socket; if this fails, it
returns \c Unknown.
\sa Protocol setSocket()
*/
Q3SocketDevice::Protocol Q3SocketDevice::protocol() const
{
if ( d->protocol == Unknown )
d->protocol = getProtocol();
return d->protocol;
}
/*!
Returns the socket number, or -1 if it is an invalid socket.
\sa isValid(), type()
*/
int Q3SocketDevice::socket() const
{
return fd;
}
/*!
Sets the socket device to operate on the existing socket \a
socket.
The \a type argument must match the actual socket type; use \c
Q3SocketDevice::Stream for a reliable, connection-oriented TCP
socket, or Q3SocketDevice::Datagram for an unreliable,
connectionless UDP socket.
Any existing socket is closed.
\sa isValid(), close()
*/
void Q3SocketDevice::setSocket( int socket, Type type )
{
if ( fd != -1 ) // close any open socket
close();
#if defined(Q3SOCKETDEVICE_DEBUG)
qDebug( "Q3SocketDevice::setSocket: socket %x, type %d", socket, type );
#endif
t = type;
fd = socket;
d->protocol = Unknown;
e = NoError;
resetStatus();
open( ReadWrite );
fetchConnectionParameters();
}
/*!
Opens the socket using the specified QIODevice file \a mode. This
function is called from the Q3SocketDevice constructors and from
the setSocket() function. You should not call it yourself.
\sa close()
*/
bool Q3SocketDevice::open( OpenMode mode )
{
if ( isOpen() || !isValid() )
return false;
#if defined(Q3SOCKETDEVICE_DEBUG)
qDebug( "Q3SocketDevice::open: mode %x", mode );
#endif
setOpenMode( (mode & ReadWrite) | Unbuffered );
return true;
}
/*!
\fn bool Q3SocketDevice::open(int mode)
\overload
*/
/*!
The current Q3SocketDevice implementation does not buffer at all,
so this is a no-op. This function always returns true.
*/
bool Q3SocketDevice::flush()
{
return true;
}
/*!
\reimp
The size is meaningless for a socket, therefore this function returns 0.
*/
QIODevice::Offset Q3SocketDevice::size() const
{
return 0;
}
/*!
The read/write index is meaningless for a socket, therefore this
function returns 0.
*/
QIODevice::Offset Q3SocketDevice::at() const
{
return 0;
}
/*!
The read/write index is meaningless for a socket, therefore this
function does nothing and returns true.
The \a offset parameter is ignored.
*/
bool Q3SocketDevice::at( Offset /* offset */ )
{
return true;
}
/*!
\reimp
Returns true if no data is currently available at the socket;
otherwise returns false.
*/
bool Q3SocketDevice::atEnd() const
{
return bytesAvailable() <= 0;
}
/*!
Returns true if the address of this socket can be used by other
sockets at the same time, and false if this socket claims
exclusive ownership.
\sa setAddressReusable()
*/
bool Q3SocketDevice::addressReusable() const
{
return option( ReuseAddress );
}
/*!
Sets the address of this socket to be usable by other sockets too
if \a enable is true, and to be used exclusively by this socket if
\a enable is false.
When a socket is reusable, other sockets can use the same port
number (and IP address), which is generally useful. Of course
other sockets cannot use the same
(address,port,peer-address,peer-port) 4-tuple as this socket, so
there is no risk of confusing the two TCP connections.
\sa addressReusable()
*/
void Q3SocketDevice::setAddressReusable( bool enable )
{
setOption( ReuseAddress, enable );
}
/*!
Returns the size of the operating system receive buffer.
\sa setReceiveBufferSize()
*/
int Q3SocketDevice::receiveBufferSize() const
{
return option( ReceiveBuffer );
}
/*!
Sets the size of the operating system receive buffer to \a size.
The operating system receive buffer size effectively limits two
things: how much data can be in transit at any one moment, and how
much data can be received in one iteration of the main event loop.
The default is operating system-dependent. A socket that receives
large amounts of data is probably best with a buffer size of
49152.
*/
void Q3SocketDevice::setReceiveBufferSize( uint size )
{
setOption( ReceiveBuffer, size );
}
/*!
Returns the size of the operating system send buffer.
\sa setSendBufferSize()
*/
int Q3SocketDevice::sendBufferSize() const
{
return option( SendBuffer );
}
/*!
Sets the size of the operating system send buffer to \a size.
The operating system send buffer size effectively limits how much
data can be in transit at any one moment.
The default is operating system-dependent. A socket that sends
large amounts of data is probably best with a buffer size of
49152.
*/
void Q3SocketDevice::setSendBufferSize( uint size )
{
setOption( SendBuffer, size );
}
/*!
Returns the port number of this socket device. This may be 0 for a
while, but is set to something sensible as soon as a sensible
value is available.
Note that Qt always uses native byte order, i.e. 67 is 67 in Qt;
there is no need to call htons().
*/
quint16 Q3SocketDevice::port() const
{
return p;
}
/*!
Returns the address of this socket device. This may be 0.0.0.0 for
a while, but is set to something sensible as soon as a sensible
value is available.
*/
QHostAddress Q3SocketDevice::address() const
{
return a;
}
/*!
Returns the first error seen.
*/
Q3SocketDevice::Error Q3SocketDevice::error() const
{
return e;
}
/*!
Allows subclasses to set the error state to \a err.
*/
void Q3SocketDevice::setError( Error err )
{
e = err;
}
/*! \fn Q3SocketDevice::readBlock(char *data, Q_ULONG maxlen)
Reads \a maxlen bytes from the socket into \a data and returns the
number of bytes read. Returns -1 if an error occurred. Returning 0
is not an error. For Stream sockets, 0 is returned when the remote
host closes the connection. For Datagram sockets, 0 is a valid
datagram size.
*/
/*! \fn Q3SocketDevice::writeBlock(const char *data, Q_ULONG len)
Writes \a len bytes to the socket from \a data and returns the
number of bytes written. Returns -1 if an error occurred.
This is used for Q3SocketDevice::Stream sockets.
*/
/*!
\fn Q_LONG Q3SocketDevice::writeBlock( const char * data, Q_ULONG len,
const QHostAddress & host, Q_UINT16 port )
\overload
Writes \a len bytes to the socket from \a data and returns the
number of bytes written. Returns -1 if an error occurred.
This is used for Q3SocketDevice::Datagram sockets. You must
specify the \a host and \a port of the destination of the data.
*/
/*!
\fn bool Q3SocketDevice::isSequential() const
\internal
*/
/*!
\fn qint64 Q3SocketDevice::readData( char *data, qint64 maxlen )
Reads \a maxlen bytes from the socket into \a data and returns the
number of bytes read. Returns -1 if an error occurred.
*/
/*!
\fn int Q3SocketDevice::createNewSocket()
Creates a new socket identifier. Returns -1 if there is a failure
to create the new identifier; error() explains why.
\sa setSocket()
*/
/*!
\fn void Q3SocketDevice::close()
\reimp
Closes the socket and sets the socket identifier to -1 (invalid).
(This function ignores errors; if there are any then a file
descriptor leakage might result. As far as we know, the only error
that can arise is EBADF, and that would of course not cause
leakage. There may be OS-specific errors that we haven't come
across, however.)
\sa open()
*/
/*!
\fn bool Q3SocketDevice::blocking() const
Returns true if the socket is valid and in blocking mode;
otherwise returns false.
Note that this function does not set error().
\warning On Windows, this function always returns true since the
ioctlsocket() function is broken.
\sa setBlocking(), isValid()
*/
/*!
\fn void Q3SocketDevice::setBlocking( bool enable )
Makes the socket blocking if \a enable is true or nonblocking if
\a enable is false.
Sockets are blocking by default, but we recommend using
nonblocking socket operations, especially for GUI programs that
need to be responsive.
\warning On Windows, this function should be used with care since
whenever you use a QSocketNotifier on Windows, the socket is
immediately made nonblocking.
\sa blocking(), isValid()
*/
/*!
\fn int Q3SocketDevice::option( Option opt ) const
Returns the value of the socket option \a opt.
*/
/*!
\fn void Q3SocketDevice::setOption( Option opt, int v )
Sets the socket option \a opt to \a v.
*/
/*!
\fn bool Q3SocketDevice::connect( const QHostAddress &addr, Q_UINT16 port )
Connects to the IP address and port specified by \a addr and \a
port. Returns true if it establishes a connection; otherwise returns false.
If it returns false, error() explains why.
Note that error() commonly returns NoError for non-blocking
sockets; this just means that you can call connect() again in a
little while and it'll probably succeed.
*/
/*!
\fn bool Q3SocketDevice::bind( const QHostAddress &address, Q_UINT16 port )
Assigns a name to an unnamed socket. The name is the host address
\a address and the port number \a port. If the operation succeeds,
bind() returns true; otherwise it returns false without changing
what port() and address() return.
bind() is used by servers for setting up incoming connections.
Call bind() before listen().
*/
/*!
\fn bool Q3SocketDevice::listen( int backlog )
Specifies how many pending connections a server socket can have.
Returns true if the operation was successful; otherwise returns
false. A \a backlog value of 50 is quite common.
The listen() call only applies to sockets where type() is \c
Stream, i.e. not to \c Datagram sockets. listen() must not be
called before bind() or after accept().
\sa bind(), accept()
*/
/*!
\fn int Q3SocketDevice::accept()
Extracts the first connection from the queue of pending
connections for this socket and returns a new socket identifier.
Returns -1 if the operation failed.
\sa bind(), listen()
*/
/*!
\fn qint64 Q3SocketDevice::bytesAvailable() const
Returns the number of bytes available for reading, or -1 if an
error occurred.
\warning On Microsoft Windows, we use the ioctlsocket() function
to determine the number of bytes queued on the socket. According
to Microsoft (KB Q125486), ioctlsocket() sometimes returns an
incorrect number. The only safe way to determine the amount of
data on the socket is to read it using readBlock(). QSocket has
workarounds to deal with this problem.
*/
/*!
\fn Q_LONG Q3SocketDevice::waitForMore( int msecs, bool *timeout ) const
Wait up to \a msecs milliseconds for more data to be available. If
\a msecs is -1 the call will block indefinitely.
Returns the number of bytes available for reading, or -1 if an
error occurred.
If \a timeout is non-null and no error occurred (i.e. it does not
return -1): this function sets *\a timeout to true, if the reason
for returning was that the timeout was reached; otherwise it sets
*\a timeout to false. This is useful to find out if the peer
closed the connection.
\warning This is a blocking call and should be avoided in event
driven applications.
\sa bytesAvailable()
*/
/*!
\fn qint64 Q3SocketDevice::writeData( const char *data, qint64 len )
Writes \a len bytes to the socket from \a data and returns the
number of bytes written. Returns -1 if an error occurred.
This is used for Q3SocketDevice::Stream sockets.
*/
/*!
\fn void Q3SocketDevice::fetchConnectionParameters()
Fetches information about both ends of the connection: whatever is
available.
*/
/*!
\fn Q_UINT16 Q3SocketDevice::peerPort() const
Returns the port number of the port this socket device is
connected to. This may be 0 for a while, but is set to something
sensible as soon as a sensible value is available.
Note that for Datagram sockets, this is the source port of the
last packet received, and that it is in native byte order.
*/
/*!
\fn QHostAddress Q3SocketDevice::peerAddress() const
Returns the address of the port this socket device is connected
to. This may be 0.0.0.0 for a while, but is set to something
sensible as soon as a sensible value is available.
Note that for Datagram sockets, this is the source port of the
last packet received.
*/
QT_END_NAMESPACE
#endif //QT_NO_NETWORK
| kobolabs/qt-everywhere-4.8.0 | src/qt3support/network/q3socketdevice.cpp | C++ | lgpl-2.1 | 20,956 |
// Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au)
// Copyright 2008-2016 National ICT Australia (NICTA)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------
//! \addtogroup gmm_diag
//! @{
namespace gmm_priv
{
template<typename eT>
inline
gmm_diag<eT>::~gmm_diag()
{
arma_extra_debug_sigprint_this(this);
arma_type_check(( (is_same_type<eT,float>::value == false) && (is_same_type<eT,double>::value == false) ));
}
template<typename eT>
inline
gmm_diag<eT>::gmm_diag()
{
arma_extra_debug_sigprint_this(this);
}
template<typename eT>
inline
gmm_diag<eT>::gmm_diag(const gmm_diag<eT>& x)
{
arma_extra_debug_sigprint_this(this);
init(x);
}
template<typename eT>
inline
gmm_diag<eT>&
gmm_diag<eT>::operator=(const gmm_diag<eT>& x)
{
arma_extra_debug_sigprint();
init(x);
return *this;
}
template<typename eT>
inline
gmm_diag<eT>::gmm_diag(const gmm_full<eT>& x)
{
arma_extra_debug_sigprint_this(this);
init(x);
}
template<typename eT>
inline
gmm_diag<eT>&
gmm_diag<eT>::operator=(const gmm_full<eT>& x)
{
arma_extra_debug_sigprint();
init(x);
return *this;
}
template<typename eT>
inline
gmm_diag<eT>::gmm_diag(const uword in_n_dims, const uword in_n_gaus)
{
arma_extra_debug_sigprint_this(this);
init(in_n_dims, in_n_gaus);
}
template<typename eT>
inline
void
gmm_diag<eT>::reset()
{
arma_extra_debug_sigprint();
init(0, 0);
}
template<typename eT>
inline
void
gmm_diag<eT>::reset(const uword in_n_dims, const uword in_n_gaus)
{
arma_extra_debug_sigprint();
init(in_n_dims, in_n_gaus);
}
template<typename eT>
template<typename T1, typename T2, typename T3>
inline
void
gmm_diag<eT>::set_params(const Base<eT,T1>& in_means_expr, const Base<eT,T2>& in_dcovs_expr, const Base<eT,T3>& in_hefts_expr)
{
arma_extra_debug_sigprint();
const unwrap<T1> tmp1(in_means_expr.get_ref());
const unwrap<T2> tmp2(in_dcovs_expr.get_ref());
const unwrap<T3> tmp3(in_hefts_expr.get_ref());
const Mat<eT>& in_means = tmp1.M;
const Mat<eT>& in_dcovs = tmp2.M;
const Mat<eT>& in_hefts = tmp3.M;
arma_debug_check
(
(arma::size(in_means) != arma::size(in_dcovs)) || (in_hefts.n_cols != in_means.n_cols) || (in_hefts.n_rows != 1),
"gmm_diag::set_params(): given parameters have inconsistent and/or wrong sizes"
);
arma_debug_check( (in_means.is_finite() == false), "gmm_diag::set_params(): given means have non-finite values" );
arma_debug_check( (in_dcovs.is_finite() == false), "gmm_diag::set_params(): given dcovs have non-finite values" );
arma_debug_check( (in_hefts.is_finite() == false), "gmm_diag::set_params(): given hefts have non-finite values" );
arma_debug_check( (any(vectorise(in_dcovs) <= eT(0))), "gmm_diag::set_params(): given dcovs have negative or zero values" );
arma_debug_check( (any(vectorise(in_hefts) < eT(0))), "gmm_diag::set_params(): given hefts have negative values" );
const eT s = accu(in_hefts);
arma_debug_check( ((s < (eT(1) - eT(0.001))) || (s > (eT(1) + eT(0.001)))), "gmm_diag::set_params(): sum of given hefts is not 1" );
access::rw(means) = in_means;
access::rw(dcovs) = in_dcovs;
access::rw(hefts) = in_hefts;
init_constants();
}
template<typename eT>
template<typename T1>
inline
void
gmm_diag<eT>::set_means(const Base<eT,T1>& in_means_expr)
{
arma_extra_debug_sigprint();
const unwrap<T1> tmp(in_means_expr.get_ref());
const Mat<eT>& in_means = tmp.M;
arma_debug_check( (arma::size(in_means) != arma::size(means)), "gmm_diag::set_means(): given means have incompatible size" );
arma_debug_check( (in_means.is_finite() == false), "gmm_diag::set_means(): given means have non-finite values" );
access::rw(means) = in_means;
}
template<typename eT>
template<typename T1>
inline
void
gmm_diag<eT>::set_dcovs(const Base<eT,T1>& in_dcovs_expr)
{
arma_extra_debug_sigprint();
const unwrap<T1> tmp(in_dcovs_expr.get_ref());
const Mat<eT>& in_dcovs = tmp.M;
arma_debug_check( (arma::size(in_dcovs) != arma::size(dcovs)), "gmm_diag::set_dcovs(): given dcovs have incompatible size" );
arma_debug_check( (in_dcovs.is_finite() == false), "gmm_diag::set_dcovs(): given dcovs have non-finite values" );
arma_debug_check( (any(vectorise(in_dcovs) <= eT(0))), "gmm_diag::set_dcovs(): given dcovs have negative or zero values" );
access::rw(dcovs) = in_dcovs;
init_constants();
}
template<typename eT>
template<typename T1>
inline
void
gmm_diag<eT>::set_hefts(const Base<eT,T1>& in_hefts_expr)
{
arma_extra_debug_sigprint();
const unwrap<T1> tmp(in_hefts_expr.get_ref());
const Mat<eT>& in_hefts = tmp.M;
arma_debug_check( (arma::size(in_hefts) != arma::size(hefts)), "gmm_diag::set_hefts(): given hefts have incompatible size" );
arma_debug_check( (in_hefts.is_finite() == false), "gmm_diag::set_hefts(): given hefts have non-finite values" );
arma_debug_check( (any(vectorise(in_hefts) < eT(0))), "gmm_diag::set_hefts(): given hefts have negative values" );
const eT s = accu(in_hefts);
arma_debug_check( ((s < (eT(1) - eT(0.001))) || (s > (eT(1) + eT(0.001)))), "gmm_diag::set_hefts(): sum of given hefts is not 1" );
// make sure all hefts are positive and non-zero
const eT* in_hefts_mem = in_hefts.memptr();
eT* hefts_mem = access::rw(hefts).memptr();
for(uword i=0; i < hefts.n_elem; ++i)
{
hefts_mem[i] = (std::max)( in_hefts_mem[i], std::numeric_limits<eT>::min() );
}
access::rw(hefts) /= accu(hefts);
log_hefts = log(hefts);
}
template<typename eT>
inline
uword
gmm_diag<eT>::n_dims() const
{
return means.n_rows;
}
template<typename eT>
inline
uword
gmm_diag<eT>::n_gaus() const
{
return means.n_cols;
}
template<typename eT>
inline
bool
gmm_diag<eT>::load(const std::string name)
{
arma_extra_debug_sigprint();
Cube<eT> Q;
bool status = Q.load(name, arma_binary);
if( (status == false) || (Q.n_slices != 2) )
{
reset();
arma_debug_warn("gmm_diag::load(): problem with loading or incompatible format");
return false;
}
if( (Q.n_rows < 2) || (Q.n_cols < 1) )
{
reset();
return true;
}
access::rw(hefts) = Q.slice(0).row(0);
access::rw(means) = Q.slice(0).submat(1, 0, Q.n_rows-1, Q.n_cols-1);
access::rw(dcovs) = Q.slice(1).submat(1, 0, Q.n_rows-1, Q.n_cols-1);
init_constants();
return true;
}
template<typename eT>
inline
bool
gmm_diag<eT>::save(const std::string name) const
{
arma_extra_debug_sigprint();
Cube<eT> Q(means.n_rows + 1, means.n_cols, 2);
if(Q.n_elem > 0)
{
Q.slice(0).row(0) = hefts;
Q.slice(1).row(0).zeros(); // reserved for future use
Q.slice(0).submat(1, 0, arma::size(means)) = means;
Q.slice(1).submat(1, 0, arma::size(dcovs)) = dcovs;
}
const bool status = Q.save(name, arma_binary);
return status;
}
template<typename eT>
inline
Col<eT>
gmm_diag<eT>::generate() const
{
arma_extra_debug_sigprint();
const uword N_dims = means.n_rows;
const uword N_gaus = means.n_cols;
Col<eT> out( ((N_gaus > 0) ? N_dims : uword(0)), fill::randn );
if(N_gaus > 0)
{
const double val = randu<double>();
double csum = double(0);
uword gaus_id = 0;
for(uword j=0; j < N_gaus; ++j)
{
csum += hefts[j];
if(val <= csum) { gaus_id = j; break; }
}
out %= sqrt(dcovs.col(gaus_id));
out += means.col(gaus_id);
}
return out;
}
template<typename eT>
inline
Mat<eT>
gmm_diag<eT>::generate(const uword N_vec) const
{
arma_extra_debug_sigprint();
const uword N_dims = means.n_rows;
const uword N_gaus = means.n_cols;
Mat<eT> out( ( (N_gaus > 0) ? N_dims : uword(0) ), N_vec, fill::randn );
if(N_gaus > 0)
{
const eT* hefts_mem = hefts.memptr();
const Mat<eT> sqrt_dcovs = sqrt(dcovs);
for(uword i=0; i < N_vec; ++i)
{
const double val = randu<double>();
double csum = double(0);
uword gaus_id = 0;
for(uword j=0; j < N_gaus; ++j)
{
csum += hefts_mem[j];
if(val <= csum) { gaus_id = j; break; }
}
subview_col<eT> out_col = out.col(i);
out_col %= sqrt_dcovs.col(gaus_id);
out_col += means.col(gaus_id);
}
}
return out;
}
template<typename eT>
template<typename T1>
inline
eT
gmm_diag<eT>::log_p(const T1& expr, const gmm_empty_arg& junk1, typename enable_if<((is_arma_type<T1>::value) && (resolves_to_colvector<T1>::value == true))>::result* junk2) const
{
arma_extra_debug_sigprint();
arma_ignore(junk1);
arma_ignore(junk2);
const quasi_unwrap<T1> tmp(expr);
arma_debug_check( (tmp.M.n_rows != means.n_rows), "gmm_diag::log_p(): incompatible dimensions" );
return internal_scalar_log_p( tmp.M.memptr() );
}
template<typename eT>
template<typename T1>
inline
eT
gmm_diag<eT>::log_p(const T1& expr, const uword gaus_id, typename enable_if<((is_arma_type<T1>::value) && (resolves_to_colvector<T1>::value == true))>::result* junk2) const
{
arma_extra_debug_sigprint();
arma_ignore(junk2);
const quasi_unwrap<T1> tmp(expr);
arma_debug_check( (tmp.M.n_rows != means.n_rows), "gmm_diag::log_p(): incompatible dimensions" );
arma_debug_check( (gaus_id >= means.n_cols), "gmm_diag::log_p(): specified gaussian is out of range" );
return internal_scalar_log_p( tmp.M.memptr(), gaus_id );
}
template<typename eT>
template<typename T1>
inline
Row<eT>
gmm_diag<eT>::log_p(const T1& expr, const gmm_empty_arg& junk1, typename enable_if<((is_arma_type<T1>::value) && (resolves_to_colvector<T1>::value == false))>::result* junk2) const
{
arma_extra_debug_sigprint();
arma_ignore(junk1);
arma_ignore(junk2);
const quasi_unwrap<T1> tmp(expr);
const Mat<eT>& X = tmp.M;
return internal_vec_log_p(X);
}
template<typename eT>
template<typename T1>
inline
Row<eT>
gmm_diag<eT>::log_p(const T1& expr, const uword gaus_id, typename enable_if<((is_arma_type<T1>::value) && (resolves_to_colvector<T1>::value == false))>::result* junk2) const
{
arma_extra_debug_sigprint();
arma_ignore(junk2);
const quasi_unwrap<T1> tmp(expr);
const Mat<eT>& X = tmp.M;
return internal_vec_log_p(X, gaus_id);
}
template<typename eT>
template<typename T1>
inline
eT
gmm_diag<eT>::sum_log_p(const Base<eT,T1>& expr) const
{
arma_extra_debug_sigprint();
const quasi_unwrap<T1> tmp(expr.get_ref());
const Mat<eT>& X = tmp.M;
return internal_sum_log_p(X);
}
template<typename eT>
template<typename T1>
inline
eT
gmm_diag<eT>::sum_log_p(const Base<eT,T1>& expr, const uword gaus_id) const
{
arma_extra_debug_sigprint();
const quasi_unwrap<T1> tmp(expr.get_ref());
const Mat<eT>& X = tmp.M;
return internal_sum_log_p(X, gaus_id);
}
template<typename eT>
template<typename T1>
inline
eT
gmm_diag<eT>::avg_log_p(const Base<eT,T1>& expr) const
{
arma_extra_debug_sigprint();
const quasi_unwrap<T1> tmp(expr.get_ref());
const Mat<eT>& X = tmp.M;
return internal_avg_log_p(X);
}
template<typename eT>
template<typename T1>
inline
eT
gmm_diag<eT>::avg_log_p(const Base<eT,T1>& expr, const uword gaus_id) const
{
arma_extra_debug_sigprint();
const quasi_unwrap<T1> tmp(expr.get_ref());
const Mat<eT>& X = tmp.M;
return internal_avg_log_p(X, gaus_id);
}
template<typename eT>
template<typename T1>
inline
uword
gmm_diag<eT>::assign(const T1& expr, const gmm_dist_mode& dist, typename enable_if<((is_arma_type<T1>::value) && (resolves_to_colvector<T1>::value == true))>::result* junk) const
{
arma_extra_debug_sigprint();
arma_ignore(junk);
const quasi_unwrap<T1> tmp(expr);
const Mat<eT>& X = tmp.M;
return internal_scalar_assign(X, dist);
}
template<typename eT>
template<typename T1>
inline
urowvec
gmm_diag<eT>::assign(const T1& expr, const gmm_dist_mode& dist, typename enable_if<((is_arma_type<T1>::value) && (resolves_to_colvector<T1>::value == false))>::result* junk) const
{
arma_extra_debug_sigprint();
arma_ignore(junk);
urowvec out;
const quasi_unwrap<T1> tmp(expr);
const Mat<eT>& X = tmp.M;
internal_vec_assign(out, X, dist);
return out;
}
template<typename eT>
template<typename T1>
inline
urowvec
gmm_diag<eT>::raw_hist(const Base<eT,T1>& expr, const gmm_dist_mode& dist_mode) const
{
arma_extra_debug_sigprint();
const unwrap<T1> tmp(expr.get_ref());
const Mat<eT>& X = tmp.M;
arma_debug_check( (X.n_rows != means.n_rows), "gmm_diag::raw_hist(): incompatible dimensions" );
arma_debug_check( ((dist_mode != eucl_dist) && (dist_mode != prob_dist)), "gmm_diag::raw_hist(): unsupported distance mode" );
urowvec hist;
internal_raw_hist(hist, X, dist_mode);
return hist;
}
template<typename eT>
template<typename T1>
inline
Row<eT>
gmm_diag<eT>::norm_hist(const Base<eT,T1>& expr, const gmm_dist_mode& dist_mode) const
{
arma_extra_debug_sigprint();
const unwrap<T1> tmp(expr.get_ref());
const Mat<eT>& X = tmp.M;
arma_debug_check( (X.n_rows != means.n_rows), "gmm_diag::norm_hist(): incompatible dimensions" );
arma_debug_check( ((dist_mode != eucl_dist) && (dist_mode != prob_dist)), "gmm_diag::norm_hist(): unsupported distance mode" );
urowvec hist;
internal_raw_hist(hist, X, dist_mode);
const uword hist_n_elem = hist.n_elem;
const uword* hist_mem = hist.memptr();
eT acc = eT(0);
for(uword i=0; i<hist_n_elem; ++i) { acc += eT(hist_mem[i]); }
if(acc == eT(0)) { acc = eT(1); }
Row<eT> out(hist_n_elem);
eT* out_mem = out.memptr();
for(uword i=0; i<hist_n_elem; ++i) { out_mem[i] = eT(hist_mem[i]) / acc; }
return out;
}
template<typename eT>
template<typename T1>
inline
bool
gmm_diag<eT>::learn
(
const Base<eT,T1>& data,
const uword N_gaus,
const gmm_dist_mode& dist_mode,
const gmm_seed_mode& seed_mode,
const uword km_iter,
const uword em_iter,
const eT var_floor,
const bool print_mode
)
{
arma_extra_debug_sigprint();
const bool dist_mode_ok = (dist_mode == eucl_dist) || (dist_mode == maha_dist);
const bool seed_mode_ok = \
(seed_mode == keep_existing)
|| (seed_mode == static_subset)
|| (seed_mode == static_spread)
|| (seed_mode == random_subset)
|| (seed_mode == random_spread);
arma_debug_check( (dist_mode_ok == false), "gmm_diag::learn(): dist_mode must be eucl_dist or maha_dist" );
arma_debug_check( (seed_mode_ok == false), "gmm_diag::learn(): unknown seed_mode" );
arma_debug_check( (var_floor < eT(0) ), "gmm_diag::learn(): variance floor is negative" );
const unwrap<T1> tmp_X(data.get_ref());
const Mat<eT>& X = tmp_X.M;
if(X.is_empty() ) { arma_debug_warn("gmm_diag::learn(): given matrix is empty" ); return false; }
if(X.is_finite() == false) { arma_debug_warn("gmm_diag::learn(): given matrix has non-finite values"); return false; }
if(N_gaus == 0) { reset(); return true; }
if(dist_mode == maha_dist)
{
mah_aux = var(X,1,1);
const uword mah_aux_n_elem = mah_aux.n_elem;
eT* mah_aux_mem = mah_aux.memptr();
for(uword i=0; i < mah_aux_n_elem; ++i)
{
const eT val = mah_aux_mem[i];
mah_aux_mem[i] = ((val != eT(0)) && arma_isfinite(val)) ? eT(1) / val : eT(1);
}
}
// copy current model, in case of failure by k-means and/or EM
const gmm_diag<eT> orig = (*this);
// initial means
if(seed_mode == keep_existing)
{
if(means.is_empty() ) { arma_debug_warn("gmm_diag::learn(): no existing means" ); return false; }
if(X.n_rows != means.n_rows) { arma_debug_warn("gmm_diag::learn(): dimensionality mismatch"); return false; }
// TODO: also check for number of vectors?
}
else
{
if(X.n_cols < N_gaus) { arma_debug_warn("gmm_diag::learn(): number of vectors is less than number of gaussians"); return false; }
reset(X.n_rows, N_gaus);
if(print_mode) { get_cout_stream() << "gmm_diag::learn(): generating initial means\n"; get_cout_stream().flush(); }
if(dist_mode == eucl_dist) { generate_initial_means<1>(X, seed_mode); }
else if(dist_mode == maha_dist) { generate_initial_means<2>(X, seed_mode); }
}
// k-means
if(km_iter > 0)
{
const arma_ostream_state stream_state(get_cout_stream());
bool status = false;
if(dist_mode == eucl_dist) { status = km_iterate<1>(X, km_iter, print_mode, "gmm_diag::learn(): k-means"); }
else if(dist_mode == maha_dist) { status = km_iterate<2>(X, km_iter, print_mode, "gmm_diag::learn(): k-means"); }
stream_state.restore(get_cout_stream());
if(status == false) { arma_debug_warn("gmm_diag::learn(): k-means algorithm failed; not enough data, or too many gaussians requested"); init(orig); return false; }
}
// initial dcovs
const eT var_floor_actual = (eT(var_floor) > eT(0)) ? eT(var_floor) : std::numeric_limits<eT>::min();
if(seed_mode != keep_existing)
{
if(print_mode) { get_cout_stream() << "gmm_diag::learn(): generating initial covariances\n"; get_cout_stream().flush(); }
if(dist_mode == eucl_dist) { generate_initial_params<1>(X, var_floor_actual); }
else if(dist_mode == maha_dist) { generate_initial_params<2>(X, var_floor_actual); }
}
// EM algorithm
if(em_iter > 0)
{
const arma_ostream_state stream_state(get_cout_stream());
const bool status = em_iterate(X, em_iter, var_floor_actual, print_mode);
stream_state.restore(get_cout_stream());
if(status == false) { arma_debug_warn("gmm_diag::learn(): EM algorithm failed"); init(orig); return false; }
}
mah_aux.reset();
init_constants();
return true;
}
template<typename eT>
template<typename T1>
inline
bool
gmm_diag<eT>::kmeans_wrapper
(
Mat<eT>& user_means,
const Base<eT,T1>& data,
const uword N_gaus,
const gmm_seed_mode& seed_mode,
const uword km_iter,
const bool print_mode
)
{
arma_extra_debug_sigprint();
const bool seed_mode_ok = \
(seed_mode == keep_existing)
|| (seed_mode == static_subset)
|| (seed_mode == static_spread)
|| (seed_mode == random_subset)
|| (seed_mode == random_spread);
arma_debug_check( (seed_mode_ok == false), "kmeans(): unknown seed_mode" );
const unwrap<T1> tmp_X(data.get_ref());
const Mat<eT>& X = tmp_X.M;
if(X.is_empty() ) { arma_debug_warn("kmeans(): given matrix is empty" ); return false; }
if(X.is_finite() == false) { arma_debug_warn("kmeans(): given matrix has non-finite values"); return false; }
if(N_gaus == 0) { reset(); return true; }
// initial means
if(seed_mode == keep_existing)
{
access::rw(means) = user_means;
if(means.is_empty() ) { arma_debug_warn("kmeans(): no existing means" ); return false; }
if(X.n_rows != means.n_rows) { arma_debug_warn("kmeans(): dimensionality mismatch"); return false; }
// TODO: also check for number of vectors?
}
else
{
if(X.n_cols < N_gaus) { arma_debug_warn("kmeans(): number of vectors is less than number of means"); return false; }
access::rw(means).zeros(X.n_rows, N_gaus);
if(print_mode) { get_cout_stream() << "kmeans(): generating initial means\n"; }
generate_initial_means<1>(X, seed_mode);
}
// k-means
if(km_iter > 0)
{
const arma_ostream_state stream_state(get_cout_stream());
bool status = false;
status = km_iterate<1>(X, km_iter, print_mode, "kmeans()");
stream_state.restore(get_cout_stream());
if(status == false) { arma_debug_warn("kmeans(): clustering failed; not enough data, or too many means requested"); return false; }
}
return true;
}
//
//
//
template<typename eT>
inline
void
gmm_diag<eT>::init(const gmm_diag<eT>& x)
{
arma_extra_debug_sigprint();
gmm_diag<eT>& t = *this;
if(&t != &x)
{
access::rw(t.means) = x.means;
access::rw(t.dcovs) = x.dcovs;
access::rw(t.hefts) = x.hefts;
init_constants();
}
}
template<typename eT>
inline
void
gmm_diag<eT>::init(const gmm_full<eT>& x)
{
arma_extra_debug_sigprint();
access::rw(hefts) = x.hefts;
access::rw(means) = x.means;
const uword N_dims = x.means.n_rows;
const uword N_gaus = x.means.n_cols;
access::rw(dcovs).zeros(N_dims,N_gaus);
for(uword g=0; g < N_gaus; ++g)
{
const Mat<eT>& fcov = x.fcovs.slice(g);
eT* dcov_mem = access::rw(dcovs).colptr(g);
for(uword d=0; d < N_dims; ++d)
{
dcov_mem[d] = fcov.at(d,d);
}
}
init_constants();
}
template<typename eT>
inline
void
gmm_diag<eT>::init(const uword in_n_dims, const uword in_n_gaus)
{
arma_extra_debug_sigprint();
access::rw(means).zeros(in_n_dims, in_n_gaus);
access::rw(dcovs).ones(in_n_dims, in_n_gaus);
access::rw(hefts).set_size(in_n_gaus);
access::rw(hefts).fill(eT(1) / eT(in_n_gaus));
init_constants();
}
template<typename eT>
inline
void
gmm_diag<eT>::init_constants()
{
arma_extra_debug_sigprint();
const uword N_dims = means.n_rows;
const uword N_gaus = means.n_cols;
//
inv_dcovs.copy_size(dcovs);
const eT* dcovs_mem = dcovs.memptr();
eT* inv_dcovs_mem = inv_dcovs.memptr();
const uword dcovs_n_elem = dcovs.n_elem;
for(uword i=0; i < dcovs_n_elem; ++i)
{
inv_dcovs_mem[i] = eT(1) / (std::max)( dcovs_mem[i], std::numeric_limits<eT>::min() );
}
//
const eT tmp = (eT(N_dims)/eT(2)) * std::log(eT(2) * Datum<eT>::pi);
log_det_etc.set_size(N_gaus);
for(uword g=0; g < N_gaus; ++g)
{
const eT* dcovs_colmem = dcovs.colptr(g);
eT log_det_val = eT(0);
for(uword d=0; d < N_dims; ++d)
{
log_det_val += std::log( (std::max)( dcovs_colmem[d], std::numeric_limits<eT>::min() ) );
}
log_det_etc[g] = eT(-1) * ( tmp + eT(0.5) * log_det_val );
}
//
eT* hefts_mem = access::rw(hefts).memptr();
for(uword g=0; g < N_gaus; ++g)
{
hefts_mem[g] = (std::max)( hefts_mem[g], std::numeric_limits<eT>::min() );
}
log_hefts = log(hefts);
}
template<typename eT>
inline
umat
gmm_diag<eT>::internal_gen_boundaries(const uword N) const
{
arma_extra_debug_sigprint();
#if defined(ARMA_USE_OPENMP)
const uword n_threads_avail = (omp_in_parallel()) ? uword(1) : uword(omp_get_max_threads());
const uword n_threads = (n_threads_avail > 0) ? ( (n_threads_avail <= N) ? n_threads_avail : 1 ) : 1;
#else
static const uword n_threads = 1;
#endif
// get_cout_stream() << "gmm_diag::internal_gen_boundaries(): n_threads: " << n_threads << '\n';
umat boundaries(2, n_threads);
if(N > 0)
{
const uword chunk_size = N / n_threads;
uword count = 0;
for(uword t=0; t<n_threads; t++)
{
boundaries.at(0,t) = count;
count += chunk_size;
boundaries.at(1,t) = count-1;
}
boundaries.at(1,n_threads-1) = N - 1;
}
else
{
boundaries.zeros();
}
// get_cout_stream() << "gmm_diag::internal_gen_boundaries(): boundaries: " << '\n' << boundaries << '\n';
return boundaries;
}
template<typename eT>
arma_hot
inline
eT
gmm_diag<eT>::internal_scalar_log_p(const eT* x) const
{
arma_extra_debug_sigprint();
const eT* log_hefts_mem = log_hefts.mem;
const uword N_gaus = means.n_cols;
if(N_gaus > 0)
{
eT log_sum = internal_scalar_log_p(x, 0) + log_hefts_mem[0];
for(uword g=1; g < N_gaus; ++g)
{
const eT tmp = internal_scalar_log_p(x, g) + log_hefts_mem[g];
log_sum = log_add_exp(log_sum, tmp);
}
return log_sum;
}
else
{
return -Datum<eT>::inf;
}
}
template<typename eT>
arma_hot
inline
eT
gmm_diag<eT>::internal_scalar_log_p(const eT* x, const uword g) const
{
arma_extra_debug_sigprint();
const eT* mean = means.colptr(g);
const eT* inv_dcov = inv_dcovs.colptr(g);
const uword N_dims = means.n_rows;
eT val_i = eT(0);
eT val_j = eT(0);
uword i,j;
for(i=0, j=1; j<N_dims; i+=2, j+=2)
{
eT tmp_i = x[i];
eT tmp_j = x[j];
tmp_i -= mean[i];
tmp_j -= mean[j];
val_i += (tmp_i*tmp_i) * inv_dcov[i];
val_j += (tmp_j*tmp_j) * inv_dcov[j];
}
if(i < N_dims)
{
const eT tmp = x[i] - mean[i];
val_i += (tmp*tmp) * inv_dcov[i];
}
return eT(-0.5)*(val_i + val_j) + log_det_etc.mem[g];
}
template<typename eT>
inline
Row<eT>
gmm_diag<eT>::internal_vec_log_p(const Mat<eT>& X) const
{
arma_extra_debug_sigprint();
arma_debug_check( (X.n_rows != means.n_rows), "gmm_diag::log_p(): incompatible dimensions" );
const uword N = X.n_cols;
Row<eT> out(N);
if(N > 0)
{
#if defined(ARMA_USE_OPENMP)
{
const umat boundaries = internal_gen_boundaries(N);
const uword n_threads = boundaries.n_cols;
#pragma omp parallel for schedule(static)
for(uword t=0; t < n_threads; ++t)
{
const uword start_index = boundaries.at(0,t);
const uword end_index = boundaries.at(1,t);
eT* out_mem = out.memptr();
for(uword i=start_index; i <= end_index; ++i)
{
out_mem[i] = internal_scalar_log_p( X.colptr(i) );
}
}
}
#else
{
eT* out_mem = out.memptr();
for(uword i=0; i < N; ++i)
{
out_mem[i] = internal_scalar_log_p( X.colptr(i) );
}
}
#endif
}
return out;
}
template<typename eT>
inline
Row<eT>
gmm_diag<eT>::internal_vec_log_p(const Mat<eT>& X, const uword gaus_id) const
{
arma_extra_debug_sigprint();
arma_debug_check( (X.n_rows != means.n_rows), "gmm_diag::log_p(): incompatible dimensions" );
arma_debug_check( (gaus_id >= means.n_cols), "gmm_diag::log_p(): specified gaussian is out of range" );
const uword N = X.n_cols;
Row<eT> out(N);
if(N > 0)
{
#if defined(ARMA_USE_OPENMP)
{
const umat boundaries = internal_gen_boundaries(N);
const uword n_threads = boundaries.n_cols;
#pragma omp parallel for schedule(static)
for(uword t=0; t < n_threads; ++t)
{
const uword start_index = boundaries.at(0,t);
const uword end_index = boundaries.at(1,t);
eT* out_mem = out.memptr();
for(uword i=start_index; i <= end_index; ++i)
{
out_mem[i] = internal_scalar_log_p( X.colptr(i), gaus_id );
}
}
}
#else
{
eT* out_mem = out.memptr();
for(uword i=0; i < N; ++i)
{
out_mem[i] = internal_scalar_log_p( X.colptr(i), gaus_id );
}
}
#endif
}
return out;
}
template<typename eT>
inline
eT
gmm_diag<eT>::internal_sum_log_p(const Mat<eT>& X) const
{
arma_extra_debug_sigprint();
arma_debug_check( (X.n_rows != means.n_rows), "gmm_diag::sum_log_p(): incompatible dimensions" );
const uword N = X.n_cols;
if(N == 0) { return (-Datum<eT>::inf); }
#if defined(ARMA_USE_OPENMP)
{
const umat boundaries = internal_gen_boundaries(N);
const uword n_threads = boundaries.n_cols;
Col<eT> t_accs(n_threads, fill::zeros);
#pragma omp parallel for schedule(static)
for(uword t=0; t < n_threads; ++t)
{
const uword start_index = boundaries.at(0,t);
const uword end_index = boundaries.at(1,t);
eT t_acc = eT(0);
for(uword i=start_index; i <= end_index; ++i)
{
t_acc += internal_scalar_log_p( X.colptr(i) );
}
t_accs[t] = t_acc;
}
return eT(accu(t_accs));
}
#else
{
eT acc = eT(0);
for(uword i=0; i<N; ++i)
{
acc += internal_scalar_log_p( X.colptr(i) );
}
return acc;
}
#endif
}
template<typename eT>
inline
eT
gmm_diag<eT>::internal_sum_log_p(const Mat<eT>& X, const uword gaus_id) const
{
arma_extra_debug_sigprint();
arma_debug_check( (X.n_rows != means.n_rows), "gmm_diag::sum_log_p(): incompatible dimensions" );
arma_debug_check( (gaus_id >= means.n_cols), "gmm_diag::sum_log_p(): specified gaussian is out of range" );
const uword N = X.n_cols;
if(N == 0) { return (-Datum<eT>::inf); }
#if defined(ARMA_USE_OPENMP)
{
const umat boundaries = internal_gen_boundaries(N);
const uword n_threads = boundaries.n_cols;
Col<eT> t_accs(n_threads, fill::zeros);
#pragma omp parallel for schedule(static)
for(uword t=0; t < n_threads; ++t)
{
const uword start_index = boundaries.at(0,t);
const uword end_index = boundaries.at(1,t);
eT t_acc = eT(0);
for(uword i=start_index; i <= end_index; ++i)
{
t_acc += internal_scalar_log_p( X.colptr(i), gaus_id );
}
t_accs[t] = t_acc;
}
return eT(accu(t_accs));
}
#else
{
eT acc = eT(0);
for(uword i=0; i<N; ++i)
{
acc += internal_scalar_log_p( X.colptr(i), gaus_id );
}
return acc;
}
#endif
}
template<typename eT>
inline
eT
gmm_diag<eT>::internal_avg_log_p(const Mat<eT>& X) const
{
arma_extra_debug_sigprint();
arma_debug_check( (X.n_rows != means.n_rows), "gmm_diag::avg_log_p(): incompatible dimensions" );
const uword N = X.n_cols;
if(N == 0) { return (-Datum<eT>::inf); }
#if defined(ARMA_USE_OPENMP)
{
const umat boundaries = internal_gen_boundaries(N);
const uword n_threads = boundaries.n_cols;
field< running_mean_scalar<eT> > t_running_means(n_threads);
#pragma omp parallel for schedule(static)
for(uword t=0; t < n_threads; ++t)
{
const uword start_index = boundaries.at(0,t);
const uword end_index = boundaries.at(1,t);
running_mean_scalar<eT>& current_running_mean = t_running_means[t];
for(uword i=start_index; i <= end_index; ++i)
{
current_running_mean( internal_scalar_log_p( X.colptr(i) ) );
}
}
eT avg = eT(0);
for(uword t=0; t < n_threads; ++t)
{
running_mean_scalar<eT>& current_running_mean = t_running_means[t];
const eT w = eT(current_running_mean.count()) / eT(N);
avg += w * current_running_mean.mean();
}
return avg;
}
#else
{
running_mean_scalar<eT> running_mean;
for(uword i=0; i<N; ++i)
{
running_mean( internal_scalar_log_p( X.colptr(i) ) );
}
return running_mean.mean();
}
#endif
}
template<typename eT>
inline
eT
gmm_diag<eT>::internal_avg_log_p(const Mat<eT>& X, const uword gaus_id) const
{
arma_extra_debug_sigprint();
arma_debug_check( (X.n_rows != means.n_rows), "gmm_diag::avg_log_p(): incompatible dimensions" );
arma_debug_check( (gaus_id >= means.n_cols), "gmm_diag::avg_log_p(): specified gaussian is out of range" );
const uword N = X.n_cols;
if(N == 0) { return (-Datum<eT>::inf); }
#if defined(ARMA_USE_OPENMP)
{
const umat boundaries = internal_gen_boundaries(N);
const uword n_threads = boundaries.n_cols;
field< running_mean_scalar<eT> > t_running_means(n_threads);
#pragma omp parallel for schedule(static)
for(uword t=0; t < n_threads; ++t)
{
const uword start_index = boundaries.at(0,t);
const uword end_index = boundaries.at(1,t);
running_mean_scalar<eT>& current_running_mean = t_running_means[t];
for(uword i=start_index; i <= end_index; ++i)
{
current_running_mean( internal_scalar_log_p( X.colptr(i), gaus_id) );
}
}
eT avg = eT(0);
for(uword t=0; t < n_threads; ++t)
{
running_mean_scalar<eT>& current_running_mean = t_running_means[t];
const eT w = eT(current_running_mean.count()) / eT(N);
avg += w * current_running_mean.mean();
}
return avg;
}
#else
{
running_mean_scalar<eT> running_mean;
for(uword i=0; i<N; ++i)
{
running_mean( internal_scalar_log_p( X.colptr(i), gaus_id ) );
}
return running_mean.mean();
}
#endif
}
template<typename eT>
inline
uword
gmm_diag<eT>::internal_scalar_assign(const Mat<eT>& X, const gmm_dist_mode& dist_mode) const
{
arma_extra_debug_sigprint();
const uword N_dims = means.n_rows;
const uword N_gaus = means.n_cols;
arma_debug_check( (X.n_rows != N_dims), "gmm_diag::assign(): incompatible dimensions" );
arma_debug_check( (N_gaus == 0), "gmm_diag::assign(): model has no means" );
const eT* X_mem = X.colptr(0);
if(dist_mode == eucl_dist)
{
eT best_dist = Datum<eT>::inf;
uword best_g = 0;
for(uword g=0; g < N_gaus; ++g)
{
const eT tmp_dist = distance<eT,1>::eval(N_dims, X_mem, means.colptr(g), X_mem);
if(tmp_dist <= best_dist) { best_dist = tmp_dist; best_g = g; }
}
return best_g;
}
else
if(dist_mode == prob_dist)
{
const eT* log_hefts_mem = log_hefts.memptr();
eT best_p = -Datum<eT>::inf;
uword best_g = 0;
for(uword g=0; g < N_gaus; ++g)
{
const eT tmp_p = internal_scalar_log_p(X_mem, g) + log_hefts_mem[g];
if(tmp_p >= best_p) { best_p = tmp_p; best_g = g; }
}
return best_g;
}
else
{
arma_debug_check(true, "gmm_diag::assign(): unsupported distance mode");
}
return uword(0);
}
template<typename eT>
inline
void
gmm_diag<eT>::internal_vec_assign(urowvec& out, const Mat<eT>& X, const gmm_dist_mode& dist_mode) const
{
arma_extra_debug_sigprint();
const uword N_dims = means.n_rows;
const uword N_gaus = means.n_cols;
arma_debug_check( (X.n_rows != N_dims), "gmm_diag::assign(): incompatible dimensions" );
const uword X_n_cols = (N_gaus > 0) ? X.n_cols : 0;
out.set_size(1,X_n_cols);
uword* out_mem = out.memptr();
if(dist_mode == eucl_dist)
{
#if defined(ARMA_USE_OPENMP)
{
#pragma omp parallel for schedule(static)
for(uword i=0; i<X_n_cols; ++i)
{
const eT* X_colptr = X.colptr(i);
eT best_dist = Datum<eT>::inf;
uword best_g = 0;
for(uword g=0; g<N_gaus; ++g)
{
const eT tmp_dist = distance<eT,1>::eval(N_dims, X_colptr, means.colptr(g), X_colptr);
if(tmp_dist <= best_dist) { best_dist = tmp_dist; best_g = g; }
}
out_mem[i] = best_g;
}
}
#else
{
for(uword i=0; i<X_n_cols; ++i)
{
const eT* X_colptr = X.colptr(i);
eT best_dist = Datum<eT>::inf;
uword best_g = 0;
for(uword g=0; g<N_gaus; ++g)
{
const eT tmp_dist = distance<eT,1>::eval(N_dims, X_colptr, means.colptr(g), X_colptr);
if(tmp_dist <= best_dist) { best_dist = tmp_dist; best_g = g; }
}
out_mem[i] = best_g;
}
}
#endif
}
else
if(dist_mode == prob_dist)
{
#if defined(ARMA_USE_OPENMP)
{
const eT* log_hefts_mem = log_hefts.memptr();
#pragma omp parallel for schedule(static)
for(uword i=0; i<X_n_cols; ++i)
{
const eT* X_colptr = X.colptr(i);
eT best_p = -Datum<eT>::inf;
uword best_g = 0;
for(uword g=0; g<N_gaus; ++g)
{
const eT tmp_p = internal_scalar_log_p(X_colptr, g) + log_hefts_mem[g];
if(tmp_p >= best_p) { best_p = tmp_p; best_g = g; }
}
out_mem[i] = best_g;
}
}
#else
{
const eT* log_hefts_mem = log_hefts.memptr();
for(uword i=0; i<X_n_cols; ++i)
{
const eT* X_colptr = X.colptr(i);
eT best_p = -Datum<eT>::inf;
uword best_g = 0;
for(uword g=0; g<N_gaus; ++g)
{
const eT tmp_p = internal_scalar_log_p(X_colptr, g) + log_hefts_mem[g];
if(tmp_p >= best_p) { best_p = tmp_p; best_g = g; }
}
out_mem[i] = best_g;
}
}
#endif
}
else
{
arma_debug_check(true, "gmm_diag::assign(): unsupported distance mode");
}
}
template<typename eT>
inline
void
gmm_diag<eT>::internal_raw_hist(urowvec& hist, const Mat<eT>& X, const gmm_dist_mode& dist_mode) const
{
arma_extra_debug_sigprint();
const uword N_dims = means.n_rows;
const uword N_gaus = means.n_cols;
const uword X_n_cols = X.n_cols;
hist.zeros(N_gaus);
if(N_gaus == 0) { return; }
#if defined(ARMA_USE_OPENMP)
{
const umat boundaries = internal_gen_boundaries(X_n_cols);
const uword n_threads = boundaries.n_cols;
field<urowvec> thread_hist(n_threads);
for(uword t=0; t < n_threads; ++t) { thread_hist(t).zeros(N_gaus); }
if(dist_mode == eucl_dist)
{
#pragma omp parallel for schedule(static)
for(uword t=0; t < n_threads; ++t)
{
uword* thread_hist_mem = thread_hist(t).memptr();
const uword start_index = boundaries.at(0,t);
const uword end_index = boundaries.at(1,t);
for(uword i=start_index; i <= end_index; ++i)
{
const eT* X_colptr = X.colptr(i);
eT best_dist = Datum<eT>::inf;
uword best_g = 0;
for(uword g=0; g < N_gaus; ++g)
{
const eT tmp_dist = distance<eT,1>::eval(N_dims, X_colptr, means.colptr(g), X_colptr);
if(tmp_dist <= best_dist) { best_dist = tmp_dist; best_g = g; }
}
thread_hist_mem[best_g]++;
}
}
}
else
if(dist_mode == prob_dist)
{
const eT* log_hefts_mem = log_hefts.memptr();
#pragma omp parallel for schedule(static)
for(uword t=0; t < n_threads; ++t)
{
uword* thread_hist_mem = thread_hist(t).memptr();
const uword start_index = boundaries.at(0,t);
const uword end_index = boundaries.at(1,t);
for(uword i=start_index; i <= end_index; ++i)
{
const eT* X_colptr = X.colptr(i);
eT best_p = -Datum<eT>::inf;
uword best_g = 0;
for(uword g=0; g < N_gaus; ++g)
{
const eT tmp_p = internal_scalar_log_p(X_colptr, g) + log_hefts_mem[g];
if(tmp_p >= best_p) { best_p = tmp_p; best_g = g; }
}
thread_hist_mem[best_g]++;
}
}
}
// reduction
hist = thread_hist(0);
for(uword t=1; t < n_threads; ++t)
{
hist += thread_hist(t);
}
}
#else
{
uword* hist_mem = hist.memptr();
if(dist_mode == eucl_dist)
{
for(uword i=0; i<X_n_cols; ++i)
{
const eT* X_colptr = X.colptr(i);
eT best_dist = Datum<eT>::inf;
uword best_g = 0;
for(uword g=0; g < N_gaus; ++g)
{
const eT tmp_dist = distance<eT,1>::eval(N_dims, X_colptr, means.colptr(g), X_colptr);
if(tmp_dist <= best_dist) { best_dist = tmp_dist; best_g = g; }
}
hist_mem[best_g]++;
}
}
else
if(dist_mode == prob_dist)
{
const eT* log_hefts_mem = log_hefts.memptr();
for(uword i=0; i<X_n_cols; ++i)
{
const eT* X_colptr = X.colptr(i);
eT best_p = -Datum<eT>::inf;
uword best_g = 0;
for(uword g=0; g < N_gaus; ++g)
{
const eT tmp_p = internal_scalar_log_p(X_colptr, g) + log_hefts_mem[g];
if(tmp_p >= best_p) { best_p = tmp_p; best_g = g; }
}
hist_mem[best_g]++;
}
}
}
#endif
}
template<typename eT>
template<uword dist_id>
inline
void
gmm_diag<eT>::generate_initial_means(const Mat<eT>& X, const gmm_seed_mode& seed_mode)
{
arma_extra_debug_sigprint();
const uword N_dims = means.n_rows;
const uword N_gaus = means.n_cols;
if( (seed_mode == static_subset) || (seed_mode == random_subset) )
{
uvec initial_indices;
if(seed_mode == static_subset) { initial_indices = linspace<uvec>(0, X.n_cols-1, N_gaus); }
else if(seed_mode == random_subset) { initial_indices = randperm<uvec>(X.n_cols, N_gaus); }
// initial_indices.print("initial_indices:");
access::rw(means) = X.cols(initial_indices);
}
else
if( (seed_mode == static_spread) || (seed_mode == random_spread) )
{
// going through all of the samples can be extremely time consuming;
// instead, if there are enough samples, randomly choose samples with probability 0.1
const bool use_sampling = ((X.n_cols/uword(100)) > N_gaus);
const uword step = (use_sampling) ? uword(10) : uword(1);
uword start_index = 0;
if(seed_mode == static_spread) { start_index = X.n_cols / 2; }
else if(seed_mode == random_spread) { start_index = as_scalar(randi<uvec>(1, distr_param(0,X.n_cols-1))); }
access::rw(means).col(0) = X.unsafe_col(start_index);
const eT* mah_aux_mem = mah_aux.memptr();
running_stat<double> rs;
for(uword g=1; g < N_gaus; ++g)
{
eT max_dist = eT(0);
uword best_i = uword(0);
uword start_i = uword(0);
if(use_sampling)
{
uword start_i_proposed = uword(0);
if(seed_mode == static_spread) { start_i_proposed = g % uword(10); }
if(seed_mode == random_spread) { start_i_proposed = as_scalar(randi<uvec>(1, distr_param(0,9))); }
if(start_i_proposed < X.n_cols) { start_i = start_i_proposed; }
}
for(uword i=start_i; i < X.n_cols; i += step)
{
rs.reset();
const eT* X_colptr = X.colptr(i);
bool ignore_i = false;
// find the average distance between sample i and the means so far
for(uword h = 0; h < g; ++h)
{
const eT dist = distance<eT,dist_id>::eval(N_dims, X_colptr, means.colptr(h), mah_aux_mem);
// ignore sample already selected as a mean
if(dist == eT(0)) { ignore_i = true; break; }
else { rs(dist); }
}
if( (rs.mean() >= max_dist) && (ignore_i == false))
{
max_dist = eT(rs.mean()); best_i = i;
}
}
// set the mean to the sample that is the furthest away from the means so far
access::rw(means).col(g) = X.unsafe_col(best_i);
}
}
// get_cout_stream() << "generate_initial_means():" << '\n';
// means.print();
}
template<typename eT>
template<uword dist_id>
inline
void
gmm_diag<eT>::generate_initial_params(const Mat<eT>& X, const eT var_floor)
{
arma_extra_debug_sigprint();
const uword N_dims = means.n_rows;
const uword N_gaus = means.n_cols;
const eT* mah_aux_mem = mah_aux.memptr();
const uword X_n_cols = X.n_cols;
if(X_n_cols == 0) { return; }
// as the covariances are calculated via accumulators,
// the means also need to be calculated via accumulators to ensure numerical consistency
Mat<eT> acc_means(N_dims, N_gaus, fill::zeros);
Mat<eT> acc_dcovs(N_dims, N_gaus, fill::zeros);
Row<uword> acc_hefts(N_gaus, fill::zeros);
uword* acc_hefts_mem = acc_hefts.memptr();
#if defined(ARMA_USE_OPENMP)
{
const umat boundaries = internal_gen_boundaries(X_n_cols);
const uword n_threads = boundaries.n_cols;
field< Mat<eT> > t_acc_means(n_threads);
field< Mat<eT> > t_acc_dcovs(n_threads);
field< Row<uword> > t_acc_hefts(n_threads);
for(uword t=0; t < n_threads; ++t)
{
t_acc_means(t).zeros(N_dims, N_gaus);
t_acc_dcovs(t).zeros(N_dims, N_gaus);
t_acc_hefts(t).zeros(N_gaus);
}
#pragma omp parallel for schedule(static)
for(uword t=0; t < n_threads; ++t)
{
uword* t_acc_hefts_mem = t_acc_hefts(t).memptr();
const uword start_index = boundaries.at(0,t);
const uword end_index = boundaries.at(1,t);
for(uword i=start_index; i <= end_index; ++i)
{
const eT* X_colptr = X.colptr(i);
eT min_dist = Datum<eT>::inf;
uword best_g = 0;
for(uword g=0; g<N_gaus; ++g)
{
const eT dist = distance<eT,dist_id>::eval(N_dims, X_colptr, means.colptr(g), mah_aux_mem);
if(dist < min_dist) { min_dist = dist; best_g = g; }
}
eT* t_acc_mean = t_acc_means(t).colptr(best_g);
eT* t_acc_dcov = t_acc_dcovs(t).colptr(best_g);
for(uword d=0; d<N_dims; ++d)
{
const eT x_d = X_colptr[d];
t_acc_mean[d] += x_d;
t_acc_dcov[d] += x_d*x_d;
}
t_acc_hefts_mem[best_g]++;
}
}
// reduction
acc_means = t_acc_means(0);
acc_dcovs = t_acc_dcovs(0);
acc_hefts = t_acc_hefts(0);
for(uword t=1; t < n_threads; ++t)
{
acc_means += t_acc_means(t);
acc_dcovs += t_acc_dcovs(t);
acc_hefts += t_acc_hefts(t);
}
}
#else
{
for(uword i=0; i<X_n_cols; ++i)
{
const eT* X_colptr = X.colptr(i);
eT min_dist = Datum<eT>::inf;
uword best_g = 0;
for(uword g=0; g<N_gaus; ++g)
{
const eT dist = distance<eT,dist_id>::eval(N_dims, X_colptr, means.colptr(g), mah_aux_mem);
if(dist < min_dist) { min_dist = dist; best_g = g; }
}
eT* acc_mean = acc_means.colptr(best_g);
eT* acc_dcov = acc_dcovs.colptr(best_g);
for(uword d=0; d<N_dims; ++d)
{
const eT x_d = X_colptr[d];
acc_mean[d] += x_d;
acc_dcov[d] += x_d*x_d;
}
acc_hefts_mem[best_g]++;
}
}
#endif
eT* hefts_mem = access::rw(hefts).memptr();
for(uword g=0; g<N_gaus; ++g)
{
const eT* acc_mean = acc_means.colptr(g);
const eT* acc_dcov = acc_dcovs.colptr(g);
const uword acc_heft = acc_hefts_mem[g];
eT* mean = access::rw(means).colptr(g);
eT* dcov = access::rw(dcovs).colptr(g);
for(uword d=0; d<N_dims; ++d)
{
const eT tmp = acc_mean[d] / eT(acc_heft);
mean[d] = (acc_heft >= 1) ? tmp : eT(0);
dcov[d] = (acc_heft >= 2) ? eT((acc_dcov[d] / eT(acc_heft)) - (tmp*tmp)) : eT(var_floor);
}
hefts_mem[g] = eT(acc_heft) / eT(X_n_cols);
}
em_fix_params(var_floor);
}
//! multi-threaded implementation of k-means, inspired by MapReduce
template<typename eT>
template<uword dist_id>
inline
bool
gmm_diag<eT>::km_iterate(const Mat<eT>& X, const uword max_iter, const bool verbose, const char* signature)
{
arma_extra_debug_sigprint();
if(verbose)
{
get_cout_stream().unsetf(ios::showbase);
get_cout_stream().unsetf(ios::uppercase);
get_cout_stream().unsetf(ios::showpos);
get_cout_stream().unsetf(ios::scientific);
get_cout_stream().setf(ios::right);
get_cout_stream().setf(ios::fixed);
}
const uword X_n_cols = X.n_cols;
if(X_n_cols == 0) { return true; }
const uword N_dims = means.n_rows;
const uword N_gaus = means.n_cols;
const eT* mah_aux_mem = mah_aux.memptr();
Mat<eT> acc_means(N_dims, N_gaus, fill::zeros);
Row<uword> acc_hefts(N_gaus, fill::zeros);
Row<uword> last_indx(N_gaus, fill::zeros);
Mat<eT> new_means = means;
Mat<eT> old_means = means;
running_mean_scalar<eT> rs_delta;
#if defined(ARMA_USE_OPENMP)
const umat boundaries = internal_gen_boundaries(X_n_cols);
const uword n_threads = boundaries.n_cols;
field< Mat<eT> > t_acc_means(n_threads);
field< Row<uword> > t_acc_hefts(n_threads);
field< Row<uword> > t_last_indx(n_threads);
#else
const uword n_threads = 1;
#endif
if(verbose) { get_cout_stream() << signature << ": n_threads: " << n_threads << '\n'; get_cout_stream().flush(); }
for(uword iter=1; iter <= max_iter; ++iter)
{
#if defined(ARMA_USE_OPENMP)
{
for(uword t=0; t < n_threads; ++t)
{
t_acc_means(t).zeros(N_dims, N_gaus);
t_acc_hefts(t).zeros(N_gaus);
t_last_indx(t).zeros(N_gaus);
}
#pragma omp parallel for schedule(static)
for(uword t=0; t < n_threads; ++t)
{
Mat<eT>& t_acc_means_t = t_acc_means(t);
uword* t_acc_hefts_mem = t_acc_hefts(t).memptr();
uword* t_last_indx_mem = t_last_indx(t).memptr();
const uword start_index = boundaries.at(0,t);
const uword end_index = boundaries.at(1,t);
for(uword i=start_index; i <= end_index; ++i)
{
const eT* X_colptr = X.colptr(i);
eT min_dist = Datum<eT>::inf;
uword best_g = 0;
for(uword g=0; g<N_gaus; ++g)
{
const eT dist = distance<eT,dist_id>::eval(N_dims, X_colptr, old_means.colptr(g), mah_aux_mem);
if(dist < min_dist) { min_dist = dist; best_g = g; }
}
eT* t_acc_mean = t_acc_means_t.colptr(best_g);
for(uword d=0; d<N_dims; ++d) { t_acc_mean[d] += X_colptr[d]; }
t_acc_hefts_mem[best_g]++;
t_last_indx_mem[best_g] = i;
}
}
// reduction
acc_means = t_acc_means(0);
acc_hefts = t_acc_hefts(0);
for(uword t=1; t < n_threads; ++t)
{
acc_means += t_acc_means(t);
acc_hefts += t_acc_hefts(t);
}
for(uword g=0; g < N_gaus; ++g)
for(uword t=0; t < n_threads; ++t)
{
if( t_acc_hefts(t)(g) >= 1 ) { last_indx(g) = t_last_indx(t)(g); }
}
}
#else
{
uword* acc_hefts_mem = acc_hefts.memptr();
uword* last_indx_mem = last_indx.memptr();
for(uword i=0; i < X_n_cols; ++i)
{
const eT* X_colptr = X.colptr(i);
eT min_dist = Datum<eT>::inf;
uword best_g = 0;
for(uword g=0; g<N_gaus; ++g)
{
const eT dist = distance<eT,dist_id>::eval(N_dims, X_colptr, old_means.colptr(g), mah_aux_mem);
if(dist < min_dist) { min_dist = dist; best_g = g; }
}
eT* acc_mean = acc_means.colptr(best_g);
for(uword d=0; d<N_dims; ++d) { acc_mean[d] += X_colptr[d]; }
acc_hefts_mem[best_g]++;
last_indx_mem[best_g] = i;
}
}
#endif
// generate new means
uword* acc_hefts_mem = acc_hefts.memptr();
for(uword g=0; g < N_gaus; ++g)
{
const eT* acc_mean = acc_means.colptr(g);
const uword acc_heft = acc_hefts_mem[g];
eT* new_mean = access::rw(new_means).colptr(g);
for(uword d=0; d<N_dims; ++d)
{
new_mean[d] = (acc_heft >= 1) ? (acc_mean[d] / eT(acc_heft)) : eT(0);
}
}
// heuristics to resurrect dead means
const uvec dead_gs = find(acc_hefts == uword(0));
if(dead_gs.n_elem > 0)
{
if(verbose) { get_cout_stream() << signature << ": recovering from dead means\n"; get_cout_stream().flush(); }
uword* last_indx_mem = last_indx.memptr();
const uvec live_gs = sort( find(acc_hefts >= uword(2)), "descend" );
if(live_gs.n_elem == 0) { return false; }
uword live_gs_count = 0;
for(uword dead_gs_count = 0; dead_gs_count < dead_gs.n_elem; ++dead_gs_count)
{
const uword dead_g_id = dead_gs(dead_gs_count);
uword proposed_i = 0;
if(live_gs_count < live_gs.n_elem)
{
const uword live_g_id = live_gs(live_gs_count); ++live_gs_count;
if(live_g_id == dead_g_id) { return false; }
// recover by using a sample from a known good mean
proposed_i = last_indx_mem[live_g_id];
}
else
{
// recover by using a randomly seleced sample (last resort)
proposed_i = as_scalar(randi<uvec>(1, distr_param(0,X_n_cols-1)));
}
if(proposed_i >= X_n_cols) { return false; }
new_means.col(dead_g_id) = X.col(proposed_i);
}
}
rs_delta.reset();
for(uword g=0; g < N_gaus; ++g)
{
rs_delta( distance<eT,dist_id>::eval(N_dims, old_means.colptr(g), new_means.colptr(g), mah_aux_mem) );
}
if(verbose)
{
get_cout_stream() << signature << ": iteration: ";
get_cout_stream().unsetf(ios::scientific);
get_cout_stream().setf(ios::fixed);
get_cout_stream().width(std::streamsize(4));
get_cout_stream() << iter;
get_cout_stream() << " delta: ";
get_cout_stream().unsetf(ios::fixed);
//get_cout_stream().setf(ios::scientific);
get_cout_stream() << rs_delta.mean() << '\n';
get_cout_stream().flush();
}
arma::swap(old_means, new_means);
if(rs_delta.mean() <= Datum<eT>::eps) { break; }
}
access::rw(means) = old_means;
if(means.is_finite() == false) { return false; }
return true;
}
//! multi-threaded implementation of Expectation-Maximisation, inspired by MapReduce
template<typename eT>
inline
bool
gmm_diag<eT>::em_iterate(const Mat<eT>& X, const uword max_iter, const eT var_floor, const bool verbose)
{
arma_extra_debug_sigprint();
if(X.n_cols == 0) { return true; }
const uword N_dims = means.n_rows;
const uword N_gaus = means.n_cols;
if(verbose)
{
get_cout_stream().unsetf(ios::showbase);
get_cout_stream().unsetf(ios::uppercase);
get_cout_stream().unsetf(ios::showpos);
get_cout_stream().unsetf(ios::scientific);
get_cout_stream().setf(ios::right);
get_cout_stream().setf(ios::fixed);
}
const umat boundaries = internal_gen_boundaries(X.n_cols);
const uword n_threads = boundaries.n_cols;
field< Mat<eT> > t_acc_means(n_threads);
field< Mat<eT> > t_acc_dcovs(n_threads);
field< Col<eT> > t_acc_norm_lhoods(n_threads);
field< Col<eT> > t_gaus_log_lhoods(n_threads);
Col<eT> t_progress_log_lhood(n_threads);
for(uword t=0; t<n_threads; t++)
{
t_acc_means[t].set_size(N_dims, N_gaus);
t_acc_dcovs[t].set_size(N_dims, N_gaus);
t_acc_norm_lhoods[t].set_size(N_gaus);
t_gaus_log_lhoods[t].set_size(N_gaus);
}
if(verbose)
{
get_cout_stream() << "gmm_diag::learn(): EM: n_threads: " << n_threads << '\n';
}
eT old_avg_log_p = -Datum<eT>::inf;
for(uword iter=1; iter <= max_iter; ++iter)
{
init_constants();
em_update_params(X, boundaries, t_acc_means, t_acc_dcovs, t_acc_norm_lhoods, t_gaus_log_lhoods, t_progress_log_lhood);
em_fix_params(var_floor);
const eT new_avg_log_p = accu(t_progress_log_lhood) / eT(t_progress_log_lhood.n_elem);
if(verbose)
{
get_cout_stream() << "gmm_diag::learn(): EM: iteration: ";
get_cout_stream().unsetf(ios::scientific);
get_cout_stream().setf(ios::fixed);
get_cout_stream().width(std::streamsize(4));
get_cout_stream() << iter;
get_cout_stream() << " avg_log_p: ";
get_cout_stream().unsetf(ios::fixed);
//get_cout_stream().setf(ios::scientific);
get_cout_stream() << new_avg_log_p << '\n';
get_cout_stream().flush();
}
if(arma_isfinite(new_avg_log_p) == false) { return false; }
if(std::abs(old_avg_log_p - new_avg_log_p) <= Datum<eT>::eps) { break; }
old_avg_log_p = new_avg_log_p;
}
if(any(vectorise(dcovs) <= eT(0))) { return false; }
if(means.is_finite() == false ) { return false; }
if(dcovs.is_finite() == false ) { return false; }
if(hefts.is_finite() == false ) { return false; }
return true;
}
template<typename eT>
inline
void
gmm_diag<eT>::em_update_params
(
const Mat<eT>& X,
const umat& boundaries,
field< Mat<eT> >& t_acc_means,
field< Mat<eT> >& t_acc_dcovs,
field< Col<eT> >& t_acc_norm_lhoods,
field< Col<eT> >& t_gaus_log_lhoods,
Col<eT>& t_progress_log_lhood
)
{
arma_extra_debug_sigprint();
const uword n_threads = boundaries.n_cols;
// em_generate_acc() is the "map" operation, which produces partial accumulators for means, diagonal covariances and hefts
#if defined(ARMA_USE_OPENMP)
{
#pragma omp parallel for schedule(static)
for(uword t=0; t<n_threads; t++)
{
Mat<eT>& acc_means = t_acc_means[t];
Mat<eT>& acc_dcovs = t_acc_dcovs[t];
Col<eT>& acc_norm_lhoods = t_acc_norm_lhoods[t];
Col<eT>& gaus_log_lhoods = t_gaus_log_lhoods[t];
eT& progress_log_lhood = t_progress_log_lhood[t];
em_generate_acc(X, boundaries.at(0,t), boundaries.at(1,t), acc_means, acc_dcovs, acc_norm_lhoods, gaus_log_lhoods, progress_log_lhood);
}
}
#else
{
em_generate_acc(X, boundaries.at(0,0), boundaries.at(1,0), t_acc_means[0], t_acc_dcovs[0], t_acc_norm_lhoods[0], t_gaus_log_lhoods[0], t_progress_log_lhood[0]);
}
#endif
const uword N_dims = means.n_rows;
const uword N_gaus = means.n_cols;
Mat<eT>& final_acc_means = t_acc_means[0];
Mat<eT>& final_acc_dcovs = t_acc_dcovs[0];
Col<eT>& final_acc_norm_lhoods = t_acc_norm_lhoods[0];
// the "reduce" operation, which combines the partial accumulators produced by the separate threads
for(uword t=1; t<n_threads; t++)
{
final_acc_means += t_acc_means[t];
final_acc_dcovs += t_acc_dcovs[t];
final_acc_norm_lhoods += t_acc_norm_lhoods[t];
}
eT* hefts_mem = access::rw(hefts).memptr();
//// update each component without sanity checking
//for(uword g=0; g < N_gaus; ++g)
// {
// const eT acc_norm_lhood = (std::max)( final_acc_norm_lhoods[g], std::numeric_limits<eT>::min() );
//
// eT* mean_mem = access::rw(means).colptr(g);
// eT* dcov_mem = access::rw(dcovs).colptr(g);
//
// eT* acc_mean_mem = final_acc_means.colptr(g);
// eT* acc_dcov_mem = final_acc_dcovs.colptr(g);
//
// hefts_mem[g] = acc_norm_lhood / eT(X.n_cols);
//
// for(uword d=0; d < N_dims; ++d)
// {
// const eT tmp = acc_mean_mem[d] / acc_norm_lhood;
//
// mean_mem[d] = tmp;
// dcov_mem[d] = acc_dcov_mem[d] / acc_norm_lhood - tmp*tmp;
// }
// }
// conditionally update each component; if only a subset of the hefts was updated, em_fix_params() will sanitise them
for(uword g=0; g < N_gaus; ++g)
{
const eT acc_norm_lhood = (std::max)( final_acc_norm_lhoods[g], std::numeric_limits<eT>::min() );
if(arma_isfinite(acc_norm_lhood) == false) { continue; }
eT* acc_mean_mem = final_acc_means.colptr(g);
eT* acc_dcov_mem = final_acc_dcovs.colptr(g);
bool ok = true;
for(uword d=0; d < N_dims; ++d)
{
const eT tmp1 = acc_mean_mem[d] / acc_norm_lhood;
const eT tmp2 = acc_dcov_mem[d] / acc_norm_lhood - tmp1*tmp1;
acc_mean_mem[d] = tmp1;
acc_dcov_mem[d] = tmp2;
if(arma_isfinite(tmp2) == false) { ok = false; }
}
if(ok)
{
hefts_mem[g] = acc_norm_lhood / eT(X.n_cols);
eT* mean_mem = access::rw(means).colptr(g);
eT* dcov_mem = access::rw(dcovs).colptr(g);
for(uword d=0; d < N_dims; ++d)
{
mean_mem[d] = acc_mean_mem[d];
dcov_mem[d] = acc_dcov_mem[d];
}
}
}
}
template<typename eT>
inline
void
gmm_diag<eT>::em_generate_acc
(
const Mat<eT>& X,
const uword start_index,
const uword end_index,
Mat<eT>& acc_means,
Mat<eT>& acc_dcovs,
Col<eT>& acc_norm_lhoods,
Col<eT>& gaus_log_lhoods,
eT& progress_log_lhood
)
const
{
arma_extra_debug_sigprint();
progress_log_lhood = eT(0);
acc_means.zeros();
acc_dcovs.zeros();
acc_norm_lhoods.zeros();
gaus_log_lhoods.zeros();
const uword N_dims = means.n_rows;
const uword N_gaus = means.n_cols;
const eT* log_hefts_mem = log_hefts.memptr();
eT* gaus_log_lhoods_mem = gaus_log_lhoods.memptr();
for(uword i=start_index; i <= end_index; i++)
{
const eT* x = X.colptr(i);
for(uword g=0; g < N_gaus; ++g)
{
gaus_log_lhoods_mem[g] = internal_scalar_log_p(x, g) + log_hefts_mem[g];
}
eT log_lhood_sum = gaus_log_lhoods_mem[0];
for(uword g=1; g < N_gaus; ++g)
{
log_lhood_sum = log_add_exp(log_lhood_sum, gaus_log_lhoods_mem[g]);
}
progress_log_lhood += log_lhood_sum;
for(uword g=0; g < N_gaus; ++g)
{
const eT norm_lhood = std::exp(gaus_log_lhoods_mem[g] - log_lhood_sum);
acc_norm_lhoods[g] += norm_lhood;
eT* acc_mean_mem = acc_means.colptr(g);
eT* acc_dcov_mem = acc_dcovs.colptr(g);
for(uword d=0; d < N_dims; ++d)
{
const eT x_d = x[d];
const eT y_d = x_d * norm_lhood;
acc_mean_mem[d] += y_d;
acc_dcov_mem[d] += y_d * x_d; // equivalent to x_d * x_d * norm_lhood
}
}
}
progress_log_lhood /= eT((end_index - start_index) + 1);
}
template<typename eT>
inline
void
gmm_diag<eT>::em_fix_params(const eT var_floor)
{
arma_extra_debug_sigprint();
const uword N_dims = means.n_rows;
const uword N_gaus = means.n_cols;
const eT var_ceiling = std::numeric_limits<eT>::max();
const uword dcovs_n_elem = dcovs.n_elem;
eT* dcovs_mem = access::rw(dcovs).memptr();
for(uword i=0; i < dcovs_n_elem; ++i)
{
eT& var_val = dcovs_mem[i];
if(var_val < var_floor ) { var_val = var_floor; }
else if(var_val > var_ceiling) { var_val = var_ceiling; }
else if(arma_isnan(var_val) ) { var_val = eT(1); }
}
eT* hefts_mem = access::rw(hefts).memptr();
for(uword g1=0; g1 < N_gaus; ++g1)
{
if(hefts_mem[g1] > eT(0))
{
const eT* means_colptr_g1 = means.colptr(g1);
for(uword g2=(g1+1); g2 < N_gaus; ++g2)
{
if( (hefts_mem[g2] > eT(0)) && (std::abs(hefts_mem[g1] - hefts_mem[g2]) <= std::numeric_limits<eT>::epsilon()) )
{
const eT dist = distance<eT,1>::eval(N_dims, means_colptr_g1, means.colptr(g2), means_colptr_g1);
if(dist == eT(0)) { hefts_mem[g2] = eT(0); }
}
}
}
}
const eT heft_floor = std::numeric_limits<eT>::min();
const eT heft_initial = eT(1) / eT(N_gaus);
for(uword i=0; i < N_gaus; ++i)
{
eT& heft_val = hefts_mem[i];
if(heft_val < heft_floor) { heft_val = heft_floor; }
else if(heft_val > eT(1) ) { heft_val = eT(1); }
else if(arma_isnan(heft_val) ) { heft_val = heft_initial; }
}
const eT heft_sum = accu(hefts);
if((heft_sum < (eT(1) - Datum<eT>::eps)) || (heft_sum > (eT(1) + Datum<eT>::eps))) { access::rw(hefts) /= heft_sum; }
}
} // namespace gmm_priv
//! @}
| numediart/MotionMachine | libs/armadillo/include/armadillo_bits/gmm_diag_meat.hpp | C++ | lgpl-2.1 | 65,539 |
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//! [using a custom style]
#include <QtWidgets>
#include "customstyle.h"
int main(int argc, char *argv[])
{
QApplication::setStyle(new CustomStyle);
QApplication app(argc, argv);
QSpinBox spinBox;
spinBox.show();
return app.exec();
}
//! [using a custom style]
| BadSingleton/pyside2 | doc/codesnippets/doc/src/snippets/customstyle/main.cpp | C++ | lgpl-2.1 | 2,252 |
/*
* Hexadecimal modes for QEmacs.
*
* Copyright (c) 2000, 2001 Fabrice Bellard.
* Copyright (c) 2002-2008 Charlie Gordon.
*
* 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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "qe.h"
/* CG: should get rid of this forward reference */
#if defined(__GNUC__) && (__GNUC__ >= 4)
static ModeDef hex_mode;
#else
extern ModeDef hex_mode;
#endif
static int to_disp(int c)
{
#if 1
/* Allow characters in range 160-255 to show as graphics */
if ((c & 127) < ' ' || c == 127)
c = '.';
#else
if (c < ' ' || c >= 127)
c = '.';
#endif
return c;
}
static int hex_backward_offset(EditState *s, int offset)
{
return align(offset, s->disp_width);
}
static int hex_display(EditState *s, DisplayState *ds, int offset)
{
int j, len, ateof;
int offset1, offset2;
unsigned char b;
display_bol(ds);
ds->style = QE_STYLE_COMMENT;
display_printf(ds, -1, -1, "%08x ", offset);
ateof = 0;
len = s->b->total_size - offset;
if (len > s->disp_width)
len = s->disp_width;
if (s->mode == &hex_mode) {
ds->style = QE_STYLE_FUNCTION;
for (j = 0; j < s->disp_width; j++) {
display_char(ds, -1, -1, ' ');
offset1 = offset + j;
offset2 = offset1 + 1;
if (j < len) {
eb_read(s->b, offset1, &b, 1);
display_printhex(ds, offset1, offset2, b, 2);
} else {
if (!ateof) {
ateof = 1;
} else {
offset1 = offset2 = -1;
}
ds->cur_hex_mode = s->hex_mode;
display_printf(ds, offset1, offset2, " ");
ds->cur_hex_mode = 0;
}
if ((j & 7) == 7)
display_char(ds, -1, -1, ' ');
}
display_char(ds, -1, -1, ' ');
}
ds->style = 0;
display_char(ds, -1, -1, ' ');
ateof = 0;
for (j = 0; j < s->disp_width; j++) {
offset1 = offset + j;
offset2 = offset1 + 1;
if (j < len) {
eb_read(s->b, offset1, &b, 1);
} else {
b = ' ';
if (!ateof) {
ateof = 1;
} else {
offset1 = offset2 = -1;
}
}
display_char(ds, offset1, offset2, to_disp(b));
}
display_eol(ds, -1, -1);
if (len >= s->disp_width)
return offset + len;
else
return -1;
}
static void do_set_width(EditState *s, int w)
{
if (w >= 1) {
s->disp_width = w;
s->offset_top = s->mode->text_backward_offset(s, s->offset_top);
}
}
static void do_incr_width(EditState *s, int incr)
{
int w;
w = s->disp_width + incr;
if (w >= 1)
do_set_width(s, w);
}
static void do_toggle_hex(EditState *s)
{
s->hex_mode = !s->hex_mode;
}
/* specific hex commands */
static CmdDef hex_commands[] = {
CMD1( KEY_CTRL_LEFT, KEY_NONE,
"decrease-width", do_incr_width, -1)
CMD1( KEY_CTRL_RIGHT, KEY_NONE,
"increase-width", do_incr_width, 1)
CMD2( KEY_NONE, KEY_NONE,
"set-width", do_set_width, ESi,
"ui{Width: }")
CMD3( KEY_META('g'), KEY_NONE,
"goto-byte", do_goto, ESsi, 'b',
"us{Goto byte: }"
"v")
CMD0( KEY_NONE, KEY_NONE,
"toggle-hex", do_toggle_hex)
CMD_DEF_END,
};
static int ascii_mode_init(EditState *s, ModeSavedData *saved_data)
{
QEFont *font;
QEStyleDef style;
int num_width;
int ret;
ret = text_mode_init(s, saved_data);
if (ret)
return ret;
/* get typical number width */
get_style(s, &style, s->default_style);
font = select_font(s->screen, style.font_style, style.font_size);
num_width = glyph_width(s->screen, font, '0');
release_font(s->screen, font);
s->disp_width = (s->screen->width / num_width) - 10;
/* align on 16 byte boundary */
s->disp_width &= ~15;
if (s->disp_width < 16)
s->disp_width = 16;
s->insert = 0;
s->hex_mode = 0;
s->wrap = WRAP_TRUNCATE;
return 0;
}
static int hex_mode_init(EditState *s, ModeSavedData *saved_data)
{
int ret;
ret = text_mode_init(s, saved_data);
if (ret)
return ret;
s->disp_width = 16;
s->hex_mode = 1;
s->unihex_mode = 0;
s->hex_nibble = 0;
s->insert = 0;
s->wrap = WRAP_TRUNCATE;
return 0;
}
static int detect_binary(const unsigned char *buf, int size)
{
int i, c;
for (i = 0; i < size; i++) {
c = buf[i];
if (c < 32 &&
(c != '\r' && c != '\n' && c != '\t' &&
c != '\033' && c != '\b' && c != '\f'))
return 1;
}
return 0;
}
static int hex_mode_probe(ModeProbeData *p)
{
if (detect_binary(p->buf, p->buf_size))
return 50;
else
return 10;
}
static void hex_move_bol(EditState *s)
{
s->offset = align(s->offset, s->disp_width);
}
static void hex_move_eol(EditState *s)
{
s->offset = align(s->offset, s->disp_width) + s->disp_width - 1;
if (s->offset > s->b->total_size)
s->offset = s->b->total_size;
}
static void hex_move_left_right(EditState *s, int dir)
{
s->offset += dir;
if (s->offset < 0)
s->offset = 0;
else
if (s->offset > s->b->total_size)
s->offset = s->b->total_size;
}
static void hex_move_up_down(EditState *s, int dir)
{
s->offset += dir * s->disp_width;
if (s->offset < 0)
s->offset = 0;
else
if (s->offset > s->b->total_size)
s->offset = s->b->total_size;
}
void hex_write_char(EditState *s, int key)
{
unsigned int cur_ch, ch;
int hsize, shift, cur_len, len, h;
char buf[10];
if (s->hex_mode) {
if (s->unihex_mode)
hsize = 4;
else
hsize = 2;
h = to_hex(key);
if (h < 0)
return;
if (s->insert && s->hex_nibble == 0) {
ch = h << ((hsize - 1) * 4);
if (s->unihex_mode) {
len = unicode_to_charset(buf, ch, s->b->charset);
} else {
len = 1;
buf[0] = ch;
}
eb_insert(s->b, s->offset, buf, len);
} else {
if (s->unihex_mode) {
cur_ch = eb_nextc(s->b, s->offset, &cur_len);
cur_len -= s->offset;
} else {
eb_read(s->b, s->offset, buf, 1);
cur_ch = buf[0];
cur_len = 1;
}
shift = (hsize - s->hex_nibble - 1) * 4;
ch = (cur_ch & ~(0xf << shift)) | (h << shift);
if (s->unihex_mode) {
len = unicode_to_charset(buf, ch, s->b->charset);
} else {
len = 1;
buf[0] = ch;
}
#if 1
eb_replace(s->b, s->offset, cur_len, buf, len);
#else
if (cur_len == len) {
eb_write(s->b, s->offset, buf, len);
} else {
eb_delete(s->b, s->offset, cur_len);
eb_insert(s->b, s->offset, buf, len);
}
#endif
}
if (++s->hex_nibble == hsize) {
s->hex_nibble = 0;
if (s->offset < s->b->total_size)
s->offset += len;
}
} else {
text_write_char(s, key);
}
}
static int hex_mode_line(EditState *s, char *buf, int buf_size)
{
int percent, pos;
pos = basic_mode_line(s, buf, buf_size, '-');
pos += snprintf(buf + pos, buf_size - pos, "0x%x--0x%x",
s->offset, s->b->total_size);
percent = 0;
if (s->b->total_size > 0)
percent = (s->offset * 100) / s->b->total_size;
pos += snprintf(buf + pos, buf_size - pos, "--%d%%", percent);
return pos;
}
static ModeDef ascii_mode = {
"ascii",
.instance_size = 0,
.mode_probe = NULL,
.mode_init = ascii_mode_init,
.mode_close = text_mode_close,
.text_display = hex_display,
.text_backward_offset = hex_backward_offset,
.move_up_down = hex_move_up_down,
.move_left_right = hex_move_left_right,
.move_bol = hex_move_bol,
.move_eol = hex_move_eol,
.scroll_up_down = text_scroll_up_down,
.write_char = text_write_char,
.mouse_goto = text_mouse_goto,
.get_mode_line = hex_mode_line,
};
static ModeDef hex_mode = {
"hex",
.instance_size = 0,
.mode_probe = hex_mode_probe,
.mode_init = hex_mode_init,
.mode_close = text_mode_close,
.text_display = hex_display,
.text_backward_offset = hex_backward_offset,
.move_up_down = hex_move_up_down,
.move_left_right = hex_move_left_right,
.move_bol = hex_move_bol,
.move_eol = hex_move_eol,
.scroll_up_down = text_scroll_up_down,
.write_char = hex_write_char,
.mouse_goto = text_mouse_goto,
.get_mode_line = hex_mode_line,
};
static int hex_init(void)
{
/* first register mode(s) */
qe_register_mode(&ascii_mode);
qe_register_mode(&hex_mode);
/* commands and default keys */
qe_register_cmd_table(hex_commands, &hex_mode);
qe_register_cmd_table(hex_commands, &ascii_mode);
/* additional mode specific keys */
qe_register_binding(KEY_TAB, "toggle-hex", &hex_mode);
qe_register_binding(KEY_SHIFT_TAB, "toggle-hex", &hex_mode);
return 0;
}
qe_module_init(hex_init);
| sonald/qemacs | hex.c | C | lgpl-2.1 | 10,042 |
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.file.types;
import org.opencms.configuration.CmsConfigurationException;
import org.opencms.db.CmsSecurityManager;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsRequestContext;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.loader.CmsLoaderException;
import org.opencms.loader.CmsXmlContainerPageLoader;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.relations.CmsLink;
import org.opencms.relations.I_CmsLinkParseable;
import org.opencms.security.CmsPermissionSet;
import org.opencms.xml.CmsXmlContentDefinition;
import org.opencms.xml.containerpage.CmsXmlContainerPage;
import org.opencms.xml.containerpage.CmsXmlContainerPageFactory;
import org.opencms.xml.types.CmsXmlVfsFileValue;
import org.opencms.xml.types.I_CmsXmlContentValue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.apache.commons.logging.Log;
/**
* Resource type descriptor for the type "containerpage".<p>
*
* It is just a xml content with a fixed schema.<p>
*
* @since 7.6
*/
public class CmsResourceTypeXmlContainerPage extends CmsResourceTypeXmlContent {
/** The configuration resource type name. */
public static final String CONFIGURATION_TYPE_NAME = "sitemap_config";
/** The group container resource type name. */
public static final String GROUP_CONTAINER_TYPE_NAME = "groupcontainer";
/** The inherit configuration resource type name. */
public static final String INHERIT_CONTAINER_CONFIG_TYPE_NAME = "inheritance_config";
/** The resource type name for inherited container references. */
public static final String INHERIT_CONTAINER_TYPE_NAME = "inheritance_group";
/** The name of this resource type. */
public static final String RESOURCE_TYPE_NAME = "containerpage";
/** A variable containing the actual configured type id of container pages. */
private static int containerPageTypeId;
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsResourceTypeXmlContainerPage.class);
/** Fixed schema for container pages. */
private static final String SCHEMA = "/system/modules/org.opencms.ade.containerpage/schemas/container_page.xsd";
/**
* Default constructor that sets the fixed schema for container pages.<p>
*/
public CmsResourceTypeXmlContainerPage() {
super();
m_typeName = RESOURCE_TYPE_NAME;
addConfigurationParameter(CONFIGURATION_SCHEMA, SCHEMA);
}
/**
* Returns the container-page type id.<p>
*
* @return the container-page type id
*
* @throws CmsLoaderException if the type is not configured
*/
public static int getContainerPageTypeId() throws CmsLoaderException {
if (containerPageTypeId == 0) {
I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(getStaticTypeName());
if (resType != null) {
containerPageTypeId = resType.getTypeId();
}
}
return containerPageTypeId;
}
/**
* Returns the container-page type id, but returns -1 instead of throwing an exception when an error happens.<p>
*
* @return the container-page type id
*/
public static int getContainerPageTypeIdSafely() {
try {
return getContainerPageTypeId();
} catch (CmsLoaderException e) {
if (LOG.isDebugEnabled()) {
LOG.debug(e.getLocalizedMessage(), e);
}
return -1;
}
}
/**
* Returns the static type name of this (default) resource type.<p>
*
* @return the static type name of this (default) resource type
*/
public static String getStaticTypeName() {
return RESOURCE_TYPE_NAME;
}
/**
* Returns <code>true</code> in case the given resource is a container page.<p>
*
* Internally this checks if the type id for the given resource is
* identical type id of the container page.<p>
*
* @param resource the resource to check
*
* @return <code>true</code> in case the given resource is a container page
*/
public static boolean isContainerPage(CmsResource resource) {
boolean result = false;
if (resource != null) {
result = (resource.getTypeId() == getContainerPageTypeIdSafely());
}
return result;
}
/**
* @see org.opencms.file.types.CmsResourceTypeXmlContent#createResource(org.opencms.file.CmsObject, org.opencms.db.CmsSecurityManager, java.lang.String, byte[], java.util.List)
*/
@Override
public CmsResource createResource(
CmsObject cms,
CmsSecurityManager securityManager,
String resourcename,
byte[] content,
List<CmsProperty> properties) throws CmsException {
boolean hasModelUri = false;
CmsXmlContainerPage newContent = null;
if ((getSchema() != null) && ((content == null) || (content.length == 0))) {
// unmarshal the content definition for the new resource
CmsXmlContentDefinition contentDefinition = CmsXmlContentDefinition.unmarshal(cms, getSchema());
// read the default locale for the new resource
Locale locale = OpenCms.getLocaleManager().getDefaultLocales(cms, CmsResource.getParentFolder(resourcename)).get(
0);
String modelUri = (String)cms.getRequestContext().getAttribute(CmsRequestContext.ATTRIBUTE_MODEL);
// must set URI of OpenCms user context to parent folder of created resource,
// in order to allow reading of properties for default values
CmsObject newCms = OpenCms.initCmsObject(cms);
newCms.getRequestContext().setUri(CmsResource.getParentFolder(resourcename));
if (modelUri != null) {
// create the new content from the model file
newContent = CmsXmlContainerPageFactory.createDocument(newCms, locale, modelUri);
hasModelUri = true;
} else {
// create the new content from the content definition
newContent = CmsXmlContainerPageFactory.createDocument(
newCms,
locale,
OpenCms.getSystemInfo().getDefaultEncoding(),
contentDefinition);
}
// get the bytes from the created content
content = newContent.marshal();
}
// now create the resource using the super class
CmsResource resource = super.createResource(cms, securityManager, resourcename, content, properties);
// a model file was used, call the content handler for post-processing
if (hasModelUri) {
newContent = CmsXmlContainerPageFactory.unmarshal(cms, resource);
resource = newContent.getHandler().prepareForWrite(cms, newContent, newContent.getFile());
}
return resource;
}
/**
* @see org.opencms.file.types.CmsResourceTypeXmlContent#getLoaderId()
*/
@Override
public int getLoaderId() {
return CmsXmlContainerPageLoader.CONTAINER_PAGE_RESOURCE_LOADER_ID;
}
/**
* @see org.opencms.file.types.A_CmsResourceType#initConfiguration(java.lang.String, java.lang.String, String)
*/
@Override
public void initConfiguration(String name, String id, String className) throws CmsConfigurationException {
if (!RESOURCE_TYPE_NAME.equals(name)) {
// default resource type MUST have default name
throw new CmsConfigurationException(Messages.get().container(
Messages.ERR_INVALID_RESTYPE_CONFIG_NAME_3,
this.getClass().getName(),
RESOURCE_TYPE_NAME,
name));
}
int typeId = Integer.valueOf(id).intValue();
if ((containerPageTypeId > 0) && (containerPageTypeId != typeId)) {
throw new CmsConfigurationException(Messages.get().container(
Messages.ERR_RESOURCE_TYPE_ALREADY_CONFIGURED_3,
this.getClass().getName(),
RESOURCE_TYPE_NAME,
name));
}
super.initConfiguration(RESOURCE_TYPE_NAME, id, className);
}
/**
* @see org.opencms.relations.I_CmsLinkParseable#parseLinks(org.opencms.file.CmsObject, org.opencms.file.CmsFile)
*/
@Override
public List<CmsLink> parseLinks(CmsObject cms, CmsFile file) {
if (file.getLength() == 0) {
return Collections.emptyList();
}
CmsXmlContainerPage xmlContent;
long requestTime = cms.getRequestContext().getRequestTime();
try {
// prevent the check rules to remove the broken links
cms.getRequestContext().setRequestTime(CmsResource.DATE_RELEASED_EXPIRED_IGNORE);
xmlContent = CmsXmlContainerPageFactory.unmarshal(cms, file);
} catch (CmsException e) {
if (LOG.isErrorEnabled()) {
LOG.error(
org.opencms.db.Messages.get().getBundle().key(
org.opencms.db.Messages.ERR_READ_RESOURCE_1,
cms.getSitePath(file)),
e);
}
return Collections.emptyList();
} finally {
cms.getRequestContext().setRequestTime(requestTime);
}
Set<CmsLink> links = new HashSet<CmsLink>();
// add XSD link
CmsLink xsdLink = getXsdLink(cms, xmlContent);
if (xsdLink != null) {
links.add(xsdLink);
}
// iterate over all languages
List<Locale> locales = xmlContent.getLocales();
Iterator<Locale> i = locales.iterator();
while (i.hasNext()) {
Locale locale = i.next();
List<I_CmsXmlContentValue> values = xmlContent.getValues(locale);
// iterate over all body elements per language
Iterator<I_CmsXmlContentValue> j = values.iterator();
while (j.hasNext()) {
I_CmsXmlContentValue value = j.next();
if (!(value instanceof CmsXmlVfsFileValue)) {
// filter only relations relevant fields
// container pages do not have XmlHtml nor VarFiles
continue;
}
CmsXmlVfsFileValue refValue = (CmsXmlVfsFileValue)value;
CmsLink link = refValue.getLink(cms);
if (link != null) {
links.add(link);
}
}
}
return new ArrayList<CmsLink>(links);
}
/**
* @see org.opencms.file.types.CmsResourceTypeXmlContent#writeFile(org.opencms.file.CmsObject, org.opencms.db.CmsSecurityManager, org.opencms.file.CmsFile)
*/
@Override
public CmsFile writeFile(CmsObject cms, CmsSecurityManager securityManager, CmsFile resource) throws CmsException {
// check if the user has write access and if resource is locked
// done here so that all the XML operations are not performed if permissions not granted
securityManager.checkPermissions(
cms.getRequestContext(),
resource,
CmsPermissionSet.ACCESS_WRITE,
true,
CmsResourceFilter.ALL);
// read the XML content, use the encoding set in the property
CmsXmlContainerPage xmlContent = CmsXmlContainerPageFactory.unmarshal(cms, resource, false, true);
// call the content handler for post-processing
resource = xmlContent.getHandler().prepareForWrite(cms, xmlContent, resource);
// now write the file
CmsFile file = securityManager.writeFile(cms.getRequestContext(), resource);
I_CmsResourceType type = getResourceType(file);
// update the relations after writing!!
List<CmsLink> links = null;
if (type instanceof I_CmsLinkParseable) { // this check is needed because of type change
// if the new type is link parseable
links = ((I_CmsLinkParseable)type).parseLinks(cms, file);
}
// this has to be always executed, even if not link parseable to remove old links
securityManager.updateRelationsForResource(cms.getRequestContext(), file, links);
return file;
}
} | it-tavis/opencms-core | src/org/opencms/file/types/CmsResourceTypeXmlContainerPage.java | Java | lgpl-2.1 | 13,782 |
/*
* Hibernate OGM, Domain model persistence for NoSQL datastores
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.ogm.backendtck.batchfetching;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.Map;
import org.fest.assertions.Assertions;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.ogm.cfg.OgmProperties;
import org.hibernate.ogm.dialect.impl.GridDialects;
import org.hibernate.ogm.dialect.multiget.spi.MultigetGridDialect;
import org.hibernate.ogm.dialect.spi.GridDialect;
import org.hibernate.ogm.utils.InvokedOperationsLoggingDialect;
import org.hibernate.ogm.utils.OgmTestCase;
import org.hibernate.ogm.utils.TestForIssue;
import org.hibernate.ogm.utils.TestHelper;
import org.hibernate.stat.Statistics;
import org.junit.Test;
/**
* @author Emmanuel Bernard emmanuel@hibernate.org
*/
public class BatchFetchingTest extends OgmTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] { Tower.class, Floor.class, CondominiumBuilding.class, Condominium.class };
}
@Test
public void testLoadSeveralFloorsByBatch() throws Exception {
Session session = openSession();
Tower tower = prepareTower( session );
session.clear();
session.beginTransaction();
for ( Floor currentFloor : tower.getFloors() ) {
// load proxies
assertFalse( Hibernate.isInitialized( session.load( Floor.class, currentFloor.getId() ) ) );
}
Statistics statistics = session.getSessionFactory().getStatistics();
statistics.setStatisticsEnabled( true );
statistics.clear();
assertEquals( 0, statistics.getEntityStatistics( Floor.class.getName() ).getFetchCount() );
getOperationsLogger().reset();
for ( Floor currentFloor : tower.getFloors() ) {
// load proxies
Object entity = session.load( Floor.class, currentFloor.getId() );
Hibernate.initialize( entity );
assertTrue( Hibernate.isInitialized( entity ) );
}
// if a multiget, we load both entities as one go, otherwise we don't
int fetchSize = isMultigetDialect() ? 1 : 2;
assertEquals( fetchSize, statistics.getEntityStatistics( Floor.class.getName() ).getFetchCount() );
if ( isMultigetDialect() ) {
assertThat( getOperations() ).containsExactly(
"getTuples"
);
}
else {
assertThat( getOperations() ).containsExactly(
"getTuple",
"getTuple"
);
}
session.getTransaction().commit();
cleanTower( session, tower );
session.close();
}
@Test
public void testLoadSeveralFloorsFromTower() throws Exception {
Session session = openSession();
Tower tower = prepareTower( session );
session.clear();
// now read the tower and its floors to detect 1+n patterns;
session.beginTransaction();
tower = session.get( Tower.class, tower.getId() );
Statistics statistics = session.getSessionFactory().getStatistics();
statistics.setStatisticsEnabled( true );
statistics.clear();
assertEquals( 0, statistics.getEntityStatistics( Floor.class.getName() ).getFetchCount() );
getOperationsLogger().reset();
Assertions.assertThat( tower.getFloors() ).hasSize( 2 );
// if a multiget, we load both entities as one go, otherwise we don't
int fetchSize = isMultigetDialect() ? 1 : 2;
assertEquals( fetchSize, statistics.getEntityStatistics( Floor.class.getName() ).getFetchCount() );
session.getTransaction().commit();
if ( isMultigetDialect() ) {
assertThat( getOperations() ).containsExactly(
"getAssociation",
"getTuples"
);
}
else {
assertThat( getOperations() ).containsExactly(
"getAssociation",
"getTuple",
"getTuple"
);
}
cleanTower( session, tower );
session.close();
}
@Test
@TestForIssue(jiraKey = "OGM-945")
public void testMultigetIsAppliedWithoutExplicitBatchSizeGiven() throws Exception {
Session session = openSession();
prepareCondoBuilding( session );
session.clear();
// now read the condo building and its appartments to detect 1+n patterns;
session.beginTransaction();
CondominiumBuilding condoBuilding = session.get( CondominiumBuilding.class, "cb-1" );
Statistics statistics = session.getSessionFactory().getStatistics();
statistics.setStatisticsEnabled( true );
statistics.clear();
assertEquals( 0, statistics.getEntityStatistics( Condominium.class.getName() ).getFetchCount() );
getOperationsLogger().reset();
Assertions.assertThat( condoBuilding.getCondominiums() ).hasSize( 3 );
// if a multiget, we load all entities as one go, otherwise we don't
int fetchSize = isMultigetDialect() ? 1 : 3;
assertEquals( fetchSize, statistics.getEntityStatistics( Condominium.class.getName() ).getFetchCount() );
session.getTransaction().commit();
if ( isMultigetDialect() ) {
assertThat( getOperations() ).containsExactly(
"getAssociation",
"getTuples"
);
}
else {
assertThat( getOperations() ).containsExactly(
"getAssociation",
"getTuple",
"getTuple",
"getTuple"
);
}
cleanCondoBuilding( session );
session.close();
}
private void cleanTower(Session session, Tower tower) {
session.beginTransaction();
session.delete( session.get( Tower.class, tower.getId() ) );
for ( Floor currentFloor : tower.getFloors() ) {
session.delete( session.get( Floor.class, currentFloor.getId() ) );
}
session.delete( new CondominiumBuilding( "cb-1" ) );
session.getTransaction().commit();
}
private Tower prepareTower(Session session) {
session.beginTransaction();
Tower tower = new Tower();
tower.setName( "Pise" );
Floor floor = new Floor();
floor.setLevel( 0 );
tower.getFloors().add( floor );
floor = new Floor();
floor.setLevel( 1 );
tower.getFloors().add( floor );
session.persist( tower );
session.getTransaction().commit();
return tower;
}
private void cleanCondoBuilding(Session session) {
session.beginTransaction();
session.delete( session.get( CondominiumBuilding.class, "cb-1" ) );
session.getTransaction().commit();
}
private CondominiumBuilding prepareCondoBuilding(Session session) {
session.beginTransaction();
CondominiumBuilding condoBuilding = new CondominiumBuilding();
condoBuilding.setId( "cb-1" );
condoBuilding.getCondominiums().add( new Condominium( "condo-1", 110 ) );
condoBuilding.getCondominiums().add( new Condominium( "condo-2", 90 ) );
condoBuilding.getCondominiums().add( new Condominium( "condo-3", 135 ) );
session.persist( condoBuilding );
session.getTransaction().commit();
return condoBuilding;
}
private boolean isMultigetDialect() {
GridDialect gridDialect = getSessionFactory().getServiceRegistry().getService( GridDialect.class );
return GridDialects.hasFacet( gridDialect, MultigetGridDialect.class );
}
@Override
protected void configure(Map<String, Object> cfg) {
cfg.put( OgmProperties.GRID_DIALECT, InvokedOperationsLoggingDialect.class );
TestHelper.enableCountersForInfinispan( cfg );
}
private InvokedOperationsLoggingDialect getOperationsLogger() {
GridDialect gridDialect = getSessionFactory().getServiceRegistry().getService( GridDialect.class );
InvokedOperationsLoggingDialect invocationLogger = GridDialects.getDelegateOrNull(
gridDialect,
InvokedOperationsLoggingDialect.class
);
return invocationLogger;
}
private List<String> getOperations() {
return getOperationsLogger().getOperations();
}
}
| DavideD/hibernate-ogm | core/src/test/java/org/hibernate/ogm/backendtck/batchfetching/BatchFetchingTest.java | Java | lgpl-2.1 | 7,666 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Struct template reference<Converter, TypeOut, void></title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Convert 2.0">
<link rel="up" href="../../boost_convert_c___reference.html#header.boost.convert_hpp" title="Header <boost/convert.hpp>">
<link rel="prev" href="reference.html" title="Struct template reference">
<link rel="next" href="apply_idm10615.html" title="Function template apply">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="reference.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_convert_c___reference.html#header.boost.convert_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="apply_idm10615.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.cnv.reference_Convert_idm10586"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template reference<Converter, TypeOut, void></span></h2>
<p>boost::cnv::reference<Converter, TypeOut, void></p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../boost_convert_c___reference.html#header.boost.convert_hpp" title="Header <boost/convert.hpp>">boost/convert.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Converter<span class="special">,</span> <span class="keyword">typename</span> TypeOut<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="reference_Convert_idm10586.html" title="Struct template reference<Converter, TypeOut, void>">reference</a><span class="special"><</span><span class="identifier">Converter</span><span class="special">,</span> <span class="identifier">TypeOut</span><span class="special">,</span> <span class="keyword">void</span><span class="special">></span> <span class="special">{</span>
<span class="comment">// types</span>
<span class="keyword">typedef</span> <a class="link" href="reference.html" title="Struct template reference">reference</a> <a name="boost.cnv.reference_Convert_idm10586.this_type"></a><span class="identifier">this_type</span><span class="special">;</span>
<span class="comment">// <a class="link" href="reference_Convert_idm10586.html#boost.cnv.reference_Convert_idm10586construct-copy-destruct">construct/copy/destruct</a></span>
<a class="link" href="reference_Convert_idm10586.html#idm10609-bb"><span class="identifier">reference</span></a><span class="special">(</span><span class="identifier">Converter</span> <span class="keyword">const</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="reference_Convert_idm10586.html#idm10612-bb"><span class="identifier">reference</span></a><span class="special">(</span><span class="identifier">Converter</span> <span class="special">&&</span><span class="special">)</span><span class="special">;</span>
<span class="comment">// <a class="link" href="reference_Convert_idm10586.html#idm10597-bb">public member functions</a></span>
this_type <span class="special">&</span> <a class="link" href="reference_Convert_idm10586.html#idm10598-bb"><span class="identifier">value_or</span></a><span class="special">(</span><span class="identifier">TypeOut</span> <span class="keyword">const</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> TypeIn<span class="special">></span> <span class="identifier">TypeOut</span> <a class="link" href="reference_Convert_idm10586.html#idm10603-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="identifier">TypeIn</span> <span class="keyword">const</span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idm11008"></a><h2>Description</h2>
<div class="refsect2">
<a name="idm11010"></a><h3>
<a name="boost.cnv.reference_Convert_idm10586construct-copy-destruct"></a><code class="computeroutput">reference</code>
public
construct/copy/destruct</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem"><pre class="literallayout"><a name="idm10609-bb"></a><span class="identifier">reference</span><span class="special">(</span><span class="identifier">Converter</span> <span class="keyword">const</span> <span class="special">&</span> cnv<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><a name="idm10612-bb"></a><span class="identifier">reference</span><span class="special">(</span><span class="identifier">Converter</span> <span class="special">&&</span> cnv<span class="special">)</span><span class="special">;</span></pre></li>
</ol></div>
</div>
<div class="refsect2">
<a name="idm11036"></a><h3>
<a name="idm10597-bb"></a><code class="computeroutput">reference</code> public member functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem"><pre class="literallayout">this_type <span class="special">&</span> <a name="idm10598-bb"></a><span class="identifier">value_or</span><span class="special">(</span><span class="identifier">TypeOut</span> <span class="keyword">const</span> <span class="special">&</span> fallback<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> TypeIn<span class="special">></span> <span class="identifier">TypeOut</span> <a name="idm10603-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="identifier">TypeIn</span> <span class="keyword">const</span> <span class="special">&</span> value_in<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
</ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2009-2020 Vladimir Batov<p>
Distributed under the Boost Software License, Version 1.0. See copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>.
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="reference.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_convert_c___reference.html#header.boost.convert_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="apply_idm10615.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| qianqians/abelkhan | cpp_component/3rdparty/boost/libs/convert/doc/html/boost/cnv/reference_Convert_idm10586.html | HTML | lgpl-2.1 | 8,668 |
<?php
/*
@version v5.21.0-dev ??-???-2016
@copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
@copyright (c) 2014 Damien Regad, Mark Newnham and the ADOdb community
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 8.
This driver only supports the original non-transactional MySQL driver. It
is deprected in PHP version 5.5 and removed in PHP version 7. It is deprecated
as of ADOdb version 5.20.0. Use the mysqli driver instead, which supports both
transactional and non-transactional updates
Requires mysql client. Works on Windows and Unix.
28 Feb 2001: MetaColumns bug fix - suggested by Freek Dijkstra (phpeverywhere@macfreek.com)
*/
// security - hide paths
if (!defined('ADODB_DIR')) die();
if (! defined("_ADODB_MYSQL_LAYER")) {
define("_ADODB_MYSQL_LAYER", 1 );
class ADODB_mysql extends ADOConnection {
var $databaseType = 'mysql';
var $dataProvider = 'mysql';
var $hasInsertID = true;
var $hasAffectedRows = true;
var $metaTablesSQL = "SELECT
TABLE_NAME,
CASE WHEN TABLE_TYPE = 'VIEW' THEN 'V' ELSE 'T' END
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA=";
var $metaColumnsSQL = "SHOW COLUMNS FROM `%s`";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $hasLimit = true;
var $hasMoveFirst = true;
var $hasGenID = true;
var $isoDates = true; // accepts dates in ISO format
var $sysDate = 'CURDATE()';
var $sysTimeStamp = 'NOW()';
var $hasTransactions = false;
var $forceNewConnect = false;
var $poorAffectedRows = true;
var $clientFlags = 0;
var $charSet = '';
var $substr = "substring";
var $nameQuote = '`'; /// string to use to quote identifiers and names
var $compat323 = false; // true if compat with mysql 3.23
/**
* ADODB_mysql constructor.
*/
public function __construct() {
if(version_compare(PHP_VERSION, '7.0.0', '>=')) {
$this->outp_throw(
'mysql extension is not supported since PHP 7.0.0, use mysqli instead',
__METHOD__
);
die(1); // Stop execution even if not using Exceptions
} elseif(version_compare(PHP_VERSION, '5.5.0', '>=')) {
// If mysql extension is available just print a warning,
// otherwise die with an error message
if(function_exists('mysql_connect')) {
$this->outp('mysql extension is deprecated since PHP 5.5.0, consider using mysqli');
} else {
$this->outp_throw(
'mysql extension is not available, use mysqli instead',
__METHOD__
);
die(1); // Stop execution even if not using Exceptions
}
}
}
// SetCharSet - switch the client encoding
function SetCharSet($charset_name)
{
if (!function_exists('mysql_set_charset')) {
return false;
}
if ($this->charSet !== $charset_name) {
$ok = @mysql_set_charset($charset_name,$this->_connectionID);
if ($ok) {
$this->charSet = $charset_name;
return true;
}
return false;
}
return true;
}
function ServerInfo()
{
$arr['description'] = ADOConnection::GetOne("select version()");
$arr['version'] = ADOConnection::_findvers($arr['description']);
return $arr;
}
function IfNull( $field, $ifNull )
{
return " IFNULL($field, $ifNull) "; // if MySQL
}
function MetaProcedures($NamePattern = false, $catalog = null, $schemaPattern = null)
{
// save old fetch mode
global $ADODB_FETCH_MODE;
$false = false;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== FALSE) {
$savem = $this->SetFetchMode(FALSE);
}
$procedures = array ();
// get index details
$likepattern = '';
if ($NamePattern) {
$likepattern = " LIKE '".$NamePattern."'";
}
$rs = $this->Execute('SHOW PROCEDURE STATUS'.$likepattern);
if (is_object($rs)) {
// parse index data into array
while ($row = $rs->FetchRow()) {
$procedures[$row[1]] = array(
'type' => 'PROCEDURE',
'catalog' => '',
'schema' => '',
'remarks' => $row[7],
);
}
}
$rs = $this->Execute('SHOW FUNCTION STATUS'.$likepattern);
if (is_object($rs)) {
// parse index data into array
while ($row = $rs->FetchRow()) {
$procedures[$row[1]] = array(
'type' => 'FUNCTION',
'catalog' => '',
'schema' => '',
'remarks' => $row[7]
);
}
}
// restore fetchmode
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
return $procedures;
}
/**
* Retrieves a list of tables based on given criteria
*
* @param string $ttype Table type = 'TABLE', 'VIEW' or false=both (default)
* @param string $showSchema schema name, false = current schema (default)
* @param string $mask filters the table by name
*
* @return array list of tables
*/
function MetaTables($ttype=false,$showSchema=false,$mask=false)
{
$save = $this->metaTablesSQL;
if ($showSchema && is_string($showSchema)) {
$this->metaTablesSQL .= $this->qstr($showSchema);
} else {
$this->metaTablesSQL .= "schema()";
}
if ($mask) {
$mask = $this->qstr($mask);
$this->metaTablesSQL .= " AND table_name LIKE $mask";
}
$ret = ADOConnection::MetaTables($ttype,$showSchema);
$this->metaTablesSQL = $save;
return $ret;
}
function MetaIndexes ($table, $primary = FALSE, $owner=false)
{
// save old fetch mode
global $ADODB_FETCH_MODE;
$false = false;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== FALSE) {
$savem = $this->SetFetchMode(FALSE);
}
// get index details
$rs = $this->Execute(sprintf('SHOW INDEX FROM %s',$table));
// restore fetchmode
if (isset($savem)) {
$this->SetFetchMode($savem);
}
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
return $false;
}
$indexes = array ();
// parse index data into array
while ($row = $rs->FetchRow()) {
if ($primary == FALSE AND $row[2] == 'PRIMARY') {
continue;
}
if (!isset($indexes[$row[2]])) {
$indexes[$row[2]] = array(
'unique' => ($row[1] == 0),
'columns' => array()
);
}
$indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
}
// sort columns by order in the index
foreach ( array_keys ($indexes) as $index )
{
ksort ($indexes[$index]['columns']);
}
return $indexes;
}
// if magic quotes disabled, use mysql_real_escape_string()
function qstr($s,$magic_quotes=false)
{
if (is_null($s)) return 'NULL';
if (!$magic_quotes) {
if (ADODB_PHPVER >= 0x4300) {
if (is_resource($this->_connectionID))
return "'".mysql_real_escape_string($s,$this->_connectionID)."'";
}
if ($this->replaceQuote[0] == '\\'){
$s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
}
return "'".str_replace("'",$this->replaceQuote,$s)."'";
}
// undo magic quotes for "
$s = str_replace('\\"','"',$s);
return "'$s'";
}
function _insertid()
{
return ADOConnection::GetOne('SELECT LAST_INSERT_ID()');
//return mysql_insert_id($this->_connectionID);
}
function GetOne($sql,$inputarr=false)
{
global $ADODB_GETONE_EOF;
if ($this->compat323 == false && strncasecmp($sql,'sele',4) == 0) {
$rs = $this->SelectLimit($sql,1,-1,$inputarr);
if ($rs) {
$rs->Close();
if ($rs->EOF) return $ADODB_GETONE_EOF;
return reset($rs->fields);
}
} else {
return ADOConnection::GetOne($sql,$inputarr);
}
return false;
}
function BeginTrans()
{
if ($this->debug) ADOConnection::outp("Transactions not supported in 'mysql' driver. Use 'mysqlt' or 'mysqli' driver");
}
function _affectedrows()
{
return mysql_affected_rows($this->_connectionID);
}
// See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
// Reference on Last_Insert_ID on the recommended way to simulate sequences
var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
var $_genSeqSQL = "create table if not exists %s (id int not null)";
var $_genSeqCountSQL = "select count(*) from %s";
var $_genSeq2SQL = "insert into %s values (%s)";
var $_dropSeqSQL = "drop table if exists %s";
function CreateSequence($seqname='adodbseq',$startID=1)
{
if (empty($this->_genSeqSQL)) return false;
$u = strtoupper($seqname);
$ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
if (!$ok) return false;
return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
}
function GenID($seqname='adodbseq',$startID=1)
{
// post-nuke sets hasGenID to false
if (!$this->hasGenID) return false;
$savelog = $this->_logsql;
$this->_logsql = false;
$getnext = sprintf($this->_genIDSQL,$seqname);
$holdtransOK = $this->_transOK; // save the current status
$rs = @$this->Execute($getnext);
if (!$rs) {
if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset
$u = strtoupper($seqname);
$this->Execute(sprintf($this->_genSeqSQL,$seqname));
$cnt = $this->GetOne(sprintf($this->_genSeqCountSQL,$seqname));
if (!$cnt) $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
$rs = $this->Execute($getnext);
}
if ($rs) {
$this->genID = mysql_insert_id($this->_connectionID);
$rs->Close();
} else
$this->genID = 0;
$this->_logsql = $savelog;
return $this->genID;
}
function MetaDatabases()
{
$qid = mysql_list_dbs($this->_connectionID);
$arr = array();
$i = 0;
$max = mysql_num_rows($qid);
while ($i < $max) {
$db = mysql_tablename($qid,$i);
if ($db != 'mysql') $arr[] = $db;
$i += 1;
}
return $arr;
}
// Format date column in sql string given an input format that understands Y M D
function SQLDate($fmt, $col=false)
{
if (!$col) $col = $this->sysTimeStamp;
$s = 'DATE_FORMAT('.$col.",'";
$concat = false;
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
$ch = $fmt[$i];
switch($ch) {
default:
if ($ch == '\\') {
$i++;
$ch = substr($fmt,$i,1);
}
/** FALL THROUGH */
case '-':
case '/':
$s .= $ch;
break;
case 'Y':
case 'y':
$s .= '%Y';
break;
case 'M':
$s .= '%b';
break;
case 'm':
$s .= '%m';
break;
case 'D':
case 'd':
$s .= '%d';
break;
case 'Q':
case 'q':
$s .= "'),Quarter($col)";
if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";
else $s .= ",('";
$concat = true;
break;
case 'H':
$s .= '%H';
break;
case 'h':
$s .= '%I';
break;
case 'i':
$s .= '%i';
break;
case 's':
$s .= '%s';
break;
case 'a':
case 'A':
$s .= '%p';
break;
case 'w':
$s .= '%w';
break;
case 'W':
$s .= '%U';
break;
case 'l':
$s .= '%W';
break;
}
}
$s.="')";
if ($concat) $s = "CONCAT($s)";
return $s;
}
// returns concatenated string
// much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator
function Concat()
{
$s = "";
$arr = func_get_args();
// suggestion by andrew005@mnogo.ru
$s = implode(',',$arr);
if (strlen($s) > 0) return "CONCAT($s)";
else return '';
}
function OffsetDate($dayFraction,$date=false)
{
if (!$date) $date = $this->sysDate;
$fraction = $dayFraction * 24 * 3600;
return '('. $date . ' + INTERVAL ' . $fraction.' SECOND)';
// return "from_unixtime(unix_timestamp($date)+$fraction)";
}
// returns true or false
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (!empty($this->port)) $argHostname .= ":".$this->port;
if (ADODB_PHPVER >= 0x4300)
$this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
$this->forceNewConnect,$this->clientFlags);
else if (ADODB_PHPVER >= 0x4200)
$this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
$this->forceNewConnect);
else
$this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
// returns true or false
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (!empty($this->port)) $argHostname .= ":".$this->port;
if (ADODB_PHPVER >= 0x4300)
$this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags);
else
$this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($this->autoRollback) $this->RollbackTrans();
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$this->forceNewConnect = true;
return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
}
function MetaColumns($table, $normalize=true)
{
$this->_findschema($table,$schema);
if ($schema) {
$dbName = $this->database;
$this->SelectDB($schema);
}
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
if ($schema) {
$this->SelectDB($dbName);
}
if (isset($savem)) $this->SetFetchMode($savem);
$ADODB_FETCH_MODE = $save;
if (!is_object($rs)) {
$false = false;
return $false;
}
$retarr = array();
while (!$rs->EOF){
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$type = $rs->fields[1];
// split type into type(length):
$fld->scale = null;
if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {
$fld->type = $query_array[1];
$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
$fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;
} elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
$fld->type = $query_array[1];
$fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
} elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) {
$fld->type = $query_array[1];
$arr = explode(",",$query_array[2]);
$fld->enums = $arr;
$zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6
$fld->max_length = ($zlen > 0) ? $zlen : 1;
} else {
$fld->type = $type;
$fld->max_length = -1;
}
$fld->not_null = ($rs->fields[2] != 'YES');
$fld->primary_key = ($rs->fields[3] == 'PRI');
$fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
$fld->binary = (strpos($type,'blob') !== false || strpos($type,'binary') !== false);
$fld->unsigned = (strpos($type,'unsigned') !== false);
$fld->zerofill = (strpos($type,'zerofill') !== false);
if (!$fld->binary) {
$d = $rs->fields[4];
if ($d != '' && $d != 'NULL') {
$fld->has_default = true;
$fld->default_value = $d;
} else {
$fld->has_default = false;
}
}
if ($save == ADODB_FETCH_NUM) {
$retarr[] = $fld;
} else {
$retarr[strtoupper($fld->name)] = $fld;
}
$rs->MoveNext();
}
$rs->Close();
return $retarr;
}
// returns true or false
function SelectDB($dbName)
{
$this->database = $dbName;
$this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
if ($this->_connectionID) {
return @mysql_select_db($dbName,$this->_connectionID);
}
else return false;
}
// parameters use PostgreSQL convention, not MySQL
function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0)
{
$nrows = (int) $nrows;
$offset = (int) $offset;
$offsetStr =($offset>=0) ? ((integer)$offset)."," : '';
// jason judge, see http://phplens.com/lens/lensforum/msgs.php?id=9220
if ($nrows < 0) $nrows = '18446744073709551615';
if ($secs)
$rs = $this->CacheExecute($secs,$sql." LIMIT $offsetStr".((integer)$nrows),$inputarr);
else
$rs = $this->Execute($sql." LIMIT $offsetStr".((integer)$nrows),$inputarr);
return $rs;
}
// returns queryID or false
function _query($sql,$inputarr=false)
{
return mysql_query($sql,$this->_connectionID);
/*
global $ADODB_COUNTRECS;
if($ADODB_COUNTRECS)
return mysql_query($sql,$this->_connectionID);
else
return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6
*/
}
/* Returns: the last error message from previous database operation */
function ErrorMsg()
{
if ($this->_logsql) return $this->_errorMsg;
if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error();
else $this->_errorMsg = @mysql_error($this->_connectionID);
return $this->_errorMsg;
}
/* Returns: the last error number from previous database operation */
function ErrorNo()
{
if ($this->_logsql) return $this->_errorCode;
if (empty($this->_connectionID)) return @mysql_errno();
else return @mysql_errno($this->_connectionID);
}
// returns true or false
function _close()
{
@mysql_close($this->_connectionID);
$this->charSet = '';
$this->_connectionID = false;
}
/*
* Maximum size of C field
*/
function CharMax()
{
return 255;
}
/*
* Maximum size of X field
*/
function TextMax()
{
return 4294967295;
}
// "Innox - Juan Carlos Gonzalez" <jgonzalez#innox.com.mx>
function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $associative = FALSE )
{
global $ADODB_FETCH_MODE;
if ($ADODB_FETCH_MODE == ADODB_FETCH_ASSOC || $this->fetchMode == ADODB_FETCH_ASSOC) $associative = true;
if ( !empty($owner) ) {
$table = "$owner.$table";
}
$a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
if ($associative) {
$create_sql = isset($a_create_table["Create Table"]) ? $a_create_table["Create Table"] : $a_create_table["Create View"];
} else {
$create_sql = $a_create_table[1];
}
$matches = array();
if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false;
$foreign_keys = array();
$num_keys = count($matches[0]);
for ( $i = 0; $i < $num_keys; $i ++ ) {
$my_field = explode('`, `', $matches[1][$i]);
$ref_table = $matches[2][$i];
$ref_field = explode('`, `', $matches[3][$i]);
if ( $upper ) {
$ref_table = strtoupper($ref_table);
}
// see https://sourceforge.net/tracker/index.php?func=detail&aid=2287278&group_id=42718&atid=433976
if (!isset($foreign_keys[$ref_table])) {
$foreign_keys[$ref_table] = array();
}
$num_fields = count($my_field);
for ( $j = 0; $j < $num_fields; $j ++ ) {
if ( $associative ) {
$foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
} else {
$foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
}
}
}
return $foreign_keys;
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordSet_mysql extends ADORecordSet{
var $databaseType = "mysql";
var $canSeek = true;
function __construct($queryID,$mode=false)
{
if ($mode === false) {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
switch ($mode)
{
case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
case ADODB_FETCH_DEFAULT:
case ADODB_FETCH_BOTH:
default:
$this->fetchMode = MYSQL_BOTH; break;
}
$this->adodbFetchMode = $mode;
parent::__construct($queryID);
}
function _initrs()
{
//GLOBAL $ADODB_COUNTRECS;
// $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1;
$this->_numOfRows = @mysql_num_rows($this->_queryID);
$this->_numOfFields = @mysql_num_fields($this->_queryID);
}
function FetchField($fieldOffset = -1)
{
if ($fieldOffset != -1) {
$o = @mysql_fetch_field($this->_queryID, $fieldOffset);
$f = @mysql_field_flags($this->_queryID,$fieldOffset);
if ($o) $o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich#att.com)
//$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
if ($o) $o->binary = (strpos($f,'binary')!== false);
}
else { /* The $fieldOffset argument is not provided thus its -1 */
$o = @mysql_fetch_field($this->_queryID);
//if ($o) $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich#att.com)
$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
}
return $o;
}
function GetRowAssoc($upper = ADODB_ASSOC_CASE)
{
if ($this->fetchMode == MYSQL_ASSOC && $upper == ADODB_ASSOC_CASE_LOWER) {
$row = $this->fields;
}
else {
$row = ADORecordSet::GetRowAssoc($upper);
}
return $row;
}
/* Use associative array to get fields array */
function Fields($colname)
{
// added @ by "Michael William Miller" <mille562@pilot.msu.edu>
if ($this->fetchMode != MYSQL_NUM) return @$this->fields[$colname];
if (!$this->bind) {
$this->bind = array();
for ($i=0; $i < $this->_numOfFields; $i++) {
$o = $this->FetchField($i);
$this->bind[strtoupper($o->name)] = $i;
}
}
return $this->fields[$this->bind[strtoupper($colname)]];
}
function _seek($row)
{
if ($this->_numOfRows == 0) return false;
return @mysql_data_seek($this->_queryID,$row);
}
function MoveNext()
{
if (@$this->fields = mysql_fetch_array($this->_queryID,$this->fetchMode)) {
$this->_updatefields();
$this->_currentRow += 1;
return true;
}
if (!$this->EOF) {
$this->_currentRow += 1;
$this->EOF = true;
}
return false;
}
function _fetch()
{
$this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);
$this->_updatefields();
return is_array($this->fields);
}
function _close() {
@mysql_free_result($this->_queryID);
$this->_queryID = false;
}
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$len = -1; // mysql max_length is not accurate
switch (strtoupper($t)) {
case 'STRING':
case 'CHAR':
case 'VARCHAR':
case 'TINYBLOB':
case 'TINYTEXT':
case 'ENUM':
case 'SET':
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
case 'LONGTEXT':
case 'MEDIUMTEXT':
return 'X';
// php_mysql extension always returns 'blob' even if 'text'
// so we have to check whether binary...
case 'IMAGE':
case 'LONGBLOB':
case 'BLOB':
case 'MEDIUMBLOB':
case 'BINARY':
return !empty($fieldobj->binary) ? 'B' : 'X';
case 'YEAR':
case 'DATE': return 'D';
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP': return 'T';
case 'INT':
case 'INTEGER':
case 'BIGINT':
case 'TINYINT':
case 'MEDIUMINT':
case 'SMALLINT':
if (!empty($fieldobj->primary_key)) return 'R';
else return 'I';
default: return ADODB_DEFAULT_METATYPE;
}
}
}
class ADORecordSet_ext_mysql extends ADORecordSet_mysql {
function MoveNext()
{
return @adodb_movenext($this);
}
}
}
| ipso/ADOdb | drivers/adodb-mysql.inc.php | PHP | lgpl-2.1 | 23,092 |
/**
* @author : Paul Taylor
* @author : Eric Farng
*
* Version @version:$Id$
*
* MusicTag Copyright (C)2003,2004
*
* 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,
* you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Description:
*
*/
package org.jaudiotagger.tag.id3.framebody;
import org.jaudiotagger.tag.InvalidTagException;
import org.jaudiotagger.tag.id3.ID3v24Frames;
import java.nio.ByteBuffer;
/**
* Title Sort name
*/
public class FrameBodyTSOT extends AbstractFrameBodyTextInfo implements ID3v24FrameBody, ID3v23FrameBody
{
/**
* Creates a new FrameBodyTSOT datatype.
*/
public FrameBodyTSOT()
{
}
public FrameBodyTSOT(FrameBodyTSOT body)
{
super(body);
}
/**
* Creates a new FrameBodyTSOT datatype.
*
* @param textEncoding
* @param text
*/
public FrameBodyTSOT(byte textEncoding, String text)
{
super(textEncoding, text);
}
/**
* Creates a new FrameBodyTSOT datatype.
*
* @param byteBuffer
* @param frameSize
* @throws InvalidTagException
*/
public FrameBodyTSOT(ByteBuffer byteBuffer, int frameSize) throws InvalidTagException
{
super(byteBuffer, frameSize);
}
/**
* The ID3v2 frame identifier
*
* @return the ID3v2 frame identifier for this frame type
*/
public String getIdentifier()
{
return ID3v24Frames.FRAME_ID_TITLE_SORT_ORDER;
}
}
| craigpetchell/Jaudiotagger | src/org/jaudiotagger/tag/id3/framebody/FrameBodyTSOT.java | Java | lgpl-2.1 | 2,188 |
/* Generated from ../../../git/cloog/test/forwardsub-3-1-2.cloog by CLooG 0.14.0-136-gb91ef26 gmp bits in 0.02s. */
S3(2,1) ;
S1(3,1) ;
S1(4,1) ;
S4(4,2) ;
for (i=5;i<=M+1;i++) {
S1(i,1) ;
for (j=2;j<=floord(i-1,2);j++) {
S2(i,j) ;
}
if (i%2 == 0) {
S4(i,i/2) ;
}
}
for (i=M+2;i<=2*M-1;i++) {
for (j=i-M;j<=floord(i-1,2);j++) {
S2(i,j) ;
}
if (i%2 == 0) {
S4(i,i/2) ;
}
}
S4(2*M,M) ;
| epowers/cloog | test/forwardsub-3-1-2.c | C | lgpl-2.1 | 418 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.