repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
GREO/GNU-Radio | gr-atsc/src/lib/atsc_rs_decoder.cc | 1900 | /* -*- c++ -*- */
/*
* Copyright 2006 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 GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <atsc_rs_decoder.h>
#include <gr_io_signature.h>
#include <atsc_consts.h>
atsc_rs_decoder_sptr
atsc_make_rs_decoder()
{
return atsc_rs_decoder_sptr(new atsc_rs_decoder());
}
atsc_rs_decoder::atsc_rs_decoder()
: gr_sync_block("atsc_rs_decoder",
gr_make_io_signature(1, 1, sizeof(atsc_mpeg_packet_rs_encoded)),
gr_make_io_signature(1, 1, sizeof(atsc_mpeg_packet_no_sync)))
{
reset();
}
int
atsc_rs_decoder::work (int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
const atsc_mpeg_packet_rs_encoded *in = (const atsc_mpeg_packet_rs_encoded *) input_items[0];
atsc_mpeg_packet_no_sync *out = (atsc_mpeg_packet_no_sync *) output_items[0];
for (int i = 0; i < noutput_items; i++){
assert(in[i].pli.regular_seg_p());
out[i].pli = in[i].pli; // copy pipeline info...
int nerrors_corrrected = d_rs_decoder.decode(out[i], in[i]);
out[i].pli.set_transport_error(nerrors_corrrected == -1);
}
return noutput_items;
}
| gpl-3.0 |
nagyistoce/moodle | lib/dml/tests/dml_test.php | 256559 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* DML layer tests.
*
* @package core_dml
* @category phpunit
* @copyright 2008 Nicolas Connault
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
class core_dml_testcase extends database_driver_testcase {
protected function setUp() {
parent::setUp();
$dbman = $this->tdb->get_manager(); // Loads DDL libs.
}
/**
* Get a xmldb_table object for testing, deleting any existing table
* of the same name, for example if one was left over from a previous test
* run that crashed.
*
* @param string $suffix table name suffix, use if you need more test tables
* @return xmldb_table the table object.
*/
private function get_test_table($suffix = '') {
$tablename = "test_table";
if ($suffix !== '') {
$tablename .= $suffix;
}
$table = new xmldb_table($tablename);
$table->setComment("This is a test'n drop table. You can drop it safely");
return $table;
}
public function test_diagnose() {
$DB = $this->tdb;
$result = $DB->diagnose();
$this->assertNull($result, 'Database self diagnostics failed %s');
}
public function test_get_server_info() {
$DB = $this->tdb;
$result = $DB->get_server_info();
$this->assertInternalType('array', $result);
$this->assertArrayHasKey('description', $result);
$this->assertArrayHasKey('version', $result);
}
public function test_get_in_or_equal() {
$DB = $this->tdb;
// SQL_PARAMS_QM - IN or =.
// Correct usage of multiple values.
$in_values = array('value1', 'value2', '3', 4, null, false, true);
list($usql, $params) = $DB->get_in_or_equal($in_values);
$this->assertSame('IN ('.implode(',', array_fill(0, count($in_values), '?')).')', $usql);
$this->assertEquals(count($in_values), count($params));
foreach ($params as $key => $value) {
$this->assertSame($in_values[$key], $value);
}
// Correct usage of single value (in an array).
$in_values = array('value1');
list($usql, $params) = $DB->get_in_or_equal($in_values);
$this->assertEquals("= ?", $usql);
$this->assertCount(1, $params);
$this->assertEquals($in_values[0], $params[0]);
// Correct usage of single value.
$in_value = 'value1';
list($usql, $params) = $DB->get_in_or_equal($in_values);
$this->assertEquals("= ?", $usql);
$this->assertCount(1, $params);
$this->assertEquals($in_value, $params[0]);
// SQL_PARAMS_QM - NOT IN or <>.
// Correct usage of multiple values.
$in_values = array('value1', 'value2', 'value3', 'value4');
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, null, false);
$this->assertEquals("NOT IN (?,?,?,?)", $usql);
$this->assertCount(4, $params);
foreach ($params as $key => $value) {
$this->assertEquals($in_values[$key], $value);
}
// Correct usage of single value (in array().
$in_values = array('value1');
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, null, false);
$this->assertEquals("<> ?", $usql);
$this->assertCount(1, $params);
$this->assertEquals($in_values[0], $params[0]);
// Correct usage of single value.
$in_value = 'value1';
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, null, false);
$this->assertEquals("<> ?", $usql);
$this->assertCount(1, $params);
$this->assertEquals($in_value, $params[0]);
// SQL_PARAMS_NAMED - IN or =.
// Correct usage of multiple values.
$in_values = array('value1', 'value2', 'value3', 'value4');
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', true);
$this->assertCount(4, $params);
reset($in_values);
$ps = array();
foreach ($params as $key => $value) {
$this->assertEquals(current($in_values), $value);
next($in_values);
$ps[] = ':'.$key;
}
$this->assertEquals("IN (".implode(',', $ps).")", $usql);
// Correct usage of single values (in array).
$in_values = array('value1');
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', true);
$this->assertCount(1, $params);
$value = reset($params);
$key = key($params);
$this->assertEquals("= :$key", $usql);
$this->assertEquals($in_value, $value);
// Correct usage of single value.
$in_value = 'value1';
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', true);
$this->assertCount(1, $params);
$value = reset($params);
$key = key($params);
$this->assertEquals("= :$key", $usql);
$this->assertEquals($in_value, $value);
// SQL_PARAMS_NAMED - NOT IN or <>.
// Correct usage of multiple values.
$in_values = array('value1', 'value2', 'value3', 'value4');
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false);
$this->assertCount(4, $params);
reset($in_values);
$ps = array();
foreach ($params as $key => $value) {
$this->assertEquals(current($in_values), $value);
next($in_values);
$ps[] = ':'.$key;
}
$this->assertEquals("NOT IN (".implode(',', $ps).")", $usql);
// Correct usage of single values (in array).
$in_values = array('value1');
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false);
$this->assertCount(1, $params);
$value = reset($params);
$key = key($params);
$this->assertEquals("<> :$key", $usql);
$this->assertEquals($in_value, $value);
// Correct usage of single value.
$in_value = 'value1';
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false);
$this->assertCount(1, $params);
$value = reset($params);
$key = key($params);
$this->assertEquals("<> :$key", $usql);
$this->assertEquals($in_value, $value);
// Make sure the param names are unique.
list($usql1, $params1) = $DB->get_in_or_equal(array(1, 2, 3), SQL_PARAMS_NAMED, 'param');
list($usql2, $params2) = $DB->get_in_or_equal(array(1, 2, 3), SQL_PARAMS_NAMED, 'param');
$params1 = array_keys($params1);
$params2 = array_keys($params2);
$common = array_intersect($params1, $params2);
$this->assertCount(0, $common);
// Some incorrect tests.
// Incorrect usage passing not-allowed params type.
$in_values = array(1, 2, 3);
try {
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_DOLLAR, 'param', false);
$this->fail('An Exception is missing, expected due to not supported SQL_PARAMS_DOLLAR');
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
$this->assertSame('typenotimplement', $e->errorcode);
}
// Incorrect usage passing empty array.
$in_values = array();
try {
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false);
$this->fail('An Exception is missing, expected due to empty array of items');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
// Test using $onemptyitems.
// Correct usage passing empty array and $onemptyitems = null (equal = true, QM).
$in_values = array();
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, 'param', true, null);
$this->assertSame(' IS NULL', $usql);
$this->assertSame(array(), $params);
// Correct usage passing empty array and $onemptyitems = null (equal = false, NAMED).
$in_values = array();
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false, null);
$this->assertSame(' IS NOT NULL', $usql);
$this->assertSame(array(), $params);
// Correct usage passing empty array and $onemptyitems = true (equal = true, QM).
$in_values = array();
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, 'param', true, true);
$this->assertSame('= ?', $usql);
$this->assertSame(array(true), $params);
// Correct usage passing empty array and $onemptyitems = true (equal = false, NAMED).
$in_values = array();
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false, true);
$this->assertCount(1, $params);
$value = reset($params);
$key = key($params);
$this->assertSame('<> :'.$key, $usql);
$this->assertSame($value, true);
// Correct usage passing empty array and $onemptyitems = -1 (equal = true, QM).
$in_values = array();
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, 'param', true, -1);
$this->assertSame('= ?', $usql);
$this->assertSame(array(-1), $params);
// Correct usage passing empty array and $onemptyitems = -1 (equal = false, NAMED).
$in_values = array();
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false, -1);
$this->assertCount(1, $params);
$value = reset($params);
$key = key($params);
$this->assertSame('<> :'.$key, $usql);
$this->assertSame($value, -1);
// Correct usage passing empty array and $onemptyitems = 'onevalue' (equal = true, QM).
$in_values = array();
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_QM, 'param', true, 'onevalue');
$this->assertSame('= ?', $usql);
$this->assertSame(array('onevalue'), $params);
// Correct usage passing empty array and $onemptyitems = 'onevalue' (equal = false, NAMED).
$in_values = array();
list($usql, $params) = $DB->get_in_or_equal($in_values, SQL_PARAMS_NAMED, 'param', false, 'onevalue');
$this->assertCount(1, $params);
$value = reset($params);
$key = key($params);
$this->assertSame('<> :'.$key, $usql);
$this->assertSame($value, 'onevalue');
}
public function test_fix_table_names() {
$DB = new moodle_database_for_testing();
$prefix = $DB->get_prefix();
// Simple placeholder.
$placeholder = "{user_123}";
$this->assertSame($prefix."user_123", $DB->public_fix_table_names($placeholder));
// Wrong table name.
$placeholder = "{user-a}";
$this->assertSame($placeholder, $DB->public_fix_table_names($placeholder));
// Wrong table name.
$placeholder = "{123user}";
$this->assertSame($placeholder, $DB->public_fix_table_names($placeholder));
// Full SQL.
$sql = "SELECT * FROM {user}, {funny_table_name}, {mdl_stupid_table} WHERE {user}.id = {funny_table_name}.userid";
$expected = "SELECT * FROM {$prefix}user, {$prefix}funny_table_name, {$prefix}mdl_stupid_table WHERE {$prefix}user.id = {$prefix}funny_table_name.userid";
$this->assertSame($expected, $DB->public_fix_table_names($sql));
}
public function test_fix_sql_params() {
$DB = $this->tdb;
$prefix = $DB->get_prefix();
$table = $this->get_test_table();
$tablename = $table->getName();
// Correct table placeholder substitution.
$sql = "SELECT * FROM {{$tablename}}";
$sqlarray = $DB->fix_sql_params($sql);
$this->assertEquals("SELECT * FROM {$prefix}".$tablename, $sqlarray[0]);
// Conversions of all param types.
$sql = array();
$sql[SQL_PARAMS_NAMED] = "SELECT * FROM {$prefix}testtable WHERE name = :param1, course = :param2";
$sql[SQL_PARAMS_QM] = "SELECT * FROM {$prefix}testtable WHERE name = ?, course = ?";
$sql[SQL_PARAMS_DOLLAR] = "SELECT * FROM {$prefix}testtable WHERE name = \$1, course = \$2";
$params = array();
$params[SQL_PARAMS_NAMED] = array('param1'=>'first record', 'param2'=>1);
$params[SQL_PARAMS_QM] = array('first record', 1);
$params[SQL_PARAMS_DOLLAR] = array('first record', 1);
list($rsql, $rparams, $rtype) = $DB->fix_sql_params($sql[SQL_PARAMS_NAMED], $params[SQL_PARAMS_NAMED]);
$this->assertSame($rsql, $sql[$rtype]);
$this->assertSame($rparams, $params[$rtype]);
list($rsql, $rparams, $rtype) = $DB->fix_sql_params($sql[SQL_PARAMS_QM], $params[SQL_PARAMS_QM]);
$this->assertSame($rsql, $sql[$rtype]);
$this->assertSame($rparams, $params[$rtype]);
list($rsql, $rparams, $rtype) = $DB->fix_sql_params($sql[SQL_PARAMS_DOLLAR], $params[SQL_PARAMS_DOLLAR]);
$this->assertSame($rsql, $sql[$rtype]);
$this->assertSame($rparams, $params[$rtype]);
// Malformed table placeholder.
$sql = "SELECT * FROM [testtable]";
$sqlarray = $DB->fix_sql_params($sql);
$this->assertSame($sql, $sqlarray[0]);
// Mixed param types (colon and dollar).
$sql = "SELECT * FROM {{$tablename}} WHERE name = :param1, course = \$1";
$params = array('param1' => 'record1', 'param2' => 3);
try {
$DB->fix_sql_params($sql, $params);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
// Mixed param types (question and dollar).
$sql = "SELECT * FROM {{$tablename}} WHERE name = ?, course = \$1";
$params = array('param1' => 'record2', 'param2' => 5);
try {
$DB->fix_sql_params($sql, $params);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
// Too few params in sql.
$sql = "SELECT * FROM {{$tablename}} WHERE name = ?, course = ?, id = ?";
$params = array('record2', 3);
try {
$DB->fix_sql_params($sql, $params);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
// Too many params in array: no error, just use what is necessary.
$params[] = 1;
$params[] = time();
$sqlarray = $DB->fix_sql_params($sql, $params);
$this->assertInternalType('array', $sqlarray);
$this->assertCount(3, $sqlarray[1]);
// Named params missing from array.
$sql = "SELECT * FROM {{$tablename}} WHERE name = :name, course = :course";
$params = array('wrongname' => 'record1', 'course' => 1);
try {
$DB->fix_sql_params($sql, $params);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
// Duplicate named param in query - this is a very important feature!!
// it helps with debugging of sloppy code.
$sql = "SELECT * FROM {{$tablename}} WHERE name = :name, course = :name";
$params = array('name' => 'record2', 'course' => 3);
try {
$DB->fix_sql_params($sql, $params);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
// Extra named param is ignored.
$sql = "SELECT * FROM {{$tablename}} WHERE name = :name, course = :course";
$params = array('name' => 'record1', 'course' => 1, 'extrastuff'=>'haha');
$sqlarray = $DB->fix_sql_params($sql, $params);
$this->assertInternalType('array', $sqlarray);
$this->assertCount(2, $sqlarray[1]);
// Params exceeding 30 chars length.
$sql = "SELECT * FROM {{$tablename}} WHERE name = :long_placeholder_with_more_than_30";
$params = array('long_placeholder_with_more_than_30' => 'record1');
try {
$DB->fix_sql_params($sql, $params);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
// Booleans in NAMED params are casting to 1/0 int.
$sql = "SELECT * FROM {{$tablename}} WHERE course = ? OR course = ?";
$params = array(true, false);
list($sql, $params) = $DB->fix_sql_params($sql, $params);
$this->assertTrue(reset($params) === 1);
$this->assertTrue(next($params) === 0);
// Booleans in QM params are casting to 1/0 int.
$sql = "SELECT * FROM {{$tablename}} WHERE course = :course1 OR course = :course2";
$params = array('course1' => true, 'course2' => false);
list($sql, $params) = $DB->fix_sql_params($sql, $params);
$this->assertTrue(reset($params) === 1);
$this->assertTrue(next($params) === 0);
// Booleans in DOLLAR params are casting to 1/0 int.
$sql = "SELECT * FROM {{$tablename}} WHERE course = \$1 OR course = \$2";
$params = array(true, false);
list($sql, $params) = $DB->fix_sql_params($sql, $params);
$this->assertTrue(reset($params) === 1);
$this->assertTrue(next($params) === 0);
// No data types are touched except bool.
$sql = "SELECT * FROM {{$tablename}} WHERE name IN (?,?,?,?,?,?)";
$inparams = array('abc', 'ABC', null, '1', 1, 1.4);
list($sql, $params) = $DB->fix_sql_params($sql, $inparams);
$this->assertSame(array_values($params), array_values($inparams));
}
public function test_strtok() {
// Strtok was previously used by bound emulation, make sure it is not used any more.
$DB = $this->tdb;
$dbman = $this->tdb->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, 'lala');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$str = 'a?b?c?d';
$this->assertSame(strtok($str, '?'), 'a');
$DB->get_records($tablename, array('id'=>1));
$this->assertSame(strtok('?'), 'b');
}
public function test_tweak_param_names() {
// Note the tweak_param_names() method is only available in the oracle driver,
// hence we look for expected results indirectly, by testing various DML methods.
// with some "extreme" conditions causing the tweak to happen.
$DB = $this->tdb;
$dbman = $this->tdb->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
// Add some columns with 28 chars in the name.
$table->add_field('long_int_columnname_with_28c', XMLDB_TYPE_INTEGER, '10');
$table->add_field('long_dec_columnname_with_28c', XMLDB_TYPE_NUMBER, '10,2');
$table->add_field('long_str_columnname_with_28c', XMLDB_TYPE_CHAR, '100');
// Add some columns with 30 chars in the name.
$table->add_field('long_int_columnname_with_30cxx', XMLDB_TYPE_INTEGER, '10');
$table->add_field('long_dec_columnname_with_30cxx', XMLDB_TYPE_NUMBER, '10,2');
$table->add_field('long_str_columnname_with_30cxx', XMLDB_TYPE_CHAR, '100');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$this->assertTrue($dbman->table_exists($tablename));
// Test insert record.
$rec1 = new stdClass();
$rec1->long_int_columnname_with_28c = 28;
$rec1->long_dec_columnname_with_28c = 28.28;
$rec1->long_str_columnname_with_28c = '28';
$rec1->long_int_columnname_with_30cxx = 30;
$rec1->long_dec_columnname_with_30cxx = 30.30;
$rec1->long_str_columnname_with_30cxx = '30';
// Insert_record().
$rec1->id = $DB->insert_record($tablename, $rec1);
$this->assertEquals($rec1, $DB->get_record($tablename, array('id' => $rec1->id)));
// Update_record().
$DB->update_record($tablename, $rec1);
$this->assertEquals($rec1, $DB->get_record($tablename, array('id' => $rec1->id)));
// Set_field().
$rec1->long_int_columnname_with_28c = 280;
$DB->set_field($tablename, 'long_int_columnname_with_28c', $rec1->long_int_columnname_with_28c,
array('id' => $rec1->id, 'long_int_columnname_with_28c' => 28));
$rec1->long_dec_columnname_with_28c = 280.28;
$DB->set_field($tablename, 'long_dec_columnname_with_28c', $rec1->long_dec_columnname_with_28c,
array('id' => $rec1->id, 'long_dec_columnname_with_28c' => 28.28));
$rec1->long_str_columnname_with_28c = '280';
$DB->set_field($tablename, 'long_str_columnname_with_28c', $rec1->long_str_columnname_with_28c,
array('id' => $rec1->id, 'long_str_columnname_with_28c' => '28'));
$rec1->long_int_columnname_with_30cxx = 300;
$DB->set_field($tablename, 'long_int_columnname_with_30cxx', $rec1->long_int_columnname_with_30cxx,
array('id' => $rec1->id, 'long_int_columnname_with_30cxx' => 30));
$rec1->long_dec_columnname_with_30cxx = 300.30;
$DB->set_field($tablename, 'long_dec_columnname_with_30cxx', $rec1->long_dec_columnname_with_30cxx,
array('id' => $rec1->id, 'long_dec_columnname_with_30cxx' => 30.30));
$rec1->long_str_columnname_with_30cxx = '300';
$DB->set_field($tablename, 'long_str_columnname_with_30cxx', $rec1->long_str_columnname_with_30cxx,
array('id' => $rec1->id, 'long_str_columnname_with_30cxx' => '30'));
$this->assertEquals($rec1, $DB->get_record($tablename, array('id' => $rec1->id)));
// Delete_records().
$rec2 = $DB->get_record($tablename, array('id' => $rec1->id));
$rec2->id = $DB->insert_record($tablename, $rec2);
$this->assertEquals(2, $DB->count_records($tablename));
$DB->delete_records($tablename, (array) $rec2);
$this->assertEquals(1, $DB->count_records($tablename));
// Get_recordset().
$rs = $DB->get_recordset($tablename, (array) $rec1);
$iterations = 0;
foreach ($rs as $rec2) {
$iterations++;
}
$rs->close();
$this->assertEquals(1, $iterations);
$this->assertEquals($rec1, $rec2);
// Get_records().
$recs = $DB->get_records($tablename, (array) $rec1);
$this->assertCount(1, $recs);
$this->assertEquals($rec1, reset($recs));
// Get_fieldset_select().
$select = 'id = :id AND
long_int_columnname_with_28c = :long_int_columnname_with_28c AND
long_dec_columnname_with_28c = :long_dec_columnname_with_28c AND
long_str_columnname_with_28c = :long_str_columnname_with_28c AND
long_int_columnname_with_30cxx = :long_int_columnname_with_30cxx AND
long_dec_columnname_with_30cxx = :long_dec_columnname_with_30cxx AND
long_str_columnname_with_30cxx = :long_str_columnname_with_30cxx';
$fields = $DB->get_fieldset_select($tablename, 'long_int_columnname_with_28c', $select, (array)$rec1);
$this->assertCount(1, $fields);
$this->assertEquals($rec1->long_int_columnname_with_28c, reset($fields));
$fields = $DB->get_fieldset_select($tablename, 'long_dec_columnname_with_28c', $select, (array)$rec1);
$this->assertEquals($rec1->long_dec_columnname_with_28c, reset($fields));
$fields = $DB->get_fieldset_select($tablename, 'long_str_columnname_with_28c', $select, (array)$rec1);
$this->assertEquals($rec1->long_str_columnname_with_28c, reset($fields));
$fields = $DB->get_fieldset_select($tablename, 'long_int_columnname_with_30cxx', $select, (array)$rec1);
$this->assertEquals($rec1->long_int_columnname_with_30cxx, reset($fields));
$fields = $DB->get_fieldset_select($tablename, 'long_dec_columnname_with_30cxx', $select, (array)$rec1);
$this->assertEquals($rec1->long_dec_columnname_with_30cxx, reset($fields));
$fields = $DB->get_fieldset_select($tablename, 'long_str_columnname_with_30cxx', $select, (array)$rec1);
$this->assertEquals($rec1->long_str_columnname_with_30cxx, reset($fields));
// Overlapping placeholders (progressive str_replace).
$overlapselect = 'id = :p AND
long_int_columnname_with_28c = :param1 AND
long_dec_columnname_with_28c = :param2 AND
long_str_columnname_with_28c = :param_with_29_characters_long AND
long_int_columnname_with_30cxx = :param_with_30_characters_long_ AND
long_dec_columnname_with_30cxx = :param_ AND
long_str_columnname_with_30cxx = :param__';
$overlapparams = array(
'p' => $rec1->id,
'param1' => $rec1->long_int_columnname_with_28c,
'param2' => $rec1->long_dec_columnname_with_28c,
'param_with_29_characters_long' => $rec1->long_str_columnname_with_28c,
'param_with_30_characters_long_' => $rec1->long_int_columnname_with_30cxx,
'param_' => $rec1->long_dec_columnname_with_30cxx,
'param__' => $rec1->long_str_columnname_with_30cxx);
$recs = $DB->get_records_select($tablename, $overlapselect, $overlapparams);
$this->assertCount(1, $recs);
$this->assertEquals($rec1, reset($recs));
// Execute().
$DB->execute("DELETE FROM {{$tablename}} WHERE $select", (array)$rec1);
$this->assertEquals(0, $DB->count_records($tablename));
}
public function test_get_tables() {
$DB = $this->tdb;
$dbman = $this->tdb->get_manager();
// Need to test with multiple DBs.
$table = $this->get_test_table();
$tablename = $table->getName();
$original_count = count($DB->get_tables());
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$this->assertTrue(count($DB->get_tables()) == $original_count + 1);
$dbman->drop_table($table);
$this->assertTrue(count($DB->get_tables()) == $original_count);
}
public function test_get_indexes() {
$DB = $this->tdb;
$dbman = $this->tdb->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$table->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course'));
$table->add_index('course-id', XMLDB_INDEX_UNIQUE, array('course', 'id'));
$dbman->create_table($table);
$indices = $DB->get_indexes($tablename);
$this->assertInternalType('array', $indices);
$this->assertCount(2, $indices);
// We do not care about index names for now.
$first = array_shift($indices);
$second = array_shift($indices);
if (count($first['columns']) == 2) {
$composed = $first;
$single = $second;
} else {
$composed = $second;
$single = $first;
}
$this->assertFalse($single['unique']);
$this->assertTrue($composed['unique']);
$this->assertCount(1, $single['columns']);
$this->assertCount(2, $composed['columns']);
$this->assertSame('course', $single['columns'][0]);
$this->assertSame('course', $composed['columns'][0]);
$this->assertSame('id', $composed['columns'][1]);
}
public function test_get_columns() {
$DB = $this->tdb;
$dbman = $this->tdb->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, 'lala');
$table->add_field('description', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
$table->add_field('enumfield', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, 'test2');
$table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null, 200);
$table->add_field('onefloat', XMLDB_TYPE_FLOAT, '10,2', null, null, null, 300);
$table->add_field('anotherfloat', XMLDB_TYPE_FLOAT, null, null, null, null, 400);
$table->add_field('negativedfltint', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '-1');
$table->add_field('negativedfltnumber', XMLDB_TYPE_NUMBER, '10', null, XMLDB_NOTNULL, null, '-2');
$table->add_field('negativedfltfloat', XMLDB_TYPE_FLOAT, '10', null, XMLDB_NOTNULL, null, '-3');
$table->add_field('someint1', XMLDB_TYPE_INTEGER, '1', null, null, null, '0');
$table->add_field('someint2', XMLDB_TYPE_INTEGER, '2', null, null, null, '0');
$table->add_field('someint3', XMLDB_TYPE_INTEGER, '3', null, null, null, '0');
$table->add_field('someint4', XMLDB_TYPE_INTEGER, '4', null, null, null, '0');
$table->add_field('someint5', XMLDB_TYPE_INTEGER, '5', null, null, null, '0');
$table->add_field('someint6', XMLDB_TYPE_INTEGER, '6', null, null, null, '0');
$table->add_field('someint7', XMLDB_TYPE_INTEGER, '7', null, null, null, '0');
$table->add_field('someint8', XMLDB_TYPE_INTEGER, '8', null, null, null, '0');
$table->add_field('someint9', XMLDB_TYPE_INTEGER, '9', null, null, null, '0');
$table->add_field('someint10', XMLDB_TYPE_INTEGER, '10', null, null, null, '0');
$table->add_field('someint18', XMLDB_TYPE_INTEGER, '18', null, null, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$columns = $DB->get_columns($tablename);
$this->assertInternalType('array', $columns);
$fields = $table->getFields();
$this->assertCount(count($columns), $fields);
$field = $columns['id'];
$this->assertSame('R', $field->meta_type);
$this->assertTrue($field->auto_increment);
$this->assertTrue($field->unique);
$field = $columns['course'];
$this->assertSame('I', $field->meta_type);
$this->assertFalse($field->auto_increment);
$this->assertTrue($field->has_default);
$this->assertEquals(0, $field->default_value);
$this->assertTrue($field->not_null);
for ($i=1; $i<=10; $i++) {
$field = $columns['someint'.$i];
$this->assertSame('I', $field->meta_type);
$this->assertGreaterThanOrEqual($i, $field->max_length);
}
$field = $columns['someint18'];
$this->assertSame('I', $field->meta_type);
$this->assertGreaterThanOrEqual(18, $field->max_length);
$field = $columns['name'];
$this->assertSame('C', $field->meta_type);
$this->assertFalse($field->auto_increment);
$this->assertEquals(255, $field->max_length);
$this->assertTrue($field->has_default);
$this->assertSame('lala', $field->default_value);
$this->assertFalse($field->not_null);
$field = $columns['description'];
$this->assertSame('X', $field->meta_type);
$this->assertFalse($field->auto_increment);
$this->assertFalse($field->has_default);
$this->assertNull($field->default_value);
$this->assertFalse($field->not_null);
$field = $columns['enumfield'];
$this->assertSame('C', $field->meta_type);
$this->assertFalse($field->auto_increment);
$this->assertSame('test2', $field->default_value);
$this->assertTrue($field->not_null);
$field = $columns['onenum'];
$this->assertSame('N', $field->meta_type);
$this->assertFalse($field->auto_increment);
$this->assertEquals(10, $field->max_length);
$this->assertEquals(2, $field->scale);
$this->assertTrue($field->has_default);
$this->assertEquals(200.0, $field->default_value);
$this->assertFalse($field->not_null);
$field = $columns['onefloat'];
$this->assertSame('N', $field->meta_type);
$this->assertFalse($field->auto_increment);
$this->assertTrue($field->has_default);
$this->assertEquals(300.0, $field->default_value);
$this->assertFalse($field->not_null);
$field = $columns['anotherfloat'];
$this->assertSame('N', $field->meta_type);
$this->assertFalse($field->auto_increment);
$this->assertTrue($field->has_default);
$this->assertEquals(400.0, $field->default_value);
$this->assertFalse($field->not_null);
// Test negative defaults in numerical columns.
$field = $columns['negativedfltint'];
$this->assertTrue($field->has_default);
$this->assertEquals(-1, $field->default_value);
$field = $columns['negativedfltnumber'];
$this->assertTrue($field->has_default);
$this->assertEquals(-2, $field->default_value);
$field = $columns['negativedfltfloat'];
$this->assertTrue($field->has_default);
$this->assertEquals(-3, $field->default_value);
for ($i = 0; $i < count($columns); $i++) {
if ($i == 0) {
$next_column = reset($columns);
$next_field = reset($fields);
} else {
$next_column = next($columns);
$next_field = next($fields);
}
$this->assertEquals($next_column->name, $next_field->getName());
}
// Test get_columns for non-existing table returns empty array. MDL-30147.
$columns = $DB->get_columns('xxxx');
$this->assertEquals(array(), $columns);
// Create something similar to "context_temp" with id column without sequence.
$dbman->drop_table($table);
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$columns = $DB->get_columns($tablename);
$this->assertFalse($columns['id']->auto_increment);
}
public function test_get_manager() {
$DB = $this->tdb;
$dbman = $this->tdb->get_manager();
$this->assertInstanceOf('database_manager', $dbman);
}
public function test_setup_is_unicodedb() {
$DB = $this->tdb;
$this->assertTrue($DB->setup_is_unicodedb());
}
public function test_set_debug() { // Tests get_debug() too.
$DB = $this->tdb;
$dbman = $this->tdb->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$sql = "SELECT * FROM {{$tablename}}";
$prevdebug = $DB->get_debug();
ob_start();
$DB->set_debug(true);
$this->assertTrue($DB->get_debug());
$DB->execute($sql);
$DB->set_debug(false);
$this->assertFalse($DB->get_debug());
$debuginfo = ob_get_contents();
ob_end_clean();
$this->assertFalse($debuginfo === '');
ob_start();
$DB->execute($sql);
$debuginfo = ob_get_contents();
ob_end_clean();
$this->assertTrue($debuginfo === '');
$DB->set_debug($prevdebug);
}
public function test_execute() {
$DB = $this->tdb;
$dbman = $this->tdb->get_manager();
$table1 = $this->get_test_table('1');
$tablename1 = $table1->getName();
$table1->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table1->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table1->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, '0');
$table1->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course'));
$table1->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table1);
$table2 = $this->get_test_table('2');
$tablename2 = $table2->getName();
$table2->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table2->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table2->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null);
$table2->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table2);
$DB->insert_record($tablename1, array('course' => 3, 'name' => 'aaa'));
$DB->insert_record($tablename1, array('course' => 1, 'name' => 'bbb'));
$DB->insert_record($tablename1, array('course' => 7, 'name' => 'ccc'));
$DB->insert_record($tablename1, array('course' => 3, 'name' => 'ddd'));
// Select results are ignored.
$sql = "SELECT * FROM {{$tablename1}} WHERE course = :course";
$this->assertTrue($DB->execute($sql, array('course'=>3)));
// Throw exception on error.
$sql = "XXUPDATE SET XSSD";
try {
$DB->execute($sql);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
// Update records.
$sql = "UPDATE {{$tablename1}}
SET course = 6
WHERE course = ?";
$this->assertTrue($DB->execute($sql, array('3')));
$this->assertEquals(2, $DB->count_records($tablename1, array('course' => 6)));
// Update records with subquery condition.
// Confirm that the option not using table aliases is cross-db.
$sql = "UPDATE {{$tablename1}}
SET course = 0
WHERE NOT EXISTS (
SELECT course
FROM {{$tablename2}} tbl2
WHERE tbl2.course = {{$tablename1}}.course
AND 1 = 0)"; // Really we don't update anything, but verify the syntax is allowed.
$this->assertTrue($DB->execute($sql));
// Insert from one into second table.
$sql = "INSERT INTO {{$tablename2}} (course)
SELECT course
FROM {{$tablename1}}";
$this->assertTrue($DB->execute($sql));
$this->assertEquals(4, $DB->count_records($tablename2));
// Insert a TEXT with raw SQL, binding TEXT params.
$course = 9999;
$onetext = file_get_contents(__DIR__ . '/fixtures/clob.txt');
$sql = "INSERT INTO {{$tablename2}} (course, onetext)
VALUES (:course, :onetext)";
$DB->execute($sql, array('course' => $course, 'onetext' => $onetext));
$records = $DB->get_records($tablename2, array('course' => $course));
$this->assertCount(1, $records);
$record = reset($records);
$this->assertSame($onetext, $record->onetext);
// Update a TEXT with raw SQL, binding TEXT params.
$newcourse = 10000;
$newonetext = file_get_contents(__DIR__ . '/fixtures/clob.txt') . '- updated';
$sql = "UPDATE {{$tablename2}} SET course = :newcourse, onetext = :newonetext
WHERE course = :oldcourse";
$DB->execute($sql, array('oldcourse' => $course, 'newcourse' => $newcourse, 'newonetext' => $newonetext));
$records = $DB->get_records($tablename2, array('course' => $course));
$this->assertCount(0, $records);
$records = $DB->get_records($tablename2, array('course' => $newcourse));
$this->assertCount(1, $records);
$record = reset($records);
$this->assertSame($newonetext, $record->onetext);
}
public function test_get_recordset() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, '0');
$table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null);
$table->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course'));
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$data = array(array('course' => 3, 'name' => 'record1', 'onetext'=>'abc'),
array('course' => 3, 'name' => 'record2', 'onetext'=>'abcd'),
array('course' => 5, 'name' => 'record3', 'onetext'=>'abcde'));
foreach ($data as $key => $record) {
$data[$key]['id'] = $DB->insert_record($tablename, $record);
}
// Standard recordset iteration.
$rs = $DB->get_recordset($tablename);
$this->assertInstanceOf('moodle_recordset', $rs);
reset($data);
foreach ($rs as $record) {
$data_record = current($data);
foreach ($record as $k => $v) {
$this->assertEquals($data_record[$k], $v);
}
next($data);
}
$rs->close();
// Iterator style usage.
$rs = $DB->get_recordset($tablename);
$this->assertInstanceOf('moodle_recordset', $rs);
reset($data);
while ($rs->valid()) {
$record = $rs->current();
$data_record = current($data);
foreach ($record as $k => $v) {
$this->assertEquals($data_record[$k], $v);
}
next($data);
$rs->next();
}
$rs->close();
// Make sure rewind is ignored.
$rs = $DB->get_recordset($tablename);
$this->assertInstanceOf('moodle_recordset', $rs);
reset($data);
$i = 0;
foreach ($rs as $record) {
$i++;
$rs->rewind();
if ($i > 10) {
$this->fail('revind not ignored in recordsets');
break;
}
$data_record = current($data);
foreach ($record as $k => $v) {
$this->assertEquals($data_record[$k], $v);
}
next($data);
}
$rs->close();
// Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int).
$conditions = array('onetext' => '1');
try {
$rs = $DB->get_recordset($tablename, $conditions);
$this->fail('An Exception is missing, expected due to equating of text fields');
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
$this->assertSame('textconditionsnotallowed', $e->errorcode);
}
// Test nested iteration.
$rs1 = $DB->get_recordset($tablename);
$i = 0;
foreach ($rs1 as $record1) {
$rs2 = $DB->get_recordset($tablename);
$i++;
$j = 0;
foreach ($rs2 as $record2) {
$j++;
}
$rs2->close();
$this->assertCount($j, $data);
}
$rs1->close();
$this->assertCount($i, $data);
// Notes:
// * limits are tested in test_get_recordset_sql()
// * where_clause() is used internally and is tested in test_get_records()
}
public function test_get_recordset_static() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 1));
$DB->insert_record($tablename, array('course' => 2));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 4));
$rs = $DB->get_recordset($tablename, array(), 'id');
$DB->set_field($tablename, 'course', 666, array('course'=>1));
$DB->delete_records($tablename, array('course'=>2));
$i = 0;
foreach ($rs as $record) {
$i++;
$this->assertEquals($i, $record->course);
}
$rs->close();
$this->assertEquals(4, $i);
// Now repeat with limits because it may use different code.
$DB->delete_records($tablename, array());
$DB->insert_record($tablename, array('course' => 1));
$DB->insert_record($tablename, array('course' => 2));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 4));
$rs = $DB->get_recordset($tablename, array(), 'id', '*', 0, 3);
$DB->set_field($tablename, 'course', 666, array('course'=>1));
$DB->delete_records($tablename, array('course'=>2));
$i = 0;
foreach ($rs as $record) {
$i++;
$this->assertEquals($i, $record->course);
}
$rs->close();
$this->assertEquals(3, $i);
}
public function test_get_recordset_iterator_keys() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, '0');
$table->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course'));
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$data = array(array('course' => 3, 'name' => 'record1'),
array('course' => 3, 'name' => 'record2'),
array('course' => 5, 'name' => 'record3'));
foreach ($data as $key => $record) {
$data[$key]['id'] = $DB->insert_record($tablename, $record);
}
// Test repeated numeric keys are returned ok.
$rs = $DB->get_recordset($tablename, null, null, 'course, name, id');
reset($data);
$count = 0;
foreach ($rs as $key => $record) {
$data_record = current($data);
$this->assertEquals($data_record['course'], $key);
next($data);
$count++;
}
$rs->close();
$this->assertEquals(3, $count);
// Test string keys are returned ok.
$rs = $DB->get_recordset($tablename, null, null, 'name, course, id');
reset($data);
$count = 0;
foreach ($rs as $key => $record) {
$data_record = current($data);
$this->assertEquals($data_record['name'], $key);
next($data);
$count++;
}
$rs->close();
$this->assertEquals(3, $count);
// Test numeric not starting in 1 keys are returned ok.
$rs = $DB->get_recordset($tablename, null, 'id DESC', 'id, course, name');
$data = array_reverse($data);
reset($data);
$count = 0;
foreach ($rs as $key => $record) {
$data_record = current($data);
$this->assertEquals($data_record['id'], $key);
next($data);
$count++;
}
$rs->close();
$this->assertEquals(3, $count);
}
public function test_get_recordset_list() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, null, null, '0');
$table->add_index('course', XMLDB_INDEX_NOTUNIQUE, array('course'));
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 5));
$DB->insert_record($tablename, array('course' => 2));
$DB->insert_record($tablename, array('course' => null));
$DB->insert_record($tablename, array('course' => 1));
$DB->insert_record($tablename, array('course' => 0));
$rs = $DB->get_recordset_list($tablename, 'course', array(3, 2));
$counter = 0;
foreach ($rs as $record) {
$counter++;
}
$this->assertEquals(3, $counter);
$rs->close();
$rs = $DB->get_recordset_list($tablename, 'course', array(3));
$counter = 0;
foreach ($rs as $record) {
$counter++;
}
$this->assertEquals(2, $counter);
$rs->close();
$rs = $DB->get_recordset_list($tablename, 'course', array(null));
$counter = 0;
foreach ($rs as $record) {
$counter++;
}
$this->assertEquals(1, $counter);
$rs->close();
$rs = $DB->get_recordset_list($tablename, 'course', array(6, null));
$counter = 0;
foreach ($rs as $record) {
$counter++;
}
$this->assertEquals(1, $counter);
$rs->close();
$rs = $DB->get_recordset_list($tablename, 'course', array(null, 5, 5, 5));
$counter = 0;
foreach ($rs as $record) {
$counter++;
}
$this->assertEquals(2, $counter);
$rs->close();
$rs = $DB->get_recordset_list($tablename, 'course', array(true));
$counter = 0;
foreach ($rs as $record) {
$counter++;
}
$this->assertEquals(1, $counter);
$rs->close();
$rs = $DB->get_recordset_list($tablename, 'course', array(false));
$counter = 0;
foreach ($rs as $record) {
$counter++;
}
$this->assertEquals(1, $counter);
$rs->close();
$rs = $DB->get_recordset_list($tablename, 'course', array()); // Must return 0 rows without conditions. MDL-17645.
$counter = 0;
foreach ($rs as $record) {
$counter++;
}
$rs->close();
$this->assertEquals(0, $counter);
// Notes:
// * limits are tested in test_get_recordset_sql()
// * where_clause() is used internally and is tested in test_get_records()
}
public function test_get_recordset_select() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 5));
$DB->insert_record($tablename, array('course' => 2));
$rs = $DB->get_recordset_select($tablename, '');
$counter = 0;
foreach ($rs as $record) {
$counter++;
}
$rs->close();
$this->assertEquals(4, $counter);
$this->assertNotEmpty($rs = $DB->get_recordset_select($tablename, 'course = 3'));
$counter = 0;
foreach ($rs as $record) {
$counter++;
}
$rs->close();
$this->assertEquals(2, $counter);
// Notes:
// * limits are tested in test_get_recordset_sql()
}
public function test_get_recordset_sql() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$inskey1 = $DB->insert_record($tablename, array('course' => 3));
$inskey2 = $DB->insert_record($tablename, array('course' => 5));
$inskey3 = $DB->insert_record($tablename, array('course' => 4));
$inskey4 = $DB->insert_record($tablename, array('course' => 3));
$inskey5 = $DB->insert_record($tablename, array('course' => 2));
$inskey6 = $DB->insert_record($tablename, array('course' => 1));
$inskey7 = $DB->insert_record($tablename, array('course' => 0));
$rs = $DB->get_recordset_sql("SELECT * FROM {{$tablename}} WHERE course = ?", array(3));
$counter = 0;
foreach ($rs as $record) {
$counter++;
}
$rs->close();
$this->assertEquals(2, $counter);
// Limits - only need to test this case, the rest have been tested by test_get_records_sql()
// only limitfrom = skips that number of records.
$rs = $DB->get_recordset_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 2, 0);
$records = array();
foreach ($rs as $key => $record) {
$records[$key] = $record;
}
$rs->close();
$this->assertCount(5, $records);
$this->assertEquals($inskey3, reset($records)->id);
$this->assertEquals($inskey7, end($records)->id);
// Note: fetching nulls, empties, LOBs already tested by test_insert_record() no needed here.
}
public function test_export_table_recordset() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$ids = array();
$ids[] = $DB->insert_record($tablename, array('course' => 3));
$ids[] = $DB->insert_record($tablename, array('course' => 5));
$ids[] = $DB->insert_record($tablename, array('course' => 4));
$ids[] = $DB->insert_record($tablename, array('course' => 3));
$ids[] = $DB->insert_record($tablename, array('course' => 2));
$ids[] = $DB->insert_record($tablename, array('course' => 1));
$ids[] = $DB->insert_record($tablename, array('course' => 0));
$rs = $DB->export_table_recordset($tablename);
$rids = array();
foreach ($rs as $record) {
$rids[] = $record->id;
}
$rs->close();
$this->assertEquals($ids, $rids, '', 0, 0, true);
}
public function test_get_records() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 5));
$DB->insert_record($tablename, array('course' => 2));
// All records.
$records = $DB->get_records($tablename);
$this->assertCount(4, $records);
$this->assertEquals(3, $records[1]->course);
$this->assertEquals(3, $records[2]->course);
$this->assertEquals(5, $records[3]->course);
$this->assertEquals(2, $records[4]->course);
// Records matching certain conditions.
$records = $DB->get_records($tablename, array('course' => 3));
$this->assertCount(2, $records);
$this->assertEquals(3, $records[1]->course);
$this->assertEquals(3, $records[2]->course);
// All records sorted by course.
$records = $DB->get_records($tablename, null, 'course');
$this->assertCount(4, $records);
$current_record = reset($records);
$this->assertEquals(4, $current_record->id);
$current_record = next($records);
$this->assertEquals(1, $current_record->id);
$current_record = next($records);
$this->assertEquals(2, $current_record->id);
$current_record = next($records);
$this->assertEquals(3, $current_record->id);
// All records, but get only one field.
$records = $DB->get_records($tablename, null, '', 'id');
$this->assertFalse(isset($records[1]->course));
$this->assertTrue(isset($records[1]->id));
$this->assertCount(4, $records);
// Booleans into params.
$records = $DB->get_records($tablename, array('course' => true));
$this->assertCount(0, $records);
$records = $DB->get_records($tablename, array('course' => false));
$this->assertCount(0, $records);
// Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int).
$conditions = array('onetext' => '1');
try {
$records = $DB->get_records($tablename, $conditions);
if (debugging()) {
// Only in debug mode - hopefully all devs test code in debug mode...
$this->fail('An Exception is missing, expected due to equating of text fields');
}
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
$this->assertSame('textconditionsnotallowed', $e->errorcode);
}
// Test get_records passing non-existing table.
// with params.
try {
$records = $DB->get_records('xxxx', array('id' => 0));
$this->fail('An Exception is missing, expected due to query against non-existing table');
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
if (debugging()) {
// Information for developers only, normal users get general error message.
$this->assertSame('ddltablenotexist', $e->errorcode);
}
}
// And without params.
try {
$records = $DB->get_records('xxxx', array());
$this->fail('An Exception is missing, expected due to query against non-existing table');
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
if (debugging()) {
// Information for developers only, normal users get general error message.
$this->assertSame('ddltablenotexist', $e->errorcode);
}
}
// Test get_records passing non-existing column.
try {
$records = $DB->get_records($tablename, array('xxxx' => 0));
$this->fail('An Exception is missing, expected due to query against non-existing column');
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
if (debugging()) {
// Information for developers only, normal users get general error message.
$this->assertSame('ddlfieldnotexist', $e->errorcode);
}
}
// Note: delegate limits testing to test_get_records_sql().
}
public function test_get_records_list() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 5));
$DB->insert_record($tablename, array('course' => 2));
$records = $DB->get_records_list($tablename, 'course', array(3, 2));
$this->assertInternalType('array', $records);
$this->assertCount(3, $records);
$this->assertEquals(1, reset($records)->id);
$this->assertEquals(2, next($records)->id);
$this->assertEquals(4, next($records)->id);
$this->assertSame(array(), $records = $DB->get_records_list($tablename, 'course', array())); // Must return 0 rows without conditions. MDL-17645.
$this->assertCount(0, $records);
// Note: delegate limits testing to test_get_records_sql().
}
public function test_get_records_sql() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$inskey1 = $DB->insert_record($tablename, array('course' => 3));
$inskey2 = $DB->insert_record($tablename, array('course' => 5));
$inskey3 = $DB->insert_record($tablename, array('course' => 4));
$inskey4 = $DB->insert_record($tablename, array('course' => 3));
$inskey5 = $DB->insert_record($tablename, array('course' => 2));
$inskey6 = $DB->insert_record($tablename, array('course' => 1));
$inskey7 = $DB->insert_record($tablename, array('course' => 0));
$table2 = $this->get_test_table("2");
$tablename2 = $table2->getName();
$table2->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table2->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table2->add_field('nametext', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
$table2->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table2);
$DB->insert_record($tablename2, array('course'=>3, 'nametext'=>'badabing'));
$DB->insert_record($tablename2, array('course'=>4, 'nametext'=>'badabang'));
$DB->insert_record($tablename2, array('course'=>5, 'nametext'=>'badabung'));
$DB->insert_record($tablename2, array('course'=>6, 'nametext'=>'badabong'));
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE course = ?", array(3));
$this->assertCount(2, $records);
$this->assertEquals($inskey1, reset($records)->id);
$this->assertEquals($inskey4, next($records)->id);
// Awful test, requires debug enabled and sent to browser. Let's do that and restore after test.
$records = $DB->get_records_sql("SELECT course AS id, course AS course FROM {{$tablename}}", null);
$this->assertDebuggingCalled();
$this->assertCount(6, $records);
set_debugging(DEBUG_MINIMAL);
$records = $DB->get_records_sql("SELECT course AS id, course AS course FROM {{$tablename}}", null);
$this->assertDebuggingNotCalled();
$this->assertCount(6, $records);
set_debugging(DEBUG_DEVELOPER);
// Negative limits = no limits.
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, -1, -1);
$this->assertCount(7, $records);
// Zero limits = no limits.
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 0, 0);
$this->assertCount(7, $records);
// Only limitfrom = skips that number of records.
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 2, 0);
$this->assertCount(5, $records);
$this->assertEquals($inskey3, reset($records)->id);
$this->assertEquals($inskey7, end($records)->id);
// Only limitnum = fetches that number of records.
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 0, 3);
$this->assertCount(3, $records);
$this->assertEquals($inskey1, reset($records)->id);
$this->assertEquals($inskey3, end($records)->id);
// Both limitfrom and limitnum = skips limitfrom records and fetches limitnum ones.
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} ORDER BY id", null, 3, 2);
$this->assertCount(2, $records);
$this->assertEquals($inskey4, reset($records)->id);
$this->assertEquals($inskey5, end($records)->id);
// Both limitfrom and limitnum in query having subqueris.
// Note the subquery skips records with course = 0 and 3.
$sql = "SELECT * FROM {{$tablename}}
WHERE course NOT IN (
SELECT course FROM {{$tablename}}
WHERE course IN (0, 3))
ORDER BY course";
$records = $DB->get_records_sql($sql, null, 0, 2); // Skip 0, get 2.
$this->assertCount(2, $records);
$this->assertEquals($inskey6, reset($records)->id);
$this->assertEquals($inskey5, end($records)->id);
$records = $DB->get_records_sql($sql, null, 2, 2); // Skip 2, get 2.
$this->assertCount(2, $records);
$this->assertEquals($inskey3, reset($records)->id);
$this->assertEquals($inskey2, end($records)->id);
// Test 2 tables with aliases and limits with order bys.
$sql = "SELECT t1.id, t1.course AS cid, t2.nametext
FROM {{$tablename}} t1, {{$tablename2}} t2
WHERE t2.course=t1.course
ORDER BY t1.course, ". $DB->sql_compare_text('t2.nametext');
$records = $DB->get_records_sql($sql, null, 2, 2); // Skip courses 3 and 6, get 4 and 5.
$this->assertCount(2, $records);
$this->assertSame('5', end($records)->cid);
$this->assertSame('4', reset($records)->cid);
// Test 2 tables with aliases and limits with the highest INT limit works.
$records = $DB->get_records_sql($sql, null, 2, PHP_INT_MAX); // Skip course {3,6}, get {4,5}.
$this->assertCount(2, $records);
$this->assertSame('5', end($records)->cid);
$this->assertSame('4', reset($records)->cid);
// Test 2 tables with aliases and limits with order bys (limit which is highest INT number).
$records = $DB->get_records_sql($sql, null, PHP_INT_MAX, 2); // Skip all courses.
$this->assertCount(0, $records);
// Test 2 tables with aliases and limits with order bys (limit which s highest INT number).
$records = $DB->get_records_sql($sql, null, PHP_INT_MAX, PHP_INT_MAX); // Skip all courses.
$this->assertCount(0, $records);
// TODO: Test limits in queries having DISTINCT clauses.
// Note: fetching nulls, empties, LOBs already tested by test_update_record() no needed here.
}
public function test_get_records_menu() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 5));
$DB->insert_record($tablename, array('course' => 2));
$records = $DB->get_records_menu($tablename, array('course' => 3));
$this->assertInternalType('array', $records);
$this->assertCount(2, $records);
$this->assertNotEmpty($records[1]);
$this->assertNotEmpty($records[2]);
$this->assertEquals(3, $records[1]);
$this->assertEquals(3, $records[2]);
// Note: delegate limits testing to test_get_records_sql().
}
public function test_get_records_select_menu() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 2));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 5));
$records = $DB->get_records_select_menu($tablename, "course > ?", array(2));
$this->assertInternalType('array', $records);
$this->assertCount(3, $records);
$this->assertArrayHasKey(1, $records);
$this->assertArrayNotHasKey(2, $records);
$this->assertArrayHasKey(3, $records);
$this->assertArrayHasKey(4, $records);
$this->assertSame('3', $records[1]);
$this->assertSame('3', $records[3]);
$this->assertSame('5', $records[4]);
// Note: delegate limits testing to test_get_records_sql().
}
public function test_get_records_sql_menu() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 2));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 5));
$records = $DB->get_records_sql_menu("SELECT * FROM {{$tablename}} WHERE course > ?", array(2));
$this->assertInternalType('array', $records);
$this->assertCount(3, $records);
$this->assertArrayHasKey(1, $records);
$this->assertArrayNotHasKey(2, $records);
$this->assertArrayHasKey(3, $records);
$this->assertArrayHasKey(4, $records);
$this->assertSame('3', $records[1]);
$this->assertSame('3', $records[3]);
$this->assertSame('5', $records[4]);
// Note: delegate limits testing to test_get_records_sql().
}
public function test_get_record() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 2));
$record = $DB->get_record($tablename, array('id' => 2));
$this->assertInstanceOf('stdClass', $record);
$this->assertEquals(2, $record->course);
$this->assertEquals(2, $record->id);
}
public function test_get_record_select() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 2));
$record = $DB->get_record_select($tablename, "id = ?", array(2));
$this->assertInstanceOf('stdClass', $record);
$this->assertEquals(2, $record->course);
// Note: delegates limit testing to test_get_records_sql().
}
public function test_get_record_sql() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 2));
// Standard use.
$record = $DB->get_record_sql("SELECT * FROM {{$tablename}} WHERE id = ?", array(2));
$this->assertInstanceOf('stdClass', $record);
$this->assertEquals(2, $record->course);
$this->assertEquals(2, $record->id);
// Backwards compatibility with $ignoremultiple.
$this->assertFalse((bool)IGNORE_MISSING);
$this->assertTrue((bool)IGNORE_MULTIPLE);
// Record not found - ignore.
$this->assertFalse($DB->get_record_sql("SELECT * FROM {{$tablename}} WHERE id = ?", array(666), IGNORE_MISSING));
$this->assertFalse($DB->get_record_sql("SELECT * FROM {{$tablename}} WHERE id = ?", array(666), IGNORE_MULTIPLE));
// Record not found error.
try {
$DB->get_record_sql("SELECT * FROM {{$tablename}} WHERE id = ?", array(666), MUST_EXIST);
$this->fail("Exception expected");
} catch (dml_missing_record_exception $e) {
$this->assertTrue(true);
}
$this->assertNotEmpty($DB->get_record_sql("SELECT * FROM {{$tablename}}", array(), IGNORE_MISSING));
$this->assertDebuggingCalled();
set_debugging(DEBUG_MINIMAL);
$this->assertNotEmpty($DB->get_record_sql("SELECT * FROM {{$tablename}}", array(), IGNORE_MISSING));
$this->assertDebuggingNotCalled();
set_debugging(DEBUG_DEVELOPER);
// Multiple matches ignored.
$this->assertNotEmpty($DB->get_record_sql("SELECT * FROM {{$tablename}}", array(), IGNORE_MULTIPLE));
// Multiple found error.
try {
$DB->get_record_sql("SELECT * FROM {{$tablename}}", array(), MUST_EXIST);
$this->fail("Exception expected");
} catch (dml_multiple_records_exception $e) {
$this->assertTrue(true);
}
}
public function test_get_field() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$id1 = $DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 5));
$DB->insert_record($tablename, array('course' => 5));
$this->assertEquals(3, $DB->get_field($tablename, 'course', array('id' => $id1)));
$this->assertEquals(3, $DB->get_field($tablename, 'course', array('course' => 3)));
$this->assertFalse($DB->get_field($tablename, 'course', array('course' => 11), IGNORE_MISSING));
try {
$DB->get_field($tablename, 'course', array('course' => 4), MUST_EXIST);
$this->fail('Exception expected due to missing record');
} catch (dml_exception $ex) {
$this->assertTrue(true);
}
$this->assertEquals(5, $DB->get_field($tablename, 'course', array('course' => 5), IGNORE_MULTIPLE));
$this->assertDebuggingNotCalled();
$this->assertEquals(5, $DB->get_field($tablename, 'course', array('course' => 5), IGNORE_MISSING));
$this->assertDebuggingCalled();
// Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int).
$conditions = array('onetext' => '1');
try {
$DB->get_field($tablename, 'course', $conditions);
if (debugging()) {
// Only in debug mode - hopefully all devs test code in debug mode...
$this->fail('An Exception is missing, expected due to equating of text fields');
}
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
$this->assertSame('textconditionsnotallowed', $e->errorcode);
}
}
public function test_get_field_select() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3));
$this->assertEquals(3, $DB->get_field_select($tablename, 'course', "id = ?", array(1)));
}
public function test_get_field_sql() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3));
$this->assertEquals(3, $DB->get_field_sql("SELECT course FROM {{$tablename}} WHERE id = ?", array(1)));
}
public function test_get_fieldset_select() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 1));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 2));
$DB->insert_record($tablename, array('course' => 6));
$fieldset = $DB->get_fieldset_select($tablename, 'course', "course > ?", array(1));
$this->assertInternalType('array', $fieldset);
$this->assertCount(3, $fieldset);
$this->assertEquals(3, $fieldset[0]);
$this->assertEquals(2, $fieldset[1]);
$this->assertEquals(6, $fieldset[2]);
}
public function test_get_fieldset_sql() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 1));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 2));
$DB->insert_record($tablename, array('course' => 6));
$fieldset = $DB->get_fieldset_sql("SELECT * FROM {{$tablename}} WHERE course > ?", array(1));
$this->assertInternalType('array', $fieldset);
$this->assertCount(3, $fieldset);
$this->assertEquals(2, $fieldset[0]);
$this->assertEquals(3, $fieldset[1]);
$this->assertEquals(4, $fieldset[2]);
}
public function test_insert_record_raw() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null, 'onestring');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$record = (object)array('course' => 1, 'onechar' => 'xx');
$before = clone($record);
$result = $DB->insert_record_raw($tablename, $record);
$this->assertSame(1, $result);
$this->assertEquals($record, $before);
$record = $DB->get_record($tablename, array('course' => 1));
$this->assertInstanceOf('stdClass', $record);
$this->assertSame('xx', $record->onechar);
$result = $DB->insert_record_raw($tablename, array('course' => 2, 'onechar' => 'yy'), false);
$this->assertTrue($result);
// Note: bulk not implemented yet.
$DB->insert_record_raw($tablename, array('course' => 3, 'onechar' => 'zz'), true, true);
$record = $DB->get_record($tablename, array('course' => 3));
$this->assertInstanceOf('stdClass', $record);
$this->assertSame('zz', $record->onechar);
// Custom sequence (id) - returnid is ignored.
$result = $DB->insert_record_raw($tablename, array('id' => 10, 'course' => 3, 'onechar' => 'bb'), true, false, true);
$this->assertTrue($result);
$record = $DB->get_record($tablename, array('id' => 10));
$this->assertInstanceOf('stdClass', $record);
$this->assertSame('bb', $record->onechar);
// Custom sequence - missing id error.
try {
$DB->insert_record_raw($tablename, array('course' => 3, 'onechar' => 'bb'), true, false, true);
$this->fail('Exception expected due to missing record');
} catch (coding_exception $ex) {
$this->assertTrue(true);
}
// Wrong column error.
try {
$DB->insert_record_raw($tablename, array('xxxxx' => 3, 'onechar' => 'bb'));
$this->fail('Exception expected due to invalid column');
} catch (dml_exception $ex) {
$this->assertTrue(true);
}
// Create something similar to "context_temp" with id column without sequence.
$dbman->drop_table($table);
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$record = (object)array('id'=>5, 'course' => 1);
$DB->insert_record_raw($tablename, $record, false, false, true);
$record = $DB->get_record($tablename, array());
$this->assertEquals(5, $record->id);
}
public function test_insert_record() {
// All the information in this test is fetched from DB by get_recordset() so we
// have such method properly tested against nulls, empties and friends...
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('oneint', XMLDB_TYPE_INTEGER, '10', null, null, null, 100);
$table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null, 200);
$table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null, 'onestring');
$table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null);
$table->add_field('onebinary', XMLDB_TYPE_BINARY, 'big', null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$this->assertSame(1, $DB->insert_record($tablename, array('course' => 1), true));
$record = $DB->get_record($tablename, array('course' => 1));
$this->assertEquals(1, $record->id);
$this->assertEquals(100, $record->oneint); // Just check column defaults have been applied.
$this->assertEquals(200, $record->onenum);
$this->assertSame('onestring', $record->onechar);
$this->assertNull($record->onetext);
$this->assertNull($record->onebinary);
// Without returning id, bulk not implemented.
$result = $this->assertTrue($DB->insert_record($tablename, array('course' => 99), false, true));
$record = $DB->get_record($tablename, array('course' => 99));
$this->assertEquals(2, $record->id);
$this->assertEquals(99, $record->course);
// Check nulls are set properly for all types.
$record = new stdClass();
$record->oneint = null;
$record->onenum = null;
$record->onechar = null;
$record->onetext = null;
$record->onebinary = null;
$recid = $DB->insert_record($tablename, $record);
$record = $DB->get_record($tablename, array('id' => $recid));
$this->assertEquals(0, $record->course);
$this->assertNull($record->oneint);
$this->assertNull($record->onenum);
$this->assertNull($record->onechar);
$this->assertNull($record->onetext);
$this->assertNull($record->onebinary);
// Check zeros are set properly for all types.
$record = new stdClass();
$record->oneint = 0;
$record->onenum = 0;
$recid = $DB->insert_record($tablename, $record);
$record = $DB->get_record($tablename, array('id' => $recid));
$this->assertEquals(0, $record->oneint);
$this->assertEquals(0, $record->onenum);
// Check booleans are set properly for all types.
$record = new stdClass();
$record->oneint = true; // Trues.
$record->onenum = true;
$record->onechar = true;
$record->onetext = true;
$recid = $DB->insert_record($tablename, $record);
$record = $DB->get_record($tablename, array('id' => $recid));
$this->assertEquals(1, $record->oneint);
$this->assertEquals(1, $record->onenum);
$this->assertEquals(1, $record->onechar);
$this->assertEquals(1, $record->onetext);
$record = new stdClass();
$record->oneint = false; // Falses.
$record->onenum = false;
$record->onechar = false;
$record->onetext = false;
$recid = $DB->insert_record($tablename, $record);
$record = $DB->get_record($tablename, array('id' => $recid));
$this->assertEquals(0, $record->oneint);
$this->assertEquals(0, $record->onenum);
$this->assertEquals(0, $record->onechar);
$this->assertEquals(0, $record->onetext);
// Check string data causes exception in numeric types.
$record = new stdClass();
$record->oneint = 'onestring';
$record->onenum = 0;
try {
$DB->insert_record($tablename, $record);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
$record = new stdClass();
$record->oneint = 0;
$record->onenum = 'onestring';
try {
$DB->insert_record($tablename, $record);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
// Check empty string data is stored as 0 in numeric datatypes.
$record = new stdClass();
$record->oneint = ''; // Empty string.
$record->onenum = 0;
$recid = $DB->insert_record($tablename, $record);
$record = $DB->get_record($tablename, array('id' => $recid));
$this->assertTrue(is_numeric($record->oneint) && $record->oneint == 0);
$record = new stdClass();
$record->oneint = 0;
$record->onenum = ''; // Empty string.
$recid = $DB->insert_record($tablename, $record);
$record = $DB->get_record($tablename, array('id' => $recid));
$this->assertTrue(is_numeric($record->onenum) && $record->onenum == 0);
// Check empty strings are set properly in string types.
$record = new stdClass();
$record->oneint = 0;
$record->onenum = 0;
$record->onechar = '';
$record->onetext = '';
$recid = $DB->insert_record($tablename, $record);
$record = $DB->get_record($tablename, array('id' => $recid));
$this->assertTrue($record->onechar === '');
$this->assertTrue($record->onetext === '');
// Check operation ((210.10 + 39.92) - 150.02) against numeric types.
$record = new stdClass();
$record->oneint = ((210.10 + 39.92) - 150.02);
$record->onenum = ((210.10 + 39.92) - 150.02);
$recid = $DB->insert_record($tablename, $record);
$record = $DB->get_record($tablename, array('id' => $recid));
$this->assertEquals(100, $record->oneint);
$this->assertEquals(100, $record->onenum);
// Check various quotes/backslashes combinations in string types.
$teststrings = array(
'backslashes and quotes alone (even): "" \'\' \\\\',
'backslashes and quotes alone (odd): """ \'\'\' \\\\\\',
'backslashes and quotes sequences (even): \\"\\" \\\'\\\'',
'backslashes and quotes sequences (odd): \\"\\"\\" \\\'\\\'\\\'');
foreach ($teststrings as $teststring) {
$record = new stdClass();
$record->onechar = $teststring;
$record->onetext = $teststring;
$recid = $DB->insert_record($tablename, $record);
$record = $DB->get_record($tablename, array('id' => $recid));
$this->assertEquals($teststring, $record->onechar);
$this->assertEquals($teststring, $record->onetext);
}
// Check LOBs in text/binary columns.
$clob = file_get_contents(__DIR__ . '/fixtures/clob.txt');
$blob = file_get_contents(__DIR__ . '/fixtures/randombinary');
$record = new stdClass();
$record->onetext = $clob;
$record->onebinary = $blob;
$recid = $DB->insert_record($tablename, $record);
$rs = $DB->get_recordset($tablename, array('id' => $recid));
$record = $rs->current();
$rs->close();
$this->assertEquals($clob, $record->onetext, 'Test CLOB insert (full contents output disabled)');
$this->assertEquals($blob, $record->onebinary, 'Test BLOB insert (full contents output disabled)');
// And "small" LOBs too, just in case.
$newclob = substr($clob, 0, 500);
$newblob = substr($blob, 0, 250);
$record = new stdClass();
$record->onetext = $newclob;
$record->onebinary = $newblob;
$recid = $DB->insert_record($tablename, $record);
$rs = $DB->get_recordset($tablename, array('id' => $recid));
$record = $rs->current();
$rs->close();
$this->assertEquals($newclob, $record->onetext, 'Test "small" CLOB insert (full contents output disabled)');
$this->assertEquals($newblob, $record->onebinary, 'Test "small" BLOB insert (full contents output disabled)');
$this->assertEquals(false, $rs->key()); // Ensure recordset key() method to be working ok after closing.
// And "diagnostic" LOBs too, just in case.
$newclob = '\'"\\;/ěščřžýáíé';
$newblob = '\'"\\;/ěščřžýáíé';
$record = new stdClass();
$record->onetext = $newclob;
$record->onebinary = $newblob;
$recid = $DB->insert_record($tablename, $record);
$rs = $DB->get_recordset($tablename, array('id' => $recid));
$record = $rs->current();
$rs->close();
$this->assertSame($newclob, $record->onetext);
$this->assertSame($newblob, $record->onebinary);
$this->assertEquals(false, $rs->key()); // Ensure recordset key() method to be working ok after closing.
// Test data is not modified.
$record = new stdClass();
$record->id = -1; // Has to be ignored.
$record->course = 3;
$record->lalala = 'lalal'; // Unused.
$before = clone($record);
$DB->insert_record($tablename, $record);
$this->assertEquals($record, $before);
// Make sure the id is always increasing and never reuses the same id.
$id1 = $DB->insert_record($tablename, array('course' => 3));
$id2 = $DB->insert_record($tablename, array('course' => 3));
$this->assertTrue($id1 < $id2);
$DB->delete_records($tablename, array('id'=>$id2));
$id3 = $DB->insert_record($tablename, array('course' => 3));
$this->assertTrue($id2 < $id3);
$DB->delete_records($tablename, array());
$id4 = $DB->insert_record($tablename, array('course' => 3));
$this->assertTrue($id3 < $id4);
// Test saving a float in a CHAR column, and reading it back.
$id = $DB->insert_record($tablename, array('onechar' => 1.0));
$this->assertEquals(1.0, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$id = $DB->insert_record($tablename, array('onechar' => 1e20));
$this->assertEquals(1e20, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$id = $DB->insert_record($tablename, array('onechar' => 1e-4));
$this->assertEquals(1e-4, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$id = $DB->insert_record($tablename, array('onechar' => 1e-5));
$this->assertEquals(1e-5, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$id = $DB->insert_record($tablename, array('onechar' => 1e-300));
$this->assertEquals(1e-300, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$id = $DB->insert_record($tablename, array('onechar' => 1e300));
$this->assertEquals(1e300, $DB->get_field($tablename, 'onechar', array('id' => $id)));
// Test saving a float in a TEXT column, and reading it back.
$id = $DB->insert_record($tablename, array('onetext' => 1.0));
$this->assertEquals(1.0, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$id = $DB->insert_record($tablename, array('onetext' => 1e20));
$this->assertEquals(1e20, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$id = $DB->insert_record($tablename, array('onetext' => 1e-4));
$this->assertEquals(1e-4, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$id = $DB->insert_record($tablename, array('onetext' => 1e-5));
$this->assertEquals(1e-5, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$id = $DB->insert_record($tablename, array('onetext' => 1e-300));
$this->assertEquals(1e-300, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$id = $DB->insert_record($tablename, array('onetext' => 1e300));
$this->assertEquals(1e300, $DB->get_field($tablename, 'onetext', array('id' => $id)));
// Test that inserting data violating one unique key leads to error.
// Empty the table completely.
$this->assertTrue($DB->delete_records($tablename));
// Add one unique constraint (index).
$key = new xmldb_key('testuk', XMLDB_KEY_UNIQUE, array('course', 'oneint'));
$dbman->add_key($table, $key);
// Let's insert one record violating the constraint multiple times.
$record = (object)array('course' => 1, 'oneint' => 1);
$this->assertTrue($DB->insert_record($tablename, $record, false)); // Insert 1st. No problem expected.
// Re-insert same record, not returning id. dml_exception expected.
try {
$DB->insert_record($tablename, $record, false);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
// Re-insert same record, returning id. dml_exception expected.
try {
$DB->insert_record($tablename, $record, true);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
// Try to insert a record into a non-existent table. dml_exception expected.
try {
$DB->insert_record('nonexistenttable', $record, true);
$this->fail("Expecting an exception, none occurred");
} catch (exception $e) {
$this->assertTrue($e instanceof dml_exception);
}
}
public function test_insert_records() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('oneint', XMLDB_TYPE_INTEGER, '10', null, null, null, 100);
$table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null, 200);
$table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null, 'onestring');
$table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$this->assertCount(0, $DB->get_records($tablename));
$record = new stdClass();
$record->id = '1';
$record->course = '1';
$record->oneint = null;
$record->onenum = '1.00';
$record->onechar = 'a';
$record->onetext = 'aaa';
$expected = array();
$records = array();
for ($i = 1; $i <= 2000; $i++) { // This may take a while, it should be higher than defaults in DML drivers.
$rec = clone($record);
$rec->id = (string)$i;
$rec->oneint = (string)$i;
$expected[$i] = $rec;
$rec = clone($rec);
unset($rec->id);
$records[$i] = $rec;
}
$DB->insert_records($tablename, $records);
$stored = $DB->get_records($tablename, array(), 'id ASC');
$this->assertEquals($expected, $stored);
// Test there can be some extra properties including id.
$count = $DB->count_records($tablename);
$rec1 = (array)$record;
$rec1['xxx'] = 1;
$rec2 = (array)$record;
$rec2['xxx'] = 2;
$records = array($rec1, $rec2);
$DB->insert_records($tablename, $records);
$this->assertEquals($count + 2, $DB->count_records($tablename));
// Test not all properties are necessary.
$rec1 = (array)$record;
unset($rec1['course']);
$rec2 = (array)$record;
unset($rec2['course']);
$records = array($rec1, $rec2);
$DB->insert_records($tablename, $records);
// Make sure no changes in data object structure are tolerated.
$rec1 = (array)$record;
unset($rec1['id']);
$rec2 = (array)$record;
unset($rec2['id']);
$records = array($rec1, $rec2);
$DB->insert_records($tablename, $records);
$rec2['xx'] = '1';
$records = array($rec1, $rec2);
try {
$DB->insert_records($tablename, $records);
$this->fail('coding_exception expected when insert_records receives different object data structures');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
unset($rec2['xx']);
unset($rec2['course']);
$rec2['course'] = '1';
$records = array($rec1, $rec2);
try {
$DB->insert_records($tablename, $records);
$this->fail('coding_exception expected when insert_records receives different object data structures');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
$records = 1;
try {
$DB->insert_records($tablename, $records);
$this->fail('coding_exception expected when insert_records receives non-traversable data');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
$records = array(1);
try {
$DB->insert_records($tablename, $records);
$this->fail('coding_exception expected when insert_records receives non-objet record');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
}
public function test_import_record() {
// All the information in this test is fetched from DB by get_recordset() so we
// have such method properly tested against nulls, empties and friends...
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('oneint', XMLDB_TYPE_INTEGER, '10', null, null, null, 100);
$table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null, 200);
$table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null, 'onestring');
$table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null);
$table->add_field('onebinary', XMLDB_TYPE_BINARY, 'big', null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$this->assertSame(1, $DB->insert_record($tablename, array('course' => 1), true));
$record = $DB->get_record($tablename, array('course' => 1));
$this->assertEquals(1, $record->id);
$this->assertEquals(100, $record->oneint); // Just check column defaults have been applied.
$this->assertEquals(200, $record->onenum);
$this->assertSame('onestring', $record->onechar);
$this->assertNull($record->onetext);
$this->assertNull($record->onebinary);
// Ignore extra columns.
$record = (object)array('id'=>13, 'course'=>2, 'xxxx'=>788778);
$before = clone($record);
$this->assertTrue($DB->import_record($tablename, $record));
$this->assertEquals($record, $before);
$records = $DB->get_records($tablename);
$this->assertEquals(2, $records[13]->course);
// Check nulls are set properly for all types.
$record = new stdClass();
$record->id = 20;
$record->oneint = null;
$record->onenum = null;
$record->onechar = null;
$record->onetext = null;
$record->onebinary = null;
$this->assertTrue($DB->import_record($tablename, $record));
$record = $DB->get_record($tablename, array('id' => 20));
$this->assertEquals(0, $record->course);
$this->assertNull($record->oneint);
$this->assertNull($record->onenum);
$this->assertNull($record->onechar);
$this->assertNull($record->onetext);
$this->assertNull($record->onebinary);
// Check zeros are set properly for all types.
$record = new stdClass();
$record->id = 23;
$record->oneint = 0;
$record->onenum = 0;
$this->assertTrue($DB->import_record($tablename, $record));
$record = $DB->get_record($tablename, array('id' => 23));
$this->assertEquals(0, $record->oneint);
$this->assertEquals(0, $record->onenum);
// Check string data causes exception in numeric types.
$record = new stdClass();
$record->id = 32;
$record->oneint = 'onestring';
$record->onenum = 0;
try {
$DB->import_record($tablename, $record);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
$record = new stdClass();
$record->id = 35;
$record->oneint = 0;
$record->onenum = 'onestring';
try {
$DB->import_record($tablename, $record);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
// Check empty strings are set properly in string types.
$record = new stdClass();
$record->id = 44;
$record->oneint = 0;
$record->onenum = 0;
$record->onechar = '';
$record->onetext = '';
$this->assertTrue($DB->import_record($tablename, $record));
$record = $DB->get_record($tablename, array('id' => 44));
$this->assertTrue($record->onechar === '');
$this->assertTrue($record->onetext === '');
// Check operation ((210.10 + 39.92) - 150.02) against numeric types.
$record = new stdClass();
$record->id = 47;
$record->oneint = ((210.10 + 39.92) - 150.02);
$record->onenum = ((210.10 + 39.92) - 150.02);
$this->assertTrue($DB->import_record($tablename, $record));
$record = $DB->get_record($tablename, array('id' => 47));
$this->assertEquals(100, $record->oneint);
$this->assertEquals(100, $record->onenum);
// Check various quotes/backslashes combinations in string types.
$i = 50;
$teststrings = array(
'backslashes and quotes alone (even): "" \'\' \\\\',
'backslashes and quotes alone (odd): """ \'\'\' \\\\\\',
'backslashes and quotes sequences (even): \\"\\" \\\'\\\'',
'backslashes and quotes sequences (odd): \\"\\"\\" \\\'\\\'\\\'');
foreach ($teststrings as $teststring) {
$record = new stdClass();
$record->id = $i;
$record->onechar = $teststring;
$record->onetext = $teststring;
$this->assertTrue($DB->import_record($tablename, $record));
$record = $DB->get_record($tablename, array('id' => $i));
$this->assertEquals($teststring, $record->onechar);
$this->assertEquals($teststring, $record->onetext);
$i = $i + 3;
}
// Check LOBs in text/binary columns.
$clob = file_get_contents(__DIR__ . '/fixtures/clob.txt');
$record = new stdClass();
$record->id = 70;
$record->onetext = $clob;
$record->onebinary = '';
$this->assertTrue($DB->import_record($tablename, $record));
$rs = $DB->get_recordset($tablename, array('id' => 70));
$record = $rs->current();
$rs->close();
$this->assertEquals($clob, $record->onetext, 'Test CLOB insert (full contents output disabled)');
$blob = file_get_contents(__DIR__ . '/fixtures/randombinary');
$record = new stdClass();
$record->id = 71;
$record->onetext = '';
$record->onebinary = $blob;
$this->assertTrue($DB->import_record($tablename, $record));
$rs = $DB->get_recordset($tablename, array('id' => 71));
$record = $rs->current();
$rs->close();
$this->assertEquals($blob, $record->onebinary, 'Test BLOB insert (full contents output disabled)');
// And "small" LOBs too, just in case.
$newclob = substr($clob, 0, 500);
$newblob = substr($blob, 0, 250);
$record = new stdClass();
$record->id = 73;
$record->onetext = $newclob;
$record->onebinary = $newblob;
$this->assertTrue($DB->import_record($tablename, $record));
$rs = $DB->get_recordset($tablename, array('id' => 73));
$record = $rs->current();
$rs->close();
$this->assertEquals($newclob, $record->onetext, 'Test "small" CLOB insert (full contents output disabled)');
$this->assertEquals($newblob, $record->onebinary, 'Test "small" BLOB insert (full contents output disabled)');
$this->assertEquals(false, $rs->key()); // Ensure recordset key() method to be working ok after closing.
}
public function test_update_record_raw() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 1));
$DB->insert_record($tablename, array('course' => 3));
$record = $DB->get_record($tablename, array('course' => 1));
$record->course = 2;
$this->assertTrue($DB->update_record_raw($tablename, $record));
$this->assertEquals(0, $DB->count_records($tablename, array('course' => 1)));
$this->assertEquals(1, $DB->count_records($tablename, array('course' => 2)));
$this->assertEquals(1, $DB->count_records($tablename, array('course' => 3)));
$record = $DB->get_record($tablename, array('course' => 3));
$record->xxxxx = 2;
try {
$DB->update_record_raw($tablename, $record);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('moodle_exception', $e);
}
$record = $DB->get_record($tablename, array('course' => 3));
unset($record->id);
try {
$DB->update_record_raw($tablename, $record);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
}
public function test_update_record() {
// All the information in this test is fetched from DB by get_record() so we
// have such method properly tested against nulls, empties and friends...
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('oneint', XMLDB_TYPE_INTEGER, '10', null, null, null, 100);
$table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null, 200);
$table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null, 'onestring');
$table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null);
$table->add_field('onebinary', XMLDB_TYPE_BINARY, 'big', null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 1));
$record = $DB->get_record($tablename, array('course' => 1));
$record->course = 2;
$this->assertTrue($DB->update_record($tablename, $record));
$this->assertFalse($record = $DB->get_record($tablename, array('course' => 1)));
$this->assertNotEmpty($record = $DB->get_record($tablename, array('course' => 2)));
$this->assertEquals(100, $record->oneint); // Just check column defaults have been applied.
$this->assertEquals(200, $record->onenum);
$this->assertSame('onestring', $record->onechar);
$this->assertNull($record->onetext);
$this->assertNull($record->onebinary);
// Check nulls are set properly for all types.
$record->oneint = null;
$record->onenum = null;
$record->onechar = null;
$record->onetext = null;
$record->onebinary = null;
$DB->update_record($tablename, $record);
$record = $DB->get_record($tablename, array('course' => 2));
$this->assertNull($record->oneint);
$this->assertNull($record->onenum);
$this->assertNull($record->onechar);
$this->assertNull($record->onetext);
$this->assertNull($record->onebinary);
// Check zeros are set properly for all types.
$record->oneint = 0;
$record->onenum = 0;
$DB->update_record($tablename, $record);
$record = $DB->get_record($tablename, array('course' => 2));
$this->assertEquals(0, $record->oneint);
$this->assertEquals(0, $record->onenum);
// Check booleans are set properly for all types.
$record->oneint = true; // Trues.
$record->onenum = true;
$record->onechar = true;
$record->onetext = true;
$DB->update_record($tablename, $record);
$record = $DB->get_record($tablename, array('course' => 2));
$this->assertEquals(1, $record->oneint);
$this->assertEquals(1, $record->onenum);
$this->assertEquals(1, $record->onechar);
$this->assertEquals(1, $record->onetext);
$record->oneint = false; // Falses.
$record->onenum = false;
$record->onechar = false;
$record->onetext = false;
$DB->update_record($tablename, $record);
$record = $DB->get_record($tablename, array('course' => 2));
$this->assertEquals(0, $record->oneint);
$this->assertEquals(0, $record->onenum);
$this->assertEquals(0, $record->onechar);
$this->assertEquals(0, $record->onetext);
// Check string data causes exception in numeric types.
$record->oneint = 'onestring';
$record->onenum = 0;
try {
$DB->update_record($tablename, $record);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
$record->oneint = 0;
$record->onenum = 'onestring';
try {
$DB->update_record($tablename, $record);
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
// Check empty string data is stored as 0 in numeric datatypes.
$record->oneint = ''; // Empty string.
$record->onenum = 0;
$DB->update_record($tablename, $record);
$record = $DB->get_record($tablename, array('course' => 2));
$this->assertTrue(is_numeric($record->oneint) && $record->oneint == 0);
$record->oneint = 0;
$record->onenum = ''; // Empty string.
$DB->update_record($tablename, $record);
$record = $DB->get_record($tablename, array('course' => 2));
$this->assertTrue(is_numeric($record->onenum) && $record->onenum == 0);
// Check empty strings are set properly in string types.
$record->oneint = 0;
$record->onenum = 0;
$record->onechar = '';
$record->onetext = '';
$DB->update_record($tablename, $record);
$record = $DB->get_record($tablename, array('course' => 2));
$this->assertTrue($record->onechar === '');
$this->assertTrue($record->onetext === '');
// Check operation ((210.10 + 39.92) - 150.02) against numeric types.
$record->oneint = ((210.10 + 39.92) - 150.02);
$record->onenum = ((210.10 + 39.92) - 150.02);
$DB->update_record($tablename, $record);
$record = $DB->get_record($tablename, array('course' => 2));
$this->assertEquals(100, $record->oneint);
$this->assertEquals(100, $record->onenum);
// Check various quotes/backslashes combinations in string types.
$teststrings = array(
'backslashes and quotes alone (even): "" \'\' \\\\',
'backslashes and quotes alone (odd): """ \'\'\' \\\\\\',
'backslashes and quotes sequences (even): \\"\\" \\\'\\\'',
'backslashes and quotes sequences (odd): \\"\\"\\" \\\'\\\'\\\'');
foreach ($teststrings as $teststring) {
$record->onechar = $teststring;
$record->onetext = $teststring;
$DB->update_record($tablename, $record);
$record = $DB->get_record($tablename, array('course' => 2));
$this->assertEquals($teststring, $record->onechar);
$this->assertEquals($teststring, $record->onetext);
}
// Check LOBs in text/binary columns.
$clob = file_get_contents(__DIR__ . '/fixtures/clob.txt');
$blob = file_get_contents(__DIR__ . '/fixtures/randombinary');
$record->onetext = $clob;
$record->onebinary = $blob;
$DB->update_record($tablename, $record);
$record = $DB->get_record($tablename, array('course' => 2));
$this->assertEquals($clob, $record->onetext, 'Test CLOB update (full contents output disabled)');
$this->assertEquals($blob, $record->onebinary, 'Test BLOB update (full contents output disabled)');
// And "small" LOBs too, just in case.
$newclob = substr($clob, 0, 500);
$newblob = substr($blob, 0, 250);
$record->onetext = $newclob;
$record->onebinary = $newblob;
$DB->update_record($tablename, $record);
$record = $DB->get_record($tablename, array('course' => 2));
$this->assertEquals($newclob, $record->onetext, 'Test "small" CLOB update (full contents output disabled)');
$this->assertEquals($newblob, $record->onebinary, 'Test "small" BLOB update (full contents output disabled)');
// Test saving a float in a CHAR column, and reading it back.
$id = $DB->insert_record($tablename, array('onechar' => 'X'));
$DB->update_record($tablename, array('id' => $id, 'onechar' => 1.0));
$this->assertEquals(1.0, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$DB->update_record($tablename, array('id' => $id, 'onechar' => 1e20));
$this->assertEquals(1e20, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$DB->update_record($tablename, array('id' => $id, 'onechar' => 1e-4));
$this->assertEquals(1e-4, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$DB->update_record($tablename, array('id' => $id, 'onechar' => 1e-5));
$this->assertEquals(1e-5, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$DB->update_record($tablename, array('id' => $id, 'onechar' => 1e-300));
$this->assertEquals(1e-300, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$DB->update_record($tablename, array('id' => $id, 'onechar' => 1e300));
$this->assertEquals(1e300, $DB->get_field($tablename, 'onechar', array('id' => $id)));
// Test saving a float in a TEXT column, and reading it back.
$id = $DB->insert_record($tablename, array('onetext' => 'X'));
$DB->update_record($tablename, array('id' => $id, 'onetext' => 1.0));
$this->assertEquals(1.0, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$DB->update_record($tablename, array('id' => $id, 'onetext' => 1e20));
$this->assertEquals(1e20, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$DB->update_record($tablename, array('id' => $id, 'onetext' => 1e-4));
$this->assertEquals(1e-4, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$DB->update_record($tablename, array('id' => $id, 'onetext' => 1e-5));
$this->assertEquals(1e-5, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$DB->update_record($tablename, array('id' => $id, 'onetext' => 1e-300));
$this->assertEquals(1e-300, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$DB->update_record($tablename, array('id' => $id, 'onetext' => 1e300));
$this->assertEquals(1e300, $DB->get_field($tablename, 'onetext', array('id' => $id)));
}
public function test_set_field() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null);
$table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
// Simple set_field.
$id1 = $DB->insert_record($tablename, array('course' => 1));
$id2 = $DB->insert_record($tablename, array('course' => 1));
$id3 = $DB->insert_record($tablename, array('course' => 3));
$this->assertTrue($DB->set_field($tablename, 'course', 2, array('id' => $id1)));
$this->assertEquals(2, $DB->get_field($tablename, 'course', array('id' => $id1)));
$this->assertEquals(1, $DB->get_field($tablename, 'course', array('id' => $id2)));
$this->assertEquals(3, $DB->get_field($tablename, 'course', array('id' => $id3)));
$DB->delete_records($tablename, array());
// Multiple fields affected.
$id1 = $DB->insert_record($tablename, array('course' => 1));
$id2 = $DB->insert_record($tablename, array('course' => 1));
$id3 = $DB->insert_record($tablename, array('course' => 3));
$DB->set_field($tablename, 'course', '5', array('course' => 1));
$this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id1)));
$this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id2)));
$this->assertEquals(3, $DB->get_field($tablename, 'course', array('id' => $id3)));
$DB->delete_records($tablename, array());
// No field affected.
$id1 = $DB->insert_record($tablename, array('course' => 1));
$id2 = $DB->insert_record($tablename, array('course' => 1));
$id3 = $DB->insert_record($tablename, array('course' => 3));
$DB->set_field($tablename, 'course', '5', array('course' => 0));
$this->assertEquals(1, $DB->get_field($tablename, 'course', array('id' => $id1)));
$this->assertEquals(1, $DB->get_field($tablename, 'course', array('id' => $id2)));
$this->assertEquals(3, $DB->get_field($tablename, 'course', array('id' => $id3)));
$DB->delete_records($tablename, array());
// All fields - no condition.
$id1 = $DB->insert_record($tablename, array('course' => 1));
$id2 = $DB->insert_record($tablename, array('course' => 1));
$id3 = $DB->insert_record($tablename, array('course' => 3));
$DB->set_field($tablename, 'course', 5, array());
$this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id1)));
$this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id2)));
$this->assertEquals(5, $DB->get_field($tablename, 'course', array('id' => $id3)));
// Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int).
$conditions = array('onetext' => '1');
try {
$DB->set_field($tablename, 'onechar', 'frog', $conditions);
if (debugging()) {
// Only in debug mode - hopefully all devs test code in debug mode...
$this->fail('An Exception is missing, expected due to equating of text fields');
}
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
$this->assertSame('textconditionsnotallowed', $e->errorcode);
}
// Test saving a float in a CHAR column, and reading it back.
$id = $DB->insert_record($tablename, array('onechar' => 'X'));
$DB->set_field($tablename, 'onechar', 1.0, array('id' => $id));
$this->assertEquals(1.0, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$DB->set_field($tablename, 'onechar', 1e20, array('id' => $id));
$this->assertEquals(1e20, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$DB->set_field($tablename, 'onechar', 1e-4, array('id' => $id));
$this->assertEquals(1e-4, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$DB->set_field($tablename, 'onechar', 1e-5, array('id' => $id));
$this->assertEquals(1e-5, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$DB->set_field($tablename, 'onechar', 1e-300, array('id' => $id));
$this->assertEquals(1e-300, $DB->get_field($tablename, 'onechar', array('id' => $id)));
$DB->set_field($tablename, 'onechar', 1e300, array('id' => $id));
$this->assertEquals(1e300, $DB->get_field($tablename, 'onechar', array('id' => $id)));
// Test saving a float in a TEXT column, and reading it back.
$id = $DB->insert_record($tablename, array('onetext' => 'X'));
$DB->set_field($tablename, 'onetext', 1.0, array('id' => $id));
$this->assertEquals(1.0, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$DB->set_field($tablename, 'onetext', 1e20, array('id' => $id));
$this->assertEquals(1e20, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$DB->set_field($tablename, 'onetext', 1e-4, array('id' => $id));
$this->assertEquals(1e-4, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$DB->set_field($tablename, 'onetext', 1e-5, array('id' => $id));
$this->assertEquals(1e-5, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$DB->set_field($tablename, 'onetext', 1e-300, array('id' => $id));
$this->assertEquals(1e-300, $DB->get_field($tablename, 'onetext', array('id' => $id)));
$DB->set_field($tablename, 'onetext', 1e300, array('id' => $id));
$this->assertEquals(1e300, $DB->get_field($tablename, 'onetext', array('id' => $id)));
// Note: All the nulls, booleans, empties, quoted and backslashes tests
// go to set_field_select() because set_field() is just one wrapper over it.
}
public function test_set_field_select() {
// All the information in this test is fetched from DB by get_field() so we
// have such method properly tested against nulls, empties and friends...
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('oneint', XMLDB_TYPE_INTEGER, '10', null, null, null);
$table->add_field('onenum', XMLDB_TYPE_NUMBER, '10,2', null, null, null);
$table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null);
$table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null);
$table->add_field('onebinary', XMLDB_TYPE_BINARY, 'big', null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 1));
$this->assertTrue($DB->set_field_select($tablename, 'course', 2, 'id = ?', array(1)));
$this->assertEquals(2, $DB->get_field($tablename, 'course', array('id' => 1)));
// Check nulls are set properly for all types.
$DB->set_field_select($tablename, 'oneint', null, 'id = ?', array(1)); // Trues.
$DB->set_field_select($tablename, 'onenum', null, 'id = ?', array(1));
$DB->set_field_select($tablename, 'onechar', null, 'id = ?', array(1));
$DB->set_field_select($tablename, 'onetext', null, 'id = ?', array(1));
$DB->set_field_select($tablename, 'onebinary', null, 'id = ?', array(1));
$this->assertNull($DB->get_field($tablename, 'oneint', array('id' => 1)));
$this->assertNull($DB->get_field($tablename, 'onenum', array('id' => 1)));
$this->assertNull($DB->get_field($tablename, 'onechar', array('id' => 1)));
$this->assertNull($DB->get_field($tablename, 'onetext', array('id' => 1)));
$this->assertNull($DB->get_field($tablename, 'onebinary', array('id' => 1)));
// Check zeros are set properly for all types.
$DB->set_field_select($tablename, 'oneint', 0, 'id = ?', array(1));
$DB->set_field_select($tablename, 'onenum', 0, 'id = ?', array(1));
$this->assertEquals(0, $DB->get_field($tablename, 'oneint', array('id' => 1)));
$this->assertEquals(0, $DB->get_field($tablename, 'onenum', array('id' => 1)));
// Check booleans are set properly for all types.
$DB->set_field_select($tablename, 'oneint', true, 'id = ?', array(1)); // Trues.
$DB->set_field_select($tablename, 'onenum', true, 'id = ?', array(1));
$DB->set_field_select($tablename, 'onechar', true, 'id = ?', array(1));
$DB->set_field_select($tablename, 'onetext', true, 'id = ?', array(1));
$this->assertEquals(1, $DB->get_field($tablename, 'oneint', array('id' => 1)));
$this->assertEquals(1, $DB->get_field($tablename, 'onenum', array('id' => 1)));
$this->assertEquals(1, $DB->get_field($tablename, 'onechar', array('id' => 1)));
$this->assertEquals(1, $DB->get_field($tablename, 'onetext', array('id' => 1)));
$DB->set_field_select($tablename, 'oneint', false, 'id = ?', array(1)); // Falses.
$DB->set_field_select($tablename, 'onenum', false, 'id = ?', array(1));
$DB->set_field_select($tablename, 'onechar', false, 'id = ?', array(1));
$DB->set_field_select($tablename, 'onetext', false, 'id = ?', array(1));
$this->assertEquals(0, $DB->get_field($tablename, 'oneint', array('id' => 1)));
$this->assertEquals(0, $DB->get_field($tablename, 'onenum', array('id' => 1)));
$this->assertEquals(0, $DB->get_field($tablename, 'onechar', array('id' => 1)));
$this->assertEquals(0, $DB->get_field($tablename, 'onetext', array('id' => 1)));
// Check string data causes exception in numeric types.
try {
$DB->set_field_select($tablename, 'oneint', 'onestring', 'id = ?', array(1));
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
try {
$DB->set_field_select($tablename, 'onenum', 'onestring', 'id = ?', array(1));
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
}
// Check empty string data is stored as 0 in numeric datatypes.
$DB->set_field_select($tablename, 'oneint', '', 'id = ?', array(1));
$field = $DB->get_field($tablename, 'oneint', array('id' => 1));
$this->assertTrue(is_numeric($field) && $field == 0);
$DB->set_field_select($tablename, 'onenum', '', 'id = ?', array(1));
$field = $DB->get_field($tablename, 'onenum', array('id' => 1));
$this->assertTrue(is_numeric($field) && $field == 0);
// Check empty strings are set properly in string types.
$DB->set_field_select($tablename, 'onechar', '', 'id = ?', array(1));
$DB->set_field_select($tablename, 'onetext', '', 'id = ?', array(1));
$this->assertTrue($DB->get_field($tablename, 'onechar', array('id' => 1)) === '');
$this->assertTrue($DB->get_field($tablename, 'onetext', array('id' => 1)) === '');
// Check operation ((210.10 + 39.92) - 150.02) against numeric types.
$DB->set_field_select($tablename, 'oneint', ((210.10 + 39.92) - 150.02), 'id = ?', array(1));
$DB->set_field_select($tablename, 'onenum', ((210.10 + 39.92) - 150.02), 'id = ?', array(1));
$this->assertEquals(100, $DB->get_field($tablename, 'oneint', array('id' => 1)));
$this->assertEquals(100, $DB->get_field($tablename, 'onenum', array('id' => 1)));
// Check various quotes/backslashes combinations in string types.
$teststrings = array(
'backslashes and quotes alone (even): "" \'\' \\\\',
'backslashes and quotes alone (odd): """ \'\'\' \\\\\\',
'backslashes and quotes sequences (even): \\"\\" \\\'\\\'',
'backslashes and quotes sequences (odd): \\"\\"\\" \\\'\\\'\\\'');
foreach ($teststrings as $teststring) {
$DB->set_field_select($tablename, 'onechar', $teststring, 'id = ?', array(1));
$DB->set_field_select($tablename, 'onetext', $teststring, 'id = ?', array(1));
$this->assertEquals($teststring, $DB->get_field($tablename, 'onechar', array('id' => 1)));
$this->assertEquals($teststring, $DB->get_field($tablename, 'onetext', array('id' => 1)));
}
// Check LOBs in text/binary columns.
$clob = file_get_contents(__DIR__ . '/fixtures/clob.txt');
$blob = file_get_contents(__DIR__ . '/fixtures/randombinary');
$DB->set_field_select($tablename, 'onetext', $clob, 'id = ?', array(1));
$DB->set_field_select($tablename, 'onebinary', $blob, 'id = ?', array(1));
$this->assertEquals($clob, $DB->get_field($tablename, 'onetext', array('id' => 1)), 'Test CLOB set_field (full contents output disabled)');
$this->assertEquals($blob, $DB->get_field($tablename, 'onebinary', array('id' => 1)), 'Test BLOB set_field (full contents output disabled)');
// And "small" LOBs too, just in case.
$newclob = substr($clob, 0, 500);
$newblob = substr($blob, 0, 250);
$DB->set_field_select($tablename, 'onetext', $newclob, 'id = ?', array(1));
$DB->set_field_select($tablename, 'onebinary', $newblob, 'id = ?', array(1));
$this->assertEquals($newclob, $DB->get_field($tablename, 'onetext', array('id' => 1)), 'Test "small" CLOB set_field (full contents output disabled)');
$this->assertEquals($newblob, $DB->get_field($tablename, 'onebinary', array('id' => 1)), 'Test "small" BLOB set_field (full contents output disabled)');
// This is the failure from MDL-24863. This was giving an error on MSSQL,
// which converts the '1' to an integer, which cannot then be compared with
// onetext cast to a varchar. This should be fixed and working now.
$newchar = 'frog';
// Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int).
$params = array('onetext' => '1');
try {
$DB->set_field_select($tablename, 'onechar', $newchar, $DB->sql_compare_text('onetext') . ' = ?', $params);
$this->assertTrue(true, 'No exceptions thrown with numerical text param comparison for text field.');
} catch (dml_exception $e) {
$this->assertFalse(true, 'We have an unexpected exception.');
throw $e;
}
}
public function test_count_records() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$this->assertSame(0, $DB->count_records($tablename));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 4));
$DB->insert_record($tablename, array('course' => 5));
$this->assertSame(3, $DB->count_records($tablename));
// Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int).
$conditions = array('onetext' => '1');
try {
$DB->count_records($tablename, $conditions);
if (debugging()) {
// Only in debug mode - hopefully all devs test code in debug mode...
$this->fail('An Exception is missing, expected due to equating of text fields');
}
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
$this->assertSame('textconditionsnotallowed', $e->errorcode);
}
}
public function test_count_records_select() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$this->assertSame(0, $DB->count_records($tablename));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 4));
$DB->insert_record($tablename, array('course' => 5));
$this->assertSame(2, $DB->count_records_select($tablename, 'course > ?', array(3)));
}
public function test_count_records_sql() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('onechar', XMLDB_TYPE_CHAR, '100', null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$this->assertSame(0, $DB->count_records($tablename));
$DB->insert_record($tablename, array('course' => 3, 'onechar' => 'a'));
$DB->insert_record($tablename, array('course' => 4, 'onechar' => 'b'));
$DB->insert_record($tablename, array('course' => 5, 'onechar' => 'c'));
$this->assertSame(2, $DB->count_records_sql("SELECT COUNT(*) FROM {{$tablename}} WHERE course > ?", array(3)));
// Test invalid use.
try {
$DB->count_records_sql("SELECT onechar FROM {{$tablename}} WHERE course = ?", array(3));
$this->fail('Exception expected when non-number field used in count_records_sql');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
try {
$DB->count_records_sql("SELECT course FROM {{$tablename}} WHERE 1 = 2");
$this->fail('Exception expected when non-number field used in count_records_sql');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
}
public function test_record_exists() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$this->assertEquals(0, $DB->count_records($tablename));
$this->assertFalse($DB->record_exists($tablename, array('course' => 3)));
$DB->insert_record($tablename, array('course' => 3));
$this->assertTrue($DB->record_exists($tablename, array('course' => 3)));
// Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int).
$conditions = array('onetext' => '1');
try {
$DB->record_exists($tablename, $conditions);
if (debugging()) {
// Only in debug mode - hopefully all devs test code in debug mode...
$this->fail('An Exception is missing, expected due to equating of text fields');
}
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
$this->assertSame('textconditionsnotallowed', $e->errorcode);
}
}
public function test_record_exists_select() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$this->assertEquals(0, $DB->count_records($tablename));
$this->assertFalse($DB->record_exists_select($tablename, "course = ?", array(3)));
$DB->insert_record($tablename, array('course' => 3));
$this->assertTrue($DB->record_exists_select($tablename, "course = ?", array(3)));
}
public function test_record_exists_sql() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$this->assertEquals(0, $DB->count_records($tablename));
$this->assertFalse($DB->record_exists_sql("SELECT * FROM {{$tablename}} WHERE course = ?", array(3)));
$DB->insert_record($tablename, array('course' => 3));
$this->assertTrue($DB->record_exists_sql("SELECT * FROM {{$tablename}} WHERE course = ?", array(3)));
}
public function test_recordset_locks_delete() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
// Setup.
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 1));
$DB->insert_record($tablename, array('course' => 2));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 4));
$DB->insert_record($tablename, array('course' => 5));
$DB->insert_record($tablename, array('course' => 6));
// Test against db write locking while on an open recordset.
$rs = $DB->get_recordset($tablename, array(), null, 'course', 2, 2); // Get courses = {3,4}.
foreach ($rs as $record) {
$cid = $record->course;
$DB->delete_records($tablename, array('course' => $cid));
$this->assertFalse($DB->record_exists($tablename, array('course' => $cid)));
}
$rs->close();
$this->assertEquals(4, $DB->count_records($tablename, array()));
}
public function test_recordset_locks_update() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
// Setup.
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 1));
$DB->insert_record($tablename, array('course' => 2));
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 4));
$DB->insert_record($tablename, array('course' => 5));
$DB->insert_record($tablename, array('course' => 6));
// Test against db write locking while on an open recordset.
$rs = $DB->get_recordset($tablename, array(), null, 'course', 2, 2); // Get courses = {3,4}.
foreach ($rs as $record) {
$cid = $record->course;
$DB->set_field($tablename, 'course', 10, array('course' => $cid));
$this->assertFalse($DB->record_exists($tablename, array('course' => $cid)));
}
$rs->close();
$this->assertEquals(2, $DB->count_records($tablename, array('course' => 10)));
}
public function test_delete_records() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('onetext', XMLDB_TYPE_TEXT, 'big', null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 2));
$DB->insert_record($tablename, array('course' => 2));
// Delete all records.
$this->assertTrue($DB->delete_records($tablename));
$this->assertEquals(0, $DB->count_records($tablename));
// Delete subset of records.
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 2));
$DB->insert_record($tablename, array('course' => 2));
$this->assertTrue($DB->delete_records($tablename, array('course' => 2)));
$this->assertEquals(1, $DB->count_records($tablename));
// Delete all.
$this->assertTrue($DB->delete_records($tablename, array()));
$this->assertEquals(0, $DB->count_records($tablename));
// Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int).
$conditions = array('onetext'=>'1');
try {
$DB->delete_records($tablename, $conditions);
if (debugging()) {
// Only in debug mode - hopefully all devs test code in debug mode...
$this->fail('An Exception is missing, expected due to equating of text fields');
}
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
$this->assertSame('textconditionsnotallowed', $e->errorcode);
}
// Test for exception throwing on text conditions being compared. (MDL-24863, unwanted auto conversion of param to int).
$conditions = array('onetext' => 1);
try {
$DB->delete_records($tablename, $conditions);
if (debugging()) {
// Only in debug mode - hopefully all devs test code in debug mode...
$this->fail('An Exception is missing, expected due to equating of text fields');
}
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_exception', $e);
$this->assertSame('textconditionsnotallowed', $e->errorcode);
}
}
public function test_delete_records_select() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3));
$DB->insert_record($tablename, array('course' => 2));
$DB->insert_record($tablename, array('course' => 2));
$this->assertTrue($DB->delete_records_select($tablename, 'course = ?', array(2)));
$this->assertEquals(1, $DB->count_records($tablename));
}
public function test_delete_records_list() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 1));
$DB->insert_record($tablename, array('course' => 2));
$DB->insert_record($tablename, array('course' => 3));
$this->assertTrue($DB->delete_records_list($tablename, 'course', array(2, 3)));
$this->assertEquals(1, $DB->count_records($tablename));
$this->assertTrue($DB->delete_records_list($tablename, 'course', array())); // Must delete 0 rows without conditions. MDL-17645.
$this->assertEquals(1, $DB->count_records($tablename));
}
public function test_object_params() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$o = new stdClass(); // Objects without __toString - never worked.
try {
$DB->fix_sql_params("SELECT {{$tablename}} WHERE course = ? ", array($o));
$this->fail('coding_exception expected');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
// Objects with __toString() forbidden everywhere since 2.3.
$o = new dml_test_object_one();
try {
$DB->fix_sql_params("SELECT {{$tablename}} WHERE course = ? ", array($o));
$this->fail('coding_exception expected');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
try {
$DB->execute("SELECT {{$tablename}} WHERE course = ? ", array($o));
$this->fail('coding_exception expected');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
try {
$DB->get_recordset_sql("SELECT {{$tablename}} WHERE course = ? ", array($o));
$this->fail('coding_exception expected');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
try {
$DB->get_records_sql("SELECT {{$tablename}} WHERE course = ? ", array($o));
$this->fail('coding_exception expected');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
try {
$record = new stdClass();
$record->course = $o;
$DB->insert_record_raw($tablename, $record);
$this->fail('coding_exception expected');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
try {
$record = new stdClass();
$record->course = $o;
$DB->insert_record($tablename, $record);
$this->fail('coding_exception expected');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
try {
$record = new stdClass();
$record->course = $o;
$DB->import_record($tablename, $record);
$this->fail('coding_exception expected');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
try {
$record = new stdClass();
$record->id = 1;
$record->course = $o;
$DB->update_record_raw($tablename, $record);
$this->fail('coding_exception expected');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
try {
$record = new stdClass();
$record->id = 1;
$record->course = $o;
$DB->update_record($tablename, $record);
$this->fail('coding_exception expected');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
try {
$DB->set_field_select($tablename, 'course', 1, "course = ? ", array($o));
$this->fail('coding_exception expected');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
try {
$DB->delete_records_select($tablename, "course = ? ", array($o));
$this->fail('coding_exception expected');
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
}
public function test_sql_null_from_clause() {
$DB = $this->tdb;
$sql = "SELECT 1 AS id ".$DB->sql_null_from_clause();
$this->assertEquals(1, $DB->get_field_sql($sql));
}
public function test_sql_bitand() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('col1', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('col2', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('col1' => 3, 'col2' => 10));
$sql = "SELECT ".$DB->sql_bitand(10, 3)." AS res ".$DB->sql_null_from_clause();
$this->assertEquals(2, $DB->get_field_sql($sql));
$sql = "SELECT id, ".$DB->sql_bitand('col1', 'col2')." AS res FROM {{$tablename}}";
$result = $DB->get_records_sql($sql);
$this->assertCount(1, $result);
$this->assertEquals(2, reset($result)->res);
$sql = "SELECT id, ".$DB->sql_bitand('col1', '?')." AS res FROM {{$tablename}}";
$result = $DB->get_records_sql($sql, array(10));
$this->assertCount(1, $result);
$this->assertEquals(2, reset($result)->res);
}
public function test_sql_bitnot() {
$DB = $this->tdb;
$not = $DB->sql_bitnot(2);
$notlimited = $DB->sql_bitand($not, 7); // Might be positive or negative number which can not fit into PHP INT!
$sql = "SELECT $notlimited AS res ".$DB->sql_null_from_clause();
$this->assertEquals(5, $DB->get_field_sql($sql));
}
public function test_sql_bitor() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('col1', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('col2', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('col1' => 3, 'col2' => 10));
$sql = "SELECT ".$DB->sql_bitor(10, 3)." AS res ".$DB->sql_null_from_clause();
$this->assertEquals(11, $DB->get_field_sql($sql));
$sql = "SELECT id, ".$DB->sql_bitor('col1', 'col2')." AS res FROM {{$tablename}}";
$result = $DB->get_records_sql($sql);
$this->assertCount(1, $result);
$this->assertEquals(11, reset($result)->res);
$sql = "SELECT id, ".$DB->sql_bitor('col1', '?')." AS res FROM {{$tablename}}";
$result = $DB->get_records_sql($sql, array(10));
$this->assertCount(1, $result);
$this->assertEquals(11, reset($result)->res);
}
public function test_sql_bitxor() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('col1', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('col2', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('col1' => 3, 'col2' => 10));
$sql = "SELECT ".$DB->sql_bitxor(10, 3)." AS res ".$DB->sql_null_from_clause();
$this->assertEquals(9, $DB->get_field_sql($sql));
$sql = "SELECT id, ".$DB->sql_bitxor('col1', 'col2')." AS res FROM {{$tablename}}";
$result = $DB->get_records_sql($sql);
$this->assertCount(1, $result);
$this->assertEquals(9, reset($result)->res);
$sql = "SELECT id, ".$DB->sql_bitxor('col1', '?')." AS res FROM {{$tablename}}";
$result = $DB->get_records_sql($sql, array(10));
$this->assertCount(1, $result);
$this->assertEquals(9, reset($result)->res);
}
public function test_sql_modulo() {
$DB = $this->tdb;
$sql = "SELECT ".$DB->sql_modulo(10, 7)." AS res ".$DB->sql_null_from_clause();
$this->assertEquals(3, $DB->get_field_sql($sql));
}
public function test_sql_ceil() {
$DB = $this->tdb;
$sql = "SELECT ".$DB->sql_ceil(665.666)." AS res ".$DB->sql_null_from_clause();
$this->assertEquals(666, $DB->get_field_sql($sql));
}
public function test_cast_char2int() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table1 = $this->get_test_table("1");
$tablename1 = $table1->getName();
$table1->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table1->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table1->add_field('nametext', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
$table1->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table1);
$DB->insert_record($tablename1, array('name'=>'0100', 'nametext'=>'0200'));
$DB->insert_record($tablename1, array('name'=>'10', 'nametext'=>'20'));
$table2 = $this->get_test_table("2");
$tablename2 = $table2->getName();
$table2->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table2->add_field('res', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table2->add_field('restext', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table2->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table2);
$DB->insert_record($tablename2, array('res'=>100, 'restext'=>200));
// Casting varchar field.
$sql = "SELECT *
FROM {".$tablename1."} t1
JOIN {".$tablename2."} t2 ON ".$DB->sql_cast_char2int("t1.name")." = t2.res ";
$records = $DB->get_records_sql($sql);
$this->assertCount(1, $records);
// Also test them in order clauses.
$sql = "SELECT * FROM {{$tablename1}} ORDER BY ".$DB->sql_cast_char2int('name');
$records = $DB->get_records_sql($sql);
$this->assertCount(2, $records);
$this->assertSame('10', reset($records)->name);
$this->assertSame('0100', next($records)->name);
// Casting text field.
$sql = "SELECT *
FROM {".$tablename1."} t1
JOIN {".$tablename2."} t2 ON ".$DB->sql_cast_char2int("t1.nametext", true)." = t2.restext ";
$records = $DB->get_records_sql($sql);
$this->assertCount(1, $records);
// Also test them in order clauses.
$sql = "SELECT * FROM {{$tablename1}} ORDER BY ".$DB->sql_cast_char2int('nametext', true);
$records = $DB->get_records_sql($sql);
$this->assertCount(2, $records);
$this->assertSame('20', reset($records)->nametext);
$this->assertSame('0200', next($records)->nametext);
}
public function test_cast_char2real() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_field('nametext', XMLDB_TYPE_TEXT, 'small', null, null, null, null);
$table->add_field('res', XMLDB_TYPE_NUMBER, '12, 7', null, null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('name'=>'10.10', 'nametext'=>'10.10', 'res'=>5.1));
$DB->insert_record($tablename, array('name'=>'91.10', 'nametext'=>'91.10', 'res'=>666));
$DB->insert_record($tablename, array('name'=>'011.10', 'nametext'=>'011.10', 'res'=>10.1));
// Casting varchar field.
$sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_cast_char2real('name')." > res";
$records = $DB->get_records_sql($sql);
$this->assertCount(2, $records);
// Also test them in order clauses.
$sql = "SELECT * FROM {{$tablename}} ORDER BY ".$DB->sql_cast_char2real('name');
$records = $DB->get_records_sql($sql);
$this->assertCount(3, $records);
$this->assertSame('10.10', reset($records)->name);
$this->assertSame('011.10', next($records)->name);
$this->assertSame('91.10', next($records)->name);
// Casting text field.
$sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_cast_char2real('nametext', true)." > res";
$records = $DB->get_records_sql($sql);
$this->assertCount(2, $records);
// Also test them in order clauses.
$sql = "SELECT * FROM {{$tablename}} ORDER BY ".$DB->sql_cast_char2real('nametext', true);
$records = $DB->get_records_sql($sql);
$this->assertCount(3, $records);
$this->assertSame('10.10', reset($records)->nametext);
$this->assertSame('011.10', next($records)->nametext);
$this->assertSame('91.10', next($records)->nametext);
}
public function test_sql_compare_text() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('name'=>'abcd', 'description'=>'abcd'));
$DB->insert_record($tablename, array('name'=>'abcdef', 'description'=>'bbcdef'));
$DB->insert_record($tablename, array('name'=>'aaaa', 'description'=>'aaaacccccccccccccccccc'));
$DB->insert_record($tablename, array('name'=>'xxxx', 'description'=>'123456789a123456789b123456789c123456789d'));
// Only some supported databases truncate TEXT fields for comparisons, currently MSSQL and Oracle.
$dbtruncatestextfields = ($DB->get_dbfamily() == 'mssql' || $DB->get_dbfamily() == 'oracle');
if ($dbtruncatestextfields) {
// Ensure truncation behaves as expected.
$sql = "SELECT " . $DB->sql_compare_text('description') . " AS field FROM {{$tablename}} WHERE name = ?";
$description = $DB->get_field_sql($sql, array('xxxx'));
// Should truncate to 32 chars (the default).
$this->assertEquals('123456789a123456789b123456789c12', $description);
$sql = "SELECT " . $DB->sql_compare_text('description', 35) . " AS field FROM {{$tablename}} WHERE name = ?";
$description = $DB->get_field_sql($sql, array('xxxx'));
// Should truncate to the specified number of chars.
$this->assertEquals('123456789a123456789b123456789c12345', $description);
}
// Ensure text field comparison is successful.
$sql = "SELECT * FROM {{$tablename}} WHERE name = ".$DB->sql_compare_text('description');
$records = $DB->get_records_sql($sql);
$this->assertCount(1, $records);
$sql = "SELECT * FROM {{$tablename}} WHERE name = ".$DB->sql_compare_text('description', 4);
$records = $DB->get_records_sql($sql);
if ($dbtruncatestextfields) {
// Should truncate description to 4 characters before comparing.
$this->assertCount(2, $records);
} else {
// Should leave untruncated, so one less match.
$this->assertCount(1, $records);
}
// Now test the function with really big content and params.
$clob = file_get_contents(__DIR__ . '/fixtures/clob.txt');
$DB->insert_record($tablename, array('name' => 'zzzz', 'description' => $clob));
$sql = "SELECT * FROM {{$tablename}}
WHERE " . $DB->sql_compare_text('description') . " = " . $DB->sql_compare_text(':clob');
$records = $DB->get_records_sql($sql, array('clob' => $clob));
$this->assertCount(1, $records);
$record = reset($records);
$this->assertSame($clob, $record->description);
}
public function test_unique_index_collation_trouble() {
// Note: this is a work in progress, we should probably move this to ddl test.
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$table->add_index('name', XMLDB_INDEX_UNIQUE, array('name'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('name'=>'aaa'));
try {
$DB->insert_record($tablename, array('name'=>'AAA'));
} catch (moodle_exception $e) {
// TODO: ignore case insensitive uniqueness problems for now.
// $this->fail("Unique index is case sensitive - this may cause problems in some tables");
}
try {
$DB->insert_record($tablename, array('name'=>'aäa'));
$DB->insert_record($tablename, array('name'=>'aáa'));
$this->assertTrue(true);
} catch (moodle_exception $e) {
$family = $DB->get_dbfamily();
if ($family === 'mysql' or $family === 'mssql') {
$this->fail("Unique index is accent insensitive, this may cause problems for non-ascii languages. This is usually caused by accent insensitive default collation.");
} else {
// This should not happen, PostgreSQL and Oracle do not support accent insensitive uniqueness.
$this->fail("Unique index is accent insensitive, this may cause problems for non-ascii languages.");
}
throw($e);
}
}
public function test_sql_binary_equal() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('name'=>'aaa'));
$DB->insert_record($tablename, array('name'=>'aáa'));
$DB->insert_record($tablename, array('name'=>'aäa'));
$DB->insert_record($tablename, array('name'=>'bbb'));
$DB->insert_record($tablename, array('name'=>'BBB'));
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE name = ?", array('bbb'));
$this->assertEquals(1, count($records), 'SQL operator "=" is expected to be case sensitive');
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE name = ?", array('aaa'));
$this->assertEquals(1, count($records), 'SQL operator "=" is expected to be accent sensitive');
}
public function test_sql_like() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('name'=>'SuperDuperRecord'));
$DB->insert_record($tablename, array('name'=>'Nodupor'));
$DB->insert_record($tablename, array('name'=>'ouch'));
$DB->insert_record($tablename, array('name'=>'ouc_'));
$DB->insert_record($tablename, array('name'=>'ouc%'));
$DB->insert_record($tablename, array('name'=>'aui'));
$DB->insert_record($tablename, array('name'=>'aüi'));
$DB->insert_record($tablename, array('name'=>'aÜi'));
$sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', false);
$records = $DB->get_records_sql($sql, array("%dup_r%"));
$this->assertCount(2, $records);
$sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true);
$records = $DB->get_records_sql($sql, array("%dup%"));
$this->assertCount(1, $records);
$sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?'); // Defaults.
$records = $DB->get_records_sql($sql, array("%dup%"));
$this->assertCount(1, $records);
$sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true);
$records = $DB->get_records_sql($sql, array("ouc\\_"));
$this->assertCount(1, $records);
$sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true, false, '|');
$records = $DB->get_records_sql($sql, array($DB->sql_like_escape("ouc%", '|')));
$this->assertCount(1, $records);
$sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true);
$records = $DB->get_records_sql($sql, array('aui'));
$this->assertCount(1, $records);
$sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true, true); // NOT LIKE.
$records = $DB->get_records_sql($sql, array("%o%"));
$this->assertCount(3, $records);
$sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', false, true, true); // NOT ILIKE.
$records = $DB->get_records_sql($sql, array("%D%"));
$this->assertCount(6, $records);
// Verify usual escaping characters work fine.
$sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true, false, '\\');
$records = $DB->get_records_sql($sql, array("ouc\\_"));
$this->assertCount(1, $records);
$sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, true, false, '|');
$records = $DB->get_records_sql($sql, array("ouc|%"));
$this->assertCount(1, $records);
// TODO: we do not require accent insensitivness yet, just make sure it does not throw errors.
$sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', true, false);
$records = $DB->get_records_sql($sql, array('aui'));
// $this->assertEquals(2, count($records), 'Accent insensitive LIKE searches may not be supported in all databases, this is not a problem.');
$sql = "SELECT * FROM {{$tablename}} WHERE ".$DB->sql_like('name', '?', false, false);
$records = $DB->get_records_sql($sql, array('aui'));
// $this->assertEquals(3, count($records), 'Accent insensitive LIKE searches may not be supported in all databases, this is not a problem.');
}
public function test_coalesce() {
$DB = $this->tdb;
// Testing not-null occurrences, return 1st.
$sql = "SELECT COALESCE('returnthis', 'orthis', 'orwhynotthis') AS test" . $DB->sql_null_from_clause();
$this->assertSame('returnthis', $DB->get_field_sql($sql, array()));
$sql = "SELECT COALESCE(:paramvalue, 'orthis', 'orwhynotthis') AS test" . $DB->sql_null_from_clause();
$this->assertSame('returnthis', $DB->get_field_sql($sql, array('paramvalue' => 'returnthis')));
// Testing null occurrences, return 2nd.
$sql = "SELECT COALESCE(null, 'returnthis', 'orthis') AS test" . $DB->sql_null_from_clause();
$this->assertSame('returnthis', $DB->get_field_sql($sql, array()));
$sql = "SELECT COALESCE(:paramvalue, 'returnthis', 'orthis') AS test" . $DB->sql_null_from_clause();
$this->assertSame('returnthis', $DB->get_field_sql($sql, array('paramvalue' => null)));
$sql = "SELECT COALESCE(null, :paramvalue, 'orthis') AS test" . $DB->sql_null_from_clause();
$this->assertSame('returnthis', $DB->get_field_sql($sql, array('paramvalue' => 'returnthis')));
// Testing null occurrences, return 3rd.
$sql = "SELECT COALESCE(null, null, 'returnthis') AS test" . $DB->sql_null_from_clause();
$this->assertSame('returnthis', $DB->get_field_sql($sql, array()));
$sql = "SELECT COALESCE(null, :paramvalue, 'returnthis') AS test" . $DB->sql_null_from_clause();
$this->assertSame('returnthis', $DB->get_field_sql($sql, array('paramvalue' => null)));
$sql = "SELECT COALESCE(null, null, :paramvalue) AS test" . $DB->sql_null_from_clause();
$this->assertSame('returnthis', $DB->get_field_sql($sql, array('paramvalue' => 'returnthis')));
// Testing all null occurrences, return null.
// Note: under mssql, if all elements are nulls, at least one must be a "typed" null, hence
// we cannot test this in a cross-db way easily, so next 2 tests are using
// different queries depending of the DB family.
$customnull = $DB->get_dbfamily() == 'mssql' ? 'CAST(null AS varchar)' : 'null';
$sql = "SELECT COALESCE(null, null, " . $customnull . ") AS test" . $DB->sql_null_from_clause();
$this->assertNull($DB->get_field_sql($sql, array()));
$sql = "SELECT COALESCE(null, :paramvalue, " . $customnull . ") AS test" . $DB->sql_null_from_clause();
$this->assertNull($DB->get_field_sql($sql, array('paramvalue' => null)));
// Check there are not problems with whitespace strings.
$sql = "SELECT COALESCE(null, :paramvalue, null) AS test" . $DB->sql_null_from_clause();
$this->assertSame('', $DB->get_field_sql($sql, array('paramvalue' => '')));
}
public function test_sql_concat() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
// Testing all sort of values.
$sql = "SELECT ".$DB->sql_concat("?", "?", "?")." AS fullname ". $DB->sql_null_from_clause();
// String, some unicode chars.
$params = array('name', 'áéíóú', 'name3');
$this->assertSame('nameáéíóúname3', $DB->get_field_sql($sql, $params));
// String, spaces and numbers.
$params = array('name', ' ', 12345);
$this->assertSame('name 12345', $DB->get_field_sql($sql, $params));
// Float, empty and strings.
$params = array(123.45, '', 'test');
$this->assertSame('123.45test', $DB->get_field_sql($sql, $params));
// Only integers.
$params = array(12, 34, 56);
$this->assertSame('123456', $DB->get_field_sql($sql, $params));
// Float, null and strings.
$params = array(123.45, null, 'test');
$this->assertNull($DB->get_field_sql($sql, $params)); // Concatenate null with anything result = null.
// Testing fieldnames + values and also integer fieldnames.
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('description'=>'áéíóú'));
$DB->insert_record($tablename, array('description'=>'dxxx'));
$DB->insert_record($tablename, array('description'=>'bcde'));
// Fieldnames and values mixed.
$sql = 'SELECT id, ' . $DB->sql_concat('description', "'harcoded'", '?', '?') . ' AS result FROM {' . $tablename . '}';
$records = $DB->get_records_sql($sql, array(123.45, 'test'));
$this->assertCount(3, $records);
$this->assertSame('áéíóúharcoded123.45test', $records[1]->result);
// Integer fieldnames and values.
$sql = 'SELECT id, ' . $DB->sql_concat('id', "'harcoded'", '?', '?') . ' AS result FROM {' . $tablename . '}';
$records = $DB->get_records_sql($sql, array(123.45, 'test'));
$this->assertCount(3, $records);
$this->assertSame('1harcoded123.45test', $records[1]->result);
// All integer fieldnames.
$sql = 'SELECT id, ' . $DB->sql_concat('id', 'id', 'id') . ' AS result FROM {' . $tablename . '}';
$records = $DB->get_records_sql($sql, array());
$this->assertCount(3, $records);
$this->assertSame('111', $records[1]->result);
}
public function test_concat_join() {
$DB = $this->tdb;
$sql = "SELECT ".$DB->sql_concat_join("' '", array("?", "?", "?"))." AS fullname ".$DB->sql_null_from_clause();
$params = array("name", "name2", "name3");
$result = $DB->get_field_sql($sql, $params);
$this->assertEquals("name name2 name3", $result);
}
public function test_sql_fullname() {
$DB = $this->tdb;
$sql = "SELECT ".$DB->sql_fullname(':first', ':last')." AS fullname ".$DB->sql_null_from_clause();
$params = array('first'=>'Firstname', 'last'=>'Surname');
$this->assertEquals("Firstname Surname", $DB->get_field_sql($sql, $params));
}
public function test_sql_order_by_text() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('description'=>'abcd'));
$DB->insert_record($tablename, array('description'=>'dxxx'));
$DB->insert_record($tablename, array('description'=>'bcde'));
$sql = "SELECT * FROM {{$tablename}} ORDER BY ".$DB->sql_order_by_text('description');
$records = $DB->get_records_sql($sql);
$first = array_shift($records);
$this->assertEquals(1, $first->id);
$second = array_shift($records);
$this->assertEquals(3, $second->id);
$last = array_shift($records);
$this->assertEquals(2, $last->id);
}
public function test_sql_substring() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$string = 'abcdefghij';
$DB->insert_record($tablename, array('name'=>$string));
$sql = "SELECT id, ".$DB->sql_substr("name", 5)." AS name FROM {{$tablename}}";
$record = $DB->get_record_sql($sql);
$this->assertEquals(substr($string, 5-1), $record->name);
$sql = "SELECT id, ".$DB->sql_substr("name", 5, 2)." AS name FROM {{$tablename}}";
$record = $DB->get_record_sql($sql);
$this->assertEquals(substr($string, 5-1, 2), $record->name);
try {
// Silence php warning.
@$DB->sql_substr("name");
$this->fail("Expecting an exception, none occurred");
} catch (moodle_exception $e) {
$this->assertInstanceOf('coding_exception', $e);
}
// Cover the function using placeholders in all positions.
$start = 4;
$length = 2;
// 1st param (target).
$sql = "SELECT id, ".$DB->sql_substr(":param1", $start)." AS name FROM {{$tablename}}";
$record = $DB->get_record_sql($sql, array('param1' => $string));
$this->assertEquals(substr($string, $start - 1), $record->name); // PHP's substr is 0-based.
// 2nd param (start).
$sql = "SELECT id, ".$DB->sql_substr("name", ":param1")." AS name FROM {{$tablename}}";
$record = $DB->get_record_sql($sql, array('param1' => $start));
$this->assertEquals(substr($string, $start - 1), $record->name); // PHP's substr is 0-based.
// 3rd param (length).
$sql = "SELECT id, ".$DB->sql_substr("name", $start, ":param1")." AS name FROM {{$tablename}}";
$record = $DB->get_record_sql($sql, array('param1' => $length));
$this->assertEquals(substr($string, $start - 1, $length), $record->name); // PHP's substr is 0-based.
// All together.
$sql = "SELECT id, ".$DB->sql_substr(":param1", ":param2", ":param3")." AS name FROM {{$tablename}}";
$record = $DB->get_record_sql($sql, array('param1' => $string, 'param2' => $start, 'param3' => $length));
$this->assertEquals(substr($string, $start - 1, $length), $record->name); // PHP's substr is 0-based.
// Try also with some expression passed.
$sql = "SELECT id, ".$DB->sql_substr("name", "(:param1 + 1) - 1")." AS name FROM {{$tablename}}";
$record = $DB->get_record_sql($sql, array('param1' => $start));
$this->assertEquals(substr($string, $start - 1), $record->name); // PHP's substr is 0-based.
}
public function test_sql_length() {
$DB = $this->tdb;
$this->assertEquals($DB->get_field_sql(
"SELECT ".$DB->sql_length("'aeiou'").$DB->sql_null_from_clause()), 5);
$this->assertEquals($DB->get_field_sql(
"SELECT ".$DB->sql_length("'áéíóú'").$DB->sql_null_from_clause()), 5);
}
public function test_sql_position() {
$DB = $this->tdb;
$this->assertEquals($DB->get_field_sql(
"SELECT ".$DB->sql_position("'ood'", "'Moodle'").$DB->sql_null_from_clause()), 2);
$this->assertEquals($DB->get_field_sql(
"SELECT ".$DB->sql_position("'Oracle'", "'Moodle'").$DB->sql_null_from_clause()), 0);
}
public function test_sql_empty() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$this->assertSame('', $DB->sql_empty()); // Since 2.5 the hack is applied automatically to all bound params.
$this->assertDebuggingCalled();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_field('namenotnull', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, 'default value');
$table->add_field('namenotnullnodeflt', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('name'=>'', 'namenotnull'=>''));
$DB->insert_record($tablename, array('name'=>null));
$DB->insert_record($tablename, array('name'=>'lalala'));
$DB->insert_record($tablename, array('name'=>0));
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE name = ?", array(''));
$this->assertCount(1, $records);
$record = reset($records);
$this->assertSame('', $record->name);
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE namenotnull = ?", array(''));
$this->assertCount(1, $records);
$record = reset($records);
$this->assertSame('', $record->namenotnull);
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE namenotnullnodeflt = ?", array(''));
$this->assertCount(4, $records);
$record = reset($records);
$this->assertSame('', $record->namenotnullnodeflt);
}
public function test_sql_isempty() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
$table->add_field('namenull', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null);
$table->add_field('descriptionnull', XMLDB_TYPE_TEXT, 'big', null, null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('name'=>'', 'namenull'=>'', 'description'=>'', 'descriptionnull'=>''));
$DB->insert_record($tablename, array('name'=>'??', 'namenull'=>null, 'description'=>'??', 'descriptionnull'=>null));
$DB->insert_record($tablename, array('name'=>'la', 'namenull'=>'la', 'description'=>'la', 'descriptionnull'=>'lalala'));
$DB->insert_record($tablename, array('name'=>0, 'namenull'=>0, 'description'=>0, 'descriptionnull'=>0));
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isempty($tablename, 'name', false, false));
$this->assertCount(1, $records);
$record = reset($records);
$this->assertSame('', $record->name);
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isempty($tablename, 'namenull', true, false));
$this->assertCount(1, $records);
$record = reset($records);
$this->assertSame('', $record->namenull);
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isempty($tablename, 'description', false, true));
$this->assertCount(1, $records);
$record = reset($records);
$this->assertSame('', $record->description);
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isempty($tablename, 'descriptionnull', true, true));
$this->assertCount(1, $records);
$record = reset($records);
$this->assertSame('', $record->descriptionnull);
}
public function test_sql_isnotempty() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null);
$table->add_field('namenull', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_field('description', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL, null, null);
$table->add_field('descriptionnull', XMLDB_TYPE_TEXT, 'big', null, null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('name'=>'', 'namenull'=>'', 'description'=>'', 'descriptionnull'=>''));
$DB->insert_record($tablename, array('name'=>'??', 'namenull'=>null, 'description'=>'??', 'descriptionnull'=>null));
$DB->insert_record($tablename, array('name'=>'la', 'namenull'=>'la', 'description'=>'la', 'descriptionnull'=>'lalala'));
$DB->insert_record($tablename, array('name'=>0, 'namenull'=>0, 'description'=>0, 'descriptionnull'=>0));
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isnotempty($tablename, 'name', false, false));
$this->assertCount(3, $records);
$record = reset($records);
$this->assertSame('??', $record->name);
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isnotempty($tablename, 'namenull', true, false));
$this->assertCount(2, $records); // Nulls aren't comparable (so they aren't "not empty"). SQL expected behaviour.
$record = reset($records);
$this->assertSame('la', $record->namenull); // So 'la' is the first non-empty 'namenull' record.
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isnotempty($tablename, 'description', false, true));
$this->assertCount(3, $records);
$record = reset($records);
$this->assertSame('??', $record->description);
$records = $DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE ".$DB->sql_isnotempty($tablename, 'descriptionnull', true, true));
$this->assertCount(2, $records); // Nulls aren't comparable (so they aren't "not empty"). SQL expected behaviour.
$record = reset($records);
$this->assertSame('lalala', $record->descriptionnull); // So 'lalala' is the first non-empty 'descriptionnull' record.
}
public function test_sql_regex() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('name'=>'lalala'));
$DB->insert_record($tablename, array('name'=>'holaaa'));
$DB->insert_record($tablename, array('name'=>'aouch'));
$sql = "SELECT * FROM {{$tablename}} WHERE name ".$DB->sql_regex()." ?";
$params = array('a$');
if ($DB->sql_regex_supported()) {
$records = $DB->get_records_sql($sql, $params);
$this->assertCount(2, $records);
} else {
$this->assertTrue(true, 'Regexp operations not supported. Test skipped');
}
$sql = "SELECT * FROM {{$tablename}} WHERE name ".$DB->sql_regex(false)." ?";
$params = array('.a');
if ($DB->sql_regex_supported()) {
$records = $DB->get_records_sql($sql, $params);
$this->assertCount(1, $records);
} else {
$this->assertTrue(true, 'Regexp operations not supported. Test skipped');
}
}
/**
* Test some complicated variations of set_field_select.
*/
public function test_set_field_select_complicated() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_field('content', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3, 'content' => 'hello', 'name'=>'xyz'));
$DB->insert_record($tablename, array('course' => 3, 'content' => 'world', 'name'=>'abc'));
$DB->insert_record($tablename, array('course' => 5, 'content' => 'hello', 'name'=>'def'));
$DB->insert_record($tablename, array('course' => 2, 'content' => 'universe', 'name'=>'abc'));
// This SQL is a tricky case because we are selecting from the same table we are updating.
$sql = 'id IN (SELECT outerq.id from (SELECT innerq.id from {' . $tablename . '} innerq WHERE course = 3) outerq)';
$DB->set_field_select($tablename, 'name', 'ghi', $sql);
$this->assertSame(2, $DB->count_records_select($tablename, 'name = ?', array('ghi')));
}
/**
* Test some more complex SQL syntax which moodle uses and depends on to work
* useful to determine if new database libraries can be supported.
*/
public function test_get_records_sql_complicated() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_field('content', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => 3, 'content' => 'hello', 'name'=>'xyz'));
$DB->insert_record($tablename, array('course' => 3, 'content' => 'world', 'name'=>'abc'));
$DB->insert_record($tablename, array('course' => 5, 'content' => 'hello', 'name'=>'def'));
$DB->insert_record($tablename, array('course' => 2, 'content' => 'universe', 'name'=>'abc'));
// Test grouping by expressions in the query. MDL-26819. Note that there are 4 ways:
// - By column position (GROUP by 1) - Not supported by mssql & oracle
// - By column name (GROUP by course) - Supported by all, but leading to wrong results
// - By column alias (GROUP by casecol) - Not supported by mssql & oracle
// - By complete expression (GROUP BY CASE ...) - 100% cross-db, this test checks it
$sql = "SELECT (CASE WHEN course = 3 THEN 1 ELSE 0 END) AS casecol,
COUNT(1) AS countrecs,
MAX(name) AS maxname
FROM {{$tablename}}
GROUP BY CASE WHEN course = 3 THEN 1 ELSE 0 END
ORDER BY casecol DESC";
$result = array(
1 => (object)array('casecol' => 1, 'countrecs' => 2, 'maxname' => 'xyz'),
0 => (object)array('casecol' => 0, 'countrecs' => 2, 'maxname' => 'def'));
$records = $DB->get_records_sql($sql, null);
$this->assertEquals($result, $records);
// Another grouping by CASE expression just to ensure it works ok for multiple WHEN.
$sql = "SELECT CASE name
WHEN 'xyz' THEN 'last'
WHEN 'def' THEN 'mid'
WHEN 'abc' THEN 'first'
END AS casecol,
COUNT(1) AS countrecs,
MAX(name) AS maxname
FROM {{$tablename}}
GROUP BY CASE name
WHEN 'xyz' THEN 'last'
WHEN 'def' THEN 'mid'
WHEN 'abc' THEN 'first'
END
ORDER BY casecol DESC";
$result = array(
'mid' => (object)array('casecol' => 'mid', 'countrecs' => 1, 'maxname' => 'def'),
'last' => (object)array('casecol' => 'last', 'countrecs' => 1, 'maxname' => 'xyz'),
'first'=> (object)array('casecol' => 'first', 'countrecs' => 2, 'maxname' => 'abc'));
$records = $DB->get_records_sql($sql, null);
$this->assertEquals($result, $records);
// Test CASE expressions in the ORDER BY clause - used by MDL-34657.
$sql = "SELECT id, course, name
FROM {{$tablename}}
ORDER BY CASE WHEN (course = 5 OR name = 'xyz') THEN 0 ELSE 1 END, name, course";
// First, records matching the course = 5 OR name = 'xyz', then the rest. Each.
// group ordered by name and course.
$result = array(
3 => (object)array('id' => 3, 'course' => 5, 'name' => 'def'),
1 => (object)array('id' => 1, 'course' => 3, 'name' => 'xyz'),
4 => (object)array('id' => 4, 'course' => 2, 'name' => 'abc'),
2 => (object)array('id' => 2, 'course' => 3, 'name' => 'abc'));
$records = $DB->get_records_sql($sql, null);
$this->assertEquals($result, $records);
// Verify also array keys, order is important in this test.
$this->assertEquals(array_keys($result), array_keys($records));
// Test limits in queries with DISTINCT/ALL clauses and multiple whitespace. MDL-25268.
$sql = "SELECT DISTINCT course
FROM {{$tablename}}
ORDER BY course";
// Only limitfrom.
$records = $DB->get_records_sql($sql, null, 1);
$this->assertCount(2, $records);
$this->assertEquals(3, reset($records)->course);
$this->assertEquals(5, next($records)->course);
// Only limitnum.
$records = $DB->get_records_sql($sql, null, 0, 2);
$this->assertCount(2, $records);
$this->assertEquals(2, reset($records)->course);
$this->assertEquals(3, next($records)->course);
// Both limitfrom and limitnum.
$records = $DB->get_records_sql($sql, null, 2, 2);
$this->assertCount(1, $records);
$this->assertEquals(5, reset($records)->course);
// We have sql like this in moodle, this syntax breaks on older versions of sqlite for example..
$sql = "SELECT a.id AS id, a.course AS course
FROM {{$tablename}} a
JOIN (SELECT * FROM {{$tablename}}) b ON a.id = b.id
WHERE a.course = ?";
$records = $DB->get_records_sql($sql, array(3));
$this->assertCount(2, $records);
$this->assertEquals(1, reset($records)->id);
$this->assertEquals(2, next($records)->id);
// Do NOT try embedding sql_xxxx() helper functions in conditions array of count_records(), they don't break params/binding!
$count = $DB->count_records_select($tablename, "course = :course AND ".$DB->sql_compare_text('content')." = :content", array('course' => 3, 'content' => 'hello'));
$this->assertEquals(1, $count);
// Test int x string comparison.
$sql = "SELECT *
FROM {{$tablename}} c
WHERE name = ?";
$this->assertCount(0, $DB->get_records_sql($sql, array(10)));
$this->assertCount(0, $DB->get_records_sql($sql, array("10")));
$DB->insert_record($tablename, array('course' => 7, 'content' => 'xx', 'name'=>'1'));
$DB->insert_record($tablename, array('course' => 7, 'content' => 'yy', 'name'=>'2'));
$this->assertCount(1, $DB->get_records_sql($sql, array(1)));
$this->assertCount(1, $DB->get_records_sql($sql, array("1")));
$this->assertCount(0, $DB->get_records_sql($sql, array(10)));
$this->assertCount(0, $DB->get_records_sql($sql, array("10")));
$DB->insert_record($tablename, array('course' => 7, 'content' => 'xx', 'name'=>'1abc'));
$this->assertCount(1, $DB->get_records_sql($sql, array(1)));
$this->assertCount(1, $DB->get_records_sql($sql, array("1")));
// Test get_in_or_equal() with a big number of elements. Note that ideally
// we should be detecting and warning about any use over, say, 200 elements
// And recommend to change code to use subqueries and/or chunks instead.
$currentcount = $DB->count_records($tablename);
$numelements = 10000; // Verify that we can handle 10000 elements (crazy!)
$values = range(1, $numelements);
list($insql, $inparams) = $DB->get_in_or_equal($values, SQL_PARAMS_QM); // With QM params.
$sql = "SELECT *
FROM {{$tablename}}
WHERE id $insql";
$results = $DB->get_records_sql($sql, $inparams);
$this->assertCount($currentcount, $results);
list($insql, $inparams) = $DB->get_in_or_equal($values, SQL_PARAMS_NAMED); // With NAMED params.
$sql = "SELECT *
FROM {{$tablename}}
WHERE id $insql";
$results = $DB->get_records_sql($sql, $inparams);
$this->assertCount($currentcount, $results);
}
public function test_replace_all_text() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
if (!$DB->replace_all_text_supported()) {
$this->markTestSkipped($DB->get_name().' does not support replacing of texts');
}
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '20', null, null);
$table->add_field('intro', XMLDB_TYPE_TEXT, 'big', null, null);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$id1 = (string)$DB->insert_record($tablename, array('name' => null, 'intro' => null));
$id2 = (string)$DB->insert_record($tablename, array('name' => '', 'intro' => ''));
$id3 = (string)$DB->insert_record($tablename, array('name' => 'xxyy', 'intro' => 'vvzz'));
$id4 = (string)$DB->insert_record($tablename, array('name' => 'aa bb aa bb', 'intro' => 'cc dd cc aa'));
$id5 = (string)$DB->insert_record($tablename, array('name' => 'kkllll', 'intro' => 'kkllll'));
$expected = $DB->get_records($tablename, array(), 'id ASC');
$columns = $DB->get_columns($tablename);
$DB->replace_all_text($tablename, $columns['name'], 'aa', 'o');
$result = $DB->get_records($tablename, array(), 'id ASC');
$expected[$id4]->name = 'o bb o bb';
$this->assertEquals($expected, $result);
$DB->replace_all_text($tablename, $columns['intro'], 'aa', 'o');
$result = $DB->get_records($tablename, array(), 'id ASC');
$expected[$id4]->intro = 'cc dd cc o';
$this->assertEquals($expected, $result);
$DB->replace_all_text($tablename, $columns['name'], '_', '*');
$DB->replace_all_text($tablename, $columns['name'], '?', '*');
$DB->replace_all_text($tablename, $columns['name'], '%', '*');
$DB->replace_all_text($tablename, $columns['intro'], '_', '*');
$DB->replace_all_text($tablename, $columns['intro'], '?', '*');
$DB->replace_all_text($tablename, $columns['intro'], '%', '*');
$result = $DB->get_records($tablename, array(), 'id ASC');
$this->assertEquals($expected, $result);
$long = '1234567890123456789';
$DB->replace_all_text($tablename, $columns['name'], 'kk', $long);
$result = $DB->get_records($tablename, array(), 'id ASC');
$expected[$id5]->name = core_text::substr($long.'llll', 0, 20);
$this->assertEquals($expected, $result);
$DB->replace_all_text($tablename, $columns['intro'], 'kk', $long);
$result = $DB->get_records($tablename, array(), 'id ASC');
$expected[$id5]->intro = $long.'llll';
$this->assertEquals($expected, $result);
}
public function test_onelevel_commit() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$transaction = $DB->start_delegated_transaction();
$data = (object)array('course'=>3);
$this->assertEquals(0, $DB->count_records($tablename));
$DB->insert_record($tablename, $data);
$this->assertEquals(1, $DB->count_records($tablename));
$transaction->allow_commit();
$this->assertEquals(1, $DB->count_records($tablename));
}
public function test_transaction_ignore_error_trouble() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$table->add_index('course', XMLDB_INDEX_UNIQUE, array('course'));
$dbman->create_table($table);
// Test error on SQL_QUERY_INSERT.
$transaction = $DB->start_delegated_transaction();
$this->assertEquals(0, $DB->count_records($tablename));
$DB->insert_record($tablename, (object)array('course'=>1));
$this->assertEquals(1, $DB->count_records($tablename));
try {
$DB->insert_record($tablename, (object)array('course'=>1));
} catch (Exception $e) {
// This must be ignored and it must not roll back the whole transaction.
}
$DB->insert_record($tablename, (object)array('course'=>2));
$this->assertEquals(2, $DB->count_records($tablename));
$transaction->allow_commit();
$this->assertEquals(2, $DB->count_records($tablename));
$this->assertFalse($DB->is_transaction_started());
// Test error on SQL_QUERY_SELECT.
$DB->delete_records($tablename);
$transaction = $DB->start_delegated_transaction();
$this->assertEquals(0, $DB->count_records($tablename));
$DB->insert_record($tablename, (object)array('course'=>1));
$this->assertEquals(1, $DB->count_records($tablename));
try {
$DB->get_records_sql('s e l e c t');
} catch (moodle_exception $e) {
// This must be ignored and it must not roll back the whole transaction.
}
$DB->insert_record($tablename, (object)array('course'=>2));
$this->assertEquals(2, $DB->count_records($tablename));
$transaction->allow_commit();
$this->assertEquals(2, $DB->count_records($tablename));
$this->assertFalse($DB->is_transaction_started());
// Test error on structure SQL_QUERY_UPDATE.
$DB->delete_records($tablename);
$transaction = $DB->start_delegated_transaction();
$this->assertEquals(0, $DB->count_records($tablename));
$DB->insert_record($tablename, (object)array('course'=>1));
$this->assertEquals(1, $DB->count_records($tablename));
try {
$DB->execute('xxxx');
} catch (moodle_exception $e) {
// This must be ignored and it must not roll back the whole transaction.
}
$DB->insert_record($tablename, (object)array('course'=>2));
$this->assertEquals(2, $DB->count_records($tablename));
$transaction->allow_commit();
$this->assertEquals(2, $DB->count_records($tablename));
$this->assertFalse($DB->is_transaction_started());
// Test error on structure SQL_QUERY_STRUCTURE.
$DB->delete_records($tablename);
$transaction = $DB->start_delegated_transaction();
$this->assertEquals(0, $DB->count_records($tablename));
$DB->insert_record($tablename, (object)array('course'=>1));
$this->assertEquals(1, $DB->count_records($tablename));
try {
$DB->change_database_structure('xxxx');
} catch (moodle_exception $e) {
// This must be ignored and it must not roll back the whole transaction.
}
$DB->insert_record($tablename, (object)array('course'=>2));
$this->assertEquals(2, $DB->count_records($tablename));
$transaction->allow_commit();
$this->assertEquals(2, $DB->count_records($tablename));
$this->assertFalse($DB->is_transaction_started());
// NOTE: SQL_QUERY_STRUCTURE is intentionally not tested here because it should never fail.
}
public function test_onelevel_rollback() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
// This might in fact encourage ppl to migrate from myisam to innodb.
$transaction = $DB->start_delegated_transaction();
$data = (object)array('course'=>3);
$this->assertEquals(0, $DB->count_records($tablename));
$DB->insert_record($tablename, $data);
$this->assertEquals(1, $DB->count_records($tablename));
try {
$transaction->rollback(new Exception('test'));
$this->fail('transaction rollback must rethrow exception');
} catch (Exception $e) {
// Ignored.
}
$this->assertEquals(0, $DB->count_records($tablename));
}
public function test_nested_transactions() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
// Two level commit.
$this->assertFalse($DB->is_transaction_started());
$transaction1 = $DB->start_delegated_transaction();
$this->assertTrue($DB->is_transaction_started());
$data = (object)array('course'=>3);
$DB->insert_record($tablename, $data);
$transaction2 = $DB->start_delegated_transaction();
$data = (object)array('course'=>4);
$DB->insert_record($tablename, $data);
$transaction2->allow_commit();
$this->assertTrue($DB->is_transaction_started());
$transaction1->allow_commit();
$this->assertFalse($DB->is_transaction_started());
$this->assertEquals(2, $DB->count_records($tablename));
$DB->delete_records($tablename);
// Rollback from top level.
$transaction1 = $DB->start_delegated_transaction();
$data = (object)array('course'=>3);
$DB->insert_record($tablename, $data);
$transaction2 = $DB->start_delegated_transaction();
$data = (object)array('course'=>4);
$DB->insert_record($tablename, $data);
$transaction2->allow_commit();
try {
$transaction1->rollback(new Exception('test'));
$this->fail('transaction rollback must rethrow exception');
} catch (Exception $e) {
$this->assertEquals(get_class($e), 'Exception');
}
$this->assertEquals(0, $DB->count_records($tablename));
$DB->delete_records($tablename);
// Rollback from nested level.
$transaction1 = $DB->start_delegated_transaction();
$data = (object)array('course'=>3);
$DB->insert_record($tablename, $data);
$transaction2 = $DB->start_delegated_transaction();
$data = (object)array('course'=>4);
$DB->insert_record($tablename, $data);
try {
$transaction2->rollback(new Exception('test'));
$this->fail('transaction rollback must rethrow exception');
} catch (Exception $e) {
$this->assertEquals(get_class($e), 'Exception');
}
$this->assertEquals(2, $DB->count_records($tablename)); // Not rolled back yet.
try {
$transaction1->allow_commit();
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_transaction_exception', $e);
}
$this->assertEquals(2, $DB->count_records($tablename)); // Not rolled back yet.
// The forced rollback is done from the default_exception handler and similar places,
// let's do it manually here.
$this->assertTrue($DB->is_transaction_started());
$DB->force_transaction_rollback();
$this->assertFalse($DB->is_transaction_started());
$this->assertEquals(0, $DB->count_records($tablename)); // Finally rolled back.
$DB->delete_records($tablename);
// Test interactions of recordset and transactions - this causes problems in SQL Server.
$table2 = $this->get_test_table('2');
$tablename2 = $table2->getName();
$table2->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table2->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table2->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table2);
$DB->insert_record($tablename, array('course'=>1));
$DB->insert_record($tablename, array('course'=>2));
$DB->insert_record($tablename, array('course'=>3));
$DB->insert_record($tablename2, array('course'=>5));
$DB->insert_record($tablename2, array('course'=>6));
$DB->insert_record($tablename2, array('course'=>7));
$DB->insert_record($tablename2, array('course'=>8));
$rs1 = $DB->get_recordset($tablename);
$i = 0;
foreach ($rs1 as $record1) {
$i++;
$rs2 = $DB->get_recordset($tablename2);
$j = 0;
foreach ($rs2 as $record2) {
$t = $DB->start_delegated_transaction();
$DB->set_field($tablename, 'course', $record1->course+1, array('id'=>$record1->id));
$DB->set_field($tablename2, 'course', $record2->course+1, array('id'=>$record2->id));
$t->allow_commit();
$j++;
}
$rs2->close();
$this->assertEquals(4, $j);
}
$rs1->close();
$this->assertEquals(3, $i);
// Test nested recordsets isolation without transaction.
$DB->delete_records($tablename);
$DB->insert_record($tablename, array('course'=>1));
$DB->insert_record($tablename, array('course'=>2));
$DB->insert_record($tablename, array('course'=>3));
$DB->delete_records($tablename2);
$DB->insert_record($tablename2, array('course'=>5));
$DB->insert_record($tablename2, array('course'=>6));
$DB->insert_record($tablename2, array('course'=>7));
$DB->insert_record($tablename2, array('course'=>8));
$rs1 = $DB->get_recordset($tablename);
$i = 0;
foreach ($rs1 as $record1) {
$i++;
$rs2 = $DB->get_recordset($tablename2);
$j = 0;
foreach ($rs2 as $record2) {
$DB->set_field($tablename, 'course', $record1->course+1, array('id'=>$record1->id));
$DB->set_field($tablename2, 'course', $record2->course+1, array('id'=>$record2->id));
$j++;
}
$rs2->close();
$this->assertEquals(4, $j);
}
$rs1->close();
$this->assertEquals(3, $i);
}
public function test_transactions_forbidden() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->transactions_forbidden();
$transaction = $DB->start_delegated_transaction();
$data = (object)array('course'=>1);
$DB->insert_record($tablename, $data);
try {
$DB->transactions_forbidden();
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_transaction_exception', $e);
}
// The previous test does not force rollback.
$transaction->allow_commit();
$this->assertFalse($DB->is_transaction_started());
$this->assertEquals(1, $DB->count_records($tablename));
}
public function test_wrong_transactions() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
// Wrong order of nested commits.
$transaction1 = $DB->start_delegated_transaction();
$data = (object)array('course'=>3);
$DB->insert_record($tablename, $data);
$transaction2 = $DB->start_delegated_transaction();
$data = (object)array('course'=>4);
$DB->insert_record($tablename, $data);
try {
$transaction1->allow_commit();
$this->fail('wrong order of commits must throw exception');
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_transaction_exception', $e);
}
try {
$transaction2->allow_commit();
$this->fail('first wrong commit forces rollback');
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_transaction_exception', $e);
}
// This is done in default exception handler usually.
$this->assertTrue($DB->is_transaction_started());
$this->assertEquals(2, $DB->count_records($tablename)); // Not rolled back yet.
$DB->force_transaction_rollback();
$this->assertEquals(0, $DB->count_records($tablename));
$DB->delete_records($tablename);
// Wrong order of nested rollbacks.
$transaction1 = $DB->start_delegated_transaction();
$data = (object)array('course'=>3);
$DB->insert_record($tablename, $data);
$transaction2 = $DB->start_delegated_transaction();
$data = (object)array('course'=>4);
$DB->insert_record($tablename, $data);
try {
// This first rollback should prevent all other rollbacks.
$transaction1->rollback(new Exception('test'));
} catch (Exception $e) {
$this->assertEquals(get_class($e), 'Exception');
}
try {
$transaction2->rollback(new Exception('test'));
} catch (Exception $e) {
$this->assertEquals(get_class($e), 'Exception');
}
try {
$transaction1->rollback(new Exception('test'));
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_transaction_exception', $e);
}
// This is done in default exception handler usually.
$this->assertTrue($DB->is_transaction_started());
$DB->force_transaction_rollback();
$DB->delete_records($tablename);
// Unknown transaction object.
$transaction1 = $DB->start_delegated_transaction();
$data = (object)array('course'=>3);
$DB->insert_record($tablename, $data);
$transaction2 = new moodle_transaction($DB);
try {
$transaction2->allow_commit();
$this->fail('foreign transaction must fail');
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_transaction_exception', $e);
}
try {
$transaction1->allow_commit();
$this->fail('first wrong commit forces rollback');
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_transaction_exception', $e);
}
$DB->force_transaction_rollback();
$DB->delete_records($tablename);
}
public function test_concurent_transactions() {
// Notes about this test:
// 1- MySQL needs to use one engine with transactions support (InnoDB).
// 2- MSSQL needs to have enabled versioning for read committed
// transactions (ALTER DATABASE xxx SET READ_COMMITTED_SNAPSHOT ON)
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$transaction = $DB->start_delegated_transaction();
$data = (object)array('course'=>1);
$this->assertEquals(0, $DB->count_records($tablename));
$DB->insert_record($tablename, $data);
$this->assertEquals(1, $DB->count_records($tablename));
// Open second connection.
$cfg = $DB->export_dbconfig();
if (!isset($cfg->dboptions)) {
$cfg->dboptions = array();
}
$DB2 = moodle_database::get_driver_instance($cfg->dbtype, $cfg->dblibrary);
$DB2->connect($cfg->dbhost, $cfg->dbuser, $cfg->dbpass, $cfg->dbname, $cfg->prefix, $cfg->dboptions);
// Second instance should not see pending inserts.
$this->assertEquals(0, $DB2->count_records($tablename));
$data = (object)array('course'=>2);
$DB2->insert_record($tablename, $data);
$this->assertEquals(1, $DB2->count_records($tablename));
// First should see the changes done from second.
$this->assertEquals(2, $DB->count_records($tablename));
// Now commit and we should see it finally in second connections.
$transaction->allow_commit();
$this->assertEquals(2, $DB2->count_records($tablename));
// Let's try delete all is also working on (this checks MDL-29198).
// Initially both connections see all the records in the table (2).
$this->assertEquals(2, $DB->count_records($tablename));
$this->assertEquals(2, $DB2->count_records($tablename));
$transaction = $DB->start_delegated_transaction();
// Delete all from within transaction.
$DB->delete_records($tablename);
// Transactional $DB, sees 0 records now.
$this->assertEquals(0, $DB->count_records($tablename));
// Others ($DB2) get no changes yet.
$this->assertEquals(2, $DB2->count_records($tablename));
// Now commit and we should see changes.
$transaction->allow_commit();
$this->assertEquals(0, $DB2->count_records($tablename));
$DB2->dispose();
}
public function test_session_locks() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
// Open second connection.
$cfg = $DB->export_dbconfig();
if (!isset($cfg->dboptions)) {
$cfg->dboptions = array();
}
$DB2 = moodle_database::get_driver_instance($cfg->dbtype, $cfg->dblibrary);
$DB2->connect($cfg->dbhost, $cfg->dbuser, $cfg->dbpass, $cfg->dbname, $cfg->prefix, $cfg->dboptions);
// Testing that acquiring a lock effectively locks.
// Get a session lock on connection1.
$rowid = rand(100, 200);
$timeout = 1;
$DB->get_session_lock($rowid, $timeout);
// Try to get the same session lock on connection2.
try {
$DB2->get_session_lock($rowid, $timeout);
$DB2->release_session_lock($rowid); // Should not be executed, but here for safety.
$this->fail('An Exception is missing, expected due to session lock acquired.');
} catch (moodle_exception $e) {
$this->assertInstanceOf('dml_sessionwait_exception', $e);
$DB->release_session_lock($rowid); // Release lock on connection1.
}
// Testing that releasing a lock effectively frees.
// Get a session lock on connection1.
$rowid = rand(100, 200);
$timeout = 1;
$DB->get_session_lock($rowid, $timeout);
// Release the lock on connection1.
$DB->release_session_lock($rowid);
// Get the just released lock on connection2.
$DB2->get_session_lock($rowid, $timeout);
// Release the lock on connection2.
$DB2->release_session_lock($rowid);
$DB2->dispose();
}
public function test_bound_param_types() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_field('content', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => '1', 'content'=>'xx')));
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => 2, 'content'=>'yy')));
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'somestring', 'content'=>'zz')));
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'aa', 'content'=>'1')));
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'bb', 'content'=>2)));
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'cc', 'content'=>'sometext')));
// Conditions in CHAR columns.
$this->assertTrue($DB->record_exists($tablename, array('name'=>1)));
$this->assertTrue($DB->record_exists($tablename, array('name'=>'1')));
$this->assertFalse($DB->record_exists($tablename, array('name'=>111)));
$this->assertNotEmpty($DB->get_record($tablename, array('name'=>1)));
$this->assertNotEmpty($DB->get_record($tablename, array('name'=>'1')));
$this->assertEmpty($DB->get_record($tablename, array('name'=>111)));
$sqlqm = "SELECT *
FROM {{$tablename}}
WHERE name = ?";
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, array(1)));
$this->assertCount(1, $records);
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, array('1')));
$this->assertCount(1, $records);
$records = $DB->get_records_sql($sqlqm, array(222));
$this->assertCount(0, $records);
$sqlnamed = "SELECT *
FROM {{$tablename}}
WHERE name = :name";
$this->assertNotEmpty($records = $DB->get_records_sql($sqlnamed, array('name' => 2)));
$this->assertCount(1, $records);
$this->assertNotEmpty($records = $DB->get_records_sql($sqlnamed, array('name' => '2')));
$this->assertCount(1, $records);
// Conditions in TEXT columns always must be performed with the sql_compare_text
// helper function on both sides of the condition.
$sqlqm = "SELECT *
FROM {{$tablename}}
WHERE " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text('?');
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, array('1')));
$this->assertCount(1, $records);
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, array(1)));
$this->assertCount(1, $records);
$sqlnamed = "SELECT *
FROM {{$tablename}}
WHERE " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':content');
$this->assertNotEmpty($records = $DB->get_records_sql($sqlnamed, array('content' => 2)));
$this->assertCount(1, $records);
$this->assertNotEmpty($records = $DB->get_records_sql($sqlnamed, array('content' => '2')));
$this->assertCount(1, $records);
}
public function test_bound_param_reserved() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => '1'));
// Make sure reserved words do not cause fatal problems in query parameters.
$DB->execute("UPDATE {{$tablename}} SET course = 1 WHERE id = :select", array('select'=>1));
$DB->get_records_sql("SELECT * FROM {{$tablename}} WHERE course = :select", array('select'=>1));
$rs = $DB->get_recordset_sql("SELECT * FROM {{$tablename}} WHERE course = :select", array('select'=>1));
$rs->close();
$DB->get_fieldset_sql("SELECT id FROM {{$tablename}} WHERE course = :select", array('select'=>1));
$DB->set_field_select($tablename, 'course', '1', "id = :select", array('select'=>1));
$DB->delete_records_select($tablename, "id = :select", array('select'=>1));
// If we get here test passed ok.
$this->assertTrue(true);
}
public function test_limits_and_offsets() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_field('content', XMLDB_TYPE_TEXT, 'big', null, XMLDB_NOTNULL);
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'a', 'content'=>'one')));
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'b', 'content'=>'two')));
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'c', 'content'=>'three')));
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'd', 'content'=>'four')));
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'e', 'content'=>'five')));
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'f', 'content'=>'six')));
$sqlqm = "SELECT *
FROM {{$tablename}}";
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 4));
$this->assertCount(2, $records);
$this->assertSame('e', reset($records)->name);
$this->assertSame('f', end($records)->name);
$sqlqm = "SELECT *
FROM {{$tablename}}";
$this->assertEmpty($records = $DB->get_records_sql($sqlqm, null, 8));
$sqlqm = "SELECT *
FROM {{$tablename}}";
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 4));
$this->assertCount(4, $records);
$this->assertSame('a', reset($records)->name);
$this->assertSame('d', end($records)->name);
$sqlqm = "SELECT *
FROM {{$tablename}}";
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 8));
$this->assertCount(6, $records);
$this->assertSame('a', reset($records)->name);
$this->assertSame('f', end($records)->name);
$sqlqm = "SELECT *
FROM {{$tablename}}";
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 1, 4));
$this->assertCount(4, $records);
$this->assertSame('b', reset($records)->name);
$this->assertSame('e', end($records)->name);
$sqlqm = "SELECT *
FROM {{$tablename}}";
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 4, 4));
$this->assertCount(2, $records);
$this->assertSame('e', reset($records)->name);
$this->assertSame('f', end($records)->name);
$sqlqm = "SELECT t.*, t.name AS test
FROM {{$tablename}} t
ORDER BY t.id ASC";
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 4, 4));
$this->assertCount(2, $records);
$this->assertSame('e', reset($records)->name);
$this->assertSame('f', end($records)->name);
$sqlqm = "SELECT DISTINCT t.name, t.name AS test
FROM {{$tablename}} t
ORDER BY t.name DESC";
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 4, 4));
$this->assertCount(2, $records);
$this->assertSame('b', reset($records)->name);
$this->assertSame('a', end($records)->name);
$sqlqm = "SELECT 1
FROM {{$tablename}} t
WHERE t.name = 'a'";
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 1));
$this->assertCount(1, $records);
$sqlqm = "SELECT 'constant'
FROM {{$tablename}} t
WHERE t.name = 'a'";
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 8));
$this->assertCount(1, $records);
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'a', 'content'=>'one')));
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'b', 'content'=>'two')));
$this->assertNotEmpty($DB->insert_record($tablename, array('name' => 'c', 'content'=>'three')));
$sqlqm = "SELECT t.name, COUNT(DISTINCT t2.id) AS count, 'Test' AS teststring
FROM {{$tablename}} t
LEFT JOIN (
SELECT t.id, t.name
FROM {{$tablename}} t
) t2 ON t2.name = t.name
GROUP BY t.name
ORDER BY t.name ASC";
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm));
$this->assertCount(6, $records); // a,b,c,d,e,f.
$this->assertEquals(2, reset($records)->count); // a has 2 records now.
$this->assertEquals(1, end($records)->count); // f has 1 record still.
$this->assertNotEmpty($records = $DB->get_records_sql($sqlqm, null, 0, 2));
$this->assertCount(2, $records);
$this->assertEquals(2, reset($records)->count);
$this->assertEquals(2, end($records)->count);
}
/**
* Test debugging messages about invalid limit number values.
*/
public function test_invalid_limits_debugging() {
$DB = $this->tdb;
$dbman = $DB->get_manager();
// Setup test data.
$table = $this->get_test_table();
$tablename = $table->getName();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$DB->insert_record($tablename, array('course' => '1'));
// Verify that get_records_sql throws debug notices with invalid limit params.
$DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 'invalid');
$this->assertDebuggingCalled("Non-numeric limitfrom parameter detected: 'invalid', did you pass the correct arguments?");
$DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 1, 'invalid');
$this->assertDebuggingCalled("Non-numeric limitnum parameter detected: 'invalid', did you pass the correct arguments?");
// Verify that get_recordset_sql throws debug notices with invalid limit params.
$rs = $DB->get_recordset_sql("SELECT * FROM {{$tablename}}", null, 'invalid');
$this->assertDebuggingCalled("Non-numeric limitfrom parameter detected: 'invalid', did you pass the correct arguments?");
$rs->close();
$rs = $DB->get_recordset_sql("SELECT * FROM {{$tablename}}", null, 1, 'invalid');
$this->assertDebuggingCalled("Non-numeric limitnum parameter detected: 'invalid', did you pass the correct arguments?");
$rs->close();
// Verify that some edge cases do no create debugging messages.
// String form of integer values.
$DB->get_records_sql("SELECT * FROM {{$tablename}}", null, '1');
$this->assertDebuggingNotCalled();
$DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 1, '2');
$this->assertDebuggingNotCalled();
// Empty strings.
$DB->get_records_sql("SELECT * FROM {{$tablename}}", null, '');
$this->assertDebuggingNotCalled();
$DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 1, '');
$this->assertDebuggingNotCalled();
// Null values.
$DB->get_records_sql("SELECT * FROM {{$tablename}}", null, null);
$this->assertDebuggingNotCalled();
$DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 1, null);
$this->assertDebuggingNotCalled();
// Verify that empty arrays DO create debugging mesages.
$DB->get_records_sql("SELECT * FROM {{$tablename}}", null, array());
$this->assertDebuggingCalled("Non-numeric limitfrom parameter detected: array (\n), did you pass the correct arguments?");
$DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 1, array());
$this->assertDebuggingCalled("Non-numeric limitnum parameter detected: array (\n), did you pass the correct arguments?");
// Verify Negative number handling:
// -1 is explicitly treated as 0 for historical reasons.
$DB->get_records_sql("SELECT * FROM {{$tablename}}", null, -1);
$this->assertDebuggingNotCalled();
$DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 1, -1);
$this->assertDebuggingNotCalled();
// Any other negative values should throw debugging messages.
$DB->get_records_sql("SELECT * FROM {{$tablename}}", null, -2);
$this->assertDebuggingCalled("Negative limitfrom parameter detected: -2, did you pass the correct arguments?");
$DB->get_records_sql("SELECT * FROM {{$tablename}}", null, 1, -2);
$this->assertDebuggingCalled("Negative limitnum parameter detected: -2, did you pass the correct arguments?");
}
public function test_queries_counter() {
$DB = $this->tdb;
$dbman = $this->tdb->get_manager();
// Test database.
$table = $this->get_test_table();
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('fieldvalue', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$tablename = $table->getName();
// Initial counters values.
$initreads = $DB->perf_get_reads();
$initwrites = $DB->perf_get_writes();
$previousqueriestime = $DB->perf_get_queries_time();
// Selects counts as reads.
// The get_records_sql() method generates only 1 db query.
$whatever = $DB->get_records_sql("SELECT * FROM {{$tablename}}");
$this->assertEquals($initreads + 1, $DB->perf_get_reads());
// The get_records() method generates 2 queries the first time is called
// as it is fetching the table structure.
$whatever = $DB->get_records($tablename);
$this->assertEquals($initreads + 3, $DB->perf_get_reads());
$this->assertEquals($initwrites, $DB->perf_get_writes());
// The elapsed time is counted.
$lastqueriestime = $DB->perf_get_queries_time();
$this->assertGreaterThanOrEqual($previousqueriestime, $lastqueriestime);
$previousqueriestime = $lastqueriestime;
// Only 1 now, it already fetched the table columns.
$whatever = $DB->get_records($tablename);
$this->assertEquals($initreads + 4, $DB->perf_get_reads());
// And only 1 more from now.
$whatever = $DB->get_records($tablename);
$this->assertEquals($initreads + 5, $DB->perf_get_reads());
// Inserts counts as writes.
$rec1 = new stdClass();
$rec1->fieldvalue = 11;
$rec1->id = $DB->insert_record($tablename, $rec1);
$this->assertEquals($initwrites + 1, $DB->perf_get_writes());
$this->assertEquals($initreads + 5, $DB->perf_get_reads());
// The elapsed time is counted.
$lastqueriestime = $DB->perf_get_queries_time();
$this->assertGreaterThanOrEqual($previousqueriestime, $lastqueriestime);
$previousqueriestime = $lastqueriestime;
$rec2 = new stdClass();
$rec2->fieldvalue = 22;
$rec2->id = $DB->insert_record($tablename, $rec2);
$this->assertEquals($initwrites + 2, $DB->perf_get_writes());
// Updates counts as writes.
$rec1->fieldvalue = 111;
$DB->update_record($tablename, $rec1);
$this->assertEquals($initwrites + 3, $DB->perf_get_writes());
$this->assertEquals($initreads + 5, $DB->perf_get_reads());
// The elapsed time is counted.
$lastqueriestime = $DB->perf_get_queries_time();
$this->assertGreaterThanOrEqual($previousqueriestime, $lastqueriestime);
$previousqueriestime = $lastqueriestime;
// Sum of them.
$totaldbqueries = $DB->perf_get_reads() + $DB->perf_get_writes();
$this->assertEquals($totaldbqueries, $DB->perf_get_queries());
}
public function test_sql_intersect() {
$DB = $this->tdb;
$dbman = $this->tdb->get_manager();
$tables = array();
for ($i = 0; $i < 3; $i++) {
$table = $this->get_test_table('i'.$i);
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
$table->add_field('ival', XMLDB_TYPE_INTEGER, '10', null, null, null, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, null, null, '0');
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
$dbman->create_table($table);
$tables[$i] = $table;
}
$DB->insert_record($tables[0]->getName(), array('ival' => 1, 'name' => 'One'), false);
$DB->insert_record($tables[0]->getName(), array('ival' => 2, 'name' => 'Two'), false);
$DB->insert_record($tables[0]->getName(), array('ival' => 3, 'name' => 'Three'), false);
$DB->insert_record($tables[0]->getName(), array('ival' => 4, 'name' => 'Four'), false);
$DB->insert_record($tables[1]->getName(), array('ival' => 1, 'name' => 'One'), false);
$DB->insert_record($tables[1]->getName(), array('ival' => 2, 'name' => 'Two'), false);
$DB->insert_record($tables[1]->getName(), array('ival' => 3, 'name' => 'Three'), false);
$DB->insert_record($tables[2]->getName(), array('ival' => 1, 'name' => 'One'), false);
$DB->insert_record($tables[2]->getName(), array('ival' => 2, 'name' => 'Two'), false);
$DB->insert_record($tables[2]->getName(), array('ival' => 5, 'name' => 'Five'), false);
// Intersection on the int column.
$params = array('excludename' => 'Two');
$sql1 = 'SELECT ival FROM {'.$tables[0]->getName().'}';
$sql2 = 'SELECT ival FROM {'.$tables[1]->getName().'} WHERE name <> :excludename';
$sql3 = 'SELECT ival FROM {'.$tables[2]->getName().'}';
$sql = $DB->sql_intersect(array($sql1), 'ival') . ' ORDER BY ival';
$this->assertEquals(array(1, 2, 3, 4), $DB->get_fieldset_sql($sql, $params));
$sql = $DB->sql_intersect(array($sql1, $sql2), 'ival') . ' ORDER BY ival';
$this->assertEquals(array(1, 3), $DB->get_fieldset_sql($sql, $params));
$sql = $DB->sql_intersect(array($sql1, $sql2, $sql3), 'ival') . ' ORDER BY ival';
$this->assertEquals(array(1),
$DB->get_fieldset_sql($sql, $params));
// Intersection on the char column.
$params = array('excludeival' => 2);
$sql1 = 'SELECT name FROM {'.$tables[0]->getName().'}';
$sql2 = 'SELECT name FROM {'.$tables[1]->getName().'} WHERE ival <> :excludeival';
$sql3 = 'SELECT name FROM {'.$tables[2]->getName().'}';
$sql = $DB->sql_intersect(array($sql1), 'name') . ' ORDER BY name';
$this->assertEquals(array('Four', 'One', 'Three', 'Two'), $DB->get_fieldset_sql($sql, $params));
$sql = $DB->sql_intersect(array($sql1, $sql2), 'name') . ' ORDER BY name';
$this->assertEquals(array('One', 'Three'), $DB->get_fieldset_sql($sql, $params));
$sql = $DB->sql_intersect(array($sql1, $sql2, $sql3), 'name') . ' ORDER BY name';
$this->assertEquals(array('One'), $DB->get_fieldset_sql($sql, $params));
// Intersection on the several columns.
$params = array('excludename' => 'Two');
$sql1 = 'SELECT ival, name FROM {'.$tables[0]->getName().'}';
$sql2 = 'SELECT ival, name FROM {'.$tables[1]->getName().'} WHERE name <> :excludename';
$sql3 = 'SELECT ival, name FROM {'.$tables[2]->getName().'}';
$sql = $DB->sql_intersect(array($sql1), 'ival, name') . ' ORDER BY ival';
$this->assertEquals(array(1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four'),
$DB->get_records_sql_menu($sql, $params));
$sql = $DB->sql_intersect(array($sql1, $sql2), 'ival, name') . ' ORDER BY ival';
$this->assertEquals(array(1 => 'One', 3 => 'Three'),
$DB->get_records_sql_menu($sql, $params));
$sql = $DB->sql_intersect(array($sql1, $sql2, $sql3), 'ival, name') . ' ORDER BY ival';
$this->assertEquals(array(1 => 'One'),
$DB->get_records_sql_menu($sql, $params));
// Drop temporary tables.
foreach ($tables as $table) {
$dbman->drop_table($table);
}
}
}
/**
* This class is not a proper subclass of moodle_database. It is
* intended to be used only in unit tests, in order to gain access to the
* protected methods of moodle_database, and unit test them.
*/
class moodle_database_for_testing extends moodle_database {
protected $prefix = 'mdl_';
public function public_fix_table_names($sql) {
return $this->fix_table_names($sql);
}
public function driver_installed() {}
public function get_dbfamily() {}
protected function get_dbtype() {}
protected function get_dblibrary() {}
public function get_name() {}
public function get_configuration_help() {}
public function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {}
public function get_server_info() {}
protected function allowed_param_types() {}
public function get_last_error() {}
public function get_tables($usecache=true) {}
public function get_indexes($table) {}
public function get_columns($table, $usecache=true) {}
protected function normalise_value($column, $value) {}
public function set_debug($state) {}
public function get_debug() {}
public function change_database_structure($sql) {}
public function execute($sql, array $params=null) {}
public function get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {}
public function get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0) {}
public function get_fieldset_sql($sql, array $params=null) {}
public function insert_record_raw($table, $params, $returnid=true, $bulk=false, $customsequence=false) {}
public function insert_record($table, $dataobject, $returnid=true, $bulk=false) {}
public function import_record($table, $dataobject) {}
public function update_record_raw($table, $params, $bulk=false) {}
public function update_record($table, $dataobject, $bulk=false) {}
public function set_field_select($table, $newfield, $newvalue, $select, array $params=null) {}
public function delete_records_select($table, $select, array $params=null) {}
public function sql_concat() {}
public function sql_concat_join($separator="' '", $elements=array()) {}
public function sql_substr($expr, $start, $length=false) {}
public function begin_transaction() {}
public function commit_transaction() {}
public function rollback_transaction() {}
}
/**
* Dumb test class with toString() returning 1.
*/
class dml_test_object_one {
public function __toString() {
return 1;
}
}
| gpl-3.0 |
Jackkal/jpexs-decompiler | libsrc/ffdec_lib/src/com/jpexs/decompiler/flash/exporters/MorphShapeExporter.java | 6261 | /*
* Copyright (C) 2010-2015 JPEXS, All rights reserved.
*
* 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 3.0 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.
*/
package com.jpexs.decompiler.flash.exporters;
import com.jpexs.decompiler.flash.AbortRetryIgnoreHandler;
import com.jpexs.decompiler.flash.EventListener;
import com.jpexs.decompiler.flash.RetryTask;
import com.jpexs.decompiler.flash.SWF;
import com.jpexs.decompiler.flash.exporters.commonshape.ExportRectangle;
import com.jpexs.decompiler.flash.exporters.commonshape.SVGExporter;
import com.jpexs.decompiler.flash.exporters.modes.MorphShapeExportMode;
import com.jpexs.decompiler.flash.exporters.morphshape.CanvasMorphShapeExporter;
import com.jpexs.decompiler.flash.exporters.settings.MorphShapeExportSettings;
import com.jpexs.decompiler.flash.tags.DefineMorphShapeTag;
import com.jpexs.decompiler.flash.tags.Tag;
import com.jpexs.decompiler.flash.tags.base.CharacterTag;
import com.jpexs.decompiler.flash.tags.base.MorphShapeTag;
import com.jpexs.decompiler.flash.types.CXFORMWITHALPHA;
import com.jpexs.helpers.Helper;
import com.jpexs.helpers.Path;
import com.jpexs.helpers.utf8.Utf8Helper;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
*
* @author JPEXS
*/
public class MorphShapeExporter {
//TODO: implement morphshape export. How to handle 65536 frames?
public List<File> exportMorphShapes(AbortRetryIgnoreHandler handler, final String outdir, List<Tag> tags, final MorphShapeExportSettings settings, EventListener evl) throws IOException, InterruptedException {
List<File> ret = new ArrayList<>();
if (tags.isEmpty()) {
return ret;
}
File foutdir = new File(outdir);
Path.createDirectorySafe(foutdir);
int count = 0;
for (Tag t : tags) {
if (t instanceof MorphShapeTag) {
count++;
}
}
if (count == 0) {
return ret;
}
int currentIndex = 1;
for (final Tag t : tags) {
if (t instanceof MorphShapeTag) {
if (evl != null) {
evl.handleExportingEvent("morphshape", currentIndex, count, t.getName());
}
int characterID = 0;
if (t instanceof CharacterTag) {
characterID = ((CharacterTag) t).getCharacterId();
}
String ext = settings.mode == MorphShapeExportMode.CANVAS ? "html" : "svg";
final File file = new File(outdir + File.separator + characterID + "." + ext);
new RetryTask(() -> {
MorphShapeTag mst = (MorphShapeTag) t;
switch (settings.mode) {
case SVG:
try (OutputStream fos = new BufferedOutputStream(new FileOutputStream(file))) {
ExportRectangle rect = new ExportRectangle(mst.getRect());
rect.xMax *= settings.zoom;
rect.yMax *= settings.zoom;
rect.xMin *= settings.zoom;
rect.yMin *= settings.zoom;
SVGExporter exporter = new SVGExporter(rect);
mst.toSVG(exporter, -2, new CXFORMWITHALPHA(), 0, settings.zoom);
fos.write(Utf8Helper.getBytes(exporter.getSVG()));
}
break;
case CANVAS:
try (OutputStream fos = new BufferedOutputStream(new FileOutputStream(file))) {
int deltaX = -Math.min(mst.getStartBounds().Xmin, mst.getEndBounds().Xmin);
int deltaY = -Math.min(mst.getStartBounds().Ymin, mst.getEndBounds().Ymin);
CanvasMorphShapeExporter cse = new CanvasMorphShapeExporter(((Tag) mst).getSwf(), mst.getShapeAtRatio(0), mst.getShapeAtRatio(DefineMorphShapeTag.MAX_RATIO), new CXFORMWITHALPHA(), SWF.unitDivisor, deltaX, deltaY);
cse.export();
Set<Integer> needed = new HashSet<>();
CharacterTag ct = ((CharacterTag) mst);
needed.add(ct.getCharacterId());
ct.getNeededCharactersDeep(needed);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
SWF.writeLibrary(ct.getSwf(), needed, baos);
fos.write(Utf8Helper.getBytes(cse.getHtml(new String(baos.toByteArray(), Utf8Helper.charset), SWF.getTypePrefix(mst) + mst.getCharacterId(), mst.getRect())));
}
break;
}
}, handler).run();
ret.add(file);
if (evl != null) {
evl.handleExportedEvent("morphshape", currentIndex, count, t.getName());
}
currentIndex++;
}
}
if (settings.mode == MorphShapeExportMode.CANVAS) {
File fcanvas = new File(foutdir + File.separator + "canvas.js");
Helper.saveStream(SWF.class.getClassLoader().getResourceAsStream("com/jpexs/helpers/resource/canvas.js"), fcanvas);
ret.add(fcanvas);
}
return ret;
}
}
| gpl-3.0 |
vuchannguyen/web | mod/lesson/pagetypes/shortanswer.php | 15979 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Short answer
*
* @package mod
* @subpackage lesson
* @copyright 2009 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
**/
defined('MOODLE_INTERNAL') || die();
/** Short answer question type */
define("LESSON_PAGE_SHORTANSWER", "1");
class lesson_page_type_shortanswer extends lesson_page {
protected $type = lesson_page::TYPE_QUESTION;
protected $typeidstring = 'shortanswer';
protected $typeid = LESSON_PAGE_SHORTANSWER;
protected $string = null;
public function get_typeid() {
return $this->typeid;
}
public function get_typestring() {
if ($this->string===null) {
$this->string = get_string($this->typeidstring, 'lesson');
}
return $this->string;
}
public function get_idstring() {
return $this->typeidstring;
}
public function display($renderer, $attempt) {
global $USER, $CFG, $PAGE;
$mform = new lesson_display_answer_form_shortanswer($CFG->wwwroot.'/mod/lesson/continue.php', array('contents'=>$this->get_contents()));
$data = new stdClass;
$data->id = $PAGE->cm->id;
$data->pageid = $this->properties->id;
if (isset($USER->modattempts[$this->lesson->id])) {
$data->answer = s($attempt->useranswer);
}
$mform->set_data($data);
return $mform->display();
}
public function check_answer() {
global $CFG;
$result = parent::check_answer();
$mform = new lesson_display_answer_form_shortanswer($CFG->wwwroot.'/mod/lesson/continue.php', array('contents'=>$this->get_contents()));
$data = $mform->get_data();
require_sesskey();
$studentanswer = trim($data->answer);
if ($studentanswer === '') {
$result->noanswer = true;
return $result;
}
$studentanswer = s($studentanswer);
$i=0;
$answers = $this->get_answers();
foreach ($answers as $answer) {
$i++;
$expectedanswer = $answer->answer; // for easier handling of $answer->answer
$ismatch = false;
$markit = false;
$useregexp = ($this->qoption);
if ($useregexp) { //we are using 'normal analysis', which ignores case
$ignorecase = '';
if (substr($expectedanswer,0,-2) == '/i') {
$expectedanswer = substr($expectedanswer,0,-2);
$ignorecase = 'i';
}
} else {
$expectedanswer = str_replace('*', '#####', $expectedanswer);
$expectedanswer = preg_quote($expectedanswer, '/');
$expectedanswer = str_replace('#####', '.*', $expectedanswer);
}
// see if user typed in any of the correct answers
if ((!$this->lesson->custom && $this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) or ($this->lesson->custom && $answer->score > 0) ) {
if (!$useregexp) { // we are using 'normal analysis', which ignores case
if (preg_match('/^'.$expectedanswer.'$/i',$studentanswer)) {
$ismatch = true;
}
} else {
if (preg_match('/^'.$expectedanswer.'$/'.$ignorecase,$studentanswer)) {
$ismatch = true;
}
}
if ($ismatch == true) {
$result->correctanswer = true;
}
} else {
if (!$useregexp) { //we are using 'normal analysis'
// see if user typed in any of the wrong answers; don't worry about case
if (preg_match('/^'.$expectedanswer.'$/i',$studentanswer)) {
$ismatch = true;
}
} else { // we are using regular expressions analysis
$startcode = substr($expectedanswer,0,2);
switch ($startcode){
//1- check for absence of required string in $studentanswer (coded by initial '--')
case "--":
$expectedanswer = substr($expectedanswer,2);
if (!preg_match('/^'.$expectedanswer.'$/'.$ignorecase,$studentanswer)) {
$ismatch = true;
}
break;
//2- check for code for marking wrong strings (coded by initial '++')
case "++":
$expectedanswer=substr($expectedanswer,2);
$markit = true;
//check for one or several matches
if (preg_match_all('/'.$expectedanswer.'/'.$ignorecase,$studentanswer, $matches)) {
$ismatch = true;
$nb = count($matches[0]);
$original = array();
$marked = array();
$fontStart = '<span class="incorrect matches">';
$fontEnd = '</span>';
for ($i = 0; $i < $nb; $i++) {
array_push($original,$matches[0][$i]);
array_push($marked,$fontStart.$matches[0][$i].$fontEnd);
}
$studentanswer = str_replace($original, $marked, $studentanswer);
}
break;
//3- check for wrong answers belonging neither to -- nor to ++ categories
default:
if (preg_match('/^'.$expectedanswer.'$/'.$ignorecase,$studentanswer, $matches)) {
$ismatch = true;
}
break;
}
$result->correctanswer = false;
}
}
if ($ismatch) {
$result->newpageid = $answer->jumpto;
if (trim(strip_tags($answer->response))) {
$result->response = $answer->response;
}
$result->answerid = $answer->id;
break; // quit answer analysis immediately after a match has been found
}
}
$result->studentanswer = $result->userresponse = $studentanswer;
return $result;
}
public function option_description_string() {
if ($this->properties->qoption) {
return " - ".get_string("casesensitive", "lesson");
}
return parent::option_description_string();
}
public function display_answers(html_table $table) {
$answers = $this->get_answers();
$options = new stdClass;
$options->noclean = true;
$options->para = false;
$i = 1;
foreach ($answers as $answer) {
$cells = array();
if ($this->lesson->custom && $answer->score > 0) {
// if the score is > 0, then it is correct
$cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n";
} else if ($this->lesson->custom) {
$cells[] = '<span class="label">'.get_string("answer", "lesson")." $i</span>: \n";
} else if ($this->lesson->jumpto_is_correct($this->properties->id, $answer->jumpto)) {
// underline correct answers
$cells[] = '<span class="correct">'.get_string("answer", "lesson")." $i</span>: \n";
} else {
$cells[] = '<span class="labelcorrect">'.get_string("answer", "lesson")." $i</span>: \n";
}
$cells[] = format_text($answer->answer, $answer->answerformat, $options);
$table->data[] = new html_table_row($cells);
$cells = array();
$cells[] = "<span class=\"label\">".get_string("response", "lesson")." $i</span>";
$cells[] = format_text($answer->response, $answer->responseformat, $options);
$table->data[] = new html_table_row($cells);
$cells = array();
$cells[] = "<span class=\"label\">".get_string("score", "lesson").'</span>';
$cells[] = $answer->score;
$table->data[] = new html_table_row($cells);
$cells = array();
$cells[] = "<span class=\"label\">".get_string("jump", "lesson").'</span>';
$cells[] = $this->get_jump_name($answer->jumpto);
$table->data[] = new html_table_row($cells);
if ($i === 1){
$table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
}
$i++;
}
return $table;
}
public function stats(array &$pagestats, $tries) {
if(count($tries) > $this->lesson->maxattempts) { // if there are more tries than the max that is allowed, grab the last "legal" attempt
$temp = $tries[$this->lesson->maxattempts - 1];
} else {
// else, user attempted the question less than the max, so grab the last one
$temp = end($tries);
}
if (isset($pagestats[$temp->pageid][$temp->useranswer])) {
$pagestats[$temp->pageid][$temp->useranswer]++;
} else {
$pagestats[$temp->pageid][$temp->useranswer] = 1;
}
if (isset($pagestats[$temp->pageid]["total"])) {
$pagestats[$temp->pageid]["total"]++;
} else {
$pagestats[$temp->pageid]["total"] = 1;
}
return true;
}
public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
$answers = $this->get_answers();
$formattextdefoptions = new stdClass;
$formattextdefoptions->para = false; //I'll use it widely in this page
foreach ($answers as $answer) {
if ($useranswer == null && $i == 0) {
// I have the $i == 0 because it is easier to blast through it all at once.
if (isset($pagestats[$this->properties->id])) {
$stats = $pagestats[$this->properties->id];
$total = $stats["total"];
unset($stats["total"]);
foreach ($stats as $valentered => $ntimes) {
$data = '<input type="text" size="50" disabled="disabled" readonly="readonly" value="'.s($valentered).'" />';
$percent = $ntimes / $total * 100;
$percent = round($percent, 2);
$percent .= "% ".get_string("enteredthis", "lesson");
$answerdata->answers[] = array($data, $percent);
}
} else {
$answerdata->answers[] = array(get_string("nooneansweredthisquestion", "lesson"), " ");
}
$i++;
} else if ($useranswer != null && ($answer->id == $useranswer->answerid || ($answer == end($answers) && empty($answerdata)))) {
// get in here when what the user entered is not one of the answers
$data = '<input type="text" size="50" disabled="disabled" readonly="readonly" value="'.s($useranswer->useranswer).'">';
if (isset($pagestats[$this->properties->id][$useranswer->useranswer])) {
$percent = $pagestats[$this->properties->id][$useranswer->useranswer] / $pagestats[$this->properties->id]["total"] * 100;
$percent = round($percent, 2);
$percent .= "% ".get_string("enteredthis", "lesson");
} else {
$percent = get_string("nooneenteredthis", "lesson");
}
$answerdata->answers[] = array($data, $percent);
if ($answer->id == $useranswer->answerid) {
if ($answer->response == NULL) {
if ($useranswer->correct) {
$answerdata->response = get_string("thatsthecorrectanswer", "lesson");
} else {
$answerdata->response = get_string("thatsthewronganswer", "lesson");
}
} else {
$answerdata->response = $answer->response;
}
if ($this->lesson->custom) {
$answerdata->score = get_string("pointsearned", "lesson").": ".$answer->score;
} elseif ($useranswer->correct) {
$answerdata->score = get_string("receivedcredit", "lesson");
} else {
$answerdata->score = get_string("didnotreceivecredit", "lesson");
}
} else {
$answerdata->response = get_string("thatsthewronganswer", "lesson");
if ($this->lesson->custom) {
$answerdata->score = get_string("pointsearned", "lesson").": 0";
} else {
$answerdata->score = get_string("didnotreceivecredit", "lesson");
}
}
}
$answerpage->answerdata = $answerdata;
}
return $answerpage;
}
}
class lesson_add_page_form_shortanswer extends lesson_add_page_form_base {
public $qtype = 'shortanswer';
public $qtypestring = 'shortanswer';
public function custom_definition() {
$this->_form->addElement('checkbox', 'qoption', get_string('options', 'lesson'), get_string('casesensitive', 'lesson')); //oh my, this is a regex option!
$this->_form->setDefault('qoption', 0);
$this->_form->addHelpButton('qoption', 'casesensitive', 'lesson');
for ($i = 0; $i < $this->_customdata['lesson']->maxanswers; $i++) {
$this->_form->addElement('header', 'answertitle'.$i, get_string('answer').' '.($i+1));
$this->add_answer($i);
$this->add_response($i);
$this->add_jumpto($i, NULL, ($i == 0 ? LESSON_NEXTPAGE : LESSON_THISPAGE));
$this->add_score($i, null, ($i===0)?1:0);
}
}
}
class lesson_display_answer_form_shortanswer extends moodleform {
public function definition() {
global $OUTPUT;
$mform = $this->_form;
$contents = $this->_customdata['contents'];
$mform->addElement('header', 'pageheader', $OUTPUT->box($contents, 'contents'));
$options = new stdClass;
$options->para = false;
$options->noclean = true;
$mform->addElement('hidden', 'id');
$mform->setType('id', PARAM_INT);
$mform->addElement('hidden', 'pageid');
$mform->setType('pageid', PARAM_INT);
$mform->addElement('text', 'answer', get_string('youranswer', 'lesson'), array('size'=>'50', 'maxlength'=>'200'));
$mform->setType('answer', PARAM_TEXT);
$this->add_action_buttons(null, get_string("pleaseenteryouranswerinthebox", "lesson"));
}
}
| gpl-3.0 |
RussianCraft/rcse | node_modules/npm/html/doc/cli/npm-access.html | 5963 | <!doctype html>
<html>
<title>npm-access</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="../../static/style.css">
<link rel="canonical" href="https://www.npmjs.org/doc/cli/npm-access.html">
<script async=true src="../../static/toc.js"></script>
<body>
<div id="wrapper">
<h1><a href="../cli/npm-access.html">npm-access</a></h1> <p>Set access level on published packages</p>
<h2 id="synopsis">SYNOPSIS</h2>
<pre><code>npm access public [<package>]
npm access restricted [<package>]
npm access grant <read-only|read-write> <scope:team> [<package>]
npm access revoke <scope:team> [<package>]
npm access 2fa-required [<package>]
npm access 2fa-not-required [<package>]
npm access ls-packages [<user>|<scope>|<scope:team>]
npm access ls-collaborators [<package> [<user>]]
npm access edit [<package>]</code></pre><h2 id="description">DESCRIPTION</h2>
<p>Used to set access controls on private packages.</p>
<p>For all of the subcommands, <code>npm access</code> will perform actions on the packages
in the current working directory if no package name is passed to the
subcommand.</p>
<ul>
<li><p>public / restricted:
Set a package to be either publicly accessible or restricted.</p>
</li>
<li><p>grant / revoke:
Add or remove the ability of users and teams to have read-only or read-write
access to a package.</p>
</li>
<li><p>2fa-required / 2fa-not-required:
Configure whether a package requires that anyone publishing it have two-factor
authentication enabled on their account.</p>
</li>
<li><p>ls-packages:
Show all of the packages a user or a team is able to access, along with the
access level, except for read-only public packages (it won't print the whole
registry listing)</p>
</li>
<li><p>ls-collaborators:
Show all of the access privileges for a package. Will only show permissions
for packages to which you have at least read access. If <code><user></code> is passed in,
the list is filtered only to teams <em>that</em> user happens to belong to.</p>
</li>
<li><p>edit:
Set the access privileges for a package at once using <code>$EDITOR</code>.</p>
</li>
</ul>
<h2 id="details">DETAILS</h2>
<p><code>npm access</code> always operates directly on the current registry, configurable
from the command line using <code>--registry=<registry url></code>.</p>
<p>Unscoped packages are <em>always public</em>.</p>
<p>Scoped packages <em>default to restricted</em>, but you can either publish them as
public using <code>npm publish --access=public</code>, or set their access as public using
<code>npm access public</code> after the initial publish.</p>
<p>You must have privileges to set the access of a package:</p>
<ul>
<li>You are an owner of an unscoped or scoped package.</li>
<li>You are a member of the team that owns a scope.</li>
<li>You have been given read-write privileges for a package, either as a member
of a team or directly as an owner.</li>
</ul>
<p>If you have two-factor authentication enabled then you'll have to pass in an
otp with <code>--otp</code> when making access changes.</p>
<p>If your account is not paid, then attempts to publish scoped packages will fail
with an HTTP 402 status code (logically enough), unless you use
<code>--access=public</code>.</p>
<p>Management of teams and team memberships is done with the <code>npm team</code> command.</p>
<h2 id="see-also">SEE ALSO</h2>
<ul>
<li><a href="https://npm.im/libnpmaccess"><code>libnpmaccess</code></a></li>
<li><a href="../cli/npm-team.html">npm-team(1)</a></li>
<li><a href="../cli/npm-publish.html">npm-publish(1)</a></li>
<li><a href="../misc/npm-config.html">npm-config(7)</a></li>
<li><a href="../misc/npm-registry.html">npm-registry(7)</a></li>
</ul>
</div>
<table border=0 cellspacing=0 cellpadding=0 id=npmlogo>
<tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18> </td></tr>
<tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td colspan=6 style="width:60px;height:10px;background:#fff"> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td></tr>
<tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2> </td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff" rowspan=2> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff"> </td></tr>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
<p id="footer">npm-access — npm@6.9.0</p>
| gpl-3.0 |
avati/samba | source3/modules/vfs_gpfs.h | 1938 | /*
Unix SMB/CIFS implementation.
Wrap gpfs calls in vfs functions.
Copyright (C) Christian Ambach <cambach1@de.ibm.com> 2006
Major code contributions by Chetan Shringarpure <chetan.sh@in.ibm.com>
and Gomati Mohanan <gomati.mohanan@in.ibm.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef GPFS_GETACL_NATIVE
#define GPFS_GETACL_NATIVE 0x00000004
#endif
bool set_gpfs_sharemode(files_struct *fsp, uint32 access_mask,
uint32 share_access);
int set_gpfs_lease(int fd, int leasetype);
int smbd_gpfs_getacl(char *pathname, int flags, void *acl);
int smbd_gpfs_putacl(char *pathname, int flags, void *acl);
int smbd_gpfs_get_realfilename_path(char *pathname, char *filenamep,
int *buflen);
int smbd_fget_gpfs_winattrs(int fd, struct gpfs_winattr *attrs);
int get_gpfs_winattrs(char * pathname,struct gpfs_winattr *attrs);
int set_gpfs_winattrs(char * pathname,int flags,struct gpfs_winattr *attrs);
int smbd_gpfs_prealloc(int fd, gpfs_off64_t start, gpfs_off64_t bytes);
int smbd_gpfs_ftruncate(int fd, gpfs_off64_t length);
int get_gpfs_quota(const char *pathname, int type, int id,
struct gpfs_quotaInfo *qi);
int get_gpfs_fset_id(const char *pathname, int *fset_id);
void init_gpfs(void);
void smbd_gpfs_lib_init(void);
| gpl-3.0 |
farmer-martin/ardupilot | libraries/AC_PrecLand/AC_PrecLand.cpp | 8721 | #include <AP_HAL/AP_HAL.h>
#include "AC_PrecLand.h"
#include "AC_PrecLand_Backend.h"
#include "AC_PrecLand_Companion.h"
#include "AC_PrecLand_IRLock.h"
#include "AC_PrecLand_SITL_Gazebo.h"
#include "AC_PrecLand_SITL.h"
extern const AP_HAL::HAL& hal;
const AP_Param::GroupInfo AC_PrecLand::var_info[] = {
// @Param: ENABLED
// @DisplayName: Precision Land enabled/disabled and behaviour
// @Description: Precision Land enabled/disabled and behaviour
// @Values: 0:Disabled, 1:Enabled Always Land, 2:Enabled Strict
// @User: Advanced
AP_GROUPINFO_FLAGS("ENABLED", 0, AC_PrecLand, _enabled, 0, AP_PARAM_FLAG_ENABLE),
// @Param: TYPE
// @DisplayName: Precision Land Type
// @Description: Precision Land Type
// @Values: 0:None, 1:CompanionComputer, 2:IRLock, 3:SITL_Gazebo, 4:SITL
// @User: Advanced
AP_GROUPINFO("TYPE", 1, AC_PrecLand, _type, 0),
// @Param: YAW_ALIGN
// @DisplayName: Sensor yaw alignment
// @Description: Yaw angle from body x-axis to sensor x-axis.
// @Range: 0 360
// @Increment: 1
// @User: Advanced
// @Units: Centi-degrees
AP_GROUPINFO("YAW_ALIGN", 2, AC_PrecLand, _yaw_align, 0),
// @Param: LAND_OFS_X
// @DisplayName: Land offset forward
// @Description: Desired landing position of the camera forward of the target in vehicle body frame
// @Range: -20 20
// @Increment: 1
// @User: Advanced
// @Units: Centimeters
AP_GROUPINFO("LAND_OFS_X", 3, AC_PrecLand, _land_ofs_cm_x, 0),
// @Param: LAND_OFS_Y
// @DisplayName: Land offset right
// @Description: desired landing position of the camera right of the target in vehicle body frame
// @Range: -20 20
// @Increment: 1
// @User: Advanced
// @Units: Centimeters
AP_GROUPINFO("LAND_OFS_Y", 4, AC_PrecLand, _land_ofs_cm_y, 0),
// 5 RESERVED for EKF_TYPE
// 6 RESERVED for ACC_NSE
AP_GROUPEND
};
// Default constructor.
// Note that the Vector/Matrix constructors already implicitly zero
// their values.
//
AC_PrecLand::AC_PrecLand(const AP_AHRS& ahrs, const AP_InertialNav& inav) :
_ahrs(ahrs),
_inav(inav),
_last_update_ms(0),
_last_backend_los_meas_ms(0),
_backend(nullptr)
{
// set parameters to defaults
AP_Param::setup_object_defaults(this, var_info);
// other initialisation
_backend_state.healthy = false;
}
// init - perform any required initialisation of backends
void AC_PrecLand::init()
{
// exit immediately if init has already been run
if (_backend != nullptr) {
return;
}
// default health to false
_backend = nullptr;
_backend_state.healthy = false;
// instantiate backend based on type parameter
switch ((enum PrecLandType)(_type.get())) {
// no type defined
case PRECLAND_TYPE_NONE:
default:
return;
// companion computer
case PRECLAND_TYPE_COMPANION:
_backend = new AC_PrecLand_Companion(*this, _backend_state);
break;
// IR Lock
#if CONFIG_HAL_BOARD == HAL_BOARD_PX4 || CONFIG_HAL_BOARD == HAL_BOARD_VRBRAIN
case PRECLAND_TYPE_IRLOCK:
_backend = new AC_PrecLand_IRLock(*this, _backend_state);
break;
#endif
#if CONFIG_HAL_BOARD == HAL_BOARD_SITL
case PRECLAND_TYPE_SITL_GAZEBO:
_backend = new AC_PrecLand_SITL_Gazebo(*this, _backend_state);
break;
case PRECLAND_TYPE_SITL:
_backend = new AC_PrecLand_SITL(*this, _backend_state);
break;
#endif
}
// init backend
if (_backend != nullptr) {
_backend->init();
}
}
// update - give chance to driver to get updates from sensor
void AC_PrecLand::update(float rangefinder_alt_cm, bool rangefinder_alt_valid)
{
_attitude_history.push_back(_ahrs.get_rotation_body_to_ned());
// run backend update
if (_backend != nullptr && _enabled) {
// read from sensor
_backend->update();
Vector3f vehicleVelocityNED = _inav.get_velocity()*0.01f;
vehicleVelocityNED.z = -vehicleVelocityNED.z;
if (target_acquired()) {
// EKF prediction step
float dt;
Vector3f targetDelVel;
_ahrs.getCorrectedDeltaVelocityNED(targetDelVel, dt);
targetDelVel = -targetDelVel;
_ekf_x.predict(dt, targetDelVel.x, 0.5f*dt);
_ekf_y.predict(dt, targetDelVel.y, 0.5f*dt);
}
if (_backend->have_los_meas() && _backend->los_meas_time_ms() != _last_backend_los_meas_ms) {
// we have a new, unique los measurement
_last_backend_los_meas_ms = _backend->los_meas_time_ms();
Vector3f target_vec_unit_body;
_backend->get_los_body(target_vec_unit_body);
// Apply sensor yaw alignment rotation
float sin_yaw_align = sinf(radians(_yaw_align*0.01f));
float cos_yaw_align = cosf(radians(_yaw_align*0.01f));
Matrix3f Rz = Matrix3f(
cos_yaw_align, -sin_yaw_align, 0,
sin_yaw_align, cos_yaw_align, 0,
0, 0, 1
);
Vector3f target_vec_unit_ned = _attitude_history.front() * Rz * target_vec_unit_body;
bool target_vec_valid = target_vec_unit_ned.z > 0.0f;
bool alt_valid = (rangefinder_alt_valid && rangefinder_alt_cm > 0.0f) || (_backend->distance_to_target() > 0.0f);
if (target_vec_valid && alt_valid) {
float alt;
if (_backend->distance_to_target() > 0.0f) {
alt = _backend->distance_to_target();
} else {
alt = MAX(rangefinder_alt_cm*0.01f, 0.0f);
}
float dist = alt/target_vec_unit_ned.z;
Vector3f targetPosRelMeasNED = Vector3f(target_vec_unit_ned.x*dist, target_vec_unit_ned.y*dist, alt);
float xy_pos_var = sq(targetPosRelMeasNED.z*(0.01f + 0.01f*_ahrs.get_gyro().length()) + 0.02f);
if (!target_acquired()) {
// reset filter state
if (_inav.get_filter_status().flags.horiz_pos_rel) {
_ekf_x.init(targetPosRelMeasNED.x, xy_pos_var, -vehicleVelocityNED.x, sq(2.0f));
_ekf_y.init(targetPosRelMeasNED.y, xy_pos_var, -vehicleVelocityNED.y, sq(2.0f));
} else {
_ekf_x.init(targetPosRelMeasNED.x, xy_pos_var, 0.0f, sq(10.0f));
_ekf_y.init(targetPosRelMeasNED.y, xy_pos_var, 0.0f, sq(10.0f));
}
_last_update_ms = AP_HAL::millis();
} else {
float NIS_x = _ekf_x.getPosNIS(targetPosRelMeasNED.x, xy_pos_var);
float NIS_y = _ekf_y.getPosNIS(targetPosRelMeasNED.y, xy_pos_var);
if (MAX(NIS_x, NIS_y) < 3.0f || _outlier_reject_count >= 3) {
_outlier_reject_count = 0;
_ekf_x.fusePos(targetPosRelMeasNED.x, xy_pos_var);
_ekf_y.fusePos(targetPosRelMeasNED.y, xy_pos_var);
_last_update_ms = AP_HAL::millis();
} else {
_outlier_reject_count++;
}
}
}
}
}
}
bool AC_PrecLand::target_acquired() const
{
return (AP_HAL::millis()-_last_update_ms) < 2000;
}
bool AC_PrecLand::get_target_position_cm(Vector2f& ret) const
{
if (!target_acquired()) {
return false;
}
Vector3f land_ofs_ned_cm = _ahrs.get_rotation_body_to_ned() * Vector3f(_land_ofs_cm_x,_land_ofs_cm_y,0);
ret.x = _ekf_x.getPos()*100.0f + _inav.get_position().x + land_ofs_ned_cm.x;
ret.y = _ekf_y.getPos()*100.0f + _inav.get_position().y + land_ofs_ned_cm.y;
return true;
}
bool AC_PrecLand::get_target_position_relative_cm(Vector2f& ret) const
{
if (!target_acquired()) {
return false;
}
Vector3f land_ofs_ned_cm = _ahrs.get_rotation_body_to_ned() * Vector3f(_land_ofs_cm_x,_land_ofs_cm_y,0);
ret.x = _ekf_x.getPos()*100.0f + land_ofs_ned_cm.x;
ret.y = _ekf_y.getPos()*100.0f + land_ofs_ned_cm.y;
return true;
}
bool AC_PrecLand::get_target_velocity_relative_cms(Vector2f& ret) const
{
if (!target_acquired()) {
return false;
}
ret.x = _ekf_x.getVel()*100.0f;
ret.y = _ekf_y.getVel()*100.0f;
return true;
}
// handle_msg - Process a LANDING_TARGET mavlink message
void AC_PrecLand::handle_msg(mavlink_message_t* msg)
{
// run backend update
if (_backend != nullptr) {
_backend->handle_msg(msg);
}
}
| gpl-3.0 |
tukusejssirs/eSpievatko | spievatko/espievatko/prtbl/srv/php-5.5.11/ext/intl/tests/timezone_createEnumeration_variation2.phpt | 504 | --TEST--
IntlTimeZone::createEnumeration(): variant with country
--SKIPIF--
<?php
if (!extension_loaded('intl'))
die('skip intl extension not enabled');
--FILE--
<?php
ini_set("intl.error_level", E_WARNING);
$tz = IntlTimeZone::createEnumeration('NL');
var_dump(get_class($tz));
$count = count(iterator_to_array($tz));
var_dump($count >= 1);
$tz->rewind();
var_dump(in_array('Europe/Amsterdam', iterator_to_array($tz)));
?>
==DONE==
--EXPECT--
string(12) "IntlIterator"
bool(true)
bool(true)
==DONE==
| gpl-3.0 |
eireford/mahara | htdocs/artefact/plans/blocktype/plans/js/plansblock.js | 963 | function rewriteTaskTitles(blockid) {
forEach(
getElementsByTagAndClassName('a', 'task-title', 'tasktable_' + blockid),
function(element) {
disconnectAll(element);
connect(element, 'onclick', function(e) {
e.stop();
var description = getFirstElementByTagAndClassName('div', 'task-desc', element.parentNode);
toggleElementClass('hidden', description);
});
}
);
}
function TaskPager(blockid) {
var self = this;
paginatorProxy.addObserver(self);
connect(self, 'pagechanged', partial(rewriteTaskTitles, blockid));
}
var taskPagers = [];
function initNewPlansBlock(blockid) {
if ($('plans_page_container_' + blockid)) {
new Paginator('block' + blockid + '_pagination', 'tasktable_' + blockid, 'artefact/plans/viewtasks.json.php', null);
taskPagers.push(new TaskPager(blockid));
}
rewriteTaskTitles(blockid);
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core.tests.model/workspace/Compiler/src/org/eclipse/jdt/internal/compiler/lookup/ClassScope.java | 40473 | /*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.compiler.lookup;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Clinit;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.ast.TypeParameter;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
public class ClassScope extends Scope {
public TypeDeclaration referenceContext;
private TypeReference superTypeReference;
private final static char[] IncompleteHierarchy = new char[] {'h', 'a', 's', ' ', 'i', 'n', 'c', 'o', 'n', 's', 'i', 's', 't', 'e', 'n', 't', ' ', 'h', 'i', 'e', 'r', 'a', 'r', 'c', 'h', 'y'};
public ClassScope(Scope parent, TypeDeclaration context) {
super(CLASS_SCOPE, parent);
this.referenceContext = context;
}
void buildAnonymousTypeBinding(SourceTypeBinding enclosingType, ReferenceBinding supertype) {
LocalTypeBinding anonymousType = buildLocalType(enclosingType, enclosingType.fPackage);
SourceTypeBinding sourceType = referenceContext.binding;
if (supertype.isInterface()) {
sourceType.superclass = getJavaLangObject();
sourceType.superInterfaces = new ReferenceBinding[] { supertype };
} else {
sourceType.superclass = supertype;
sourceType.superInterfaces = TypeConstants.NoSuperInterfaces;
}
connectMemberTypes();
buildFieldsAndMethods();
anonymousType.faultInTypesForFieldsAndMethods();
sourceType.verifyMethods(environment().methodVerifier());
}
private void buildFields() {
boolean hierarchyIsInconsistent = referenceContext.binding.isHierarchyInconsistent();
if (referenceContext.fields == null) {
if (hierarchyIsInconsistent) { // 72468
referenceContext.binding.fields = new FieldBinding[1];
referenceContext.binding.fields[0] =
new FieldBinding(IncompleteHierarchy, VoidBinding, AccPrivate, referenceContext.binding, null);
} else {
referenceContext.binding.fields = NoFields;
}
return;
}
// count the number of fields vs. initializers
FieldDeclaration[] fields = referenceContext.fields;
int size = fields.length;
int count = 0;
for (int i = 0; i < size; i++)
if (fields[i].isField())
count++;
if (hierarchyIsInconsistent)
count++;
// iterate the field declarations to create the bindings, lose all duplicates
FieldBinding[] fieldBindings = new FieldBinding[count];
HashtableOfObject knownFieldNames = new HashtableOfObject(count);
boolean duplicate = false;
count = 0;
for (int i = 0; i < size; i++) {
FieldDeclaration field = fields[i];
if (!field.isField()) {
if (referenceContext.binding.isInterface())
problemReporter().interfaceCannotHaveInitializers(referenceContext.binding, field);
} else {
FieldBinding fieldBinding = new FieldBinding(field, null, field.modifiers | AccUnresolved, referenceContext.binding);
// field's type will be resolved when needed for top level types
checkAndSetModifiersForField(fieldBinding, field);
if (knownFieldNames.containsKey(field.name)) {
duplicate = true;
FieldBinding previousBinding = (FieldBinding) knownFieldNames.get(field.name);
if (previousBinding != null) {
for (int f = 0; f < i; f++) {
FieldDeclaration previousField = fields[f];
if (previousField.binding == previousBinding) {
problemReporter().duplicateFieldInType(referenceContext.binding, previousField);
previousField.binding = null;
break;
}
}
}
knownFieldNames.put(field.name, null); // ensure that the duplicate field is found & removed
problemReporter().duplicateFieldInType(referenceContext.binding, field);
field.binding = null;
} else {
knownFieldNames.put(field.name, fieldBinding);
// remember that we have seen a field with this name
if (fieldBinding != null)
fieldBindings[count++] = fieldBinding;
}
}
}
// remove duplicate fields
if (duplicate) {
FieldBinding[] newFieldBindings = new FieldBinding[knownFieldNames.size() - 1];
// we know we'll be removing at least 1 duplicate name
size = count;
count = 0;
for (int i = 0; i < size; i++) {
FieldBinding fieldBinding = fieldBindings[i];
if (knownFieldNames.get(fieldBinding.name) != null)
newFieldBindings[count++] = fieldBinding;
}
fieldBindings = newFieldBindings;
}
if (hierarchyIsInconsistent)
fieldBindings[count++] = new FieldBinding(IncompleteHierarchy, VoidBinding, AccPrivate, referenceContext.binding, null);
if (count != fieldBindings.length)
System.arraycopy(fieldBindings, 0, fieldBindings = new FieldBinding[count], 0, count);
for (int i = 0; i < count; i++)
fieldBindings[i].id = i;
referenceContext.binding.fields = fieldBindings;
}
void buildFieldsAndMethods() {
buildFields();
buildMethods();
SourceTypeBinding sourceType = referenceContext.binding;
if (sourceType.isMemberType() && !sourceType.isLocalType())
((MemberTypeBinding) sourceType).checkSyntheticArgsAndFields();
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++)
((SourceTypeBinding) memberTypes[i]).scope.buildFieldsAndMethods();
}
private LocalTypeBinding buildLocalType(
SourceTypeBinding enclosingType,
PackageBinding packageBinding) {
referenceContext.scope = this;
referenceContext.staticInitializerScope = new MethodScope(this, referenceContext, true);
referenceContext.initializerScope = new MethodScope(this, referenceContext, false);
// build the binding or the local type
LocalTypeBinding localType = new LocalTypeBinding(this, enclosingType, this.switchCase());
referenceContext.binding = localType;
checkAndSetModifiers();
buildTypeVariables();
// Look at member types
ReferenceBinding[] memberTypeBindings = NoMemberTypes;
if (referenceContext.memberTypes != null) {
int size = referenceContext.memberTypes.length;
memberTypeBindings = new ReferenceBinding[size];
int count = 0;
nextMember : for (int i = 0; i < size; i++) {
TypeDeclaration memberContext = referenceContext.memberTypes[i];
if (memberContext.isInterface()) {
problemReporter().nestedClassCannotDeclareInterface(memberContext);
continue nextMember;
}
ReferenceBinding type = localType;
// check that the member does not conflict with an enclosing type
do {
if (CharOperation.equals(type.sourceName, memberContext.name)) {
problemReporter().hidingEnclosingType(memberContext);
continue nextMember;
}
type = type.enclosingType();
} while (type != null);
// check the member type does not conflict with another sibling member type
for (int j = 0; j < i; j++) {
if (CharOperation.equals(referenceContext.memberTypes[j].name, memberContext.name)) {
problemReporter().duplicateNestedType(memberContext);
continue nextMember;
}
}
ClassScope memberScope = new ClassScope(this, referenceContext.memberTypes[i]);
LocalTypeBinding memberBinding = memberScope.buildLocalType(localType, packageBinding);
memberBinding.setAsMemberType();
memberTypeBindings[count++] = memberBinding;
}
if (count != size)
System.arraycopy(memberTypeBindings, 0, memberTypeBindings = new ReferenceBinding[count], 0, count);
}
localType.memberTypes = memberTypeBindings;
return localType;
}
void buildLocalTypeBinding(SourceTypeBinding enclosingType) {
LocalTypeBinding localType = buildLocalType(enclosingType, enclosingType.fPackage);
connectTypeHierarchy();
buildFieldsAndMethods();
localType.faultInTypesForFieldsAndMethods();
referenceContext.binding.verifyMethods(environment().methodVerifier());
}
private void buildMemberTypes() {
SourceTypeBinding sourceType = referenceContext.binding;
ReferenceBinding[] memberTypeBindings = NoMemberTypes;
if (referenceContext.memberTypes != null) {
int length = referenceContext.memberTypes.length;
memberTypeBindings = new ReferenceBinding[length];
int count = 0;
nextMember : for (int i = 0; i < length; i++) {
TypeDeclaration memberContext = referenceContext.memberTypes[i];
if (memberContext.isInterface()
&& sourceType.isNestedType()
&& sourceType.isClass()
&& !sourceType.isStatic()) {
problemReporter().nestedClassCannotDeclareInterface(memberContext);
continue nextMember;
}
ReferenceBinding type = sourceType;
// check that the member does not conflict with an enclosing type
do {
if (CharOperation.equals(type.sourceName, memberContext.name)) {
problemReporter().hidingEnclosingType(memberContext);
continue nextMember;
}
type = type.enclosingType();
} while (type != null);
// check that the member type does not conflict with another sibling member type
for (int j = 0; j < i; j++) {
if (CharOperation.equals(referenceContext.memberTypes[j].name, memberContext.name)) {
problemReporter().duplicateNestedType(memberContext);
continue nextMember;
}
}
ClassScope memberScope = new ClassScope(this, memberContext);
memberTypeBindings[count++] = memberScope.buildType(sourceType, sourceType.fPackage);
}
if (count != length)
System.arraycopy(memberTypeBindings, 0, memberTypeBindings = new ReferenceBinding[count], 0, count);
}
sourceType.memberTypes = memberTypeBindings;
}
private void buildMethods() {
if (referenceContext.methods == null) {
referenceContext.binding.methods = NoMethods;
return;
}
// iterate the method declarations to create the bindings
AbstractMethodDeclaration[] methods = referenceContext.methods;
int size = methods.length;
int clinitIndex = -1;
for (int i = 0; i < size; i++) {
if (methods[i] instanceof Clinit) {
clinitIndex = i;
break;
}
}
MethodBinding[] methodBindings = new MethodBinding[clinitIndex == -1 ? size : size - 1];
int count = 0;
for (int i = 0; i < size; i++) {
if (i != clinitIndex) {
MethodScope scope = new MethodScope(this, methods[i], false);
MethodBinding methodBinding = scope.createMethod(methods[i]);
if (methodBinding != null) // is null if binding could not be created
methodBindings[count++] = methodBinding;
}
}
if (count != methodBindings.length)
System.arraycopy(methodBindings, 0, methodBindings = new MethodBinding[count], 0, count);
referenceContext.binding.methods = methodBindings;
referenceContext.binding.modifiers |= AccUnresolved; // until methods() is sent
}
SourceTypeBinding buildType(SourceTypeBinding enclosingType, PackageBinding packageBinding) {
// provide the typeDeclaration with needed scopes
referenceContext.scope = this;
referenceContext.staticInitializerScope = new MethodScope(this, referenceContext, true);
referenceContext.initializerScope = new MethodScope(this, referenceContext, false);
if (enclosingType == null) {
char[][] className = CharOperation.arrayConcat(packageBinding.compoundName, referenceContext.name);
referenceContext.binding = new SourceTypeBinding(className, packageBinding, this);
} else {
char[][] className = CharOperation.deepCopy(enclosingType.compoundName);
className[className.length - 1] =
CharOperation.concat(className[className.length - 1], referenceContext.name, '$');
referenceContext.binding = new MemberTypeBinding(className, this, enclosingType);
}
SourceTypeBinding sourceType = referenceContext.binding;
sourceType.fPackage.addType(sourceType);
checkAndSetModifiers();
buildTypeVariables();
buildMemberTypes();
return sourceType;
}
private void buildTypeVariables() {
SourceTypeBinding sourceType = referenceContext.binding;
TypeParameter[] typeParameters = referenceContext.typeParameters;
// do not construct type variables if source < 1.5
if (typeParameters == null || environment().options.sourceLevel < ClassFileConstants.JDK1_5) {
sourceType.typeVariables = NoTypeVariables;
return;
}
sourceType.typeVariables = NoTypeVariables; // safety
if (sourceType.id == T_Object) { // handle the case of redefining java.lang.Object up front
problemReporter().objectCannotBeGeneric(referenceContext);
return;
}
sourceType.typeVariables = createTypeVariables(typeParameters, sourceType);
sourceType.modifiers |= AccGenericSignature;
}
private void checkAndSetModifiers() {
SourceTypeBinding sourceType = referenceContext.binding;
int modifiers = sourceType.modifiers;
if ((modifiers & AccAlternateModifierProblem) != 0)
problemReporter().duplicateModifierForType(sourceType);
ReferenceBinding enclosingType = sourceType.enclosingType();
boolean isMemberType = sourceType.isMemberType();
if (isMemberType) {
// checks for member types before local types to catch local members
if (enclosingType.isStrictfp())
modifiers |= AccStrictfp;
if (enclosingType.isViewedAsDeprecated() && !sourceType.isDeprecated())
modifiers |= AccDeprecatedImplicitly;
if (enclosingType.isInterface())
modifiers |= AccPublic;
} else if (sourceType.isLocalType()) {
if (sourceType.isAnonymousType())
modifiers |= AccFinal;
Scope scope = this;
do {
switch (scope.kind) {
case METHOD_SCOPE :
MethodScope methodScope = (MethodScope) scope;
if (methodScope.isInsideInitializer()) {
SourceTypeBinding type = ((TypeDeclaration) methodScope.referenceContext).binding;
// inside field declaration ? check field modifier to see if deprecated
if (methodScope.initializedField != null) {
// currently inside this field initialization
if (methodScope.initializedField.isViewedAsDeprecated() && !sourceType.isDeprecated()){
modifiers |= AccDeprecatedImplicitly;
}
} else {
if (type.isStrictfp())
modifiers |= AccStrictfp;
if (type.isViewedAsDeprecated() && !sourceType.isDeprecated())
modifiers |= AccDeprecatedImplicitly;
}
} else {
MethodBinding method = ((AbstractMethodDeclaration) methodScope.referenceContext).binding;
if (method != null){
if (method.isStrictfp())
modifiers |= AccStrictfp;
if (method.isViewedAsDeprecated() && !sourceType.isDeprecated())
modifiers |= AccDeprecatedImplicitly;
}
}
break;
case CLASS_SCOPE :
// local member
if (enclosingType.isStrictfp())
modifiers |= AccStrictfp;
if (enclosingType.isViewedAsDeprecated() && !sourceType.isDeprecated())
modifiers |= AccDeprecatedImplicitly;
break;
}
scope = scope.parent;
} while (scope != null);
}
// after this point, tests on the 16 bits reserved.
int realModifiers = modifiers & AccJustFlag;
if ((realModifiers & AccInterface) != 0) {
// detect abnormal cases for interfaces
if (isMemberType) {
int unexpectedModifiers =
~(AccPublic | AccPrivate | AccProtected | AccStatic | AccAbstract | AccInterface | AccStrictfp);
if ((realModifiers & unexpectedModifiers) != 0)
problemReporter().illegalModifierForMemberInterface(sourceType);
/*
} else if (sourceType.isLocalType()) { //interfaces cannot be defined inside a method
int unexpectedModifiers = ~(AccAbstract | AccInterface | AccStrictfp);
if ((realModifiers & unexpectedModifiers) != 0)
problemReporter().illegalModifierForLocalInterface(sourceType);
*/
} else {
int unexpectedModifiers = ~(AccPublic | AccAbstract | AccInterface | AccStrictfp);
if ((realModifiers & unexpectedModifiers) != 0)
problemReporter().illegalModifierForInterface(sourceType);
}
modifiers |= AccAbstract;
} else {
// detect abnormal cases for types
if (isMemberType) { // includes member types defined inside local types
int unexpectedModifiers =
~(AccPublic | AccPrivate | AccProtected | AccStatic | AccAbstract | AccFinal | AccStrictfp);
if ((realModifiers & unexpectedModifiers) != 0)
problemReporter().illegalModifierForMemberClass(sourceType);
} else if (sourceType.isLocalType()) {
int unexpectedModifiers = ~(AccAbstract | AccFinal | AccStrictfp);
if ((realModifiers & unexpectedModifiers) != 0)
problemReporter().illegalModifierForLocalClass(sourceType);
} else {
int unexpectedModifiers = ~(AccPublic | AccAbstract | AccFinal | AccStrictfp);
if ((realModifiers & unexpectedModifiers) != 0)
problemReporter().illegalModifierForClass(sourceType);
}
// check that Final and Abstract are not set together
if ((realModifiers & (AccFinal | AccAbstract)) == (AccFinal | AccAbstract))
problemReporter().illegalModifierCombinationFinalAbstractForClass(sourceType);
}
if (isMemberType) {
// test visibility modifiers inconsistency, isolate the accessors bits
if (enclosingType.isInterface()) {
if ((realModifiers & (AccProtected | AccPrivate)) != 0) {
problemReporter().illegalVisibilityModifierForInterfaceMemberType(sourceType);
// need to keep the less restrictive
if ((realModifiers & AccProtected) != 0)
modifiers ^= AccProtected;
if ((realModifiers & AccPrivate) != 0)
modifiers ^= AccPrivate;
}
} else {
int accessorBits = realModifiers & (AccPublic | AccProtected | AccPrivate);
if ((accessorBits & (accessorBits - 1)) > 1) {
problemReporter().illegalVisibilityModifierCombinationForMemberType(sourceType);
// need to keep the less restrictive
if ((accessorBits & AccPublic) != 0) {
if ((accessorBits & AccProtected) != 0)
modifiers ^= AccProtected;
if ((accessorBits & AccPrivate) != 0)
modifiers ^= AccPrivate;
}
if ((accessorBits & AccProtected) != 0)
if ((accessorBits & AccPrivate) != 0)
modifiers ^= AccPrivate;
}
}
// static modifier test
if ((realModifiers & AccStatic) == 0) {
if (enclosingType.isInterface())
modifiers |= AccStatic;
} else {
if (!enclosingType.isStatic())
// error the enclosing type of a static field must be static or a top-level type
problemReporter().illegalStaticModifierForMemberType(sourceType);
}
}
sourceType.modifiers = modifiers;
}
/* This method checks the modifiers of a field.
*
* 9.3 & 8.3
* Need to integrate the check for the final modifiers for nested types
*
* Note : A scope is accessible by : fieldBinding.declaringClass.scope
*/
private void checkAndSetModifiersForField(FieldBinding fieldBinding, FieldDeclaration fieldDecl) {
int modifiers = fieldBinding.modifiers;
if ((modifiers & AccAlternateModifierProblem) != 0)
problemReporter().duplicateModifierForField(fieldBinding.declaringClass, fieldDecl);
if (fieldBinding.declaringClass.isInterface()) {
int expectedValue = AccPublic | AccStatic | AccFinal;
// set the modifiers
modifiers |= expectedValue;
// and then check that they are the only ones
if ((modifiers & AccJustFlag) != expectedValue)
problemReporter().illegalModifierForInterfaceField(fieldBinding.declaringClass, fieldDecl);
fieldBinding.modifiers = modifiers;
return;
}
// after this point, tests on the 16 bits reserved.
int realModifiers = modifiers & AccJustFlag;
int unexpectedModifiers =
~(AccPublic | AccPrivate | AccProtected | AccFinal | AccStatic | AccTransient | AccVolatile);
if ((realModifiers & unexpectedModifiers) != 0)
problemReporter().illegalModifierForField(fieldBinding.declaringClass, fieldDecl);
int accessorBits = realModifiers & (AccPublic | AccProtected | AccPrivate);
if ((accessorBits & (accessorBits - 1)) > 1) {
problemReporter().illegalVisibilityModifierCombinationForField(
fieldBinding.declaringClass,
fieldDecl);
// need to keep the less restrictive
if ((accessorBits & AccPublic) != 0) {
if ((accessorBits & AccProtected) != 0)
modifiers ^= AccProtected;
if ((accessorBits & AccPrivate) != 0)
modifiers ^= AccPrivate;
}
if ((accessorBits & AccProtected) != 0)
if ((accessorBits & AccPrivate) != 0)
modifiers ^= AccPrivate;
}
if ((realModifiers & (AccFinal | AccVolatile)) == (AccFinal | AccVolatile))
problemReporter().illegalModifierCombinationFinalVolatileForField(
fieldBinding.declaringClass,
fieldDecl);
if (fieldDecl.initialization == null && (modifiers & AccFinal) != 0) {
modifiers |= AccBlankFinal;
}
fieldBinding.modifiers = modifiers;
}
private void checkForInheritedMemberTypes(SourceTypeBinding sourceType) {
// search up the hierarchy of the sourceType to see if any superType defines a member type
// when no member types are defined, tag the sourceType & each superType with the HasNoMemberTypes bit
// assumes super types have already been checked & tagged
ReferenceBinding currentType = sourceType;
ReferenceBinding[][] interfacesToVisit = null;
int lastPosition = -1;
do {
if (currentType.hasMemberTypes()) // avoid resolving member types eagerly
return;
ReferenceBinding[] itsInterfaces = currentType.superInterfaces();
if (itsInterfaces != NoSuperInterfaces) {
if (interfacesToVisit == null)
interfacesToVisit = new ReferenceBinding[5][];
if (++lastPosition == interfacesToVisit.length)
System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition);
interfacesToVisit[lastPosition] = itsInterfaces;
}
} while ((currentType = currentType.superclass()) != null && (currentType.tagBits & HasNoMemberTypes) == 0);
if (interfacesToVisit != null) {
// contains the interfaces between the sourceType and any superclass, which was tagged as having no member types
boolean needToTag = false;
for (int i = 0; i <= lastPosition; i++) {
ReferenceBinding[] interfaces = interfacesToVisit[i];
for (int j = 0, length = interfaces.length; j < length; j++) {
ReferenceBinding anInterface = interfaces[j];
if ((anInterface.tagBits & HasNoMemberTypes) == 0) { // skip interface if it already knows it has no member types
if (anInterface.hasMemberTypes()) // avoid resolving member types eagerly
return;
needToTag = true;
ReferenceBinding[] itsInterfaces = anInterface.superInterfaces();
if (itsInterfaces != NoSuperInterfaces) {
if (++lastPosition == interfacesToVisit.length)
System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition);
interfacesToVisit[lastPosition] = itsInterfaces;
}
}
}
}
if (needToTag) {
for (int i = 0; i <= lastPosition; i++) {
ReferenceBinding[] interfaces = interfacesToVisit[i];
for (int j = 0, length = interfaces.length; j < length; j++)
interfaces[j].tagBits |= HasNoMemberTypes;
}
}
}
// tag the sourceType and all of its superclasses, unless they have already been tagged
currentType = sourceType;
do {
currentType.tagBits |= HasNoMemberTypes;
} while ((currentType = currentType.superclass()) != null && (currentType.tagBits & HasNoMemberTypes) == 0);
}
// Perform deferred bound checks for parameterized type references (only done after hierarchy is connected)
private void checkParameterizedTypeBounds() {
TypeReference superclass = referenceContext.superclass;
if (superclass != null) {
superclass.checkBounds(this);
}
TypeReference[] superinterfaces = referenceContext.superInterfaces;
if (superinterfaces != null) {
for (int i = 0, length = superinterfaces.length; i < length; i++) {
superinterfaces[i].checkBounds(this);
}
}
TypeParameter[] typeParameters = referenceContext.typeParameters;
if (typeParameters != null) {
for (int i = 0, paramLength = typeParameters.length; i < paramLength; i++) {
TypeParameter typeParameter = typeParameters[i];
TypeReference typeRef = typeParameter.type;
if (typeRef != null) {
typeRef.checkBounds(this);
TypeReference[] boundRefs = typeParameter.bounds;
if (boundRefs != null)
for (int j = 0, k = boundRefs.length; j < k; j++)
boundRefs[j].checkBounds(this);
}
}
}
}
private void connectMemberTypes() {
SourceTypeBinding sourceType = referenceContext.binding;
if (sourceType.memberTypes != NoMemberTypes)
for (int i = 0, size = sourceType.memberTypes.length; i < size; i++)
((SourceTypeBinding) sourceType.memberTypes[i]).scope.connectTypeHierarchy();
}
/*
Our current belief based on available JCK tests is:
inherited member types are visible as a potential superclass.
inherited interfaces are not visible when defining a superinterface.
Error recovery story:
ensure the superclass is set to java.lang.Object if a problem is detected
resolving the superclass.
Answer false if an error was reported against the sourceType.
*/
private boolean connectSuperclass() {
SourceTypeBinding sourceType = referenceContext.binding;
if (sourceType.id == T_Object) { // handle the case of redefining java.lang.Object up front
sourceType.superclass = null;
sourceType.superInterfaces = NoSuperInterfaces;
if (referenceContext.superclass != null || referenceContext.superInterfaces != null)
problemReporter().objectCannotHaveSuperTypes(sourceType);
return true; // do not propagate Object's hierarchy problems down to every subtype
}
if (referenceContext.superclass == null) {
sourceType.superclass = getJavaLangObject();
return !detectCycle(sourceType, sourceType.superclass, null);
}
TypeReference superclassRef = referenceContext.superclass;
ReferenceBinding superclass = findSupertype(superclassRef);
if (superclass != null) { // is null if a cycle was detected cycle or a problem
if (superclass.isInterface()) {
problemReporter().superclassMustBeAClass(sourceType, superclassRef, superclass);
} else if (superclass.isFinal()) {
problemReporter().classExtendFinalClass(sourceType, superclassRef, superclass);
} else if ((superclass.tagBits & TagBits.HasWildcard) != 0) {
problemReporter().superTypeCannotUseWildcard(sourceType, superclassRef, superclass);
} else {
// only want to reach here when no errors are reported
sourceType.superclass = superclass;
return true;
}
}
sourceType.tagBits |= HierarchyHasProblems;
sourceType.superclass = getJavaLangObject();
if ((sourceType.superclass.tagBits & BeginHierarchyCheck) == 0)
detectCycle(sourceType, sourceType.superclass, null);
return false; // reported some error against the source type
}
/*
Our current belief based on available JCK 1.3 tests is:
inherited member types are visible as a potential superclass.
inherited interfaces are visible when defining a superinterface.
Error recovery story:
ensure the superinterfaces contain only valid visible interfaces.
Answer false if an error was reported against the sourceType.
*/
private boolean connectSuperInterfaces() {
SourceTypeBinding sourceType = referenceContext.binding;
sourceType.superInterfaces = NoSuperInterfaces;
if (referenceContext.superInterfaces == null)
return true;
if (sourceType.id == T_Object) // already handled the case of redefining java.lang.Object
return true;
boolean noProblems = true;
int length = referenceContext.superInterfaces.length;
ReferenceBinding[] interfaceBindings = new ReferenceBinding[length];
int count = 0;
nextInterface : for (int i = 0; i < length; i++) {
TypeReference superInterfaceRef = referenceContext.superInterfaces[i];
ReferenceBinding superInterface = findSupertype(superInterfaceRef);
if (superInterface == null) { // detected cycle
sourceType.tagBits |= HierarchyHasProblems;
noProblems = false;
continue nextInterface;
}
superInterfaceRef.resolvedType = superInterface; // hold onto the problem type
// Check for a duplicate interface once the name is resolved, otherwise we may be confused (ie : a.b.I and c.d.I)
for (int k = 0; k < count; k++) {
if (interfaceBindings[k] == superInterface) {
// should this be treated as a warning?
problemReporter().duplicateSuperinterface(sourceType, referenceContext, superInterface);
continue nextInterface;
}
}
if (superInterface.isClass()) {
problemReporter().superinterfaceMustBeAnInterface(sourceType, superInterfaceRef, superInterface);
sourceType.tagBits |= HierarchyHasProblems;
noProblems = false;
continue nextInterface;
}
if ((superInterface.tagBits & TagBits.HasWildcard) != 0) {
problemReporter().superTypeCannotUseWildcard(sourceType, superInterfaceRef, superInterface);
sourceType.tagBits |= HierarchyHasProblems;
noProblems = false;
continue nextInterface;
}
ReferenceBinding invalid = findAmbiguousInterface(superInterface, sourceType);
if (invalid != null) {
ReferenceBinding generic = null;
if (superInterface.isParameterizedType())
generic = ((ParameterizedTypeBinding) superInterface).type;
else if (invalid.isParameterizedType())
generic = ((ParameterizedTypeBinding) invalid).type;
problemReporter().superinterfacesCollide(generic, referenceContext, superInterface, invalid);
sourceType.tagBits |= HierarchyHasProblems;
noProblems = false;
continue nextInterface;
}
// only want to reach here when no errors are reported
interfaceBindings[count++] = superInterface;
}
// hold onto all correctly resolved superinterfaces
if (count > 0) {
if (count != length)
System.arraycopy(interfaceBindings, 0, interfaceBindings = new ReferenceBinding[count], 0, count);
sourceType.superInterfaces = interfaceBindings;
}
return noProblems;
}
void connectTypeHierarchy() {
SourceTypeBinding sourceType = referenceContext.binding;
if ((sourceType.tagBits & BeginHierarchyCheck) == 0) {
sourceType.tagBits |= BeginHierarchyCheck;
boolean noProblems = connectTypeVariables(referenceContext.typeParameters);
noProblems &= connectSuperclass();
noProblems &= connectSuperInterfaces();
sourceType.tagBits |= EndHierarchyCheck;
if (noProblems && sourceType.isHierarchyInconsistent())
problemReporter().hierarchyHasProblems(sourceType);
}
// Perform deferred bound checks for parameterized type references (only done after hierarchy is connected)
checkParameterizedTypeBounds();
connectMemberTypes();
try {
checkForInheritedMemberTypes(sourceType);
} catch (AbortCompilation e) {
e.updateContext(referenceContext, referenceCompilationUnit().compilationResult);
throw e;
}
}
private void connectTypeHierarchyWithoutMembers() {
// must ensure the imports are resolved
if (parent instanceof CompilationUnitScope) {
if (((CompilationUnitScope) parent).imports == null)
((CompilationUnitScope) parent).checkAndSetImports();
} else if (parent instanceof ClassScope) {
// ensure that the enclosing type has already been checked
((ClassScope) parent).connectTypeHierarchyWithoutMembers();
}
// double check that the hierarchy search has not already begun...
SourceTypeBinding sourceType = referenceContext.binding;
if ((sourceType.tagBits & BeginHierarchyCheck) != 0)
return;
sourceType.tagBits |= BeginHierarchyCheck;
boolean noProblems = connectTypeVariables(referenceContext.typeParameters);
noProblems &= connectSuperclass();
noProblems &= connectSuperInterfaces();
sourceType.tagBits |= EndHierarchyCheck;
if (noProblems && sourceType.isHierarchyInconsistent())
problemReporter().hierarchyHasProblems(sourceType);
}
public boolean detectCycle(TypeBinding superType, TypeReference reference, TypeBinding[] argTypes) {
if (!(superType instanceof ReferenceBinding)) return false;
if (argTypes != null) {
for (int i = 0, l = argTypes.length; i < l; i++) {
TypeBinding argType = argTypes[i].leafComponentType();
if ((argType.tagBits & BeginHierarchyCheck) == 0 && argType instanceof SourceTypeBinding)
// ensure if this is a source argument type that it has already been checked
((SourceTypeBinding) argType).scope.connectTypeHierarchyWithoutMembers();
}
}
if (reference == this.superTypeReference) { // see findSuperType()
if (superType.isTypeVariable())
return false; // error case caught in resolveSuperType()
// abstract class X<K,V> implements java.util.Map<K,V>
// static abstract class M<K,V> implements Entry<K,V>
if (superType.isParameterizedType())
superType = ((ParameterizedTypeBinding) superType).type;
compilationUnitScope().recordSuperTypeReference(superType); // to record supertypes
return detectCycle(referenceContext.binding, (ReferenceBinding) superType, reference);
}
if ((superType.tagBits & BeginHierarchyCheck) == 0 && superType instanceof SourceTypeBinding)
// ensure if this is a source superclass that it has already been checked
((SourceTypeBinding) superType).scope.connectTypeHierarchyWithoutMembers();
return false;
}
// Answer whether a cycle was found between the sourceType & the superType
private boolean detectCycle(SourceTypeBinding sourceType, ReferenceBinding superType, TypeReference reference) {
if (superType.isRawType())
superType = ((RawTypeBinding) superType).type;
// by this point the superType must be a binary or source type
if (sourceType == superType) {
problemReporter().hierarchyCircularity(sourceType, superType, reference);
sourceType.tagBits |= HierarchyHasProblems;
return true;
}
if (superType.isMemberType()) {
ReferenceBinding current = superType.enclosingType();
do {
if (current.isHierarchyBeingConnected()) {
problemReporter().hierarchyCircularity(sourceType, current, reference);
sourceType.tagBits |= HierarchyHasProblems;
current.tagBits |= HierarchyHasProblems;
return true;
}
} while ((current = current.enclosingType()) != null);
}
if (superType.isBinaryBinding()) {
// force its superclass & superinterfaces to be found... 2 possibilities exist - the source type is included in the hierarchy of:
// - a binary type... this case MUST be caught & reported here
// - another source type... this case is reported against the other source type
boolean hasCycle = false;
if (superType.superclass() != null) {
if (sourceType == superType.superclass()) {
problemReporter().hierarchyCircularity(sourceType, superType, reference);
sourceType.tagBits |= HierarchyHasProblems;
superType.tagBits |= HierarchyHasProblems;
return true;
}
ReferenceBinding parentType = superType.superclass();
if (parentType.isParameterizedType())
parentType = ((ParameterizedTypeBinding) parentType).type;
hasCycle |= detectCycle(sourceType, parentType, reference);
if ((parentType.tagBits & HierarchyHasProblems) != 0) {
sourceType.tagBits |= HierarchyHasProblems;
parentType.tagBits |= HierarchyHasProblems; // propagate down the hierarchy
}
}
ReferenceBinding[] itsInterfaces = superType.superInterfaces();
if (itsInterfaces != NoSuperInterfaces) {
for (int i = 0, length = itsInterfaces.length; i < length; i++) {
ReferenceBinding anInterface = itsInterfaces[i];
if (sourceType == anInterface) {
problemReporter().hierarchyCircularity(sourceType, superType, reference);
sourceType.tagBits |= HierarchyHasProblems;
superType.tagBits |= HierarchyHasProblems;
return true;
}
if (anInterface.isParameterizedType())
anInterface = ((ParameterizedTypeBinding) anInterface).type;
hasCycle |= detectCycle(sourceType, anInterface, reference);
if ((anInterface.tagBits & HierarchyHasProblems) != 0) {
sourceType.tagBits |= HierarchyHasProblems;
superType.tagBits |= HierarchyHasProblems;
}
}
}
return hasCycle;
}
if (superType.isHierarchyBeingConnected()) {
if (((SourceTypeBinding) superType).scope.superTypeReference != null) { // if null then its connecting its type variables
problemReporter().hierarchyCircularity(sourceType, superType, reference);
sourceType.tagBits |= HierarchyHasProblems;
superType.tagBits |= HierarchyHasProblems;
return true;
}
}
if ((superType.tagBits & BeginHierarchyCheck) == 0)
// ensure if this is a source superclass that it has already been checked
((SourceTypeBinding) superType).scope.connectTypeHierarchyWithoutMembers();
if ((superType.tagBits & HierarchyHasProblems) != 0)
sourceType.tagBits |= HierarchyHasProblems;
return false;
}
private ReferenceBinding findAmbiguousInterface(ReferenceBinding newInterface, ReferenceBinding currentType) {
TypeBinding newErasure = newInterface.erasure();
if (newInterface == newErasure) return null;
ReferenceBinding[][] interfacesToVisit = new ReferenceBinding[5][];
int lastPosition = -1;
do {
ReferenceBinding[] itsInterfaces = currentType.superInterfaces();
if (itsInterfaces != NoSuperInterfaces) {
if (++lastPosition == interfacesToVisit.length)
System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition);
interfacesToVisit[lastPosition] = itsInterfaces;
}
} while ((currentType = currentType.superclass()) != null);
for (int i = 0; i <= lastPosition; i++) {
ReferenceBinding[] interfaces = interfacesToVisit[i];
for (int j = 0, length = interfaces.length; j < length; j++) {
currentType = interfaces[j];
if (currentType.erasure() == newErasure)
if (currentType != newInterface)
return currentType;
ReferenceBinding[] itsInterfaces = currentType.superInterfaces();
if (itsInterfaces != NoSuperInterfaces) {
if (++lastPosition == interfacesToVisit.length)
System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition);
interfacesToVisit[lastPosition] = itsInterfaces;
}
}
}
return null;
}
private ReferenceBinding findSupertype(TypeReference typeReference) {
try {
typeReference.aboutToResolve(this); // allows us to trap completion & selection nodes
compilationUnitScope().recordQualifiedReference(typeReference.getTypeName());
this.superTypeReference = typeReference;
ReferenceBinding superType = (ReferenceBinding) typeReference.resolveSuperType(this);
this.superTypeReference = null;
return superType;
} catch (AbortCompilation e) {
e.updateContext(typeReference, referenceCompilationUnit().compilationResult);
throw e;
}
}
/* Answer the problem reporter to use for raising new problems.
*
* Note that as a side-effect, this updates the current reference context
* (unit, type or method) in case the problem handler decides it is necessary
* to abort.
*/
public ProblemReporter problemReporter() {
MethodScope outerMethodScope;
if ((outerMethodScope = outerMostMethodScope()) == null) {
ProblemReporter problemReporter = referenceCompilationUnit().problemReporter;
problemReporter.referenceContext = referenceContext;
return problemReporter;
}
return outerMethodScope.problemReporter();
}
/* Answer the reference type of this scope.
* It is the nearest enclosing type of this scope.
*/
public TypeDeclaration referenceType() {
return referenceContext;
}
public String toString() {
if (referenceContext != null)
return "--- Class Scope ---\n\n" //$NON-NLS-1$
+ referenceContext.binding.toString();
return "--- Class Scope ---\n\n Binding not initialized" ; //$NON-NLS-1$
}
}
| gpl-3.0 |
mgood7123/UPM | perl-5.26.1/perl5.26.1/lib/5.26.1/unicore/lib/Ccc/A.pl | 1655 | # !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by lib/unicore/mktables from the Unicode
# database, Version 9.0.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly. Use Unicode::UCD to access the Unicode character data
# base.
return <<'END';
V220
768
789
829
837
838
839
842
845
848
851
855
856
859
860
867
880
1155
1160
1426
1430
1431
1434
1436
1442
1448
1450
1451
1453
1455
1456
1476
1477
1552
1560
1619
1621
1623
1628
1629
1631
1750
1757
1759
1763
1764
1765
1767
1769
1771
1773
1840
1841
1842
1844
1845
1847
1850
1851
1853
1854
1855
1858
1859
1860
1861
1862
1863
1864
1865
1867
2027
2034
2035
2036
2070
2074
2075
2084
2085
2088
2089
2094
2260
2274
2276
2278
2279
2281
2282
2285
2291
2294
2295
2297
2299
2304
2385
2386
2387
2389
3970
3972
3974
3976
4957
4960
6109
6110
6458
6459
6679
6680
6773
6781
6832
6837
6843
6845
7019
7020
7021
7028
7376
7379
7386
7388
7392
7393
7412
7413
7416
7418
7616
7618
7619
7626
7627
7629
7633
7670
7675
7676
7678
7679
8400
8402
8404
8408
8411
8413
8417
8418
8423
8424
8425
8426
8432
8433
11503
11506
11744
11776
42607
42608
42612
42622
42654
42656
42736
42738
43232
43250
43696
43697
43698
43700
43703
43705
43710
43712
43713
43714
65056
65063
65070
65072
66422
66427
68111
68112
68152
68153
68325
68326
69888
69891
70502
70509
70512
70517
92976
92983
119173
119178
119210
119214
119362
119365
122880
122887
122888
122905
122907
122914
122915
122917
122918
122923
125252
125258
END
| gpl-3.0 |
AbrahmAB/sugar | src/jarabe/journal/__init__.py | 679 | # Copyright (C) 2007, One Laptop Per Child
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
| gpl-3.0 |
jbampton/eclipse-cheatsheets-to-dita-to-pdf | src/libs/fop-2.1/javadocs/org/apache/fop/render/awt/viewer/Renderable.html | 9950 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_34) on Thu Jan 07 14:13:56 GMT 2016 -->
<TITLE>
Renderable (Apache FOP 2.1 API)
</TITLE>
<META NAME="date" CONTENT="2016-01-07">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Renderable (Apache FOP 2.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Renderable.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 2.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../org/apache/fop/render/awt/viewer/PreviewPanel.html" title="class in org.apache.fop.render.awt.viewer"><B>PREV CLASS</B></A>
<A HREF="../../../../../../org/apache/fop/render/awt/viewer/StatusListener.html" title="interface in org.apache.fop.render.awt.viewer"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/fop/render/awt/viewer/Renderable.html" target="_top"><B>FRAMES</B></A>
<A HREF="Renderable.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.apache.fop.render.awt.viewer</FONT>
<BR>
Interface Renderable</H2>
<DL>
<DT><B>All Known Implementing Classes:</B> <DD><A HREF="../../../../../../org/apache/fop/cli/AreaTreeInputHandler.html" title="class in org.apache.fop.cli">AreaTreeInputHandler</A>, <A HREF="../../../../../../org/apache/fop/cli/IFInputHandler.html" title="class in org.apache.fop.cli">IFInputHandler</A>, <A HREF="../../../../../../org/apache/fop/cli/ImageInputHandler.html" title="class in org.apache.fop.cli">ImageInputHandler</A>, <A HREF="../../../../../../org/apache/fop/cli/InputHandler.html" title="class in org.apache.fop.cli">InputHandler</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public interface <B>Renderable</B></DL>
</PRE>
<P>
The interface is used by the AWT preview dialog to reload a document.
<P>
<P>
<HR>
<P>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/fop/render/awt/viewer/Renderable.html#renderTo(org.apache.fop.apps.FOUserAgent, java.lang.String)">renderTo</A></B>(<A HREF="../../../../../../org/apache/fop/apps/FOUserAgent.html" title="class in org.apache.fop.apps">FOUserAgent</A> userAgent,
java.lang.String outputFormat)</CODE>
<BR>
Renders the pre-setup document.</TD>
</TR>
</TABLE>
<P>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="renderTo(org.apache.fop.apps.FOUserAgent, java.lang.String)"><!-- --></A><H3>
renderTo</H3>
<PRE>
void <B>renderTo</B>(<A HREF="../../../../../../org/apache/fop/apps/FOUserAgent.html" title="class in org.apache.fop.apps">FOUserAgent</A> userAgent,
java.lang.String outputFormat)
throws <A HREF="../../../../../../org/apache/fop/apps/FOPException.html" title="class in org.apache.fop.apps">FOPException</A></PRE>
<DL>
<DD>Renders the pre-setup document.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>userAgent</CODE> - the user agent<DD><CODE>outputFormat</CODE> - the output format to generate (MIME type, see MimeConstants)
<DT><B>Throws:</B>
<DD><CODE><A HREF="../../../../../../org/apache/fop/apps/FOPException.html" title="class in org.apache.fop.apps">FOPException</A></CODE> - if the FO processing fails</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Renderable.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
fop 2.1</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../org/apache/fop/render/awt/viewer/PreviewPanel.html" title="class in org.apache.fop.render.awt.viewer"><B>PREV CLASS</B></A>
<A HREF="../../../../../../org/apache/fop/render/awt/viewer/StatusListener.html" title="interface in org.apache.fop.render.awt.viewer"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/fop/render/awt/viewer/Renderable.html" target="_top"><B>FRAMES</B></A>
<A HREF="Renderable.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved.
</BODY>
</HTML>
| gpl-3.0 |
massar5289/openairinterface5G | openair-cn/NAS/UE/ESM/EsmStatusHdl.c | 7850 | /*******************************************************************************
OpenAirInterface
Copyright(c) 1999 - 2014 Eurecom
OpenAirInterface 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.
OpenAirInterface 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 OpenAirInterface.The full GNU General Public License is
included in this distribution in the file called "COPYING". If not,
see <http://www.gnu.org/licenses/>.
Contact Information
OpenAirInterface Admin: openair_admin@eurecom.fr
OpenAirInterface Tech : openair_tech@eurecom.fr
OpenAirInterface Dev : openair4g-devel@eurecom.fr
Address : Eurecom, Compus SophiaTech 450, route des chappes, 06451 Biot, France.
*******************************************************************************/
/*****************************************************************************
Source EsmStatus.c
Version 0.1
Date 2013/06/17
Product NAS stack
Subsystem EPS Session Management
Author Frederic Maurel
Description Defines the ESM status procedure executed by the Non-Access
Stratum.
ESM status procedure can be related to an EPS bearer context
or to a procedure transaction.
The purpose of the sending of the ESM STATUS message is to
report at any time certain error conditions detected upon
receipt of ESM protocol data. The ESM STATUS message can be
sent by both the MME and the UE.
*****************************************************************************/
#include "esm_proc.h"
#include "commonDef.h"
#include "nas_log.h"
#include "esm_cause.h"
#include "emm_sap.h"
/****************************************************************************/
/**************** E X T E R N A L D E F I N I T I O N S ****************/
/****************************************************************************/
/****************************************************************************/
/******************* L O C A L D E F I N I T I O N S *******************/
/****************************************************************************/
/****************************************************************************/
/****************** E X P O R T E D F U N C T I O N S ******************/
/****************************************************************************/
/****************************************************************************
** **
** Name: esm_proc_status_ind() **
** **
** Description: Processes received ESM status message. **
** **
** 3GPP TS 24.301, section 6.7 **
** Upon receiving ESM Status message the UE/MME shall take **
** different actions depending on the received ESM cause **
** value. **
** **
** Inputs: ueid: UE lower layer identifier **
** pti: Procedure transaction identity **
** ebi: EPS bearer identity **
** esm_cause: Received ESM cause code **
** failure **
** Others: None **
** **
** Outputs: esm_cause: Cause code returned upon ESM procedure **
** failure **
** Return: RETURNok, RETURNerror **
** Others: None **
** **
***************************************************************************/
int esm_proc_status_ind(
int pti, int ebi, int *esm_cause)
{
LOG_FUNC_IN;
int rc;
LOG_TRACE(INFO,"ESM-PROC - ESM status procedure requested (cause=%d)",
*esm_cause);
LOG_TRACE(DEBUG, "ESM-PROC - To be implemented");
switch (*esm_cause) {
case ESM_CAUSE_INVALID_EPS_BEARER_IDENTITY:
/*
* Abort any ongoing ESM procedure related to the received EPS
* bearer identity, stop any related timer, and deactivate the
* corresponding EPS bearer context locally
*/
/* TODO */
rc = RETURNok;
break;
case ESM_CAUSE_INVALID_PTI_VALUE:
/*
* Abort any ongoing ESM procedure related to the received PTI
* value and stop any related timer
*/
/* TODO */
rc = RETURNok;
break;
case ESM_CAUSE_MESSAGE_TYPE_NOT_IMPLEMENTED:
/*
* Abort any ongoing ESM procedure related to the PTI or
* EPS bearer identity and stop any related timer
*/
/* TODO */
rc = RETURNok;
break;
default:
/*
* No state transition and no specific action shall be taken;
* local actions are possible
*/
/* TODO */
rc = RETURNok;
break;
}
LOG_FUNC_RETURN (rc);
}
/****************************************************************************
** **
** Name: esm_proc_status() **
** **
** Description: Initiates ESM status procedure. **
** **
** Inputs: is_standalone: Not used - Always TRUE **
** ueid: UE lower layer identifier **
** ebi: Not used **
** msg: Encoded ESM status message to be sent **
** ue_triggered: Not used **
** Others: None **
** **
** Outputs: None **
** Return: RETURNok, RETURNerror **
** Others: None **
** **
***************************************************************************/
int esm_proc_status(int is_standalone,
int ebi, OctetString *msg,
int ue_triggered)
{
LOG_FUNC_IN;
int rc;
emm_sap_t emm_sap;
LOG_TRACE(INFO,"ESM-PROC - ESM status procedure requested");
/*
* Notity EMM that ESM PDU has to be forwarded to lower layers
*/
emm_sap.primitive = EMMESM_UNITDATA_REQ;
emm_sap.u.emm_esm.ueid = 0;
emm_sap.u.emm_esm.u.data.msg.length = msg->length;
emm_sap.u.emm_esm.u.data.msg.value = msg->value;
rc = emm_sap_send(&emm_sap);
LOG_FUNC_RETURN (rc);
}
/****************************************************************************/
/********************* L O C A L F U N C T I O N S *********************/
/****************************************************************************/
| gpl-3.0 |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/content/browser/android/content_view_statics.cc | 4753 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <jni.h>
#include <vector>
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "content/browser/android/content_view_statics.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/common/android/address_parser.h"
#include "content/common/view_messages.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_process_host_observer.h"
#include "jni/ContentViewStatics_jni.h"
using base::android::ConvertJavaStringToUTF16;
using base::android::ConvertUTF16ToJavaString;
using base::android::JavaParamRef;
using base::android::ScopedJavaLocalRef;
namespace {
// TODO(pliard): http://crbug.com/235909. Move WebKit shared timer toggling
// functionality out of ContentViewStatistics and not be build on top of
// blink::Platform::SuspendSharedTimer.
// TODO(pliard): http://crbug.com/235912. Add unit tests for WebKit shared timer
// toggling.
// This tracks the renderer processes that received a suspend request. It's
// important on resume to only resume the renderer processes that were actually
// suspended as opposed to all the current renderer processes because the
// suspend calls are refcounted within BlinkPlatformImpl and it expects a
// perfectly matched number of resume calls.
// Note that this class is only accessed from the UI thread.
class SuspendedProcessWatcher : public content::RenderProcessHostObserver {
public:
// If the process crashes, stop watching the corresponding RenderProcessHost
// and ensure it doesn't get over-resumed.
void RenderProcessExited(content::RenderProcessHost* host,
base::TerminationStatus status,
int exit_code) override {
StopWatching(host);
}
void RenderProcessHostDestroyed(content::RenderProcessHost* host) override {
StopWatching(host);
}
// Suspends timers in all current render processes.
void SuspendWebKitSharedTimers() {
DCHECK(suspended_processes_.empty());
for (content::RenderProcessHost::iterator i(
content::RenderProcessHost::AllHostsIterator());
!i.IsAtEnd(); i.Advance()) {
content::RenderProcessHost* host = i.GetCurrentValue();
host->AddObserver(this);
host->GetRendererInterface()->SetWebKitSharedTimersSuspended(true);
suspended_processes_.push_back(host->GetID());
}
}
// Resumes timers in processes that were previously stopped.
void ResumeWebkitSharedTimers() {
for (std::vector<int>::const_iterator it = suspended_processes_.begin();
it != suspended_processes_.end(); ++it) {
content::RenderProcessHost* host =
content::RenderProcessHost::FromID(*it);
DCHECK(host);
host->RemoveObserver(this);
host->GetRendererInterface()->SetWebKitSharedTimersSuspended(false);
}
suspended_processes_.clear();
}
private:
void StopWatching(content::RenderProcessHost* host) {
std::vector<int>::iterator pos = std::find(suspended_processes_.begin(),
suspended_processes_.end(),
host->GetID());
DCHECK(pos != suspended_processes_.end());
host->RemoveObserver(this);
suspended_processes_.erase(pos);
}
std::vector<int /* RenderProcessHost id */> suspended_processes_;
};
base::LazyInstance<SuspendedProcessWatcher> g_suspended_processes_watcher =
LAZY_INSTANCE_INITIALIZER;
} // namespace
// Returns the first substring consisting of the address of a physical location.
static ScopedJavaLocalRef<jstring> FindAddress(
JNIEnv* env,
const JavaParamRef<jclass>& clazz,
const JavaParamRef<jstring>& addr) {
base::string16 content_16 = ConvertJavaStringToUTF16(env, addr);
base::string16 result_16;
if (content::address_parser::FindAddress(content_16, &result_16))
return ConvertUTF16ToJavaString(env, result_16);
return ScopedJavaLocalRef<jstring>();
}
static void SetWebKitSharedTimersSuspended(JNIEnv* env,
const JavaParamRef<jclass>& obj,
jboolean suspend) {
if (suspend) {
g_suspended_processes_watcher.Pointer()->SuspendWebKitSharedTimers();
} else {
g_suspended_processes_watcher.Pointer()->ResumeWebkitSharedTimers();
}
}
namespace content {
bool RegisterWebViewStatics(JNIEnv* env) {
return RegisterNativesImpl(env);
}
} // namespace content
| gpl-3.0 |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/net/data/verify_certificate_chain_unittest/generate-unconstrained-non-self-signed-root.py | 1019 | #!/usr/bin/python
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Certificate chain with 1 intermediate and a non-self-signed trust anchor.
Verification should succeed, it doesn't matter that the root was not
self-signed if it is designated as the trust anchor."""
import common
uber_root = common.create_self_signed_root_certificate('UberRoot')
# Non-self-signed root certificate (used as trust anchor)
root = common.create_intermediate_certificate('Root', uber_root)
# Intermediate certificate.
intermediate = common.create_intermediate_certificate('Intermediate', root)
# Target certificate.
target = common.create_end_entity_certificate('Target', intermediate)
chain = [target, intermediate]
trusted = common.TrustAnchor(root, constrained=False)
time = common.DEFAULT_TIME
verify_result = True
errors = None
common.write_test_file(__doc__, chain, trusted, time, verify_result, errors)
| gpl-3.0 |
Aghosh993/TARS_codebase | libopencm3/doc/sam3x/html/search/defines_7.js | 132 | var searchData=
[
['matrix_5fbase',['MATRIX_BASE',['../memorymap_8h.html#a096dcc80deb3676aeb5d5b8db13cfeba',1,'memorymap.h']]]
];
| gpl-3.0 |
marcoarruda/MissionPlanner | ExtLibs/Grid/GridUI.Designer.cs | 60645 | namespace MissionPlanner
{
partial class GridUI
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GridUI));
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.lbl_turnrad = new System.Windows.Forms.Label();
this.label36 = new System.Windows.Forms.Label();
this.lbl_photoevery = new System.Windows.Forms.Label();
this.label35 = new System.Windows.Forms.Label();
this.lbl_flighttime = new System.Windows.Forms.Label();
this.label31 = new System.Windows.Forms.Label();
this.lbl_distbetweenlines = new System.Windows.Forms.Label();
this.label25 = new System.Windows.Forms.Label();
this.lbl_footprint = new System.Windows.Forms.Label();
this.label30 = new System.Windows.Forms.Label();
this.lbl_strips = new System.Windows.Forms.Label();
this.lbl_pictures = new System.Windows.Forms.Label();
this.label33 = new System.Windows.Forms.Label();
this.label34 = new System.Windows.Forms.Label();
this.lbl_grndres = new System.Windows.Forms.Label();
this.label29 = new System.Windows.Forms.Label();
this.lbl_spacing = new System.Windows.Forms.Label();
this.label27 = new System.Windows.Forms.Label();
this.lbl_distance = new System.Windows.Forms.Label();
this.lbl_area = new System.Windows.Forms.Label();
this.label23 = new System.Windows.Forms.Label();
this.label22 = new System.Windows.Forms.Label();
this.tabCamera = new System.Windows.Forms.TabPage();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.label18 = new System.Windows.Forms.Label();
this.label17 = new System.Windows.Forms.Label();
this.label16 = new System.Windows.Forms.Label();
this.NUM_repttime = new System.Windows.Forms.NumericUpDown();
this.num_reptpwm = new System.Windows.Forms.NumericUpDown();
this.NUM_reptservo = new System.Windows.Forms.NumericUpDown();
this.rad_digicam = new System.Windows.Forms.RadioButton();
this.rad_repeatservo = new System.Windows.Forms.RadioButton();
this.rad_trigdist = new System.Windows.Forms.RadioButton();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.BUT_samplephoto = new MissionPlanner.Controls.MyButton();
this.label21 = new System.Windows.Forms.Label();
this.label19 = new System.Windows.Forms.Label();
this.label20 = new System.Windows.Forms.Label();
this.TXT_fovV = new System.Windows.Forms.TextBox();
this.TXT_fovH = new System.Windows.Forms.TextBox();
this.label12 = new System.Windows.Forms.Label();
this.TXT_cmpixel = new System.Windows.Forms.TextBox();
this.TXT_sensheight = new System.Windows.Forms.TextBox();
this.TXT_senswidth = new System.Windows.Forms.TextBox();
this.TXT_imgheight = new System.Windows.Forms.TextBox();
this.TXT_imgwidth = new System.Windows.Forms.TextBox();
this.NUM_focallength = new System.Windows.Forms.NumericUpDown();
this.label9 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.BUT_save = new MissionPlanner.Controls.MyButton();
this.tabGrid = new System.Windows.Forms.TabPage();
this.groupBox7 = new System.Windows.Forms.GroupBox();
this.LBL_Alternating_lanes = new System.Windows.Forms.Label();
this.LBL_Lane_Dist = new System.Windows.Forms.Label();
this.NUM_Lane_Dist = new System.Windows.Forms.NumericUpDown();
this.label28 = new System.Windows.Forms.Label();
this.groupBox_copter = new System.Windows.Forms.GroupBox();
this.TXT_headinghold = new System.Windows.Forms.TextBox();
this.BUT_headingholdminus = new System.Windows.Forms.Button();
this.BUT_headingholdplus = new System.Windows.Forms.Button();
this.CHK_copter_headingholdlock = new System.Windows.Forms.CheckBox();
this.CHK_copter_headinghold = new System.Windows.Forms.CheckBox();
this.LBL_copter_delay = new System.Windows.Forms.Label();
this.NUM_copter_delay = new System.Windows.Forms.NumericUpDown();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label32 = new System.Windows.Forms.Label();
this.NUM_leadin = new System.Windows.Forms.NumericUpDown();
this.label3 = new System.Windows.Forms.Label();
this.NUM_spacing = new System.Windows.Forms.NumericUpDown();
this.label7 = new System.Windows.Forms.Label();
this.NUM_overshoot2 = new System.Windows.Forms.NumericUpDown();
this.label8 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label15 = new System.Windows.Forms.Label();
this.CMB_startfrom = new System.Windows.Forms.ComboBox();
this.num_overlap = new System.Windows.Forms.NumericUpDown();
this.num_sidelap = new System.Windows.Forms.NumericUpDown();
this.label5 = new System.Windows.Forms.Label();
this.NUM_overshoot = new System.Windows.Forms.NumericUpDown();
this.label2 = new System.Windows.Forms.Label();
this.NUM_Distance = new System.Windows.Forms.NumericUpDown();
this.tabSimple = new System.Windows.Forms.TabPage();
this.groupBox6 = new System.Windows.Forms.GroupBox();
this.label37 = new System.Windows.Forms.Label();
this.NUM_split = new System.Windows.Forms.NumericUpDown();
this.CHK_usespeed = new System.Windows.Forms.CheckBox();
this.CHK_toandland_RTL = new System.Windows.Forms.CheckBox();
this.CHK_toandland = new System.Windows.Forms.CheckBox();
this.label24 = new System.Windows.Forms.Label();
this.NUM_UpDownFlySpeed = new System.Windows.Forms.NumericUpDown();
this.label26 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.NUM_angle = new System.Windows.Forms.NumericUpDown();
this.CMB_camera = new System.Windows.Forms.ComboBox();
this.CHK_camdirection = new System.Windows.Forms.CheckBox();
this.NUM_altitude = new System.Windows.Forms.NumericUpDown();
this.label1 = new System.Windows.Forms.Label();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.CHK_advanced = new System.Windows.Forms.CheckBox();
this.CHK_footprints = new System.Windows.Forms.CheckBox();
this.CHK_internals = new System.Windows.Forms.CheckBox();
this.CHK_grid = new System.Windows.Forms.CheckBox();
this.CHK_markers = new System.Windows.Forms.CheckBox();
this.CHK_boundary = new System.Windows.Forms.CheckBox();
this.BUT_Accept = new MissionPlanner.Controls.MyButton();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.map = new MissionPlanner.Controls.myGMAP();
this.TRK_zoom = new MissionPlanner.Controls.MyTrackBar();
this.groupBox5.SuspendLayout();
this.tabCamera.SuspendLayout();
this.groupBox3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.NUM_repttime)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.num_reptpwm)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_reptservo)).BeginInit();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.NUM_focallength)).BeginInit();
this.tabGrid.SuspendLayout();
this.groupBox7.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.NUM_Lane_Dist)).BeginInit();
this.groupBox_copter.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.NUM_copter_delay)).BeginInit();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.NUM_leadin)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_spacing)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_overshoot2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.num_overlap)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.num_sidelap)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_overshoot)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_Distance)).BeginInit();
this.tabSimple.SuspendLayout();
this.groupBox6.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.NUM_split)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_UpDownFlySpeed)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_angle)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_altitude)).BeginInit();
this.groupBox4.SuspendLayout();
this.tabControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.TRK_zoom)).BeginInit();
this.SuspendLayout();
//
// groupBox5
//
this.groupBox5.Controls.Add(this.lbl_turnrad);
this.groupBox5.Controls.Add(this.label36);
this.groupBox5.Controls.Add(this.lbl_photoevery);
this.groupBox5.Controls.Add(this.label35);
this.groupBox5.Controls.Add(this.lbl_flighttime);
this.groupBox5.Controls.Add(this.label31);
this.groupBox5.Controls.Add(this.lbl_distbetweenlines);
this.groupBox5.Controls.Add(this.label25);
this.groupBox5.Controls.Add(this.lbl_footprint);
this.groupBox5.Controls.Add(this.label30);
this.groupBox5.Controls.Add(this.lbl_strips);
this.groupBox5.Controls.Add(this.lbl_pictures);
this.groupBox5.Controls.Add(this.label33);
this.groupBox5.Controls.Add(this.label34);
this.groupBox5.Controls.Add(this.lbl_grndres);
this.groupBox5.Controls.Add(this.label29);
this.groupBox5.Controls.Add(this.lbl_spacing);
this.groupBox5.Controls.Add(this.label27);
this.groupBox5.Controls.Add(this.lbl_distance);
this.groupBox5.Controls.Add(this.lbl_area);
this.groupBox5.Controls.Add(this.label23);
this.groupBox5.Controls.Add(this.label22);
resources.ApplyResources(this.groupBox5, "groupBox5");
this.groupBox5.Name = "groupBox5";
this.groupBox5.TabStop = false;
//
// lbl_turnrad
//
resources.ApplyResources(this.lbl_turnrad, "lbl_turnrad");
this.lbl_turnrad.Name = "lbl_turnrad";
//
// label36
//
resources.ApplyResources(this.label36, "label36");
this.label36.Name = "label36";
//
// lbl_photoevery
//
resources.ApplyResources(this.lbl_photoevery, "lbl_photoevery");
this.lbl_photoevery.Name = "lbl_photoevery";
//
// label35
//
resources.ApplyResources(this.label35, "label35");
this.label35.Name = "label35";
//
// lbl_flighttime
//
resources.ApplyResources(this.lbl_flighttime, "lbl_flighttime");
this.lbl_flighttime.Name = "lbl_flighttime";
//
// label31
//
resources.ApplyResources(this.label31, "label31");
this.label31.Name = "label31";
//
// lbl_distbetweenlines
//
resources.ApplyResources(this.lbl_distbetweenlines, "lbl_distbetweenlines");
this.lbl_distbetweenlines.Name = "lbl_distbetweenlines";
//
// label25
//
resources.ApplyResources(this.label25, "label25");
this.label25.Name = "label25";
//
// lbl_footprint
//
resources.ApplyResources(this.lbl_footprint, "lbl_footprint");
this.lbl_footprint.Name = "lbl_footprint";
//
// label30
//
resources.ApplyResources(this.label30, "label30");
this.label30.Name = "label30";
//
// lbl_strips
//
resources.ApplyResources(this.lbl_strips, "lbl_strips");
this.lbl_strips.Name = "lbl_strips";
//
// lbl_pictures
//
resources.ApplyResources(this.lbl_pictures, "lbl_pictures");
this.lbl_pictures.Name = "lbl_pictures";
//
// label33
//
resources.ApplyResources(this.label33, "label33");
this.label33.Name = "label33";
//
// label34
//
resources.ApplyResources(this.label34, "label34");
this.label34.Name = "label34";
//
// lbl_grndres
//
resources.ApplyResources(this.lbl_grndres, "lbl_grndres");
this.lbl_grndres.Name = "lbl_grndres";
//
// label29
//
resources.ApplyResources(this.label29, "label29");
this.label29.Name = "label29";
//
// lbl_spacing
//
resources.ApplyResources(this.lbl_spacing, "lbl_spacing");
this.lbl_spacing.Name = "lbl_spacing";
//
// label27
//
resources.ApplyResources(this.label27, "label27");
this.label27.Name = "label27";
//
// lbl_distance
//
resources.ApplyResources(this.lbl_distance, "lbl_distance");
this.lbl_distance.Name = "lbl_distance";
//
// lbl_area
//
resources.ApplyResources(this.lbl_area, "lbl_area");
this.lbl_area.Name = "lbl_area";
//
// label23
//
resources.ApplyResources(this.label23, "label23");
this.label23.Name = "label23";
//
// label22
//
resources.ApplyResources(this.label22, "label22");
this.label22.Name = "label22";
//
// tabCamera
//
this.tabCamera.Controls.Add(this.groupBox3);
this.tabCamera.Controls.Add(this.groupBox2);
resources.ApplyResources(this.tabCamera, "tabCamera");
this.tabCamera.Name = "tabCamera";
this.tabCamera.UseVisualStyleBackColor = true;
//
// groupBox3
//
this.groupBox3.Controls.Add(this.label18);
this.groupBox3.Controls.Add(this.label17);
this.groupBox3.Controls.Add(this.label16);
this.groupBox3.Controls.Add(this.NUM_repttime);
this.groupBox3.Controls.Add(this.num_reptpwm);
this.groupBox3.Controls.Add(this.NUM_reptservo);
this.groupBox3.Controls.Add(this.rad_digicam);
this.groupBox3.Controls.Add(this.rad_repeatservo);
this.groupBox3.Controls.Add(this.rad_trigdist);
resources.ApplyResources(this.groupBox3, "groupBox3");
this.groupBox3.Name = "groupBox3";
this.groupBox3.TabStop = false;
//
// label18
//
resources.ApplyResources(this.label18, "label18");
this.label18.Name = "label18";
//
// label17
//
resources.ApplyResources(this.label17, "label17");
this.label17.Name = "label17";
//
// label16
//
resources.ApplyResources(this.label16, "label16");
this.label16.Name = "label16";
//
// NUM_repttime
//
resources.ApplyResources(this.NUM_repttime, "NUM_repttime");
this.NUM_repttime.Maximum = new decimal(new int[] {
5000,
0,
0,
0});
this.NUM_repttime.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.NUM_repttime.Name = "NUM_repttime";
this.NUM_repttime.Value = new decimal(new int[] {
2,
0,
0,
0});
//
// num_reptpwm
//
resources.ApplyResources(this.num_reptpwm, "num_reptpwm");
this.num_reptpwm.Maximum = new decimal(new int[] {
5000,
0,
0,
0});
this.num_reptpwm.Name = "num_reptpwm";
this.num_reptpwm.Value = new decimal(new int[] {
1100,
0,
0,
0});
//
// NUM_reptservo
//
resources.ApplyResources(this.NUM_reptservo, "NUM_reptservo");
this.NUM_reptservo.Maximum = new decimal(new int[] {
12,
0,
0,
0});
this.NUM_reptservo.Minimum = new decimal(new int[] {
5,
0,
0,
0});
this.NUM_reptservo.Name = "NUM_reptservo";
this.NUM_reptservo.Value = new decimal(new int[] {
5,
0,
0,
0});
//
// rad_digicam
//
resources.ApplyResources(this.rad_digicam, "rad_digicam");
this.rad_digicam.Name = "rad_digicam";
this.rad_digicam.Tag = "";
this.rad_digicam.UseVisualStyleBackColor = true;
//
// rad_repeatservo
//
resources.ApplyResources(this.rad_repeatservo, "rad_repeatservo");
this.rad_repeatservo.Name = "rad_repeatservo";
this.rad_repeatservo.Tag = "";
this.rad_repeatservo.UseVisualStyleBackColor = true;
//
// rad_trigdist
//
resources.ApplyResources(this.rad_trigdist, "rad_trigdist");
this.rad_trigdist.Checked = true;
this.rad_trigdist.Name = "rad_trigdist";
this.rad_trigdist.TabStop = true;
this.rad_trigdist.Tag = "";
this.rad_trigdist.UseVisualStyleBackColor = true;
//
// groupBox2
//
resources.ApplyResources(this.groupBox2, "groupBox2");
this.groupBox2.Controls.Add(this.BUT_samplephoto);
this.groupBox2.Controls.Add(this.label21);
this.groupBox2.Controls.Add(this.label19);
this.groupBox2.Controls.Add(this.label20);
this.groupBox2.Controls.Add(this.TXT_fovV);
this.groupBox2.Controls.Add(this.TXT_fovH);
this.groupBox2.Controls.Add(this.label12);
this.groupBox2.Controls.Add(this.TXT_cmpixel);
this.groupBox2.Controls.Add(this.TXT_sensheight);
this.groupBox2.Controls.Add(this.TXT_senswidth);
this.groupBox2.Controls.Add(this.TXT_imgheight);
this.groupBox2.Controls.Add(this.TXT_imgwidth);
this.groupBox2.Controls.Add(this.NUM_focallength);
this.groupBox2.Controls.Add(this.label9);
this.groupBox2.Controls.Add(this.label10);
this.groupBox2.Controls.Add(this.label14);
this.groupBox2.Controls.Add(this.label13);
this.groupBox2.Controls.Add(this.label11);
this.groupBox2.Controls.Add(this.BUT_save);
this.groupBox2.Name = "groupBox2";
this.groupBox2.TabStop = false;
//
// BUT_samplephoto
//
resources.ApplyResources(this.BUT_samplephoto, "BUT_samplephoto");
this.BUT_samplephoto.Name = "BUT_samplephoto";
this.BUT_samplephoto.UseVisualStyleBackColor = true;
this.BUT_samplephoto.Click += new System.EventHandler(this.BUT_samplephoto_Click);
//
// label21
//
resources.ApplyResources(this.label21, "label21");
this.label21.Name = "label21";
//
// label19
//
resources.ApplyResources(this.label19, "label19");
this.label19.Name = "label19";
//
// label20
//
resources.ApplyResources(this.label20, "label20");
this.label20.Name = "label20";
//
// TXT_fovV
//
resources.ApplyResources(this.TXT_fovV, "TXT_fovV");
this.TXT_fovV.Name = "TXT_fovV";
//
// TXT_fovH
//
resources.ApplyResources(this.TXT_fovH, "TXT_fovH");
this.TXT_fovH.Name = "TXT_fovH";
//
// label12
//
resources.ApplyResources(this.label12, "label12");
this.label12.Name = "label12";
//
// TXT_cmpixel
//
resources.ApplyResources(this.TXT_cmpixel, "TXT_cmpixel");
this.TXT_cmpixel.Name = "TXT_cmpixel";
//
// TXT_sensheight
//
resources.ApplyResources(this.TXT_sensheight, "TXT_sensheight");
this.TXT_sensheight.Name = "TXT_sensheight";
this.TXT_sensheight.TextChanged += new System.EventHandler(this.TXT_TextChanged);
//
// TXT_senswidth
//
resources.ApplyResources(this.TXT_senswidth, "TXT_senswidth");
this.TXT_senswidth.Name = "TXT_senswidth";
this.TXT_senswidth.TextChanged += new System.EventHandler(this.TXT_TextChanged);
//
// TXT_imgheight
//
resources.ApplyResources(this.TXT_imgheight, "TXT_imgheight");
this.TXT_imgheight.Name = "TXT_imgheight";
this.TXT_imgheight.TextChanged += new System.EventHandler(this.TXT_TextChanged);
//
// TXT_imgwidth
//
resources.ApplyResources(this.TXT_imgwidth, "TXT_imgwidth");
this.TXT_imgwidth.Name = "TXT_imgwidth";
this.TXT_imgwidth.TextChanged += new System.EventHandler(this.TXT_TextChanged);
//
// NUM_focallength
//
this.NUM_focallength.DecimalPlaces = 1;
this.NUM_focallength.Increment = new decimal(new int[] {
1,
0,
0,
65536});
resources.ApplyResources(this.NUM_focallength, "NUM_focallength");
this.NUM_focallength.Maximum = new decimal(new int[] {
180,
0,
0,
0});
this.NUM_focallength.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.NUM_focallength.Name = "NUM_focallength";
this.NUM_focallength.Value = new decimal(new int[] {
5,
0,
0,
0});
this.NUM_focallength.ValueChanged += new System.EventHandler(this.NUM_ValueChanged);
//
// label9
//
resources.ApplyResources(this.label9, "label9");
this.label9.Name = "label9";
//
// label10
//
resources.ApplyResources(this.label10, "label10");
this.label10.Name = "label10";
//
// label14
//
resources.ApplyResources(this.label14, "label14");
this.label14.Name = "label14";
//
// label13
//
resources.ApplyResources(this.label13, "label13");
this.label13.Name = "label13";
//
// label11
//
resources.ApplyResources(this.label11, "label11");
this.label11.Name = "label11";
//
// BUT_save
//
resources.ApplyResources(this.BUT_save, "BUT_save");
this.BUT_save.Name = "BUT_save";
this.BUT_save.UseVisualStyleBackColor = true;
this.BUT_save.Click += new System.EventHandler(this.BUT_save_Click);
//
// tabGrid
//
this.tabGrid.Controls.Add(this.groupBox7);
this.tabGrid.Controls.Add(this.groupBox_copter);
this.tabGrid.Controls.Add(this.groupBox1);
resources.ApplyResources(this.tabGrid, "tabGrid");
this.tabGrid.Name = "tabGrid";
this.tabGrid.UseVisualStyleBackColor = true;
//
// groupBox7
//
resources.ApplyResources(this.groupBox7, "groupBox7");
this.groupBox7.Controls.Add(this.LBL_Alternating_lanes);
this.groupBox7.Controls.Add(this.LBL_Lane_Dist);
this.groupBox7.Controls.Add(this.NUM_Lane_Dist);
this.groupBox7.Controls.Add(this.label28);
this.groupBox7.Name = "groupBox7";
this.groupBox7.TabStop = false;
//
// LBL_Alternating_lanes
//
resources.ApplyResources(this.LBL_Alternating_lanes, "LBL_Alternating_lanes");
this.LBL_Alternating_lanes.Name = "LBL_Alternating_lanes";
//
// LBL_Lane_Dist
//
resources.ApplyResources(this.LBL_Lane_Dist, "LBL_Lane_Dist");
this.LBL_Lane_Dist.Name = "LBL_Lane_Dist";
//
// NUM_Lane_Dist
//
resources.ApplyResources(this.NUM_Lane_Dist, "NUM_Lane_Dist");
this.NUM_Lane_Dist.Maximum = new decimal(new int[] {
9999,
0,
0,
0});
this.NUM_Lane_Dist.Name = "NUM_Lane_Dist";
this.NUM_Lane_Dist.ValueChanged += new System.EventHandler(this.NUM_Lane_Dist_ValueChanged);
//
// label28
//
resources.ApplyResources(this.label28, "label28");
this.label28.Name = "label28";
//
// groupBox_copter
//
resources.ApplyResources(this.groupBox_copter, "groupBox_copter");
this.groupBox_copter.Controls.Add(this.TXT_headinghold);
this.groupBox_copter.Controls.Add(this.BUT_headingholdminus);
this.groupBox_copter.Controls.Add(this.BUT_headingholdplus);
this.groupBox_copter.Controls.Add(this.CHK_copter_headingholdlock);
this.groupBox_copter.Controls.Add(this.CHK_copter_headinghold);
this.groupBox_copter.Controls.Add(this.LBL_copter_delay);
this.groupBox_copter.Controls.Add(this.NUM_copter_delay);
this.groupBox_copter.Name = "groupBox_copter";
this.groupBox_copter.TabStop = false;
//
// TXT_headinghold
//
resources.ApplyResources(this.TXT_headinghold, "TXT_headinghold");
this.TXT_headinghold.Name = "TXT_headinghold";
this.TXT_headinghold.ReadOnly = true;
//
// BUT_headingholdminus
//
resources.ApplyResources(this.BUT_headingholdminus, "BUT_headingholdminus");
this.BUT_headingholdminus.Name = "BUT_headingholdminus";
this.BUT_headingholdminus.UseVisualStyleBackColor = true;
this.BUT_headingholdminus.Click += new System.EventHandler(this.BUT_headingholdminus_Click);
//
// BUT_headingholdplus
//
resources.ApplyResources(this.BUT_headingholdplus, "BUT_headingholdplus");
this.BUT_headingholdplus.Name = "BUT_headingholdplus";
this.BUT_headingholdplus.UseVisualStyleBackColor = true;
this.BUT_headingholdplus.Click += new System.EventHandler(this.BUT_headingholdplus_Click);
//
// CHK_copter_headingholdlock
//
resources.ApplyResources(this.CHK_copter_headingholdlock, "CHK_copter_headingholdlock");
this.CHK_copter_headingholdlock.Name = "CHK_copter_headingholdlock";
this.CHK_copter_headingholdlock.UseVisualStyleBackColor = true;
this.CHK_copter_headingholdlock.CheckedChanged += new System.EventHandler(this.CHK_copter_headingholdlock_CheckedChanged);
//
// CHK_copter_headinghold
//
resources.ApplyResources(this.CHK_copter_headinghold, "CHK_copter_headinghold");
this.CHK_copter_headinghold.Name = "CHK_copter_headinghold";
this.CHK_copter_headinghold.UseVisualStyleBackColor = true;
this.CHK_copter_headinghold.CheckedChanged += new System.EventHandler(this.CHK_copter_headinghold_CheckedChanged);
//
// LBL_copter_delay
//
resources.ApplyResources(this.LBL_copter_delay, "LBL_copter_delay");
this.LBL_copter_delay.Name = "LBL_copter_delay";
//
// NUM_copter_delay
//
this.NUM_copter_delay.DecimalPlaces = 1;
this.NUM_copter_delay.Increment = new decimal(new int[] {
1,
0,
0,
65536});
resources.ApplyResources(this.NUM_copter_delay, "NUM_copter_delay");
this.NUM_copter_delay.Maximum = new decimal(new int[] {
9999,
0,
0,
0});
this.NUM_copter_delay.Name = "NUM_copter_delay";
//
// groupBox1
//
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Controls.Add(this.label32);
this.groupBox1.Controls.Add(this.NUM_leadin);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.NUM_spacing);
this.groupBox1.Controls.Add(this.label7);
this.groupBox1.Controls.Add(this.NUM_overshoot2);
this.groupBox1.Controls.Add(this.label8);
this.groupBox1.Controls.Add(this.label6);
this.groupBox1.Controls.Add(this.label15);
this.groupBox1.Controls.Add(this.CMB_startfrom);
this.groupBox1.Controls.Add(this.num_overlap);
this.groupBox1.Controls.Add(this.num_sidelap);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.NUM_overshoot);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.NUM_Distance);
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// label32
//
resources.ApplyResources(this.label32, "label32");
this.label32.Name = "label32";
//
// NUM_leadin
//
resources.ApplyResources(this.NUM_leadin, "NUM_leadin");
this.NUM_leadin.Maximum = new decimal(new int[] {
9999,
0,
0,
0});
this.NUM_leadin.Name = "NUM_leadin";
this.NUM_leadin.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// NUM_spacing
//
resources.ApplyResources(this.NUM_spacing, "NUM_spacing");
this.NUM_spacing.Maximum = new decimal(new int[] {
5000,
0,
0,
0});
this.NUM_spacing.Name = "NUM_spacing";
this.NUM_spacing.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// label7
//
resources.ApplyResources(this.label7, "label7");
this.label7.Name = "label7";
//
// NUM_overshoot2
//
resources.ApplyResources(this.NUM_overshoot2, "NUM_overshoot2");
this.NUM_overshoot2.Maximum = new decimal(new int[] {
9999,
0,
0,
0});
this.NUM_overshoot2.Name = "NUM_overshoot2";
this.NUM_overshoot2.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// label8
//
resources.ApplyResources(this.label8, "label8");
this.label8.Name = "label8";
//
// label6
//
resources.ApplyResources(this.label6, "label6");
this.label6.Name = "label6";
//
// label15
//
resources.ApplyResources(this.label15, "label15");
this.label15.Name = "label15";
//
// CMB_startfrom
//
this.CMB_startfrom.FormattingEnabled = true;
resources.ApplyResources(this.CMB_startfrom, "CMB_startfrom");
this.CMB_startfrom.Name = "CMB_startfrom";
this.CMB_startfrom.SelectedIndexChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// num_overlap
//
this.num_overlap.DecimalPlaces = 1;
resources.ApplyResources(this.num_overlap, "num_overlap");
this.num_overlap.Name = "num_overlap";
this.num_overlap.Value = new decimal(new int[] {
50,
0,
0,
0});
this.num_overlap.ValueChanged += new System.EventHandler(this.NUM_ValueChanged);
//
// num_sidelap
//
this.num_sidelap.DecimalPlaces = 1;
resources.ApplyResources(this.num_sidelap, "num_sidelap");
this.num_sidelap.Name = "num_sidelap";
this.num_sidelap.Value = new decimal(new int[] {
60,
0,
0,
0});
this.num_sidelap.ValueChanged += new System.EventHandler(this.NUM_ValueChanged);
//
// label5
//
resources.ApplyResources(this.label5, "label5");
this.label5.Name = "label5";
//
// NUM_overshoot
//
resources.ApplyResources(this.NUM_overshoot, "NUM_overshoot");
this.NUM_overshoot.Maximum = new decimal(new int[] {
9999,
0,
0,
0});
this.NUM_overshoot.Name = "NUM_overshoot";
this.NUM_overshoot.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// NUM_Distance
//
this.NUM_Distance.DecimalPlaces = 2;
resources.ApplyResources(this.NUM_Distance, "NUM_Distance");
this.NUM_Distance.Maximum = new decimal(new int[] {
9999,
0,
0,
0});
this.NUM_Distance.Minimum = new decimal(new int[] {
3,
0,
0,
65536});
this.NUM_Distance.Name = "NUM_Distance";
this.NUM_Distance.Value = new decimal(new int[] {
50,
0,
0,
0});
this.NUM_Distance.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// tabSimple
//
this.tabSimple.Controls.Add(this.groupBox6);
this.tabSimple.Controls.Add(this.groupBox4);
this.tabSimple.Controls.Add(this.BUT_Accept);
resources.ApplyResources(this.tabSimple, "tabSimple");
this.tabSimple.Name = "tabSimple";
this.tabSimple.UseVisualStyleBackColor = true;
//
// groupBox6
//
this.groupBox6.Controls.Add(this.label37);
this.groupBox6.Controls.Add(this.NUM_split);
this.groupBox6.Controls.Add(this.CHK_usespeed);
this.groupBox6.Controls.Add(this.CHK_toandland_RTL);
this.groupBox6.Controls.Add(this.CHK_toandland);
this.groupBox6.Controls.Add(this.label24);
this.groupBox6.Controls.Add(this.NUM_UpDownFlySpeed);
this.groupBox6.Controls.Add(this.label26);
this.groupBox6.Controls.Add(this.label4);
this.groupBox6.Controls.Add(this.NUM_angle);
this.groupBox6.Controls.Add(this.CMB_camera);
this.groupBox6.Controls.Add(this.CHK_camdirection);
this.groupBox6.Controls.Add(this.NUM_altitude);
this.groupBox6.Controls.Add(this.label1);
resources.ApplyResources(this.groupBox6, "groupBox6");
this.groupBox6.Name = "groupBox6";
this.groupBox6.TabStop = false;
//
// label37
//
resources.ApplyResources(this.label37, "label37");
this.label37.Name = "label37";
//
// NUM_split
//
resources.ApplyResources(this.NUM_split, "NUM_split");
this.NUM_split.Maximum = new decimal(new int[] {
300,
0,
0,
0});
this.NUM_split.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.NUM_split.Name = "NUM_split";
this.NUM_split.Value = new decimal(new int[] {
1,
0,
0,
0});
this.NUM_split.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// CHK_usespeed
//
resources.ApplyResources(this.CHK_usespeed, "CHK_usespeed");
this.CHK_usespeed.Name = "CHK_usespeed";
this.CHK_usespeed.UseVisualStyleBackColor = true;
//
// CHK_toandland_RTL
//
resources.ApplyResources(this.CHK_toandland_RTL, "CHK_toandland_RTL");
this.CHK_toandland_RTL.Checked = true;
this.CHK_toandland_RTL.CheckState = System.Windows.Forms.CheckState.Checked;
this.CHK_toandland_RTL.Name = "CHK_toandland_RTL";
this.CHK_toandland_RTL.UseVisualStyleBackColor = true;
//
// CHK_toandland
//
resources.ApplyResources(this.CHK_toandland, "CHK_toandland");
this.CHK_toandland.Checked = true;
this.CHK_toandland.CheckState = System.Windows.Forms.CheckState.Checked;
this.CHK_toandland.Name = "CHK_toandland";
this.CHK_toandland.UseVisualStyleBackColor = true;
//
// label24
//
resources.ApplyResources(this.label24, "label24");
this.label24.Name = "label24";
//
// NUM_UpDownFlySpeed
//
resources.ApplyResources(this.NUM_UpDownFlySpeed, "NUM_UpDownFlySpeed");
this.NUM_UpDownFlySpeed.Maximum = new decimal(new int[] {
360,
0,
0,
0});
this.NUM_UpDownFlySpeed.Name = "NUM_UpDownFlySpeed";
this.NUM_UpDownFlySpeed.Value = new decimal(new int[] {
5,
0,
0,
0});
this.NUM_UpDownFlySpeed.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// label26
//
resources.ApplyResources(this.label26, "label26");
this.label26.Name = "label26";
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// NUM_angle
//
resources.ApplyResources(this.NUM_angle, "NUM_angle");
this.NUM_angle.Maximum = new decimal(new int[] {
360,
0,
0,
0});
this.NUM_angle.Name = "NUM_angle";
this.NUM_angle.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// CMB_camera
//
this.CMB_camera.FormattingEnabled = true;
resources.ApplyResources(this.CMB_camera, "CMB_camera");
this.CMB_camera.Name = "CMB_camera";
this.CMB_camera.SelectedIndexChanged += new System.EventHandler(this.CMB_camera_SelectedIndexChanged);
//
// CHK_camdirection
//
resources.ApplyResources(this.CHK_camdirection, "CHK_camdirection");
this.CHK_camdirection.Checked = true;
this.CHK_camdirection.CheckState = System.Windows.Forms.CheckState.Checked;
this.CHK_camdirection.Name = "CHK_camdirection";
this.CHK_camdirection.UseVisualStyleBackColor = true;
this.CHK_camdirection.CheckedChanged += new System.EventHandler(this.CHK_camdirection_CheckedChanged);
//
// NUM_altitude
//
this.NUM_altitude.Increment = new decimal(new int[] {
10,
0,
0,
0});
resources.ApplyResources(this.NUM_altitude, "NUM_altitude");
this.NUM_altitude.Maximum = new decimal(new int[] {
9999,
0,
0,
0});
this.NUM_altitude.Minimum = new decimal(new int[] {
5,
0,
0,
0});
this.NUM_altitude.Name = "NUM_altitude";
this.NUM_altitude.Value = new decimal(new int[] {
100,
0,
0,
0});
this.NUM_altitude.ValueChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// groupBox4
//
this.groupBox4.Controls.Add(this.CHK_advanced);
this.groupBox4.Controls.Add(this.CHK_footprints);
this.groupBox4.Controls.Add(this.CHK_internals);
this.groupBox4.Controls.Add(this.CHK_grid);
this.groupBox4.Controls.Add(this.CHK_markers);
this.groupBox4.Controls.Add(this.CHK_boundary);
resources.ApplyResources(this.groupBox4, "groupBox4");
this.groupBox4.Name = "groupBox4";
this.groupBox4.TabStop = false;
//
// CHK_advanced
//
resources.ApplyResources(this.CHK_advanced, "CHK_advanced");
this.CHK_advanced.Name = "CHK_advanced";
this.CHK_advanced.UseVisualStyleBackColor = true;
this.CHK_advanced.CheckedChanged += new System.EventHandler(this.CHK_advanced_CheckedChanged);
//
// CHK_footprints
//
resources.ApplyResources(this.CHK_footprints, "CHK_footprints");
this.CHK_footprints.Name = "CHK_footprints";
this.CHK_footprints.UseVisualStyleBackColor = true;
this.CHK_footprints.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// CHK_internals
//
resources.ApplyResources(this.CHK_internals, "CHK_internals");
this.CHK_internals.Name = "CHK_internals";
this.CHK_internals.UseVisualStyleBackColor = true;
this.CHK_internals.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// CHK_grid
//
resources.ApplyResources(this.CHK_grid, "CHK_grid");
this.CHK_grid.Checked = true;
this.CHK_grid.CheckState = System.Windows.Forms.CheckState.Checked;
this.CHK_grid.Name = "CHK_grid";
this.CHK_grid.UseVisualStyleBackColor = true;
this.CHK_grid.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// CHK_markers
//
resources.ApplyResources(this.CHK_markers, "CHK_markers");
this.CHK_markers.Checked = true;
this.CHK_markers.CheckState = System.Windows.Forms.CheckState.Checked;
this.CHK_markers.Name = "CHK_markers";
this.CHK_markers.UseVisualStyleBackColor = true;
this.CHK_markers.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// CHK_boundary
//
resources.ApplyResources(this.CHK_boundary, "CHK_boundary");
this.CHK_boundary.Checked = true;
this.CHK_boundary.CheckState = System.Windows.Forms.CheckState.Checked;
this.CHK_boundary.Name = "CHK_boundary";
this.CHK_boundary.UseVisualStyleBackColor = true;
this.CHK_boundary.CheckedChanged += new System.EventHandler(this.domainUpDown1_ValueChanged);
//
// BUT_Accept
//
resources.ApplyResources(this.BUT_Accept, "BUT_Accept");
this.BUT_Accept.Name = "BUT_Accept";
this.BUT_Accept.UseVisualStyleBackColor = true;
this.BUT_Accept.Click += new System.EventHandler(this.BUT_Accept_Click);
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabSimple);
this.tabControl1.Controls.Add(this.tabGrid);
this.tabControl1.Controls.Add(this.tabCamera);
resources.ApplyResources(this.tabControl1, "tabControl1");
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
//
// map
//
resources.ApplyResources(this.map, "map");
this.map.Bearing = 0F;
this.map.CanDragMap = true;
this.map.EmptyTileColor = System.Drawing.Color.Gray;
this.map.GrayScaleMode = false;
this.map.HelperLineOption = GMap.NET.WindowsForms.HelperLineOptions.DontShow;
this.map.LevelsKeepInMemmory = 5;
this.map.MarkersEnabled = true;
this.map.MaxZoom = 19;
this.map.MinZoom = 2;
this.map.MouseWheelZoomType = GMap.NET.MouseWheelZoomType.MousePositionAndCenter;
this.map.Name = "map";
this.map.NegativeMode = false;
this.map.PolygonsEnabled = true;
this.map.RetryLoadTile = 0;
this.map.RoutesEnabled = true;
this.map.ScaleMode = GMap.NET.WindowsForms.ScaleModes.Fractional;
this.map.SelectedAreaFillColor = System.Drawing.Color.FromArgb(((int)(((byte)(33)))), ((int)(((byte)(65)))), ((int)(((byte)(105)))), ((int)(((byte)(225)))));
this.map.ShowTileGridLines = false;
this.map.Zoom = 3D;
this.map.MouseDown += new System.Windows.Forms.MouseEventHandler(this.map_MouseDown);
this.map.MouseMove += new System.Windows.Forms.MouseEventHandler(this.map_MouseMove);
//
// TRK_zoom
//
resources.ApplyResources(this.TRK_zoom, "TRK_zoom");
this.TRK_zoom.LargeChange = 0.005F;
this.TRK_zoom.Maximum = 19F;
this.TRK_zoom.Minimum = 2F;
this.TRK_zoom.Name = "TRK_zoom";
this.TRK_zoom.SmallChange = 0.001F;
this.TRK_zoom.TickFrequency = 1F;
this.TRK_zoom.TickStyle = System.Windows.Forms.TickStyle.TopLeft;
this.TRK_zoom.Value = 2F;
this.TRK_zoom.Scroll += new System.EventHandler(this.trackBar1_Scroll);
//
// GridUI
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
resources.ApplyResources(this, "$this");
this.Controls.Add(this.TRK_zoom);
this.Controls.Add(this.map);
this.Controls.Add(this.groupBox5);
this.Controls.Add(this.tabControl1);
this.Name = "GridUI";
this.Load += new System.EventHandler(this.GridUI_Load);
this.Resize += new System.EventHandler(this.GridUI_Resize);
this.groupBox5.ResumeLayout(false);
this.groupBox5.PerformLayout();
this.tabCamera.ResumeLayout(false);
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.NUM_repttime)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.num_reptpwm)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_reptservo)).EndInit();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.NUM_focallength)).EndInit();
this.tabGrid.ResumeLayout(false);
this.groupBox7.ResumeLayout(false);
this.groupBox7.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.NUM_Lane_Dist)).EndInit();
this.groupBox_copter.ResumeLayout(false);
this.groupBox_copter.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.NUM_copter_delay)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.NUM_leadin)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_spacing)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_overshoot2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.num_overlap)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.num_sidelap)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_overshoot)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_Distance)).EndInit();
this.tabSimple.ResumeLayout(false);
this.groupBox6.ResumeLayout(false);
this.groupBox6.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.NUM_split)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_UpDownFlySpeed)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_angle)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.NUM_altitude)).EndInit();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.tabControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.TRK_zoom)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Controls.myGMAP map;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.Label label22;
private System.Windows.Forms.Label label23;
private System.Windows.Forms.Label lbl_distance;
private System.Windows.Forms.Label lbl_area;
private System.Windows.Forms.Label lbl_spacing;
private System.Windows.Forms.Label label27;
private System.Windows.Forms.Label lbl_grndres;
private System.Windows.Forms.Label label29;
private System.Windows.Forms.Label lbl_distbetweenlines;
private System.Windows.Forms.Label label25;
private System.Windows.Forms.Label lbl_footprint;
private System.Windows.Forms.Label label30;
private System.Windows.Forms.Label lbl_strips;
private System.Windows.Forms.Label lbl_pictures;
private System.Windows.Forms.Label label33;
private System.Windows.Forms.Label label34;
private System.Windows.Forms.Label lbl_flighttime;
private System.Windows.Forms.Label label31;
private System.Windows.Forms.Label lbl_photoevery;
private System.Windows.Forms.Label label35;
private System.Windows.Forms.TabPage tabCamera;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Label label18;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.NumericUpDown NUM_repttime;
private System.Windows.Forms.NumericUpDown num_reptpwm;
private System.Windows.Forms.NumericUpDown NUM_reptservo;
private System.Windows.Forms.RadioButton rad_digicam;
private System.Windows.Forms.RadioButton rad_repeatservo;
private System.Windows.Forms.RadioButton rad_trigdist;
private System.Windows.Forms.GroupBox groupBox2;
private Controls.MyButton BUT_samplephoto;
private System.Windows.Forms.Label label21;
private System.Windows.Forms.Label label19;
private System.Windows.Forms.Label label20;
private System.Windows.Forms.TextBox TXT_fovV;
private System.Windows.Forms.TextBox TXT_fovH;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.TextBox TXT_cmpixel;
private System.Windows.Forms.TextBox TXT_sensheight;
private System.Windows.Forms.TextBox TXT_senswidth;
private System.Windows.Forms.TextBox TXT_imgheight;
private System.Windows.Forms.TextBox TXT_imgwidth;
private System.Windows.Forms.NumericUpDown NUM_focallength;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label11;
private Controls.MyButton BUT_save;
private System.Windows.Forms.TabPage tabGrid;
private System.Windows.Forms.GroupBox groupBox_copter;
private System.Windows.Forms.CheckBox CHK_copter_headinghold;
private System.Windows.Forms.Label LBL_copter_delay;
private System.Windows.Forms.NumericUpDown NUM_copter_delay;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.NumericUpDown NUM_spacing;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.NumericUpDown NUM_overshoot2;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.ComboBox CMB_startfrom;
private System.Windows.Forms.NumericUpDown num_overlap;
private System.Windows.Forms.NumericUpDown num_sidelap;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.NumericUpDown NUM_overshoot;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.NumericUpDown NUM_Distance;
private System.Windows.Forms.TabPage tabSimple;
private System.Windows.Forms.GroupBox groupBox6;
private System.Windows.Forms.CheckBox CHK_usespeed;
private System.Windows.Forms.CheckBox CHK_toandland_RTL;
private System.Windows.Forms.CheckBox CHK_toandland;
private System.Windows.Forms.Label label24;
private System.Windows.Forms.NumericUpDown NUM_UpDownFlySpeed;
private System.Windows.Forms.Label label26;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.NumericUpDown NUM_angle;
private System.Windows.Forms.ComboBox CMB_camera;
private System.Windows.Forms.CheckBox CHK_camdirection;
private System.Windows.Forms.NumericUpDown NUM_altitude;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.CheckBox CHK_advanced;
private System.Windows.Forms.CheckBox CHK_footprints;
private System.Windows.Forms.CheckBox CHK_internals;
private System.Windows.Forms.CheckBox CHK_grid;
private System.Windows.Forms.CheckBox CHK_markers;
private System.Windows.Forms.CheckBox CHK_boundary;
private Controls.MyButton BUT_Accept;
private System.Windows.Forms.TabControl tabControl1;
private Controls.MyTrackBar TRK_zoom;
private System.Windows.Forms.CheckBox CHK_copter_headingholdlock;
private System.Windows.Forms.TextBox TXT_headinghold;
private System.Windows.Forms.Button BUT_headingholdminus;
private System.Windows.Forms.Button BUT_headingholdplus;
private System.Windows.Forms.GroupBox groupBox7;
private System.Windows.Forms.Label label28;
private System.Windows.Forms.Label LBL_Lane_Dist;
private System.Windows.Forms.NumericUpDown NUM_Lane_Dist;
private System.Windows.Forms.Label LBL_Alternating_lanes;
private System.Windows.Forms.Label lbl_turnrad;
private System.Windows.Forms.Label label36;
private System.Windows.Forms.Label label32;
private System.Windows.Forms.NumericUpDown NUM_leadin;
private System.Windows.Forms.Label label37;
private System.Windows.Forms.NumericUpDown NUM_split;
}
} | gpl-3.0 |
HeavensSword/darkstar | scripts/zones/Mhaura/MobIDs.lua | 34 | MHAURA_EXPLORER_MOOGLE = 17797253; | gpl-3.0 |
Ninos/woocommerce | tests/e2e/core-tests/specs/shopper/front-end-variable-product-updates.test.js | 2776 | /* eslint-disable jest/no-export, jest/no-disabled-tests */
/**
* Internal dependencies
*/
const {
shopper,
merchant,
createVariableProduct,
} = require( '@woocommerce/e2e-utils' );
let variablePostIdValue;
const cartDialogMessage = 'Please select some product options before adding this product to your cart.';
const runVariableProductUpdateTest = () => {
describe('Shopper > Update variable product',() => {
beforeAll(async () => {
await merchant.login();
variablePostIdValue = await createVariableProduct();
await merchant.logout();
});
it('shopper can change variable attributes to the same value', async () => {
await shopper.goToProduct(variablePostIdValue);
await expect(page).toSelect('#attr-1', 'val1');
await expect(page).toSelect('#attr-2', 'val1');
await expect(page).toSelect('#attr-3', 'val1');
await expect(page).toMatchElement('.woocommerce-variation-price', { text: '9.99' });
});
it('shopper can change attributes to combination with dimensions and weight', async () => {
await shopper.goToProduct(variablePostIdValue);
await expect(page).toSelect('#attr-1', 'val1');
await expect(page).toSelect('#attr-2', 'val2');
await expect(page).toSelect('#attr-3', 'val1');
await expect(page).toMatchElement('.woocommerce-variation-price', { text: '20.00' });
await expect(page).toMatchElement('.woocommerce-variation-availability', { text: 'Out of stock' });
await expect(page).toMatchElement('.woocommerce-product-attributes-item--weight', { text: '200 kg' });
await expect(page).toMatchElement('.woocommerce-product-attributes-item--dimensions', { text: '10 × 20 × 15 cm' });
});
it('shopper can change variable product attributes to variation with a different price', async () => {
await shopper.goToProduct(variablePostIdValue);
await expect(page).toSelect('#attr-1', 'val1');
await expect(page).toSelect('#attr-2', 'val1');
await expect(page).toSelect('#attr-3', 'val2');
await expect(page).toMatchElement('.woocommerce-variation-price', { text: '11.99' });
});
it('shopper can reset variations', async () => {
await shopper.goToProduct(variablePostIdValue);
await expect(page).toSelect('#attr-1', 'val1');
await expect(page).toSelect('#attr-2', 'val2');
await expect(page).toSelect('#attr-3', 'val1');
await expect(page).toClick('.reset_variations');
// Verify the reset by attempting to add the product to the cart
const couponDialog = await expect(page).toDisplayDialog(async () => {
await expect(page).toClick('.single_add_to_cart_button');
});
expect(couponDialog.message()).toMatch(cartDialogMessage);
// Accept the dialog
await couponDialog.accept();
});
});
};
module.exports = runVariableProductUpdateTest;
| gpl-3.0 |
isage/falltergeist | src/VM/OpcodeFactory.h | 1253 | /*
* Copyright 2012-2014 Falltergeist Developers.
*
* This file is part of Falltergeist.
*
* Falltergeist 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.
*
* Falltergeist 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 Falltergeist. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FALLTERGEIST_VM_OPCODEFACTORY_H
#define FALLTERGEIST_VM_OPCODEFACTORY_H
// C++ standard includes
#include <memory>
// Falltergeist include
#include "../VM/OpcodeHandler.h"
// Third party includes
namespace Falltergeist
{
namespace VM
{
class Script;
class OpcodeFactory
{
public:
static std::unique_ptr<OpcodeHandler> createOpcode(unsigned int number, VM::Script* script);
};
}
}
#endif // FALLTERGEIST_VM_OPCODEFACTORY_H
| gpl-3.0 |
Distrotech/coreutils | tests/cp/attr-existing.sh | 975 | #!/bin/sh
# Make sure cp --attributes-only doesn't truncate existing data
# Copyright 2012-2014 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
# (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/>.
. "${srcdir=.}/tests/init.sh"; path_prepend_ ./src
print_ver_ cp
printf '1' > file1
printf '2' > file2
printf '2' > file2.exp
cp --attributes-only file1 file2 || fail=1
cmp file2 file2.exp || fail=1
Exit $fail
| gpl-3.0 |
Kubuxu/cjdns | interface/ETHInterface_darwin.c | 10799 | /* vim: set expandtab ts=4 sw=4: */
/*
* You may redistribute this program and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "interface/ETHInterface.h"
#include "exception/Except.h"
#include "wire/Message.h"
#include "wire/Ethernet.h"
#include "util/Assert.h"
#include "util/platform/Socket.h"
#include "util/events/Event.h"
#include "util/Identity.h"
#include "util/version/Version.h"
#include <ifaddrs.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <net/bpf.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <net/if.h>
#include <net/if_dl.h>
#define MAX_PACKET_SIZE 1496
#define MIN_PACKET_SIZE 46
#define PADDING 512
// single ethernet_frame
struct ethernet_frame
{
uint8_t dest[6];
uint8_t src[6];
uint16_t type;
} Gcc_PACKED;
#define ethernet_frame_SIZE 14
Assert_compileTime(ethernet_frame_SIZE == sizeof(struct ethernet_frame));
struct ETHInterface_pvt
{
struct ETHInterface pub;
Socket socket;
struct Log* logger;
uint8_t myMac[6];
String* ifName;
uint8_t* buffer;
int bufLen;
Identity
};
static Iface_DEFUN sendMessage(struct Message* msg, struct Iface* iface)
{
struct ETHInterface_pvt* ctx =
Identity_containerOf(iface, struct ETHInterface_pvt, pub.generic.iface);
struct Sockaddr* sa = (struct Sockaddr*) msg->bytes;
Assert_true(msg->length >= Sockaddr_OVERHEAD);
Assert_true(sa->addrLen <= ETHInterface_Sockaddr_SIZE);
struct ETHInterface_Sockaddr sockaddr = { .generic = { .addrLen = 0 } };
Message_pop(msg, &sockaddr, sa->addrLen, NULL);
struct ETHInterface_Header hdr = {
.version = ETHInterface_CURRENT_VERSION,
.zero = 0,
.length_be = Endian_hostToBigEndian16(msg->length + ETHInterface_Header_SIZE),
.fc00_be = Endian_hostToBigEndian16(0xfc00)
};
Message_push(msg, &hdr, ETHInterface_Header_SIZE, NULL);
struct ethernet_frame ethFr = {
.type = Ethernet_TYPE_CJDNS
};
if (sockaddr.generic.flags & Sockaddr_flags_BCAST) {
Bits_memset(ethFr.dest, 0xff, 6);
} else {
Bits_memcpy(ethFr.dest, sockaddr.mac, 6);
}
Bits_memcpy(ethFr.src, ctx->myMac, 6);
Message_push(msg, ðFr, ethernet_frame_SIZE, NULL);
/*
struct bpf_hdr bpfPkt = {
.bh_caplen = msg->length,
.bh_datalen = msg->length,
.bh_hdrlen = BPF_WORDALIGN(sizeof(struct bpf_hdr))
};
Message_push(msg, &bpfPkt, bpfPkt.bh_hdrlen, NULL);
*/
if (msg->length != write(ctx->socket, msg->bytes, msg->length)) {
Log_debug(ctx->logger, "Error writing to eth device [%s]", strerror(errno));
}
Log_debug(ctx->logger, "message sent");
return NULL;
}
static void handleEvent2(struct ETHInterface_pvt* context,
uint8_t src[6],
uint8_t dst[6],
int length,
uint8_t* data,
struct Allocator* alloc)
{
if (length < ETHInterface_Header_SIZE) {
Log_debug(context->logger, "runt");
return;
}
uint32_t contentLength = BPF_WORDALIGN(length - ETHInterface_Header_SIZE);
struct Message* msg = Message_new(contentLength, PADDING, alloc);
struct ETHInterface_Header hdr;
Bits_memcpy(&hdr, data, ETHInterface_Header_SIZE);
Bits_memcpy(msg->bytes, &data[ETHInterface_Header_SIZE], contentLength);
// here we could put a switch statement to handle different versions differently.
if (hdr.version != ETHInterface_CURRENT_VERSION) {
Log_debug(context->logger, "DROP unknown version");
return;
}
uint16_t reportedLength = Endian_bigEndianToHost16(hdr.length_be);
reportedLength -= ETHInterface_Header_SIZE;
if (msg->length != reportedLength) {
if (msg->length < reportedLength) {
Log_debug(context->logger, "DROP size field is larger than frame");
return;
}
msg->length = reportedLength;
}
if (hdr.fc00_be != Endian_hostToBigEndian16(0xfc00)) {
Log_debug(context->logger, "DROP bad magic");
return;
}
struct ETHInterface_Sockaddr sockaddr = { .zero = 0 };
Bits_memcpy(sockaddr.mac, src, 6);
sockaddr.generic.addrLen = ETHInterface_Sockaddr_SIZE;
if (dst[0] == 0xff) {
sockaddr.generic.flags |= Sockaddr_flags_BCAST;
}
Message_push(msg, &sockaddr, ETHInterface_Sockaddr_SIZE, NULL);
Assert_true(!((uintptr_t)msg->bytes % 4) && "Alignment fault");
Iface_send(&context->pub.generic.iface, msg);
}
static void handleEvent(void* vcontext)
{
struct ETHInterface_pvt* context = Identity_check((struct ETHInterface_pvt*) vcontext);
ssize_t bytes = read(context->socket, context->buffer, context->bufLen);
if (bytes < 0) {
Log_debug(context->logger, "read(bpf, bpf_buf, buf_len) -> [%s]", strerror(errno));
}
if (bytes < 1) { return; }
if (bytes < (ssize_t)sizeof(struct bpf_hdr)) {
Log_debug(context->logger, "runt [%lld]", (long long) bytes);
return;
}
int offset = 0;
while (offset < bytes) {
struct bpf_hdr* bpfPkt = (struct bpf_hdr*) &context->buffer[offset];
struct ethernet_frame* ethFr =
(struct ethernet_frame*) &context->buffer[offset + bpfPkt->bh_hdrlen];
int frameLength = bpfPkt->bh_datalen;
uint8_t* frameContent =
(uint8_t*) &context->buffer[offset + bpfPkt->bh_hdrlen + ethernet_frame_SIZE];
int contentLength = frameLength - ethernet_frame_SIZE;
Assert_true(offset + bpfPkt->bh_hdrlen + frameLength <= bytes);
Assert_true(Ethernet_TYPE_CJDNS == ethFr->type);
struct Allocator* messageAlloc = Allocator_child(context->pub.generic.alloc);
handleEvent2(context, ethFr->src, ethFr->dest, contentLength, frameContent, messageAlloc);
Allocator_free(messageAlloc);
offset += BPF_WORDALIGN(bpfPkt->bh_hdrlen + bpfPkt->bh_caplen);
}
}
List* ETHInterface_listDevices(struct Allocator* alloc, struct Except* eh)
{
List* out = List_new(alloc);
struct ifaddrs* ifaddr = NULL;
if (getifaddrs(&ifaddr) || ifaddr == NULL) {
Except_throw(eh, "getifaddrs() -> errno:%d [%s]", errno, strerror(errno));
}
for (struct ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr) {
} else if (ifa->ifa_addr->sa_family != AF_LINK) {
} else if (!(ifa->ifa_flags & IFF_UP)) {
} else if (ifa->ifa_flags & IFF_LOOPBACK) {
} else {
List_addString(out, String_new(ifa->ifa_name, alloc), alloc);
}
}
freeifaddrs(ifaddr);
return out;
}
static int closeSocket(struct Allocator_OnFreeJob* j)
{
struct ETHInterface_pvt* ctx = Identity_check((struct ETHInterface_pvt*) j->userData);
close(ctx->socket);
return 0;
}
static int openBPF(struct Except* eh)
{
for (int retry = 0; retry < 100; retry++) {
for (int i = 0; i < 256; i++) {
char buf[11] = { 0 };
snprintf(buf, 10, "/dev/bpf%i", i);
int bpf = open(buf, O_RDWR);
if (bpf != -1) { return bpf; }
}
// sleep for 0.1 seconds
usleep(1000 * 100);
}
Except_throw(eh, "Could not find available /dev/bpf device");
}
static void macaddr(const char* ifname, uint8_t addrOut[6], struct Except* eh)
{
struct ifaddrs* ifa;
if (getifaddrs(&ifa)) {
Except_throw(eh, "getifaddrs() -> [%s]", strerror(errno));
} else {
for (struct ifaddrs* ifap = ifa; ifap; ifap = ifap->ifa_next) {
if (!strcmp(ifap->ifa_name, ifname) && ifap->ifa_addr->sa_family == AF_LINK) {
Bits_memcpy(addrOut, LLADDR((struct sockaddr_dl*) ifap->ifa_addr), 6);
freeifaddrs(ifa);
return;
}
}
}
freeifaddrs(ifa);
Except_throw(eh, "Could not find mac address for [%s]", ifname);
}
struct ETHInterface* ETHInterface_new(struct EventBase* eventBase,
const char* bindDevice,
struct Allocator* alloc,
struct Except* exHandler,
struct Log* logger)
{
struct ETHInterface_pvt* ctx = Allocator_calloc(alloc, sizeof(struct ETHInterface_pvt), 1);
Identity_set(ctx);
ctx->pub.generic.iface.send = sendMessage;
ctx->pub.generic.alloc = alloc;
ctx->logger = logger;
ctx->socket = openBPF(exHandler);
macaddr(bindDevice, ctx->myMac, exHandler);
struct ifreq ifr = { .ifr_name = { 0 } };
CString_strcpy(ifr.ifr_name, bindDevice);
if (ioctl(ctx->socket, BIOCSETIF, &ifr) > 0) {
Except_throw(exHandler, "ioctl(BIOCSETIF, [%s]) [%s]", bindDevice, strerror(errno));
}
// activate immediate mode (therefore, bufLen is initially set to "1")
int bufLen = 1;
if (ioctl(ctx->socket, BIOCIMMEDIATE, &bufLen) == -1) {
Except_throw(exHandler, "ioctl(BIOCIMMEDIATE) [%s]", strerror(errno));
}
// request buffer length
if (ioctl(ctx->socket, BIOCGBLEN, &bufLen) == -1) {
Except_throw(exHandler, "ioctl(BIOCGBLEN) [%s]", strerror(errno));
}
Log_debug(logger, "ioctl(BIOCGBLEN) -> bufLen=%i", bufLen);
ctx->buffer = Allocator_malloc(alloc, bufLen);
ctx->bufLen = bufLen;
// filter for cjdns ethertype (0xfc00)
static struct bpf_insn cjdnsFilter[] = {
BPF_STMT(BPF_LD+BPF_H+BPF_ABS, 12),
BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, /* Ethernet_TYPE_CJDNS */ 0xfc00, 1, 0),
// drop
BPF_STMT(BPF_RET+BPF_K, 0),
// How much of the packet to ask for...
BPF_STMT(BPF_RET+BPF_K, ~0u)
};
struct bpf_program cjdnsFilterProgram = {
.bf_len = (sizeof(cjdnsFilter) / sizeof(struct bpf_insn)),
.bf_insns = cjdnsFilter,
};
if (ioctl(ctx->socket, BIOCSETF, &cjdnsFilterProgram) == -1) {
Except_throw(exHandler, "ioctl(BIOCSETF) [%s]", strerror(errno));
}
Socket_makeNonBlocking(ctx->socket);
Event_socketRead(handleEvent, ctx, ctx->socket, eventBase, alloc, exHandler);
Allocator_onFree(alloc, closeSocket, ctx);
return &ctx->pub;
}
| gpl-3.0 |
Merrick28/delain | web/vendor/google/apiclient-services/src/Google/Service/DataFusion/DataAccessOptions.php | 837 | <?php
/*
* Copyright 2014 Google Inc.
*
* 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.
*/
class Google_Service_DataFusion_DataAccessOptions extends Google_Model
{
public $logMode;
public function setLogMode($logMode)
{
$this->logMode = $logMode;
}
public function getLogMode()
{
return $this->logMode;
}
}
| gpl-3.0 |
CYBAI/servo | tests/wpt/webgpu/tests/webgpu/webgpu/api/validation/copy_between_linear_data_and_texture/copyBetweenLinearDataAndTexture_textureRelated.spec.js | 8523 | /**
* AUTO-GENERATED - DO NOT EDIT. Source: https://github.com/gpuweb/cts
**/ export const description = '';
import { params, poptions } from '../../../../common/framework/params_builder.js';
import { makeTestGroup } from '../../../../common/framework/test_group.js';
import { kSizedTextureFormats, kSizedTextureFormatInfo } from '../../../capability_info.js';
import {
CopyBetweenLinearDataAndTextureTest,
kAllTestMethods,
texelBlockAlignmentTestExpanderForValueToCoordinate,
formatCopyableWithMethod,
} from './copyBetweenLinearDataAndTexture.js';
export const g = makeTestGroup(CopyBetweenLinearDataAndTextureTest);
g.test('texture_must_be_valid')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(poptions('textureState', ['valid', 'destroyed', 'error']))
)
.fn(async t => {
const { method, textureState } = t.params;
// A valid texture.
let texture = t.device.createTexture({
size: { width: 4, height: 4, depth: 1 },
format: 'rgba8unorm',
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST,
});
switch (textureState) {
case 'destroyed': {
texture.destroy();
break;
}
case 'error': {
texture = t.getErrorTexture();
break;
}
}
const success = textureState === 'valid';
const submit = textureState === 'destroyed';
t.testRun(
{ texture },
{ bytesPerRow: 0 },
{ width: 0, height: 0, depth: 0 },
{ dataSize: 1, method, success, submit }
);
});
g.test('texture_usage_must_be_valid')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(
poptions('usage', [
GPUTextureUsage.COPY_SRC | GPUTextureUsage.SAMPLED,
GPUTextureUsage.COPY_DST | GPUTextureUsage.SAMPLED,
GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST,
])
)
)
.fn(async t => {
const { usage, method } = t.params;
const texture = t.device.createTexture({
size: { width: 4, height: 4, depth: 1 },
format: 'rgba8unorm',
usage,
});
const success =
method === 'CopyTextureToBuffer'
? (usage & GPUTextureUsage.COPY_SRC) !== 0
: (usage & GPUTextureUsage.COPY_DST) !== 0;
t.testRun(
{ texture },
{ bytesPerRow: 0 },
{ width: 0, height: 0, depth: 0 },
{ dataSize: 1, method, success }
);
});
g.test('sample_count_must_be_1')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(poptions('sampleCount', [1, 4]))
)
.fn(async t => {
const { sampleCount, method } = t.params;
const texture = t.device.createTexture({
size: { width: 4, height: 4, depth: 1 },
sampleCount,
format: 'rgba8unorm',
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST | GPUTextureUsage.SAMPLED,
});
const success = sampleCount === 1;
t.testRun(
{ texture },
{ bytesPerRow: 0 },
{ width: 0, height: 0, depth: 0 },
{ dataSize: 1, method, success }
);
});
g.test('mip_level_must_be_in_range')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(poptions('mipLevelCount', [3, 5]))
.combine(poptions('mipLevel', [3, 4]))
)
.fn(async t => {
const { mipLevelCount, mipLevel, method } = t.params;
const texture = t.device.createTexture({
size: { width: 32, height: 32, depth: 1 },
mipLevelCount,
format: 'rgba8unorm',
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST,
});
const success = mipLevel < mipLevelCount;
t.testRun(
{ texture, mipLevel },
{ bytesPerRow: 0 },
{ width: 0, height: 0, depth: 0 },
{ dataSize: 1, method, success }
);
});
g.test('texel_block_alignments_on_origin')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(poptions('coordinateToTest', ['x', 'y', 'z']))
.combine(poptions('format', kSizedTextureFormats))
.filter(formatCopyableWithMethod)
.expand(texelBlockAlignmentTestExpanderForValueToCoordinate)
)
.fn(async t => {
const { valueToCoordinate, coordinateToTest, format, method } = t.params;
const info = kSizedTextureFormatInfo[format];
const origin = { x: 0, y: 0, z: 0 };
const size = { width: 0, height: 0, depth: 0 };
let success = true;
origin[coordinateToTest] = valueToCoordinate;
switch (coordinateToTest) {
case 'x': {
success = origin.x % info.blockWidth === 0;
break;
}
case 'y': {
success = origin.y % info.blockHeight === 0;
break;
}
}
const texture = t.createAlignedTexture(format, size, origin);
t.testRun({ texture, origin }, { bytesPerRow: 0 }, size, {
dataSize: 1,
method,
success,
});
});
g.test('1d_texture')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(poptions('width', [0, 1]))
.combine([
{ height: 1, depth: 1 },
{ height: 1, depth: 0 },
{ height: 1, depth: 2 },
{ height: 0, depth: 1 },
{ height: 2, depth: 1 },
])
)
.fn(async t => {
const { method, width, height, depth } = t.params;
const size = { width, height, depth };
const texture = t.device.createTexture({
size: { width: 2, height: 1, depth: 1 },
dimension: '1d',
format: 'rgba8unorm',
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST,
});
// For 1d textures we require copyHeight and copyDepth to be 1,
// copyHeight or copyDepth being 0 should cause a validation error.
const success = size.height === 1 && size.depth === 1;
t.testRun({ texture }, { bytesPerRow: 256, rowsPerImage: 4 }, size, {
dataSize: 16,
method,
success,
});
});
g.test('texel_block_alignments_on_size')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(poptions('coordinateToTest', ['width', 'height', 'depth']))
.combine(poptions('format', kSizedTextureFormats))
.filter(formatCopyableWithMethod)
.expand(texelBlockAlignmentTestExpanderForValueToCoordinate)
)
.fn(async t => {
const { valueToCoordinate, coordinateToTest, format, method } = t.params;
const info = kSizedTextureFormatInfo[format];
const origin = { x: 0, y: 0, z: 0 };
const size = { width: 0, height: 0, depth: 0 };
let success = true;
size[coordinateToTest] = valueToCoordinate;
switch (coordinateToTest) {
case 'width': {
success = size.width % info.blockWidth === 0;
break;
}
case 'height': {
success = size.height % info.blockHeight === 0;
break;
}
}
const texture = t.createAlignedTexture(format, size, origin);
t.testRun({ texture, origin }, { bytesPerRow: 0 }, size, {
dataSize: 1,
method,
success,
});
});
g.test('texture_range_conditions')
.params(
params()
.combine(poptions('method', kAllTestMethods))
.combine(poptions('originValue', [7, 8]))
.combine(poptions('copySizeValue', [7, 8]))
.combine(poptions('textureSizeValue', [14, 15]))
.combine(poptions('mipLevel', [0, 2]))
.combine(poptions('coordinateToTest', [0, 1, 2]))
)
.fn(async t => {
const {
originValue,
copySizeValue,
textureSizeValue,
mipLevel,
coordinateToTest,
method,
} = t.params;
const origin = [0, 0, 0];
const copySize = [0, 0, 0];
const textureSize = { width: 16 << mipLevel, height: 16 << mipLevel, depth: 16 };
const success = originValue + copySizeValue <= textureSizeValue;
origin[coordinateToTest] = originValue;
copySize[coordinateToTest] = copySizeValue;
switch (coordinateToTest) {
case 0: {
textureSize.width = textureSizeValue << mipLevel;
break;
}
case 1: {
textureSize.height = textureSizeValue << mipLevel;
break;
}
case 2: {
textureSize.depth = textureSizeValue;
break;
}
}
const texture = t.device.createTexture({
size: textureSize,
mipLevelCount: 3,
format: 'rgba8unorm',
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST,
});
t.testRun({ texture, origin, mipLevel }, { bytesPerRow: 0 }, copySize, {
dataSize: 1,
method,
success,
});
});
| mpl-2.0 |
grange74/terraform | config/module/inode_windows.go | 128 | package module
// no syscall.Stat_t on windows, return 0 for inodes
func inode(path string) (uint64, error) {
return 0, nil
}
| mpl-2.0 |
tmj-fstate/maszyna | ref/glfw/docs/html/quick_guide.html | 42335 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.16"/>
<title>GLFW: Getting started</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="extra.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<div class="glfwheader">
<a href="https://www.glfw.org/" id="glfwhome">GLFW</a>
<ul class="glfwnavbar">
<li><a href="https://www.glfw.org/documentation.html">Documentation</a></li>
<li><a href="https://www.glfw.org/download.html">Download</a></li>
<li><a href="https://www.glfw.org/community.html">Community</a></li>
</ul>
</div>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.16 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div><!-- top -->
<div class="PageDoc"><div class="header">
<div class="headertitle">
<div class="title">Getting started </div> </div>
</div><!--header-->
<div class="contents">
<div class="toc"><h3>Table of Contents</h3>
<ul><li class="level1"><a href="#quick_steps">Step by step</a><ul><li class="level2"><a href="#quick_include">Including the GLFW header</a></li>
<li class="level2"><a href="#quick_init_term">Initializing and terminating GLFW</a></li>
<li class="level2"><a href="#quick_capture_error">Setting an error callback</a></li>
<li class="level2"><a href="#quick_create_window">Creating a window and context</a></li>
<li class="level2"><a href="#quick_context_current">Making the OpenGL context current</a></li>
<li class="level2"><a href="#quick_window_close">Checking the window close flag</a></li>
<li class="level2"><a href="#quick_key_input">Receiving input events</a></li>
<li class="level2"><a href="#quick_render">Rendering with OpenGL</a></li>
<li class="level2"><a href="#quick_timer">Reading the timer</a></li>
<li class="level2"><a href="#quick_swap_buffers">Swapping buffers</a></li>
<li class="level2"><a href="#quick_process_events">Processing events</a></li>
</ul>
</li>
<li class="level1"><a href="#quick_example">Putting it together</a></li>
</ul>
</div>
<div class="textblock"><p>This guide takes you through writing a simple application using GLFW 3. The application will create a window and OpenGL context, render a rotating triangle and exit when the user closes the window or presses <em>Escape</em>. This guide will introduce a few of the most commonly used functions, but there are many more.</p>
<p>This guide assumes no experience with earlier versions of GLFW. If you have used GLFW 2 in the past, read <a class="el" href="moving_guide.html">Moving from GLFW 2 to 3</a>, as some functions behave differently in GLFW 3.</p>
<h1><a class="anchor" id="quick_steps"></a>
Step by step</h1>
<h2><a class="anchor" id="quick_include"></a>
Including the GLFW header</h2>
<p>In the source files of your application where you use OpenGL or GLFW, you need to include the GLFW 3 header file.</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include <<a class="code" href="glfw3_8h.html">GLFW/glfw3.h</a>></span></div>
</div><!-- fragment --><p>This defines all the constants, types and function prototypes of the GLFW API. It also includes the OpenGL header from your development environment and defines all the constants and types necessary for it to work on your platform without including any platform-specific headers.</p>
<p>In other words:</p>
<ul>
<li>Do <em>not</em> include the OpenGL header yourself, as GLFW does this for you in a platform-independent way</li>
<li>Do <em>not</em> include <code>windows.h</code> or other platform-specific headers unless you plan on using those APIs yourself</li>
<li>If you <em>do</em> need to include such headers, include them <em>before</em> the GLFW header and it will detect this</li>
</ul>
<p>On some platforms supported by GLFW the OpenGL header and link library only expose older versions of OpenGL. The most extreme case is Windows, which only exposes OpenGL 1.2. The easiest way to work around this is to use an <a class="el" href="context_guide.html#context_glext_auto">extension loader library</a>.</p>
<p>If you are using such a library then you should include its header <em>before</em> the GLFW header. This lets it replace the OpenGL header included by GLFW without conflicts. This example uses <a href="https://github.com/Dav1dde/glad">glad2</a>, but the same rule applies to all such libraries.</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include <glad/gl.h></span></div>
<div class="line"><span class="preprocessor">#include <<a class="code" href="glfw3_8h.html">GLFW/glfw3.h</a>></span></div>
</div><!-- fragment --><h2><a class="anchor" id="quick_init_term"></a>
Initializing and terminating GLFW</h2>
<p>Before you can use most GLFW functions, the library must be initialized. On successful initialization, <code>GLFW_TRUE</code> is returned. If an error occurred, <code>GLFW_FALSE</code> is returned.</p>
<div class="fragment"><div class="line"><span class="keywordflow">if</span> (!<a class="code" href="group__init.html#ga317aac130a235ab08c6db0834907d85e">glfwInit</a>())</div>
<div class="line">{</div>
<div class="line"> <span class="comment">// Initialization failed</span></div>
<div class="line">}</div>
</div><!-- fragment --><p>Note that <code>GLFW_TRUE</code> and <code>GLFW_FALSE</code> are and will always be one and zero.</p>
<p>When you are done using GLFW, typically just before the application exits, you need to terminate GLFW.</p>
<div class="fragment"><div class="line"><a class="code" href="group__init.html#gaaae48c0a18607ea4a4ba951d939f0901">glfwTerminate</a>();</div>
</div><!-- fragment --><p>This destroys any remaining windows and releases any other resources allocated by GLFW. After this call, you must initialize GLFW again before using any GLFW functions that require it.</p>
<h2><a class="anchor" id="quick_capture_error"></a>
Setting an error callback</h2>
<p>Most events are reported through callbacks, whether it's a key being pressed, a GLFW window being moved, or an error occurring. Callbacks are C functions (or C++ static methods) that are called by GLFW with arguments describing the event.</p>
<p>In case a GLFW function fails, an error is reported to the GLFW error callback. You can receive these reports with an error callback. This function must have the signature below but may do anything permitted in other callbacks.</p>
<div class="fragment"><div class="line"><span class="keywordtype">void</span> error_callback(<span class="keywordtype">int</span> error, <span class="keyword">const</span> <span class="keywordtype">char</span>* description)</div>
<div class="line">{</div>
<div class="line"> fprintf(stderr, <span class="stringliteral">"Error: %s\n"</span>, description);</div>
<div class="line">}</div>
</div><!-- fragment --><p>Callback functions must be set, so GLFW knows to call them. The function to set the error callback is one of the few GLFW functions that may be called before initialization, which lets you be notified of errors both during and after initialization.</p>
<div class="fragment"><div class="line"><a class="code" href="group__init.html#gaff45816610d53f0b83656092a4034f40">glfwSetErrorCallback</a>(error_callback);</div>
</div><!-- fragment --><h2><a class="anchor" id="quick_create_window"></a>
Creating a window and context</h2>
<p>The window and its OpenGL context are created with a single call to <a class="el" href="group__window.html#ga5c336fddf2cbb5b92f65f10fb6043344">glfwCreateWindow</a>, which returns a handle to the created combined window and context object</p>
<div class="fragment"><div class="line"><a class="code" href="group__window.html#ga3c96d80d363e67d13a41b5d1821f3242">GLFWwindow</a>* window = <a class="code" href="group__window.html#ga5c336fddf2cbb5b92f65f10fb6043344">glfwCreateWindow</a>(640, 480, <span class="stringliteral">"My Title"</span>, NULL, NULL);</div>
<div class="line"><span class="keywordflow">if</span> (!window)</div>
<div class="line">{</div>
<div class="line"> <span class="comment">// Window or OpenGL context creation failed</span></div>
<div class="line">}</div>
</div><!-- fragment --><p>This creates a 640 by 480 windowed mode window with an OpenGL context. If window or OpenGL context creation fails, <code>NULL</code> will be returned. You should always check the return value. While window creation rarely fails, context creation depends on properly installed drivers and may fail even on machines with the necessary hardware.</p>
<p>By default, the OpenGL context GLFW creates may have any version. You can require a minimum OpenGL version by setting the <code>GLFW_CONTEXT_VERSION_MAJOR</code> and <code>GLFW_CONTEXT_VERSION_MINOR</code> hints <em>before</em> creation. If the required minimum version is not supported on the machine, context (and window) creation fails.</p>
<div class="fragment"><div class="line"><a class="code" href="group__window.html#ga7d9c8c62384b1e2821c4dc48952d2033">glfwWindowHint</a>(<a class="code" href="group__window.html#gafe5e4922de1f9932d7e9849bb053b0c0">GLFW_CONTEXT_VERSION_MAJOR</a>, 2);</div>
<div class="line"><a class="code" href="group__window.html#ga7d9c8c62384b1e2821c4dc48952d2033">glfwWindowHint</a>(<a class="code" href="group__window.html#ga31aca791e4b538c4e4a771eb95cc2d07">GLFW_CONTEXT_VERSION_MINOR</a>, 0);</div>
<div class="line"><a class="code" href="group__window.html#ga3c96d80d363e67d13a41b5d1821f3242">GLFWwindow</a>* window = <a class="code" href="group__window.html#ga5c336fddf2cbb5b92f65f10fb6043344">glfwCreateWindow</a>(640, 480, <span class="stringliteral">"My Title"</span>, NULL, NULL);</div>
<div class="line"><span class="keywordflow">if</span> (!window)</div>
<div class="line">{</div>
<div class="line"> <span class="comment">// Window or context creation failed</span></div>
<div class="line">}</div>
</div><!-- fragment --><p>The window handle is passed to all window related functions and is provided to along to all window related callbacks, so they can tell which window received the event.</p>
<p>When a window and context is no longer needed, destroy it.</p>
<div class="fragment"><div class="line"><a class="code" href="group__window.html#gacdf43e51376051d2c091662e9fe3d7b2">glfwDestroyWindow</a>(window);</div>
</div><!-- fragment --><p>Once this function is called, no more events will be delivered for that window and its handle becomes invalid.</p>
<h2><a class="anchor" id="quick_context_current"></a>
Making the OpenGL context current</h2>
<p>Before you can use the OpenGL API, you must have a current OpenGL context.</p>
<div class="fragment"><div class="line"><a class="code" href="group__context.html#ga1c04dc242268f827290fe40aa1c91157">glfwMakeContextCurrent</a>(window);</div>
</div><!-- fragment --><p>The context will remain current until you make another context current or until the window owning the current context is destroyed.</p>
<p>If you are using an <a class="el" href="context_guide.html#context_glext_auto">extension loader library</a> to access modern OpenGL then this is when to initialize it, as the loader needs a current context to load from. This example uses <a href="https://github.com/Dav1dde/glad">glad</a>, but the same rule applies to all such libraries.</p>
<div class="fragment"><div class="line">gladLoadGL(<a class="code" href="group__context.html#ga35f1837e6f666781842483937612f163">glfwGetProcAddress</a>);</div>
</div><!-- fragment --><h2><a class="anchor" id="quick_window_close"></a>
Checking the window close flag</h2>
<p>Each window has a flag indicating whether the window should be closed.</p>
<p>When the user attempts to close the window, either by pressing the close widget in the title bar or using a key combination like Alt+F4, this flag is set to 1. Note that <b>the window isn't actually closed</b>, so you are expected to monitor this flag and either destroy the window or give some kind of feedback to the user.</p>
<div class="fragment"><div class="line"><span class="keywordflow">while</span> (!<a class="code" href="group__window.html#ga24e02fbfefbb81fc45320989f8140ab5">glfwWindowShouldClose</a>(window))</div>
<div class="line">{</div>
<div class="line"> <span class="comment">// Keep running</span></div>
<div class="line">}</div>
</div><!-- fragment --><p>You can be notified when the user is attempting to close the window by setting a close callback with <a class="el" href="group__window.html#gada646d775a7776a95ac000cfc1885331">glfwSetWindowCloseCallback</a>. The callback will be called immediately after the close flag has been set.</p>
<p>You can also set it yourself with <a class="el" href="group__window.html#ga49c449dde2a6f87d996f4daaa09d6708">glfwSetWindowShouldClose</a>. This can be useful if you want to interpret other kinds of input as closing the window, like for example pressing the <em>Escape</em> key.</p>
<h2><a class="anchor" id="quick_key_input"></a>
Receiving input events</h2>
<p>Each window has a large number of callbacks that can be set to receive all the various kinds of events. To receive key press and release events, create a key callback function.</p>
<div class="fragment"><div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span> key_callback(<a class="code" href="group__window.html#ga3c96d80d363e67d13a41b5d1821f3242">GLFWwindow</a>* window, <span class="keywordtype">int</span> key, <span class="keywordtype">int</span> scancode, <span class="keywordtype">int</span> action, <span class="keywordtype">int</span> mods)</div>
<div class="line">{</div>
<div class="line"> <span class="keywordflow">if</span> (key == <a class="code" href="group__keys.html#gaac6596c350b635c245113b81c2123b93">GLFW_KEY_ESCAPE</a> && action == <a class="code" href="group__input.html#ga2485743d0b59df3791c45951c4195265">GLFW_PRESS</a>)</div>
<div class="line"> <a class="code" href="group__window.html#ga49c449dde2a6f87d996f4daaa09d6708">glfwSetWindowShouldClose</a>(window, <a class="code" href="group__init.html#ga2744fbb29b5631bb28802dbe0cf36eba">GLFW_TRUE</a>);</div>
<div class="line">}</div>
</div><!-- fragment --><p>The key callback, like other window related callbacks, are set per-window.</p>
<div class="fragment"><div class="line"><a class="code" href="group__input.html#ga1caf18159767e761185e49a3be019f8d">glfwSetKeyCallback</a>(window, key_callback);</div>
</div><!-- fragment --><p>In order for event callbacks to be called when events occur, you need to process events as described below.</p>
<h2><a class="anchor" id="quick_render"></a>
Rendering with OpenGL</h2>
<p>Once you have a current OpenGL context, you can use OpenGL normally. In this tutorial, a multi-colored rotating triangle will be rendered. The framebuffer size needs to be retrieved for <code>glViewport</code>.</p>
<div class="fragment"><div class="line"><span class="keywordtype">int</span> width, height;</div>
<div class="line"><a class="code" href="group__window.html#ga0e2637a4161afb283f5300c7f94785c9">glfwGetFramebufferSize</a>(window, &width, &height);</div>
<div class="line">glViewport(0, 0, width, height);</div>
</div><!-- fragment --><p>You can also set a framebuffer size callback using <a class="el" href="group__window.html#gab3fb7c3366577daef18c0023e2a8591f">glfwSetFramebufferSizeCallback</a> and be notified when the size changes.</p>
<p>Actual rendering with OpenGL is outside the scope of this tutorial, but there are <a href="https://open.gl/">many</a> <a href="https://learnopengl.com/">excellent</a> <a href="http://openglbook.com/">tutorial</a> <a href="http://ogldev.atspace.co.uk/">sites</a> that teach modern OpenGL. Some of them use GLFW to create the context and window while others use GLUT or SDL, but remember that OpenGL itself always works the same.</p>
<h2><a class="anchor" id="quick_timer"></a>
Reading the timer</h2>
<p>To create smooth animation, a time source is needed. GLFW provides a timer that returns the number of seconds since initialization. The time source used is the most accurate on each platform and generally has micro- or nanosecond resolution.</p>
<div class="fragment"><div class="line"><span class="keywordtype">double</span> time = <a class="code" href="group__input.html#gaa6cf4e7a77158a3b8fd00328b1720a4a">glfwGetTime</a>();</div>
</div><!-- fragment --><h2><a class="anchor" id="quick_swap_buffers"></a>
Swapping buffers</h2>
<p>GLFW windows by default use double buffering. That means that each window has two rendering buffers; a front buffer and a back buffer. The front buffer is the one being displayed and the back buffer the one you render to.</p>
<p>When the entire frame has been rendered, the buffers need to be swapped with one another, so the back buffer becomes the front buffer and vice versa.</p>
<div class="fragment"><div class="line"><a class="code" href="group__window.html#ga15a5a1ee5b3c2ca6b15ca209a12efd14">glfwSwapBuffers</a>(window);</div>
</div><!-- fragment --><p>The swap interval indicates how many frames to wait until swapping the buffers, commonly known as <em>vsync</em>. By default, the swap interval is zero, meaning buffer swapping will occur immediately. On fast machines, many of those frames will never be seen, as the screen is still only updated typically 60-75 times per second, so this wastes a lot of CPU and GPU cycles.</p>
<p>Also, because the buffers will be swapped in the middle the screen update, leading to <a href="https://en.wikipedia.org/wiki/Screen_tearing">screen tearing</a>.</p>
<p>For these reasons, applications will typically want to set the swap interval to one. It can be set to higher values, but this is usually not recommended, because of the input latency it leads to.</p>
<div class="fragment"><div class="line"><a class="code" href="group__context.html#ga6d4e0cdf151b5e579bd67f13202994ed">glfwSwapInterval</a>(1);</div>
</div><!-- fragment --><p>This function acts on the current context and will fail unless a context is current.</p>
<h2><a class="anchor" id="quick_process_events"></a>
Processing events</h2>
<p>GLFW needs to communicate regularly with the window system both in order to receive events and to show that the application hasn't locked up. Event processing must be done regularly while you have visible windows and is normally done each frame after buffer swapping.</p>
<p>There are two methods for processing pending events; polling and waiting. This example will use event polling, which processes only those events that have already been received and then returns immediately.</p>
<div class="fragment"><div class="line"><a class="code" href="group__window.html#ga37bd57223967b4211d60ca1a0bf3c832">glfwPollEvents</a>();</div>
</div><!-- fragment --><p>This is the best choice when rendering continually, like most games do. If instead you only need to update your rendering once you have received new input, <a class="el" href="group__window.html#ga554e37d781f0a997656c26b2c56c835e">glfwWaitEvents</a> is a better choice. It waits until at least one event has been received, putting the thread to sleep in the meantime, and then processes all received events. This saves a great deal of CPU cycles and is useful for, for example, many kinds of editing tools.</p>
<h1><a class="anchor" id="quick_example"></a>
Putting it together</h1>
<p>Now that you know how to initialize GLFW, create a window and poll for keyboard input, it's possible to create a simple program.</p>
<p>This program creates a 640 by 480 windowed mode window and starts a loop that clears the screen, renders a triangle and processes events until the user either presses <em>Escape</em> or closes the window.</p>
<div class="fragment"><div class="line"> </div>
<div class="line"><span class="preprocessor">#include <glad/gl.h></span></div>
<div class="line"><span class="preprocessor">#define GLFW_INCLUDE_NONE</span></div>
<div class="line"><span class="preprocessor">#include <<a class="code" href="glfw3_8h.html">GLFW/glfw3.h</a>></span></div>
<div class="line"> </div>
<div class="line"><span class="preprocessor">#include "linmath.h"</span></div>
<div class="line"> </div>
<div class="line"><span class="preprocessor">#include <stdlib.h></span></div>
<div class="line"><span class="preprocessor">#include <stdio.h></span></div>
<div class="line"> </div>
<div class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">struct</span></div>
<div class="line">{</div>
<div class="line"> <span class="keywordtype">float</span> x, y;</div>
<div class="line"> <span class="keywordtype">float</span> r, g, b;</div>
<div class="line">} vertices[3] =</div>
<div class="line">{</div>
<div class="line"> { -0.6f, -0.4f, 1.f, 0.f, 0.f },</div>
<div class="line"> { 0.6f, -0.4f, 0.f, 1.f, 0.f },</div>
<div class="line"> { 0.f, 0.6f, 0.f, 0.f, 1.f }</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keywordtype">char</span>* vertex_shader_text =</div>
<div class="line"><span class="stringliteral">"#version 110\n"</span></div>
<div class="line"><span class="stringliteral">"uniform mat4 MVP;\n"</span></div>
<div class="line"><span class="stringliteral">"attribute vec3 vCol;\n"</span></div>
<div class="line"><span class="stringliteral">"attribute vec2 vPos;\n"</span></div>
<div class="line"><span class="stringliteral">"varying vec3 color;\n"</span></div>
<div class="line"><span class="stringliteral">"void main()\n"</span></div>
<div class="line"><span class="stringliteral">"{\n"</span></div>
<div class="line"><span class="stringliteral">" gl_Position = MVP * vec4(vPos, 0.0, 1.0);\n"</span></div>
<div class="line"><span class="stringliteral">" color = vCol;\n"</span></div>
<div class="line"><span class="stringliteral">"}\n"</span>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keywordtype">char</span>* fragment_shader_text =</div>
<div class="line"><span class="stringliteral">"#version 110\n"</span></div>
<div class="line"><span class="stringliteral">"varying vec3 color;\n"</span></div>
<div class="line"><span class="stringliteral">"void main()\n"</span></div>
<div class="line"><span class="stringliteral">"{\n"</span></div>
<div class="line"><span class="stringliteral">" gl_FragColor = vec4(color, 1.0);\n"</span></div>
<div class="line"><span class="stringliteral">"}\n"</span>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span> error_callback(<span class="keywordtype">int</span> error, <span class="keyword">const</span> <span class="keywordtype">char</span>* description)</div>
<div class="line">{</div>
<div class="line"> fprintf(stderr, <span class="stringliteral">"Error: %s\n"</span>, description);</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span> key_callback(<a class="code" href="group__window.html#ga3c96d80d363e67d13a41b5d1821f3242">GLFWwindow</a>* window, <span class="keywordtype">int</span> key, <span class="keywordtype">int</span> scancode, <span class="keywordtype">int</span> action, <span class="keywordtype">int</span> mods)</div>
<div class="line">{</div>
<div class="line"> <span class="keywordflow">if</span> (key == <a class="code" href="group__keys.html#gaac6596c350b635c245113b81c2123b93">GLFW_KEY_ESCAPE</a> && action == <a class="code" href="group__input.html#ga2485743d0b59df3791c45951c4195265">GLFW_PRESS</a>)</div>
<div class="line"> <a class="code" href="group__window.html#ga49c449dde2a6f87d996f4daaa09d6708">glfwSetWindowShouldClose</a>(window, <a class="code" href="group__init.html#ga2744fbb29b5631bb28802dbe0cf36eba">GLFW_TRUE</a>);</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line"><span class="keywordtype">int</span> main(<span class="keywordtype">void</span>)</div>
<div class="line">{</div>
<div class="line"> <a class="code" href="group__window.html#ga3c96d80d363e67d13a41b5d1821f3242">GLFWwindow</a>* window;</div>
<div class="line"> GLuint vertex_buffer, vertex_shader, fragment_shader, program;</div>
<div class="line"> GLint mvp_location, vpos_location, vcol_location;</div>
<div class="line"> </div>
<div class="line"> <a class="code" href="group__init.html#gaff45816610d53f0b83656092a4034f40">glfwSetErrorCallback</a>(error_callback);</div>
<div class="line"> </div>
<div class="line"> <span class="keywordflow">if</span> (!<a class="code" href="group__init.html#ga317aac130a235ab08c6db0834907d85e">glfwInit</a>())</div>
<div class="line"> exit(EXIT_FAILURE);</div>
<div class="line"> </div>
<div class="line"> <a class="code" href="group__window.html#ga7d9c8c62384b1e2821c4dc48952d2033">glfwWindowHint</a>(<a class="code" href="group__window.html#gafe5e4922de1f9932d7e9849bb053b0c0">GLFW_CONTEXT_VERSION_MAJOR</a>, 2);</div>
<div class="line"> <a class="code" href="group__window.html#ga7d9c8c62384b1e2821c4dc48952d2033">glfwWindowHint</a>(<a class="code" href="group__window.html#ga31aca791e4b538c4e4a771eb95cc2d07">GLFW_CONTEXT_VERSION_MINOR</a>, 0);</div>
<div class="line"> </div>
<div class="line"> window = <a class="code" href="group__window.html#ga5c336fddf2cbb5b92f65f10fb6043344">glfwCreateWindow</a>(640, 480, <span class="stringliteral">"Simple example"</span>, NULL, NULL);</div>
<div class="line"> <span class="keywordflow">if</span> (!window)</div>
<div class="line"> {</div>
<div class="line"> <a class="code" href="group__init.html#gaaae48c0a18607ea4a4ba951d939f0901">glfwTerminate</a>();</div>
<div class="line"> exit(EXIT_FAILURE);</div>
<div class="line"> }</div>
<div class="line"> </div>
<div class="line"> <a class="code" href="group__input.html#ga1caf18159767e761185e49a3be019f8d">glfwSetKeyCallback</a>(window, key_callback);</div>
<div class="line"> </div>
<div class="line"> <a class="code" href="group__context.html#ga1c04dc242268f827290fe40aa1c91157">glfwMakeContextCurrent</a>(window);</div>
<div class="line"> gladLoadGL(<a class="code" href="group__context.html#ga35f1837e6f666781842483937612f163">glfwGetProcAddress</a>);</div>
<div class="line"> <a class="code" href="group__context.html#ga6d4e0cdf151b5e579bd67f13202994ed">glfwSwapInterval</a>(1);</div>
<div class="line"> </div>
<div class="line"> <span class="comment">// NOTE: OpenGL error checks have been omitted for brevity</span></div>
<div class="line"> </div>
<div class="line"> glGenBuffers(1, &vertex_buffer);</div>
<div class="line"> glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);</div>
<div class="line"> glBufferData(GL_ARRAY_BUFFER, <span class="keyword">sizeof</span>(vertices), vertices, GL_STATIC_DRAW);</div>
<div class="line"> </div>
<div class="line"> vertex_shader = glCreateShader(GL_VERTEX_SHADER);</div>
<div class="line"> glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);</div>
<div class="line"> glCompileShader(vertex_shader);</div>
<div class="line"> </div>
<div class="line"> fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);</div>
<div class="line"> glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);</div>
<div class="line"> glCompileShader(fragment_shader);</div>
<div class="line"> </div>
<div class="line"> program = glCreateProgram();</div>
<div class="line"> glAttachShader(program, vertex_shader);</div>
<div class="line"> glAttachShader(program, fragment_shader);</div>
<div class="line"> glLinkProgram(program);</div>
<div class="line"> </div>
<div class="line"> mvp_location = glGetUniformLocation(program, <span class="stringliteral">"MVP"</span>);</div>
<div class="line"> vpos_location = glGetAttribLocation(program, <span class="stringliteral">"vPos"</span>);</div>
<div class="line"> vcol_location = glGetAttribLocation(program, <span class="stringliteral">"vCol"</span>);</div>
<div class="line"> </div>
<div class="line"> glEnableVertexAttribArray(vpos_location);</div>
<div class="line"> glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE,</div>
<div class="line"> <span class="keyword">sizeof</span>(vertices[0]), (<span class="keywordtype">void</span>*) 0);</div>
<div class="line"> glEnableVertexAttribArray(vcol_location);</div>
<div class="line"> glVertexAttribPointer(vcol_location, 3, GL_FLOAT, GL_FALSE,</div>
<div class="line"> <span class="keyword">sizeof</span>(vertices[0]), (<span class="keywordtype">void</span>*) (<span class="keyword">sizeof</span>(<span class="keywordtype">float</span>) * 2));</div>
<div class="line"> </div>
<div class="line"> <span class="keywordflow">while</span> (!<a class="code" href="group__window.html#ga24e02fbfefbb81fc45320989f8140ab5">glfwWindowShouldClose</a>(window))</div>
<div class="line"> {</div>
<div class="line"> <span class="keywordtype">float</span> ratio;</div>
<div class="line"> <span class="keywordtype">int</span> width, height;</div>
<div class="line"> mat4x4 m, p, mvp;</div>
<div class="line"> </div>
<div class="line"> <a class="code" href="group__window.html#ga0e2637a4161afb283f5300c7f94785c9">glfwGetFramebufferSize</a>(window, &width, &height);</div>
<div class="line"> ratio = width / (float) height;</div>
<div class="line"> </div>
<div class="line"> glViewport(0, 0, width, height);</div>
<div class="line"> glClear(GL_COLOR_BUFFER_BIT);</div>
<div class="line"> </div>
<div class="line"> mat4x4_identity(m);</div>
<div class="line"> mat4x4_rotate_Z(m, m, (<span class="keywordtype">float</span>) <a class="code" href="group__input.html#gaa6cf4e7a77158a3b8fd00328b1720a4a">glfwGetTime</a>());</div>
<div class="line"> mat4x4_ortho(p, -ratio, ratio, -1.f, 1.f, 1.f, -1.f);</div>
<div class="line"> mat4x4_mul(mvp, p, m);</div>
<div class="line"> </div>
<div class="line"> glUseProgram(program);</div>
<div class="line"> glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (<span class="keyword">const</span> GLfloat*) mvp);</div>
<div class="line"> glDrawArrays(GL_TRIANGLES, 0, 3);</div>
<div class="line"> </div>
<div class="line"> <a class="code" href="group__window.html#ga15a5a1ee5b3c2ca6b15ca209a12efd14">glfwSwapBuffers</a>(window);</div>
<div class="line"> <a class="code" href="group__window.html#ga37bd57223967b4211d60ca1a0bf3c832">glfwPollEvents</a>();</div>
<div class="line"> }</div>
<div class="line"> </div>
<div class="line"> <a class="code" href="group__window.html#gacdf43e51376051d2c091662e9fe3d7b2">glfwDestroyWindow</a>(window);</div>
<div class="line"> </div>
<div class="line"> <a class="code" href="group__init.html#gaaae48c0a18607ea4a4ba951d939f0901">glfwTerminate</a>();</div>
<div class="line"> exit(EXIT_SUCCESS);</div>
<div class="line">}</div>
<div class="line"> </div>
</div><!-- fragment --><p> The program above can be found in the <a href="https://www.glfw.org/download.html">source package</a> as <code>examples/simple.c</code> and is compiled along with all other examples when you build GLFW. If you built GLFW from the source package then you already have this as <code>simple.exe</code> on Windows, <code>simple</code> on Linux or <code>simple.app</code> on macOS.</p>
<p>This tutorial used only a few of the many functions GLFW provides. There are guides for each of the areas covered by GLFW. Each guide will introduce all the functions for that category.</p>
<ul>
<li><a class="el" href="intro_guide.html">Introduction to the API</a></li>
<li><a class="el" href="window_guide.html">Window guide</a></li>
<li><a class="el" href="context_guide.html">Context guide</a></li>
<li><a class="el" href="monitor_guide.html">Monitor guide</a></li>
<li><a class="el" href="input_guide.html">Input guide</a></li>
</ul>
<p>You can access reference documentation for any GLFW function by clicking it and the reference for each function links to related functions and guide sections.</p>
<p>The tutorial ends here. Once you have written a program that uses GLFW, you will need to compile and link it. How to do that depends on the development environment you are using and is best explained by the documentation for that environment. To learn about the details that are specific to GLFW, see <a class="el" href="build_guide.html">Building applications</a>. </p>
</div></div><!-- contents -->
</div><!-- PageDoc -->
<div class="ttc" id="agroup__input_html_gaa6cf4e7a77158a3b8fd00328b1720a4a"><div class="ttname"><a href="group__input.html#gaa6cf4e7a77158a3b8fd00328b1720a4a">glfwGetTime</a></div><div class="ttdeci">double glfwGetTime(void)</div><div class="ttdoc">Returns the GLFW time.</div></div>
<div class="ttc" id="agroup__input_html_ga2485743d0b59df3791c45951c4195265"><div class="ttname"><a href="group__input.html#ga2485743d0b59df3791c45951c4195265">GLFW_PRESS</a></div><div class="ttdeci">#define GLFW_PRESS</div><div class="ttdoc">The key or mouse button was pressed.</div><div class="ttdef"><b>Definition:</b> glfw3.h:306</div></div>
<div class="ttc" id="aglfw3_8h_html"><div class="ttname"><a href="glfw3_8h.html">glfw3.h</a></div><div class="ttdoc">The header of the GLFW 3 API.</div></div>
<div class="ttc" id="agroup__window_html_ga31aca791e4b538c4e4a771eb95cc2d07"><div class="ttname"><a href="group__window.html#ga31aca791e4b538c4e4a771eb95cc2d07">GLFW_CONTEXT_VERSION_MINOR</a></div><div class="ttdeci">#define GLFW_CONTEXT_VERSION_MINOR</div><div class="ttdoc">Context client API minor version hint and attribute.</div><div class="ttdef"><b>Definition:</b> glfw3.h:929</div></div>
<div class="ttc" id="agroup__window_html_ga3c96d80d363e67d13a41b5d1821f3242"><div class="ttname"><a href="group__window.html#ga3c96d80d363e67d13a41b5d1821f3242">GLFWwindow</a></div><div class="ttdeci">struct GLFWwindow GLFWwindow</div><div class="ttdoc">Opaque window object.</div><div class="ttdef"><b>Definition:</b> glfw3.h:1152</div></div>
<div class="ttc" id="agroup__init_html_gaaae48c0a18607ea4a4ba951d939f0901"><div class="ttname"><a href="group__init.html#gaaae48c0a18607ea4a4ba951d939f0901">glfwTerminate</a></div><div class="ttdeci">void glfwTerminate(void)</div><div class="ttdoc">Terminates the GLFW library.</div></div>
<div class="ttc" id="agroup__window_html_ga15a5a1ee5b3c2ca6b15ca209a12efd14"><div class="ttname"><a href="group__window.html#ga15a5a1ee5b3c2ca6b15ca209a12efd14">glfwSwapBuffers</a></div><div class="ttdeci">void glfwSwapBuffers(GLFWwindow *window)</div><div class="ttdoc">Swaps the front and back buffers of the specified window.</div></div>
<div class="ttc" id="agroup__context_html_ga1c04dc242268f827290fe40aa1c91157"><div class="ttname"><a href="group__context.html#ga1c04dc242268f827290fe40aa1c91157">glfwMakeContextCurrent</a></div><div class="ttdeci">void glfwMakeContextCurrent(GLFWwindow *window)</div><div class="ttdoc">Makes the context of the specified window current for the calling thread.</div></div>
<div class="ttc" id="agroup__context_html_ga6d4e0cdf151b5e579bd67f13202994ed"><div class="ttname"><a href="group__context.html#ga6d4e0cdf151b5e579bd67f13202994ed">glfwSwapInterval</a></div><div class="ttdeci">void glfwSwapInterval(int interval)</div><div class="ttdoc">Sets the swap interval for the current context.</div></div>
<div class="ttc" id="agroup__window_html_ga24e02fbfefbb81fc45320989f8140ab5"><div class="ttname"><a href="group__window.html#ga24e02fbfefbb81fc45320989f8140ab5">glfwWindowShouldClose</a></div><div class="ttdeci">int glfwWindowShouldClose(GLFWwindow *window)</div><div class="ttdoc">Checks the close flag of the specified window.</div></div>
<div class="ttc" id="agroup__window_html_ga37bd57223967b4211d60ca1a0bf3c832"><div class="ttname"><a href="group__window.html#ga37bd57223967b4211d60ca1a0bf3c832">glfwPollEvents</a></div><div class="ttdeci">void glfwPollEvents(void)</div><div class="ttdoc">Processes all pending events.</div></div>
<div class="ttc" id="agroup__init_html_ga2744fbb29b5631bb28802dbe0cf36eba"><div class="ttname"><a href="group__init.html#ga2744fbb29b5631bb28802dbe0cf36eba">GLFW_TRUE</a></div><div class="ttdeci">#define GLFW_TRUE</div><div class="ttdoc">One.</div><div class="ttdef"><b>Definition:</b> glfw3.h:280</div></div>
<div class="ttc" id="agroup__window_html_gafe5e4922de1f9932d7e9849bb053b0c0"><div class="ttname"><a href="group__window.html#gafe5e4922de1f9932d7e9849bb053b0c0">GLFW_CONTEXT_VERSION_MAJOR</a></div><div class="ttdeci">#define GLFW_CONTEXT_VERSION_MAJOR</div><div class="ttdoc">Context client API major version hint and attribute.</div><div class="ttdef"><b>Definition:</b> glfw3.h:923</div></div>
<div class="ttc" id="agroup__window_html_ga5c336fddf2cbb5b92f65f10fb6043344"><div class="ttname"><a href="group__window.html#ga5c336fddf2cbb5b92f65f10fb6043344">glfwCreateWindow</a></div><div class="ttdeci">GLFWwindow * glfwCreateWindow(int width, int height, const char *title, GLFWmonitor *monitor, GLFWwindow *share)</div><div class="ttdoc">Creates a window and its associated context.</div></div>
<div class="ttc" id="agroup__window_html_ga49c449dde2a6f87d996f4daaa09d6708"><div class="ttname"><a href="group__window.html#ga49c449dde2a6f87d996f4daaa09d6708">glfwSetWindowShouldClose</a></div><div class="ttdeci">void glfwSetWindowShouldClose(GLFWwindow *window, int value)</div><div class="ttdoc">Sets the close flag of the specified window.</div></div>
<div class="ttc" id="agroup__keys_html_gaac6596c350b635c245113b81c2123b93"><div class="ttname"><a href="group__keys.html#gaac6596c350b635c245113b81c2123b93">GLFW_KEY_ESCAPE</a></div><div class="ttdeci">#define GLFW_KEY_ESCAPE</div><div class="ttdef"><b>Definition:</b> glfw3.h:414</div></div>
<div class="ttc" id="agroup__init_html_ga317aac130a235ab08c6db0834907d85e"><div class="ttname"><a href="group__init.html#ga317aac130a235ab08c6db0834907d85e">glfwInit</a></div><div class="ttdeci">int glfwInit(void)</div><div class="ttdoc">Initializes the GLFW library.</div></div>
<div class="ttc" id="agroup__context_html_ga35f1837e6f666781842483937612f163"><div class="ttname"><a href="group__context.html#ga35f1837e6f666781842483937612f163">glfwGetProcAddress</a></div><div class="ttdeci">GLFWglproc glfwGetProcAddress(const char *procname)</div><div class="ttdoc">Returns the address of the specified function for the current context.</div></div>
<div class="ttc" id="agroup__input_html_ga1caf18159767e761185e49a3be019f8d"><div class="ttname"><a href="group__input.html#ga1caf18159767e761185e49a3be019f8d">glfwSetKeyCallback</a></div><div class="ttdeci">GLFWkeyfun glfwSetKeyCallback(GLFWwindow *window, GLFWkeyfun callback)</div><div class="ttdoc">Sets the key callback.</div></div>
<div class="ttc" id="agroup__init_html_gaff45816610d53f0b83656092a4034f40"><div class="ttname"><a href="group__init.html#gaff45816610d53f0b83656092a4034f40">glfwSetErrorCallback</a></div><div class="ttdeci">GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun callback)</div><div class="ttdoc">Sets the error callback.</div></div>
<div class="ttc" id="agroup__window_html_ga0e2637a4161afb283f5300c7f94785c9"><div class="ttname"><a href="group__window.html#ga0e2637a4161afb283f5300c7f94785c9">glfwGetFramebufferSize</a></div><div class="ttdeci">void glfwGetFramebufferSize(GLFWwindow *window, int *width, int *height)</div><div class="ttdoc">Retrieves the size of the framebuffer of the specified window.</div></div>
<div class="ttc" id="agroup__window_html_ga7d9c8c62384b1e2821c4dc48952d2033"><div class="ttname"><a href="group__window.html#ga7d9c8c62384b1e2821c4dc48952d2033">glfwWindowHint</a></div><div class="ttdeci">void glfwWindowHint(int hint, int value)</div><div class="ttdoc">Sets the specified window hint to the desired value.</div></div>
<div class="ttc" id="agroup__window_html_gacdf43e51376051d2c091662e9fe3d7b2"><div class="ttname"><a href="group__window.html#gacdf43e51376051d2c091662e9fe3d7b2">glfwDestroyWindow</a></div><div class="ttdeci">void glfwDestroyWindow(GLFWwindow *window)</div><div class="ttdoc">Destroys the specified window and its context.</div></div>
<address class="footer">
<p>
Last update on Mon Jan 20 2020 for GLFW 3.3.2
</p>
</address>
</body>
</html>
| mpl-2.0 |
Yukarumya/Yukarum-Redfoxes | layout/reftests/bugs/428810-2f-ltr.html | 354 | <!DOCTYPE HTML>
<title>Testcase, bug 428810</title>
<style type="text/css">
html, body { margin: 0; padding: 0; }
</style>
<div style="height: 10px">
<div style="float: left; height: 20px; width: 100px"></div>
</div>
<div style="margin-left: 40px; width: 70px; display: list-item;">
<div style="float: left; height: 20px; width: 15px"></div>
</div>
| mpl-2.0 |
Yukarumya/Yukarum-Redfoxes | dom/canvas/test/webgl-conf/generated/test_2_conformance__ogles__GL__functions__functions_017_to_024.html | 570 | <!-- GENERATED FILE, DO NOT EDIT -->
<!DOCTYPE HTML>
<html>
<head>
<meta charset='utf-8'/>
<title>
Mochitest wrapper for WebGL Conformance Test Suite tests
</title>
<link rel='stylesheet' type='text/css' href='../iframe-passthrough.css'/>
<script src='/tests/SimpleTest/SimpleTest.js'></script>
<link rel='stylesheet' type='text/css' href='/tests/SimpleTest/test.css'/>
</head>
<body>
<iframe src='../mochi-single.html?checkout/conformance/ogles/GL/functions/functions_017_to_024.html?webglVersion=2'></iframe>
</body>
</html>
| mpl-2.0 |
Yukarumya/Yukarum-Redfoxes | dom/canvas/test/webgl-conf/generated/test_2_conformance2__textures__image_data__tex-3d-rgb5_a1-rgba-unsigned_short_5_5_5_1.html | 594 | <!-- GENERATED FILE, DO NOT EDIT -->
<!DOCTYPE HTML>
<html>
<head>
<meta charset='utf-8'/>
<title>
Mochitest wrapper for WebGL Conformance Test Suite tests
</title>
<link rel='stylesheet' type='text/css' href='../iframe-passthrough.css'/>
<script src='/tests/SimpleTest/SimpleTest.js'></script>
<link rel='stylesheet' type='text/css' href='/tests/SimpleTest/test.css'/>
</head>
<body>
<iframe src='../mochi-single.html?checkout/conformance2/textures/image_data/tex-3d-rgb5_a1-rgba-unsigned_short_5_5_5_1.html?webglVersion=2'></iframe>
</body>
</html>
| mpl-2.0 |
Yukarumya/Yukarum-Redfoxes | dom/canvas/test/reftest/filters/subregion-ref.html | 260 | <!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="100" height="100"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#0f0';
ctx.fillRect(25, 25, 50, 50);
</script>
</body>
</html>
| mpl-2.0 |
peterjoel/servo | tests/wpt/web-platform-tests/css/css-text/overflow-wrap/word-wrap-004.html | 776 | <!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Text Test: word-wrap - normal (basic)</title>
<link rel="author" title="Intel" href="http://www.intel.com">
<link rel="author" title="Shiyou Tan" href="mailto:shiyoux.tan@intel.com">
<link rel="help" href="http://www.w3.org/TR/css-text-3/#overflow-wrap-property">
<link rel="match" href="overflow-wrap-004-ref.html">
<meta name="flags" content="ahem">
<meta name="assert" content="The 'word-wrap' property set 'normal' overflows container">
<style>
#test {
border: 5px solid orange;
font: 20px/1 Ahem;
word-wrap: normal;
width: 200px;
}
</style>
<body>
<p class="instructions">Test passes if the black box overflows the orange box.</p>
<p id="test">FillerTextFillerTextFillerTextFillerText</p>
</body>
| mpl-2.0 |
dayglojesus/packer | builder/profitbricks/step_create_server.go | 6663 | package profitbricks
import (
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/hashicorp/packer/packer"
"github.com/mitchellh/multistep"
"github.com/profitbricks/profitbricks-sdk-go"
)
type stepCreateServer struct{}
func (s *stepCreateServer) Run(state multistep.StateBag) multistep.StepAction {
ui := state.Get("ui").(packer.Ui)
c := state.Get("config").(*Config)
profitbricks.SetAuth(c.PBUsername, c.PBPassword)
profitbricks.SetDepth("5")
if sshkey, ok := state.GetOk("publicKey"); ok {
c.SSHKey = sshkey.(string)
}
ui.Say("Creating Virtual Data Center...")
img := s.getImageId(c.Image, c)
datacenter := profitbricks.Datacenter{
Properties: profitbricks.DatacenterProperties{
Name: c.SnapshotName,
Location: c.Region,
},
Entities: profitbricks.DatacenterEntities{
Servers: &profitbricks.Servers{
Items: []profitbricks.Server{
{
Properties: profitbricks.ServerProperties{
Name: c.SnapshotName,
Ram: c.Ram,
Cores: c.Cores,
},
Entities: &profitbricks.ServerEntities{
Volumes: &profitbricks.Volumes{
Items: []profitbricks.Volume{
{
Properties: profitbricks.VolumeProperties{
Type: c.DiskType,
Size: c.DiskSize,
Name: c.SnapshotName,
Image: img,
},
},
},
},
},
},
},
},
},
}
if c.SSHKey != "" {
datacenter.Entities.Servers.Items[0].Entities.Volumes.Items[0].Properties.SshKeys = []string{c.SSHKey}
}
if c.Comm.SSHPassword != "" {
datacenter.Entities.Servers.Items[0].Entities.Volumes.Items[0].Properties.ImagePassword = c.Comm.SSHPassword
}
datacenter = profitbricks.CompositeCreateDatacenter(datacenter)
if datacenter.StatusCode > 299 {
if datacenter.StatusCode > 299 {
var restError RestError
err := json.Unmarshal([]byte(datacenter.Response), &restError)
if err != nil {
ui.Error(fmt.Sprintf("Error decoding json response: %s", err.Error()))
return multistep.ActionHalt
}
if len(restError.Messages) > 0 {
ui.Error(restError.Messages[0].Message)
} else {
ui.Error(datacenter.Response)
}
return multistep.ActionHalt
}
}
err := s.waitTillProvisioned(datacenter.Headers.Get("Location"), *c)
if err != nil {
ui.Error(fmt.Sprintf("Error occurred while creating a datacenter %s", err.Error()))
return multistep.ActionHalt
}
state.Put("datacenter_id", datacenter.Id)
lan := profitbricks.CreateLan(datacenter.Id, profitbricks.Lan{
Properties: profitbricks.LanProperties{
Public: true,
Name: c.SnapshotName,
},
})
if lan.StatusCode > 299 {
ui.Error(fmt.Sprintf("Error occurred %s", parseErrorMessage(lan.Response)))
return multistep.ActionHalt
}
err = s.waitTillProvisioned(lan.Headers.Get("Location"), *c)
if err != nil {
ui.Error(fmt.Sprintf("Error occurred while creating a LAN %s", err.Error()))
return multistep.ActionHalt
}
lanId, _ := strconv.Atoi(lan.Id)
nic := profitbricks.CreateNic(datacenter.Id, datacenter.Entities.Servers.Items[0].Id, profitbricks.Nic{
Properties: profitbricks.NicProperties{
Name: c.SnapshotName,
Lan: lanId,
Dhcp: true,
},
})
if lan.StatusCode > 299 {
ui.Error(fmt.Sprintf("Error occurred %s", parseErrorMessage(nic.Response)))
return multistep.ActionHalt
}
err = s.waitTillProvisioned(nic.Headers.Get("Location"), *c)
if err != nil {
ui.Error(fmt.Sprintf("Error occurred while creating a NIC %s", err.Error()))
return multistep.ActionHalt
}
state.Put("volume_id", datacenter.Entities.Servers.Items[0].Entities.Volumes.Items[0].Id)
server := profitbricks.GetServer(datacenter.Id, datacenter.Entities.Servers.Items[0].Id)
state.Put("server_ip", server.Entities.Nics.Items[0].Properties.Ips[0])
return multistep.ActionContinue
}
func (s *stepCreateServer) Cleanup(state multistep.StateBag) {
c := state.Get("config").(*Config)
ui := state.Get("ui").(packer.Ui)
ui.Say("Removing Virtual Data Center...")
profitbricks.SetAuth(c.PBUsername, c.PBPassword)
if dcId, ok := state.GetOk("datacenter_id"); ok {
resp := profitbricks.DeleteDatacenter(dcId.(string))
if err := s.checkForErrors(resp); err != nil {
ui.Error(fmt.Sprintf(
"Error deleting Virtual Data Center. Please destroy it manually: %s", err))
}
if err := s.waitTillProvisioned(resp.Headers.Get("Location"), *c); err != nil {
ui.Error(fmt.Sprintf(
"Error deleting Virtual Data Center. Please destroy it manually: %s", err))
}
}
}
func (d *stepCreateServer) waitTillProvisioned(path string, config Config) error {
d.setPB(config.PBUsername, config.PBPassword, config.PBUrl)
waitCount := 120
if config.Retries > 0 {
waitCount = config.Retries
}
for i := 0; i < waitCount; i++ {
request := profitbricks.GetRequestStatus(path)
if request.Metadata.Status == "DONE" {
return nil
}
if request.Metadata.Status == "FAILED" {
return errors.New(request.Metadata.Message)
}
time.Sleep(1 * time.Second)
i++
}
return nil
}
func (d *stepCreateServer) setPB(username string, password string, url string) {
profitbricks.SetAuth(username, password)
profitbricks.SetEndpoint(url)
}
func (d *stepCreateServer) checkForErrors(instance profitbricks.Resp) error {
if instance.StatusCode > 299 {
return errors.New(fmt.Sprintf("Error occurred %s", string(instance.Body)))
}
return nil
}
type RestError struct {
HttpStatus int `json:"httpStatus,omitempty"`
Messages []Message `json:"messages,omitempty"`
}
type Message struct {
ErrorCode string `json:"errorCode,omitempty"`
Message string `json:"message,omitempty"`
}
func (d *stepCreateServer) getImageId(imageName string, c *Config) string {
d.setPB(c.PBUsername, c.PBPassword, c.PBUrl)
images := profitbricks.ListImages()
for i := 0; i < len(images.Items); i++ {
imgName := ""
if images.Items[i].Properties.Name != "" {
imgName = images.Items[i].Properties.Name
}
diskType := c.DiskType
if c.DiskType == "SSD" {
diskType = "HDD"
}
if imgName != "" && strings.Contains(strings.ToLower(imgName), strings.ToLower(imageName)) && images.Items[i].Properties.ImageType == diskType && images.Items[i].Properties.Location == c.Region && images.Items[i].Properties.Public == true {
return images.Items[i].Id
}
}
return ""
}
func parseErrorMessage(raw string) (toreturn string) {
var tmp map[string]interface{}
json.Unmarshal([]byte(raw), &tmp)
for _, v := range tmp["messages"].([]interface{}) {
for index, i := range v.(map[string]interface{}) {
if index == "message" {
toreturn = toreturn + i.(string) + "\n"
}
}
}
return toreturn
}
| mpl-2.0 |
co-ment/comt | src/cm/media/js/lib/yui/yui3-3.15.0/src/scrollview/js/scrollview.js | 556 | /**
* <p>
* The scrollview module does not add any new classes. It simply plugs the ScrollViewScrollbars plugin into the
* base ScrollView class implementation provided by the scrollview-base module, so that all scrollview instances
* have scrollbars enabled.
* </p>
*
* <ul>
* <li><a href="../classes/ScrollView.html">ScrollView API documentation</a></li>
* <li><a href="scrollview-base.html">scrollview-base Module documentation</a></li>
* </ul>
*
* @module scrollview
*/
Y.Base.plug(Y.ScrollView, Y.Plugin.ScrollViewScrollbars);
| agpl-3.0 |
alexhuang888/xibo-cms | lib/Factory/CommandFactory.php | 4638 | <?php
/*
* Spring Signage Ltd - http://www.springsignage.com
* Copyright (C) 2015 Spring Signage Ltd
* (CommandFactory.php)
*/
namespace Xibo\Factory;
use Xibo\Entity\Command;
use Xibo\Entity\User;
use Xibo\Exception\NotFoundException;
use Xibo\Service\LogServiceInterface;
use Xibo\Service\SanitizerServiceInterface;
use Xibo\Storage\StorageServiceInterface;
/**
* Class CommandFactory
* @package Xibo\Factory
*/
class CommandFactory extends BaseFactory
{
/**
* @var DisplayProfileFactory
*/
private $displayProfileFactory;
/**
* Construct a factory
* @param StorageServiceInterface $store
* @param LogServiceInterface $log
* @param SanitizerServiceInterface $sanitizerService
* @param User $user
* @param UserFactory $userFactory
*/
public function __construct($store, $log, $sanitizerService, $user, $userFactory)
{
$this->setCommonDependencies($store, $log, $sanitizerService);
$this->setAclDependencies($user, $userFactory);
}
/**
* Create Command
* @return Command
*/
public function create()
{
return new Command($this->getStore(), $this->getLog());
}
/**
* Get by Id
* @param $commandId
* @return Command
* @throws NotFoundException
*/
public function getById($commandId)
{
$commands = $this->query(null, ['commandId' => $commandId]);
if (count($commands) <= 0)
throw new NotFoundException();
return $commands[0];
}
/**
* Get by Display Profile Id
* @param $displayProfileId
* @return array[Command]
*/
public function getByDisplayProfileId($displayProfileId)
{
return $this->query(null, ['displayProfileId' => $displayProfileId]);
}
/**
* @param array $sortOrder
* @param array $filterBy
* @return array
*/
public function query($sortOrder = null, $filterBy = null)
{
$entries = array();
if ($sortOrder == null)
$sortOrder = ['command'];
$params = array();
$select = 'SELECT `command`.commandId, `command`.command, `command`.code, `command`.description, `command`.userId ';
if ($this->getSanitizer()->getInt('displayProfileId', $filterBy) !== null) {
$select .= ', commandString, validationString ';
}
$body = ' FROM `command` ';
if ($this->getSanitizer()->getInt('displayProfileId', $filterBy) !== null) {
$body .= '
INNER JOIN `lkcommanddisplayprofile`
ON `lkcommanddisplayprofile`.commandId = `command`.commandId
AND `lkcommanddisplayprofile`.displayProfileId = :displayProfileId
';
$params['displayProfileId'] = $this->getSanitizer()->getInt('displayProfileId', $filterBy);
}
$body .= ' WHERE 1 = 1 ';
if ($this->getSanitizer()->getInt('commandId', $filterBy) !== null) {
$body .= ' AND `command`.commandId = :commandId ';
$params['commandId'] = $this->getSanitizer()->getInt('commandId', $filterBy);
}
if ($this->getSanitizer()->getString('command', $filterBy) != null) {
$body .= ' AND `command`.command = :command ';
$params['command'] = $this->getSanitizer()->getString('command', $filterBy);
}
if ($this->getSanitizer()->getString('code', $filterBy) != null) {
$body .= ' AND `code`.code = :code ';
$params['code'] = $this->getSanitizer()->getString('code', $filterBy);
}
// Sorting?
$order = '';
if (is_array($sortOrder))
$order .= 'ORDER BY ' . implode(',', $sortOrder);
$limit = '';
// Paging
if ($filterBy !== null && $this->getSanitizer()->getInt('start', $filterBy) !== null && $this->getSanitizer()->getInt('length', $filterBy) !== null) {
$limit = ' LIMIT ' . intval($this->getSanitizer()->getInt('start', $filterBy), 0) . ', ' . $this->getSanitizer()->getInt('length', 10, $filterBy);
}
$sql = $select . $body . $order . $limit;
foreach ($this->getStore()->select($sql, $params) as $row) {
$entries[] = (new Command($this->getStore(), $this->getLog(), $this->displayProfileFactory))->hydrate($row);
}
// Paging
if ($limit != '' && count($entries) > 0) {
$results = $this->getStore()->select('SELECT COUNT(*) AS total ' . $body, $params);
$this->_countLast = intval($results[0]['total']);
}
return $entries;
}
} | agpl-3.0 |
Open365/spice-web-client | misc/spice-0.12.0/client/red_channel.cpp | 27728 | /* -*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
Copyright (C) 2009 Red Hat, Inc.
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, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "common.h"
#include "red_channel.h"
#include "red_client.h"
#include "application.h"
#include "debug.h"
#include "utils.h"
#include "openssl/rsa.h"
#include "openssl/evp.h"
#include "openssl/x509.h"
void MigrationDisconnectSrcEvent::response(AbstractProcessLoop& events_loop)
{
static_cast<RedChannel*>(events_loop.get_owner())->do_migration_disconnect_src();
}
void MigrationConnectTargetEvent::response(AbstractProcessLoop& events_loop)
{
static_cast<RedChannel*>(events_loop.get_owner())->do_migration_connect_target();
}
RedChannelBase::RedChannelBase(uint8_t type, uint8_t id, const ChannelCaps& common_caps,
const ChannelCaps& caps)
: RedPeer()
, _type (type)
, _id (id)
, _common_caps (common_caps)
, _caps (caps)
{
}
RedChannelBase::~RedChannelBase()
{
}
static const char *spice_link_error_string(int err)
{
switch (err) {
case SPICE_LINK_ERR_OK: return "no error";
case SPICE_LINK_ERR_ERROR: return "general error";
case SPICE_LINK_ERR_INVALID_MAGIC: return "invalid magic";
case SPICE_LINK_ERR_INVALID_DATA: return "invalid data";
case SPICE_LINK_ERR_VERSION_MISMATCH: return "version mismatch";
case SPICE_LINK_ERR_NEED_SECURED: return "need secured connection";
case SPICE_LINK_ERR_NEED_UNSECURED: return "need unsecured connection";
case SPICE_LINK_ERR_PERMISSION_DENIED: return "permission denied";
case SPICE_LINK_ERR_BAD_CONNECTION_ID: return "bad connection id";
case SPICE_LINK_ERR_CHANNEL_NOT_AVAILABLE: return "channel not available";
}
return "";
}
void RedChannelBase::link(uint32_t connection_id, const std::string& password,
int protocol)
{
SpiceLinkHeader header;
SpiceLinkMess link_mess;
SpiceLinkReply* reply;
uint32_t link_res;
uint32_t i;
BIO *bioKey;
uint8_t *buffer, *p;
uint32_t expected_major;
header.magic = SPICE_MAGIC;
header.size = sizeof(link_mess);
if (protocol == 1) {
/* protocol 1 == major 1, old 0.4 protocol, last active minor */
expected_major = header.major_version = 1;
header.minor_version = 3;
} else if (protocol == 2) {
/* protocol 2 == current */
expected_major = header.major_version = SPICE_VERSION_MAJOR;
header.minor_version = SPICE_VERSION_MINOR;
} else {
THROW("unsupported protocol version specified");
}
link_mess.connection_id = connection_id;
link_mess.channel_type = _type;
link_mess.channel_id = _id;
link_mess.num_common_caps = get_common_caps().size();
link_mess.num_channel_caps = get_caps().size();
link_mess.caps_offset = sizeof(link_mess);
header.size += (link_mess.num_common_caps + link_mess.num_channel_caps) * sizeof(uint32_t);
buffer =
new uint8_t[sizeof(header) + sizeof(link_mess) +
_common_caps.size() * sizeof(uint32_t) +
_caps.size() * sizeof(uint32_t)];
p = buffer;
memcpy(p, (uint8_t*)&header, sizeof(header));
p += sizeof(header);
memcpy(p, (uint8_t*)&link_mess, sizeof(link_mess));
p += sizeof(link_mess);
for (i = 0; i < _common_caps.size(); i++) {
*(uint32_t *)p = _common_caps[i];
p += sizeof(uint32_t);
}
for (i = 0; i < _caps.size(); i++) {
*(uint32_t *)p = _caps[i];
p += sizeof(uint32_t);
}
send(buffer, p - buffer);
delete [] buffer;
receive((uint8_t*)&header, sizeof(header));
if (header.magic != SPICE_MAGIC) {
THROW_ERR(SPICEC_ERROR_CODE_CONNECT_FAILED, "bad magic");
}
if (header.major_version != expected_major) {
THROW_ERR(SPICEC_ERROR_CODE_VERSION_MISMATCH,
"version mismatch: expect %u got %u",
expected_major,
header.major_version);
}
_remote_major = header.major_version;
_remote_minor = header.minor_version;
AutoArray<uint8_t> reply_buf(new uint8_t[header.size]);
receive(reply_buf.get(), header.size);
reply = (SpiceLinkReply *)reply_buf.get();
if (reply->error != SPICE_LINK_ERR_OK) {
THROW_ERR(SPICEC_ERROR_CODE_CONNECT_FAILED, "connect error %u - %s",
reply->error, spice_link_error_string(reply->error));
}
uint32_t num_caps = reply->num_channel_caps + reply->num_common_caps;
if ((uint8_t *)(reply + 1) > reply_buf.get() + header.size ||
(uint8_t *)reply + reply->caps_offset + num_caps * sizeof(uint32_t) >
reply_buf.get() + header.size) {
THROW_ERR(SPICEC_ERROR_CODE_CONNECT_FAILED, "access violation");
}
uint32_t *caps = (uint32_t *)((uint8_t *)reply + reply->caps_offset);
_remote_common_caps.clear();
for (i = 0; i < reply->num_common_caps; i++, caps++) {
_remote_common_caps.resize(i + 1);
_remote_common_caps[i] = *caps;
}
_remote_caps.clear();
for (i = 0; i < reply->num_channel_caps; i++, caps++) {
_remote_caps.resize(i + 1);
_remote_caps[i] = *caps;
}
bioKey = BIO_new(BIO_s_mem());
if (bioKey != NULL) {
EVP_PKEY *pubkey;
int nRSASize;
RSA *rsa;
BIO_write(bioKey, reply->pub_key, SPICE_TICKET_PUBKEY_BYTES);
pubkey = d2i_PUBKEY_bio(bioKey, NULL);
rsa = pubkey->pkey.rsa;
nRSASize = RSA_size(rsa);
AutoArray<unsigned char> bufEncrypted(new unsigned char[nRSASize]);
/*
The use of RSA encryption limit the potential maximum password length.
for RSA_PKCS1_OAEP_PADDING it is RSA_size(rsa) - 41.
*/
if (RSA_public_encrypt(password.length() + 1, (unsigned char *)password.c_str(),
(uint8_t *)bufEncrypted.get(),
rsa, RSA_PKCS1_OAEP_PADDING) > 0) {
send((uint8_t*)bufEncrypted.get(), nRSASize);
} else {
EVP_PKEY_free(pubkey);
BIO_free(bioKey);
THROW("could not encrypt password");
}
memset(bufEncrypted.get(), 0, nRSASize);
EVP_PKEY_free(pubkey);
} else {
THROW("Could not initiate BIO");
}
BIO_free(bioKey);
receive((uint8_t*)&link_res, sizeof(link_res));
if (link_res != SPICE_LINK_ERR_OK) {
int error_code = (link_res == SPICE_LINK_ERR_PERMISSION_DENIED) ?
SPICEC_ERROR_CODE_CONNECT_FAILED : SPICEC_ERROR_CODE_CONNECT_FAILED;
THROW_ERR(error_code, "connect failed %u", link_res);
}
}
void RedChannelBase::connect(const ConnectionOptions& options, uint32_t connection_id,
const char* host, std::string password)
{
int protocol = options.protocol;
if (protocol == 0) { /* AUTO, try major 2 first */
protocol = 2;
}
retry:
try {
if (options.allow_unsecure()) {
try {
RedPeer::connect_unsecure(host, options.unsecure_port);
link(connection_id, password, protocol);
return;
} catch (Exception& e) {
// On protocol version mismatch, don't connect_secure with the same version
if (e.get_error_code() == SPICEC_ERROR_CODE_VERSION_MISMATCH ||
!options.allow_secure()) {
throw;
}
RedPeer::close();
}
}
ASSERT(options.allow_secure());
RedPeer::connect_secure(options, host);
link(connection_id, password, protocol);
} catch (Exception& e) {
// On protocol version mismatch, retry with older version
if (e.get_error_code() == SPICEC_ERROR_CODE_VERSION_MISMATCH &&
protocol == 2 && options.protocol == 0) {
RedPeer::cleanup();
protocol = 1;
goto retry;
}
throw;
}
}
void RedChannelBase::set_capability(ChannelCaps& caps, uint32_t cap)
{
uint32_t word_index = cap / 32;
if (caps.size() < word_index + 1) {
caps.resize(word_index + 1);
}
caps[word_index] |= 1 << (cap % 32);
}
void RedChannelBase::set_common_capability(uint32_t cap)
{
set_capability(_common_caps, cap);
}
void RedChannelBase::set_capability(uint32_t cap)
{
set_capability(_caps, cap);
}
bool RedChannelBase::test_capability(const ChannelCaps& caps, uint32_t cap)
{
uint32_t word_index = cap / 32;
if (caps.size() < word_index + 1) {
return false;
}
return (caps[word_index] & (1 << (cap % 32))) != 0;
}
bool RedChannelBase::test_common_capability(uint32_t cap)
{
return test_capability(_remote_common_caps, cap);
}
bool RedChannelBase::test_capability(uint32_t cap)
{
return test_capability(_remote_caps, cap);
}
void RedChannelBase::swap(RedChannelBase* other)
{
int tmp_ver;
RedPeer::swap(other);
tmp_ver = _remote_major;
_remote_major = other->_remote_major;
other->_remote_major = tmp_ver;
tmp_ver = _remote_minor;
_remote_minor = other->_remote_minor;
other->_remote_minor = tmp_ver;
}
SendTrigger::SendTrigger(RedChannel& channel)
: _channel (channel)
{
}
void SendTrigger::on_event()
{
_channel.on_send_trigger();
}
SPICE_GNUC_NORETURN void AbortTrigger::on_event()
{
THROW("abort");
}
RedChannel::RedChannel(RedClient& client, uint8_t type, uint8_t id,
RedChannel::MessageHandler* handler,
Platform::ThreadPriority worker_priority)
: RedChannelBase(type, id, ChannelCaps(), ChannelCaps())
, _marshallers (NULL)
, _client (client)
, _state (PASSIVE_STATE)
, _action (WAIT_ACTION)
, _error (SPICEC_ERROR_CODE_SUCCESS)
, _wait_for_threads (true)
, _socket_in_loop (false)
, _worker (NULL)
, _worker_priority (worker_priority)
, _message_handler (handler)
, _outgoing_message (NULL)
, _incomming_header_pos (0)
, _incomming_message (NULL)
, _message_ack_count (0)
, _message_ack_window (0)
, _loop (this)
, _send_trigger (*this)
, _disconnect_stamp (0)
, _disconnect_reason (SPICE_LINK_ERR_OK)
{
_loop.add_trigger(_send_trigger);
_loop.add_trigger(_abort_trigger);
}
RedChannel::~RedChannel()
{
ASSERT(_state == TERMINATED_STATE || _state == PASSIVE_STATE);
delete _worker;
}
void* RedChannel::worker_main(void *data)
{
try {
RedChannel* channel = static_cast<RedChannel*>(data);
channel->set_state(DISCONNECTED_STATE);
Platform::set_thread_priority(NULL, channel->get_worker_priority());
channel->run();
} catch (Exception& e) {
LOG_ERROR("unhandled exception: %s", e.what());
} catch (std::exception& e) {
LOG_ERROR("unhandled exception: %s", e.what());
} catch (...) {
LOG_ERROR("unhandled exception");
}
return NULL;
}
void RedChannel::post_message(RedChannel::OutMessage* message)
{
Lock lock(_outgoing_lock);
_outgoing_messages.push_back(message);
lock.unlock();
_send_trigger.trigger();
}
RedPeer::CompoundInMessage *RedChannel::receive()
{
CompoundInMessage *message = RedChannelBase::receive();
on_message_received();
return message;
}
RedChannel::OutMessage* RedChannel::get_outgoing_message()
{
if (_state != CONNECTED_STATE || _outgoing_messages.empty()) {
return NULL;
}
RedChannel::OutMessage* message = _outgoing_messages.front();
_outgoing_messages.pop_front();
return message;
}
class AutoMessage {
public:
AutoMessage(RedChannel::OutMessage* message) : _message (message) {}
~AutoMessage() {if (_message) _message->release();}
void set(RedChannel::OutMessage* message) { _message = message;}
RedChannel::OutMessage* get() { return _message;}
RedChannel::OutMessage* release();
private:
RedChannel::OutMessage* _message;
};
RedChannel::OutMessage* AutoMessage::release()
{
RedChannel::OutMessage* ret = _message;
_message = NULL;
return ret;
}
void RedChannel::start()
{
ASSERT(!_worker);
_worker = new Thread(RedChannel::worker_main, this);
Lock lock(_state_lock);
while (_state == PASSIVE_STATE) {
_state_cond.wait(lock);
}
}
void RedChannel::set_state(int state)
{
Lock lock(_state_lock);
_state = state;
_state_cond.notify_all();
}
void RedChannel::connect()
{
Lock lock(_action_lock);
if (_state != DISCONNECTED_STATE && _state != PASSIVE_STATE) {
return;
}
_action = CONNECT_ACTION;
_action_cond.notify_one();
}
void RedChannel::disconnect()
{
clear_outgoing_messages();
Lock lock(_action_lock);
if (_state != CONNECTING_STATE && _state != CONNECTED_STATE) {
return;
}
_action = DISCONNECT_ACTION;
RedPeer::disconnect();
_action_cond.notify_one();
}
void RedChannel::disconnect_migration_src()
{
clear_outgoing_messages();
Lock lock(_action_lock);
if (_state == CONNECTING_STATE || _state == CONNECTED_STATE) {
AutoRef<MigrationDisconnectSrcEvent> migrate_event(new MigrationDisconnectSrcEvent());
_loop.push_event(*migrate_event);
}
}
void RedChannel::connect_migration_target()
{
LOG_INFO("");
AutoRef<MigrationConnectTargetEvent> migrate_event(new MigrationConnectTargetEvent());
_loop.push_event(*migrate_event);
}
void RedChannel::do_migration_disconnect_src()
{
if (_socket_in_loop) {
_socket_in_loop = false;
_loop.remove_socket(*this);
}
clear_outgoing_messages();
if (_outgoing_message) {
_outgoing_message->release();
_outgoing_message = NULL;
}
_incomming_header_pos = 0;
if (_incomming_message) {
_incomming_message->unref();
_incomming_message = NULL;
}
on_disconnect_mig_src();
get_client().migrate_channel(*this);
get_client().on_channel_disconnect_mig_src_completed(*this);
}
void RedChannel::do_migration_connect_target()
{
LOG_INFO("");
ASSERT(get_client().get_protocol() != 0);
if (get_client().get_protocol() == 1) {
_marshallers = spice_message_marshallers_get1();
} else {
_marshallers = spice_message_marshallers_get();
}
_loop.add_socket(*this);
_socket_in_loop = true;
on_connect_mig_target();
set_state(CONNECTED_STATE);
on_event();
}
void RedChannel::clear_outgoing_messages()
{
Lock lock(_outgoing_lock);
while (!_outgoing_messages.empty()) {
RedChannel::OutMessage* message = _outgoing_messages.front();
_outgoing_messages.pop_front();
message->release();
}
}
void RedChannel::run()
{
for (;;) {
Lock lock(_action_lock);
if (_action == WAIT_ACTION) {
_action_cond.wait(lock);
}
int action = _action;
_action = WAIT_ACTION;
lock.unlock();
switch (action) {
case CONNECT_ACTION:
try {
get_client().get_sync_info(get_type(), get_id(), _sync_info);
on_connecting();
set_state(CONNECTING_STATE);
ConnectionOptions con_options(_client.get_connection_options(get_type()),
_client.get_port(),
_client.get_sport(),
_client.get_protocol(),
_client.get_host_auth_options(),
_client.get_connection_ciphers());
RedChannelBase::connect(con_options, _client.get_connection_id(),
_client.get_host().c_str(),
_client.get_password().c_str());
/* If automatic protocol, remember the first connect protocol type */
if (_client.get_protocol() == 0) {
if (get_peer_major() == 1) {
_client.set_protocol(1);
} else {
/* Major is 2 or unstable high value, use 2 */
_client.set_protocol(2);
}
}
/* Initialize when we know the remote major version */
if (_client.get_peer_major() == 1) {
_marshallers = spice_message_marshallers_get1();
} else {
_marshallers = spice_message_marshallers_get();
}
on_connect();
set_state(CONNECTED_STATE);
_loop.add_socket(*this);
_socket_in_loop = true;
on_event();
_loop.run();
} catch (RedPeer::DisconnectedException&) {
_error = SPICEC_ERROR_CODE_SUCCESS;
} catch (Exception& e) {
LOG_WARN("%s", e.what());
_error = e.get_error_code();
} catch (std::exception& e) {
LOG_WARN("%s", e.what());
_error = SPICEC_ERROR_CODE_ERROR;
}
if (_socket_in_loop) {
_socket_in_loop = false;
_loop.remove_socket(*this);
}
if (_outgoing_message) {
_outgoing_message->release();
_outgoing_message = NULL;
}
_incomming_header_pos = 0;
if (_incomming_message) {
_incomming_message->unref();
_incomming_message = NULL;
}
case DISCONNECT_ACTION:
close();
on_disconnect();
set_state(DISCONNECTED_STATE);
_client.on_channel_disconnected(*this);
continue;
case QUIT_ACTION:
set_state(TERMINATED_STATE);
return;
}
}
}
bool RedChannel::abort()
{
clear_outgoing_messages();
Lock lock(_action_lock);
if (_state == TERMINATED_STATE) {
if (_wait_for_threads) {
_wait_for_threads = false;
_worker->join();
}
return true;
}
_action = QUIT_ACTION;
_action_cond.notify_one();
lock.unlock();
RedPeer::disconnect();
_abort_trigger.trigger();
for (;;) {
Lock state_lock(_state_lock);
if (_state == TERMINATED_STATE) {
break;
}
uint64_t timout = 1000 * 1000 * 100; // 100ms
if (!_state_cond.timed_wait(state_lock, timout)) {
return false;
}
}
if (_wait_for_threads) {
_wait_for_threads = false;
_worker->join();
}
return true;
}
void RedChannel::send_messages()
{
if (_outgoing_message) {
return;
}
for (;;) {
Lock lock(_outgoing_lock);
AutoMessage message(get_outgoing_message());
if (!message.get()) {
return;
}
RedPeer::OutMessage& peer_message = message.get()->peer_message();
uint32_t n = send(peer_message);
if (n != peer_message.message_size()) {
_outgoing_message = message.release();
_outgoing_pos = n;
return;
}
}
}
void RedChannel::on_send_trigger()
{
send_messages();
}
void RedChannel::on_message_received()
{
if (_message_ack_count && !--_message_ack_count) {
post_message(new Message(SPICE_MSGC_ACK));
_message_ack_count = _message_ack_window;
}
}
void RedChannel::on_message_complition(uint64_t serial)
{
Lock lock(*_sync_info.lock);
*_sync_info.message_serial = serial;
_sync_info.condition->notify_all();
}
void RedChannel::receive_messages()
{
for (;;) {
uint32_t n = RedPeer::receive((uint8_t*)&_incomming_header, sizeof(SpiceDataHeader));
if (n != sizeof(SpiceDataHeader)) {
_incomming_header_pos = n;
return;
}
AutoRef<CompoundInMessage> message(new CompoundInMessage(_incomming_header.serial,
_incomming_header.type,
_incomming_header.size,
_incomming_header.sub_list));
n = RedPeer::receive((*message)->data(), (*message)->compound_size());
if (n != (*message)->compound_size()) {
_incomming_message = message.release();
_incomming_message_pos = n;
return;
}
on_message_received();
_message_handler->handle_message(*(*message));
on_message_complition((*message)->serial());
}
}
void RedChannel::on_event()
{
if (_outgoing_message) {
RedPeer::OutMessage& peer_message = _outgoing_message->peer_message();
_outgoing_pos += do_send(peer_message, _outgoing_pos);
if (_outgoing_pos == peer_message.message_size()) {
_outgoing_message->release();
_outgoing_message = NULL;
}
}
send_messages();
if (_incomming_header_pos) {
_incomming_header_pos += RedPeer::receive(((uint8_t*)&_incomming_header) +
_incomming_header_pos,
sizeof(SpiceDataHeader) - _incomming_header_pos);
if (_incomming_header_pos != sizeof(SpiceDataHeader)) {
return;
}
_incomming_header_pos = 0;
_incomming_message = new CompoundInMessage(_incomming_header.serial,
_incomming_header.type,
_incomming_header.size,
_incomming_header.sub_list);
_incomming_message_pos = 0;
}
if (_incomming_message) {
_incomming_message_pos += RedPeer::receive(_incomming_message->data() +
_incomming_message_pos,
_incomming_message->compound_size() -
_incomming_message_pos);
if (_incomming_message_pos != _incomming_message->compound_size()) {
return;
}
AutoRef<CompoundInMessage> message(_incomming_message);
_incomming_message = NULL;
on_message_received();
_message_handler->handle_message(*(*message));
on_message_complition((*message)->serial());
}
receive_messages();
}
void RedChannel::send_migrate_flush_mark()
{
if (_outgoing_message) {
RedPeer::OutMessage& peer_message = _outgoing_message->peer_message();
do_send(peer_message, _outgoing_pos);
_outgoing_message->release();
_outgoing_message = NULL;
}
Lock lock(_outgoing_lock);
for (;;) {
AutoMessage message(get_outgoing_message());
if (!message.get()) {
break;
}
send(message.get()->peer_message());
}
lock.unlock();
std::auto_ptr<RedPeer::OutMessage> message(new RedPeer::OutMessage(SPICE_MSGC_MIGRATE_FLUSH_MARK));
send(*message);
}
void RedChannel::handle_migrate(RedPeer::InMessage* message)
{
DBG(0, "channel type %u id %u", get_type(), get_id());
_socket_in_loop = false;
_loop.remove_socket(*this);
SpiceMsgMigrate* migrate = (SpiceMsgMigrate*)message->data();
if (migrate->flags & SPICE_MIGRATE_NEED_FLUSH) {
send_migrate_flush_mark();
}
AutoRef<CompoundInMessage> data_message;
if (migrate->flags & SPICE_MIGRATE_NEED_DATA_TRANSFER) {
data_message.reset(receive());
}
_client.migrate_channel(*this);
if (migrate->flags & SPICE_MIGRATE_NEED_DATA_TRANSFER) {
if ((*data_message)->type() != SPICE_MSG_MIGRATE_DATA) {
THROW("expect SPICE_MSG_MIGRATE_DATA");
}
std::auto_ptr<RedPeer::OutMessage> message(new RedPeer::OutMessage(SPICE_MSGC_MIGRATE_DATA));
spice_marshaller_add(message->marshaller(), (*data_message)->data(), (*data_message)->size());
send(*message);
}
_loop.add_socket(*this);
_socket_in_loop = true;
on_migrate();
set_state(CONNECTED_STATE);
on_event();
}
void RedChannel::handle_set_ack(RedPeer::InMessage* message)
{
SpiceMsgSetAck* ack = (SpiceMsgSetAck*)message->data();
_message_ack_window = _message_ack_count = ack->window;
Message *response = new Message(SPICE_MSGC_ACK_SYNC);
SpiceMsgcAckSync sync;
sync.generation = ack->generation;
_marshallers->msgc_ack_sync(response->marshaller(), &sync);
post_message(response);
}
void RedChannel::handle_ping(RedPeer::InMessage* message)
{
SpiceMsgPing *ping = (SpiceMsgPing *)message->data();
Message *pong = new Message(SPICE_MSGC_PONG);
_marshallers->msgc_pong(pong->marshaller(), ping);
post_message(pong);
}
void RedChannel::handle_disconnect(RedPeer::InMessage* message)
{
SpiceMsgDisconnect *disconnect = (SpiceMsgDisconnect *)message->data();
_disconnect_stamp = disconnect->time_stamp;
_disconnect_reason = disconnect->reason;
}
void RedChannel::handle_notify(RedPeer::InMessage* message)
{
SpiceMsgNotify *notify = (SpiceMsgNotify *)message->data();
const char *severity;
const char *visibility;
char *message_str = (char *)"";
const char *message_prefix = "";
static const char* severity_strings[] = {"info", "warn", "error"};
static const char* visibility_strings[] = {"!", "!!", "!!!"};
if (notify->severity > SPICE_NOTIFY_SEVERITY_ERROR) {
THROW("bad severity");
}
severity = severity_strings[notify->severity];
if (notify->visibilty > SPICE_NOTIFY_VISIBILITY_HIGH) {
THROW("bad visibility");
}
visibility = visibility_strings[notify->visibilty];
if (notify->message_len) {
if ((message->size() - sizeof(*notify) < notify->message_len)) {
THROW("access violation");
}
message_str = new char[notify->message_len + 1];
memcpy(message_str, notify->message, notify->message_len);
message_str[notify->message_len] = 0;
message_prefix = ": ";
}
LOG_INFO("remote channel %u:%u %s%s #%u%s%s",
get_type(), get_id(),
severity, visibility,
notify->what,
message_prefix, message_str);
if (notify->message_len) {
delete [] message_str;
}
}
void RedChannel::handle_wait_for_channels(RedPeer::InMessage* message)
{
SpiceMsgWaitForChannels *wait = (SpiceMsgWaitForChannels *)message->data();
if (message->size() < sizeof(*wait) + wait->wait_count * sizeof(wait->wait_list[0])) {
THROW("access violation");
}
_client.wait_for_channels(wait->wait_count, wait->wait_list);
}
| agpl-3.0 |
Irstea/collec | vendor/thecodingmachine/safe/generated/swoole.php | 2407 | <?php
namespace Safe;
use Safe\Exceptions\SwooleException;
/**
*
*
* @param string $filename The filename being written.
* @param string $content The content writing to the file.
* @param int $offset The offset.
* @param callable $callback
* @throws SwooleException
*
*/
function swoole_async_write(string $filename, string $content, int $offset = null, callable $callback = null): void
{
error_clear_last();
if ($callback !== null) {
$result = \swoole_async_write($filename, $content, $offset, $callback);
} elseif ($offset !== null) {
$result = \swoole_async_write($filename, $content, $offset);
} else {
$result = \swoole_async_write($filename, $content);
}
if ($result === false) {
throw SwooleException::createFromPhpError();
}
}
/**
*
*
* @param string $filename The filename being written.
* @param string $content The content writing to the file.
* @param callable $callback
* @param int $flags
* @throws SwooleException
*
*/
function swoole_async_writefile(string $filename, string $content, callable $callback = null, int $flags = 0): void
{
error_clear_last();
if ($flags !== 0) {
$result = \swoole_async_writefile($filename, $content, $callback, $flags);
} elseif ($callback !== null) {
$result = \swoole_async_writefile($filename, $content, $callback);
} else {
$result = \swoole_async_writefile($filename, $content);
}
if ($result === false) {
throw SwooleException::createFromPhpError();
}
}
/**
*
*
* @param callable $callback
* @throws SwooleException
*
*/
function swoole_event_defer(callable $callback): void
{
error_clear_last();
$result = \swoole_event_defer($callback);
if ($result === false) {
throw SwooleException::createFromPhpError();
}
}
/**
*
*
* @param int $fd
* @throws SwooleException
*
*/
function swoole_event_del(int $fd): void
{
error_clear_last();
$result = \swoole_event_del($fd);
if ($result === false) {
throw SwooleException::createFromPhpError();
}
}
/**
*
*
* @param int $fd
* @param string $data
* @throws SwooleException
*
*/
function swoole_event_write(int $fd, string $data): void
{
error_clear_last();
$result = \swoole_event_write($fd, $data);
if ($result === false) {
throw SwooleException::createFromPhpError();
}
}
| agpl-3.0 |
rdvincent/brainbrowser | build/brainbrowser-2.1.1/workers/mniobj.intensity.worker.js | 1377 | /*
* BrainBrowser: Web-based Neurological Visualization Tools
* (https://brainbrowser.cbrain.mcgill.ca)
*
* Copyright (C) 2011
* The Royal Institution for the Advancement of Learning
* McGill University
*
* 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/>.
*/
/*
* BrainBrowser v2.1.1
*
* Author: Tarek Sherif <tsherif@gmail.com> (http://tareksherif.ca/)
* Author: Nicolas Kassis
* Author: Paul Mougel
*/
!function(){"use strict";function a(a){var b,c,d,e,f={};for(f.values=a.replace(/^\s+/,"").replace(/\s+$/,"").split(/\s+/).map(parseFloat),d=f.values[0],e=f.values[0],b=1,c=f.values.length;c>b;b++)d=Math.min(d,f.values[b]),e=Math.max(e,f.values[b]);return f.min=d,f.max=e,f}self.addEventListener("message",function(b){var c=b.data,d=c.data;self.postMessage(a(d))})}(); | agpl-3.0 |
onursumer/cbioportal | core/src/main/java/org/mskcc/cbio/portal/util/SessionServiceRequestWrapper.java | 6093 | /*
* Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center.
*
* 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. The software and documentation provided hereunder
* is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no
* obligations to provide maintenance, support, updates, enhancements or
* modifications. In no event shall Memorial Sloan-Kettering Cancer Center be
* liable to any party for direct, indirect, special, incidental or
* consequential damages, including lost profits, arising out of the use of this
* software and its documentation, even if Memorial Sloan-Kettering Cancer
* Center has been advised of the possibility of such damage.
*/
/*
* This file is part of cBioPortal.
*
* cBioPortal 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.
*
* 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/>.
*/
package org.mskcc.cbio.portal.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang3.StringUtils;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.*;
import javax.servlet.http.*;
/**
*
* @author Manda Wilson
*/
public class SessionServiceRequestWrapper extends HttpServletRequestWrapper {
public static final String SESSION_ERROR = "session_error";
public static final String SESSION_ID_PARAM = "session_id";
private static Log LOG = LogFactory.getLog(SessionServiceRequestWrapper.class);
private Map<String, String[]> storedParameters;
private String sessionId;
/**
* If session_id is a request parameter, calls session-service API to retrieve
* stored session. Stores SESSION_ERROR as a request attribute if the session is
* not found, or the session service returns an error. Stored session parameters
* override current request parameters. If session_id is not a request parameter,
* request behaves as normal.
*
* @param request wrapped HttpServletRequest
*/
public SessionServiceRequestWrapper(final HttpServletRequest request) {
super(request);
LOG.debug("new SessionServiceRequestWrapper()");
sessionId = super.getParameter(SESSION_ID_PARAM);
LOG.debug("new SessionServiceRequestWrapper(): request parameter '" + SESSION_ID_PARAM + "' = '" + sessionId + "'");
if (!StringUtils.isBlank(sessionId)) {
LOG.debug("new SessionServiceRequestWrapper(): retrieved parameters = '" + storedParameters + "'");
try {
storedParameters = SessionServiceUtil.getSession(sessionId);
if (storedParameters == null || storedParameters.size() == 0) {
request.setAttribute(SESSION_ERROR, "Session with id '" + sessionId + "' not found.");
}
} catch (Exception e) {
request.setAttribute(SESSION_ERROR, "Session service error. Session with id '" + sessionId + "' not loaded. Try again later. If problem persists contact site administrator.");
}
}
}
@Override
public String getParameter(final String name) {
if (storedParameters != null && !SESSION_ID_PARAM.equals(name)) {
LOG.debug("SessionServiceRequestWrapper.getParameter(" + name + "): accessing parameters from stored session with id '" + sessionId + "'");
if (storedParameters.containsKey(name)) {
String value = storedParameters.get(name)[0];
LOG.debug("SessionServiceRequestWrapper.getParameter(" + name + "): returning '" + value + "'");
return value;
}
LOG.debug("SessionServiceRequestWrapper.getParameter(" + name + "): returning null - parameter name not found");
return null;
}
LOG.debug("SessionServiceRequestWrapper.getParameter(" + name + "): accessing current request parameters");
return super.getParameter(name);
}
@Override
public Map<String, String[]> getParameterMap() {
if (storedParameters != null) {
LOG.debug("SessionServiceRequestWrapper.getParameterMap(): accessing parameters from stored session with id '" + sessionId + "'");
return Collections.unmodifiableMap(storedParameters);
}
LOG.debug("SessionServiceRequestWrapper.getParameterMap(): accessing current request parameters");
return super.getParameterMap();
}
@Override
public Enumeration<String> getParameterNames() {
if (storedParameters != null) {
LOG.debug("SessionServiceRequestWrapper.getParameterNames(): accessing parameters from stored session with id '" + sessionId + "'");
return Collections.enumeration(storedParameters.keySet());
}
LOG.debug("SessionServiceRequestWrapper.getParameterNames(): accessing current request parameters");
return super.getParameterNames();
}
@Override
public String[] getParameterValues(final String name) {
if (storedParameters != null) {
LOG.debug("SessionServiceRequestWrapper.getParameterValues(): accessing parameters from stored session with id '" + sessionId + "'");
return storedParameters.get(name);
}
LOG.debug("SessionServiceRequestWrapper.getParameterValues(): accessing current request parameters");
return super.getParameterValues(name);
}
}
| agpl-3.0 |
sanjupolus/KC6.oLatest | coeus-impl/src/main/java/org/kuali/coeus/common/budget/framework/period/GenerateBudgetPeriodEvent.java | 1109 | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2015 Kuali, Inc.
*
* 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/>.
*/
package org.kuali.coeus.common.budget.framework.period;
import org.kuali.coeus.common.budget.framework.core.Budget;
public class GenerateBudgetPeriodEvent extends BudgetPeriodEventBase {
public GenerateBudgetPeriodEvent(Budget budget, BudgetPeriod budgetPeriod) {
super(budget, budgetPeriod);
}
}
| agpl-3.0 |
rven/odoo | addons/website_slides/static/src/components/activity/activity_tests.js | 3940 | odoo.define('website_slides/static/src/tests/activity_tests.js', function (require) {
'use strict';
const components = {
Activity: require('mail/static/src/components/activity/activity.js'),
};
const {
afterEach,
beforeEach,
createRootComponent,
start,
} = require('mail/static/src/utils/test_utils.js');
QUnit.module('website_slides', {}, function () {
QUnit.module('components', {}, function () {
QUnit.module('activity', {}, function () {
QUnit.module('activity_tests.js', {
beforeEach() {
beforeEach(this);
this.createActivityComponent = async activity => {
await createRootComponent(this, components.Activity, {
props: { activityLocalId: activity.localId },
target: this.widget.el,
});
};
this.start = async params => {
const { env, widget } = await start(Object.assign({}, params, {
data: this.data,
}));
this.env = env;
this.widget = widget;
};
},
afterEach() {
afterEach(this);
},
});
QUnit.test('grant course access', async function (assert) {
assert.expect(8);
await this.start({
async mockRPC(route, args) {
if (args.method === 'action_grant_access') {
assert.strictEqual(args.args.length, 1);
assert.strictEqual(args.args[0].length, 1);
assert.strictEqual(args.args[0][0], 100);
assert.strictEqual(args.kwargs.partner_id, 5);
assert.step('access_grant');
}
return this._super(...arguments);
},
});
const activity = this.env.models['mail.activity'].create({
id: 100,
canWrite: true,
thread: [['insert', {
id: 100,
model: 'slide.channel',
}]],
requestingPartner: [['insert', {
id: 5,
displayName: "Pauvre pomme",
}]],
type: [['insert', {
id: 1,
displayName: "Access Request",
}]],
});
await this.createActivityComponent(activity);
assert.containsOnce(document.body, '.o_Activity', "should have activity component");
assert.containsOnce(document.body, '.o_Activity_grantAccessButton', "should have grant access button");
document.querySelector('.o_Activity_grantAccessButton').click();
assert.verifySteps(['access_grant'], "Grant button should trigger the right rpc call");
});
QUnit.test('refuse course access', async function (assert) {
assert.expect(8);
await this.start({
async mockRPC(route, args) {
if (args.method === 'action_refuse_access') {
assert.strictEqual(args.args.length, 1);
assert.strictEqual(args.args[0].length, 1);
assert.strictEqual(args.args[0][0], 100);
assert.strictEqual(args.kwargs.partner_id, 5);
assert.step('access_refuse');
}
return this._super(...arguments);
},
});
const activity = this.env.models['mail.activity'].create({
id: 100,
canWrite: true,
thread: [['insert', {
id: 100,
model: 'slide.channel',
}]],
requestingPartner: [['insert', {
id: 5,
displayName: "Pauvre pomme",
}]],
type: [['insert', {
id: 1,
displayName: "Access Request",
}]],
});
await this.createActivityComponent(activity);
assert.containsOnce(document.body, '.o_Activity', "should have activity component");
assert.containsOnce(document.body, '.o_Activity_refuseAccessButton', "should have refuse access button");
document.querySelector('.o_Activity_refuseAccessButton').click();
assert.verifySteps(['access_refuse'], "refuse button should trigger the right rpc call");
});
});
});
});
});
| agpl-3.0 |
mattattack7/canvas-contrib | SIS_Integration/java/basic_example/lib/httpcomponents-client-4.3-alpha1/javadoc/org/apache/http/impl/conn/tsccm/class-use/AbstractConnPool.html | 10926 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_22) on Wed Jan 16 18:27:39 CET 2013 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.http.impl.conn.tsccm.AbstractConnPool (HttpComponents Client 4.3-alpha1 API)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Class org.apache.http.impl.conn.tsccm.AbstractConnPool (HttpComponents Client 4.3-alpha1 API)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/AbstractConnPool.html" title="class in org.apache.http.impl.conn.tsccm"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/http/impl/conn/tsccm/class-use/AbstractConnPool.html" target="_top"><B>FRAMES</B></A>
<A HREF="AbstractConnPool.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.http.impl.conn.tsccm.AbstractConnPool</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/AbstractConnPool.html" title="class in org.apache.http.impl.conn.tsccm">AbstractConnPool</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.http.impl.conn.tsccm"><B>org.apache.http.impl.conn.tsccm</B></A></TD>
<TD>The implementation of a thread-safe client connection manager. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.http.impl.conn.tsccm"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/AbstractConnPool.html" title="class in org.apache.http.impl.conn.tsccm">AbstractConnPool</A> in <A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/package-summary.html">org.apache.http.impl.conn.tsccm</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/AbstractConnPool.html" title="class in org.apache.http.impl.conn.tsccm">AbstractConnPool</A> in <A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/package-summary.html">org.apache.http.impl.conn.tsccm</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/ConnPoolByRoute.html" title="class in org.apache.http.impl.conn.tsccm">ConnPoolByRoute</A></B></CODE>
<BR>
<B>Deprecated.</B> <I>(4.2) use <A HREF="http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/pool/AbstractConnPool.html" title="class or interface in org.apache.http.pool"><CODE>AbstractConnPool</CODE></A></I></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/package-summary.html">org.apache.http.impl.conn.tsccm</A> declared as <A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/AbstractConnPool.html" title="class in org.apache.http.impl.conn.tsccm">AbstractConnPool</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/AbstractConnPool.html" title="class in org.apache.http.impl.conn.tsccm">AbstractConnPool</A></CODE></FONT></TD>
<TD><CODE><B>ThreadSafeClientConnManager.</B><B><A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/ThreadSafeClientConnManager.html#connectionPool">connectionPool</A></B></CODE>
<BR>
<B>Deprecated.</B> </TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/package-summary.html">org.apache.http.impl.conn.tsccm</A> that return <A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/AbstractConnPool.html" title="class in org.apache.http.impl.conn.tsccm">AbstractConnPool</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/AbstractConnPool.html" title="class in org.apache.http.impl.conn.tsccm">AbstractConnPool</A></CODE></FONT></TD>
<TD><CODE><B>ThreadSafeClientConnManager.</B><B><A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/ThreadSafeClientConnManager.html#createConnectionPool(org.apache.http.params.HttpParams)">createConnectionPool</A></B>(<A HREF="http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/params/HttpParams.html" title="class or interface in org.apache.http.params">HttpParams</A> params)</CODE>
<BR>
<B>Deprecated.</B> <I>(4.1) use #createConnectionPool(long, TimeUnit))</I></TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/http/impl/conn/tsccm/AbstractConnPool.html" title="class in org.apache.http.impl.conn.tsccm"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/http/impl/conn/tsccm/class-use/AbstractConnPool.html" target="_top"><B>FRAMES</B></A>
<A HREF="AbstractConnPool.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 1999-2013 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
| agpl-3.0 |
schlos/OIPA-V2.1 | OIPA/OIPA/wsgi.py | 1413 | """
WSGI config for OIPA project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "OIPA.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "OIPA.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| agpl-3.0 |
egoistIT/shopware | recovery/install/src/Service/ShopService.php | 4461 | <?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\Recovery\Install\Service;
use Shopware\Recovery\Install\Struct\Shop;
/**
* @category Shopware
*
* @copyright Copyright (c) shopware AG (http://www.shopware.de)
*/
class ShopService
{
/**
* @var \PDO
*/
private $connection;
/**
* @param \PDO $connection
*/
public function __construct(\PDO $connection)
{
$this->connection = $connection;
}
/**
* @param Shop $shop
*
* @throws \RuntimeException
*/
public function updateShop(Shop $shop)
{
if (empty($shop->locale)
|| empty($shop->host)
) {
throw new \RuntimeException('Please fill in all required fields. (shop configuration)');
}
try {
$fetchLanguageId = $this->getLocaleIdByLocale($shop->locale);
// Update s_core_shops
$sql = <<<'EOT'
UPDATE
s_core_shops
SET
`name` = ?,
locale_id = ?,
host = ?,
base_path = ?,
hosts = ?
WHERE
`default` = 1
EOT;
$prepareStatement = $this->connection->prepare($sql);
$prepareStatement->execute([
$shop->name,
$fetchLanguageId,
$shop->host,
$shop->basePath,
$shop->host,
]);
} catch (\Exception $e) {
throw new \RuntimeException($e->getMessage(), 0, $e);
}
}
/**
* @param Shop $shop
*
* @throws \RuntimeException
*/
public function updateConfig(Shop $shop)
{
// Do update on shop-configuration
if (empty($shop->name) || empty($shop->email)) {
throw new \RuntimeException('Please fill in all required fields. (shop configuration#2)');
}
$this->updateMailAddress($shop);
$this->updateShopName($shop);
}
/**
* @param string $locale
*
* @return int
*/
protected function getLocaleIdByLocale($locale)
{
$fetchLanguageId = $this->connection->prepare(
'SELECT id FROM s_core_locales WHERE locale = ?'
);
$fetchLanguageId->execute([$locale]);
$fetchLanguageId = $fetchLanguageId->fetchColumn();
if (!$fetchLanguageId) {
throw new \RuntimeException('Language with id ' . $locale . ' not found');
}
return (int) $fetchLanguageId;
}
/**
* @param Shop $shop
*/
private function updateMailAddress(Shop $shop)
{
$this->updateConfigValue('mail', $shop->email);
}
/**
* @param Shop $shop
*/
private function updateShopName(Shop $shop)
{
$this->updateConfigValue('shopName', $shop->name);
}
/**
* @param string $elementName
* @param mixed $value
*/
private function updateConfigValue($elementName, $value)
{
$sql = <<<'EOT'
DELETE
FROM s_core_config_values
WHERE element_id =
(SELECT id FROM s_core_config_elements WHERE name=:elementName)
AND shop_id = 1
EOT;
$this->connection->prepare($sql)->execute([
'elementName' => $elementName,
]);
$sql = <<<'EOT'
INSERT INTO `s_core_config_values`
(`id`, `element_id`, `shop_id`, `value`) VALUES
(NULL, (SELECT id FROM s_core_config_elements WHERE name=:elementName), 1, :value);
EOT;
$prepared = $this->connection->prepare($sql);
$prepared->execute([
'elementName' => $elementName,
'value' => serialize($value),
]);
}
}
| agpl-3.0 |
step21/inkscape-osx-packaging-native | src/ui/widget/imageicon.h | 2544 | #ifndef __UI_DIALOG_IMAGE_H__
#define __UI_DIALOG_IMAGE_H__
/*
* A simple image display widget, using Inkscape's own rendering engine
*
* Authors:
* Bob Jamison
* Other dudes from The Inkscape Organization
*
* Copyright (C) 2004 The Inkscape Organization
*
* Released under GNU GPL, read the file 'COPYING' for more information
*/
#include <glibmm/ustring.h>
#include <gtkmm/box.h>
class SPDocument;
namespace Inkscape
{
namespace UI
{
namespace Widget
{
/*#########################################################################
### ImageIcon widget
#########################################################################*/
/**
* This class is evolved from the SVGPreview widget of the FileChooser
* This uses Inkscape's renderer to show images in a variety of formats,
* including SVG
*/
class ImageIcon : public Gtk::VBox
{
public:
/**
* Constructor
*/
ImageIcon();
/**
* Construct from a file name
*/
ImageIcon(const Glib::ustring &fileName);
/**
* Copy Constructor
*/
ImageIcon(const ImageIcon &other);
/**
* Destructor
*/
~ImageIcon();
/**
*
*/
bool showSvgDocument(const SPDocument *doc);
/**
*
*/
bool showSvgFile(const Glib::ustring &fileName);
/**
*
*/
bool showSvgFromMemory(const char *xmlBuffer);
/**
* Show image embedded in SVG
*/
bool showBitmap(const Glib::ustring &fileName);
/**
* Show the "Too large" image
*/
void showBrokenImage(const Glib::ustring &reason);
/**
*
*/
bool show(const Glib::ustring &fileName);
private:
/**
* basic initialization, called by the various constructors
*/
void init();
/**
* The svg document we are currently showing
*/
SPDocument *document;
/**
* The sp_svg_view widget
*/
Gtk::Widget *viewerGtkmm;
/**
* are we currently showing the "broken image" image?
*/
bool showingBrokenImage;
/**
* will be set by showImageIcon as a side-effect of an error
*/
Glib::ustring bitmapError;
/**
* will be set by showImageIcon as a side-effect of an error
*/
Glib::ustring svgError;
};
} // namespace Widget
} // namespace UI
} // namespace Inkscape
#endif /* __UI_DIALOG_IMAGE_H__ */
/*#########################################################################
### E N D O F F I L E
#########################################################################*/
| lgpl-2.1 |
youfoh/webkit-efl | LayoutTests/fast/dom/htmlallcollection-call-with-index-caching-bug.html | 550 | <!DOCTYPE html>
<html>
<head id="foo">
<meta charset="utf-8">
<script src="../js/resources/js-test-pre.js"></script>
</head>
<body>
<script>
description("This tests verifies that calling document.all(name, index) doesn't affect subsequent calls to document.all.item(index)");
shouldBe("document.all.item(0)", "document.documentElement");
debug("Calling document.all('foo', 0).");
document.all('foo', 0)
shouldBe("document.all.item(0)", "document.documentElement");
</script>
<script src="../js/resources/js-test-post.js"></script>
</body>
</html>
| lgpl-2.1 |
juhovh/tapcfg | src/demos/TAPNetTest.cs | 1388 | /**
* tapcfg - A cross-platform configuration utility for TAP driver
* Copyright (C) 2008-2011 Juho Vähä-Herttua
*
* 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.
*/
using TAPNet;
using System;
using System.Net;
using System.Threading;
public class TAPNetTest {
private static void Main(string[] args) {
VirtualDevice dev = new VirtualDevice();
dev.LogCallback = new LogCallback(LogCallback);
dev.Start("Device name", true);
Console.WriteLine("Got device name: {0}", dev.DeviceName);
Console.WriteLine("Got device hwaddr: {0}", BitConverter.ToString(dev.HWAddress));
dev.HWAddress = new byte[] { 0x00, 0x01, 0x23, 0x45, 0x67, 0x89 };
dev.MTU = 1280;
dev.SetAddress(IPAddress.Parse("192.168.10.1"), 16);
dev.Enabled = true;
while (true) {
Thread.Sleep(1000);
}
}
private static void LogCallback(LogLevel level, string msg) {
Console.WriteLine(level + ": " + msg);
}
}
| lgpl-2.1 |
EmreAtes/spack | var/spack/repos/builtin/packages/psi4/package.py | 4596 | ##############################################################################
# Copyright (c) 2013-2018, 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/spack/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 *
import os
class Psi4(CMakePackage):
"""Psi4 is an open-source suite of ab initio quantum chemistry
programs designed for efficient, high-accuracy simulations of
a variety of molecular properties."""
homepage = "http://www.psicode.org/"
url = "https://github.com/psi4/psi4/archive/0.5.tar.gz"
version('0.5', '53041b8a9be3958384171d0d22f9fdd0')
variant('build_type', default='Release',
description='The build type to build',
values=('Debug', 'Release'))
# Required dependencies
depends_on('blas')
depends_on('lapack')
depends_on('boost+chrono+filesystem+python+regex+serialization+system+timer+thread')
depends_on('python')
depends_on('cmake@3.3:', type='build')
depends_on('py-numpy', type=('build', 'run'))
# Optional dependencies
# TODO: add packages for these
# depends_on('perl')
# depends_on('erd')
# depends_on('pcm-solver')
# depends_on('chemps2')
def cmake_args(self):
spec = self.spec
return [
'-DBLAS_TYPE={0}'.format(spec['blas'].name.upper()),
'-DBLAS_LIBRARIES={0}'.format(spec['blas'].libs.joined()),
'-DLAPACK_TYPE={0}'.format(spec['lapack'].name.upper()),
'-DLAPACK_LIBRARIES={0}'.format(
spec['lapack'].libs.joined()),
'-DBOOST_INCLUDEDIR={0}'.format(spec['boost'].prefix.include),
'-DBOOST_LIBRARYDIR={0}'.format(spec['boost'].prefix.lib),
'-DENABLE_CHEMPS2=OFF'
]
@run_after('install')
def filter_compilers(self, spec, prefix):
"""Run after install to tell the configuration files to
use the compilers that Spack built the package with.
If this isn't done, they'll have PLUGIN_CXX set to
Spack's generic cxx. We want it to be bound to
whatever compiler it was built with."""
kwargs = {'ignore_absent': True, 'backup': False, 'string': True}
cc_files = ['bin/psi4-config']
cxx_files = ['bin/psi4-config', 'include/psi4/psiconfig.h']
template = 'share/psi4/plugin/Makefile.template'
for filename in cc_files:
filter_file(os.environ['CC'], self.compiler.cc,
os.path.join(prefix, filename), **kwargs)
for filename in cxx_files:
filter_file(os.environ['CXX'], self.compiler.cxx,
os.path.join(prefix, filename), **kwargs)
# The binary still keeps track of the compiler used to install Psi4
# and uses it when creating a plugin template
filter_file('@PLUGIN_CXX@', self.compiler.cxx,
os.path.join(prefix, template), **kwargs)
# The binary links to the build include directory instead of the
# installation include directory:
# https://github.com/psi4/psi4/issues/410
filter_file('@PLUGIN_INCLUDES@', '-I{0}'.format(
' -I'.join([
os.path.join(spec['psi4'].prefix.include, 'psi4'),
os.path.join(spec['boost'].prefix.include, 'boost'),
os.path.join(spec['python'].headers.directories[0]),
spec['lapack'].prefix.include,
spec['blas'].prefix.include,
'/usr/include'
])
), os.path.join(prefix, template), **kwargs)
| lgpl-2.1 |
NAM-IL/bluez-5.33 | obexd/src/PaxHeaders.11798/map_ap.h | 40 | 20 atime=1438284042
20 ctime=1438284117
| lgpl-2.1 |
viktorTarasov/OpenSC-SM | src/libopensc/card-jpki.c | 10425 | /*
* card-jpki.c: Support for JPKI(Japanese Individual Number Cards).
*
* Copyright (C) 2016, HAMANO Tsukasa <hamano@osstech.co.jp>
*
* 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
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <stdlib.h>
#include "internal.h"
#include "jpki.h"
static const struct sc_atr_table jpki_atrs[] = {
{"3b:e0:00:ff:81:31:fe:45:14", NULL, NULL,
SC_CARD_TYPE_JPKI_BASE, 0, NULL},
{NULL, NULL, NULL, 0, 0, NULL}
};
static struct sc_card_operations jpki_ops;
static struct sc_card_driver jpki_drv = {
"JPKI(Japanese Individual Number Cards)",
"jpki",
&jpki_ops,
NULL, 0, NULL
};
int jpki_select_ap(struct sc_card *card)
{
int rc;
sc_path_t path;
LOG_FUNC_CALLED(card->ctx);
/* Select JPKI application */
sc_format_path(AID_JPKI, &path);
path.type = SC_PATH_TYPE_DF_NAME;
rc = sc_select_file(card, &path, NULL);
LOG_TEST_RET(card->ctx, rc, "select JPKI AP failed");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
jpki_match_card(struct sc_card *card)
{
int i, rc;
i = _sc_match_atr(card, jpki_atrs, &card->type);
if (i >= 0) {
return 1;
}
rc = jpki_select_ap(card);
if (rc == SC_SUCCESS) {
card->type = SC_CARD_TYPE_JPKI_BASE;
return 1;
}
return 0;
}
static int
jpki_finish(sc_card_t * card)
{
struct jpki_private_data *drvdata = JPKI_DRVDATA(card);
LOG_FUNC_CALLED(card->ctx);
if (drvdata) {
if (drvdata->mf) {
free(drvdata->mf);
}
free(drvdata);
card->drv_data = NULL;
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
jpki_init(struct sc_card *card)
{
struct jpki_private_data *drvdata;
sc_file_t *mf;
int flags;
LOG_FUNC_CALLED(card->ctx);
drvdata = malloc(sizeof (struct jpki_private_data));
if (!drvdata)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memset(drvdata, 0, sizeof (struct jpki_private_data));
/* create virtual MF */
mf = sc_file_new();
if (!mf) {
free(drvdata);
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
sc_format_path("3f00", &mf->path);
mf->type = SC_FILE_TYPE_DF;
mf->shareable = 0;
mf->ef_structure = SC_FILE_EF_UNKNOWN;
mf->size = 0;
mf->id = 0x3f00;
mf->status = SC_FILE_STATUS_ACTIVATED;
sc_file_add_acl_entry(mf, SC_AC_OP_SELECT, SC_AC_NONE, 0);
sc_file_add_acl_entry(mf, SC_AC_OP_LIST_FILES, SC_AC_NONE, 0);
sc_file_add_acl_entry(mf, SC_AC_OP_LOCK, SC_AC_NEVER, 0);
sc_file_add_acl_entry(mf, SC_AC_OP_DELETE, SC_AC_NEVER, 0);
sc_file_add_acl_entry(mf, SC_AC_OP_CREATE, SC_AC_NEVER, 0);
drvdata->mf = mf;
drvdata->selected = SELECT_MF;
card->name = "jpki";
card->drv_data = drvdata;
flags = SC_ALGORITHM_RSA_HASH_NONE | SC_ALGORITHM_RSA_PAD_PKCS1;
_sc_card_add_rsa_alg(card, 2048, flags, 0);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
jpki_select_file(struct sc_card *card,
const struct sc_path *path, struct sc_file **file_out)
{
struct jpki_private_data *drvdata = JPKI_DRVDATA(card);
int rc;
sc_apdu_t apdu;
struct sc_file *file = NULL;
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx,
"jpki_select_file: path=%s, len=%"SC_FORMAT_LEN_SIZE_T"u",
sc_print_path(path), path->len);
if (path->len == 2 && memcmp(path->value, "\x3F\x00", 2) == 0) {
drvdata->selected = SELECT_MF;
if (file_out) {
sc_file_dup(file_out, drvdata->mf);
if (*file_out == NULL) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
}
return 0;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 0, 0);
switch (path->type) {
case SC_PATH_TYPE_FILE_ID:
apdu.p1 = 2;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
apdu.p2 = 0x0C;
apdu.data = path->value;
apdu.datalen = path->len;
apdu.lc = path->len;
rc = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rc, "APDU transmit failed");
rc = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rc, "SW Check failed");
if (!file_out) {
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
/* read certificate file size */
if (path->len == 2 && (
memcmp(path->value, "\x00\x0A", 2) == 0 ||
memcmp(path->value, "\x00\x01", 2) == 0 ||
memcmp(path->value, "\x00\x0B", 2) == 0 ||
memcmp(path->value, "\x00\x02", 2) == 0 )
) {
u8 buf[4];
rc = sc_read_binary(card, 0, buf, 4, 0);
LOG_TEST_RET(card->ctx, rc, "SW Check failed");
file = sc_file_new();
if (!file) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
file->path = *path;
file->size = (buf[2] << 8 | buf[3]) + 4;
*file_out = file;
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
jpki_read_binary(sc_card_t * card, unsigned int idx,
u8 * buf, size_t count, unsigned long flags)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
const struct sc_card_operations *iso_ops = iso_drv->ops;
int rc;
LOG_FUNC_CALLED(card->ctx);
rc = iso_ops->read_binary(card, idx, buf, count, flags);
LOG_FUNC_RETURN(card->ctx, rc);
}
static int
jpki_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left)
{
int rc;
sc_path_t path;
sc_apdu_t apdu;
struct jpki_private_data *priv = JPKI_DRVDATA(card);
int max_tries = 0;
LOG_FUNC_CALLED(card->ctx);
if (tries_left) {
*tries_left = -1;
}
switch (data->pin_reference) {
case 1:
sc_format_path(JPKI_AUTH_PIN, &path);
path.type = SC_PATH_TYPE_FILE_ID;
rc = sc_select_file(card, &path, NULL);
max_tries = JPKI_AUTH_PIN_MAX_TRIES;
break;
case 2:
sc_format_path(JPKI_SIGN_PIN, &path);
path.type = SC_PATH_TYPE_FILE_ID;
rc = sc_select_file(card, &path, NULL);
max_tries = JPKI_SIGN_PIN_MAX_TRIES;
break;
default:
sc_log(card->ctx, "Unknown PIN reference: %d", data->pin_reference);
LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS);
}
LOG_TEST_RET(card->ctx, rc, "SELECT_FILE error");
switch (data->cmd) {
case SC_PIN_CMD_VERIFY:
sc_format_apdu(card, &apdu, SC_APDU_CASE_3, 0x20, 0x00, 0x80);
apdu.data = data->pin1.data;
apdu.datalen = data->pin1.len;
apdu.lc = data->pin1.len;
rc = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rc, "APDU transmit failed");
rc = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (rc == SC_SUCCESS) {
data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN;
data->pin1.tries_left = max_tries;
} else {
data->pin1.logged_in = SC_PIN_STATE_LOGGED_OUT;
data->pin1.tries_left = apdu.sw2 & 0xF;
}
priv->logged_in = data->pin1.logged_in;
LOG_TEST_RET(card->ctx, rc, "VERIFY failed");
break;
case SC_PIN_CMD_GET_INFO:
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x20, 0x00, 0x80);
rc = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rc, "APDU transmit failed");
if (apdu.sw1 != 0x63) {
sc_log(card->ctx, "VERIFY GET_INFO error");
LOG_FUNC_RETURN(card->ctx, SC_ERROR_CARD_CMD_FAILED);
}
data->pin1.logged_in = priv->logged_in;
data->pin1.tries_left = apdu.sw2 & 0xF;
if (tries_left) {
*tries_left = data->pin1.tries_left;
}
break;
default:
sc_log(card->ctx, "Card does not support PIN command: %d", data->cmd);
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
jpki_set_security_env(sc_card_t * card,
const sc_security_env_t * env, int se_num)
{
int rc;
sc_path_t path;
LOG_FUNC_CALLED(card->ctx);
sc_log(card->ctx,
"flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u",
env->flags, env->operation, env->algorithm,
env->algorithm_flags, env->algorithm_ref, env->key_ref[0],
env->key_ref_len);
switch (env->operation) {
case SC_SEC_OPERATION_SIGN:
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
switch (env->key_ref[0]) {
case 1:
sc_format_path(JPKI_AUTH_KEY, &path);
break;
case 2:
sc_format_path(JPKI_SIGN_KEY, &path);
break;
default:
LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
}
path.type = SC_PATH_TYPE_FILE_ID;
rc = sc_select_file(card, &path, NULL);
LOG_TEST_RET(card->ctx, rc, "select key failed");
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
static int
jpki_compute_signature(sc_card_t * card,
const u8 * data, size_t datalen, u8 * out, size_t outlen)
{
int rc;
sc_apdu_t apdu;
unsigned char resp[SC_MAX_APDU_BUFFER_SIZE];
LOG_FUNC_CALLED(card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x00, 0x80);
apdu.cla = 0x80;
apdu.data = data;
apdu.datalen = datalen;
apdu.lc = datalen;
apdu.resp = resp;
apdu.resplen = sizeof(resp);
apdu.le = 0;
rc = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rc, "APDU transmit failed");
rc = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rc, "SW Check failed");
if (apdu.resplen > outlen) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
memcpy(out, resp, apdu.resplen);
LOG_FUNC_RETURN(card->ctx, apdu.resplen);
}
static int jpki_card_reader_lock_obtained(sc_card_t *card, int was_reset)
{
int r = SC_SUCCESS;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (was_reset > 0) {
r = jpki_select_ap(card);
}
LOG_FUNC_RETURN(card->ctx, r);
}
static struct sc_card_driver *
sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
jpki_ops = *iso_drv->ops;
jpki_ops.match_card = jpki_match_card;
jpki_ops.init = jpki_init;
jpki_ops.finish = jpki_finish;
jpki_ops.select_file = jpki_select_file;
jpki_ops.read_binary = jpki_read_binary;
jpki_ops.pin_cmd = jpki_pin_cmd;
jpki_ops.set_security_env = jpki_set_security_env;
jpki_ops.compute_signature = jpki_compute_signature;
jpki_ops.card_reader_lock_obtained = jpki_card_reader_lock_obtained;
return &jpki_drv;
}
struct sc_card_driver *
sc_get_jpki_driver(void)
{
return sc_get_driver();
}
| lgpl-2.1 |
probonopd/marble | src/plugins/runner/local-osm-search/DatabaseQuery.h | 1783 | //
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org>
// Copyright 2013 Bernhard Beschow <bbeschow@cs.tu-berlin.de>
//
#ifndef MARBLE_DATABASEQUERY_H
#define MARBLE_DATABASEQUERY_H
#include "GeoDataCoordinates.h"
#include "OsmPlacemark.h"
#include <QList>
#include <QString>
namespace Marble {
class MarbleModel;
class GeoDataLatLonBox;
/**
* Parse result of a user's search term
*/
class DatabaseQuery
{
public:
enum QueryType {
AddressSearch, /// precise search for an address
CategorySearch, /// search which contains a poi category
BroadSearch /// any other non specific search
};
enum ResultFormat {
AddressFormat, /// display results with location information
DistanceFormat /// display results with distance information
};
DatabaseQuery( const MarbleModel* model, const QString &searchTerm, const GeoDataLatLonBox &preferred );
QueryType queryType() const;
ResultFormat resultFormat() const;
QString street() const;
QString houseNumber() const;
QString region() const;
QString searchTerm() const;
OsmPlacemark::OsmCategory category() const;
GeoDataCoordinates position() const;
private:
bool isPointOfInterest( const QString &category );
QueryType m_queryType;
ResultFormat m_resultFormat;
QString m_street;
QString m_houseNumber;
QString m_region;
QString m_searchTerm;
GeoDataCoordinates m_position;
OsmPlacemark::OsmCategory m_category;
};
}
#endif // MARBLE_DATABASEQUERY_H
| lgpl-2.1 |
prefetchnta/crhack | src/naked/cmsis/DSP/Source/SupportFunctions/arm_insertion_sort_f32.c | 2673 | /* ----------------------------------------------------------------------
* Project: CMSIS DSP Library
* Title: arm_insertion_sort_f32.c
* Description: Floating point insertion sort
*
* $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/support_functions.h"
#include "arm_sorting.h"
/**
@ingroup groupSupport
*/
/**
@addtogroup Sorting
@{
*/
/**
* @private
* @param[in] S points to an instance of the sorting structure.
* @param[in] pSrc points to the block of input data.
* @param[out] pDst points to the block of output data
* @param[in] blockSize number of samples to process.
*
* @par Algorithm
* The insertion sort is a simple sorting algorithm that
* reads all the element of the input array and removes one element
* at a time, finds the location it belongs in the final sorted list,
* and inserts it there.
*
* @par It's an in-place algorithm. In order to obtain an out-of-place
* function, a memcpy of the source vector is performed.
*/
void arm_insertion_sort_f32(
const arm_sort_instance_f32 * S,
float32_t *pSrc,
float32_t* pDst,
uint32_t blockSize)
{
float32_t * pA;
uint8_t dir = S->dir;
uint32_t i, j;
float32_t temp;
if(pSrc != pDst) // out-of-place
{
memcpy(pDst, pSrc, blockSize*sizeof(float32_t) );
pA = pDst;
}
else
pA = pSrc;
// Real all the element of the input array
for(i=0; i<blockSize; i++)
{
// Move the i-th element to the right position
for (j = i; j>0 && dir==(pA[j]<pA[j-1]); j--)
{
// Swap
temp = pA[j];
pA[j] = pA[j-1];
pA[j-1] = temp;
}
}
}
/**
@} end of Sorting group
*/
| lgpl-2.1 |
youfoh/webkit-efl | LayoutTests/sputnik/Conformance/15_Native_Objects/15.4_Array/15.4.4/15.4.4.12_Array_prototype_splice/S15.4.4.12_A1.4_T3.html | 2877 | <html>
<head>
<meta charset='utf-8'>
<style>
.pass {
font-weight: bold;
color: green;
}
.fail {
font-weight: bold;
color: red;
}
</style>
<script>
if (window.testRunner)
testRunner.dumpAsText();
function SputnikError(message)
{
this.message = message;
}
SputnikError.prototype.toString = function ()
{
return 'SputnikError: ' + this.message;
};
var sputnikException;
function testPrint(msg)
{
var span = document.createElement("span");
document.getElementById("console").appendChild(span); // insert it first so XHTML knows the namespace
span.innerHTML = msg + '<br />';
}
function escapeHTML(text)
{
return text.toString().replace(/&/g, "&").replace(/</g, "<");
}
function printTestPassed(msg)
{
testPrint('<span><span class="pass">PASS</span> ' + escapeHTML(msg) + '</span>');
}
function printTestFailed(msg)
{
testPrint('<span><span class="fail">FAIL</span> ' + escapeHTML(msg) + '</span>');
}
function testFailed(msg)
{
throw new SputnikError(msg);
}
var successfullyParsed = false;
</script>
</head>
<body>
<p>S15.4.4.12_A1.4_T3</p>
<div id='console'></div>
<script>
try {
/**
* @name: S15.4.4.12_A1.4_T3;
* @section: 15.4.4.12;
* @assertion: If start is negative, use max(start + length, 0).
* If deleteCount is positive, use min(deleteCount, length - start);
* @description: -start > length = deleteCount > 0, itemCount = 0;
*/
var x = [0,1,2,3];
var arr = x.splice(-5,4);
//CHECK#1
arr.getClass = Object.prototype.toString;
if (arr.getClass() !== "[object " + "Array" + "]") {
testFailed('#1: var x = [0,1,2,3]; var arr = x.splice(-5,4); arr is Array object. Actual: ' + (arr.getClass()));
}
//CHECK#2
if (arr.length !== 4) {
testFailed('#2: var x = [0,1,2,3]; var arr = x.splice(-5,4); arr.length === 4. Actual: ' + (arr.length));
}
//CHECK#3
if (arr[0] !== 0) {
testFailed('#3: var x = [0,1,2,3]; var arr = x.splice(-5,4); arr[0] === 0. Actual: ' + (arr[0]));
}
//CHECK#4
if (arr[1] !== 1) {
testFailed('#4: var x = [0,1,2,3]; var arr = x.splice(-5,4); arr[1] === 1. Actual: ' + (arr[1]));
}
//CHECK#5
if (arr[2] !== 2) {
testFailed('#5: var x = [0,1,2,3]; var arr = x.splice(-5,4); arr[2] === 2. Actual: ' + (arr[2]));
}
//CHECK#6
if (arr[3] !== 3) {
testFailed('#6: var x = [0,1,2,3]; var arr = x.splice(-5,4); arr[3] === 3. Actual: ' + (arr[3]));
}
//CHECK#7
if (x.length !== 0) {
testFailed('#7: var x = [0,1,2,3]; var arr = x.splice(-5,4); x.length === 0. Actual: ' + (x.length));
}
} catch (ex) {
sputnikException = ex;
}
var successfullyParsed = true;
</script>
<script>
if (!successfullyParsed)
printTestFailed('successfullyParsed is not set');
else if (sputnikException)
printTestFailed(sputnikException);
else
printTestPassed("");
testPrint('<br /><span class="pass">TEST COMPLETE</span>');
</script>
</body>
</html>
| lgpl-2.1 |
libvirt/libvirt | src/security/security_driver.c | 2613 | /*
* Copyright (C) 2008-2012 Red Hat, Inc.
*
* 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, see
* <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include "virerror.h"
#include "virlog.h"
#include "security_driver.h"
#ifdef WITH_SECDRIVER_SELINUX
# include "security_selinux.h"
#endif
#ifdef WITH_SECDRIVER_APPARMOR
# include "security_apparmor.h"
#endif
#include "security_nop.h"
#define VIR_FROM_THIS VIR_FROM_SECURITY
VIR_LOG_INIT("security.security_driver");
static virSecurityDriver *security_drivers[] = {
#ifdef WITH_SECDRIVER_SELINUX
&virSecurityDriverSELinux,
#endif
#ifdef WITH_SECDRIVER_APPARMOR
&virAppArmorSecurityDriver,
#endif
&virSecurityDriverNop, /* Must always be last, since it will always probe */
};
virSecurityDriver *virSecurityDriverLookup(const char *name,
const char *virtDriver)
{
virSecurityDriver *drv = NULL;
size_t i;
VIR_DEBUG("name=%s", NULLSTR(name));
for (i = 0; i < G_N_ELEMENTS(security_drivers) && !drv; i++) {
virSecurityDriver *tmp = security_drivers[i];
if (name &&
STRNEQ(tmp->name, name))
continue;
switch (tmp->probe(virtDriver)) {
case SECURITY_DRIVER_ENABLE:
VIR_DEBUG("Probed name=%s", tmp->name);
drv = tmp;
break;
case SECURITY_DRIVER_DISABLE:
VIR_DEBUG("Not enabled name=%s", tmp->name);
if (name && STREQ(tmp->name, name)) {
virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
_("Security driver %s not enabled"),
name);
return NULL;
}
break;
case SECURITY_DRIVER_ERROR:
default:
return NULL;
}
}
if (!drv) {
virReportError(VIR_ERR_INTERNAL_ERROR,
_("Security driver %s not found"),
NULLSTR(name));
return NULL;
}
return drv;
}
| lgpl-2.1 |
cpritam/moose | modules/richards/src/postprocessors/RichardsExcavFlow.C | 1375 | /*****************************************/
/* Written by andrew.wilkins@csiro.au */
/* Please contact me if you make changes */
/*****************************************/
#include "RichardsExcavFlow.h"
#include "Function.h"
#include "Material.h"
template<>
InputParameters validParams<RichardsExcavFlow>()
{
InputParameters params = validParams<SideIntegralVariablePostprocessor>();
params.addRequiredParam<FunctionName>("excav_geom_function", "The function describing the excavation geometry (type RichardsExcavGeom)");
params.addRequiredParam<UserObjectName>("richardsVarNames_UO", "The UserObject that holds the list of Richards variable names.");
params.addClassDescription("Records total flow INTO an excavation (if quantity is positive then flow has occured from rock into excavation void)");
return params;
}
RichardsExcavFlow::RichardsExcavFlow(const std::string & name, InputParameters parameters) :
SideIntegralVariablePostprocessor(name, parameters),
_richards_name_UO(getUserObject<RichardsVarNames>("richardsVarNames_UO")),
_pvar(_richards_name_UO.richards_var_num(_var.number())),
_flux(getMaterialProperty<std::vector<RealVectorValue> >("flux")),
_func(getFunction("excav_geom_function"))
{}
Real
RichardsExcavFlow::computeQpIntegral()
{
return -_func.value(_t, _q_point[_qp])*_normals[_qp]*_flux[_qp][_pvar]*_dt;
}
| lgpl-2.1 |
gleicher27/Tardigrade | moose/modules/richards/src/postprocessors/RichardsExcavFlow.C | 1602 | /****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "RichardsExcavFlow.h"
#include "Function.h"
#include "Material.h"
template<>
InputParameters validParams<RichardsExcavFlow>()
{
InputParameters params = validParams<SideIntegralVariablePostprocessor>();
params.addRequiredParam<FunctionName>("excav_geom_function", "The function describing the excavation geometry (type RichardsExcavGeom)");
params.addRequiredParam<UserObjectName>("richardsVarNames_UO", "The UserObject that holds the list of Richards variable names.");
params.addClassDescription("Records total flow INTO an excavation (if quantity is positive then flow has occured from rock into excavation void)");
return params;
}
RichardsExcavFlow::RichardsExcavFlow(const std::string & name, InputParameters parameters) :
SideIntegralVariablePostprocessor(name, parameters),
_richards_name_UO(getUserObject<RichardsVarNames>("richardsVarNames_UO")),
_pvar(_richards_name_UO.richards_var_num(_var.number())),
_flux(getMaterialProperty<std::vector<RealVectorValue> >("flux")),
_func(getFunction("excav_geom_function"))
{}
Real
RichardsExcavFlow::computeQpIntegral()
{
return -_func.value(_t, _q_point[_qp])*_normals[_qp]*_flux[_qp][_pvar]*_dt;
}
| lgpl-2.1 |
marclaporte/jitsi | src/net/java/sip/communicator/impl/gui/main/contactlist/contactsource/StringContactSourceServiceImpl.java | 6347 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main.contactlist.contactsource;
import java.util.*;
import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.service.contactsource.*;
import net.java.sip.communicator.service.protocol.*;
/**
* The <tt>StringContactSourceServiceImpl</tt> is an implementation of the
* <tt>ContactSourceService</tt> that returns the searched string as a result
* contact.
*
* @author Yana Stamcheva
*/
public class StringContactSourceServiceImpl
implements ContactSourceService
{
/**
* The protocol provider to be used with this string contact source.
*/
private final ProtocolProviderService protocolProvider;
/**
* The operation set supported by this string contact source.
*/
private final Class<? extends OperationSet> opSetClass;
/**
* Can display disable adding display details for source contacts.
*/
private boolean disableDisplayDetails = true;
/**
* Creates an instance of <tt>StringContactSourceServiceImpl</tt>.
*
* @param protocolProvider the protocol provider to be used with this string
* contact source
* @param opSet the operation set supported by this string contact source
*/
public StringContactSourceServiceImpl(
ProtocolProviderService protocolProvider,
Class<? extends OperationSet> opSet)
{
this.protocolProvider = protocolProvider;
this.opSetClass = opSet;
}
/**
* Returns the type of this contact source.
*
* @return the type of this contact source
*/
public int getType()
{
return SEARCH_TYPE;
}
/**
* Returns a user-friendly string that identifies this contact source.
*
* @return the display name of this contact source
*/
public String getDisplayName()
{
return GuiActivator.getResources().getI18NString(
"service.gui.SEARCH_STRING_CONTACT_SOURCE");
}
/**
* Creates query for the given <tt>queryString</tt>.
*
* @param queryString the string to search for
* @return the created query
*/
public ContactQuery createContactQuery(String queryString)
{
return createContactQuery(queryString, -1);
}
/**
* Creates query for the given <tt>queryString</tt>.
*
* @param queryString the string to search for
* @param contactCount the maximum count of result contacts
* @return the created query
*/
public ContactQuery createContactQuery( String queryString,
int contactCount)
{
return new StringQuery(queryString);
}
/**
* Changes whether to add display details for contact sources.
* @param disableDisplayDetails
*/
public void setDisableDisplayDetails(boolean disableDisplayDetails)
{
this.disableDisplayDetails = disableDisplayDetails;
}
/**
* Returns the source contact corresponding to the query string.
*
* @return the source contact corresponding to the query string
*/
public SourceContact createSourceContact(String queryString)
{
ArrayList<ContactDetail> contactDetails
= new ArrayList<ContactDetail>();
ContactDetail contactDetail = new ContactDetail(queryString);
// Init supported operation sets.
ArrayList<Class<? extends OperationSet>>
supportedOpSets
= new ArrayList<Class<? extends OperationSet>>();
supportedOpSets.add(opSetClass);
contactDetail.setSupportedOpSets(supportedOpSets);
// Init preferred protocol providers.
Map<Class<? extends OperationSet>,ProtocolProviderService>
providers = new HashMap<Class<? extends OperationSet>,
ProtocolProviderService>();
providers.put(opSetClass, protocolProvider);
contactDetail.setPreferredProviders(providers);
contactDetails.add(contactDetail);
GenericSourceContact sourceContact
= new GenericSourceContact( StringContactSourceServiceImpl.this,
queryString,
contactDetails);
if(disableDisplayDetails)
{
sourceContact.setDisplayDetails(
GuiActivator.getResources().getI18NString(
"service.gui.CALL_VIA")
+ " "
+ protocolProvider.getAccountID().getDisplayName());
}
return sourceContact;
}
/**
* The query implementation.
*/
private class StringQuery
extends AbstractContactQuery<ContactSourceService>
{
/**
* The query string.
*/
private String queryString;
/**
* The query result list.
*/
private final List<SourceContact> results;
/**
* Creates an instance of this query implementation.
*
* @param queryString the string to query
*/
public StringQuery(String queryString)
{
super(StringContactSourceServiceImpl.this);
this.queryString = queryString;
this.results = new ArrayList<SourceContact>();
}
/**
* Returns the query string.
*
* @return the query string
*/
public String getQueryString()
{
return queryString;
}
/**
* Returns the list of query results.
*
* @return the list of query results
*/
public List<SourceContact> getQueryResults()
{
return results;
}
@Override
public void start()
{
SourceContact contact = createSourceContact(queryString);
results.add(contact);
fireContactReceived(contact);
if (getStatus() != QUERY_CANCELED)
setStatus(QUERY_COMPLETED);
}
}
/**
* Returns the index of the contact source in the result list.
*
* @return the index of the contact source in the result list
*/
public int getIndex()
{
return 0;
}
}
| lgpl-2.1 |
cfallin/soot | src/soot/jimple/toolkits/scalar/pre/BusyCodeMotion.java | 6656 | /* Soot - a J*va Optimization Framework
* Copyright (C) 2002 Florian Loitsch
*
* 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.
*/
/*
* Modified by the Sable Research Group and others 1997-1999.
* See the 'credits' file distributed with Soot for the complete list of
* contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot)
*/
package soot.jimple.toolkits.scalar.pre;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.EquivalentValue;
import soot.G;
import soot.Local;
import soot.Scene;
import soot.SideEffectTester;
import soot.Singletons;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.IdentityStmt;
import soot.jimple.Jimple;
import soot.jimple.NaiveSideEffectTester;
import soot.jimple.toolkits.graph.CriticalEdgeRemover;
import soot.jimple.toolkits.pointer.PASideEffectTester;
import soot.jimple.toolkits.scalar.LocalCreation;
import soot.options.BCMOptions;
import soot.options.Options;
import soot.toolkits.graph.BriefUnitGraph;
import soot.toolkits.graph.UnitGraph;
import soot.util.Chain;
import soot.util.UnitMap;
/**
* Performs a partial redundancy elimination (= code motion). This is done, by
* moving <b>every</b>computation as high as possible (it is easy to show, that
* they are computationally optimal), and then replacing the original
* computation by a reference to this new high computation. This implies, that
* we introduce <b>many</b> new helper-variables (that can easily be eliminated
* afterwards).<br>
* In order to catch every redundant expression, this transformation must be
* done on a graph without critical edges. Therefore the first thing we do, is
* removing them. A subsequent pass can then easily remove the synthetic nodes
* we have introduced.<br>
* The term "busy" refers to the fact, that we <b>always</b> move computations
* as high as possible. Even, if this is not necessary.
*
* @see soot.jimple.toolkits.graph.CriticalEdgeRemover
*/
public class BusyCodeMotion extends BodyTransformer {
public BusyCodeMotion(Singletons.Global g) {
}
public static BusyCodeMotion v() {
return G.v().soot_jimple_toolkits_scalar_pre_BusyCodeMotion();
}
private static final String PREFIX = "$bcm";
/**
* performs the busy code motion.
*/
protected void internalTransform(Body b, String phaseName, Map<String, String> opts) {
BCMOptions options = new BCMOptions(opts);
HashMap<EquivalentValue, Local> expToHelper = new HashMap<EquivalentValue, Local>();
Chain<Unit> unitChain = b.getUnits();
if (Options.v().verbose())
G.v().out.println("[" + b.getMethod().getName() + "] performing Busy Code Motion...");
CriticalEdgeRemover.v().transform(b, phaseName + ".cer");
UnitGraph graph = new BriefUnitGraph(b);
/* map each unit to its RHS. only take binary expressions */
Map<Unit, EquivalentValue> unitToEquivRhs = new UnitMap<EquivalentValue>(b, graph.size() + 1, 0.7f) {
protected EquivalentValue mapTo(Unit unit) {
Value tmp = SootFilter.noInvokeRhs(unit);
Value tmp2 = SootFilter.binop(tmp);
if (tmp2 == null)
tmp2 = SootFilter.concreteRef(tmp);
return SootFilter.equiVal(tmp2);
}
};
/* same as before, but without exception-throwing expressions */
Map<Unit, EquivalentValue> unitToNoExceptionEquivRhs = new UnitMap<EquivalentValue>(b, graph.size() + 1, 0.7f) {
protected EquivalentValue mapTo(Unit unit) {
Value tmp = SootFilter.binopRhs(unit);
tmp = SootFilter.noExceptionThrowing(tmp);
return SootFilter.equiVal(tmp);
}
};
/* if a more precise sideeffect-tester comes out, please change it here! */
SideEffectTester sideEffect;
if (Scene.v().hasCallGraph() && !options.naive_side_effect()) {
sideEffect = new PASideEffectTester();
} else {
sideEffect = new NaiveSideEffectTester();
}
sideEffect.newMethod(b.getMethod());
UpSafetyAnalysis upSafe = new UpSafetyAnalysis(graph, unitToEquivRhs, sideEffect);
DownSafetyAnalysis downSafe = new DownSafetyAnalysis(graph, unitToNoExceptionEquivRhs, sideEffect);
EarliestnessComputation earliest = new EarliestnessComputation(graph, upSafe, downSafe, sideEffect);
LocalCreation localCreation = new LocalCreation(b.getLocals(), PREFIX);
Iterator<Unit> unitIt = unitChain.snapshotIterator();
{ /* insert the computations at the earliest positions */
while (unitIt.hasNext()) {
Unit currentUnit = unitIt.next();
for (EquivalentValue equiVal : earliest.getFlowBefore(currentUnit)) {
// Value exp = equiVal.getValue();
/* get the unic helper-name for this expression */
Local helper = expToHelper.get(equiVal);
// Make sure not to place any stuff inside the identity block at
// the beginning of the method
if (currentUnit instanceof IdentityStmt)
currentUnit = getFirstNonIdentityStmt(b);
if (helper == null) {
helper = localCreation.newLocal(equiVal.getType());
expToHelper.put(equiVal, helper);
}
/* insert a new Assignment-stmt before the currentUnit */
Value insertValue = Jimple.cloneIfNecessary(equiVal.getValue());
Unit firstComp = Jimple.v().newAssignStmt(helper, insertValue);
unitChain.insertBefore(firstComp, currentUnit);
}
}
}
{ /* replace old computations by the helper-vars */
unitIt = unitChain.iterator();
while (unitIt.hasNext()) {
Unit currentUnit = unitIt.next();
EquivalentValue rhs = unitToEquivRhs.get(currentUnit);
if (rhs != null) {
Local helper = expToHelper.get(rhs);
if (helper != null)
((AssignStmt) currentUnit).setRightOp(helper);
}
}
}
if (Options.v().verbose())
G.v().out.println("[" + b.getMethod().getName() + "] Busy Code Motion done!");
}
private Unit getFirstNonIdentityStmt(Body b) {
for (Unit u : b.getUnits())
if (!(u instanceof IdentityStmt))
return u;
return null;
}
}
| lgpl-2.1 |
Alfresco/alfresco-repository | src/main/java/org/alfresco/repo/cache/InMemoryCacheStatistics.java | 8474 | /*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.cache;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
import org.alfresco.repo.cache.TransactionStats.OpType;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Simple non-persistent implementation of {@link CacheStatistics}. Statistics
* are empty at repository startup.
*
* @since 5.0
* @author Matt Ward
*/
public class InMemoryCacheStatistics implements CacheStatistics, ApplicationContextAware
{
/** Read/Write locks by cache name */
private final ConcurrentMap<String, ReentrantReadWriteLock> locks = new ConcurrentHashMap<>();
private Map<String, Map<OpType, OperationStats>> cacheToStatsMap = new HashMap<>();
private ApplicationContext applicationContext;
@Override
public long count(String cacheName, OpType opType)
{
ReadLock readLock = getReadLock(cacheName);
readLock.lock();
try
{
Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName);
if (cacheStats == null)
{
throw new NoStatsForCache(cacheName);
}
OperationStats opStats = cacheStats.get(opType);
return opStats.getCount();
}
finally
{
readLock.unlock();
}
}
@Override
public double meanTime(String cacheName, OpType opType)
{
ReadLock readLock = getReadLock(cacheName);
readLock.lock();
try
{
Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName);
if (cacheStats == null)
{
throw new NoStatsForCache(cacheName);
}
OperationStats opStats = cacheStats.get(opType);
return opStats.meanTime();
}
finally
{
readLock.unlock();
}
}
@Override
public void add(String cacheName, TransactionStats txStats)
{
boolean registerCacheStats = false;
WriteLock writeLock = getWriteLock(cacheName);
writeLock.lock();
try
{
// Are we adding new stats for a previously unseen cache?
registerCacheStats = !cacheToStatsMap.containsKey(cacheName);
if (registerCacheStats)
{
// There are no statistics yet for this cache.
cacheToStatsMap.put(cacheName, new HashMap<OpType, OperationStats>());
}
Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName);
for (OpType opType : OpType.values())
{
SummaryStatistics txOpSummary = txStats.getTimings(opType);
long count = txOpSummary.getN();
double totalTime = txOpSummary.getSum();
OperationStats oldStats = cacheStats.get(opType);
OperationStats newStats;
if (oldStats == null)
{
newStats = new OperationStats(totalTime, count);
}
else
{
newStats = new OperationStats(oldStats, totalTime, count);
}
cacheStats.put(opType, newStats);
}
}
finally
{
writeLock.unlock();
}
if (registerCacheStats)
{
// We've added stats for a previously unseen cache, raise an event
// so that an MBean for the cache may be registered, for example.
applicationContext.publishEvent(new CacheStatisticsCreated(this, cacheName));
}
}
@Override
public double hitMissRatio(String cacheName)
{
ReadLock readLock = getReadLock(cacheName);
readLock.lock();
try
{
Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName);
if (cacheStats == null)
{
throw new NoStatsForCache(cacheName);
}
long hits = cacheStats.get(OpType.GET_HIT).getCount();
long misses = cacheStats.get(OpType.GET_MISS).getCount();
return (double)hits / (hits+misses);
}
finally
{
readLock.unlock();
}
}
@Override
public long numGets(String cacheName)
{
ReadLock readLock = getReadLock(cacheName);
readLock.lock();
try
{
Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName);
if (cacheStats == null)
{
throw new NoStatsForCache(cacheName);
}
long hits = cacheStats.get(OpType.GET_HIT).getCount();
long misses = cacheStats.get(OpType.GET_MISS).getCount();
return hits+misses;
}
finally
{
readLock.unlock();
}
}
@Override
public Map<OpType, OperationStats> allStats(String cacheName)
{
ReadLock readLock = getReadLock(cacheName);
readLock.lock();
try
{
Map<OpType, OperationStats> cacheStats = cacheToStatsMap.get(cacheName);
if (cacheStats == null)
{
throw new NoStatsForCache(cacheName);
}
return new HashMap<>(cacheStats);
}
finally
{
readLock.unlock();
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
this.applicationContext = applicationContext;
}
/**
* Gets a {@link ReentrantReadWriteLock} for a specific cache, lazily
* creating the lock if necessary. Locks may be created per cache
* (rather than hashing to a smaller pool) since the number of
* caches is not too large.
*
* @param cacheName Cache name to obtain lock for.
* @return ReentrantReadWriteLock
*/
private ReentrantReadWriteLock getLock(String cacheName)
{
if (!locks.containsKey(cacheName))
{
ReentrantReadWriteLock newLock = new ReentrantReadWriteLock();
if (locks.putIfAbsent(cacheName, newLock) == null)
{
// Lock was successfully added to map.
return newLock;
};
}
return locks.get(cacheName);
}
private ReadLock getReadLock(String cacheName)
{
ReadLock readLock = getLock(cacheName).readLock();
return readLock;
}
private WriteLock getWriteLock(String cacheName)
{
WriteLock writeLock = getLock(cacheName).writeLock();
return writeLock;
}
}
| lgpl-3.0 |
cpopescu/whispermedialib | third-party/gstreamer/gst-ffmpeg/gst-libs/ext/ffmpeg/libavutil/lls.c | 4066 | /*
* linear least squares model
*
* Copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file lls.c
* linear least squares model
*/
#include <math.h>
#include <string.h>
#include "lls.h"
void av_init_lls(LLSModel *m, int indep_count){
memset(m, 0, sizeof(LLSModel));
m->indep_count= indep_count;
}
void av_update_lls(LLSModel *m, double *var, double decay){
int i,j;
for(i=0; i<=m->indep_count; i++){
for(j=i; j<=m->indep_count; j++){
m->covariance[i][j] *= decay;
m->covariance[i][j] += var[i]*var[j];
}
}
}
void av_solve_lls(LLSModel *m, double threshold, int min_order){
int i,j,k;
double (*factor)[MAX_VARS+1]= (void*)&m->covariance[1][0];
double (*covar )[MAX_VARS+1]= (void*)&m->covariance[1][1];
double *covar_y = m->covariance[0];
int count= m->indep_count;
for(i=0; i<count; i++){
for(j=i; j<count; j++){
double sum= covar[i][j];
for(k=i-1; k>=0; k--)
sum -= factor[i][k]*factor[j][k];
if(i==j){
if(sum < threshold)
sum= 1.0;
factor[i][i]= sqrt(sum);
}else
factor[j][i]= sum / factor[i][i];
}
}
for(i=0; i<count; i++){
double sum= covar_y[i+1];
for(k=i-1; k>=0; k--)
sum -= factor[i][k]*m->coeff[0][k];
m->coeff[0][i]= sum / factor[i][i];
}
for(j=count-1; j>=min_order; j--){
for(i=j; i>=0; i--){
double sum= m->coeff[0][i];
for(k=i+1; k<=j; k++)
sum -= factor[k][i]*m->coeff[j][k];
m->coeff[j][i]= sum / factor[i][i];
}
m->variance[j]= covar_y[0];
for(i=0; i<=j; i++){
double sum= m->coeff[j][i]*covar[i][i] - 2*covar_y[i+1];
for(k=0; k<i; k++)
sum += 2*m->coeff[j][k]*covar[k][i];
m->variance[j] += m->coeff[j][i]*sum;
}
}
}
double av_evaluate_lls(LLSModel *m, double *param, int order){
int i;
double out= 0;
for(i=0; i<=order; i++)
out+= param[i]*m->coeff[order][i];
return out;
}
#ifdef TEST
#include <stdlib.h>
#include <stdio.h>
int main(void){
LLSModel m;
int i, order;
av_init_lls(&m, 3);
for(i=0; i<100; i++){
double var[4];
double eval;
#if 0
var[1] = rand() / (double)RAND_MAX;
var[2] = rand() / (double)RAND_MAX;
var[3] = rand() / (double)RAND_MAX;
var[2]= var[1] + var[3]/2;
var[0] = var[1] + var[2] + var[3] + var[1]*var[2]/100;
#else
var[0] = (rand() / (double)RAND_MAX - 0.5)*2;
var[1] = var[0] + rand() / (double)RAND_MAX - 0.5;
var[2] = var[1] + rand() / (double)RAND_MAX - 0.5;
var[3] = var[2] + rand() / (double)RAND_MAX - 0.5;
#endif
av_update_lls(&m, var, 0.99);
av_solve_lls(&m, 0.001, 0);
for(order=0; order<3; order++){
eval= av_evaluate_lls(&m, var+1, order);
printf("real:%f order:%d pred:%f var:%f coeffs:%f %f %f\n",
var[0], order, eval, sqrt(m.variance[order] / (i+1)),
m.coeff[order][0], m.coeff[order][1], m.coeff[order][2]);
}
}
return 0;
}
#endif
| lgpl-3.0 |
cpopescu/whispermedialib | third-party/gstreamer/gst-ffmpeg-0.10.10/gst-libs/ext/ffmpeg/libavformat/mpegenc.c | 42954 | /*
* MPEG1/2 muxer
* Copyright (c) 2000, 2001, 2002 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/fifo.h"
#include "libavcodec/put_bits.h"
#include "avformat.h"
#include "mpeg.h"
#define MAX_PAYLOAD_SIZE 4096
//#define DEBUG_SEEK
#undef NDEBUG
#include <assert.h>
typedef struct PacketDesc {
int64_t pts;
int64_t dts;
int size;
int unwritten_size;
int flags;
struct PacketDesc *next;
} PacketDesc;
typedef struct {
AVFifoBuffer *fifo;
uint8_t id;
int max_buffer_size; /* in bytes */
int buffer_index;
PacketDesc *predecode_packet;
PacketDesc *premux_packet;
PacketDesc **next_packet;
int packet_number;
uint8_t lpcm_header[3];
int lpcm_align;
int bytes_to_iframe;
int align_iframe;
int64_t vobu_start_pts;
} StreamInfo;
typedef struct {
int packet_size; /* required packet size */
int packet_number;
int pack_header_freq; /* frequency (in packets^-1) at which we send pack headers */
int system_header_freq;
int system_header_size;
int mux_rate; /* bitrate in units of 50 bytes/s */
/* stream info */
int audio_bound;
int video_bound;
int is_mpeg2;
int is_vcd;
int is_svcd;
int is_dvd;
int64_t last_scr; /* current system clock */
double vcd_padding_bitrate; //FIXME floats
int64_t vcd_padding_bytes_written;
} MpegMuxContext;
extern AVOutputFormat mpeg1vcd_muxer;
extern AVOutputFormat mpeg2dvd_muxer;
extern AVOutputFormat mpeg2svcd_muxer;
extern AVOutputFormat mpeg2vob_muxer;
static int put_pack_header(AVFormatContext *ctx,
uint8_t *buf, int64_t timestamp)
{
MpegMuxContext *s = ctx->priv_data;
PutBitContext pb;
init_put_bits(&pb, buf, 128);
put_bits32(&pb, PACK_START_CODE);
if (s->is_mpeg2) {
put_bits(&pb, 2, 0x1);
} else {
put_bits(&pb, 4, 0x2);
}
put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
put_bits(&pb, 1, 1);
put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
put_bits(&pb, 1, 1);
put_bits(&pb, 15, (uint32_t)((timestamp ) & 0x7fff));
put_bits(&pb, 1, 1);
if (s->is_mpeg2) {
/* clock extension */
put_bits(&pb, 9, 0);
}
put_bits(&pb, 1, 1);
put_bits(&pb, 22, s->mux_rate);
put_bits(&pb, 1, 1);
if (s->is_mpeg2) {
put_bits(&pb, 1, 1);
put_bits(&pb, 5, 0x1f); /* reserved */
put_bits(&pb, 3, 0); /* stuffing length */
}
flush_put_bits(&pb);
return put_bits_ptr(&pb) - pb.buf;
}
static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)
{
MpegMuxContext *s = ctx->priv_data;
int size, i, private_stream_coded, id;
PutBitContext pb;
init_put_bits(&pb, buf, 128);
put_bits32(&pb, SYSTEM_HEADER_START_CODE);
put_bits(&pb, 16, 0);
put_bits(&pb, 1, 1);
put_bits(&pb, 22, s->mux_rate); /* maximum bit rate of the multiplexed stream */
put_bits(&pb, 1, 1); /* marker */
if (s->is_vcd && only_for_stream_id==VIDEO_ID) {
/* This header applies only to the video stream (see VCD standard p. IV-7)*/
put_bits(&pb, 6, 0);
} else
put_bits(&pb, 6, s->audio_bound);
if (s->is_vcd) {
/* see VCD standard, p. IV-7*/
put_bits(&pb, 1, 0);
put_bits(&pb, 1, 1);
} else {
put_bits(&pb, 1, 0); /* variable bitrate*/
put_bits(&pb, 1, 0); /* non constrainted bit stream */
}
if (s->is_vcd || s->is_dvd) {
/* see VCD standard p IV-7 */
put_bits(&pb, 1, 1); /* audio locked */
put_bits(&pb, 1, 1); /* video locked */
} else {
put_bits(&pb, 1, 0); /* audio locked */
put_bits(&pb, 1, 0); /* video locked */
}
put_bits(&pb, 1, 1); /* marker */
if (s->is_vcd && (only_for_stream_id & 0xe0) == AUDIO_ID) {
/* This header applies only to the audio stream (see VCD standard p. IV-7)*/
put_bits(&pb, 5, 0);
} else
put_bits(&pb, 5, s->video_bound);
if (s->is_dvd) {
put_bits(&pb, 1, 0); /* packet_rate_restriction_flag */
put_bits(&pb, 7, 0x7f); /* reserved byte */
} else
put_bits(&pb, 8, 0xff); /* reserved byte */
/* DVD-Video Stream_bound entries
id (0xB9) video, maximum P-STD for stream 0xE0. (P-STD_buffer_bound_scale = 1)
id (0xB8) audio, maximum P-STD for any MPEG audio (0xC0 to 0xC7) streams. If there are none set to 4096 (32x128). (P-STD_buffer_bound_scale = 0)
id (0xBD) private stream 1 (audio other than MPEG and subpictures). (P-STD_buffer_bound_scale = 1)
id (0xBF) private stream 2, NAV packs, set to 2x1024. */
if (s->is_dvd) {
int P_STD_max_video = 0;
int P_STD_max_mpeg_audio = 0;
int P_STD_max_mpeg_PS1 = 0;
for(i=0;i<ctx->nb_streams;i++) {
StreamInfo *stream = ctx->streams[i]->priv_data;
id = stream->id;
if (id == 0xbd && stream->max_buffer_size > P_STD_max_mpeg_PS1) {
P_STD_max_mpeg_PS1 = stream->max_buffer_size;
} else if (id >= 0xc0 && id <= 0xc7 && stream->max_buffer_size > P_STD_max_mpeg_audio) {
P_STD_max_mpeg_audio = stream->max_buffer_size;
} else if (id == 0xe0 && stream->max_buffer_size > P_STD_max_video) {
P_STD_max_video = stream->max_buffer_size;
}
}
/* video */
put_bits(&pb, 8, 0xb9); /* stream ID */
put_bits(&pb, 2, 3);
put_bits(&pb, 1, 1);
put_bits(&pb, 13, P_STD_max_video / 1024);
/* audio */
if (P_STD_max_mpeg_audio == 0)
P_STD_max_mpeg_audio = 4096;
put_bits(&pb, 8, 0xb8); /* stream ID */
put_bits(&pb, 2, 3);
put_bits(&pb, 1, 0);
put_bits(&pb, 13, P_STD_max_mpeg_audio / 128);
/* private stream 1 */
put_bits(&pb, 8, 0xbd); /* stream ID */
put_bits(&pb, 2, 3);
put_bits(&pb, 1, 0);
put_bits(&pb, 13, P_STD_max_mpeg_PS1 / 128);
/* private stream 2 */
put_bits(&pb, 8, 0xbf); /* stream ID */
put_bits(&pb, 2, 3);
put_bits(&pb, 1, 1);
put_bits(&pb, 13, 2);
}
else {
/* audio stream info */
private_stream_coded = 0;
for(i=0;i<ctx->nb_streams;i++) {
StreamInfo *stream = ctx->streams[i]->priv_data;
/* For VCDs, only include the stream info for the stream
that the pack which contains this system belongs to.
(see VCD standard p. IV-7) */
if ( !s->is_vcd || stream->id==only_for_stream_id
|| only_for_stream_id==0) {
id = stream->id;
if (id < 0xc0) {
/* special case for private streams (AC-3 uses that) */
if (private_stream_coded)
continue;
private_stream_coded = 1;
id = 0xbd;
}
put_bits(&pb, 8, id); /* stream ID */
put_bits(&pb, 2, 3);
if (id < 0xe0) {
/* audio */
put_bits(&pb, 1, 0);
put_bits(&pb, 13, stream->max_buffer_size / 128);
} else {
/* video */
put_bits(&pb, 1, 1);
put_bits(&pb, 13, stream->max_buffer_size / 1024);
}
}
}
}
flush_put_bits(&pb);
size = put_bits_ptr(&pb) - pb.buf;
/* patch packet size */
buf[4] = (size - 6) >> 8;
buf[5] = (size - 6) & 0xff;
return size;
}
static int get_system_header_size(AVFormatContext *ctx)
{
int buf_index, i, private_stream_coded;
StreamInfo *stream;
MpegMuxContext *s = ctx->priv_data;
if (s->is_dvd)
return 18; // DVD-Video system headers are 18 bytes fixed length.
buf_index = 12;
private_stream_coded = 0;
for(i=0;i<ctx->nb_streams;i++) {
stream = ctx->streams[i]->priv_data;
if (stream->id < 0xc0) {
if (private_stream_coded)
continue;
private_stream_coded = 1;
}
buf_index += 3;
}
return buf_index;
}
static int mpeg_mux_init(AVFormatContext *ctx)
{
MpegMuxContext *s = ctx->priv_data;
int bitrate, i, mpa_id, mpv_id, mps_id, ac3_id, dts_id, lpcm_id, j;
AVStream *st;
StreamInfo *stream;
int audio_bitrate;
int video_bitrate;
s->packet_number = 0;
s->is_vcd = (CONFIG_MPEG1VCD_MUXER && ctx->oformat == &mpeg1vcd_muxer);
s->is_svcd = (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &mpeg2svcd_muxer);
s->is_mpeg2 = ((CONFIG_MPEG2VOB_MUXER && ctx->oformat == &mpeg2vob_muxer) ||
(CONFIG_MPEG2DVD_MUXER && ctx->oformat == &mpeg2dvd_muxer) ||
(CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &mpeg2svcd_muxer));
s->is_dvd = (CONFIG_MPEG2DVD_MUXER && ctx->oformat == &mpeg2dvd_muxer);
if(ctx->packet_size) {
if (ctx->packet_size < 20 || ctx->packet_size > (1 << 23) + 10) {
av_log(ctx, AV_LOG_ERROR, "Invalid packet size %d\n",
ctx->packet_size);
goto fail;
}
s->packet_size = ctx->packet_size;
} else
s->packet_size = 2048;
s->vcd_padding_bytes_written = 0;
s->vcd_padding_bitrate=0;
s->audio_bound = 0;
s->video_bound = 0;
mpa_id = AUDIO_ID;
ac3_id = AC3_ID;
dts_id = DTS_ID;
mpv_id = VIDEO_ID;
mps_id = SUB_ID;
lpcm_id = LPCM_ID;
for(i=0;i<ctx->nb_streams;i++) {
st = ctx->streams[i];
stream = av_mallocz(sizeof(StreamInfo));
if (!stream)
goto fail;
st->priv_data = stream;
av_set_pts_info(st, 64, 1, 90000);
switch(st->codec->codec_type) {
case CODEC_TYPE_AUDIO:
if (st->codec->codec_id == CODEC_ID_AC3) {
stream->id = ac3_id++;
} else if (st->codec->codec_id == CODEC_ID_DTS) {
stream->id = dts_id++;
} else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
stream->id = lpcm_id++;
for(j = 0; j < 4; j++) {
if (lpcm_freq_tab[j] == st->codec->sample_rate)
break;
}
if (j == 4)
goto fail;
if (st->codec->channels > 8)
return -1;
stream->lpcm_header[0] = 0x0c;
stream->lpcm_header[1] = (st->codec->channels - 1) | (j << 4);
stream->lpcm_header[2] = 0x80;
stream->lpcm_align = st->codec->channels * 2;
} else {
stream->id = mpa_id++;
}
/* This value HAS to be used for VCD (see VCD standard, p. IV-7).
Right now it is also used for everything else.*/
stream->max_buffer_size = 4 * 1024;
s->audio_bound++;
break;
case CODEC_TYPE_VIDEO:
stream->id = mpv_id++;
if (st->codec->rc_buffer_size)
stream->max_buffer_size = 6*1024 + st->codec->rc_buffer_size/8;
else
stream->max_buffer_size = 230*1024; //FIXME this is probably too small as default
#if 0
/* see VCD standard, p. IV-7*/
stream->max_buffer_size = 46 * 1024;
else
/* This value HAS to be used for SVCD (see SVCD standard, p. 26 V.2.3.2).
Right now it is also used for everything else.*/
stream->max_buffer_size = 230 * 1024;
#endif
s->video_bound++;
break;
case CODEC_TYPE_SUBTITLE:
stream->id = mps_id++;
stream->max_buffer_size = 16 * 1024;
break;
default:
return -1;
}
stream->fifo= av_fifo_alloc(16);
if (!stream->fifo)
goto fail;
}
bitrate = 0;
audio_bitrate = 0;
video_bitrate = 0;
for(i=0;i<ctx->nb_streams;i++) {
int codec_rate;
st = ctx->streams[i];
stream = (StreamInfo*) st->priv_data;
if(st->codec->rc_max_rate || stream->id==VIDEO_ID)
codec_rate= st->codec->rc_max_rate;
else
codec_rate= st->codec->bit_rate;
if(!codec_rate)
codec_rate= (1<<21)*8*50/ctx->nb_streams;
bitrate += codec_rate;
if ((stream->id & 0xe0) == AUDIO_ID)
audio_bitrate += codec_rate;
else if (stream->id==VIDEO_ID)
video_bitrate += codec_rate;
}
if(ctx->mux_rate){
s->mux_rate= (ctx->mux_rate + (8 * 50) - 1) / (8 * 50);
} else {
/* we increase slightly the bitrate to take into account the
headers. XXX: compute it exactly */
bitrate += bitrate*5/100;
bitrate += 10000;
s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
}
if (s->is_vcd) {
double overhead_rate;
/* The VCD standard mandates that the mux_rate field is 3528
(see standard p. IV-6).
The value is actually "wrong", i.e. if you calculate
it using the normal formula and the 75 sectors per second transfer
rate you get a different value because the real pack size is 2324,
not 2352. But the standard explicitly specifies that the mux_rate
field in the header must have this value.*/
// s->mux_rate=2352 * 75 / 50; /* = 3528*/
/* The VCD standard states that the muxed stream must be
exactly 75 packs / second (the data rate of a single speed cdrom).
Since the video bitrate (probably 1150000 bits/sec) will be below
the theoretical maximum we have to add some padding packets
to make up for the lower data rate.
(cf. VCD standard p. IV-6 )*/
/* Add the header overhead to the data rate.
2279 data bytes per audio pack, 2294 data bytes per video pack*/
overhead_rate = ((audio_bitrate / 8.0) / 2279) * (2324 - 2279);
overhead_rate += ((video_bitrate / 8.0) / 2294) * (2324 - 2294);
overhead_rate *= 8;
/* Add padding so that the full bitrate is 2324*75 bytes/sec */
s->vcd_padding_bitrate = 2324 * 75 * 8 - (bitrate + overhead_rate);
}
if (s->is_vcd || s->is_mpeg2)
/* every packet */
s->pack_header_freq = 1;
else
/* every 2 seconds */
s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
/* the above seems to make pack_header_freq zero sometimes */
if (s->pack_header_freq == 0)
s->pack_header_freq = 1;
if (s->is_mpeg2)
/* every 200 packets. Need to look at the spec. */
s->system_header_freq = s->pack_header_freq * 40;
else if (s->is_vcd)
/* the standard mandates that there are only two system headers
in the whole file: one in the first packet of each stream.
(see standard p. IV-7 and IV-8) */
s->system_header_freq = 0x7fffffff;
else
s->system_header_freq = s->pack_header_freq * 5;
for(i=0;i<ctx->nb_streams;i++) {
stream = ctx->streams[i]->priv_data;
stream->packet_number = 0;
}
s->system_header_size = get_system_header_size(ctx);
s->last_scr = 0;
return 0;
fail:
for(i=0;i<ctx->nb_streams;i++) {
av_free(ctx->streams[i]->priv_data);
}
return AVERROR(ENOMEM);
}
static inline void put_timestamp(ByteIOContext *pb, int id, int64_t timestamp)
{
put_byte(pb,
(id << 4) |
(((timestamp >> 30) & 0x07) << 1) |
1);
put_be16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
put_be16(pb, (uint16_t)((((timestamp ) & 0x7fff) << 1) | 1));
}
/* return the number of padding bytes that should be inserted into
the multiplexed stream.*/
static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
{
MpegMuxContext *s = ctx->priv_data;
int pad_bytes = 0;
if (s->vcd_padding_bitrate > 0 && pts!=AV_NOPTS_VALUE)
{
int64_t full_pad_bytes;
full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0); //FIXME this is wrong
pad_bytes = (int) (full_pad_bytes - s->vcd_padding_bytes_written);
if (pad_bytes<0)
/* might happen if we have already padded to a later timestamp. This
can occur if another stream has already advanced further.*/
pad_bytes=0;
}
return pad_bytes;
}
#if 0 /* unused, remove? */
/* return the exact available payload size for the next packet for
stream 'stream_index'. 'pts' and 'dts' are only used to know if
timestamps are needed in the packet header. */
static int get_packet_payload_size(AVFormatContext *ctx, int stream_index,
int64_t pts, int64_t dts)
{
MpegMuxContext *s = ctx->priv_data;
int buf_index;
StreamInfo *stream;
stream = ctx->streams[stream_index]->priv_data;
buf_index = 0;
if (((s->packet_number % s->pack_header_freq) == 0)) {
/* pack header size */
if (s->is_mpeg2)
buf_index += 14;
else
buf_index += 12;
if (s->is_vcd) {
/* there is exactly one system header for each stream in a VCD MPEG,
One in the very first video packet and one in the very first
audio packet (see VCD standard p. IV-7 and IV-8).*/
if (stream->packet_number==0)
/* The system headers refer only to the stream they occur in,
so they have a constant size.*/
buf_index += 15;
} else {
if ((s->packet_number % s->system_header_freq) == 0)
buf_index += s->system_header_size;
}
}
if ((s->is_vcd && stream->packet_number==0)
|| (s->is_svcd && s->packet_number==0))
/* the first pack of each stream contains only the pack header,
the system header and some padding (see VCD standard p. IV-6)
Add the padding size, so that the actual payload becomes 0.*/
buf_index += s->packet_size - buf_index;
else {
/* packet header size */
buf_index += 6;
if (s->is_mpeg2) {
buf_index += 3;
if (stream->packet_number==0)
buf_index += 3; /* PES extension */
buf_index += 1; /* obligatory stuffing byte */
}
if (pts != AV_NOPTS_VALUE) {
if (dts != pts)
buf_index += 5 + 5;
else
buf_index += 5;
} else {
if (!s->is_mpeg2)
buf_index++;
}
if (stream->id < 0xc0) {
/* AC-3/LPCM private data header */
buf_index += 4;
if (stream->id >= 0xa0) {
int n;
buf_index += 3;
/* NOTE: we round the payload size to an integer number of
LPCM samples */
n = (s->packet_size - buf_index) % stream->lpcm_align;
if (n)
buf_index += (stream->lpcm_align - n);
}
}
if (s->is_vcd && (stream->id & 0xe0) == AUDIO_ID)
/* The VCD standard demands that 20 zero bytes follow
each audio packet (see standard p. IV-8).*/
buf_index+=20;
}
return s->packet_size - buf_index;
}
#endif
/* Write an MPEG padding packet header. */
static void put_padding_packet(AVFormatContext *ctx, ByteIOContext *pb,int packet_bytes)
{
MpegMuxContext *s = ctx->priv_data;
int i;
put_be32(pb, PADDING_STREAM);
put_be16(pb, packet_bytes - 6);
if (!s->is_mpeg2) {
put_byte(pb, 0x0f);
packet_bytes -= 7;
} else
packet_bytes -= 6;
for(i=0;i<packet_bytes;i++)
put_byte(pb, 0xff);
}
static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len){
int nb_frames=0;
PacketDesc *pkt_desc= stream->premux_packet;
while(len>0){
if(pkt_desc->size == pkt_desc->unwritten_size)
nb_frames++;
len -= pkt_desc->unwritten_size;
pkt_desc= pkt_desc->next;
}
return nb_frames;
}
/* flush the packet on stream stream_index */
static int flush_packet(AVFormatContext *ctx, int stream_index,
int64_t pts, int64_t dts, int64_t scr, int trailer_size)
{
MpegMuxContext *s = ctx->priv_data;
StreamInfo *stream = ctx->streams[stream_index]->priv_data;
uint8_t *buf_ptr;
int size, payload_size, startcode, id, stuffing_size, i, header_len;
int packet_size;
uint8_t buffer[128];
int zero_trail_bytes = 0;
int pad_packet_bytes = 0;
int pes_flags;
int general_pack = 0; /*"general" pack without data specific to one stream?*/
int nb_frames;
id = stream->id;
#if 0
printf("packet ID=%2x PTS=%0.3f\n",
id, pts / 90000.0);
#endif
buf_ptr = buffer;
if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
/* output pack and systems header if needed */
size = put_pack_header(ctx, buf_ptr, scr);
buf_ptr += size;
s->last_scr= scr;
if (s->is_vcd) {
/* there is exactly one system header for each stream in a VCD MPEG,
One in the very first video packet and one in the very first
audio packet (see VCD standard p. IV-7 and IV-8).*/
if (stream->packet_number==0) {
size = put_system_header(ctx, buf_ptr, id);
buf_ptr += size;
}
} else if (s->is_dvd) {
if (stream->align_iframe || s->packet_number == 0){
int PES_bytes_to_fill = s->packet_size - size - 10;
if (pts != AV_NOPTS_VALUE) {
if (dts != pts)
PES_bytes_to_fill -= 5 + 5;
else
PES_bytes_to_fill -= 5;
}
if (stream->bytes_to_iframe == 0 || s->packet_number == 0) {
size = put_system_header(ctx, buf_ptr, 0);
buf_ptr += size;
size = buf_ptr - buffer;
put_buffer(ctx->pb, buffer, size);
put_be32(ctx->pb, PRIVATE_STREAM_2);
put_be16(ctx->pb, 0x03d4); // length
put_byte(ctx->pb, 0x00); // substream ID, 00=PCI
for (i = 0; i < 979; i++)
put_byte(ctx->pb, 0x00);
put_be32(ctx->pb, PRIVATE_STREAM_2);
put_be16(ctx->pb, 0x03fa); // length
put_byte(ctx->pb, 0x01); // substream ID, 01=DSI
for (i = 0; i < 1017; i++)
put_byte(ctx->pb, 0x00);
memset(buffer, 0, 128);
buf_ptr = buffer;
s->packet_number++;
stream->align_iframe = 0;
scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
size = put_pack_header(ctx, buf_ptr, scr);
s->last_scr= scr;
buf_ptr += size;
/* GOP Start */
} else if (stream->bytes_to_iframe < PES_bytes_to_fill) {
pad_packet_bytes = PES_bytes_to_fill - stream->bytes_to_iframe;
}
}
} else {
if ((s->packet_number % s->system_header_freq) == 0) {
size = put_system_header(ctx, buf_ptr, 0);
buf_ptr += size;
}
}
}
size = buf_ptr - buffer;
put_buffer(ctx->pb, buffer, size);
packet_size = s->packet_size - size;
if (s->is_vcd && (id & 0xe0) == AUDIO_ID)
/* The VCD standard demands that 20 zero bytes follow
each audio pack (see standard p. IV-8).*/
zero_trail_bytes += 20;
if ((s->is_vcd && stream->packet_number==0)
|| (s->is_svcd && s->packet_number==0)) {
/* for VCD the first pack of each stream contains only the pack header,
the system header and lots of padding (see VCD standard p. IV-6).
In the case of an audio pack, 20 zero bytes are also added at
the end.*/
/* For SVCD we fill the very first pack to increase compatibility with
some DVD players. Not mandated by the standard.*/
if (s->is_svcd)
general_pack = 1; /* the system header refers to both streams and no stream data*/
pad_packet_bytes = packet_size - zero_trail_bytes;
}
packet_size -= pad_packet_bytes + zero_trail_bytes;
if (packet_size > 0) {
/* packet header size */
packet_size -= 6;
/* packet header */
if (s->is_mpeg2) {
header_len = 3;
if (stream->packet_number==0)
header_len += 3; /* PES extension */
header_len += 1; /* obligatory stuffing byte */
} else {
header_len = 0;
}
if (pts != AV_NOPTS_VALUE) {
if (dts != pts)
header_len += 5 + 5;
else
header_len += 5;
} else {
if (!s->is_mpeg2)
header_len++;
}
payload_size = packet_size - header_len;
if (id < 0xc0) {
startcode = PRIVATE_STREAM_1;
payload_size -= 1;
if (id >= 0x40) {
payload_size -= 3;
if (id >= 0xa0)
payload_size -= 3;
}
} else {
startcode = 0x100 + id;
}
stuffing_size = payload_size - av_fifo_size(stream->fifo);
// first byte does not fit -> reset pts/dts + stuffing
if(payload_size <= trailer_size && pts != AV_NOPTS_VALUE){
int timestamp_len=0;
if(dts != pts)
timestamp_len += 5;
if(pts != AV_NOPTS_VALUE)
timestamp_len += s->is_mpeg2 ? 5 : 4;
pts=dts= AV_NOPTS_VALUE;
header_len -= timestamp_len;
if (s->is_dvd && stream->align_iframe) {
pad_packet_bytes += timestamp_len;
packet_size -= timestamp_len;
} else {
payload_size += timestamp_len;
}
stuffing_size += timestamp_len;
if(payload_size > trailer_size)
stuffing_size += payload_size - trailer_size;
}
if (pad_packet_bytes > 0 && pad_packet_bytes <= 7) { // can't use padding, so use stuffing
packet_size += pad_packet_bytes;
payload_size += pad_packet_bytes; // undo the previous adjustment
if (stuffing_size < 0) {
stuffing_size = pad_packet_bytes;
} else {
stuffing_size += pad_packet_bytes;
}
pad_packet_bytes = 0;
}
if (stuffing_size < 0)
stuffing_size = 0;
if (stuffing_size > 16) { /*<=16 for MPEG-1, <=32 for MPEG-2*/
pad_packet_bytes += stuffing_size;
packet_size -= stuffing_size;
payload_size -= stuffing_size;
stuffing_size = 0;
}
nb_frames= get_nb_frames(ctx, stream, payload_size - stuffing_size);
put_be32(ctx->pb, startcode);
put_be16(ctx->pb, packet_size);
if (!s->is_mpeg2)
for(i=0;i<stuffing_size;i++)
put_byte(ctx->pb, 0xff);
if (s->is_mpeg2) {
put_byte(ctx->pb, 0x80); /* mpeg2 id */
pes_flags=0;
if (pts != AV_NOPTS_VALUE) {
pes_flags |= 0x80;
if (dts != pts)
pes_flags |= 0x40;
}
/* Both the MPEG-2 and the SVCD standards demand that the
P-STD_buffer_size field be included in the first packet of
every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
and MPEG-2 standard 2.7.7) */
if (stream->packet_number == 0)
pes_flags |= 0x01;
put_byte(ctx->pb, pes_flags); /* flags */
put_byte(ctx->pb, header_len - 3 + stuffing_size);
if (pes_flags & 0x80) /*write pts*/
put_timestamp(ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
if (pes_flags & 0x40) /*write dts*/
put_timestamp(ctx->pb, 0x01, dts);
if (pes_flags & 0x01) { /*write pes extension*/
put_byte(ctx->pb, 0x10); /* flags */
/* P-STD buffer info */
if ((id & 0xe0) == AUDIO_ID)
put_be16(ctx->pb, 0x4000 | stream->max_buffer_size/ 128);
else
put_be16(ctx->pb, 0x6000 | stream->max_buffer_size/1024);
}
} else {
if (pts != AV_NOPTS_VALUE) {
if (dts != pts) {
put_timestamp(ctx->pb, 0x03, pts);
put_timestamp(ctx->pb, 0x01, dts);
} else {
put_timestamp(ctx->pb, 0x02, pts);
}
} else {
put_byte(ctx->pb, 0x0f);
}
}
if (s->is_mpeg2) {
/* special stuffing byte that is always written
to prevent accidental generation of start codes. */
put_byte(ctx->pb, 0xff);
for(i=0;i<stuffing_size;i++)
put_byte(ctx->pb, 0xff);
}
if (startcode == PRIVATE_STREAM_1) {
put_byte(ctx->pb, id);
if (id >= 0xa0) {
/* LPCM (XXX: check nb_frames) */
put_byte(ctx->pb, 7);
put_be16(ctx->pb, 4); /* skip 3 header bytes */
put_byte(ctx->pb, stream->lpcm_header[0]);
put_byte(ctx->pb, stream->lpcm_header[1]);
put_byte(ctx->pb, stream->lpcm_header[2]);
} else if (id >= 0x40) {
/* AC-3 */
put_byte(ctx->pb, nb_frames);
put_be16(ctx->pb, trailer_size+1);
}
}
/* output data */
assert(payload_size - stuffing_size <= av_fifo_size(stream->fifo));
av_fifo_generic_read(stream->fifo, ctx->pb, payload_size - stuffing_size, &put_buffer);
stream->bytes_to_iframe -= payload_size - stuffing_size;
}else{
payload_size=
stuffing_size= 0;
}
if (pad_packet_bytes > 0)
put_padding_packet(ctx,ctx->pb, pad_packet_bytes);
for(i=0;i<zero_trail_bytes;i++)
put_byte(ctx->pb, 0x00);
put_flush_packet(ctx->pb);
s->packet_number++;
/* only increase the stream packet number if this pack actually contains
something that is specific to this stream! I.e. a dedicated header
or some data.*/
if (!general_pack)
stream->packet_number++;
return payload_size - stuffing_size;
}
static void put_vcd_padding_sector(AVFormatContext *ctx)
{
/* There are two ways to do this padding: writing a sector/pack
of 0 values, or writing an MPEG padding pack. Both seem to
work with most decoders, BUT the VCD standard only allows a 0-sector
(see standard p. IV-4, IV-5).
So a 0-sector it is...*/
MpegMuxContext *s = ctx->priv_data;
int i;
for(i=0;i<s->packet_size;i++)
put_byte(ctx->pb, 0);
s->vcd_padding_bytes_written += s->packet_size;
put_flush_packet(ctx->pb);
/* increasing the packet number is correct. The SCR of the following packs
is calculated from the packet_number and it has to include the padding
sector (it represents the sector index, not the MPEG pack index)
(see VCD standard p. IV-6)*/
s->packet_number++;
}
#if 0 /* unused, remove? */
static int64_t get_vcd_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
{
MpegMuxContext *s = ctx->priv_data;
int64_t scr;
/* Since the data delivery rate is constant, SCR is computed
using the formula C + i * 1200 where C is the start constant
and i is the pack index.
It is recommended that SCR 0 is at the beginning of the VCD front
margin (a sequence of empty Form 2 sectors on the CD).
It is recommended that the front margin is 30 sectors long, so
we use C = 30*1200 = 36000
(Note that even if the front margin is not 30 sectors the file
will still be correct according to the standard. It just won't have
the "recommended" value).*/
scr = 36000 + s->packet_number * 1200;
return scr;
}
#endif
static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr){
// MpegMuxContext *s = ctx->priv_data;
int i;
for(i=0; i<ctx->nb_streams; i++){
AVStream *st = ctx->streams[i];
StreamInfo *stream = st->priv_data;
PacketDesc *pkt_desc;
while((pkt_desc= stream->predecode_packet)
&& scr > pkt_desc->dts){ //FIXME > vs >=
if(stream->buffer_index < pkt_desc->size ||
stream->predecode_packet == stream->premux_packet){
av_log(ctx, AV_LOG_ERROR,
"buffer underflow i=%d bufi=%d size=%d\n",
i, stream->buffer_index, pkt_desc->size);
break;
}
stream->buffer_index -= pkt_desc->size;
stream->predecode_packet= pkt_desc->next;
av_freep(&pkt_desc);
}
}
return 0;
}
static int output_packet(AVFormatContext *ctx, int flush){
MpegMuxContext *s = ctx->priv_data;
AVStream *st;
StreamInfo *stream;
int i, avail_space=0, es_size, trailer_size;
int best_i= -1;
int best_score= INT_MIN;
int ignore_constraints=0;
int64_t scr= s->last_scr;
PacketDesc *timestamp_packet;
const int64_t max_delay= av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
retry:
for(i=0; i<ctx->nb_streams; i++){
AVStream *st = ctx->streams[i];
StreamInfo *stream = st->priv_data;
const int avail_data= av_fifo_size(stream->fifo);
const int space= stream->max_buffer_size - stream->buffer_index;
int rel_space= 1024*space / stream->max_buffer_size;
PacketDesc *next_pkt= stream->premux_packet;
/* for subtitle, a single PES packet must be generated,
so we flush after every single subtitle packet */
if(s->packet_size > avail_data && !flush
&& st->codec->codec_type != CODEC_TYPE_SUBTITLE)
return 0;
if(avail_data==0)
continue;
assert(avail_data>0);
if(space < s->packet_size && !ignore_constraints)
continue;
if(next_pkt && next_pkt->dts - scr > max_delay)
continue;
if(rel_space > best_score){
best_score= rel_space;
best_i = i;
avail_space= space;
}
}
if(best_i < 0){
int64_t best_dts= INT64_MAX;
for(i=0; i<ctx->nb_streams; i++){
AVStream *st = ctx->streams[i];
StreamInfo *stream = st->priv_data;
PacketDesc *pkt_desc= stream->predecode_packet;
if(pkt_desc && pkt_desc->dts < best_dts)
best_dts= pkt_desc->dts;
}
#if 0
av_log(ctx, AV_LOG_DEBUG, "bumping scr, scr:%f, dts:%f\n",
scr/90000.0, best_dts/90000.0);
#endif
if(best_dts == INT64_MAX)
return 0;
if(scr >= best_dts+1 && !ignore_constraints){
av_log(ctx, AV_LOG_ERROR, "packet too large, ignoring buffer limits to mux it\n");
ignore_constraints= 1;
}
scr= FFMAX(best_dts+1, scr);
if(remove_decoded_packets(ctx, scr) < 0)
return -1;
goto retry;
}
assert(best_i >= 0);
st = ctx->streams[best_i];
stream = st->priv_data;
assert(av_fifo_size(stream->fifo) > 0);
assert(avail_space >= s->packet_size || ignore_constraints);
timestamp_packet= stream->premux_packet;
if(timestamp_packet->unwritten_size == timestamp_packet->size){
trailer_size= 0;
}else{
trailer_size= timestamp_packet->unwritten_size;
timestamp_packet= timestamp_packet->next;
}
if(timestamp_packet){
//av_log(ctx, AV_LOG_DEBUG, "dts:%f pts:%f scr:%f stream:%d\n", timestamp_packet->dts/90000.0, timestamp_packet->pts/90000.0, scr/90000.0, best_i);
es_size= flush_packet(ctx, best_i, timestamp_packet->pts, timestamp_packet->dts, scr, trailer_size);
}else{
assert(av_fifo_size(stream->fifo) == trailer_size);
es_size= flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr, trailer_size);
}
if (s->is_vcd) {
/* Write one or more padding sectors, if necessary, to reach
the constant overall bitrate.*/
int vcd_pad_bytes;
while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->premux_packet->pts) ) >= s->packet_size){ //FIXME pts cannot be correct here
put_vcd_padding_sector(ctx);
s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
}
}
stream->buffer_index += es_size;
s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
while(stream->premux_packet && stream->premux_packet->unwritten_size <= es_size){
es_size -= stream->premux_packet->unwritten_size;
stream->premux_packet= stream->premux_packet->next;
}
if(es_size)
stream->premux_packet->unwritten_size -= es_size;
if(remove_decoded_packets(ctx, s->last_scr) < 0)
return -1;
return 1;
}
static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
{
MpegMuxContext *s = ctx->priv_data;
int stream_index= pkt->stream_index;
int size= pkt->size;
uint8_t *buf= pkt->data;
AVStream *st = ctx->streams[stream_index];
StreamInfo *stream = st->priv_data;
int64_t pts, dts;
PacketDesc *pkt_desc;
const int preload= av_rescale(ctx->preload, 90000, AV_TIME_BASE);
const int is_iframe = st->codec->codec_type == CODEC_TYPE_VIDEO && (pkt->flags & PKT_FLAG_KEY);
pts= pkt->pts;
dts= pkt->dts;
if(pts != AV_NOPTS_VALUE) pts += preload;
if(dts != AV_NOPTS_VALUE) dts += preload;
//av_log(ctx, AV_LOG_DEBUG, "dts:%f pts:%f flags:%d stream:%d nopts:%d\n", dts/90000.0, pts/90000.0, pkt->flags, pkt->stream_index, pts != AV_NOPTS_VALUE);
if (!stream->premux_packet)
stream->next_packet = &stream->premux_packet;
*stream->next_packet=
pkt_desc= av_mallocz(sizeof(PacketDesc));
pkt_desc->pts= pts;
pkt_desc->dts= dts;
pkt_desc->unwritten_size=
pkt_desc->size= size;
if(!stream->predecode_packet)
stream->predecode_packet= pkt_desc;
stream->next_packet= &pkt_desc->next;
if (av_fifo_realloc2(stream->fifo, av_fifo_size(stream->fifo) + size) < 0)
return -1;
if (s->is_dvd){
if (is_iframe && (s->packet_number == 0 || (pts - stream->vobu_start_pts >= 36000))) { // min VOBU length 0.4 seconds (mpucoder)
stream->bytes_to_iframe = av_fifo_size(stream->fifo);
stream->align_iframe = 1;
stream->vobu_start_pts = pts;
}
}
av_fifo_generic_write(stream->fifo, buf, size, NULL);
for(;;){
int ret= output_packet(ctx, 0);
if(ret<=0)
return ret;
}
}
static int mpeg_mux_end(AVFormatContext *ctx)
{
// MpegMuxContext *s = ctx->priv_data;
StreamInfo *stream;
int i;
for(;;){
int ret= output_packet(ctx, 1);
if(ret<0)
return ret;
else if(ret==0)
break;
}
/* End header according to MPEG1 systems standard. We do not write
it as it is usually not needed by decoders and because it
complicates MPEG stream concatenation. */
//put_be32(ctx->pb, ISO_11172_END_CODE);
//put_flush_packet(ctx->pb);
for(i=0;i<ctx->nb_streams;i++) {
stream = ctx->streams[i]->priv_data;
assert(av_fifo_size(stream->fifo) == 0);
av_fifo_free(stream->fifo);
}
return 0;
}
#if CONFIG_MPEG1SYSTEM_MUXER
AVOutputFormat mpeg1system_muxer = {
"mpeg",
NULL_IF_CONFIG_SMALL("MPEG-1 System format"),
"video/mpeg",
"mpg,mpeg",
sizeof(MpegMuxContext),
CODEC_ID_MP2,
CODEC_ID_MPEG1VIDEO,
mpeg_mux_init,
mpeg_mux_write_packet,
mpeg_mux_end,
};
#endif
#if CONFIG_MPEG1VCD_MUXER
AVOutputFormat mpeg1vcd_muxer = {
"vcd",
NULL_IF_CONFIG_SMALL("MPEG-1 System format (VCD)"),
"video/mpeg",
NULL,
sizeof(MpegMuxContext),
CODEC_ID_MP2,
CODEC_ID_MPEG1VIDEO,
mpeg_mux_init,
mpeg_mux_write_packet,
mpeg_mux_end,
};
#endif
#if CONFIG_MPEG2VOB_MUXER
AVOutputFormat mpeg2vob_muxer = {
"vob",
NULL_IF_CONFIG_SMALL("MPEG-2 PS format (VOB)"),
"video/mpeg",
"vob",
sizeof(MpegMuxContext),
CODEC_ID_MP2,
CODEC_ID_MPEG2VIDEO,
mpeg_mux_init,
mpeg_mux_write_packet,
mpeg_mux_end,
};
#endif
/* Same as mpeg2vob_mux except that the pack size is 2324 */
#if CONFIG_MPEG2SVCD_MUXER
AVOutputFormat mpeg2svcd_muxer = {
"svcd",
NULL_IF_CONFIG_SMALL("MPEG-2 PS format (VOB)"),
"video/mpeg",
"vob",
sizeof(MpegMuxContext),
CODEC_ID_MP2,
CODEC_ID_MPEG2VIDEO,
mpeg_mux_init,
mpeg_mux_write_packet,
mpeg_mux_end,
};
#endif
/* Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
#if CONFIG_MPEG2DVD_MUXER
AVOutputFormat mpeg2dvd_muxer = {
"dvd",
NULL_IF_CONFIG_SMALL("MPEG-2 PS format (DVD VOB)"),
"video/mpeg",
"dvd",
sizeof(MpegMuxContext),
CODEC_ID_MP2,
CODEC_ID_MPEG2VIDEO,
mpeg_mux_init,
mpeg_mux_write_packet,
mpeg_mux_end,
};
#endif
| lgpl-3.0 |
edwinspire/VSharp | class/dlr/Runtime/Microsoft.Scripting.Core/Ast/NewArrayExpression.cs | 10491 | /* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Runtime.CompilerServices;
#if !FEATURE_CORE_DLR
namespace Microsoft.Scripting.Ast {
#else
namespace System.Linq.Expressions {
#endif
/// <summary>
/// Represents creating a new array and possibly initializing the elements of the new array.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.NewArrayExpressionProxy))]
public class NewArrayExpression : Expression {
private readonly ReadOnlyCollection<Expression> _expressions;
private readonly Type _type;
internal NewArrayExpression(Type type, ReadOnlyCollection<Expression> expressions) {
_expressions = expressions;
_type = type;
}
internal static NewArrayExpression Make(ExpressionType nodeType, Type type, ReadOnlyCollection<Expression> expressions) {
if (nodeType == ExpressionType.NewArrayInit) {
return new NewArrayInitExpression(type, expressions);
} else {
return new NewArrayBoundsExpression(type, expressions);
}
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type {
get { return _type; }
}
/// <summary>
/// Gets the bounds of the array if the value of the <see cref="P:NodeType"/> property is NewArrayBounds, or the values to initialize the elements of the new array if the value of the <see cref="P:NodeType"/> property is NewArrayInit.
/// </summary>
public ReadOnlyCollection<Expression> Expressions {
get { return _expressions; }
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor) {
return visitor.VisitNewArray(this);
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="expressions">The <see cref="Expressions" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public NewArrayExpression Update(IEnumerable<Expression> expressions) {
if (expressions == Expressions) {
return this;
}
if (NodeType == ExpressionType.NewArrayInit) {
return Expression.NewArrayInit(Type.GetElementType(), expressions);
}
return Expression.NewArrayBounds(Type.GetElementType(), expressions);
}
}
internal sealed class NewArrayInitExpression : NewArrayExpression {
internal NewArrayInitExpression(Type type, ReadOnlyCollection<Expression> expressions)
: base(type, expressions) {
}
/// <summary>
/// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType {
get { return ExpressionType.NewArrayInit; }
}
}
internal sealed class NewArrayBoundsExpression : NewArrayExpression {
internal NewArrayBoundsExpression(Type type, ReadOnlyCollection<Expression> expressions)
: base(type, expressions) {
}
/// <summary>
/// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType {
get { return ExpressionType.NewArrayBounds; }
}
}
public partial class Expression {
#region NewArrayInit
/// <summary>
/// Creates a new array expression of the specified type from the provided initializers.
/// </summary>
/// <param name="type">A Type that represents the element type of the array.</param>
/// <param name="initializers">The expressions used to create the array elements.</param>
/// <returns>An instance of the <see cref="NewArrayExpression"/>.</returns>
public static NewArrayExpression NewArrayInit(Type type, params Expression[] initializers) {
return NewArrayInit(type, (IEnumerable<Expression>)initializers);
}
/// <summary>
/// Creates a new array expression of the specified type from the provided initializers.
/// </summary>
/// <param name="type">A Type that represents the element type of the array.</param>
/// <param name="initializers">The expressions used to create the array elements.</param>
/// <returns>An instance of the <see cref="NewArrayExpression"/>.</returns>
public static NewArrayExpression NewArrayInit(Type type, IEnumerable<Expression> initializers) {
ContractUtils.RequiresNotNull(type, "type");
ContractUtils.RequiresNotNull(initializers, "initializers");
if (type.Equals(typeof(void))) {
throw Error.ArgumentCannotBeOfTypeVoid();
}
ReadOnlyCollection<Expression> initializerList = initializers.ToReadOnly();
Expression[] newList = null;
for (int i = 0, n = initializerList.Count; i < n; i++) {
Expression expr = initializerList[i];
RequiresCanRead(expr, "initializers");
if (!TypeUtils.AreReferenceAssignable(type, expr.Type)) {
if (!TryQuote(type, ref expr)){
throw Error.ExpressionTypeCannotInitializeArrayType(expr.Type, type);
}
if (newList == null) {
newList = new Expression[initializerList.Count];
for (int j = 0; j < i; j++) {
newList[j] = initializerList[j];
}
}
}
if (newList != null) {
newList[i] = expr;
}
}
if (newList != null) {
initializerList = new TrueReadOnlyCollection<Expression>(newList);
}
return NewArrayExpression.Make(ExpressionType.NewArrayInit, type.MakeArrayType(), initializerList);
}
#endregion
#region NewArrayBounds
/// <summary>
/// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank.
/// </summary>
/// <param name="type">A <see cref="Type"/> that represents the element type of the array.</param>
/// <param name="bounds">An array that contains Expression objects to use to populate the Expressions collection.</param>
/// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="P:NodeType"/> property equal to type and the <see cref="P:Expressions"/> property set to the specified value.</returns>
public static NewArrayExpression NewArrayBounds(Type type, params Expression[] bounds) {
return NewArrayBounds(type, (IEnumerable<Expression>)bounds);
}
/// <summary>
/// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank.
/// </summary>
/// <param name="type">A <see cref="Type"/> that represents the element type of the array.</param>
/// <param name="bounds">An IEnumerable{T} that contains Expression objects to use to populate the Expressions collection.</param>
/// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="P:NodeType"/> property equal to type and the <see cref="P:Expressions"/> property set to the specified value.</returns>
public static NewArrayExpression NewArrayBounds(Type type, IEnumerable<Expression> bounds) {
ContractUtils.RequiresNotNull(type, "type");
ContractUtils.RequiresNotNull(bounds, "bounds");
if (type.Equals(typeof(void))) {
throw Error.ArgumentCannotBeOfTypeVoid();
}
ReadOnlyCollection<Expression> boundsList = bounds.ToReadOnly();
int dimensions = boundsList.Count;
if (dimensions <= 0) throw Error.BoundsCannotBeLessThanOne();
for (int i = 0; i < dimensions; i++) {
Expression expr = boundsList[i];
RequiresCanRead(expr, "bounds");
if (!TypeUtils.IsInteger(expr.Type)) {
throw Error.ArgumentMustBeInteger();
}
}
Type arrayType;
if (dimensions == 1) {
//To get a vector, need call Type.MakeArrayType().
//Type.MakeArrayType(1) gives a non-vector array, which will cause type check error.
arrayType = type.MakeArrayType();
} else {
arrayType = type.MakeArrayType(dimensions);
}
return NewArrayExpression.Make(ExpressionType.NewArrayBounds, arrayType, bounds.ToReadOnly());
}
#endregion
}
}
| lgpl-3.0 |
AlphaStaxLLC/OpenSim | docs/org/cloudbus/cloudsim/class-use/DatacenterBroker.html | 6343 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_09) on Wed Nov 07 14:56:31 EST 2012 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class org.cloudbus.cloudsim.DatacenterBroker (cloudsim 3.0.2 API)</title>
<meta name="date" content="2012-11-07">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.cloudbus.cloudsim.DatacenterBroker (cloudsim 3.0.2 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../org/cloudbus/cloudsim/DatacenterBroker.html" title="class in org.cloudbus.cloudsim">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/cloudbus/cloudsim/class-use/DatacenterBroker.html" target="_top">Frames</a></li>
<li><a href="DatacenterBroker.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.cloudbus.cloudsim.DatacenterBroker" class="title">Uses of Class<br>org.cloudbus.cloudsim.DatacenterBroker</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../org/cloudbus/cloudsim/DatacenterBroker.html" title="class in org.cloudbus.cloudsim">DatacenterBroker</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.cloudbus.cloudsim.power">org.cloudbus.cloudsim.power</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.cloudbus.cloudsim.power">
<!-- -->
</a>
<h3>Uses of <a href="../../../../org/cloudbus/cloudsim/DatacenterBroker.html" title="class in org.cloudbus.cloudsim">DatacenterBroker</a> in <a href="../../../../org/cloudbus/cloudsim/power/package-summary.html">org.cloudbus.cloudsim.power</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../org/cloudbus/cloudsim/DatacenterBroker.html" title="class in org.cloudbus.cloudsim">DatacenterBroker</a> in <a href="../../../../org/cloudbus/cloudsim/power/package-summary.html">org.cloudbus.cloudsim.power</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../org/cloudbus/cloudsim/power/PowerDatacenterBroker.html" title="class in org.cloudbus.cloudsim.power">PowerDatacenterBroker</a></strong></code>
<div class="block">A broker for the power package.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../org/cloudbus/cloudsim/DatacenterBroker.html" title="class in org.cloudbus.cloudsim">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/cloudbus/cloudsim/class-use/DatacenterBroker.html" target="_top">Frames</a></li>
<li><a href="DatacenterBroker.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2012 <a href="http://cloudbus.org/">The Cloud Computing and Distributed Systems (CLOUDS) Laboratory, The University of Melbourne</a>. All Rights Reserved.</small></p>
</body>
</html>
| lgpl-3.0 |
genome/genome | lib/perl/Genome/Model/Command/Report/Mail.pm | 8053 | package Genome::Model::Command::Report::Mail;
use strict;
use warnings;
use Mail::Sender;
use Genome;
class Genome::Model::Command::Report::Mail {
is => 'Genome::Model::Command::BaseDeprecated',
has => [
report_name => {
is => 'Text',
doc => "the name of the report to mail",
},
build => {
is => 'Genome::Model::Build',
id_by => 'build_id',
doc => "the specific build of a genome model to mail a report for",
},
build_id => {
doc => 'the id for the build on which to report',
},
to => {
is => 'Text',
doc => 'the recipient list to mail the report to',
},
],
has_optional => [
directory => {
is => 'Text',
doc => 'the path of report directory to mail (needed only if the report was saved to a non-default location)',
}
],
};
sub help_brief {
"mail a report for a given build of a model"
}
sub help_synopsis {
return <<EOS
genome model report mail --build-id 12345 --report-name "Summary" --to user1\@example.com,user2\@example.com
genome model report run -b 12345 -r "DbSnp" --to user\@example.com
genome model report run -b 12345 -r "GoldSnp" --to user\@example.com --directory /homedirs/username/reports
EOS
}
sub help_detail {
return <<EOS
This launcher mails a report for some build of a genome model.
EOS
}
sub sub_command_sort_position { 1 }
sub create {
my $class = shift;
my $self = $class->SUPER::create(@_);
return unless $self;
# TODO: move this up
if (my $build = $self->build) {
if ($self->model_name and $self->build->model->name ne $self->model_name) {
$self->error_message("Redundant conflicting parameters. Specified model name "
. $self->model_name
. " does not match the name of build " . $build->id
. " which is " . $build->model->name
);
$self->delete;
return;
}
}
elsif ($self->model_name) {
my @models = Genome::Model->get(name => $self->model_name);
unless (@models) {
$self->warning_message("No models have exact name " . $self->model_name);
@models = Genome::Model->get("name like" => $self->model_name . "%");
unless (@models) {
$self->error_message("No models have a name beginning with " . $self->model_name);
$self->delete;
return;
}
if (@models > 1) {
$self->error_message("Found multiple models with names like " . $self->model_name . ":\n\t"
. join("\n\t", map { $_->name } @models)
. "\n"
);
$self->delete;
return;
}
$self->debug_message("Found model " . $models[0]->id . " (" . $models[0]->name . ")");
my $build = $models[0]->last_complete_build;
unless ($build) {
$self->error_message("No complete build for model!");
$self->delete;
return;
}
$self->debug_message("Found build " . $build->id . " from " . $build->date_completed);
$self->build($build);
}
}
else {
$self->error_message("A build must be specified either directly, or indirectly via a model name!");
$self->delete;
return;
}
return $self;
}
sub execute {
my $self = shift;
$DB::single = $DB::stopper;
my $build = $self->build;
my $model = $build->model;
my $report_name = $self->report_name;
my $report_path = $self->directory;
unless ( defined($report_path) ) {
$report_path = $build->resolve_reports_directory;
}
unless (-d $report_path) {
$self->error_message("Failed to find report directory $report_path!");
return;
}
my @mail_parts;
my $report_subdir = $self->report_name;
$report_subdir =~ s/ /_/g;
unless (-d "$report_path/$report_subdir") {
my @others = glob("$report_path/*");
$self->error_message(
"Failed to find subdirectory $report_subdir under $report_path!\n"
. "Found:\n\t" . join("\n\t",@others) . "\n"
);
return;
}
my $html_file = $report_path."/".$report_subdir."/report.html";
my $txt_file = $report_path."/".$report_subdir."/report.txt";
#Need at least one part to send!
my $file_count = 0;
if (-e $html_file) {
#print("\nFound html file.\n");
$file_count++;
}
if (-e $txt_file) {
#print("\nFound txt file.\n");
$file_count++;
}
if ( $file_count == 0 ) {
my @others = glob("$report_path/$report_subdir/*");
$self->error_message(
"Failed to find either text or html reports at the expected paths under $report_path/$report_subdir!"
. "\nFound:\n\t" . join("\n\t",@others) . "\n"
. "Expected HTML report at: $html_file\n"
. "Expected Text report at: $txt_file"
);
return;
}
$report_name =~ s/_/ /g;
my $subject = 'Genome Model '.$model->id.' "'.$model->name.'" '.$report_name.' Report for Build '.$build->id;
$self->debug_message("Sending email...");
if ($self->send_mail($subject,$html_file,$txt_file)) {
$self->debug_message("Email sent.");
return 1;
}
$self->error_message("Email not sent!");
return;
}
sub send_mail {
my $self = shift;
my $subject = shift;
my $msg_html = shift;
my $msg_txt = shift;
my $recipients = $self->to;
eval {
my $sender = Mail::Sender->new(
{
smtp => Genome::Config::get('email_smtp_server'),
to => $recipients,
from => Genome::Config::get('email_pipeline'),
subject => $subject,
multipart => 'related',
on_error => 'die',
}
);
$sender->OpenMultipart;
$sender->Part({ctype => 'multipart/alternative'});
if (-e $msg_txt) {
my $msg_txt_contents = get_contents($msg_txt);
$sender->Part({ctype => 'text/plain', disposition => 'NONE', msg => $msg_txt_contents})
}
if (-e $msg_html) {
my $msg_html_contents = get_contents($msg_html);
$sender->Part({ctype => 'text/html', disposition => 'NONE', msg => $msg_html_contents})
}
$sender->EndPart("multipart/alternative");
$sender->Close;
};
if ($@) {
$self->error_message("Error sending mail!: $@");
return;
}
return 1;
}
sub get_contents {
my $in_file_name = shift;
my $in = new IO::File($in_file_name, "r");
#print ("\nGetting contents for : $in_file_name\n");
my $ret = "";
while (<$in>) {
$ret.= $_;
}
$in->close();
return $ret;
}
# TODO: move onto the build or report as a method
sub _resolve_valid_report_class_for_build_and_name{
my $self = shift;
my $build = shift;
my $report_name = shift;
my $report_class_suffix =
join('',
map { ucfirst($_) }
split(" ",$report_name)
);
my @model_classes = (
grep { $_->isa('Genome::Model') and $_ ne 'Genome::Model' }
map { $_, $_->inheritance }
$build->model->__meta__->class_name
);
my $report_class_meta;
for my $model_class_name (@model_classes) {
$report_class_meta = UR::Object::Type->get($model_class_name . '::Report::' . $report_class_suffix);
last if $report_class_meta;
}
unless ($report_class_meta) {
$self->error_message("No reports named '$report_name' are available for models of type "
. join(", ", @model_classes));
return;
}
return $report_class_meta->class_name;
}
1;
| lgpl-3.0 |
ericomattos/javaforce | projects/jfcalc/src/ProgrammerPanel.java | 20790 | /**
* Created : Mar 26, 2012
*
* @author pquiring
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ProgrammerPanel extends javax.swing.JPanel implements Display, ActionListener {
/**
* Creates new form MainPanel
*/
public ProgrammerPanel(Backend backend) {
initComponents();
divide.setText("\u00f7");
this.backend = backend;
Insets zero = new Insets(0, 0, 0, 0);
JButton b;
for(int a=0;a<getComponentCount();a++) {
Component c = getComponent(a);
if (c instanceof JButton) {
b = (JButton)c;
b.addActionListener(this);
b.setMargin(zero);
}
}
backend.setRadix(10);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
output = new javax.swing.JTextField();
n7 = new javax.swing.JButton();
n8 = new javax.swing.JButton();
n9 = new javax.swing.JButton();
n4 = new javax.swing.JButton();
n5 = new javax.swing.JButton();
n6 = new javax.swing.JButton();
n1 = new javax.swing.JButton();
n2 = new javax.swing.JButton();
n3 = new javax.swing.JButton();
n0 = new javax.swing.JButton();
divide = new javax.swing.JButton();
multiple = new javax.swing.JButton();
minus = new javax.swing.JButton();
plus = new javax.swing.JButton();
allClear = new javax.swing.JButton();
open = new javax.swing.JButton();
close = new javax.swing.JButton();
eq = new javax.swing.JButton();
open1 = new javax.swing.JButton();
open2 = new javax.swing.JButton();
open3 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
hex = new javax.swing.JRadioButton();
decimal = new javax.swing.JRadioButton();
oct = new javax.swing.JRadioButton();
bin = new javax.swing.JRadioButton();
n10 = new javax.swing.JButton();
n11 = new javax.swing.JButton();
n12 = new javax.swing.JButton();
n13 = new javax.swing.JButton();
n14 = new javax.swing.JButton();
n15 = new javax.swing.JButton();
open4 = new javax.swing.JButton();
open5 = new javax.swing.JButton();
dec1 = new javax.swing.JButton();
allClear1 = new javax.swing.JButton();
output.setEditable(false);
output.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
n7.setText("7");
n8.setText("8");
n9.setText("9");
n4.setText("4");
n5.setText("5");
n6.setText("6");
n1.setText("1");
n2.setText("2");
n3.setText("3");
n0.setText("0");
divide.setText("/");
multiple.setText("x");
minus.setText("-");
plus.setText("+");
allClear.setText("AC");
allClear.setToolTipText("All Clear");
open.setText("(");
close.setText(")");
eq.setText("=");
open1.setText("XOR");
open2.setText("AND");
open3.setText("NOT");
buttonGroup1.add(hex);
hex.setText("Hex");
hex.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
hexActionPerformed(evt);
}
});
buttonGroup1.add(decimal);
decimal.setSelected(true);
decimal.setText("Dec");
decimal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
decimalActionPerformed(evt);
}
});
buttonGroup1.add(oct);
oct.setText("Oct");
oct.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
octActionPerformed(evt);
}
});
buttonGroup1.add(bin);
bin.setText("Bin");
bin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
binActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(hex)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(decimal)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(oct)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bin)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(hex)
.addComponent(decimal)
.addComponent(oct)
.addComponent(bin))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
n10.setText("A");
n11.setText("B");
n12.setText("C");
n13.setText("D");
n14.setText("E");
n15.setText("F");
open4.setText("MOD");
open5.setText("OR");
dec1.setText("+/-");
allClear1.setText("<");
allClear1.setToolTipText("All Clear");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(output, javax.swing.GroupLayout.DEFAULT_SIZE, 386, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(n10, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(n0, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(n1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(n4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(n7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(n8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(n9, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(divide, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(allClear, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(dec1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(62, 62, 62)
.addComponent(plus, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(eq, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(n2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(n3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(minus, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(56, 56, 56))
.addGroup(layout.createSequentialGroup()
.addComponent(n5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(n6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(multiple, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(open, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(close, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(allClear1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(open4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(open5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(open1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(open2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(open3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(n11, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(n12, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(n13, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(n14, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(n15, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(output, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(n7)
.addComponent(n8)
.addComponent(n9)
.addComponent(divide)
.addComponent(allClear)
.addComponent(open2)
.addComponent(allClear1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(n4)
.addComponent(n5)
.addComponent(n6)
.addComponent(multiple)
.addComponent(close)
.addComponent(open5)
.addComponent(open))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(n1)
.addComponent(n2)
.addComponent(n3)
.addComponent(minus)
.addComponent(open1)
.addComponent(open4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(n0)
.addComponent(plus)
.addComponent(dec1)
.addComponent(open3)
.addComponent(eq))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(n10)
.addComponent(n11)
.addComponent(n12)
.addComponent(n13)
.addComponent(n14)
.addComponent(n15))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void hexActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hexActionPerformed
backend.setRadix(16);
}//GEN-LAST:event_hexActionPerformed
private void decimalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_decimalActionPerformed
backend.setRadix(10);
}//GEN-LAST:event_decimalActionPerformed
private void octActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_octActionPerformed
backend.setRadix(8);
}//GEN-LAST:event_octActionPerformed
private void binActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_binActionPerformed
backend.setRadix(2);
}//GEN-LAST:event_binActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton allClear;
private javax.swing.JButton allClear1;
private javax.swing.JRadioButton bin;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton close;
private javax.swing.JButton dec1;
private javax.swing.JRadioButton decimal;
private javax.swing.JButton divide;
private javax.swing.JButton eq;
private javax.swing.JRadioButton hex;
private javax.swing.JPanel jPanel1;
private javax.swing.JButton minus;
private javax.swing.JButton multiple;
private javax.swing.JButton n0;
private javax.swing.JButton n1;
private javax.swing.JButton n10;
private javax.swing.JButton n11;
private javax.swing.JButton n12;
private javax.swing.JButton n13;
private javax.swing.JButton n14;
private javax.swing.JButton n15;
private javax.swing.JButton n2;
private javax.swing.JButton n3;
private javax.swing.JButton n4;
private javax.swing.JButton n5;
private javax.swing.JButton n6;
private javax.swing.JButton n7;
private javax.swing.JButton n8;
private javax.swing.JButton n9;
private javax.swing.JRadioButton oct;
private javax.swing.JButton open;
private javax.swing.JButton open1;
private javax.swing.JButton open2;
private javax.swing.JButton open3;
private javax.swing.JButton open4;
private javax.swing.JButton open5;
private javax.swing.JTextField output;
private javax.swing.JButton plus;
// End of variables declaration//GEN-END:variables
private Backend backend;
public void setDisplay(String str) {
int idx = str.indexOf(',');
if (idx != -1) {
output.setText(str.substring(0,idx)); //remove radix
} else {
output.setText(str);
}
}
public void actionPerformed(ActionEvent ae) {
JButton b = (JButton)ae.getSource();
String txt = b.getText();
if (txt.length() == 1) {
char first = txt.charAt(0);
if (((first >= '0') && (first <= '9')) || (first == '.') || ((first >= 'A') && (first <= 'F'))) {
backend.addDigit(first);
return;
}
}
backend.addOperation(txt);
}
public void cut() {
output.cut();
}
public void copy() {
output.copy();
}
public void setRadix(int rx) {
switch (rx) {
case 16: hex.setSelected(true); break;
case 10: decimal.setSelected(true); break;
case 8: oct.setSelected(true); break;
case 2: bin.setSelected(true); break;
}
backend.setRadix(rx);
}
}
| lgpl-3.0 |
yonghuang/fastui | samplecenter/basic/timeTest/operamasks-ui-2.0/development-bundle/ui/editor/_source/plugins/wsc/plugin.js | 1027 | /*
Copyright 2011, AUTHORS.txt (http://ui.operamasks.org/about)
Dual licensed under the MIT or LGPL Version 2 licenses.
*/
/**
* @file Spell checker
*/
// Register a plugin named "wsc".
OMEDITOR.plugins.add( 'wsc',
{
requires : [ 'dialog' ],
init : function( editor )
{
var commandName = 'checkspell';
var command = editor.addCommand( commandName, new OMEDITOR.dialogCommand( commandName ) );
// SpellChecker doesn't work in Opera and with custom domain
command.modes = { wysiwyg : ( !OMEDITOR.env.opera && !OMEDITOR.env.air && document.domain == window.location.hostname ) };
editor.ui.addButton( 'SpellChecker',
{
label : editor.lang.spellCheck.toolbar,
command : commandName
});
OMEDITOR.dialog.add( commandName, this.path + 'dialogs/wsc.js' );
}
});
OMEDITOR.config.wsc_customerId = OMEDITOR.config.wsc_customerId || '1:ua3xw1-2XyGJ3-GWruD3-6OFNT1-oXcuB1-nR6Bp4-hgQHc-EcYng3-sdRXG3-NOfFk' ;
OMEDITOR.config.wsc_customLoaderScript = OMEDITOR.config.wsc_customLoaderScript || null;
| lgpl-3.0 |
rospilot/rospilot | share/web_assets/nodejs_deps/node_modules/@angular/common/locales/extra/ta-MY.js | 1346 | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export default [
[
[
'நள்.', 'நண்.', 'அதி.', 'கா.', 'மதி.', 'பிற்.', 'மா.',
'அந்தி மா.', 'இர.'
],
[
'நள்ளிரவு', 'நண்பகல்', 'அதிகாலை', 'காலை',
'மதியம்', 'பிற்பகல்', 'மாலை',
'அந்தி மாலை', 'இரவு'
],
],
[
[
'நள்.', 'நண்.', 'அதி.', 'கா.', 'மதி.', 'பிற்.', 'மா.',
'அந்தி மா.', 'இ.'
],
[
'நள்ளிரவு', 'நண்பகல்', 'அதிகாலை', 'காலை',
'மதியம்', 'பிற்பகல்', 'மாலை',
'அந்தி மாலை', 'இரவு'
],
],
[
'00:00', '12:00', ['03:00', '05:00'], ['05:00', '12:00'], ['12:00', '14:00'],
['14:00', '16:00'], ['16:00', '18:00'], ['18:00', '21:00'], ['21:00', '03:00']
]
];
//# sourceMappingURL=ta-MY.js.map | apache-2.0 |
buildscientist/greenmail | greenmail-core/src/main/java/com/icegreen/greenmail/imap/ProtocolException.java | 610 | /*
* Copyright (c) 2014 Wael Chatila / Icegreen Technologies. All Rights Reserved.
* This software is released under the Apache license 2.0
* This file has been modified by the copyright holder.
* Original file can be found at http://james.apache.org
*/
package com.icegreen.greenmail.imap;
/**
* @author Darrell DeBoer <darrell@apache.org>
* @version $Revision: 109034 $
*/
public class ProtocolException extends Exception {
public ProtocolException(String s) {
super(s);
}
public ProtocolException(String s, Throwable cause) {
super(s,cause);
}
}
| apache-2.0 |
viticm/pfadmin | vendor/frozennode/administrator/public/js/ckeditor/plugins/uicolor/lang/et.js | 344 | /*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("uicolor","et",{title:"Värvivalija kasutajaliides",preview:"Automaatne eelvaade",config:"Aseta see sõne oma config.js faili.",predefined:"Eelmääratud värvikomplektid"}); | apache-2.0 |
wuranbo/elasticsearch | core/src/test/java/org/elasticsearch/index/mapper/GeoPointFieldTypeTests.java | 1095 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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.elasticsearch.index.mapper;
import org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.GeoPointFieldType;
public class GeoPointFieldTypeTests extends FieldTypeTestCase {
@Override
protected MappedFieldType createDefaultFieldType() {
return new GeoPointFieldType();
}
}
| apache-2.0 |
grpc/grpc-ios | native_src/third_party/protobuf/kokoro/linux/bazel/build.sh | 1053 | #!/bin/bash
#
# Build file to set up and run tests
set -ex
# Install Bazel 4.0.0.
use_bazel.sh 4.0.0
bazel version
# Print bazel testlogs to stdout when tests failed.
function print_test_logs {
# TODO(yannic): Only print logs of failing tests.
testlogs_dir=$(bazel info bazel-testlogs)
testlogs=$(find "${testlogs_dir}" -name "*.log")
for log in $testlogs; do
cat "${log}"
done
}
# Change to repo root
cd $(dirname $0)/../../..
git submodule update --init --recursive
# Disabled for now, re-enable if appropriate.
# //:build_files_updated_unittest \
trap print_test_logs EXIT
bazel test -k --copt=-Werror --host_copt=-Werror \
//java:tests \
//:protoc \
//:protobuf \
//:protobuf_python \
//:protobuf_test \
@com_google_protobuf//:cc_proto_blacklist_test
trap - EXIT
pushd examples
bazel build //...
popd
# Verify that we can build successfully from generated tar files.
./autogen.sh && ./configure && make -j$(nproc) dist
DIST=`ls *.tar.gz`
tar -xf $DIST
cd ${DIST//.tar.gz}
bazel build //:protobuf //:protobuf_java
| apache-2.0 |
wgpshashank/mysql_perf_analyzer | myperf/src/main/java/com/yahoo/dba/perf/myperf/common/MyDatabases.java | 1264 | /*
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the Apache License.
* See the accompanying LICENSE file for terms.
*/
package com.yahoo.dba.perf.myperf.common;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class MyDatabases implements java.io.Serializable{
private static final long serialVersionUID = -8586381924495834726L;
private Set<String> myDbSet = new TreeSet<String>();
synchronized public Set<String> getMyDbList()
{
return java.util.Collections.unmodifiableSet(this.myDbSet);
}
synchronized public void addDb(String name)
{
if(!this.myDbSet.contains(name))
this.myDbSet.add(name);
}
synchronized public void addDbs(List<String> names)
{
for (String name:names)
{
if(!this.myDbSet.contains(name))
this.myDbSet.add(name);
}
}
synchronized public void removeDb(String name)
{
if(this.myDbSet.contains(name))
this.myDbSet.remove(name);
}
synchronized public void replaceDb(String oldName, String newName)
{
if(!this.myDbSet.contains(oldName))
{
this.myDbSet.remove(oldName);
this.myDbSet.remove(newName);
}
}
synchronized public int size()
{
return this.myDbSet.size();
}
}
| apache-2.0 |
droolsjbpm/droolsjbpm-tools | drools-eclipse/org.guvnor.tools/src/org/guvnor/tools/actions/EditConnectionAction.java | 3786 | /*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* 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.guvnor.tools.actions;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Properties;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.webdav.IResponse;
import org.guvnor.tools.Activator;
import org.guvnor.tools.GuvnorRepository;
import org.guvnor.tools.Messages;
import org.guvnor.tools.utils.GuvnorMetadataProps;
import org.guvnor.tools.utils.GuvnorMetadataUtils;
import org.guvnor.tools.utils.PlatformUtils;
import org.guvnor.tools.utils.webdav.IWebDavClient;
import org.guvnor.tools.utils.webdav.WebDavClientFactory;
import org.guvnor.tools.utils.webdav.WebDavException;
import org.guvnor.tools.utils.webdav.WebDavServerCache;
import org.guvnor.tools.views.RepositoryView;
import org.guvnor.tools.views.ResourceHistoryView;
import org.guvnor.tools.views.model.TreeObject;
import org.guvnor.tools.views.model.TreeParent;
import org.guvnor.tools.wizards.EditRepLocationWizard;
/**
* Shows the revision history for a given resource.
*/
public class EditConnectionAction implements IObjectActionDelegate {
private GuvnorRepository rep;
public EditConnectionAction() {
super();
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction, org.eclipse.ui.IWorkbenchPart)
*/
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
*/
public void run(IAction action) {
EditRepLocationWizard editWizard = new EditRepLocationWizard(rep);
editWizard.init(Activator.getDefault().getWorkbench(), null);
WizardDialog dialog =
new WizardDialog(Display.getCurrent().getActiveShell(), editWizard);
dialog.create();
dialog.open();
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
// Reset state to default
action.setEnabled(false);
if (!(selection instanceof IStructuredSelection)) {
return;
}
IStructuredSelection sel = (IStructuredSelection)selection;
if (sel.size() != 1) {
return;
}
if (sel.getFirstElement() instanceof TreeObject) {
if (((TreeObject)sel.getFirstElement()).getNodeType() == TreeObject.Type.REPOSITORY) {
rep = ((TreeObject)sel.getFirstElement()).getGuvnorRepository();
action.setEnabled(true);
}
}
}
}
| apache-2.0 |
mrchristine/spark-examples-dbc | src/main/python/ml/index_to_string_example.py | 1615 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
from __future__ import print_function
# $example on$
from pyspark.ml.feature import IndexToString, StringIndexer
# $example off$
from pyspark.sql import SparkSession
if __name__ == "__main__":
spark = SparkSession\
.builder\
.appName("IndexToStringExample")\
.getOrCreate()
# $example on$
df = spark.createDataFrame(
[(0, "a"), (1, "b"), (2, "c"), (3, "a"), (4, "a"), (5, "c")],
["id", "category"])
stringIndexer = StringIndexer(inputCol="category", outputCol="categoryIndex")
model = stringIndexer.fit(df)
indexed = model.transform(df)
converter = IndexToString(inputCol="categoryIndex", outputCol="originalCategory")
converted = converter.transform(indexed)
converted.select("id", "originalCategory").show()
# $example off$
spark.stop()
| apache-2.0 |
WSO2Telco/component-dep | components/oneapi-validation/src/main/java/com/wso2telco/dep/oneapivalidation/service/impl/smsmessaging/northbound/ValidateNBDeliveryInfoNotification.java | 4034 | /*******************************************************************************
* Copyright (c) 2015-2016, WSO2.Telco Inc. (http://www.wso2telco.com) All Rights Reserved.
*
* WSO2.Telco Inc. licences this file to you 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 com.wso2telco.dep.oneapivalidation.service.impl.smsmessaging.northbound;
import org.json.JSONObject;
import com.wso2telco.dep.oneapivalidation.exceptions.CustomException;
import com.wso2telco.dep.oneapivalidation.service.IServiceValidate;
import com.wso2telco.dep.oneapivalidation.util.UrlValidator;
import com.wso2telco.dep.oneapivalidation.util.Validation;
import com.wso2telco.dep.oneapivalidation.util.ValidationRule;
/**
*
* @author WSO2telco
*/
public class ValidateNBDeliveryInfoNotification implements IServiceValidate {
private final String[] validationRules = { "DeliveryInfoNotification" };
public void validate(String json) throws CustomException {
String callbackData = null;
String address = null;
String operatorCode = null;
String filterCriteria = null;
String deliveryStatus = null;
try {
JSONObject objJSONObject = new JSONObject(json);
JSONObject objDeliveryInfoNotification = (JSONObject) objJSONObject
.get("deliveryInfoNotification");
if (!objDeliveryInfoNotification.isNull("callbackData")) {
callbackData = nullOrTrimmed(objDeliveryInfoNotification
.getString("callbackData"));
}
JSONObject objDeliveryInfo = (JSONObject) objDeliveryInfoNotification
.get("deliveryInfo");
if (objDeliveryInfo.get("address") != null) {
address = nullOrTrimmed(objDeliveryInfo.getString("address"));
}
if (objDeliveryInfo.get("operatorCode") != null) {
operatorCode = nullOrTrimmed(objDeliveryInfo
.getString("operatorCode"));
}
if (!objDeliveryInfo.isNull("filterCriteria")) {
filterCriteria = nullOrTrimmed(objDeliveryInfo
.getString("filterCriteria"));
}
if (objDeliveryInfo.get("deliveryStatus") != null) {
deliveryStatus = nullOrTrimmed(objDeliveryInfo
.getString("deliveryStatus"));
}
} catch (Exception e) {
throw new CustomException("POL0299", "Unexpected Error",
new String[] { "" });
}
ValidationRule[] rules = null;
rules = new ValidationRule[] {
new ValidationRule(ValidationRule.VALIDATION_TYPE_OPTIONAL,
"callbackData", callbackData),
new ValidationRule(
ValidationRule.VALIDATION_TYPE_MANDATORY_TEL,
"address", address),
new ValidationRule(ValidationRule.VALIDATION_TYPE_MANDATORY,
"operatorCode", operatorCode),
new ValidationRule(ValidationRule.VALIDATION_TYPE_OPTIONAL,
"filterCriteria", filterCriteria),
new ValidationRule(ValidationRule.VALIDATION_TYPE_MANDATORY,
"deliveryStatus", deliveryStatus) };
Validation.checkRequestParams(rules);
}
public void validateUrl(String pathInfo) throws CustomException {
String[] requestParts = null;
if (pathInfo != null) {
if (pathInfo.startsWith("/")) {
pathInfo = pathInfo.substring(1);
}
requestParts = pathInfo.split("/");
}
UrlValidator.validateRequest(requestParts, validationRules);
}
private static String nullOrTrimmed(String s) {
String rv = null;
if (s != null && s.trim().length() > 0) {
rv = s.trim();
}
return rv;
}
public void validate(String[] params) throws CustomException {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| apache-2.0 |
robin13/elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/DataFrameAnalyticsSource.java | 10456 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.core.ml.dataframe;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.core.ml.utils.QueryProvider;
import org.elasticsearch.xpack.core.ml.utils.RuntimeMappingsValidator;
import org.elasticsearch.xpack.core.ml.utils.XContentObjectTransformer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class DataFrameAnalyticsSource implements Writeable, ToXContentObject {
public static final ParseField INDEX = new ParseField("index");
public static final ParseField QUERY = new ParseField("query");
public static final ParseField _SOURCE = new ParseField("_source");
@SuppressWarnings({ "unchecked"})
public static ConstructingObjectParser<DataFrameAnalyticsSource, Void> createParser(boolean ignoreUnknownFields) {
ConstructingObjectParser<DataFrameAnalyticsSource, Void> parser = new ConstructingObjectParser<>("data_frame_analytics_source",
ignoreUnknownFields, a -> new DataFrameAnalyticsSource(
((List<String>) a[0]).toArray(new String[0]),
(QueryProvider) a[1],
(FetchSourceContext) a[2],
(Map<String, Object>) a[3]));
parser.declareStringArray(ConstructingObjectParser.constructorArg(), INDEX);
parser.declareObject(ConstructingObjectParser.optionalConstructorArg(),
(p, c) -> QueryProvider.fromXContent(p, ignoreUnknownFields, Messages.DATA_FRAME_ANALYTICS_BAD_QUERY_FORMAT), QUERY);
parser.declareField(ConstructingObjectParser.optionalConstructorArg(),
(p, c) -> FetchSourceContext.fromXContent(p),
_SOURCE,
ObjectParser.ValueType.OBJECT_ARRAY_BOOLEAN_OR_STRING);
parser.declareObject(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> p.map(),
SearchSourceBuilder.RUNTIME_MAPPINGS_FIELD);
return parser;
}
private final String[] index;
private final QueryProvider queryProvider;
private final FetchSourceContext sourceFiltering;
private final Map<String, Object> runtimeMappings;
public DataFrameAnalyticsSource(String[] index, @Nullable QueryProvider queryProvider, @Nullable FetchSourceContext sourceFiltering,
@Nullable Map<String, Object> runtimeMappings) {
this.index = ExceptionsHelper.requireNonNull(index, INDEX);
if (index.length == 0) {
throw new IllegalArgumentException("source.index must specify at least one index");
}
if (Arrays.stream(index).anyMatch(Strings::isNullOrEmpty)) {
throw new IllegalArgumentException("source.index must contain non-null and non-empty strings");
}
this.queryProvider = queryProvider == null ? QueryProvider.defaultQuery() : queryProvider;
if (sourceFiltering != null && sourceFiltering.fetchSource() == false) {
throw new IllegalArgumentException("source._source cannot be disabled");
}
this.sourceFiltering = sourceFiltering;
this.runtimeMappings = runtimeMappings == null ? Collections.emptyMap() : Collections.unmodifiableMap(runtimeMappings);
RuntimeMappingsValidator.validate(this.runtimeMappings);
}
public DataFrameAnalyticsSource(StreamInput in) throws IOException {
index = in.readStringArray();
queryProvider = QueryProvider.fromStream(in);
sourceFiltering = in.readOptionalWriteable(FetchSourceContext::new);
runtimeMappings = in.readMap();
}
public DataFrameAnalyticsSource(DataFrameAnalyticsSource other) {
this.index = Arrays.copyOf(other.index, other.index.length);
this.queryProvider = new QueryProvider(other.queryProvider);
this.sourceFiltering = other.sourceFiltering == null ? null : new FetchSourceContext(
other.sourceFiltering.fetchSource(), other.sourceFiltering.includes(), other.sourceFiltering.excludes());
this.runtimeMappings = Collections.unmodifiableMap(new HashMap<>(other.runtimeMappings));
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeStringArray(index);
queryProvider.writeTo(out);
out.writeOptionalWriteable(sourceFiltering);
out.writeMap(runtimeMappings);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.array(INDEX.getPreferredName(), index);
builder.field(QUERY.getPreferredName(), queryProvider.getQuery());
if (sourceFiltering != null) {
builder.field(_SOURCE.getPreferredName(), sourceFiltering);
}
if (runtimeMappings.isEmpty() == false) {
builder.field(SearchSourceBuilder.RUNTIME_MAPPINGS_FIELD.getPreferredName(), runtimeMappings);
}
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || getClass() != o.getClass()) return false;
DataFrameAnalyticsSource other = (DataFrameAnalyticsSource) o;
return Arrays.equals(index, other.index)
&& Objects.equals(queryProvider, other.queryProvider)
&& Objects.equals(sourceFiltering, other.sourceFiltering)
&& Objects.equals(runtimeMappings, other.runtimeMappings);
}
@Override
public int hashCode() {
return Objects.hash(Arrays.asList(index), queryProvider, sourceFiltering, runtimeMappings);
}
public String[] getIndex() {
return index;
}
/**
* Get the fully parsed query from the semi-parsed stored {@code Map<String, Object>}
*
* @return Fully parsed query
*/
public QueryBuilder getParsedQuery() {
Exception exception = queryProvider.getParsingException();
if (exception != null) {
if (exception instanceof RuntimeException) {
throw (RuntimeException) exception;
} else {
throw new ElasticsearchException(queryProvider.getParsingException());
}
}
return queryProvider.getParsedQuery();
}
public FetchSourceContext getSourceFiltering() {
return sourceFiltering;
}
Exception getQueryParsingException() {
return queryProvider.getParsingException();
}
// visible for testing
QueryProvider getQueryProvider() {
return queryProvider;
}
/**
* Calls the parser and returns any gathered deprecations
*
* @param namedXContentRegistry XContent registry to transform the lazily parsed query
* @return The deprecations from parsing the query
*/
public List<String> getQueryDeprecations(NamedXContentRegistry namedXContentRegistry) {
List<String> deprecations = new ArrayList<>();
try {
XContentObjectTransformer.queryBuilderTransformer(namedXContentRegistry).fromMap(queryProvider.getQuery(),
deprecations);
} catch (Exception exception) {
// Certain thrown exceptions wrap up the real Illegal argument making it hard to determine cause for the user
if (exception.getCause() instanceof IllegalArgumentException) {
exception = (Exception) exception.getCause();
}
throw ExceptionsHelper.badRequestException(Messages.DATA_FRAME_ANALYTICS_BAD_QUERY_FORMAT, exception);
}
return deprecations;
}
// Visible for testing
Map<String, Object> getQuery() {
return queryProvider.getQuery();
}
public Map<String, Object> getRuntimeMappings() {
return runtimeMappings;
}
public boolean isFieldExcluded(String path) {
if (sourceFiltering == null) {
return false;
}
// First we check in the excludes as they are applied last
for (String exclude : sourceFiltering.excludes()) {
if (pathMatchesSourcePattern(path, exclude)) {
return true;
}
}
// Now we can check the includes
// Empty includes means no further exclusions
if (sourceFiltering.includes().length == 0) {
return false;
}
for (String include : sourceFiltering.includes()) {
if (pathMatchesSourcePattern(path, include)) {
return false;
}
}
return true;
}
private static boolean pathMatchesSourcePattern(String path, String sourcePattern) {
if (sourcePattern.equals(path)) {
return true;
}
if (Regex.isSimpleMatchPattern(sourcePattern)) {
return Regex.simpleMatch(sourcePattern, path);
}
// At this stage sourcePattern is a concrete field name and path is not equal to it.
// We should check if path is a nested field of pattern.
// Let us take "foo" as an example.
// Fields that are "foo.*" should also be matched.
return Regex.simpleMatch(sourcePattern + ".*", path);
}
}
| apache-2.0 |
Starlink/xerces | doc/html/apiDocs-3/classDOMMemoryManager.html | 23041 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Xerces-C++: DOMMemoryManager Class Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.5.6 -->
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li class="current"><a href="classes.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="classes.html"><span>Alphabetical List</span></a></li>
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div>
<div class="contents">
<h1>DOMMemoryManager Class Reference</h1><!-- doxytag: class="DOMMemoryManager" -->The <code><a class="el" href="classDOMMemoryManager.html" title="The DOMMemoryManager interface exposes the memory allocation-related functionalities...">DOMMemoryManager</a></code> interface exposes the memory allocation-related functionalities of a <code><a class="el" href="classDOMDocument.html" title="The DOMDocument interface represents the entire XML document.">DOMDocument</a></code>.
<a href="#_details">More...</a>
<p>
<p>
<a href="classDOMMemoryManager-members.html">List of all members.</a><table border="0" cellpadding="0" cellspacing="0">
<tr><td></td></tr>
<tr><td colspan="2"><br><h2>Public Types</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">enum </td><td class="memItemRight" valign="bottom"><a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1">NodeObjectType</a> { <br>
<a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1d5cfa34c934527ff8f5f8a53459c923c">ATTR_OBJECT</a> = 0,
<a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1b7fd2a25a694520341224ed6ff032d40">ATTR_NS_OBJECT</a> = 1,
<a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b160b25457a0f1e8a4e40469eb30325e96">CDATA_SECTION_OBJECT</a> = 2,
<a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1dd02e894262059c2bfc42396aa5d0f74">COMMENT_OBJECT</a> = 3,
<br>
<a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1c4c27446f78089e0525197cbed77f3dc">DOCUMENT_FRAGMENT_OBJECT</a> = 4,
<a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1b4b79e3ed0f67394cb8f1cbbc525d341">DOCUMENT_TYPE_OBJECT</a> = 5,
<a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b10ccde53ba19e8e540efc8b15232e792c">ELEMENT_OBJECT</a> = 6,
<a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1f9d48f846414d0f23b1f4c094fccc958">ELEMENT_NS_OBJECT</a> = 7,
<br>
<a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1f80e82759d98a1fba66ed00c63871805">ENTITY_OBJECT</a> = 8,
<a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1ed024ba957c0d64c3040b98e2f110fa9">ENTITY_REFERENCE_OBJECT</a> = 9,
<a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1941da709a628b2b292b7b82a09271b7e">NOTATION_OBJECT</a> = 10,
<a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1bfae514728836b3c1b41e7b9d3ce4609">PROCESSING_INSTRUCTION_OBJECT</a> = 11,
<br>
<a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1bb73daebe6be1b19430e0c7c92fe664c">TEXT_OBJECT</a> = 12
<br>
}</td></tr>
<tr><td colspan="2"><br><h2>Public Member Functions</h2></td></tr>
<tr><td colspan="2"><div class="groupHeader">Destructor</div></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">virtual </td><td class="memItemRight" valign="bottom"><a class="el" href="classDOMMemoryManager.html#8e84f1a479924e27311d03e818c1bdf5">~DOMMemoryManager</a> ()</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Destructor. <a href="#8e84f1a479924e27311d03e818c1bdf5"></a><br></td></tr>
<tr><td colspan="2"><div class="groupHeader"></div></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="Xerces__autoconf__config_8msvc_8hpp.html#c0f7e36996cd03eb43bcee10321f77cd">XMLSize_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="classDOMMemoryManager.html#e5d3f6c25b749592885a3e8e343be17d">getMemoryAllocationBlockSize</a> () const =0</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Returns the size of the chunks of memory allocated by the memory manager. <a href="#e5d3f6c25b749592885a3e8e343be17d"></a><br></td></tr>
<tr><td colspan="2"><div class="groupHeader"></div></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="classDOMMemoryManager.html#b8be3b7267aee9f065540f4d2aca8473">setMemoryAllocationBlockSize</a> (<a class="el" href="Xerces__autoconf__config_8msvc_8hpp.html#c0f7e36996cd03eb43bcee10321f77cd">XMLSize_t</a> size)=0</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Set the size of the chunks of memory allocated by the memory manager. <a href="#b8be3b7267aee9f065540f4d2aca8473"></a><br></td></tr>
<tr><td colspan="2"><div class="groupHeader"></div></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">virtual void * </td><td class="memItemRight" valign="bottom"><a class="el" href="classDOMMemoryManager.html#8f2a6eb58cbc23b34578dd86053e0009">allocate</a> (<a class="el" href="Xerces__autoconf__config_8msvc_8hpp.html#c0f7e36996cd03eb43bcee10321f77cd">XMLSize_t</a> amount)=0</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Allocate a memory block of the requested size from the managed pool. <a href="#8f2a6eb58cbc23b34578dd86053e0009"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">virtual void * </td><td class="memItemRight" valign="bottom"><a class="el" href="classDOMMemoryManager.html#0ad243c3259c64f87be03ae9cf0f76c4">allocate</a> (<a class="el" href="Xerces__autoconf__config_8msvc_8hpp.html#c0f7e36996cd03eb43bcee10321f77cd">XMLSize_t</a> amount, <a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1">DOMMemoryManager::NodeObjectType</a> type)=0</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Allocate a memory block of the requested size from the managed pool of DOM objects. <a href="#0ad243c3259c64f87be03ae9cf0f76c4"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="classDOMMemoryManager.html#507e1458fc07f91096ec36fe3e5e809c">release</a> (<a class="el" href="classDOMNode.html">DOMNode</a> *object, <a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1">DOMMemoryManager::NodeObjectType</a> type)=0</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Release a DOM object and place its memory back in the pool. <a href="#507e1458fc07f91096ec36fe3e5e809c"></a><br></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="Xerces__autoconf__config_8msvc_8hpp.html#fae8f92d83170d97f757f704eca7f52a">XMLCh</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="classDOMMemoryManager.html#06d5f3b2247df46e2d62e3418cc703d4">cloneString</a> (const <a class="el" href="Xerces__autoconf__config_8msvc_8hpp.html#fae8f92d83170d97f757f704eca7f52a">XMLCh</a> *src)=0</td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Allocate a memory block from the mnaged pool and copy the provided string. <a href="#06d5f3b2247df46e2d62e3418cc703d4"></a><br></td></tr>
<tr><td colspan="2"><br><h2>Protected Member Functions</h2></td></tr>
<tr><td colspan="2"><div class="groupHeader">Hidden constructors</div></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classDOMMemoryManager.html#cd7d61638fa0f9e301de4a28501e8ec6">DOMMemoryManager</a> ()</td></tr>
</table>
<hr><a name="_details"></a><h2>Detailed Description</h2>
The <code><a class="el" href="classDOMMemoryManager.html" title="The DOMMemoryManager interface exposes the memory allocation-related functionalities...">DOMMemoryManager</a></code> interface exposes the memory allocation-related functionalities of a <code><a class="el" href="classDOMDocument.html" title="The DOMDocument interface represents the entire XML document.">DOMDocument</a></code>. <hr><h2>Member Enumeration Documentation</h2>
<a class="anchor" name="204df2f42dde53d6b6c30c3ca46e27b1"></a><!-- doxytag: member="DOMMemoryManager::NodeObjectType" ref="204df2f42dde53d6b6c30c3ca46e27b1" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">enum <a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1">DOMMemoryManager::NodeObjectType</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
<dl compact><dt><b>Enumerator: </b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"><em><a class="anchor" name="204df2f42dde53d6b6c30c3ca46e27b1d5cfa34c934527ff8f5f8a53459c923c"></a><!-- doxytag: member="ATTR_OBJECT" ref="204df2f42dde53d6b6c30c3ca46e27b1d5cfa34c934527ff8f5f8a53459c923c" args="" -->ATTR_OBJECT</em> </td><td>
</td></tr>
<tr><td valign="top"><em><a class="anchor" name="204df2f42dde53d6b6c30c3ca46e27b1b7fd2a25a694520341224ed6ff032d40"></a><!-- doxytag: member="ATTR_NS_OBJECT" ref="204df2f42dde53d6b6c30c3ca46e27b1b7fd2a25a694520341224ed6ff032d40" args="" -->ATTR_NS_OBJECT</em> </td><td>
</td></tr>
<tr><td valign="top"><em><a class="anchor" name="204df2f42dde53d6b6c30c3ca46e27b160b25457a0f1e8a4e40469eb30325e96"></a><!-- doxytag: member="CDATA_SECTION_OBJECT" ref="204df2f42dde53d6b6c30c3ca46e27b160b25457a0f1e8a4e40469eb30325e96" args="" -->CDATA_SECTION_OBJECT</em> </td><td>
</td></tr>
<tr><td valign="top"><em><a class="anchor" name="204df2f42dde53d6b6c30c3ca46e27b1dd02e894262059c2bfc42396aa5d0f74"></a><!-- doxytag: member="COMMENT_OBJECT" ref="204df2f42dde53d6b6c30c3ca46e27b1dd02e894262059c2bfc42396aa5d0f74" args="" -->COMMENT_OBJECT</em> </td><td>
</td></tr>
<tr><td valign="top"><em><a class="anchor" name="204df2f42dde53d6b6c30c3ca46e27b1c4c27446f78089e0525197cbed77f3dc"></a><!-- doxytag: member="DOCUMENT_FRAGMENT_OBJECT" ref="204df2f42dde53d6b6c30c3ca46e27b1c4c27446f78089e0525197cbed77f3dc" args="" -->DOCUMENT_FRAGMENT_OBJECT</em> </td><td>
</td></tr>
<tr><td valign="top"><em><a class="anchor" name="204df2f42dde53d6b6c30c3ca46e27b1b4b79e3ed0f67394cb8f1cbbc525d341"></a><!-- doxytag: member="DOCUMENT_TYPE_OBJECT" ref="204df2f42dde53d6b6c30c3ca46e27b1b4b79e3ed0f67394cb8f1cbbc525d341" args="" -->DOCUMENT_TYPE_OBJECT</em> </td><td>
</td></tr>
<tr><td valign="top"><em><a class="anchor" name="204df2f42dde53d6b6c30c3ca46e27b10ccde53ba19e8e540efc8b15232e792c"></a><!-- doxytag: member="ELEMENT_OBJECT" ref="204df2f42dde53d6b6c30c3ca46e27b10ccde53ba19e8e540efc8b15232e792c" args="" -->ELEMENT_OBJECT</em> </td><td>
</td></tr>
<tr><td valign="top"><em><a class="anchor" name="204df2f42dde53d6b6c30c3ca46e27b1f9d48f846414d0f23b1f4c094fccc958"></a><!-- doxytag: member="ELEMENT_NS_OBJECT" ref="204df2f42dde53d6b6c30c3ca46e27b1f9d48f846414d0f23b1f4c094fccc958" args="" -->ELEMENT_NS_OBJECT</em> </td><td>
</td></tr>
<tr><td valign="top"><em><a class="anchor" name="204df2f42dde53d6b6c30c3ca46e27b1f80e82759d98a1fba66ed00c63871805"></a><!-- doxytag: member="ENTITY_OBJECT" ref="204df2f42dde53d6b6c30c3ca46e27b1f80e82759d98a1fba66ed00c63871805" args="" -->ENTITY_OBJECT</em> </td><td>
</td></tr>
<tr><td valign="top"><em><a class="anchor" name="204df2f42dde53d6b6c30c3ca46e27b1ed024ba957c0d64c3040b98e2f110fa9"></a><!-- doxytag: member="ENTITY_REFERENCE_OBJECT" ref="204df2f42dde53d6b6c30c3ca46e27b1ed024ba957c0d64c3040b98e2f110fa9" args="" -->ENTITY_REFERENCE_OBJECT</em> </td><td>
</td></tr>
<tr><td valign="top"><em><a class="anchor" name="204df2f42dde53d6b6c30c3ca46e27b1941da709a628b2b292b7b82a09271b7e"></a><!-- doxytag: member="NOTATION_OBJECT" ref="204df2f42dde53d6b6c30c3ca46e27b1941da709a628b2b292b7b82a09271b7e" args="" -->NOTATION_OBJECT</em> </td><td>
</td></tr>
<tr><td valign="top"><em><a class="anchor" name="204df2f42dde53d6b6c30c3ca46e27b1bfae514728836b3c1b41e7b9d3ce4609"></a><!-- doxytag: member="PROCESSING_INSTRUCTION_OBJECT" ref="204df2f42dde53d6b6c30c3ca46e27b1bfae514728836b3c1b41e7b9d3ce4609" args="" -->PROCESSING_INSTRUCTION_OBJECT</em> </td><td>
</td></tr>
<tr><td valign="top"><em><a class="anchor" name="204df2f42dde53d6b6c30c3ca46e27b1bb73daebe6be1b19430e0c7c92fe664c"></a><!-- doxytag: member="TEXT_OBJECT" ref="204df2f42dde53d6b6c30c3ca46e27b1bb73daebe6be1b19430e0c7c92fe664c" args="" -->TEXT_OBJECT</em> </td><td>
</td></tr>
</table>
</dl>
</div>
</div><p>
<hr><h2>Constructor & Destructor Documentation</h2>
<a class="anchor" name="cd7d61638fa0f9e301de4a28501e8ec6"></a><!-- doxytag: member="DOMMemoryManager::DOMMemoryManager" ref="cd7d61638fa0f9e301de4a28501e8ec6" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">DOMMemoryManager::DOMMemoryManager </td>
<td>(</td>
<td class="paramname"> </td>
<td> ) </td>
<td><code> [protected]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
</div>
</div><p>
<a class="anchor" name="8e84f1a479924e27311d03e818c1bdf5"></a><!-- doxytag: member="DOMMemoryManager::~DOMMemoryManager" ref="8e84f1a479924e27311d03e818c1bdf5" args="()" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual DOMMemoryManager::~DOMMemoryManager </td>
<td>(</td>
<td class="paramname"> </td>
<td> ) </td>
<td><code> [virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Destructor.
<p>
</div>
</div><p>
<hr><h2>Member Function Documentation</h2>
<a class="anchor" name="e5d3f6c25b749592885a3e8e343be17d"></a><!-- doxytag: member="DOMMemoryManager::getMemoryAllocationBlockSize" ref="e5d3f6c25b749592885a3e8e343be17d" args="() const =0" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual <a class="el" href="Xerces__autoconf__config_8msvc_8hpp.html#c0f7e36996cd03eb43bcee10321f77cd">XMLSize_t</a> DOMMemoryManager::getMemoryAllocationBlockSize </td>
<td>(</td>
<td class="paramname"> </td>
<td> ) </td>
<td> const<code> [pure virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Returns the size of the chunks of memory allocated by the memory manager.
<p>
<dl class="return" compact><dt><b>Returns:</b></dt><dd>the dimension of the chunks of memory allocated by the memory manager </dd></dl>
</div>
</div><p>
<a class="anchor" name="b8be3b7267aee9f065540f4d2aca8473"></a><!-- doxytag: member="DOMMemoryManager::setMemoryAllocationBlockSize" ref="b8be3b7267aee9f065540f4d2aca8473" args="(XMLSize_t size)=0" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void DOMMemoryManager::setMemoryAllocationBlockSize </td>
<td>(</td>
<td class="paramtype"><a class="el" href="Xerces__autoconf__config_8msvc_8hpp.html#c0f7e36996cd03eb43bcee10321f77cd">XMLSize_t</a> </td>
<td class="paramname"> <em>size</em> </td>
<td> ) </td>
<td><code> [pure virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Set the size of the chunks of memory allocated by the memory manager.
<p>
<dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>size</em> </td><td>the new size of the chunks; it must be greater than 4KB </td></tr>
</table>
</dl>
</div>
</div><p>
<a class="anchor" name="8f2a6eb58cbc23b34578dd86053e0009"></a><!-- doxytag: member="DOMMemoryManager::allocate" ref="8f2a6eb58cbc23b34578dd86053e0009" args="(XMLSize_t amount)=0" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void* DOMMemoryManager::allocate </td>
<td>(</td>
<td class="paramtype"><a class="el" href="Xerces__autoconf__config_8msvc_8hpp.html#c0f7e36996cd03eb43bcee10321f77cd">XMLSize_t</a> </td>
<td class="paramname"> <em>amount</em> </td>
<td> ) </td>
<td><code> [pure virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Allocate a memory block of the requested size from the managed pool.
<p>
<dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>amount</em> </td><td>the size of the new memory block</td></tr>
</table>
</dl>
<dl class="return" compact><dt><b>Returns:</b></dt><dd>the pointer to the newly allocated block </dd></dl>
</div>
</div><p>
<a class="anchor" name="0ad243c3259c64f87be03ae9cf0f76c4"></a><!-- doxytag: member="DOMMemoryManager::allocate" ref="0ad243c3259c64f87be03ae9cf0f76c4" args="(XMLSize_t amount, DOMMemoryManager::NodeObjectType type)=0" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void* DOMMemoryManager::allocate </td>
<td>(</td>
<td class="paramtype"><a class="el" href="Xerces__autoconf__config_8msvc_8hpp.html#c0f7e36996cd03eb43bcee10321f77cd">XMLSize_t</a> </td>
<td class="paramname"> <em>amount</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1">DOMMemoryManager::NodeObjectType</a> </td>
<td class="paramname"> <em>type</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td><code> [pure virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Allocate a memory block of the requested size from the managed pool of DOM objects.
<p>
<dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>amount</em> </td><td>the size of the new memory block </td></tr>
<tr><td valign="top"></td><td valign="top"><em>type</em> </td><td>the type of the DOM object that will be stored in the block</td></tr>
</table>
</dl>
<dl class="return" compact><dt><b>Returns:</b></dt><dd>the pointer to the newly allocated block </dd></dl>
</div>
</div><p>
<a class="anchor" name="507e1458fc07f91096ec36fe3e5e809c"></a><!-- doxytag: member="DOMMemoryManager::release" ref="507e1458fc07f91096ec36fe3e5e809c" args="(DOMNode *object, DOMMemoryManager::NodeObjectType type)=0" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual void DOMMemoryManager::release </td>
<td>(</td>
<td class="paramtype"><a class="el" href="classDOMNode.html">DOMNode</a> * </td>
<td class="paramname"> <em>object</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="classDOMMemoryManager.html#204df2f42dde53d6b6c30c3ca46e27b1">DOMMemoryManager::NodeObjectType</a> </td>
<td class="paramname"> <em>type</em></td><td> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td><td><code> [pure virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Release a DOM object and place its memory back in the pool.
<p>
<dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>object</em> </td><td>the pointer to the DOM node </td></tr>
<tr><td valign="top"></td><td valign="top"><em>type</em> </td><td>the type of the DOM object </td></tr>
</table>
</dl>
</div>
</div><p>
<a class="anchor" name="06d5f3b2247df46e2d62e3418cc703d4"></a><!-- doxytag: member="DOMMemoryManager::cloneString" ref="06d5f3b2247df46e2d62e3418cc703d4" args="(const XMLCh *src)=0" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">virtual <a class="el" href="Xerces__autoconf__config_8msvc_8hpp.html#fae8f92d83170d97f757f704eca7f52a">XMLCh</a>* DOMMemoryManager::cloneString </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="Xerces__autoconf__config_8msvc_8hpp.html#fae8f92d83170d97f757f704eca7f52a">XMLCh</a> * </td>
<td class="paramname"> <em>src</em> </td>
<td> ) </td>
<td><code> [pure virtual]</code></td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
Allocate a memory block from the mnaged pool and copy the provided string.
<p>
<dl compact><dt><b>Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>src</em> </td><td>the string to be copied</td></tr>
</table>
</dl>
<dl class="return" compact><dt><b>Returns:</b></dt><dd>the pointer to the newly allocated block </dd></dl>
</div>
</div><p>
<hr>The documentation for this class was generated from the following file:<ul>
<li><a class="el" href="DOMMemoryManager_8hpp-source.html">DOMMemoryManager.hpp</a></ul>
</div>
<hr size="1"><address style="text-align: right;"><small>Generated on Wed Apr 21 17:55:49 2010 for Xerces-C++ by
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.6 </small></address>
</body>
</html>
| apache-2.0 |
GBGamer/rust | src/test/run-pass/use.rs | 881 | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(stable_features)]
// pretty-expanded FIXME #23616
#![allow(unused_imports)]
#![feature(start, no_core, core)]
#![no_core]
extern crate std;
extern crate std as zed;
use std::str;
use zed::str as x;
use std::io::{self, Error as IoError, Result as IoResult};
use std::error::{self as foo};
mod baz {
pub use std::str as x;
}
#[start]
pub fn start(_: isize, _: *const *const u8) -> isize { 0 }
| apache-2.0 |
MRNAS/NTRT | src/core/tgSimView.cpp | 5374 | /*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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.
*/
/**
* @file tgSimView.cpp
* @brief Contains the definitions of members of class tgSimView
* @author Brian Mirletz, Ryan Adams
* $Id$
*/
// This module
#include "tgSimulation.h"
// This application
#include "tgModelVisitor.h"
#include "tgSimView.h"
// The C++ Standard Library
#include <cassert>
#include <iostream>
#include <stdexcept>
tgSimView::tgSimView(tgWorld& world,
double stepSize,
double renderRate) :
m_world(world),
m_pSimulation(NULL),
m_pModelVisitor(NULL),
m_stepSize(stepSize),
m_renderRate(renderRate),
m_renderTime(0.0),
m_initialized(false)
{
if (m_stepSize < 0.0)
{
throw std::invalid_argument("stepSize is not positive");
}
else if (renderRate < m_stepSize)
{
throw std::invalid_argument("renderRate is less than stepSize");
}
// Postcondition
assert(invariant());
assert(m_pSimulation == NULL);
assert(m_pModelVisitor == NULL);
assert(m_stepSize == stepSize);
assert(m_renderRate == renderRate);
assert(m_renderTime == 0.0);
assert(!m_initialized);
}
tgSimView::~tgSimView()
{
if (m_pSimulation != NULL)
{
// The tgSimView has been passed to a tgSimulation
teardown();
}
delete m_pModelVisitor;
}
void tgSimView::bindToSimulation(tgSimulation& simulation)
{
if (m_pSimulation != NULL)
{
throw
std::invalid_argument("The view already belongs to a simulation.");
}
else
{
m_pSimulation = &simulation;
tgWorld& world = simulation.getWorld();
bindToWorld(world);
}
// Postcondition
assert(invariant());
assert(m_pSimulation == &simulation);
}
void tgSimView::releaseFromSimulation()
{
// The destructor that calls this must not fail, so don't assert or throw
// on a precondition
m_pSimulation = NULL;
// The destructor that calls this must not fail, so don't assert a
// postcondition
}
void tgSimView::bindToWorld(tgWorld& world)
{
}
void tgSimView::setup()
{
assert(m_pSimulation != NULL);
// Just note that this function was called.
// tgSimViewGraphics needs to know for now.
m_initialized = true;
// Postcondition
assert(invariant());
assert(m_initialized);
}
void tgSimView::teardown()
{
// Just note that this function was called.
// tgSimViewGraphics needs to know for now.
m_initialized = false;
// Postcondition
assert(invariant());
assert(!m_initialized);
}
void tgSimView::run()
{
// This would normally run forever, but this is just for testing
run(10);
}
void tgSimView::run(int steps)
{
if (m_pSimulation != NULL)
{
// The tgSimView has been passed to a tgSimulation
std::cout << "SimView::run("<<steps<<")" << std::endl;
// This would normally run forever, but this is just for testing
m_renderTime = 0;
double totalTime = 0.0;
for (int i = 0; i < steps; i++) {
m_pSimulation->step(m_stepSize);
m_renderTime += m_stepSize;
totalTime += m_stepSize;
if (m_renderTime >= m_renderRate) {
render();
//std::cout << totalTime << std::endl;
m_renderTime = 0;
}
}
}
}
void tgSimView::render() const
{
if ((m_pSimulation != NULL) && (m_pModelVisitor != NULL))
{
// The tgSimView has been passed to a tgSimulation
m_pSimulation->onVisit(*m_pModelVisitor);
}
}
void tgSimView::render(const tgModelVisitor& r) const
{
if (m_pSimulation != NULL)
{
// The tgSimView has been passed to a tgSimulation
m_pSimulation->onVisit(r);
}
}
void tgSimView::reset()
{
if (m_pSimulation != NULL)
{
// The tgSimView has been passed to a tgSimulation
m_pSimulation->reset();
}
}
void tgSimView::setRenderRate(double renderRate)
{
m_renderRate = (renderRate > m_stepSize) ? renderRate : m_stepSize;
// Postcondition
assert(invariant());
}
void tgSimView::setStepSize(double stepSize)
{
if (stepSize <= 0.0)
{
throw std::invalid_argument("stepSize is not positive");
}
else
{
m_stepSize = stepSize;
// Assure that the render rate is no less than the new step size
setRenderRate(m_renderRate);
}
// Postcondition
assert(invariant());
assert((stepSize <= 0.0) || (m_stepSize == stepSize));
}
bool tgSimView::invariant() const
{
return
(m_stepSize >= 0.0) &&
(m_renderRate >= m_stepSize) &&
(m_renderTime >= 0.0);
}
| apache-2.0 |
mahim97/zulip | templates/zerver/register.html | 11442 | {% extends "zerver/portico_signup.html" %}
{#
Gather other user information, after having confirmed
their email address.
Form is validated both client-side using jquery-validate (see signup.js) and server-side.
#}
{% block customhead %}
{{ super() }}
{{ render_bundle('zxcvbn') }}
{{ render_bundle('translations') }}
{% endblock %}
{% block portico_content %}
<div class="register-account flex full-page">
<div class="center-block new-style" style="padding: 20px 0px">
<div class="pitch">
{% trans %}
<h1>You're almost there.</h1>
<p>We just need you to do one last thing.</p>
{% endtrans %}
</div>
<form method="post" class="form-horizontal white-box" id="registration" action="{{ url('zerver.views.registration.accounts_register') }}">
{{ csrf_input }}
<section class="user-registration">
<div class="input-box no-validation">
<input type='hidden' name='key' value='{{ key }}' />
<input type='hidden' name='timezone' id='timezone'/>
<input id="id_email" type='text' disabled="true" placeholder="{{ email }}" required />
<label for="id_email" class="inline-block label-title">{{ _('Email') }}</label>
</div>
<div class="input-box">
{% if lock_name %}
<p class="fakecontrol">{{ full_name }}</p>
{% else %}
<input id="id_full_name" class="required" type="text" name="full_name"
value="{% if full_name %}{{ full_name }}{% elif form.full_name.value() %}{{ form.full_name.value() }}{% endif %}"
maxlength={{ MAX_NAME_LENGTH }} placeholder="{% trans %}Full name or 名前{% endtrans %}" required />
<label for="id_full_name" class="inline-block label-title">{{ _('Full name') }}</label>
{% if form.full_name.errors %}
{% for error in form.full_name.errors %}
<p class="help-inline text-error">{{ error }}</p>
{% endfor %}
{% endif %}
{% endif %}
</div>
{% if password_required %}
<div class="input-box">
<input id="id_password" class="required" type="password" name="password"
value="{% if form.password.value() %}{{ form.password.value() }}{% endif %}"
maxlength={{ MAX_PASSWORD_LENGTH }}
data-min-length="{{password_min_length}}"
data-min-guesses="{{password_min_guesses}}" required />
<label for="id_password" class="inline-block">{{ _('Password') }}</label>
{% if full_name %}
<span class="help-inline">
{{ _('This is used for mobile applications and other tools that require a password.') }}
</span>
{% endif %}
{% if form.password.errors %}
{% for error in form.password.errors %}
<p class="help-inline text-error">{{ error }}</p>
{% endfor %}
{% endif %}
<div class="progress" id="pw_strength" title="{{ _('Password strength') }}">
<div class="bar bar-danger" style="width: 10%;"></div>
</div>
</div>
{% endif %}
</section>
{% if default_stream_groups %}
<div class="input-group m-10 inline-block">
<label for="default_stream_group">{{ _('What parts of the organization are you interested in?') }}</label>
{% for default_stream_group in default_stream_groups %}
<div class="input-group radio">
<input class="inline-block" type="checkbox" name="default_stream_group" value="{{ default_stream_group.name }}"
{% if "default_stream_group" in form.data and default_stream_group.name in form.data.getlist('default_stream_group') %} checked {% endif %} />
<label for="id_radio_{{ default_stream_group.name }}" class="inline-block">{{ default_stream_group.name }}</label>
</div>
{% endfor %}
</div>
{% endif %}
<section class="org-registration">
{% if creating_new_team %}
<div class="input-box">
<div class="inline-block relative">
<input id="id_team_name" class="required" type="text"
placeholder="Acme or Aκμή"
value="{% if form.realm_name.value() %}{{ form.realm_name.value() }}{% endif %}"
name="realm_name" maxlength={{ MAX_REALM_NAME_LENGTH }} required />
</div>
<label for="id_team_name" class="inline-block label-title">{{ _('Organization name') }}</label>
{% if form.realm_name.errors %}
{% for error in form.realm_name.errors %}
<p class="help-inline text-error">{{ error }}</p>
{% endfor %}
{% endif %}
<div class="help-box margin-top">
{{ _('Shorter is better than longer.') }}
</div>
</div>
<div class="input-box">
<label class="static org-url">
{{ _('Organization URL') }}
</label>
{% if root_domain_available %}
<label class="checkbox static" for="realm_in_root_domain">
<input type="checkbox" name="realm_in_root_domain" id="realm_in_root_domain"
{% if not form.realm_subdomain.value() and not form.realm_subdomain.errors %}checked="checked"{% endif %}/>
<span></span>
{% trans %}Use {{ external_host }}{% endtrans %}
</label>
{% endif %}
<div class="inline-block" id="subdomain_section" {% if root_domain_available and
not form.realm_subdomain.errors and not form.realm_subdomain.value() %}style="display: none;"{% endif %}>
<div class="or">or</div>
<div class="inline-block relative">
<input id="id_team_subdomain"
class="{% if root_domain_landing_page %}required{% endif %} subdomain" type="text"
placeholder="acme"
value="{% if form.realm_subdomain.value() %}{{ form.realm_subdomain.value() }}{% endif %}"
name="realm_subdomain" maxlength={{ MAX_REALM_SUBDOMAIN_LENGTH }}
{% if root_domain_landing_page %}required{% endif %} />
<p class="realm_subdomain_label">.{{ external_host }}</p>
<p id="id_team_subdomain_error_client" class="error help-inline text-error"></p>
</div>
{% if form.realm_subdomain.errors %}
{% for error in form.realm_subdomain.errors %}
<p class="error help-inline text-error team_subdomain_error_server">{{ error }}</p>
{% endfor %}
{% endif %}
</div>
<div class="help-box margin-top">
{{ _("The address you'll use to sign in to your organization.") }}
</div>
</div>
{% endif %}
</section>
<div class="input-group margin terms-of-service">
{% if terms_of_service %}
<div class="input-group">
{#
This is somewhat subtle.
Checkboxes have a name and value, and when the checkbox is ticked, the form posts
with name=value. If the checkbox is unticked, the field just isn't present at all.
This is distinct from 'checked', which determines whether the checkbox appears
at all. (So, it's not symmetric to the code above.)
#}
<label for="id_terms" class="inline-block checkbox">
<input id="id_terms" class="required" type="checkbox" name="terms"
{% if form.terms.value() %}checked="checked"{% endif %} />
<span></span>
{% trans %}I agree to the <a href="{{ root_domain_uri }}/terms" target="_blank">Terms of Service</a>.{% endtrans %}
</label>
{% if form.terms.errors %}
{% for error in form.terms.errors %}
<p class="help-inline text-error">{{ error }}</p>
{% endfor %}
{% endif %}
</div>
{% endif %}
<div class="register-button-box">
<button class="register-button" type="submit">{{ _('Register') }}</button>
<input type="hidden" name="next" value="{{ next }}" />
</div>
</div>
</form>
</div>
</div>
<script type="text/javascript">
if ($('#id_email').length === 1) {
if (!$('#id_email').attr('disabled')) {
common.autofocus('#id_email');
} else {
common.autofocus('#id_full_name');
}
} else {
common.autofocus('#id_full_name');
}
// reset error message displays
$('#id_team_subdomain_error_client').css('display', 'none');
if ($('.team_subdomain_error_server').text() === '') {
$('.team_subdomain_error_server').css('display', 'none');
}
$("#timezone").val(moment.tz.guess());
$('#id_team_subdomain').on('input', function (e) {
// preserve selection range, to be set after setting the text
var start = e.target.selectionStart,
end = e.target.selectionEnd;
// toggle displaying server-side / client-side errors; messages
// from only one of the two should be showing at any time.
$('.team_subdomain_error_server').text('').css('display', 'none');
var autocorrected = e.target.value
.toLowerCase()
.replace(/[_|\s]/g, '-');
e.target.value = autocorrected;
if (e.target.value.charAt(0) === '-' ||
e.target.value.charAt(e.target.value.length - 1) === '-') {
$('#id_team_subdomain_error_client')
.text(i18n.t("Cannot start or end with a '-'"))
.css('display', 'block');
} else if (/[^0-9a-z\-]/.test(e.target.value)) {
$('#id_team_subdomain_error_client')
.text(i18n.t("Can only use letters a-z, numbers 0-9, and '-'s."))
.css('display', 'block');
} else {
$('#id_team_subdomain_error_client').text('').css('display', 'none');
}
e.target.setSelectionRange(start, end);
});
</script>
{% endblock %}
| apache-2.0 |
Azure/azure-linux-extensions | Diagnostic/mdsd/mdscommands/BodyOnlyXmlParser.cc | 1350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <cctype>
#include "BodyOnlyXmlParser.hh"
#include "MdsException.hh"
using namespace mdsd::details;
void
BodyOnlyXmlParser::ParseFile(std::string xmlFilePath)
{
m_xmlFilePath = std::move(xmlFilePath);
std::ifstream infile{m_xmlFilePath};
if (!infile) {
std::ostringstream strm;
strm << "Failed to open file '" << m_xmlFilePath << "'.";
throw MDSEXCEPTION(strm.str());
}
std::string line;
while(std::getline(infile, line)) {
ParseChunk(line);
}
if (!infile.eof()) {
std::ostringstream strm;
strm << "Failed to parse file '" << m_xmlFilePath << "': ";
if (infile.bad()) {
strm << "Corrupted stream.";
}
else if (infile.fail()) {
strm << "IO operation failed.";
}
else {
strm << "std::getline() returned 0 for unknown reason.";
}
throw MDSEXCEPTION(strm.str());
}
}
void
BodyOnlyXmlParser::OnCharacters(const std::string& chars)
{
bool isEmptyOrWhiteSpace = std::all_of(chars.cbegin(), chars.cend(), ::isspace);
if (!isEmptyOrWhiteSpace) {
m_body.append(chars);
}
}
| apache-2.0 |
callkalpa/product-mss | samples/stockquote/deployable-jar/src/main/java/org/wso2/msf4j/stockquote/example/exception/EntityNotFoundMapper.java | 1196 | /*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.wso2.msf4j.stockquote.example.exception;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
/**
* EntityNotFoundMapper.
*/
public class EntityNotFoundMapper implements ExceptionMapper<EntityNotFoundException> {
@Override
public Response toResponse(EntityNotFoundException ex) {
return Response.status(404).
entity(ex.getMessage() + " [from EntityNotFoundMapper]").
type("text/plain").
build();
}
}
| apache-2.0 |
neeraj9/otp | erts/emulator/beam/erl_thr_progress.c | 41485 | /*
* %CopyrightBegin%
*
* Copyright Ericsson AB 2011-2016. All Rights Reserved.
*
* 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.
*
* %CopyrightEnd%
*/
/*
* Description: Thread progress information. Used by lock free algorithms
* to determine when all involved threads are guaranteed to
* have passed a specific point of execution.
*
* Usage instructions below.
*
* Author: Rickard Green
*/
/*
* ------ Usage instructions -----------------------------------------------
*
* This module keeps track of the progress of a set of managed threads. Only
* threads that behave well can be allowed to be managed. A managed thread
* should update its thread progress frequently. Currently only scheduler
* threads, the system-message-dispatcher threads, and the aux-thread are
* managed threads. We typically do not want any async threads as managed
* threads since they cannot guarantee a frequent update of thread progress,
* since they execute user implemented driver code that is assumed to be
* time consuming.
*
* erts_thr_progress_current() returns the global current thread progress
* value of managed threads. I.e., the latest progress value that all
* managed threads have reached. Thread progress values are opaque.
*
* erts_thr_progress_has_reached(VAL) returns a value != 0 if current
* global thread progress has reached or passed VAL.
*
* erts_thr_progress_later() returns a thread progress value in the future
* which no managed thread have yet reached.
*
* All threads issue a full memory barrier when reaching a new thread
* progress value. They only reach new thread progress values in specific
* controlled states when calling erts_thr_progress_update(). Schedulers
* call erts_thr_progress_update() in between execution of processes,
* when going to sleep and when waking up.
*
* Sleeping managed threads are considered to have reached next thread
* progress value immediately. They are not woken and do therefore not
* issue any memory barriers when reaching a new thread progress value.
* A sleeping thread do however immediately issue a memory barrier upon
* wakeup.
*
* Both managed and registered unmanaged threads may request wakeup when
* the global thread progress reach a certain value using
* erts_thr_progress_wakeup().
*
* Note that thread progress values are opaque, and that you are only
* allowed to use thread progress values retrieved from this API!
*
* -------------------------------------------------------------------------
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stddef.h> /* offsetof() */
#include "erl_thr_progress.h"
#include "global.h"
#ifdef ERTS_SMP
#define ERTS_THR_PRGR_DBG_CHK_WAKEUP_REQUEST_VALUE 0
#ifdef DEBUG
#undef ERTS_THR_PRGR_DBG_CHK_WAKEUP_REQUEST_VALUE
#define ERTS_THR_PRGR_DBG_CHK_WAKEUP_REQUEST_VALUE 1
#endif
#define ERTS_THR_PRGR_PRINT_LEADER 0
#define ERTS_THR_PRGR_PRINT_VAL 0
#define ERTS_THR_PRGR_PRINT_BLOCKERS 0
#define ERTS_THR_PRGR_FTL_ERR_BLCK_POLL_INTERVAL 100
#define ERTS_THR_PRGR_LFLG_BLOCK ((erts_aint32_t) (1U << 31))
#define ERTS_THR_PRGR_LFLG_NO_LEADER ((erts_aint32_t) (1U << 30))
#define ERTS_THR_PRGR_LFLG_WAITING_UM ((erts_aint32_t) (1U << 29))
#define ERTS_THR_PRGR_LFLG_ACTIVE_MASK (~(ERTS_THR_PRGR_LFLG_NO_LEADER \
| ERTS_THR_PRGR_LFLG_BLOCK \
| ERTS_THR_PRGR_LFLG_WAITING_UM))
#define ERTS_THR_PRGR_LFLGS_ACTIVE(LFLGS) \
((LFLGS) & ERTS_THR_PRGR_LFLG_ACTIVE_MASK)
/*
* We use a 64-bit value for thread progress. By this wrapping of
* the thread progress will more or less never occur.
*
* On 32-bit systems we therefore need a double word atomic.
*/
#undef read_acqb
#define read_acqb erts_thr_prgr_read_acqb__
#undef read_nob
#define read_nob erts_thr_prgr_read_nob__
static ERTS_INLINE void
set_mb(ERTS_THR_PRGR_ATOMIC *atmc, ErtsThrPrgrVal val)
{
erts_atomic64_set_mb(atmc, (erts_aint64_t) val);
}
static ERTS_INLINE void
set_nob(ERTS_THR_PRGR_ATOMIC *atmc, ErtsThrPrgrVal val)
{
erts_atomic64_set_nob(atmc, (erts_aint64_t) val);
}
static ERTS_INLINE void
init_nob(ERTS_THR_PRGR_ATOMIC *atmc, ErtsThrPrgrVal val)
{
erts_atomic64_init_nob(atmc, (erts_aint64_t) val);
}
/* #define ERTS_THR_PROGRESS_STATE_DEBUG */
#ifdef ERTS_THR_PROGRESS_STATE_DEBUG
#ifdef __GNUC__
#warning "Thread progress state debug is on"
#endif
#define ERTS_THR_PROGRESS_STATE_DEBUG_LEADER ((erts_aint32_t) (1U << 0))
#define ERTS_THR_PROGRESS_STATE_DEBUG_ACTIVE ((erts_aint32_t) (1U << 1))
#define ERTS_THR_PROGRESS_STATE_DEBUG_INIT(ID) \
erts_atomic32_init_nob(&intrnl->thr[(ID)].data.state_debug, \
ERTS_THR_PROGRESS_STATE_DEBUG_ACTIVE)
#define ERTS_THR_PROGRESS_STATE_DEBUG_SET_ACTIVE(ID, ON) \
do { \
erts_aint32_t state_debug__; \
state_debug__ = erts_atomic32_read_nob(&intrnl->thr[(ID)].data.state_debug); \
if ((ON)) \
state_debug__ |= ERTS_THR_PROGRESS_STATE_DEBUG_ACTIVE; \
else \
state_debug__ &= ~ERTS_THR_PROGRESS_STATE_DEBUG_ACTIVE; \
erts_atomic32_set_nob(&intrnl->thr[(ID)].data.state_debug, state_debug__); \
} while (0)
#define ERTS_THR_PROGRESS_STATE_DEBUG_SET_LEADER(ID, ON) \
do { \
erts_aint32_t state_debug__; \
state_debug__ = erts_atomic32_read_nob(&intrnl->thr[(ID)].data.state_debug); \
if ((ON)) \
state_debug__ |= ERTS_THR_PROGRESS_STATE_DEBUG_LEADER; \
else \
state_debug__ &= ~ERTS_THR_PROGRESS_STATE_DEBUG_LEADER; \
erts_atomic32_set_nob(&intrnl->thr[(ID)].data.state_debug, state_debug__); \
} while (0)
#else
#define ERTS_THR_PROGRESS_STATE_DEBUG_INIT(ID)
#define ERTS_THR_PROGRESS_STATE_DEBUG_SET_ACTIVE(ID, ON)
#define ERTS_THR_PROGRESS_STATE_DEBUG_SET_LEADER(ID, ON)
#endif /* ERTS_THR_PROGRESS_STATE_DEBUG */
#define ERTS_THR_PRGR_BLCKR_INVALID ((erts_aint32_t) (~0U))
#define ERTS_THR_PRGR_BLCKR_UNMANAGED ((erts_aint32_t) (1U << 31))
#define ERTS_THR_PRGR_BC_FLG_NOT_BLOCKING ((erts_aint32_t) (1U << 31))
#define ERTS_THR_PRGR_BM_BITS 32
#define ERTS_THR_PRGR_BM_SHIFT 5
#define ERTS_THR_PRGR_BM_MASK 0x1f
#define ERTS_THR_PRGR_WAKEUP_DATA_MASK (ERTS_THR_PRGR_WAKEUP_DATA_SIZE - 1)
#define ERTS_THR_PRGR_WAKEUP_IX(V) \
((int) ((V) & ERTS_THR_PRGR_WAKEUP_DATA_MASK))
typedef struct {
erts_atomic32_t len;
int id[1];
} ErtsThrPrgrManagedWakeupData;
typedef struct {
erts_atomic32_t len;
int high_sz;
int low_sz;
erts_atomic32_t *high;
erts_atomic32_t *low;
} ErtsThrPrgrUnmanagedWakeupData;
typedef struct {
erts_atomic32_t lflgs;
erts_atomic32_t block_count;
erts_atomic_t blocker_event;
erts_atomic32_t pref_wakeup_used;
erts_atomic32_t managed_count;
erts_atomic32_t managed_id;
erts_atomic32_t unmanaged_id;
int chk_next_ix;
struct {
int waiting;
erts_atomic32_t current;
} umrefc_ix;
} ErtsThrPrgrMiscData;
typedef struct {
ERTS_THR_PRGR_ATOMIC current;
#ifdef ERTS_THR_PROGRESS_STATE_DEBUG
erts_atomic32_t state_debug;
#endif
} ErtsThrPrgrElement;
typedef union {
ErtsThrPrgrElement data;
char align__[ERTS_ALC_CACHE_LINE_ALIGN_SIZE(sizeof(ErtsThrPrgrElement))];
} ErtsThrPrgrArray;
typedef union {
erts_atomic_t refc;
char align__[ERTS_ALC_CACHE_LINE_ALIGN_SIZE(sizeof(erts_atomic_t))];
} ErtsThrPrgrUnmanagedRefc;
typedef struct {
union {
ErtsThrPrgrMiscData data;
char align__[ERTS_ALC_CACHE_LINE_ALIGN_SIZE(
sizeof(ErtsThrPrgrMiscData))];
} misc;
ErtsThrPrgrUnmanagedRefc umrefc[2];
ErtsThrPrgrArray *thr;
struct {
int no;
ErtsThrPrgrCallbacks *callbacks;
ErtsThrPrgrManagedWakeupData *data[ERTS_THR_PRGR_WAKEUP_DATA_SIZE];
} managed;
struct {
int no;
ErtsThrPrgrCallbacks *callbacks;
ErtsThrPrgrUnmanagedWakeupData *data[ERTS_THR_PRGR_WAKEUP_DATA_SIZE];
} unmanaged;
} ErtsThrPrgrInternalData;
static ErtsThrPrgrInternalData *intrnl;
ErtsThrPrgr erts_thr_prgr__;
erts_tsd_key_t erts_thr_prgr_data_key__;
static void handle_wakeup_requests(ErtsThrPrgrVal current);
static int got_sched_wakeups(void);
static erts_aint32_t block_thread(ErtsThrPrgrData *tpd);
static ERTS_INLINE void
wakeup_managed(int id)
{
ErtsThrPrgrCallbacks *cbp = &intrnl->managed.callbacks[id];
ASSERT(0 <= id && id < intrnl->managed.no);
cbp->wakeup(cbp->arg);
}
static ERTS_INLINE void
wakeup_unmanaged(int id)
{
ErtsThrPrgrCallbacks *cbp = &intrnl->unmanaged.callbacks[id];
ASSERT(0 <= id && id < intrnl->unmanaged.no);
cbp->wakeup(cbp->arg);
}
static ERTS_INLINE ErtsThrPrgrData *
perhaps_thr_prgr_data(ErtsSchedulerData *esdp)
{
if (esdp)
return &esdp->thr_progress_data;
else
return erts_tsd_get(erts_thr_prgr_data_key__);
}
static ERTS_INLINE ErtsThrPrgrData *
thr_prgr_data(ErtsSchedulerData *esdp)
{
ErtsThrPrgrData *tpd = perhaps_thr_prgr_data(esdp);
ASSERT(tpd);
return tpd;
}
static void
init_tmp_thr_prgr_data(ErtsThrPrgrData *tpd)
{
tpd->id = -1;
tpd->is_managed = 0;
tpd->is_blocking = 0;
tpd->is_temporary = 1;
#ifdef ERTS_ENABLE_LOCK_CHECK
tpd->is_delaying = 0;
#endif
erts_tsd_set(erts_thr_prgr_data_key__, (void *) tpd);
}
static ERTS_INLINE ErtsThrPrgrData *
tmp_thr_prgr_data(ErtsSchedulerData *esdp)
{
ErtsThrPrgrData *tpd = perhaps_thr_prgr_data(esdp);
if (!tpd) {
/*
* We only allocate the part up to the wakeup_request field
* which is the first field only used by registered threads
*/
tpd = erts_alloc(ERTS_ALC_T_T_THR_PRGR_DATA,
offsetof(ErtsThrPrgrData, wakeup_request));
init_tmp_thr_prgr_data(tpd);
}
return tpd;
}
static ERTS_INLINE void
return_tmp_thr_prgr_data(ErtsThrPrgrData *tpd)
{
if (tpd->is_temporary) {
erts_tsd_set(erts_thr_prgr_data_key__, NULL);
erts_free(ERTS_ALC_T_T_THR_PRGR_DATA, tpd);
}
}
static ERTS_INLINE int
block_count_dec(void)
{
erts_aint32_t block_count;
block_count = erts_atomic32_dec_read_mb(&intrnl->misc.data.block_count);
if (block_count == 0) {
erts_tse_t *event;
event = ((erts_tse_t*)
erts_atomic_read_nob(&intrnl->misc.data.blocker_event));
if (event)
erts_tse_set(event);
return 1;
}
return (block_count & ERTS_THR_PRGR_BC_FLG_NOT_BLOCKING) == 0;
}
static ERTS_INLINE int
block_count_inc(void)
{
erts_aint32_t block_count;
block_count = erts_atomic32_inc_read_mb(&intrnl->misc.data.block_count);
return (block_count & ERTS_THR_PRGR_BC_FLG_NOT_BLOCKING) == 0;
}
void
erts_thr_progress_pre_init(void)
{
intrnl = NULL;
erts_tsd_key_create(&erts_thr_prgr_data_key__,
"erts_thr_prgr_data_key");
init_nob(&erts_thr_prgr__.current, ERTS_THR_PRGR_VAL_FIRST);
}
void
erts_thr_progress_init(int no_schedulers, int managed, int unmanaged)
{
int i, j, um_low, um_high;
char *ptr;
size_t cb_sz, intrnl_sz, thr_arr_sz, m_wakeup_size, um_wakeup_size,
tot_size;
intrnl_sz = sizeof(ErtsThrPrgrInternalData);
intrnl_sz = ERTS_ALC_CACHE_LINE_ALIGN_SIZE(intrnl_sz);
cb_sz = sizeof(ErtsThrPrgrCallbacks)*(managed+unmanaged);
cb_sz = ERTS_ALC_CACHE_LINE_ALIGN_SIZE(cb_sz);
thr_arr_sz = sizeof(ErtsThrPrgrArray)*managed;
ASSERT(thr_arr_sz == ERTS_ALC_CACHE_LINE_ALIGN_SIZE(thr_arr_sz));
m_wakeup_size = sizeof(ErtsThrPrgrManagedWakeupData);
m_wakeup_size += (managed - 1)*sizeof(int);
m_wakeup_size = ERTS_ALC_CACHE_LINE_ALIGN_SIZE(m_wakeup_size);
um_low = (unmanaged - 1)/ERTS_THR_PRGR_BM_BITS + 1;
um_high = (um_low - 1)/ERTS_THR_PRGR_BM_BITS + 1;
um_wakeup_size = sizeof(ErtsThrPrgrUnmanagedWakeupData);
um_wakeup_size += (um_high + um_low)*sizeof(erts_atomic32_t);
um_wakeup_size = ERTS_ALC_CACHE_LINE_ALIGN_SIZE(um_wakeup_size);
tot_size = intrnl_sz;
tot_size += cb_sz;
tot_size += thr_arr_sz;
tot_size += m_wakeup_size*ERTS_THR_PRGR_WAKEUP_DATA_SIZE;
tot_size += um_wakeup_size*ERTS_THR_PRGR_WAKEUP_DATA_SIZE;
ptr = erts_alloc_permanent_cache_aligned(ERTS_ALC_T_THR_PRGR_IDATA,
tot_size);
intrnl = (ErtsThrPrgrInternalData *) ptr;
ptr += intrnl_sz;
erts_atomic32_init_nob(&intrnl->misc.data.lflgs,
ERTS_THR_PRGR_LFLG_NO_LEADER);
erts_atomic32_init_nob(&intrnl->misc.data.block_count,
(ERTS_THR_PRGR_BC_FLG_NOT_BLOCKING
| (erts_aint32_t) managed));
erts_atomic_init_nob(&intrnl->misc.data.blocker_event, ERTS_AINT_NULL);
erts_atomic32_init_nob(&intrnl->misc.data.pref_wakeup_used, 0);
erts_atomic32_init_nob(&intrnl->misc.data.managed_count, 0);
erts_atomic32_init_nob(&intrnl->misc.data.managed_id, no_schedulers);
erts_atomic32_init_nob(&intrnl->misc.data.unmanaged_id, -1);
intrnl->misc.data.chk_next_ix = 0;
intrnl->misc.data.umrefc_ix.waiting = -1;
erts_atomic32_init_nob(&intrnl->misc.data.umrefc_ix.current, 0);
erts_atomic_init_nob(&intrnl->umrefc[0].refc, (erts_aint_t) 0);
erts_atomic_init_nob(&intrnl->umrefc[1].refc, (erts_aint_t) 0);
intrnl->thr = (ErtsThrPrgrArray *) ptr;
ptr += thr_arr_sz;
for (i = 0; i < managed; i++)
init_nob(&intrnl->thr[i].data.current, 0);
intrnl->managed.callbacks = (ErtsThrPrgrCallbacks *) ptr;
intrnl->unmanaged.callbacks = &intrnl->managed.callbacks[managed];
ptr += cb_sz;
intrnl->managed.no = managed;
for (i = 0; i < managed; i++) {
intrnl->managed.callbacks[i].arg = NULL;
intrnl->managed.callbacks[i].wakeup = NULL;
}
intrnl->unmanaged.no = unmanaged;
for (i = 0; i < unmanaged; i++) {
intrnl->unmanaged.callbacks[i].arg = NULL;
intrnl->unmanaged.callbacks[i].wakeup = NULL;
}
for (i = 0; i < ERTS_THR_PRGR_WAKEUP_DATA_SIZE; i++) {
intrnl->managed.data[i] = (ErtsThrPrgrManagedWakeupData *) ptr;
erts_atomic32_init_nob(&intrnl->managed.data[i]->len, 0);
ptr += m_wakeup_size;
}
for (i = 0; i < ERTS_THR_PRGR_WAKEUP_DATA_SIZE; i++) {
erts_atomic32_t *bm;
intrnl->unmanaged.data[i] = (ErtsThrPrgrUnmanagedWakeupData *) ptr;
erts_atomic32_init_nob(&intrnl->unmanaged.data[i]->len, 0);
bm = (erts_atomic32_t *) (ptr + sizeof(ErtsThrPrgrUnmanagedWakeupData));
intrnl->unmanaged.data[i]->high = bm;
intrnl->unmanaged.data[i]->high_sz = um_high;
for (j = 0; j < um_high; j++)
erts_atomic32_init_nob(&intrnl->unmanaged.data[i]->high[j], 0);
intrnl->unmanaged.data[i]->low
= &intrnl->unmanaged.data[i]->high[um_high];
intrnl->unmanaged.data[i]->low_sz = um_low;
for (j = 0; j < um_low; j++)
erts_atomic32_init_nob(&intrnl->unmanaged.data[i]->low[j], 0);
ptr += um_wakeup_size;
}
ERTS_THR_MEMORY_BARRIER;
}
static void
init_wakeup_request_array(ErtsThrPrgrVal *w)
{
int i;
ErtsThrPrgrVal current;
current = read_acqb(&erts_thr_prgr__.current);
for (i = 0; i < ERTS_THR_PRGR_WAKEUP_DATA_SIZE; i++) {
w[i] = current - ((ErtsThrPrgrVal) (ERTS_THR_PRGR_WAKEUP_DATA_SIZE + i));
if (w[i] > current)
w[i]--;
}
}
void
erts_thr_progress_register_unmanaged_thread(ErtsThrPrgrCallbacks *callbacks)
{
ErtsThrPrgrData *tpd = perhaps_thr_prgr_data(NULL);
int is_blocking = 0;
if (tpd) {
if (!tpd->is_temporary)
erts_exit(ERTS_ABORT_EXIT,
"%s:%d:%s(): Double register of thread\n",
__FILE__, __LINE__, __func__);
is_blocking = tpd->is_blocking;
return_tmp_thr_prgr_data(tpd);
}
/*
* We only allocate the part up to the leader field
* which is the first field only used by managed threads
*/
tpd = erts_alloc(ERTS_ALC_T_THR_PRGR_DATA,
offsetof(ErtsThrPrgrData, leader));
tpd->id = (int) erts_atomic32_inc_read_nob(&intrnl->misc.data.unmanaged_id);
tpd->is_managed = 0;
tpd->is_blocking = is_blocking;
tpd->is_temporary = 0;
#ifdef ERTS_ENABLE_LOCK_CHECK
tpd->is_delaying = 0;
#endif
ASSERT(tpd->id >= 0);
if (tpd->id >= intrnl->unmanaged.no)
erts_exit(ERTS_ABORT_EXIT,
"%s:%d:%s(): Too many unmanaged registered threads\n",
__FILE__, __LINE__, __func__);
init_wakeup_request_array(&tpd->wakeup_request[0]);
erts_tsd_set(erts_thr_prgr_data_key__, (void *) tpd);
ASSERT(callbacks->wakeup);
intrnl->unmanaged.callbacks[tpd->id] = *callbacks;
}
void
erts_thr_progress_register_managed_thread(ErtsSchedulerData *esdp,
ErtsThrPrgrCallbacks *callbacks,
int pref_wakeup)
{
ErtsThrPrgrData *tpd = perhaps_thr_prgr_data(NULL);
int is_blocking = 0, managed;
if (tpd) {
if (!tpd->is_temporary)
erts_exit(ERTS_ABORT_EXIT,
"%s:%d:%s(): Double register of thread\n",
__FILE__, __LINE__, __func__);
is_blocking = tpd->is_blocking;
return_tmp_thr_prgr_data(tpd);
}
if (esdp)
tpd = &esdp->thr_progress_data;
else
tpd = erts_alloc(ERTS_ALC_T_THR_PRGR_DATA, sizeof(ErtsThrPrgrData));
if (pref_wakeup
&& !erts_atomic32_xchg_nob(&intrnl->misc.data.pref_wakeup_used, 1))
tpd->id = 0;
else if (esdp)
tpd->id = (int) esdp->no;
else
tpd->id = erts_atomic32_inc_read_nob(&intrnl->misc.data.managed_id);
ASSERT(tpd->id >= 0);
if (tpd->id >= intrnl->managed.no)
erts_exit(ERTS_ABORT_EXIT,
"%s:%d:%s(): Too many managed registered threads\n",
__FILE__, __LINE__, __func__);
tpd->is_managed = 1;
tpd->is_blocking = is_blocking;
tpd->is_temporary = 0;
#ifdef ERTS_ENABLE_LOCK_CHECK
tpd->is_delaying = 1;
#endif
init_wakeup_request_array(&tpd->wakeup_request[0]);
ERTS_THR_PROGRESS_STATE_DEBUG_INIT(tpd->id);
tpd->leader = 0;
tpd->active = 1;
tpd->confirmed = 0;
tpd->leader_state.current = ERTS_THR_PRGR_VAL_WAITING;
erts_tsd_set(erts_thr_prgr_data_key__, (void *) tpd);
erts_atomic32_inc_nob(&intrnl->misc.data.lflgs);
ASSERT(callbacks->wakeup);
ASSERT(callbacks->prepare_wait);
ASSERT(callbacks->wait);
ASSERT(callbacks->finalize_wait);
intrnl->managed.callbacks[tpd->id] = *callbacks;
callbacks->prepare_wait(callbacks->arg);
managed = erts_atomic32_inc_read_relb(&intrnl->misc.data.managed_count);
if (managed != intrnl->managed.no) {
/* Wait until all managed threads have registered... */
do {
callbacks->wait(callbacks->arg);
callbacks->prepare_wait(callbacks->arg);
managed = erts_atomic32_read_acqb(&intrnl->misc.data.managed_count);
} while (managed != intrnl->managed.no);
}
else {
int id;
/* All managed threads have registered; lets go... */
for (id = 0; id < managed; id++)
if (id != tpd->id)
wakeup_managed(id);
}
callbacks->finalize_wait(callbacks->arg);
}
static ERTS_INLINE int
leader_update(ErtsThrPrgrData *tpd)
{
#ifdef ERTS_ENABLE_LOCK_CHECK
erts_lc_check_exact(NULL, 0);
#endif
if (!tpd->leader) {
/* Probably need to block... */
block_thread(tpd);
}
else {
ErtsThrPrgrVal current;
int ix, chk_next_ix, umrefc_ix, my_ix, no_managed, waiting_unmanaged;
erts_aint32_t lflgs;
ErtsThrPrgrVal next;
erts_aint_t refc;
my_ix = tpd->id;
if (tpd->leader_state.current == ERTS_THR_PRGR_VAL_WAITING) {
/* Took over as leader from another thread */
tpd->leader_state.current = read_nob(&erts_thr_prgr__.current);
tpd->leader_state.next = tpd->leader_state.current;
tpd->leader_state.next++;
if (tpd->leader_state.next == ERTS_THR_PRGR_VAL_WAITING)
tpd->leader_state.next = 0;
tpd->leader_state.chk_next_ix = intrnl->misc.data.chk_next_ix;
tpd->leader_state.umrefc_ix.waiting = intrnl->misc.data.umrefc_ix.waiting;
tpd->leader_state.umrefc_ix.current =
(int) erts_atomic32_read_nob(&intrnl->misc.data.umrefc_ix.current);
if (tpd->confirmed == tpd->leader_state.current) {
ErtsThrPrgrVal val = tpd->leader_state.current + 1;
if (val == ERTS_THR_PRGR_VAL_WAITING)
val = 0;
tpd->confirmed = val;
set_mb(&intrnl->thr[my_ix].data.current, val);
}
}
next = tpd->leader_state.next;
waiting_unmanaged = 0;
umrefc_ix = -1; /* Shut up annoying warning */
chk_next_ix = tpd->leader_state.chk_next_ix;
no_managed = intrnl->managed.no;
ASSERT(0 <= chk_next_ix && chk_next_ix <= no_managed);
/* Check manged threads */
if (chk_next_ix < no_managed) {
for (ix = chk_next_ix; ix < no_managed; ix++) {
ErtsThrPrgrVal tmp;
if (ix == my_ix)
continue;
tmp = read_nob(&intrnl->thr[ix].data.current);
if (tmp != next && tmp != ERTS_THR_PRGR_VAL_WAITING) {
tpd->leader_state.chk_next_ix = ix;
ASSERT(erts_thr_progress_has_passed__(next, tmp));
goto done;
}
}
}
/* Check unmanged threads */
waiting_unmanaged = tpd->leader_state.umrefc_ix.waiting != -1;
umrefc_ix = (waiting_unmanaged
? tpd->leader_state.umrefc_ix.waiting
: tpd->leader_state.umrefc_ix.current);
refc = erts_atomic_read_nob(&intrnl->umrefc[umrefc_ix].refc);
ASSERT(refc >= 0);
if (refc != 0) {
int new_umrefc_ix;
if (waiting_unmanaged)
goto done;
new_umrefc_ix = (umrefc_ix + 1) & 0x1;
tpd->leader_state.umrefc_ix.waiting = umrefc_ix;
tpd->leader_state.chk_next_ix = no_managed;
erts_atomic32_set_nob(&intrnl->misc.data.umrefc_ix.current,
(erts_aint32_t) new_umrefc_ix);
ETHR_MEMBAR(ETHR_StoreLoad);
refc = erts_atomic_read_nob(&intrnl->umrefc[umrefc_ix].refc);
ASSERT(refc >= 0);
waiting_unmanaged = 1;
if (refc != 0)
goto done;
}
/* Make progress */
current = next;
next++;
if (next == ERTS_THR_PRGR_VAL_WAITING)
next = 0;
set_nob(&intrnl->thr[my_ix].data.current, next);
set_mb(&erts_thr_prgr__.current, current);
tpd->confirmed = next;
tpd->leader_state.next = next;
tpd->leader_state.current = current;
#if ERTS_THR_PRGR_PRINT_VAL
if (current % 1000 == 0)
erts_fprintf(stderr, "%b64u\n", current);
#endif
handle_wakeup_requests(current);
if (waiting_unmanaged) {
waiting_unmanaged = 0;
tpd->leader_state.umrefc_ix.waiting = -1;
erts_atomic32_read_band_nob(&intrnl->misc.data.lflgs,
~ERTS_THR_PRGR_LFLG_WAITING_UM);
}
tpd->leader_state.chk_next_ix = 0;
done:
if (tpd->active) {
lflgs = erts_atomic32_read_nob(&intrnl->misc.data.lflgs);
if (lflgs & ERTS_THR_PRGR_LFLG_BLOCK)
(void) block_thread(tpd);
}
else {
int force_wakeup_check = 0;
erts_aint32_t set_flags = ERTS_THR_PRGR_LFLG_NO_LEADER;
tpd->leader = 0;
tpd->leader_state.current = ERTS_THR_PRGR_VAL_WAITING;
#if ERTS_THR_PRGR_PRINT_LEADER
erts_fprintf(stderr, "L <- %d\n", tpd->id);
#endif
ERTS_THR_PROGRESS_STATE_DEBUG_SET_LEADER(tpd->id, 0);
intrnl->misc.data.umrefc_ix.waiting
= tpd->leader_state.umrefc_ix.waiting;
if (waiting_unmanaged)
set_flags |= ERTS_THR_PRGR_LFLG_WAITING_UM;
lflgs = erts_atomic32_read_bor_relb(&intrnl->misc.data.lflgs,
set_flags);
lflgs |= set_flags;
if (lflgs & ERTS_THR_PRGR_LFLG_BLOCK)
lflgs = block_thread(tpd);
if (waiting_unmanaged) {
/* Need to check umrefc again */
ETHR_MEMBAR(ETHR_StoreLoad);
refc = erts_atomic_read_nob(&intrnl->umrefc[umrefc_ix].refc);
if (refc == 0) {
/* Need to force wakeup check */
force_wakeup_check = 1;
}
}
if ((force_wakeup_check
|| ((lflgs & (ERTS_THR_PRGR_LFLG_NO_LEADER
| ERTS_THR_PRGR_LFLG_WAITING_UM
| ERTS_THR_PRGR_LFLG_ACTIVE_MASK))
== ERTS_THR_PRGR_LFLG_NO_LEADER))
&& got_sched_wakeups()) {
/* Someone need to make progress */
wakeup_managed(0);
}
}
}
return tpd->leader;
}
static int
update(ErtsThrPrgrData *tpd)
{
int res;
ErtsThrPrgrVal val;
if (tpd->leader)
res = 1;
else {
erts_aint32_t lflgs;
res = 0;
val = read_acqb(&erts_thr_prgr__.current);
if (tpd->confirmed == val) {
val++;
if (val == ERTS_THR_PRGR_VAL_WAITING)
val = 0;
tpd->confirmed = val;
set_mb(&intrnl->thr[tpd->id].data.current, val);
}
lflgs = erts_atomic32_read_nob(&intrnl->misc.data.lflgs);
if (lflgs & ERTS_THR_PRGR_LFLG_BLOCK)
res = 1; /* Need to block in leader_update() */
if ((lflgs & ERTS_THR_PRGR_LFLG_NO_LEADER)
&& (tpd->active || ERTS_THR_PRGR_LFLGS_ACTIVE(lflgs) == 0)) {
/* Try to take over leadership... */
erts_aint32_t olflgs;
olflgs = erts_atomic32_read_band_acqb(
&intrnl->misc.data.lflgs,
~ERTS_THR_PRGR_LFLG_NO_LEADER);
if (olflgs & ERTS_THR_PRGR_LFLG_NO_LEADER) {
tpd->leader = 1;
#if ERTS_THR_PRGR_PRINT_LEADER
erts_fprintf(stderr, "L -> %d\n", tpd->id);
#endif
ERTS_THR_PROGRESS_STATE_DEBUG_SET_LEADER(tpd->id, 1);
}
}
res |= tpd->leader;
}
return res;
}
int
erts_thr_progress_update(ErtsSchedulerData *esdp)
{
return update(thr_prgr_data(esdp));
}
int
erts_thr_progress_leader_update(ErtsSchedulerData *esdp)
{
return leader_update(thr_prgr_data(esdp));
}
void
erts_thr_progress_prepare_wait(ErtsSchedulerData *esdp)
{
erts_aint32_t lflgs;
ErtsThrPrgrData *tpd = thr_prgr_data(esdp);
#ifdef ERTS_ENABLE_LOCK_CHECK
erts_lc_check_exact(NULL, 0);
#endif
block_count_dec();
tpd->confirmed = ERTS_THR_PRGR_VAL_WAITING;
set_mb(&intrnl->thr[tpd->id].data.current, ERTS_THR_PRGR_VAL_WAITING);
lflgs = erts_atomic32_read_nob(&intrnl->misc.data.lflgs);
if ((lflgs & (ERTS_THR_PRGR_LFLG_NO_LEADER
| ERTS_THR_PRGR_LFLG_WAITING_UM
| ERTS_THR_PRGR_LFLG_ACTIVE_MASK))
== ERTS_THR_PRGR_LFLG_NO_LEADER
&& got_sched_wakeups()) {
/* Someone need to make progress */
wakeup_managed(0);
}
}
void
erts_thr_progress_finalize_wait(ErtsSchedulerData *esdp)
{
ErtsThrPrgrData *tpd = thr_prgr_data(esdp);
ErtsThrPrgrVal current, val;
#ifdef ERTS_ENABLE_LOCK_CHECK
erts_lc_check_exact(NULL, 0);
#endif
/*
* We aren't allowed to continue until our thread
* progress is past global current.
*/
val = current = read_acqb(&erts_thr_prgr__.current);
while (1) {
val++;
if (val == ERTS_THR_PRGR_VAL_WAITING)
val = 0;
tpd->confirmed = val;
set_mb(&intrnl->thr[tpd->id].data.current, val);
val = read_acqb(&erts_thr_prgr__.current);
if (current == val)
break;
current = val;
}
if (block_count_inc())
block_thread(tpd);
if (update(tpd))
leader_update(tpd);
}
void
erts_thr_progress_active(ErtsSchedulerData *esdp, int on)
{
ErtsThrPrgrData *tpd = thr_prgr_data(esdp);
#ifdef ERTS_ENABLE_LOCK_CHECK
erts_lc_check_exact(NULL, 0);
#endif
ERTS_THR_PROGRESS_STATE_DEBUG_SET_ACTIVE(tpd->id, on);
if (on) {
ASSERT(!tpd->active);
tpd->active = 1;
erts_atomic32_inc_nob(&intrnl->misc.data.lflgs);
}
else {
ASSERT(tpd->active);
tpd->active = 0;
erts_atomic32_dec_nob(&intrnl->misc.data.lflgs);
if (update(tpd))
leader_update(tpd);
}
#ifdef DEBUG
{
erts_aint32_t n = erts_atomic32_read_nob(&intrnl->misc.data.lflgs);
n &= ERTS_THR_PRGR_LFLG_ACTIVE_MASK;
ASSERT(tpd->active <= n && n <= intrnl->managed.no);
}
#endif
}
static ERTS_INLINE void
unmanaged_continue(ErtsThrPrgrDelayHandle handle)
{
int umrefc_ix = (int) handle;
erts_aint_t refc;
ASSERT(umrefc_ix == 0 || umrefc_ix == 1);
refc = erts_atomic_dec_read_relb(&intrnl->umrefc[umrefc_ix].refc);
ASSERT(refc >= 0);
if (refc == 0) {
erts_aint_t lflgs;
ERTS_THR_READ_MEMORY_BARRIER;
lflgs = erts_atomic32_read_nob(&intrnl->misc.data.lflgs);
if ((lflgs & (ERTS_THR_PRGR_LFLG_NO_LEADER
| ERTS_THR_PRGR_LFLG_WAITING_UM
| ERTS_THR_PRGR_LFLG_ACTIVE_MASK))
== (ERTS_THR_PRGR_LFLG_NO_LEADER|ERTS_THR_PRGR_LFLG_WAITING_UM)
&& got_sched_wakeups()) {
/* Others waiting for us... */
wakeup_managed(0);
}
}
}
void
erts_thr_progress_unmanaged_continue__(ErtsThrPrgrDelayHandle handle)
{
#ifdef ERTS_ENABLE_LOCK_CHECK
ErtsThrPrgrData *tpd = perhaps_thr_prgr_data(NULL);
ERTS_LC_ASSERT(tpd && tpd->is_delaying);
tpd->is_delaying = 0;
return_tmp_thr_prgr_data(tpd);
#endif
ASSERT(!erts_thr_progress_is_managed_thread());
unmanaged_continue(handle);
}
ErtsThrPrgrDelayHandle
erts_thr_progress_unmanaged_delay__(void)
{
int umrefc_ix;
ASSERT(!erts_thr_progress_is_managed_thread());
umrefc_ix = (int) erts_atomic32_read_acqb(&intrnl->misc.data.umrefc_ix.current);
while (1) {
int tmp_ix;
erts_atomic_inc_acqb(&intrnl->umrefc[umrefc_ix].refc);
tmp_ix = (int) erts_atomic32_read_acqb(&intrnl->misc.data.umrefc_ix.current);
if (tmp_ix == umrefc_ix)
break;
unmanaged_continue(umrefc_ix);
umrefc_ix = tmp_ix;
}
#ifdef ERTS_ENABLE_LOCK_CHECK
{
ErtsThrPrgrData *tpd = tmp_thr_prgr_data(NULL);
tpd->is_delaying = 1;
}
#endif
return (ErtsThrPrgrDelayHandle) umrefc_ix;
}
static ERTS_INLINE int
has_reached_wakeup(ErtsThrPrgrVal wakeup)
{
/*
* Exactly the same as erts_thr_progress_has_reached(), but
* also verify valid wakeup requests in debug mode.
*/
ErtsThrPrgrVal current;
current = read_acqb(&erts_thr_prgr__.current);
#if ERTS_THR_PRGR_DBG_CHK_WAKEUP_REQUEST_VALUE
{
ErtsThrPrgrVal limit;
/*
* erts_thr_progress_later() returns values which are
* equal to 'current + 2', or 'current + 3'. That is, users
* should never get a hold of values larger than that.
*
* That is, valid values are values less than 'current + 4'.
*
* Values larger than this won't work with the wakeup
* algorithm.
*/
limit = current + 4;
if (limit == ERTS_THR_PRGR_VAL_WAITING)
limit = 0;
else if (limit < current) /* Wrapped */
limit += 1;
if (!erts_thr_progress_has_passed__(limit, wakeup))
erts_exit(ERTS_ABORT_EXIT,
"Invalid wakeup request value found:"
" current=%b64u, wakeup=%b64u, limit=%b64u",
current, wakeup, limit);
}
#endif
if (current == wakeup)
return 1;
return erts_thr_progress_has_passed__(current, wakeup);
}
static void
request_wakeup_managed(ErtsThrPrgrData *tpd, ErtsThrPrgrVal value)
{
ErtsThrPrgrManagedWakeupData *mwd;
int ix, wix;
/*
* Only managed threads that aren't in waiting state
* are allowed to call this function.
*/
ASSERT(tpd->is_managed);
ASSERT(tpd->confirmed != ERTS_THR_PRGR_VAL_WAITING);
if (has_reached_wakeup(value)) {
wakeup_managed(tpd->id);
return;
}
wix = ERTS_THR_PRGR_WAKEUP_IX(value);
if (tpd->wakeup_request[wix] == value)
return; /* Already got a request registered */
ASSERT(erts_thr_progress_has_passed__(value,
tpd->wakeup_request[wix]));
if (tpd->confirmed == value) {
/*
* We have already confirmed this value. We need to request
* wakeup for a value later than our latest confirmed value in
* order to prevent progress from reaching the requested value
* while we are writing the request.
*
* It is ok to move the wakeup request forward since the only
* guarantee we make (and can make) is that the thread will be
* woken some time *after* the requested value has been reached.
*/
value++;
if (value == ERTS_THR_PRGR_VAL_WAITING)
value = 0;
wix = ERTS_THR_PRGR_WAKEUP_IX(value);
if (tpd->wakeup_request[wix] == value)
return; /* Already got a request registered */
ASSERT(erts_thr_progress_has_passed__(value,
tpd->wakeup_request[wix]));
}
tpd->wakeup_request[wix] = value;
mwd = intrnl->managed.data[wix];
ix = erts_atomic32_inc_read_nob(&mwd->len) - 1;
#if ERTS_THR_PRGR_DBG_CHK_WAKEUP_REQUEST_VALUE
if (ix >= intrnl->managed.no)
erts_exit(ERTS_ABORT_EXIT, "Internal error: Too many wakeup requests\n");
#endif
mwd->id[ix] = tpd->id;
ASSERT(!erts_thr_progress_has_reached(value));
/*
* This thread is guarranteed to issue a full memory barrier:
* - after the request has been written, but
* - before the global thread progress reach the (possibly
* increased) requested wakeup value.
*/
}
static void
request_wakeup_unmanaged(ErtsThrPrgrData *tpd, ErtsThrPrgrVal value)
{
int wix, ix, id, bit;
ErtsThrPrgrUnmanagedWakeupData *umwd;
ASSERT(!tpd->is_managed);
/*
* Thread progress *can* reach and pass our requested value while
* we are writing the request.
*/
if (has_reached_wakeup(value)) {
wakeup_unmanaged(tpd->id);
return;
}
wix = ERTS_THR_PRGR_WAKEUP_IX(value);
if (tpd->wakeup_request[wix] == value)
return; /* Already got a request registered */
ASSERT(erts_thr_progress_has_passed__(value,
tpd->wakeup_request[wix]));
umwd = intrnl->unmanaged.data[wix];
id = tpd->id;
bit = id & ERTS_THR_PRGR_BM_MASK;
ix = id >> ERTS_THR_PRGR_BM_SHIFT;
ASSERT(0 <= ix && ix < umwd->low_sz);
erts_atomic32_read_bor_nob(&umwd->low[ix], 1 << bit);
bit = ix & ERTS_THR_PRGR_BM_MASK;
ix >>= ERTS_THR_PRGR_BM_SHIFT;
ASSERT(0 <= ix && ix < umwd->high_sz);
erts_atomic32_read_bor_nob(&umwd->high[ix], 1 << bit);
erts_atomic32_inc_mb(&umwd->len);
if (erts_thr_progress_has_reached(value))
wakeup_unmanaged(tpd->id);
else
tpd->wakeup_request[wix] = value;
}
void
erts_thr_progress_wakeup(ErtsSchedulerData *esdp,
ErtsThrPrgrVal value)
{
ErtsThrPrgrData *tpd = thr_prgr_data(esdp);
ASSERT(!tpd->is_temporary);
if (tpd->is_managed)
request_wakeup_managed(tpd, value);
else
request_wakeup_unmanaged(tpd, value);
}
static void
wakeup_unmanaged_threads(ErtsThrPrgrUnmanagedWakeupData *umwd)
{
int hix;
for (hix = 0; hix < umwd->high_sz; hix++) {
erts_aint32_t hmask = erts_atomic32_read_nob(&umwd->high[hix]);
if (hmask) {
int hbase = hix << ERTS_THR_PRGR_BM_SHIFT;
int hbit;
for (hbit = 0; hbit < ERTS_THR_PRGR_BM_BITS; hbit++) {
if (hmask & (1U << hbit)) {
erts_aint_t lmask;
int lix = hbase + hbit;
ASSERT(0 <= lix && lix < umwd->low_sz);
lmask = erts_atomic32_read_nob(&umwd->low[lix]);
if (lmask) {
int lbase = lix << ERTS_THR_PRGR_BM_SHIFT;
int lbit;
for (lbit = 0; lbit < ERTS_THR_PRGR_BM_BITS; lbit++) {
if (lmask & (1U << lbit)) {
int id = lbase + lbit;
wakeup_unmanaged(id);
}
}
erts_atomic32_set_nob(&umwd->low[lix], 0);
}
}
}
erts_atomic32_set_nob(&umwd->high[hix], 0);
}
}
}
static void
handle_wakeup_requests(ErtsThrPrgrVal current)
{
ErtsThrPrgrManagedWakeupData *mwd;
ErtsThrPrgrUnmanagedWakeupData *umwd;
int wix, len, i;
wix = ERTS_THR_PRGR_WAKEUP_IX(current);
mwd = intrnl->managed.data[wix];
len = erts_atomic32_read_nob(&mwd->len);
ASSERT(len >= 0);
if (len) {
for (i = 0; i < len; i++)
wakeup_managed(mwd->id[i]);
erts_atomic32_set_nob(&mwd->len, 0);
}
umwd = intrnl->unmanaged.data[wix];
len = erts_atomic32_read_nob(&umwd->len);
ASSERT(len >= 0);
if (len) {
wakeup_unmanaged_threads(umwd);
erts_atomic32_set_nob(&umwd->len, 0);
}
}
static int
got_sched_wakeups(void)
{
int wix;
ERTS_THR_MEMORY_BARRIER;
for (wix = 0; wix < ERTS_THR_PRGR_WAKEUP_DATA_SIZE; wix++) {
ErtsThrPrgrManagedWakeupData **mwd = intrnl->managed.data;
if (erts_atomic32_read_nob(&mwd[wix]->len))
return 1;
}
for (wix = 0; wix < ERTS_THR_PRGR_WAKEUP_DATA_SIZE; wix++) {
ErtsThrPrgrUnmanagedWakeupData **umwd = intrnl->unmanaged.data;
if (erts_atomic32_read_nob(&umwd[wix]->len))
return 1;
}
return 0;
}
static erts_aint32_t
block_thread(ErtsThrPrgrData *tpd)
{
erts_aint32_t lflgs;
ErtsThrPrgrCallbacks *cbp = &intrnl->managed.callbacks[tpd->id];
do {
block_count_dec();
while (1) {
cbp->prepare_wait(cbp->arg);
lflgs = erts_atomic32_read_nob(&intrnl->misc.data.lflgs);
if (lflgs & ERTS_THR_PRGR_LFLG_BLOCK)
cbp->wait(cbp->arg);
else
break;
}
} while (block_count_inc());
cbp->finalize_wait(cbp->arg);
return lflgs;
}
static erts_aint32_t
thr_progress_block(ErtsThrPrgrData *tpd, int wait)
{
erts_tse_t *event = NULL; /* Remove erroneous warning... sigh... */
erts_aint32_t lflgs, bc;
if (tpd->is_blocking++)
return (erts_aint32_t) 0;
while (1) {
lflgs = erts_atomic32_read_bor_nob(&intrnl->misc.data.lflgs,
ERTS_THR_PRGR_LFLG_BLOCK);
if (lflgs & ERTS_THR_PRGR_LFLG_BLOCK)
block_thread(tpd);
else
break;
}
#if ERTS_THR_PRGR_PRINT_BLOCKERS
erts_fprintf(stderr, "block(%d)\n", tpd->id);
#endif
ASSERT(ERTS_AINT_NULL
== erts_atomic_read_nob(&intrnl->misc.data.blocker_event));
if (wait) {
event = erts_tse_fetch();
erts_tse_reset(event);
erts_atomic_set_nob(&intrnl->misc.data.blocker_event,
(erts_aint_t) event);
}
if (tpd->is_managed)
erts_atomic32_dec_nob(&intrnl->misc.data.block_count);
bc = erts_atomic32_read_band_mb(&intrnl->misc.data.block_count,
~ERTS_THR_PRGR_BC_FLG_NOT_BLOCKING);
bc &= ~ERTS_THR_PRGR_BC_FLG_NOT_BLOCKING;
if (wait) {
while (bc != 0) {
erts_tse_wait(event);
erts_tse_reset(event);
bc = erts_atomic32_read_acqb(&intrnl->misc.data.block_count);
}
}
return bc;
}
void
erts_thr_progress_block(void)
{
thr_progress_block(tmp_thr_prgr_data(NULL), 1);
}
int
erts_thr_progress_fatal_error_block(ErtsThrPrgrData *tmp_tpd_bufp)
{
ErtsThrPrgrData *tpd = perhaps_thr_prgr_data(NULL);
if (!tpd) {
/*
* We stack allocate since failure to allocate memory may
* have caused the problem in the first place. This is ok
* since we never complete an unblock after a fatal error
* block.
*/
tpd = tmp_tpd_bufp;
init_tmp_thr_prgr_data(tpd);
}
/* Returns number of threads that have not yes been blocked */
return thr_progress_block(tpd, 0);
}
void
erts_thr_progress_fatal_error_wait(SWord timeout) {
erts_aint32_t bc;
SWord time_left = timeout;
ErtsMonotonicTime timeout_time;
ErtsSchedulerData *esdp = erts_get_scheduler_data();
/*
* Counting poll intervals may give us a too long timeout
* if cpu is busy. We use timeout time to try to prevent
* this. In case we havn't got time correction this may
* however fail too...
*/
timeout_time = erts_get_monotonic_time(esdp);
timeout_time += ERTS_MSEC_TO_MONOTONIC((ErtsMonotonicTime) timeout);
while (1) {
if (erts_milli_sleep(ERTS_THR_PRGR_FTL_ERR_BLCK_POLL_INTERVAL) == 0)
time_left -= ERTS_THR_PRGR_FTL_ERR_BLCK_POLL_INTERVAL;
bc = erts_atomic32_read_acqb(&intrnl->misc.data.block_count);
if (bc == 0)
break; /* Succefully blocked all managed threads */
if (time_left <= 0)
break; /* Timeout */
if (timeout_time <= erts_get_monotonic_time(esdp))
break; /* Timeout */
}
}
void
erts_thr_progress_unblock(void)
{
erts_tse_t *event;
int id, break_id, sz, wakeup;
ErtsThrPrgrData *tpd = thr_prgr_data(NULL);
ASSERT(tpd->is_blocking);
if (--tpd->is_blocking)
return;
sz = intrnl->managed.no;
wakeup = 1;
if (!tpd->is_managed)
id = break_id = tpd->id < 0 ? 0 : tpd->id % sz;
else {
break_id = tpd->id;
id = break_id + 1;
if (id >= sz)
id = 0;
if (id == break_id)
wakeup = 0;
erts_atomic32_inc_nob(&intrnl->misc.data.block_count);
}
event = ((erts_tse_t *)
erts_atomic_read_nob(&intrnl->misc.data.blocker_event));
ASSERT(event);
erts_atomic_set_nob(&intrnl->misc.data.blocker_event, ERTS_AINT_NULL);
erts_atomic32_read_bor_relb(&intrnl->misc.data.block_count,
ERTS_THR_PRGR_BC_FLG_NOT_BLOCKING);
#if ERTS_THR_PRGR_PRINT_BLOCKERS
erts_fprintf(stderr, "unblock(%d)\n", tpd->id);
#endif
erts_atomic32_read_band_mb(&intrnl->misc.data.lflgs,
~ERTS_THR_PRGR_LFLG_BLOCK);
if (wakeup) {
do {
ErtsThrPrgrVal tmp;
tmp = read_nob(&intrnl->thr[id].data.current);
if (tmp != ERTS_THR_PRGR_VAL_WAITING)
wakeup_managed(id);
if (++id >= sz)
id = 0;
} while (id != break_id);
}
return_tmp_thr_prgr_data(tpd);
erts_tse_return(event);
}
int
erts_thr_progress_is_blocking(void)
{
ErtsThrPrgrData *tpd = perhaps_thr_prgr_data(NULL);
return tpd && tpd->is_blocking;
}
void erts_thr_progress_dbg_print_state(void)
{
int id;
int sz = intrnl->managed.no;
erts_fprintf(stderr, "--- thread progress ---\n");
erts_fprintf(stderr,"current=%b64u\n", erts_thr_progress_current());
for (id = 0; id < sz; id++) {
ErtsThrPrgrVal current = read_nob(&intrnl->thr[id].data.current);
#ifdef ERTS_THR_PROGRESS_STATE_DEBUG
erts_aint32_t state_debug;
char *active, *leader;
state_debug = erts_atomic32_read_nob(&intrnl->thr[id].data.state_debug);
active = (state_debug & ERTS_THR_PROGRESS_STATE_DEBUG_ACTIVE
? "true"
: "false");
leader = (state_debug & ERTS_THR_PROGRESS_STATE_DEBUG_LEADER
? "true"
: "false");
#endif
if (current == ERTS_THR_PRGR_VAL_WAITING)
erts_fprintf(stderr,
" id=%d, current=WAITING"
#ifdef ERTS_THR_PROGRESS_STATE_DEBUG
", active=%s, leader=%s"
#endif
"\n", id
#ifdef ERTS_THR_PROGRESS_STATE_DEBUG
, active, leader
#endif
);
else
erts_fprintf(stderr,
" id=%d, current=%b64u"
#ifdef ERTS_THR_PROGRESS_STATE_DEBUG
", active=%s, leader=%s"
#endif
"\n", id, current
#ifdef ERTS_THR_PROGRESS_STATE_DEBUG
, active, leader
#endif
);
}
erts_fprintf(stderr, "-----------------------\n");
}
#endif
| apache-2.0 |
sneivandt/elasticsearch | client/rest/src/test/java/org/elasticsearch/client/RestClientBuilderIntegTests.java | 4718 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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.elasticsearch.client;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
import org.elasticsearch.client.http.HttpHost;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;
import org.elasticsearch.mocksocket.MockHttpServer;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.security.KeyStore;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Integration test to validate the builder builds a client with the correct configuration
*/
//animal-sniffer doesn't like our usage of com.sun.net.httpserver.* classes
@IgnoreJRERequirement
public class RestClientBuilderIntegTests extends RestClientTestCase {
private static HttpsServer httpsServer;
@BeforeClass
public static void startHttpServer() throws Exception {
httpsServer = MockHttpServer.createHttps(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
httpsServer.setHttpsConfigurator(new HttpsConfigurator(getSslContext()));
httpsServer.createContext("/", new ResponseHandler());
httpsServer.start();
}
//animal-sniffer doesn't like our usage of com.sun.net.httpserver.* classes
@IgnoreJRERequirement
private static class ResponseHandler implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
httpExchange.sendResponseHeaders(200, -1);
httpExchange.close();
}
}
@AfterClass
public static void stopHttpServers() throws IOException {
httpsServer.stop(0);
httpsServer = null;
}
public void testBuilderUsesDefaultSSLContext() throws Exception {
final SSLContext defaultSSLContext = SSLContext.getDefault();
try {
try (RestClient client = buildRestClient()) {
try {
client.performRequest("GET", "/");
fail("connection should have been rejected due to SSL handshake");
} catch (Exception e) {
assertThat(e.getMessage(), containsString("General SSLEngine problem"));
}
}
SSLContext.setDefault(getSslContext());
try (RestClient client = buildRestClient()) {
Response response = client.performRequest("GET", "/");
assertEquals(200, response.getStatusLine().getStatusCode());
}
} finally {
SSLContext.setDefault(defaultSSLContext);
}
}
private RestClient buildRestClient() {
InetSocketAddress address = httpsServer.getAddress();
return RestClient.builder(new HttpHost(address.getHostString(), address.getPort(), "https")).build();
}
private static SSLContext getSslContext() throws Exception {
SSLContext sslContext = SSLContext.getInstance("TLS");
try (InputStream in = RestClientBuilderIntegTests.class.getResourceAsStream("/testks.jks")) {
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(in, "password".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keyStore, "password".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(keyStore);
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
}
return sslContext;
}
}
| apache-2.0 |
RusticiSoftware/TinCanPHP | tests/DocumentTest.php | 1020 | <?php
/*
Copyright 2016 Rustici Software
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.
*/
namespace TinCanTest;
use TinCan\Document;
class StubDocument extends Document {}
class DocumentTest extends \PHPUnit_Framework_TestCase {
public function testExceptionOnInvalidDateTime() {
$this->setExpectedException(
"InvalidArgumentException",
'type of arg1 must be string or DateTime'
);
$obj = new StubDocument();
$obj->setTimestamp(1);
}
}
| apache-2.0 |
siconos/siconos | externals/numeric_bindings/libs/numeric/bindings/doc/html/boost_numeric_bindings/reference/lapack/driver_routines/hbgv.html | 11701 | <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>hbgv</title>
<link rel="stylesheet" href="../../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../../index.html" title="Chapter 1. Boost.Numeric_Bindings">
<link rel="up" href="../driver_routines.html" title="Driver Routines">
<link rel="prev" href="ggsvd.html" title="ggsvd">
<link rel="next" href="hbgvd.html" title="hbgvd">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="ggsvd.html"><img src="../../../../images/prev.png" alt="Prev"></a><a accesskey="u" href="../driver_routines.html"><img src="../../../../images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../images/home.png" alt="Home"></a><a accesskey="n" href="hbgvd.html"><img src="../../../../images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="boost_numeric_bindings.reference.lapack.driver_routines.hbgv"></a><a class="link" href="hbgv.html" title="hbgv">hbgv</a>
</h5></div></div></div>
<a name="boost_numeric_bindings.reference.lapack.driver_routines.hbgv.prototype"></a><h6>
<a name="id816800"></a>
<a class="link" href="hbgv.html#boost_numeric_bindings.reference.lapack.driver_routines.hbgv.prototype">Prototype</a>
</h6>
<p>
There is one prototype of <code class="computeroutput"><span class="identifier">hbgv</span></code>
available, please see below.
</p>
<pre class="programlisting"><span class="identifier">hbgv</span><span class="special">(</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="identifier">jobz</span><span class="special">,</span> <span class="identifier">MatrixAB</span><span class="special">&</span> <span class="identifier">ab</span><span class="special">,</span> <span class="identifier">MatrixBB</span><span class="special">&</span> <span class="identifier">bb</span><span class="special">,</span> <span class="identifier">VectorW</span><span class="special">&</span> <span class="identifier">w</span><span class="special">,</span>
<span class="identifier">MatrixZ</span><span class="special">&</span> <span class="identifier">z</span> <span class="special">);</span>
</pre>
<p>
</p>
<a name="boost_numeric_bindings.reference.lapack.driver_routines.hbgv.description"></a><h6>
<a name="id816978"></a>
<a class="link" href="hbgv.html#boost_numeric_bindings.reference.lapack.driver_routines.hbgv.description">Description</a>
</h6>
<p>
<code class="computeroutput"><span class="identifier">hbgv</span></code> (short for $FRIENDLY_NAME)
provides a C++ interface to LAPACK routines SSBGV, DSBGV, CHBGV, and
ZHBGV. <code class="computeroutput"><span class="identifier">hbgv</span></code> computes
all the eigenvalues, and optionally, the eigenvectors of a complex generalized
Hermitian-definite banded eigenproblem, of the form A*x=(lambda)*B*x.
Here A and B are assumed to be Hermitian and banded, and B is also positive
definite.
</p>
<p>
The selection of the LAPACK routine is done during compile-time, and
is determined by the type of values contained in type <code class="computeroutput"><span class="identifier">MatrixAB</span></code>.
The type of values is obtained through the <code class="computeroutput"><span class="identifier">value_type</span></code>
meta-function <code class="computeroutput"><span class="keyword">typename</span> <span class="identifier">value_type</span><span class="special"><</span><span class="identifier">MatrixAB</span><span class="special">>::</span><span class="identifier">type</span></code>. The dispatching table below illustrates
to which specific routine the code path will be generated.
</p>
<div class="table">
<a name="boost_numeric_bindings.reference.lapack.driver_routines.hbgv.dispatching_of_hbgv"></a><p class="title"><b>Table 1.106. Dispatching of hbgv</b></p>
<div class="table-contents"><table class="table" summary="Dispatching of hbgv">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Value type of MatrixAB
</p>
</th>
<th>
<p>
LAPACK routine
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="keyword">float</span></code>
</p>
</td>
<td>
<p>
SSBGV
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="keyword">double</span></code>
</p>
</td>
<td>
<p>
DSBGV
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">complex</span><span class="special"><</span><span class="keyword">float</span><span class="special">></span></code>
</p>
</td>
<td>
<p>
CHBGV
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">complex</span><span class="special"><</span><span class="keyword">double</span><span class="special">></span></code>
</p>
</td>
<td>
<p>
ZHBGV
</p>
</td>
</tr>
</tbody>
</table></div>
</div>
<br class="table-break"><a name="boost_numeric_bindings.reference.lapack.driver_routines.hbgv.definition"></a><h6>
<a name="id817310"></a>
<a class="link" href="hbgv.html#boost_numeric_bindings.reference.lapack.driver_routines.hbgv.definition">Definition</a>
</h6>
<p>
Defined in header <code class="computeroutput">boost/numeric/bindings/lapack/driver/hbgv.hpp</code>.
</p>
<a name="boost_numeric_bindings.reference.lapack.driver_routines.hbgv.parameters_or_requirements_on_types"></a><h6>
<a name="id817350"></a>
<a class="link" href="hbgv.html#boost_numeric_bindings.reference.lapack.driver_routines.hbgv.parameters_or_requirements_on_types">Parameters
or Requirements on Types</a>
</h6>
<div class="variablelist">
<p class="title"><b>Parameters</b></p>
<dl>
<dt><span class="term">MatrixA</span></dt>
<dd><p>
The definition of term 1
</p></dd>
<dt><span class="term">MatrixB</span></dt>
<dd><p>
The definition of term 2
</p></dd>
<dt><span class="term">MatrixC</span></dt>
<dd>
<p>
The definition of term 3.
</p>
<p>
Definitions may contain paragraphs.
</p>
</dd>
</dl>
</div>
<a name="boost_numeric_bindings.reference.lapack.driver_routines.hbgv.complexity"></a><h6>
<a name="id817436"></a>
<a class="link" href="hbgv.html#boost_numeric_bindings.reference.lapack.driver_routines.hbgv.complexity">Complexity</a>
</h6>
<a name="boost_numeric_bindings.reference.lapack.driver_routines.hbgv.example"></a><h6>
<a name="id817462"></a>
<a class="link" href="hbgv.html#boost_numeric_bindings.reference.lapack.driver_routines.hbgv.example">Example</a>
</h6>
<p>
</p>
<pre class="programlisting"><span class="preprocessor">#include</span> <span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">numeric</span><span class="special">/</span><span class="identifier">bindings</span><span class="special">/</span><span class="identifier">lapack</span><span class="special">/</span><span class="identifier">driver</span><span class="special">/</span><span class="identifier">hbgv</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span>
<span class="keyword">using</span> <span class="keyword">namespace</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">numeric</span><span class="special">::</span><span class="identifier">bindings</span><span class="special">;</span>
<span class="identifier">lapack</span><span class="special">::</span><span class="identifier">hbgv</span><span class="special">(</span> <span class="identifier">x</span><span class="special">,</span> <span class="identifier">y</span><span class="special">,</span> <span class="identifier">z</span> <span class="special">);</span>
</pre>
<p>
</p>
<p>
this will output
</p>
<p>
</p>
<pre class="programlisting"><span class="special">[</span><span class="number">5</span><span class="special">]</span> <span class="number">0</span> <span class="number">1</span> <span class="number">2</span> <span class="number">3</span> <span class="number">4</span> <span class="number">5</span>
</pre>
<p>
</p>
<a name="boost_numeric_bindings.reference.lapack.driver_routines.hbgv.notes"></a><h6>
<a name="id817746"></a>
<a class="link" href="hbgv.html#boost_numeric_bindings.reference.lapack.driver_routines.hbgv.notes">Notes</a>
</h6>
<a name="boost_numeric_bindings.reference.lapack.driver_routines.hbgv.see_also"></a><h6>
<a name="id817771"></a>
<a class="link" href="hbgv.html#boost_numeric_bindings.reference.lapack.driver_routines.hbgv.see_also">See
Also</a>
</h6>
<div class="itemizedlist"><ul class="itemizedlist" type="disc"><li class="listitem">
Originating Fortran source files <a href="http://www.netlib.org/lapack/single/ssbgv.f" target="_top">ssbgv.f</a>,
<a href="http://www.netlib.org/lapack/double/dsbgv.f" target="_top">dsbgv.f</a>,
<a href="http://www.netlib.org/lapack/complex/chbgv.f" target="_top">chbgv.f</a>,
and <a href="http://www.netlib.org/lapack/complex16/zhbgv.f" target="_top">zhbgv.f</a>
at Netlib.
</li></ul></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 © 2002 -2009 Rutger ter Borg, Krešimir Fresl, Thomas Klimpel,
Toon Knapen, Karl Meerbergen<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="ggsvd.html"><img src="../../../../images/prev.png" alt="Prev"></a><a accesskey="u" href="../driver_routines.html"><img src="../../../../images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../images/home.png" alt="Home"></a><a accesskey="n" href="hbgvd.html"><img src="../../../../images/next.png" alt="Next"></a>
</div>
</body>
</html>
| apache-2.0 |
gradle/gradle | subprojects/language-native/src/main/java/org/gradle/swiftpm/internal/DefaultTarget.java | 2004 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.swiftpm.internal;
import com.google.common.collect.ImmutableSet;
import javax.annotation.Nullable;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class DefaultTarget implements Serializable {
private final String name;
private final File path;
private final Collection<File> sourceFiles;
private final List<String> requiredTargets = new ArrayList<String>();
private final List<String> requiredProducts = new ArrayList<String>();
private File publicHeaderDir;
public DefaultTarget(String name, File path, Iterable<File> sourceFiles) {
this.name = name;
this.path = path;
this.sourceFiles = ImmutableSet.copyOf(sourceFiles);
}
public String getName() {
return name;
}
public File getPath() {
return path;
}
public Collection<File> getSourceFiles() {
return sourceFiles;
}
@Nullable
public File getPublicHeaderDir() {
return publicHeaderDir;
}
public void setPublicHeaderDir(File publicHeaderDir) {
this.publicHeaderDir = publicHeaderDir;
}
public Collection<String> getRequiredTargets() {
return requiredTargets;
}
public Collection<String> getRequiredProducts() {
return requiredProducts;
}
}
| apache-2.0 |
ehsan/js-symbolic-executor | js-symbolic-executor/src/symbolicexecutor/CompareFiles.java | 3614 | /*
* Copyright 2010 Google Inc.
*
* 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 symbolicexecutor;
import com.google.common.collect.Sets;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.ScriptableObject;
import java.io.IOException;
import java.util.Set;
/**
* An object that runs symbolic execution on one program to generate a bunch of
* tests and their outputs, runs a second program with these tests, compares
* against the first set of outputs, and reports the differences.
*
* @author elnatan@google.com (Elnatan Reisner)
*
*/
public class CompareFiles {
/** The file names of the original and new programs */
private final String originalProgram;
private final String newProgram;
/** The name of the function at which to start symbolic execution */
private final String entryFunction;
/** The arguments to pass to the entry function to start execution */
private final String[] arguments;
/**
* @param originalProgram file name of the original version of the program
* @param newProgram file name of the new version of the program
* @param entryFunction the function at which to start symbolic execution
* @param arguments the arguments to pass to the entry function
*/
public CompareFiles(String originalProgram, String newProgram,
String entryFunction, String... arguments) {
this.originalProgram = originalProgram;
this.newProgram = newProgram;
this.entryFunction = entryFunction;
this.arguments = arguments;
}
/**
* @param maxTests the maximum number of tests to generate
* @return the set of differences between the old and new programs, given as
* pairs (x, y), where x is the {@link Output} from the original
* program and y is the new program's output on {@code x.input}
* @throws IOException
*/
public Set<Pair<Output, Object>> compare(FileLoader loader, int maxTests)
throws IOException {
Cvc3Context cvc3Context = Cvc3Context.create(arguments.length, loader);
NewInputGenerator inputGenerator = new ApiBasedInputGenerator(cvc3Context);
SymbolicExecutor executor = SymbolicExecutor.create(
originalProgram, loader, inputGenerator, maxTests, entryFunction,
arguments);
Context rhinoContext = Context.enter();
Set<Pair<Output, Object>> differences = Sets.newHashSet();
// Run symbolic execution, and iterate through all generated inputs
for (Output output : executor.run()) {
// Run the new program with the old arguments
ScriptableObject scope = rhinoContext.initStandardObjects();
rhinoContext.evaluateString(scope, loader.toString(newProgram),
"new program", 0, null);
Object result = ScriptableObject.callMethod(scope, entryFunction,
output.input.toArray(ContextFactory.getGlobal()));
// If the results differ, add them to the set of differences
if (!output.result.equals(result)) {
differences.add(new Pair<Output, Object>(output, result));
}
}
return differences;
}
}
| apache-2.0 |
Fiware/ops.Validator | extras/ChefCookBook/bork/recipes/0.0.1_configure.rb | 702 | #
# Cookbook Name:: bork
# Recipe:: configure
#
# Copyright 2015, GING, ETSIT, UPM
#
# 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.
#
node.set['bork']['version'] = '0.0.1'
include_recipe 'bork::configure' | apache-2.0 |
geniusgogo/rt-thread | bsp/tm4c129x/libraries/inc/hw_adc.h | 73477 | //*****************************************************************************
//
// hw_adc.h - Macros used when accessing the ADC hardware.
//
// Copyright (c) 2005-2020 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// 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 Texas Instruments Incorporated nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// This is part of revision 2.2.0.295 of the Tiva Firmware Development Package.
//
//*****************************************************************************
#ifndef __HW_ADC_H__
#define __HW_ADC_H__
//*****************************************************************************
//
// The following are defines for the ADC register offsets.
//
//*****************************************************************************
#define ADC_O_ACTSS 0x00000000 // ADC Active Sample Sequencer
#define ADC_O_RIS 0x00000004 // ADC Raw Interrupt Status
#define ADC_O_IM 0x00000008 // ADC Interrupt Mask
#define ADC_O_ISC 0x0000000C // ADC Interrupt Status and Clear
#define ADC_O_OSTAT 0x00000010 // ADC Overflow Status
#define ADC_O_EMUX 0x00000014 // ADC Event Multiplexer Select
#define ADC_O_USTAT 0x00000018 // ADC Underflow Status
#define ADC_O_TSSEL 0x0000001C // ADC Trigger Source Select
#define ADC_O_SSPRI 0x00000020 // ADC Sample Sequencer Priority
#define ADC_O_SPC 0x00000024 // ADC Sample Phase Control
#define ADC_O_PSSI 0x00000028 // ADC Processor Sample Sequence
// Initiate
#define ADC_O_SAC 0x00000030 // ADC Sample Averaging Control
#define ADC_O_DCISC 0x00000034 // ADC Digital Comparator Interrupt
// Status and Clear
#define ADC_O_CTL 0x00000038 // ADC Control
#define ADC_O_SSMUX0 0x00000040 // ADC Sample Sequence Input
// Multiplexer Select 0
#define ADC_O_SSCTL0 0x00000044 // ADC Sample Sequence Control 0
#define ADC_O_SSFIFO0 0x00000048 // ADC Sample Sequence Result FIFO
// 0
#define ADC_O_SSFSTAT0 0x0000004C // ADC Sample Sequence FIFO 0
// Status
#define ADC_O_SSOP0 0x00000050 // ADC Sample Sequence 0 Operation
#define ADC_O_SSDC0 0x00000054 // ADC Sample Sequence 0 Digital
// Comparator Select
#define ADC_O_SSEMUX0 0x00000058 // ADC Sample Sequence Extended
// Input Multiplexer Select 0
#define ADC_O_SSTSH0 0x0000005C // ADC Sample Sequence 0 Sample and
// Hold Time
#define ADC_O_SSMUX1 0x00000060 // ADC Sample Sequence Input
// Multiplexer Select 1
#define ADC_O_SSCTL1 0x00000064 // ADC Sample Sequence Control 1
#define ADC_O_SSFIFO1 0x00000068 // ADC Sample Sequence Result FIFO
// 1
#define ADC_O_SSFSTAT1 0x0000006C // ADC Sample Sequence FIFO 1
// Status
#define ADC_O_SSOP1 0x00000070 // ADC Sample Sequence 1 Operation
#define ADC_O_SSDC1 0x00000074 // ADC Sample Sequence 1 Digital
// Comparator Select
#define ADC_O_SSEMUX1 0x00000078 // ADC Sample Sequence Extended
// Input Multiplexer Select 1
#define ADC_O_SSTSH1 0x0000007C // ADC Sample Sequence 1 Sample and
// Hold Time
#define ADC_O_SSMUX2 0x00000080 // ADC Sample Sequence Input
// Multiplexer Select 2
#define ADC_O_SSCTL2 0x00000084 // ADC Sample Sequence Control 2
#define ADC_O_SSFIFO2 0x00000088 // ADC Sample Sequence Result FIFO
// 2
#define ADC_O_SSFSTAT2 0x0000008C // ADC Sample Sequence FIFO 2
// Status
#define ADC_O_SSOP2 0x00000090 // ADC Sample Sequence 2 Operation
#define ADC_O_SSDC2 0x00000094 // ADC Sample Sequence 2 Digital
// Comparator Select
#define ADC_O_SSEMUX2 0x00000098 // ADC Sample Sequence Extended
// Input Multiplexer Select 2
#define ADC_O_SSTSH2 0x0000009C // ADC Sample Sequence 2 Sample and
// Hold Time
#define ADC_O_SSMUX3 0x000000A0 // ADC Sample Sequence Input
// Multiplexer Select 3
#define ADC_O_SSCTL3 0x000000A4 // ADC Sample Sequence Control 3
#define ADC_O_SSFIFO3 0x000000A8 // ADC Sample Sequence Result FIFO
// 3
#define ADC_O_SSFSTAT3 0x000000AC // ADC Sample Sequence FIFO 3
// Status
#define ADC_O_SSOP3 0x000000B0 // ADC Sample Sequence 3 Operation
#define ADC_O_SSDC3 0x000000B4 // ADC Sample Sequence 3 Digital
// Comparator Select
#define ADC_O_SSEMUX3 0x000000B8 // ADC Sample Sequence Extended
// Input Multiplexer Select 3
#define ADC_O_SSTSH3 0x000000BC // ADC Sample Sequence 3 Sample and
// Hold Time
#define ADC_O_DCRIC 0x00000D00 // ADC Digital Comparator Reset
// Initial Conditions
#define ADC_O_DCCTL0 0x00000E00 // ADC Digital Comparator Control 0
#define ADC_O_DCCTL1 0x00000E04 // ADC Digital Comparator Control 1
#define ADC_O_DCCTL2 0x00000E08 // ADC Digital Comparator Control 2
#define ADC_O_DCCTL3 0x00000E0C // ADC Digital Comparator Control 3
#define ADC_O_DCCTL4 0x00000E10 // ADC Digital Comparator Control 4
#define ADC_O_DCCTL5 0x00000E14 // ADC Digital Comparator Control 5
#define ADC_O_DCCTL6 0x00000E18 // ADC Digital Comparator Control 6
#define ADC_O_DCCTL7 0x00000E1C // ADC Digital Comparator Control 7
#define ADC_O_DCCMP0 0x00000E40 // ADC Digital Comparator Range 0
#define ADC_O_DCCMP1 0x00000E44 // ADC Digital Comparator Range 1
#define ADC_O_DCCMP2 0x00000E48 // ADC Digital Comparator Range 2
#define ADC_O_DCCMP3 0x00000E4C // ADC Digital Comparator Range 3
#define ADC_O_DCCMP4 0x00000E50 // ADC Digital Comparator Range 4
#define ADC_O_DCCMP5 0x00000E54 // ADC Digital Comparator Range 5
#define ADC_O_DCCMP6 0x00000E58 // ADC Digital Comparator Range 6
#define ADC_O_DCCMP7 0x00000E5C // ADC Digital Comparator Range 7
#define ADC_O_PP 0x00000FC0 // ADC Peripheral Properties
#define ADC_O_PC 0x00000FC4 // ADC Peripheral Configuration
#define ADC_O_CC 0x00000FC8 // ADC Clock Configuration
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_ACTSS register.
//
//*****************************************************************************
#define ADC_ACTSS_BUSY 0x00010000 // ADC Busy
#define ADC_ACTSS_ADEN3 0x00000800 // ADC SS3 DMA Enable
#define ADC_ACTSS_ADEN2 0x00000400 // ADC SS2 DMA Enable
#define ADC_ACTSS_ADEN1 0x00000200 // ADC SS1 DMA Enable
#define ADC_ACTSS_ADEN0 0x00000100 // ADC SS1 DMA Enable
#define ADC_ACTSS_ASEN3 0x00000008 // ADC SS3 Enable
#define ADC_ACTSS_ASEN2 0x00000004 // ADC SS2 Enable
#define ADC_ACTSS_ASEN1 0x00000002 // ADC SS1 Enable
#define ADC_ACTSS_ASEN0 0x00000001 // ADC SS0 Enable
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_RIS register.
//
//*****************************************************************************
#define ADC_RIS_INRDC 0x00010000 // Digital Comparator Raw Interrupt
// Status
#define ADC_RIS_DMAINR3 0x00000800 // SS3 DMA Raw Interrupt Status
#define ADC_RIS_DMAINR2 0x00000400 // SS2 DMA Raw Interrupt Status
#define ADC_RIS_DMAINR1 0x00000200 // SS1 DMA Raw Interrupt Status
#define ADC_RIS_DMAINR0 0x00000100 // SS0 DMA Raw Interrupt Status
#define ADC_RIS_INR3 0x00000008 // SS3 Raw Interrupt Status
#define ADC_RIS_INR2 0x00000004 // SS2 Raw Interrupt Status
#define ADC_RIS_INR1 0x00000002 // SS1 Raw Interrupt Status
#define ADC_RIS_INR0 0x00000001 // SS0 Raw Interrupt Status
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_IM register.
//
//*****************************************************************************
#define ADC_IM_DCONSS3 0x00080000 // Digital Comparator Interrupt on
// SS3
#define ADC_IM_DCONSS2 0x00040000 // Digital Comparator Interrupt on
// SS2
#define ADC_IM_DCONSS1 0x00020000 // Digital Comparator Interrupt on
// SS1
#define ADC_IM_DCONSS0 0x00010000 // Digital Comparator Interrupt on
// SS0
#define ADC_IM_DMAMASK3 0x00000800 // SS3 DMA Interrupt Mask
#define ADC_IM_DMAMASK2 0x00000400 // SS2 DMA Interrupt Mask
#define ADC_IM_DMAMASK1 0x00000200 // SS1 DMA Interrupt Mask
#define ADC_IM_DMAMASK0 0x00000100 // SS0 DMA Interrupt Mask
#define ADC_IM_MASK3 0x00000008 // SS3 Interrupt Mask
#define ADC_IM_MASK2 0x00000004 // SS2 Interrupt Mask
#define ADC_IM_MASK1 0x00000002 // SS1 Interrupt Mask
#define ADC_IM_MASK0 0x00000001 // SS0 Interrupt Mask
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_ISC register.
//
//*****************************************************************************
#define ADC_ISC_DCINSS3 0x00080000 // Digital Comparator Interrupt
// Status on SS3
#define ADC_ISC_DCINSS2 0x00040000 // Digital Comparator Interrupt
// Status on SS2
#define ADC_ISC_DCINSS1 0x00020000 // Digital Comparator Interrupt
// Status on SS1
#define ADC_ISC_DCINSS0 0x00010000 // Digital Comparator Interrupt
// Status on SS0
#define ADC_ISC_DMAIN3 0x00000800 // SS3 DMA Interrupt Status and
// Clear
#define ADC_ISC_DMAIN2 0x00000400 // SS2 DMA Interrupt Status and
// Clear
#define ADC_ISC_DMAIN1 0x00000200 // SS1 DMA Interrupt Status and
// Clear
#define ADC_ISC_DMAIN0 0x00000100 // SS0 DMA Interrupt Status and
// Clear
#define ADC_ISC_IN3 0x00000008 // SS3 Interrupt Status and Clear
#define ADC_ISC_IN2 0x00000004 // SS2 Interrupt Status and Clear
#define ADC_ISC_IN1 0x00000002 // SS1 Interrupt Status and Clear
#define ADC_ISC_IN0 0x00000001 // SS0 Interrupt Status and Clear
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_OSTAT register.
//
//*****************************************************************************
#define ADC_OSTAT_OV3 0x00000008 // SS3 FIFO Overflow
#define ADC_OSTAT_OV2 0x00000004 // SS2 FIFO Overflow
#define ADC_OSTAT_OV1 0x00000002 // SS1 FIFO Overflow
#define ADC_OSTAT_OV0 0x00000001 // SS0 FIFO Overflow
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_EMUX register.
//
//*****************************************************************************
#define ADC_EMUX_EM3_M 0x0000F000 // SS3 Trigger Select
#define ADC_EMUX_EM3_PROCESSOR 0x00000000 // Processor (default)
#define ADC_EMUX_EM3_COMP0 0x00001000 // Analog Comparator 0
#define ADC_EMUX_EM3_COMP1 0x00002000 // Analog Comparator 1
#define ADC_EMUX_EM3_COMP2 0x00003000 // Analog Comparator 2
#define ADC_EMUX_EM3_EXTERNAL 0x00004000 // External (GPIO Pins)
#define ADC_EMUX_EM3_TIMER 0x00005000 // Timer
#define ADC_EMUX_EM3_PWM0 0x00006000 // PWM generator 0
#define ADC_EMUX_EM3_PWM1 0x00007000 // PWM generator 1
#define ADC_EMUX_EM3_PWM2 0x00008000 // PWM generator 2
#define ADC_EMUX_EM3_PWM3 0x00009000 // PWM generator 3
#define ADC_EMUX_EM3_NEVER 0x0000E000 // Never Trigger
#define ADC_EMUX_EM3_ALWAYS 0x0000F000 // Always (continuously sample)
#define ADC_EMUX_EM2_M 0x00000F00 // SS2 Trigger Select
#define ADC_EMUX_EM2_PROCESSOR 0x00000000 // Processor (default)
#define ADC_EMUX_EM2_COMP0 0x00000100 // Analog Comparator 0
#define ADC_EMUX_EM2_COMP1 0x00000200 // Analog Comparator 1
#define ADC_EMUX_EM2_COMP2 0x00000300 // Analog Comparator 2
#define ADC_EMUX_EM2_EXTERNAL 0x00000400 // External (GPIO Pins)
#define ADC_EMUX_EM2_TIMER 0x00000500 // Timer
#define ADC_EMUX_EM2_PWM0 0x00000600 // PWM generator 0
#define ADC_EMUX_EM2_PWM1 0x00000700 // PWM generator 1
#define ADC_EMUX_EM2_PWM2 0x00000800 // PWM generator 2
#define ADC_EMUX_EM2_PWM3 0x00000900 // PWM generator 3
#define ADC_EMUX_EM2_NEVER 0x00000E00 // Never Trigger
#define ADC_EMUX_EM2_ALWAYS 0x00000F00 // Always (continuously sample)
#define ADC_EMUX_EM1_M 0x000000F0 // SS1 Trigger Select
#define ADC_EMUX_EM1_PROCESSOR 0x00000000 // Processor (default)
#define ADC_EMUX_EM1_COMP0 0x00000010 // Analog Comparator 0
#define ADC_EMUX_EM1_COMP1 0x00000020 // Analog Comparator 1
#define ADC_EMUX_EM1_COMP2 0x00000030 // Analog Comparator 2
#define ADC_EMUX_EM1_EXTERNAL 0x00000040 // External (GPIO Pins)
#define ADC_EMUX_EM1_TIMER 0x00000050 // Timer
#define ADC_EMUX_EM1_PWM0 0x00000060 // PWM generator 0
#define ADC_EMUX_EM1_PWM1 0x00000070 // PWM generator 1
#define ADC_EMUX_EM1_PWM2 0x00000080 // PWM generator 2
#define ADC_EMUX_EM1_PWM3 0x00000090 // PWM generator 3
#define ADC_EMUX_EM1_NEVER 0x000000E0 // Never Trigger
#define ADC_EMUX_EM1_ALWAYS 0x000000F0 // Always (continuously sample)
#define ADC_EMUX_EM0_M 0x0000000F // SS0 Trigger Select
#define ADC_EMUX_EM0_PROCESSOR 0x00000000 // Processor (default)
#define ADC_EMUX_EM0_COMP0 0x00000001 // Analog Comparator 0
#define ADC_EMUX_EM0_COMP1 0x00000002 // Analog Comparator 1
#define ADC_EMUX_EM0_COMP2 0x00000003 // Analog Comparator 2
#define ADC_EMUX_EM0_EXTERNAL 0x00000004 // External (GPIO Pins)
#define ADC_EMUX_EM0_TIMER 0x00000005 // Timer
#define ADC_EMUX_EM0_PWM0 0x00000006 // PWM generator 0
#define ADC_EMUX_EM0_PWM1 0x00000007 // PWM generator 1
#define ADC_EMUX_EM0_PWM2 0x00000008 // PWM generator 2
#define ADC_EMUX_EM0_PWM3 0x00000009 // PWM generator 3
#define ADC_EMUX_EM0_NEVER 0x0000000E // Never Trigger
#define ADC_EMUX_EM0_ALWAYS 0x0000000F // Always (continuously sample)
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_USTAT register.
//
//*****************************************************************************
#define ADC_USTAT_UV3 0x00000008 // SS3 FIFO Underflow
#define ADC_USTAT_UV2 0x00000004 // SS2 FIFO Underflow
#define ADC_USTAT_UV1 0x00000002 // SS1 FIFO Underflow
#define ADC_USTAT_UV0 0x00000001 // SS0 FIFO Underflow
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_TSSEL register.
//
//*****************************************************************************
#define ADC_TSSEL_PS3_M 0x30000000 // Generator 3 PWM Module Trigger
// Select
#define ADC_TSSEL_PS3_0 0x00000000 // Use Generator 3 (and its
// trigger) in PWM module 0
#define ADC_TSSEL_PS3_1 0x10000000 // Use Generator 3 (and its
// trigger) in PWM module 1
#define ADC_TSSEL_PS2_M 0x00300000 // Generator 2 PWM Module Trigger
// Select
#define ADC_TSSEL_PS2_0 0x00000000 // Use Generator 2 (and its
// trigger) in PWM module 0
#define ADC_TSSEL_PS2_1 0x00100000 // Use Generator 2 (and its
// trigger) in PWM module 1
#define ADC_TSSEL_PS1_M 0x00003000 // Generator 1 PWM Module Trigger
// Select
#define ADC_TSSEL_PS1_0 0x00000000 // Use Generator 1 (and its
// trigger) in PWM module 0
#define ADC_TSSEL_PS1_1 0x00001000 // Use Generator 1 (and its
// trigger) in PWM module 1
#define ADC_TSSEL_PS0_M 0x00000030 // Generator 0 PWM Module Trigger
// Select
#define ADC_TSSEL_PS0_0 0x00000000 // Use Generator 0 (and its
// trigger) in PWM module 0
#define ADC_TSSEL_PS0_1 0x00000010 // Use Generator 0 (and its
// trigger) in PWM module 1
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSPRI register.
//
//*****************************************************************************
#define ADC_SSPRI_SS3_M 0x00003000 // SS3 Priority
#define ADC_SSPRI_SS2_M 0x00000300 // SS2 Priority
#define ADC_SSPRI_SS1_M 0x00000030 // SS1 Priority
#define ADC_SSPRI_SS0_M 0x00000003 // SS0 Priority
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SPC register.
//
//*****************************************************************************
#define ADC_SPC_PHASE_M 0x0000000F // Phase Difference
#define ADC_SPC_PHASE_0 0x00000000 // ADC sample lags by 0.0
#define ADC_SPC_PHASE_22_5 0x00000001 // ADC sample lags by 22.5
#define ADC_SPC_PHASE_45 0x00000002 // ADC sample lags by 45.0
#define ADC_SPC_PHASE_67_5 0x00000003 // ADC sample lags by 67.5
#define ADC_SPC_PHASE_90 0x00000004 // ADC sample lags by 90.0
#define ADC_SPC_PHASE_112_5 0x00000005 // ADC sample lags by 112.5
#define ADC_SPC_PHASE_135 0x00000006 // ADC sample lags by 135.0
#define ADC_SPC_PHASE_157_5 0x00000007 // ADC sample lags by 157.5
#define ADC_SPC_PHASE_180 0x00000008 // ADC sample lags by 180.0
#define ADC_SPC_PHASE_202_5 0x00000009 // ADC sample lags by 202.5
#define ADC_SPC_PHASE_225 0x0000000A // ADC sample lags by 225.0
#define ADC_SPC_PHASE_247_5 0x0000000B // ADC sample lags by 247.5
#define ADC_SPC_PHASE_270 0x0000000C // ADC sample lags by 270.0
#define ADC_SPC_PHASE_292_5 0x0000000D // ADC sample lags by 292.5
#define ADC_SPC_PHASE_315 0x0000000E // ADC sample lags by 315.0
#define ADC_SPC_PHASE_337_5 0x0000000F // ADC sample lags by 337.5
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_PSSI register.
//
//*****************************************************************************
#define ADC_PSSI_GSYNC 0x80000000 // Global Synchronize
#define ADC_PSSI_SYNCWAIT 0x08000000 // Synchronize Wait
#define ADC_PSSI_SS3 0x00000008 // SS3 Initiate
#define ADC_PSSI_SS2 0x00000004 // SS2 Initiate
#define ADC_PSSI_SS1 0x00000002 // SS1 Initiate
#define ADC_PSSI_SS0 0x00000001 // SS0 Initiate
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SAC register.
//
//*****************************************************************************
#define ADC_SAC_AVG_M 0x00000007 // Hardware Averaging Control
#define ADC_SAC_AVG_OFF 0x00000000 // No hardware oversampling
#define ADC_SAC_AVG_2X 0x00000001 // 2x hardware oversampling
#define ADC_SAC_AVG_4X 0x00000002 // 4x hardware oversampling
#define ADC_SAC_AVG_8X 0x00000003 // 8x hardware oversampling
#define ADC_SAC_AVG_16X 0x00000004 // 16x hardware oversampling
#define ADC_SAC_AVG_32X 0x00000005 // 32x hardware oversampling
#define ADC_SAC_AVG_64X 0x00000006 // 64x hardware oversampling
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCISC register.
//
//*****************************************************************************
#define ADC_DCISC_DCINT7 0x00000080 // Digital Comparator 7 Interrupt
// Status and Clear
#define ADC_DCISC_DCINT6 0x00000040 // Digital Comparator 6 Interrupt
// Status and Clear
#define ADC_DCISC_DCINT5 0x00000020 // Digital Comparator 5 Interrupt
// Status and Clear
#define ADC_DCISC_DCINT4 0x00000010 // Digital Comparator 4 Interrupt
// Status and Clear
#define ADC_DCISC_DCINT3 0x00000008 // Digital Comparator 3 Interrupt
// Status and Clear
#define ADC_DCISC_DCINT2 0x00000004 // Digital Comparator 2 Interrupt
// Status and Clear
#define ADC_DCISC_DCINT1 0x00000002 // Digital Comparator 1 Interrupt
// Status and Clear
#define ADC_DCISC_DCINT0 0x00000001 // Digital Comparator 0 Interrupt
// Status and Clear
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_CTL register.
//
//*****************************************************************************
#define ADC_CTL_VREF_M 0x00000003 // Voltage Reference Select
#define ADC_CTL_VREF_INTERNAL 0x00000000 // VDDA and GNDA are the voltage
// references
#define ADC_CTL_VREF_EXT_3V 0x00000001 // The external VREFA+ and VREFA-
// inputs are the voltage
// references
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSMUX0 register.
//
//*****************************************************************************
#define ADC_SSMUX0_MUX7_M 0xF0000000 // 8th Sample Input Select
#define ADC_SSMUX0_MUX6_M 0x0F000000 // 7th Sample Input Select
#define ADC_SSMUX0_MUX5_M 0x00F00000 // 6th Sample Input Select
#define ADC_SSMUX0_MUX4_M 0x000F0000 // 5th Sample Input Select
#define ADC_SSMUX0_MUX3_M 0x0000F000 // 4th Sample Input Select
#define ADC_SSMUX0_MUX2_M 0x00000F00 // 3rd Sample Input Select
#define ADC_SSMUX0_MUX1_M 0x000000F0 // 2nd Sample Input Select
#define ADC_SSMUX0_MUX0_M 0x0000000F // 1st Sample Input Select
#define ADC_SSMUX0_MUX7_S 28
#define ADC_SSMUX0_MUX6_S 24
#define ADC_SSMUX0_MUX5_S 20
#define ADC_SSMUX0_MUX4_S 16
#define ADC_SSMUX0_MUX3_S 12
#define ADC_SSMUX0_MUX2_S 8
#define ADC_SSMUX0_MUX1_S 4
#define ADC_SSMUX0_MUX0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSCTL0 register.
//
//*****************************************************************************
#define ADC_SSCTL0_TS7 0x80000000 // 8th Sample Temp Sensor Select
#define ADC_SSCTL0_IE7 0x40000000 // 8th Sample Interrupt Enable
#define ADC_SSCTL0_END7 0x20000000 // 8th Sample is End of Sequence
#define ADC_SSCTL0_D7 0x10000000 // 8th Sample Differential Input
// Select
#define ADC_SSCTL0_TS6 0x08000000 // 7th Sample Temp Sensor Select
#define ADC_SSCTL0_IE6 0x04000000 // 7th Sample Interrupt Enable
#define ADC_SSCTL0_END6 0x02000000 // 7th Sample is End of Sequence
#define ADC_SSCTL0_D6 0x01000000 // 7th Sample Differential Input
// Select
#define ADC_SSCTL0_TS5 0x00800000 // 6th Sample Temp Sensor Select
#define ADC_SSCTL0_IE5 0x00400000 // 6th Sample Interrupt Enable
#define ADC_SSCTL0_END5 0x00200000 // 6th Sample is End of Sequence
#define ADC_SSCTL0_D5 0x00100000 // 6th Sample Differential Input
// Select
#define ADC_SSCTL0_TS4 0x00080000 // 5th Sample Temp Sensor Select
#define ADC_SSCTL0_IE4 0x00040000 // 5th Sample Interrupt Enable
#define ADC_SSCTL0_END4 0x00020000 // 5th Sample is End of Sequence
#define ADC_SSCTL0_D4 0x00010000 // 5th Sample Differential Input
// Select
#define ADC_SSCTL0_TS3 0x00008000 // 4th Sample Temp Sensor Select
#define ADC_SSCTL0_IE3 0x00004000 // 4th Sample Interrupt Enable
#define ADC_SSCTL0_END3 0x00002000 // 4th Sample is End of Sequence
#define ADC_SSCTL0_D3 0x00001000 // 4th Sample Differential Input
// Select
#define ADC_SSCTL0_TS2 0x00000800 // 3rd Sample Temp Sensor Select
#define ADC_SSCTL0_IE2 0x00000400 // 3rd Sample Interrupt Enable
#define ADC_SSCTL0_END2 0x00000200 // 3rd Sample is End of Sequence
#define ADC_SSCTL0_D2 0x00000100 // 3rd Sample Differential Input
// Select
#define ADC_SSCTL0_TS1 0x00000080 // 2nd Sample Temp Sensor Select
#define ADC_SSCTL0_IE1 0x00000040 // 2nd Sample Interrupt Enable
#define ADC_SSCTL0_END1 0x00000020 // 2nd Sample is End of Sequence
#define ADC_SSCTL0_D1 0x00000010 // 2nd Sample Differential Input
// Select
#define ADC_SSCTL0_TS0 0x00000008 // 1st Sample Temp Sensor Select
#define ADC_SSCTL0_IE0 0x00000004 // 1st Sample Interrupt Enable
#define ADC_SSCTL0_END0 0x00000002 // 1st Sample is End of Sequence
#define ADC_SSCTL0_D0 0x00000001 // 1st Sample Differential Input
// Select
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSFIFO0 register.
//
//*****************************************************************************
#define ADC_SSFIFO0_DATA_M 0x00000FFF // Conversion Result Data
#define ADC_SSFIFO0_DATA_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSFSTAT0 register.
//
//*****************************************************************************
#define ADC_SSFSTAT0_FULL 0x00001000 // FIFO Full
#define ADC_SSFSTAT0_EMPTY 0x00000100 // FIFO Empty
#define ADC_SSFSTAT0_HPTR_M 0x000000F0 // FIFO Head Pointer
#define ADC_SSFSTAT0_TPTR_M 0x0000000F // FIFO Tail Pointer
#define ADC_SSFSTAT0_HPTR_S 4
#define ADC_SSFSTAT0_TPTR_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSOP0 register.
//
//*****************************************************************************
#define ADC_SSOP0_S7DCOP 0x10000000 // Sample 7 Digital Comparator
// Operation
#define ADC_SSOP0_S6DCOP 0x01000000 // Sample 6 Digital Comparator
// Operation
#define ADC_SSOP0_S5DCOP 0x00100000 // Sample 5 Digital Comparator
// Operation
#define ADC_SSOP0_S4DCOP 0x00010000 // Sample 4 Digital Comparator
// Operation
#define ADC_SSOP0_S3DCOP 0x00001000 // Sample 3 Digital Comparator
// Operation
#define ADC_SSOP0_S2DCOP 0x00000100 // Sample 2 Digital Comparator
// Operation
#define ADC_SSOP0_S1DCOP 0x00000010 // Sample 1 Digital Comparator
// Operation
#define ADC_SSOP0_S0DCOP 0x00000001 // Sample 0 Digital Comparator
// Operation
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSDC0 register.
//
//*****************************************************************************
#define ADC_SSDC0_S7DCSEL_M 0xF0000000 // Sample 7 Digital Comparator
// Select
#define ADC_SSDC0_S6DCSEL_M 0x0F000000 // Sample 6 Digital Comparator
// Select
#define ADC_SSDC0_S5DCSEL_M 0x00F00000 // Sample 5 Digital Comparator
// Select
#define ADC_SSDC0_S4DCSEL_M 0x000F0000 // Sample 4 Digital Comparator
// Select
#define ADC_SSDC0_S3DCSEL_M 0x0000F000 // Sample 3 Digital Comparator
// Select
#define ADC_SSDC0_S2DCSEL_M 0x00000F00 // Sample 2 Digital Comparator
// Select
#define ADC_SSDC0_S1DCSEL_M 0x000000F0 // Sample 1 Digital Comparator
// Select
#define ADC_SSDC0_S0DCSEL_M 0x0000000F // Sample 0 Digital Comparator
// Select
#define ADC_SSDC0_S6DCSEL_S 24
#define ADC_SSDC0_S5DCSEL_S 20
#define ADC_SSDC0_S4DCSEL_S 16
#define ADC_SSDC0_S3DCSEL_S 12
#define ADC_SSDC0_S2DCSEL_S 8
#define ADC_SSDC0_S1DCSEL_S 4
#define ADC_SSDC0_S0DCSEL_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSEMUX0 register.
//
//*****************************************************************************
#define ADC_SSEMUX0_EMUX7 0x10000000 // 8th Sample Input Select (Upper
// Bit)
#define ADC_SSEMUX0_EMUX6 0x01000000 // 7th Sample Input Select (Upper
// Bit)
#define ADC_SSEMUX0_EMUX5 0x00100000 // 6th Sample Input Select (Upper
// Bit)
#define ADC_SSEMUX0_EMUX4 0x00010000 // 5th Sample Input Select (Upper
// Bit)
#define ADC_SSEMUX0_EMUX3 0x00001000 // 4th Sample Input Select (Upper
// Bit)
#define ADC_SSEMUX0_EMUX2 0x00000100 // 3rd Sample Input Select (Upper
// Bit)
#define ADC_SSEMUX0_EMUX1 0x00000010 // 2th Sample Input Select (Upper
// Bit)
#define ADC_SSEMUX0_EMUX0 0x00000001 // 1st Sample Input Select (Upper
// Bit)
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSTSH0 register.
//
//*****************************************************************************
#define ADC_SSTSH0_TSH7_M 0xF0000000 // 8th Sample and Hold Period
// Select
#define ADC_SSTSH0_TSH6_M 0x0F000000 // 7th Sample and Hold Period
// Select
#define ADC_SSTSH0_TSH5_M 0x00F00000 // 6th Sample and Hold Period
// Select
#define ADC_SSTSH0_TSH4_M 0x000F0000 // 5th Sample and Hold Period
// Select
#define ADC_SSTSH0_TSH3_M 0x0000F000 // 4th Sample and Hold Period
// Select
#define ADC_SSTSH0_TSH2_M 0x00000F00 // 3rd Sample and Hold Period
// Select
#define ADC_SSTSH0_TSH1_M 0x000000F0 // 2nd Sample and Hold Period
// Select
#define ADC_SSTSH0_TSH0_M 0x0000000F // 1st Sample and Hold Period
// Select
#define ADC_SSTSH0_TSH7_S 28
#define ADC_SSTSH0_TSH6_S 24
#define ADC_SSTSH0_TSH5_S 20
#define ADC_SSTSH0_TSH4_S 16
#define ADC_SSTSH0_TSH3_S 12
#define ADC_SSTSH0_TSH2_S 8
#define ADC_SSTSH0_TSH1_S 4
#define ADC_SSTSH0_TSH0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSMUX1 register.
//
//*****************************************************************************
#define ADC_SSMUX1_MUX3_M 0x0000F000 // 4th Sample Input Select
#define ADC_SSMUX1_MUX2_M 0x00000F00 // 3rd Sample Input Select
#define ADC_SSMUX1_MUX1_M 0x000000F0 // 2nd Sample Input Select
#define ADC_SSMUX1_MUX0_M 0x0000000F // 1st Sample Input Select
#define ADC_SSMUX1_MUX3_S 12
#define ADC_SSMUX1_MUX2_S 8
#define ADC_SSMUX1_MUX1_S 4
#define ADC_SSMUX1_MUX0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSCTL1 register.
//
//*****************************************************************************
#define ADC_SSCTL1_TS3 0x00008000 // 4th Sample Temp Sensor Select
#define ADC_SSCTL1_IE3 0x00004000 // 4th Sample Interrupt Enable
#define ADC_SSCTL1_END3 0x00002000 // 4th Sample is End of Sequence
#define ADC_SSCTL1_D3 0x00001000 // 4th Sample Differential Input
// Select
#define ADC_SSCTL1_TS2 0x00000800 // 3rd Sample Temp Sensor Select
#define ADC_SSCTL1_IE2 0x00000400 // 3rd Sample Interrupt Enable
#define ADC_SSCTL1_END2 0x00000200 // 3rd Sample is End of Sequence
#define ADC_SSCTL1_D2 0x00000100 // 3rd Sample Differential Input
// Select
#define ADC_SSCTL1_TS1 0x00000080 // 2nd Sample Temp Sensor Select
#define ADC_SSCTL1_IE1 0x00000040 // 2nd Sample Interrupt Enable
#define ADC_SSCTL1_END1 0x00000020 // 2nd Sample is End of Sequence
#define ADC_SSCTL1_D1 0x00000010 // 2nd Sample Differential Input
// Select
#define ADC_SSCTL1_TS0 0x00000008 // 1st Sample Temp Sensor Select
#define ADC_SSCTL1_IE0 0x00000004 // 1st Sample Interrupt Enable
#define ADC_SSCTL1_END0 0x00000002 // 1st Sample is End of Sequence
#define ADC_SSCTL1_D0 0x00000001 // 1st Sample Differential Input
// Select
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSFIFO1 register.
//
//*****************************************************************************
#define ADC_SSFIFO1_DATA_M 0x00000FFF // Conversion Result Data
#define ADC_SSFIFO1_DATA_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSFSTAT1 register.
//
//*****************************************************************************
#define ADC_SSFSTAT1_FULL 0x00001000 // FIFO Full
#define ADC_SSFSTAT1_EMPTY 0x00000100 // FIFO Empty
#define ADC_SSFSTAT1_HPTR_M 0x000000F0 // FIFO Head Pointer
#define ADC_SSFSTAT1_TPTR_M 0x0000000F // FIFO Tail Pointer
#define ADC_SSFSTAT1_HPTR_S 4
#define ADC_SSFSTAT1_TPTR_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSOP1 register.
//
//*****************************************************************************
#define ADC_SSOP1_S3DCOP 0x00001000 // Sample 3 Digital Comparator
// Operation
#define ADC_SSOP1_S2DCOP 0x00000100 // Sample 2 Digital Comparator
// Operation
#define ADC_SSOP1_S1DCOP 0x00000010 // Sample 1 Digital Comparator
// Operation
#define ADC_SSOP1_S0DCOP 0x00000001 // Sample 0 Digital Comparator
// Operation
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSDC1 register.
//
//*****************************************************************************
#define ADC_SSDC1_S3DCSEL_M 0x0000F000 // Sample 3 Digital Comparator
// Select
#define ADC_SSDC1_S2DCSEL_M 0x00000F00 // Sample 2 Digital Comparator
// Select
#define ADC_SSDC1_S1DCSEL_M 0x000000F0 // Sample 1 Digital Comparator
// Select
#define ADC_SSDC1_S0DCSEL_M 0x0000000F // Sample 0 Digital Comparator
// Select
#define ADC_SSDC1_S2DCSEL_S 8
#define ADC_SSDC1_S1DCSEL_S 4
#define ADC_SSDC1_S0DCSEL_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSEMUX1 register.
//
//*****************************************************************************
#define ADC_SSEMUX1_EMUX3 0x00001000 // 4th Sample Input Select (Upper
// Bit)
#define ADC_SSEMUX1_EMUX2 0x00000100 // 3rd Sample Input Select (Upper
// Bit)
#define ADC_SSEMUX1_EMUX1 0x00000010 // 2th Sample Input Select (Upper
// Bit)
#define ADC_SSEMUX1_EMUX0 0x00000001 // 1st Sample Input Select (Upper
// Bit)
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSTSH1 register.
//
//*****************************************************************************
#define ADC_SSTSH1_TSH3_M 0x0000F000 // 4th Sample and Hold Period
// Select
#define ADC_SSTSH1_TSH2_M 0x00000F00 // 3rd Sample and Hold Period
// Select
#define ADC_SSTSH1_TSH1_M 0x000000F0 // 2nd Sample and Hold Period
// Select
#define ADC_SSTSH1_TSH0_M 0x0000000F // 1st Sample and Hold Period
// Select
#define ADC_SSTSH1_TSH3_S 12
#define ADC_SSTSH1_TSH2_S 8
#define ADC_SSTSH1_TSH1_S 4
#define ADC_SSTSH1_TSH0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSMUX2 register.
//
//*****************************************************************************
#define ADC_SSMUX2_MUX3_M 0x0000F000 // 4th Sample Input Select
#define ADC_SSMUX2_MUX2_M 0x00000F00 // 3rd Sample Input Select
#define ADC_SSMUX2_MUX1_M 0x000000F0 // 2nd Sample Input Select
#define ADC_SSMUX2_MUX0_M 0x0000000F // 1st Sample Input Select
#define ADC_SSMUX2_MUX3_S 12
#define ADC_SSMUX2_MUX2_S 8
#define ADC_SSMUX2_MUX1_S 4
#define ADC_SSMUX2_MUX0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSCTL2 register.
//
//*****************************************************************************
#define ADC_SSCTL2_TS3 0x00008000 // 4th Sample Temp Sensor Select
#define ADC_SSCTL2_IE3 0x00004000 // 4th Sample Interrupt Enable
#define ADC_SSCTL2_END3 0x00002000 // 4th Sample is End of Sequence
#define ADC_SSCTL2_D3 0x00001000 // 4th Sample Differential Input
// Select
#define ADC_SSCTL2_TS2 0x00000800 // 3rd Sample Temp Sensor Select
#define ADC_SSCTL2_IE2 0x00000400 // 3rd Sample Interrupt Enable
#define ADC_SSCTL2_END2 0x00000200 // 3rd Sample is End of Sequence
#define ADC_SSCTL2_D2 0x00000100 // 3rd Sample Differential Input
// Select
#define ADC_SSCTL2_TS1 0x00000080 // 2nd Sample Temp Sensor Select
#define ADC_SSCTL2_IE1 0x00000040 // 2nd Sample Interrupt Enable
#define ADC_SSCTL2_END1 0x00000020 // 2nd Sample is End of Sequence
#define ADC_SSCTL2_D1 0x00000010 // 2nd Sample Differential Input
// Select
#define ADC_SSCTL2_TS0 0x00000008 // 1st Sample Temp Sensor Select
#define ADC_SSCTL2_IE0 0x00000004 // 1st Sample Interrupt Enable
#define ADC_SSCTL2_END0 0x00000002 // 1st Sample is End of Sequence
#define ADC_SSCTL2_D0 0x00000001 // 1st Sample Differential Input
// Select
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSFIFO2 register.
//
//*****************************************************************************
#define ADC_SSFIFO2_DATA_M 0x00000FFF // Conversion Result Data
#define ADC_SSFIFO2_DATA_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSFSTAT2 register.
//
//*****************************************************************************
#define ADC_SSFSTAT2_FULL 0x00001000 // FIFO Full
#define ADC_SSFSTAT2_EMPTY 0x00000100 // FIFO Empty
#define ADC_SSFSTAT2_HPTR_M 0x000000F0 // FIFO Head Pointer
#define ADC_SSFSTAT2_TPTR_M 0x0000000F // FIFO Tail Pointer
#define ADC_SSFSTAT2_HPTR_S 4
#define ADC_SSFSTAT2_TPTR_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSOP2 register.
//
//*****************************************************************************
#define ADC_SSOP2_S3DCOP 0x00001000 // Sample 3 Digital Comparator
// Operation
#define ADC_SSOP2_S2DCOP 0x00000100 // Sample 2 Digital Comparator
// Operation
#define ADC_SSOP2_S1DCOP 0x00000010 // Sample 1 Digital Comparator
// Operation
#define ADC_SSOP2_S0DCOP 0x00000001 // Sample 0 Digital Comparator
// Operation
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSDC2 register.
//
//*****************************************************************************
#define ADC_SSDC2_S3DCSEL_M 0x0000F000 // Sample 3 Digital Comparator
// Select
#define ADC_SSDC2_S2DCSEL_M 0x00000F00 // Sample 2 Digital Comparator
// Select
#define ADC_SSDC2_S1DCSEL_M 0x000000F0 // Sample 1 Digital Comparator
// Select
#define ADC_SSDC2_S0DCSEL_M 0x0000000F // Sample 0 Digital Comparator
// Select
#define ADC_SSDC2_S2DCSEL_S 8
#define ADC_SSDC2_S1DCSEL_S 4
#define ADC_SSDC2_S0DCSEL_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSEMUX2 register.
//
//*****************************************************************************
#define ADC_SSEMUX2_EMUX3 0x00001000 // 4th Sample Input Select (Upper
// Bit)
#define ADC_SSEMUX2_EMUX2 0x00000100 // 3rd Sample Input Select (Upper
// Bit)
#define ADC_SSEMUX2_EMUX1 0x00000010 // 2th Sample Input Select (Upper
// Bit)
#define ADC_SSEMUX2_EMUX0 0x00000001 // 1st Sample Input Select (Upper
// Bit)
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSTSH2 register.
//
//*****************************************************************************
#define ADC_SSTSH2_TSH3_M 0x0000F000 // 4th Sample and Hold Period
// Select
#define ADC_SSTSH2_TSH2_M 0x00000F00 // 3rd Sample and Hold Period
// Select
#define ADC_SSTSH2_TSH1_M 0x000000F0 // 2nd Sample and Hold Period
// Select
#define ADC_SSTSH2_TSH0_M 0x0000000F // 1st Sample and Hold Period
// Select
#define ADC_SSTSH2_TSH3_S 12
#define ADC_SSTSH2_TSH2_S 8
#define ADC_SSTSH2_TSH1_S 4
#define ADC_SSTSH2_TSH0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSMUX3 register.
//
//*****************************************************************************
#define ADC_SSMUX3_MUX0_M 0x0000000F // 1st Sample Input Select
#define ADC_SSMUX3_MUX0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSCTL3 register.
//
//*****************************************************************************
#define ADC_SSCTL3_TS0 0x00000008 // 1st Sample Temp Sensor Select
#define ADC_SSCTL3_IE0 0x00000004 // Sample Interrupt Enable
#define ADC_SSCTL3_END0 0x00000002 // End of Sequence
#define ADC_SSCTL3_D0 0x00000001 // Sample Differential Input Select
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSFIFO3 register.
//
//*****************************************************************************
#define ADC_SSFIFO3_DATA_M 0x00000FFF // Conversion Result Data
#define ADC_SSFIFO3_DATA_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSFSTAT3 register.
//
//*****************************************************************************
#define ADC_SSFSTAT3_FULL 0x00001000 // FIFO Full
#define ADC_SSFSTAT3_EMPTY 0x00000100 // FIFO Empty
#define ADC_SSFSTAT3_HPTR_M 0x000000F0 // FIFO Head Pointer
#define ADC_SSFSTAT3_TPTR_M 0x0000000F // FIFO Tail Pointer
#define ADC_SSFSTAT3_HPTR_S 4
#define ADC_SSFSTAT3_TPTR_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSOP3 register.
//
//*****************************************************************************
#define ADC_SSOP3_S0DCOP 0x00000001 // Sample 0 Digital Comparator
// Operation
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSDC3 register.
//
//*****************************************************************************
#define ADC_SSDC3_S0DCSEL_M 0x0000000F // Sample 0 Digital Comparator
// Select
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSEMUX3 register.
//
//*****************************************************************************
#define ADC_SSEMUX3_EMUX0 0x00000001 // 1st Sample Input Select (Upper
// Bit)
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_SSTSH3 register.
//
//*****************************************************************************
#define ADC_SSTSH3_TSH0_M 0x0000000F // 1st Sample and Hold Period
// Select
#define ADC_SSTSH3_TSH0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCRIC register.
//
//*****************************************************************************
#define ADC_DCRIC_DCTRIG7 0x00800000 // Digital Comparator Trigger 7
#define ADC_DCRIC_DCTRIG6 0x00400000 // Digital Comparator Trigger 6
#define ADC_DCRIC_DCTRIG5 0x00200000 // Digital Comparator Trigger 5
#define ADC_DCRIC_DCTRIG4 0x00100000 // Digital Comparator Trigger 4
#define ADC_DCRIC_DCTRIG3 0x00080000 // Digital Comparator Trigger 3
#define ADC_DCRIC_DCTRIG2 0x00040000 // Digital Comparator Trigger 2
#define ADC_DCRIC_DCTRIG1 0x00020000 // Digital Comparator Trigger 1
#define ADC_DCRIC_DCTRIG0 0x00010000 // Digital Comparator Trigger 0
#define ADC_DCRIC_DCINT7 0x00000080 // Digital Comparator Interrupt 7
#define ADC_DCRIC_DCINT6 0x00000040 // Digital Comparator Interrupt 6
#define ADC_DCRIC_DCINT5 0x00000020 // Digital Comparator Interrupt 5
#define ADC_DCRIC_DCINT4 0x00000010 // Digital Comparator Interrupt 4
#define ADC_DCRIC_DCINT3 0x00000008 // Digital Comparator Interrupt 3
#define ADC_DCRIC_DCINT2 0x00000004 // Digital Comparator Interrupt 2
#define ADC_DCRIC_DCINT1 0x00000002 // Digital Comparator Interrupt 1
#define ADC_DCRIC_DCINT0 0x00000001 // Digital Comparator Interrupt 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCTL0 register.
//
//*****************************************************************************
#define ADC_DCCTL0_CTE 0x00001000 // Comparison Trigger Enable
#define ADC_DCCTL0_CTC_M 0x00000C00 // Comparison Trigger Condition
#define ADC_DCCTL0_CTC_LOW 0x00000000 // Low Band
#define ADC_DCCTL0_CTC_MID 0x00000400 // Mid Band
#define ADC_DCCTL0_CTC_HIGH 0x00000C00 // High Band
#define ADC_DCCTL0_CTM_M 0x00000300 // Comparison Trigger Mode
#define ADC_DCCTL0_CTM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL0_CTM_ONCE 0x00000100 // Once
#define ADC_DCCTL0_CTM_HALWAYS 0x00000200 // Hysteresis Always
#define ADC_DCCTL0_CTM_HONCE 0x00000300 // Hysteresis Once
#define ADC_DCCTL0_CIE 0x00000010 // Comparison Interrupt Enable
#define ADC_DCCTL0_CIC_M 0x0000000C // Comparison Interrupt Condition
#define ADC_DCCTL0_CIC_LOW 0x00000000 // Low Band
#define ADC_DCCTL0_CIC_MID 0x00000004 // Mid Band
#define ADC_DCCTL0_CIC_HIGH 0x0000000C // High Band
#define ADC_DCCTL0_CIM_M 0x00000003 // Comparison Interrupt Mode
#define ADC_DCCTL0_CIM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL0_CIM_ONCE 0x00000001 // Once
#define ADC_DCCTL0_CIM_HALWAYS 0x00000002 // Hysteresis Always
#define ADC_DCCTL0_CIM_HONCE 0x00000003 // Hysteresis Once
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCTL1 register.
//
//*****************************************************************************
#define ADC_DCCTL1_CTE 0x00001000 // Comparison Trigger Enable
#define ADC_DCCTL1_CTC_M 0x00000C00 // Comparison Trigger Condition
#define ADC_DCCTL1_CTC_LOW 0x00000000 // Low Band
#define ADC_DCCTL1_CTC_MID 0x00000400 // Mid Band
#define ADC_DCCTL1_CTC_HIGH 0x00000C00 // High Band
#define ADC_DCCTL1_CTM_M 0x00000300 // Comparison Trigger Mode
#define ADC_DCCTL1_CTM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL1_CTM_ONCE 0x00000100 // Once
#define ADC_DCCTL1_CTM_HALWAYS 0x00000200 // Hysteresis Always
#define ADC_DCCTL1_CTM_HONCE 0x00000300 // Hysteresis Once
#define ADC_DCCTL1_CIE 0x00000010 // Comparison Interrupt Enable
#define ADC_DCCTL1_CIC_M 0x0000000C // Comparison Interrupt Condition
#define ADC_DCCTL1_CIC_LOW 0x00000000 // Low Band
#define ADC_DCCTL1_CIC_MID 0x00000004 // Mid Band
#define ADC_DCCTL1_CIC_HIGH 0x0000000C // High Band
#define ADC_DCCTL1_CIM_M 0x00000003 // Comparison Interrupt Mode
#define ADC_DCCTL1_CIM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL1_CIM_ONCE 0x00000001 // Once
#define ADC_DCCTL1_CIM_HALWAYS 0x00000002 // Hysteresis Always
#define ADC_DCCTL1_CIM_HONCE 0x00000003 // Hysteresis Once
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCTL2 register.
//
//*****************************************************************************
#define ADC_DCCTL2_CTE 0x00001000 // Comparison Trigger Enable
#define ADC_DCCTL2_CTC_M 0x00000C00 // Comparison Trigger Condition
#define ADC_DCCTL2_CTC_LOW 0x00000000 // Low Band
#define ADC_DCCTL2_CTC_MID 0x00000400 // Mid Band
#define ADC_DCCTL2_CTC_HIGH 0x00000C00 // High Band
#define ADC_DCCTL2_CTM_M 0x00000300 // Comparison Trigger Mode
#define ADC_DCCTL2_CTM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL2_CTM_ONCE 0x00000100 // Once
#define ADC_DCCTL2_CTM_HALWAYS 0x00000200 // Hysteresis Always
#define ADC_DCCTL2_CTM_HONCE 0x00000300 // Hysteresis Once
#define ADC_DCCTL2_CIE 0x00000010 // Comparison Interrupt Enable
#define ADC_DCCTL2_CIC_M 0x0000000C // Comparison Interrupt Condition
#define ADC_DCCTL2_CIC_LOW 0x00000000 // Low Band
#define ADC_DCCTL2_CIC_MID 0x00000004 // Mid Band
#define ADC_DCCTL2_CIC_HIGH 0x0000000C // High Band
#define ADC_DCCTL2_CIM_M 0x00000003 // Comparison Interrupt Mode
#define ADC_DCCTL2_CIM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL2_CIM_ONCE 0x00000001 // Once
#define ADC_DCCTL2_CIM_HALWAYS 0x00000002 // Hysteresis Always
#define ADC_DCCTL2_CIM_HONCE 0x00000003 // Hysteresis Once
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCTL3 register.
//
//*****************************************************************************
#define ADC_DCCTL3_CTE 0x00001000 // Comparison Trigger Enable
#define ADC_DCCTL3_CTC_M 0x00000C00 // Comparison Trigger Condition
#define ADC_DCCTL3_CTC_LOW 0x00000000 // Low Band
#define ADC_DCCTL3_CTC_MID 0x00000400 // Mid Band
#define ADC_DCCTL3_CTC_HIGH 0x00000C00 // High Band
#define ADC_DCCTL3_CTM_M 0x00000300 // Comparison Trigger Mode
#define ADC_DCCTL3_CTM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL3_CTM_ONCE 0x00000100 // Once
#define ADC_DCCTL3_CTM_HALWAYS 0x00000200 // Hysteresis Always
#define ADC_DCCTL3_CTM_HONCE 0x00000300 // Hysteresis Once
#define ADC_DCCTL3_CIE 0x00000010 // Comparison Interrupt Enable
#define ADC_DCCTL3_CIC_M 0x0000000C // Comparison Interrupt Condition
#define ADC_DCCTL3_CIC_LOW 0x00000000 // Low Band
#define ADC_DCCTL3_CIC_MID 0x00000004 // Mid Band
#define ADC_DCCTL3_CIC_HIGH 0x0000000C // High Band
#define ADC_DCCTL3_CIM_M 0x00000003 // Comparison Interrupt Mode
#define ADC_DCCTL3_CIM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL3_CIM_ONCE 0x00000001 // Once
#define ADC_DCCTL3_CIM_HALWAYS 0x00000002 // Hysteresis Always
#define ADC_DCCTL3_CIM_HONCE 0x00000003 // Hysteresis Once
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCTL4 register.
//
//*****************************************************************************
#define ADC_DCCTL4_CTE 0x00001000 // Comparison Trigger Enable
#define ADC_DCCTL4_CTC_M 0x00000C00 // Comparison Trigger Condition
#define ADC_DCCTL4_CTC_LOW 0x00000000 // Low Band
#define ADC_DCCTL4_CTC_MID 0x00000400 // Mid Band
#define ADC_DCCTL4_CTC_HIGH 0x00000C00 // High Band
#define ADC_DCCTL4_CTM_M 0x00000300 // Comparison Trigger Mode
#define ADC_DCCTL4_CTM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL4_CTM_ONCE 0x00000100 // Once
#define ADC_DCCTL4_CTM_HALWAYS 0x00000200 // Hysteresis Always
#define ADC_DCCTL4_CTM_HONCE 0x00000300 // Hysteresis Once
#define ADC_DCCTL4_CIE 0x00000010 // Comparison Interrupt Enable
#define ADC_DCCTL4_CIC_M 0x0000000C // Comparison Interrupt Condition
#define ADC_DCCTL4_CIC_LOW 0x00000000 // Low Band
#define ADC_DCCTL4_CIC_MID 0x00000004 // Mid Band
#define ADC_DCCTL4_CIC_HIGH 0x0000000C // High Band
#define ADC_DCCTL4_CIM_M 0x00000003 // Comparison Interrupt Mode
#define ADC_DCCTL4_CIM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL4_CIM_ONCE 0x00000001 // Once
#define ADC_DCCTL4_CIM_HALWAYS 0x00000002 // Hysteresis Always
#define ADC_DCCTL4_CIM_HONCE 0x00000003 // Hysteresis Once
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCTL5 register.
//
//*****************************************************************************
#define ADC_DCCTL5_CTE 0x00001000 // Comparison Trigger Enable
#define ADC_DCCTL5_CTC_M 0x00000C00 // Comparison Trigger Condition
#define ADC_DCCTL5_CTC_LOW 0x00000000 // Low Band
#define ADC_DCCTL5_CTC_MID 0x00000400 // Mid Band
#define ADC_DCCTL5_CTC_HIGH 0x00000C00 // High Band
#define ADC_DCCTL5_CTM_M 0x00000300 // Comparison Trigger Mode
#define ADC_DCCTL5_CTM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL5_CTM_ONCE 0x00000100 // Once
#define ADC_DCCTL5_CTM_HALWAYS 0x00000200 // Hysteresis Always
#define ADC_DCCTL5_CTM_HONCE 0x00000300 // Hysteresis Once
#define ADC_DCCTL5_CIE 0x00000010 // Comparison Interrupt Enable
#define ADC_DCCTL5_CIC_M 0x0000000C // Comparison Interrupt Condition
#define ADC_DCCTL5_CIC_LOW 0x00000000 // Low Band
#define ADC_DCCTL5_CIC_MID 0x00000004 // Mid Band
#define ADC_DCCTL5_CIC_HIGH 0x0000000C // High Band
#define ADC_DCCTL5_CIM_M 0x00000003 // Comparison Interrupt Mode
#define ADC_DCCTL5_CIM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL5_CIM_ONCE 0x00000001 // Once
#define ADC_DCCTL5_CIM_HALWAYS 0x00000002 // Hysteresis Always
#define ADC_DCCTL5_CIM_HONCE 0x00000003 // Hysteresis Once
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCTL6 register.
//
//*****************************************************************************
#define ADC_DCCTL6_CTE 0x00001000 // Comparison Trigger Enable
#define ADC_DCCTL6_CTC_M 0x00000C00 // Comparison Trigger Condition
#define ADC_DCCTL6_CTC_LOW 0x00000000 // Low Band
#define ADC_DCCTL6_CTC_MID 0x00000400 // Mid Band
#define ADC_DCCTL6_CTC_HIGH 0x00000C00 // High Band
#define ADC_DCCTL6_CTM_M 0x00000300 // Comparison Trigger Mode
#define ADC_DCCTL6_CTM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL6_CTM_ONCE 0x00000100 // Once
#define ADC_DCCTL6_CTM_HALWAYS 0x00000200 // Hysteresis Always
#define ADC_DCCTL6_CTM_HONCE 0x00000300 // Hysteresis Once
#define ADC_DCCTL6_CIE 0x00000010 // Comparison Interrupt Enable
#define ADC_DCCTL6_CIC_M 0x0000000C // Comparison Interrupt Condition
#define ADC_DCCTL6_CIC_LOW 0x00000000 // Low Band
#define ADC_DCCTL6_CIC_MID 0x00000004 // Mid Band
#define ADC_DCCTL6_CIC_HIGH 0x0000000C // High Band
#define ADC_DCCTL6_CIM_M 0x00000003 // Comparison Interrupt Mode
#define ADC_DCCTL6_CIM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL6_CIM_ONCE 0x00000001 // Once
#define ADC_DCCTL6_CIM_HALWAYS 0x00000002 // Hysteresis Always
#define ADC_DCCTL6_CIM_HONCE 0x00000003 // Hysteresis Once
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCTL7 register.
//
//*****************************************************************************
#define ADC_DCCTL7_CTE 0x00001000 // Comparison Trigger Enable
#define ADC_DCCTL7_CTC_M 0x00000C00 // Comparison Trigger Condition
#define ADC_DCCTL7_CTC_LOW 0x00000000 // Low Band
#define ADC_DCCTL7_CTC_MID 0x00000400 // Mid Band
#define ADC_DCCTL7_CTC_HIGH 0x00000C00 // High Band
#define ADC_DCCTL7_CTM_M 0x00000300 // Comparison Trigger Mode
#define ADC_DCCTL7_CTM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL7_CTM_ONCE 0x00000100 // Once
#define ADC_DCCTL7_CTM_HALWAYS 0x00000200 // Hysteresis Always
#define ADC_DCCTL7_CTM_HONCE 0x00000300 // Hysteresis Once
#define ADC_DCCTL7_CIE 0x00000010 // Comparison Interrupt Enable
#define ADC_DCCTL7_CIC_M 0x0000000C // Comparison Interrupt Condition
#define ADC_DCCTL7_CIC_LOW 0x00000000 // Low Band
#define ADC_DCCTL7_CIC_MID 0x00000004 // Mid Band
#define ADC_DCCTL7_CIC_HIGH 0x0000000C // High Band
#define ADC_DCCTL7_CIM_M 0x00000003 // Comparison Interrupt Mode
#define ADC_DCCTL7_CIM_ALWAYS 0x00000000 // Always
#define ADC_DCCTL7_CIM_ONCE 0x00000001 // Once
#define ADC_DCCTL7_CIM_HALWAYS 0x00000002 // Hysteresis Always
#define ADC_DCCTL7_CIM_HONCE 0x00000003 // Hysteresis Once
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCMP0 register.
//
//*****************************************************************************
#define ADC_DCCMP0_COMP1_M 0x0FFF0000 // Compare 1
#define ADC_DCCMP0_COMP0_M 0x00000FFF // Compare 0
#define ADC_DCCMP0_COMP1_S 16
#define ADC_DCCMP0_COMP0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCMP1 register.
//
//*****************************************************************************
#define ADC_DCCMP1_COMP1_M 0x0FFF0000 // Compare 1
#define ADC_DCCMP1_COMP0_M 0x00000FFF // Compare 0
#define ADC_DCCMP1_COMP1_S 16
#define ADC_DCCMP1_COMP0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCMP2 register.
//
//*****************************************************************************
#define ADC_DCCMP2_COMP1_M 0x0FFF0000 // Compare 1
#define ADC_DCCMP2_COMP0_M 0x00000FFF // Compare 0
#define ADC_DCCMP2_COMP1_S 16
#define ADC_DCCMP2_COMP0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCMP3 register.
//
//*****************************************************************************
#define ADC_DCCMP3_COMP1_M 0x0FFF0000 // Compare 1
#define ADC_DCCMP3_COMP0_M 0x00000FFF // Compare 0
#define ADC_DCCMP3_COMP1_S 16
#define ADC_DCCMP3_COMP0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCMP4 register.
//
//*****************************************************************************
#define ADC_DCCMP4_COMP1_M 0x0FFF0000 // Compare 1
#define ADC_DCCMP4_COMP0_M 0x00000FFF // Compare 0
#define ADC_DCCMP4_COMP1_S 16
#define ADC_DCCMP4_COMP0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCMP5 register.
//
//*****************************************************************************
#define ADC_DCCMP5_COMP1_M 0x0FFF0000 // Compare 1
#define ADC_DCCMP5_COMP0_M 0x00000FFF // Compare 0
#define ADC_DCCMP5_COMP1_S 16
#define ADC_DCCMP5_COMP0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCMP6 register.
//
//*****************************************************************************
#define ADC_DCCMP6_COMP1_M 0x0FFF0000 // Compare 1
#define ADC_DCCMP6_COMP0_M 0x00000FFF // Compare 0
#define ADC_DCCMP6_COMP1_S 16
#define ADC_DCCMP6_COMP0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_DCCMP7 register.
//
//*****************************************************************************
#define ADC_DCCMP7_COMP1_M 0x0FFF0000 // Compare 1
#define ADC_DCCMP7_COMP0_M 0x00000FFF // Compare 0
#define ADC_DCCMP7_COMP1_S 16
#define ADC_DCCMP7_COMP0_S 0
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_PP register.
//
//*****************************************************************************
#define ADC_PP_APSHT 0x01000000 // Application-Programmable
// Sample-and-Hold Time
#define ADC_PP_TS 0x00800000 // Temperature Sensor
#define ADC_PP_RSL_M 0x007C0000 // Resolution
#define ADC_PP_TYPE_M 0x00030000 // ADC Architecture
#define ADC_PP_TYPE_SAR 0x00000000 // SAR
#define ADC_PP_DC_M 0x0000FC00 // Digital Comparator Count
#define ADC_PP_CH_M 0x000003F0 // ADC Channel Count
#define ADC_PP_MCR_M 0x0000000F // Maximum Conversion Rate
#define ADC_PP_MCR_FULL 0x00000007 // Full conversion rate (FCONV) as
// defined by TADC and NSH
#define ADC_PP_MSR_M 0x0000000F // Maximum ADC Sample Rate
#define ADC_PP_MSR_125K 0x00000001 // 125 ksps
#define ADC_PP_MSR_250K 0x00000003 // 250 ksps
#define ADC_PP_MSR_500K 0x00000005 // 500 ksps
#define ADC_PP_MSR_1M 0x00000007 // 1 Msps
#define ADC_PP_RSL_S 18
#define ADC_PP_DC_S 10
#define ADC_PP_CH_S 4
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_PC register.
//
//*****************************************************************************
#define ADC_PC_SR_M 0x0000000F // ADC Sample Rate
#define ADC_PC_SR_125K 0x00000001 // 125 ksps
#define ADC_PC_SR_250K 0x00000003 // 250 ksps
#define ADC_PC_SR_500K 0x00000005 // 500 ksps
#define ADC_PC_SR_1M 0x00000007 // 1 Msps
#define ADC_PC_MCR_M 0x0000000F // Conversion Rate
#define ADC_PC_MCR_1_8 0x00000001 // Eighth conversion rate. After a
// conversion completes, the logic
// pauses for 112 TADC periods
// before starting the next
// conversion
#define ADC_PC_MCR_1_4 0x00000003 // Quarter conversion rate. After a
// conversion completes, the logic
// pauses for 48 TADC periods
// before starting the next
// conversion
#define ADC_PC_MCR_1_2 0x00000005 // Half conversion rate. After a
// conversion completes, the logic
// pauses for 16 TADC periods
// before starting the next
// conversion
#define ADC_PC_MCR_FULL 0x00000007 // Full conversion rate (FCONV) as
// defined by TADC and NSH
//*****************************************************************************
//
// The following are defines for the bit fields in the ADC_O_CC register.
//
//*****************************************************************************
#define ADC_CC_CLKDIV_M 0x000003F0 // PLL VCO Clock Divisor
#define ADC_CC_CS_M 0x0000000F // ADC Clock Source
#define ADC_CC_CS_SYSPLL 0x00000000 // PLL VCO divided by CLKDIV
#define ADC_CC_CS_PIOSC 0x00000001 // PIOSC
#define ADC_CC_CS_MOSC 0x00000002 // MOSC
#define ADC_CC_CLKDIV_S 4
#endif // __HW_ADC_H__
| apache-2.0 |
MatrixFrog/closure-compiler | externs/browser/intersection_observer.js | 6017 | /*
* Copyright 2016 The Closure Compiler Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Externs for Intersection Observer objects.
* @see https://wicg.github.io/IntersectionObserver/
* @externs
*/
// TODO(user): Once the Intersection Observer spec is adopted by W3C, add
// a w3c_ prefix to this file's name.
/**
* These contain the information provided from a change event.
* @see https://wicg.github.io/IntersectionObserver/#intersection-observer-entry
* @record
*/
function IntersectionObserverEntry() {}
/**
* The time the change was observed.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-time
* @type {number}
* @const
*/
IntersectionObserverEntry.prototype.time;
/**
* The root intersection rectangle, if target belongs to the same unit of
* related similar-origin browsing contexts as the intersection root, null
* otherwise.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-rootbounds
* @type {{top: number, right: number, bottom: number, left: number,
* height: number, width: number}}
* @const
*/
IntersectionObserverEntry.prototype.rootBounds;
/**
* The rectangle describing the element being observed.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-boundingclientrect
* @type {!{top: number, right: number, bottom: number, left: number,
* height: number, width: number}}
* @const
*/
IntersectionObserverEntry.prototype.boundingClientRect;
/**
* The rectangle describing the intersection between the observed element and
* the viewport.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-intersectionrect
* @type {!{top: number, right: number, bottom: number, left: number,
* height: number, width: number}}
* @const
*/
IntersectionObserverEntry.prototype.intersectionRect;
/**
* Ratio of intersectionRect area to boundingClientRect area.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-intersectionratio
* @type {!number}
* @const
*/
IntersectionObserverEntry.prototype.intersectionRatio;
/**
* The Element whose intersection with the intersection root changed.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-target
* @type {!Element}
* @const
*/
IntersectionObserverEntry.prototype.target;
/**
* Whether or not the target is intersecting with the root.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserverentry-isintersecting
* @type {boolean}
* @const
*/
IntersectionObserverEntry.prototype.isIntersecting;
/**
* Callback for the IntersectionObserver.
* @see https://wicg.github.io/IntersectionObserver/#intersection-observer-callback
* @typedef {function(!Array<!IntersectionObserverEntry>,!IntersectionObserver)}
*/
var IntersectionObserverCallback;
/**
* Options for the IntersectionObserver.
* @see https://wicg.github.io/IntersectionObserver/#intersection-observer-init
* @typedef {{
* threshold: (!Array<number>|number|undefined),
* root: (!Element|undefined),
* rootMargin: (string|undefined)
* }}
*/
var IntersectionObserverInit;
/**
* This is the constructor for Intersection Observer objects.
* @see https://wicg.github.io/IntersectionObserver/#intersection-observer-interface
* @param {!IntersectionObserverCallback} handler The callback for the observer.
* @param {!IntersectionObserverInit=} opt_options The object defining the
* thresholds, etc.
* @constructor
*/
function IntersectionObserver(handler, opt_options) {};
/**
* The root Element to use for intersection, or null if the observer uses the
* implicit root.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-root
* @type {?Element}
* @const
*/
IntersectionObserver.prototype.root;
/**
* Offsets applied to the intersection root’s bounding box, effectively growing
* or shrinking the box that is used to calculate intersections.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-rootmargin
* @type {!string}
* @const
*/
IntersectionObserver.prototype.rootMargin;
/**
* A list of thresholds, sorted in increasing numeric order, where each
* threshold is a ratio of intersection area to bounding box area of an observed
* target.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-thresholds
* @type {!Array.<!number>}
* @const
*/
IntersectionObserver.prototype.thresholds;
/**
* This is used to set which element to observe.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-observe
* @param {!Element} element The element to observe.
* @return {undefined}
*/
IntersectionObserver.prototype.observe = function(element) {};
/**
* This is used to stop observing a given element.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-unobserve
* @param {!Element} element The elmenent to stop observing.
* @return {undefined}
*/
IntersectionObserver.prototype.unobserve = function(element) {};
/**
* Disconnect.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-disconnect
*/
IntersectionObserver.prototype.disconnect = function() {};
/**
* Take records.
* @see https://wicg.github.io/IntersectionObserver/#dom-intersectionobserver-takerecords
* @return {!Array.<!IntersectionObserverEntry>}
*/
IntersectionObserver.prototype.takeRecords = function() {};
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/java/findJavaMethodUsages/JavaWithGroovyInvoke.0.java | 257 | // PSI_ELEMENT: com.intellij.psi.PsiMethod
// OPTIONS: usages
// PLAIN_WHEN_NEEDED
public class JavaWithGroovyInvoke_0 {
public void <caret>invoke() {
}
public static class OtherJavaClass extends JavaWithGroovyInvoke_0 {
}
}
// CRI_IGNORE | apache-2.0 |
lakshani/carbon-identity | components/application-mgt/org.wso2.carbon.identity.application.common/src/test/java/org/wso2/carbon/identity/application/common/model/test/ProvisioningConnectorConfigTest.java | 2091 | /*
* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.wso2.carbon.identity.application.common.model.test;
import org.junit.Test;
import org.wso2.carbon.identity.application.common.model.Property;
import org.wso2.carbon.identity.application.common.model.ProvisioningConnectorConfig;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertFalse;
/**
* Testing the ProvisioningConnectorConfig class
*/
public class ProvisioningConnectorConfigTest {
@Test
public void shouldGenerateDifferentHashCodesForDifferentNames() {
ProvisioningConnectorConfig config1 = new ProvisioningConnectorConfig();
config1.setName("Name1");
config1.setProvisioningProperties(new Property[0]);
ProvisioningConnectorConfig config2 = new ProvisioningConnectorConfig();
config2.setName("Name2");
config2.setProvisioningProperties(new Property[0]);
assertNotEquals(config1.hashCode(), config2.hashCode());
}
@Test
public void shouldReturnFalseByEqualsForDifferentNames() {
ProvisioningConnectorConfig config1 = new ProvisioningConnectorConfig();
config1.setName("Name1");
config1.setProvisioningProperties(new Property[0]);
ProvisioningConnectorConfig config2 = new ProvisioningConnectorConfig();
config2.setName("Name2");
config2.setProvisioningProperties(new Property[0]);
assertFalse(config1.equals(config2));
}
}
| apache-2.0 |
sdmcraft/jackrabbit | jackrabbit-jca/src/test/java/org/apache/jackrabbit/jca/test/ConnectionRequestInfoTest.java | 2835 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.jackrabbit.jca.test;
import org.apache.jackrabbit.jca.JCAConnectionRequestInfo;
import javax.jcr.SimpleCredentials;
import java.util.HashMap;
/**
* This case executes tests on the connection request info.
*/
public final class ConnectionRequestInfoTest
extends AbstractTestCase {
private SimpleCredentials creds1 = new SimpleCredentials("user", "password".toCharArray());
private SimpleCredentials creds2 = new SimpleCredentials("user", "password".toCharArray());
private SimpleCredentials creds3 = new SimpleCredentials("another_user", "password".toCharArray());
private JCAConnectionRequestInfo info1 = new JCAConnectionRequestInfo(creds1, "default");
private JCAConnectionRequestInfo info2 = new JCAConnectionRequestInfo(creds2, "default");
private JCAConnectionRequestInfo info3 = new JCAConnectionRequestInfo(creds3, "default");
/**
* Test the JCAConnectionRequestInfo equals() method.
*/
public void testEquals() throws Exception {
assertEquals("Object must be equal to itself", info1, info1);
assertEquals("Infos with the same auth data must be equal", info1, info2);
assertTrue("Infos with different auth data must not be equal", !info1.equals(info3));
}
/**
* Test the JCAConnectionRequestInfo hashCode() method.
*/
public void testHashCode() throws Exception {
assertEquals("Object must be equal to itself", info1.hashCode(), info1.hashCode());
assertEquals("Infos with the same auth data must have same hashCode", info1.hashCode(), info2.hashCode());
assertTrue("Infos with different auth data must not have same hashCode", info1.hashCode() != info3.hashCode());
}
/**
* Tests that JCAConnectionRequestInfo works as a HashMap key correctly.
*/
public void testPutToHashMap() throws Exception {
HashMap map = new HashMap();
map.put(info1, new Object());
assertTrue("Map must contain the info", map.containsKey(info2));
}
}
| apache-2.0 |
chhsia0/mesos | src/tests/resource_provider_validation_tests.cpp | 3426 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
#include <gtest/gtest.h>
#include <mesos/mesos.hpp>
#include <mesos/resource_provider/resource_provider.hpp>
#include <stout/error.hpp>
#include <stout/gtest.hpp>
#include <stout/option.hpp>
#include <stout/uuid.hpp>
#include "common/protobuf_utils.hpp"
#include "resource_provider/validation.hpp"
namespace call = mesos::internal::resource_provider::validation::call;
using mesos::resource_provider::Call;
namespace mesos {
namespace internal {
namespace tests {
TEST(ResourceProviderCallValidationTest, Subscribe)
{
Call call;
call.set_type(Call::SUBSCRIBE);
// Expecting `Call::Subscribe`.
Option<Error> error = call::validate(call);
EXPECT_SOME(error);
Call::Subscribe* subscribe = call.mutable_subscribe();
ResourceProviderInfo* info = subscribe->mutable_resource_provider_info();
info->set_type("org.apache.mesos.rp.test");
info->set_name("test");
error = call::validate(call);
EXPECT_NONE(error);
}
TEST(ResourceProviderCallValidationTest, UpdateOperationStatus)
{
Call call;
call.set_type(Call::UPDATE_OPERATION_STATUS);
// Expecting a resource provider ID and `Call::UpdateOperationStatus`.
Option<Error> error = call::validate(call);
EXPECT_SOME(error);
ResourceProviderID* id = call.mutable_resource_provider_id();
id->set_value(id::UUID::random().toString());
// Still expecting `Call::UpdateOperationStatus`.
error = call::validate(call);
EXPECT_SOME(error);
Call::UpdateOperationStatus* update =
call.mutable_update_operation_status();
update->mutable_framework_id()->set_value(id::UUID::random().toString());
update->mutable_operation_uuid()->CopyFrom(protobuf::createUUID());
OperationStatus* status = update->mutable_status();
status->mutable_operation_id()->set_value(id::UUID::random().toString());
status->set_state(OPERATION_FINISHED);
error = call::validate(call);
EXPECT_NONE(error);
}
TEST(ResourceProviderCallValidationTest, UpdateState)
{
Call call;
call.set_type(Call::UPDATE_STATE);
// Expecting a resource provider ID and `Call::UpdateState`.
Option<Error> error = call::validate(call);
EXPECT_SOME(error);
ResourceProviderID* id = call.mutable_resource_provider_id();
id->set_value(id::UUID::random().toString());
// Still expecting `Call::UpdateState`.
error = call::validate(call);
EXPECT_SOME(error);
Call::UpdateState* updateState = call.mutable_update_state();
updateState->mutable_resource_version_uuid()->CopyFrom(
protobuf::createUUID());
error = call::validate(call);
EXPECT_NONE(error);
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
| apache-2.0 |
raffaelespazzoli/origin | pkg/authorization/registry/rolebinding/proxy.go | 4978 | package rolebinding
import (
apierrors "k8s.io/apimachinery/pkg/api/errors"
metainternal "k8s.io/apimachinery/pkg/apis/meta/internalversion"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/runtime"
apirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
restclient "k8s.io/client-go/rest"
rbacinternalversion "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/rbac/internalversion"
authclient "github.com/openshift/origin/pkg/auth/client"
authorizationapi "github.com/openshift/origin/pkg/authorization/apis/authorization"
"github.com/openshift/origin/pkg/authorization/registry/util"
utilregistry "github.com/openshift/origin/pkg/util/registry"
)
type REST struct {
privilegedClient restclient.Interface
}
var _ rest.Lister = &REST{}
var _ rest.Getter = &REST{}
var _ rest.CreaterUpdater = &REST{}
var _ rest.GracefulDeleter = &REST{}
func NewREST(client restclient.Interface) utilregistry.NoWatchStorage {
return utilregistry.WrapNoWatchStorageError(&REST{privilegedClient: client})
}
func (s *REST) New() runtime.Object {
return &authorizationapi.RoleBinding{}
}
func (s *REST) NewList() runtime.Object {
return &authorizationapi.RoleBindingList{}
}
func (s *REST) List(ctx apirequest.Context, options *metainternal.ListOptions) (runtime.Object, error) {
client, err := s.getImpersonatingClient(ctx)
if err != nil {
return nil, err
}
optv1 := metav1.ListOptions{}
if err := metainternal.Convert_internalversion_ListOptions_To_v1_ListOptions(options, &optv1, nil); err != nil {
return nil, err
}
bindings, err := client.List(optv1)
if err != nil {
return nil, err
}
ret := &authorizationapi.RoleBindingList{}
for _, curr := range bindings.Items {
role, err := util.RoleBindingFromRBAC(&curr)
if err != nil {
return nil, err
}
ret.Items = append(ret.Items, *role)
}
ret.ListMeta.ResourceVersion = bindings.ResourceVersion
return ret, nil
}
func (s *REST) Get(ctx apirequest.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {
client, err := s.getImpersonatingClient(ctx)
if err != nil {
return nil, err
}
ret, err := client.Get(name, *options)
if err != nil {
return nil, err
}
binding, err := util.RoleBindingFromRBAC(ret)
if err != nil {
return nil, err
}
return binding, nil
}
func (s *REST) Delete(ctx apirequest.Context, name string, options *metav1.DeleteOptions) (runtime.Object, bool, error) {
client, err := s.getImpersonatingClient(ctx)
if err != nil {
return nil, false, err
}
if err := client.Delete(name, options); err != nil {
return nil, false, err
}
return &metav1.Status{Status: metav1.StatusSuccess}, true, nil
}
func (s *REST) Create(ctx apirequest.Context, obj runtime.Object, _ bool) (runtime.Object, error) {
client, err := s.getImpersonatingClient(ctx)
if err != nil {
return nil, err
}
rb := obj.(*authorizationapi.RoleBinding)
// Default the namespace if it is not specified so conversion does not error
// Normally this is done during the REST strategy but we avoid those here to keep the proxies simple
if ns, ok := apirequest.NamespaceFrom(ctx); ok && len(ns) > 0 && len(rb.Namespace) == 0 && len(rb.RoleRef.Namespace) > 0 {
deepcopiedObj := rb.DeepCopy()
deepcopiedObj.Namespace = ns
rb = deepcopiedObj
}
convertedObj, err := util.RoleBindingToRBAC(rb)
if err != nil {
return nil, err
}
ret, err := client.Create(convertedObj)
if err != nil {
return nil, err
}
binding, err := util.RoleBindingFromRBAC(ret)
if err != nil {
return nil, err
}
return binding, nil
}
func (s *REST) Update(ctx apirequest.Context, name string, objInfo rest.UpdatedObjectInfo) (runtime.Object, bool, error) {
client, err := s.getImpersonatingClient(ctx)
if err != nil {
return nil, false, err
}
old, err := client.Get(name, metav1.GetOptions{})
if err != nil {
return nil, false, err
}
oldRoleBinding, err := util.RoleBindingFromRBAC(old)
if err != nil {
return nil, false, err
}
obj, err := objInfo.UpdatedObject(ctx, oldRoleBinding)
if err != nil {
return nil, false, err
}
updatedRoleBinding, err := util.RoleBindingToRBAC(obj.(*authorizationapi.RoleBinding))
if err != nil {
return nil, false, err
}
ret, err := client.Update(updatedRoleBinding)
if err != nil {
return nil, false, err
}
role, err := util.RoleBindingFromRBAC(ret)
if err != nil {
return nil, false, err
}
return role, false, err
}
func (s *REST) getImpersonatingClient(ctx apirequest.Context) (rbacinternalversion.RoleBindingInterface, error) {
namespace, ok := apirequest.NamespaceFrom(ctx)
if !ok {
return nil, apierrors.NewBadRequest("namespace parameter required")
}
rbacClient, err := authclient.NewImpersonatingRBACFromContext(ctx, s.privilegedClient)
if err != nil {
return nil, err
}
return rbacClient.RoleBindings(namespace), nil
}
var cloner = conversion.NewCloner()
| apache-2.0 |
xingwu1/azure-sdk-for-node | lib/services/recoveryServicesBackupManagement/lib/models/dPMProtectedItemExtendedInfo.js | 5048 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Additional information of DPM Protected item.
*
*/
class DPMProtectedItemExtendedInfo {
/**
* Create a DPMProtectedItemExtendedInfo.
* @member {object} [protectableObjectLoadPath] Attribute to provide
* information on various DBs.
* @member {boolean} [protectedProperty] To check if backup item is disk
* protected.
* @member {boolean} [isPresentOnCloud] To check if backup item is cloud
* protected.
* @member {string} [lastBackupStatus] Last backup status information on
* backup item.
* @member {date} [lastRefreshedAt] Last refresh time on backup item.
* @member {date} [oldestRecoveryPoint] Oldest cloud recovery point time.
* @member {number} [recoveryPointCount] cloud recovery point count.
* @member {date} [onPremiseOldestRecoveryPoint] Oldest disk recovery point
* time.
* @member {date} [onPremiseLatestRecoveryPoint] latest disk recovery point
* time.
* @member {number} [onPremiseRecoveryPointCount] disk recovery point count.
* @member {boolean} [isCollocated] To check if backup item is collocated.
* @member {string} [protectionGroupName] Protection group name of the backup
* item.
* @member {string} [diskStorageUsedInBytes] Used Disk storage in bytes.
* @member {string} [totalDiskStorageSizeInBytes] total Disk storage in
* bytes.
*/
constructor() {
}
/**
* Defines the metadata of DPMProtectedItemExtendedInfo
*
* @returns {object} metadata of DPMProtectedItemExtendedInfo
*
*/
mapper() {
return {
required: false,
serializedName: 'DPMProtectedItemExtendedInfo',
type: {
name: 'Composite',
className: 'DPMProtectedItemExtendedInfo',
modelProperties: {
protectableObjectLoadPath: {
required: false,
serializedName: 'protectableObjectLoadPath',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
protectedProperty: {
required: false,
serializedName: 'protected',
type: {
name: 'Boolean'
}
},
isPresentOnCloud: {
required: false,
serializedName: 'isPresentOnCloud',
type: {
name: 'Boolean'
}
},
lastBackupStatus: {
required: false,
serializedName: 'lastBackupStatus',
type: {
name: 'String'
}
},
lastRefreshedAt: {
required: false,
serializedName: 'lastRefreshedAt',
type: {
name: 'DateTime'
}
},
oldestRecoveryPoint: {
required: false,
serializedName: 'oldestRecoveryPoint',
type: {
name: 'DateTime'
}
},
recoveryPointCount: {
required: false,
serializedName: 'recoveryPointCount',
type: {
name: 'Number'
}
},
onPremiseOldestRecoveryPoint: {
required: false,
serializedName: 'onPremiseOldestRecoveryPoint',
type: {
name: 'DateTime'
}
},
onPremiseLatestRecoveryPoint: {
required: false,
serializedName: 'onPremiseLatestRecoveryPoint',
type: {
name: 'DateTime'
}
},
onPremiseRecoveryPointCount: {
required: false,
serializedName: 'onPremiseRecoveryPointCount',
type: {
name: 'Number'
}
},
isCollocated: {
required: false,
serializedName: 'isCollocated',
type: {
name: 'Boolean'
}
},
protectionGroupName: {
required: false,
serializedName: 'protectionGroupName',
type: {
name: 'String'
}
},
diskStorageUsedInBytes: {
required: false,
serializedName: 'diskStorageUsedInBytes',
type: {
name: 'String'
}
},
totalDiskStorageSizeInBytes: {
required: false,
serializedName: 'totalDiskStorageSizeInBytes',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = DPMProtectedItemExtendedInfo;
| apache-2.0 |
apple/swift-lldb | source/Plugins/Process/Utility/FreeBSDSignals.cpp | 5613 | //===-- FreeBSDSignals.cpp --------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "FreeBSDSignals.h"
using namespace lldb_private;
FreeBSDSignals::FreeBSDSignals() : UnixSignals() { Reset(); }
void FreeBSDSignals::Reset() {
UnixSignals::Reset();
// SIGNO NAME SUPPRESS STOP NOTIFY DESCRIPTION
// ====== ============ ======== ====== ======
// ===================================================
AddSignal(32, "SIGTHR", false, false, false, "thread interrupt");
AddSignal(33, "SIGLIBRT", false, false, false,
"reserved by real-time library");
AddSignal(65, "SIGRTMIN", false, false, false, "real time signal 0");
AddSignal(66, "SIGRTMIN+1", false, false, false, "real time signal 1");
AddSignal(67, "SIGRTMIN+2", false, false, false, "real time signal 2");
AddSignal(68, "SIGRTMIN+3", false, false, false, "real time signal 3");
AddSignal(69, "SIGRTMIN+4", false, false, false, "real time signal 4");
AddSignal(70, "SIGRTMIN+5", false, false, false, "real time signal 5");
AddSignal(71, "SIGRTMIN+6", false, false, false, "real time signal 6");
AddSignal(72, "SIGRTMIN+7", false, false, false, "real time signal 7");
AddSignal(73, "SIGRTMIN+8", false, false, false, "real time signal 8");
AddSignal(74, "SIGRTMIN+9", false, false, false, "real time signal 9");
AddSignal(75, "SIGRTMIN+10", false, false, false, "real time signal 10");
AddSignal(76, "SIGRTMIN+11", false, false, false, "real time signal 11");
AddSignal(77, "SIGRTMIN+12", false, false, false, "real time signal 12");
AddSignal(78, "SIGRTMIN+13", false, false, false, "real time signal 13");
AddSignal(79, "SIGRTMIN+14", false, false, false, "real time signal 14");
AddSignal(80, "SIGRTMIN+15", false, false, false, "real time signal 15");
AddSignal(81, "SIGRTMIN+16", false, false, false, "real time signal 16");
AddSignal(82, "SIGRTMIN+17", false, false, false, "real time signal 17");
AddSignal(83, "SIGRTMIN+18", false, false, false, "real time signal 18");
AddSignal(84, "SIGRTMIN+19", false, false, false, "real time signal 19");
AddSignal(85, "SIGRTMIN+20", false, false, false, "real time signal 20");
AddSignal(86, "SIGRTMIN+21", false, false, false, "real time signal 21");
AddSignal(87, "SIGRTMIN+22", false, false, false, "real time signal 22");
AddSignal(88, "SIGRTMIN+23", false, false, false, "real time signal 23");
AddSignal(89, "SIGRTMIN+24", false, false, false, "real time signal 24");
AddSignal(90, "SIGRTMIN+25", false, false, false, "real time signal 25");
AddSignal(91, "SIGRTMIN+26", false, false, false, "real time signal 26");
AddSignal(92, "SIGRTMIN+27", false, false, false, "real time signal 27");
AddSignal(93, "SIGRTMIN+28", false, false, false, "real time signal 28");
AddSignal(94, "SIGRTMIN+29", false, false, false, "real time signal 29");
AddSignal(95, "SIGRTMIN+30", false, false, false, "real time signal 30");
AddSignal(96, "SIGRTMAX-30", false, false, false, "real time signal 31");
AddSignal(97, "SIGRTMAX-29", false, false, false, "real time signal 32");
AddSignal(98, "SIGRTMAX-28", false, false, false, "real time signal 33");
AddSignal(99, "SIGRTMAX-27", false, false, false, "real time signal 34");
AddSignal(100, "SIGRTMAX-26", false, false, false, "real time signal 35");
AddSignal(101, "SIGRTMAX-25", false, false, false, "real time signal 36");
AddSignal(102, "SIGRTMAX-24", false, false, false, "real time signal 37");
AddSignal(103, "SIGRTMAX-23", false, false, false, "real time signal 38");
AddSignal(104, "SIGRTMAX-22", false, false, false, "real time signal 39");
AddSignal(105, "SIGRTMAX-21", false, false, false, "real time signal 40");
AddSignal(106, "SIGRTMAX-20", false, false, false, "real time signal 41");
AddSignal(107, "SIGRTMAX-19", false, false, false, "real time signal 42");
AddSignal(108, "SIGRTMAX-18", false, false, false, "real time signal 43");
AddSignal(109, "SIGRTMAX-17", false, false, false, "real time signal 44");
AddSignal(110, "SIGRTMAX-16", false, false, false, "real time signal 45");
AddSignal(111, "SIGRTMAX-15", false, false, false, "real time signal 46");
AddSignal(112, "SIGRTMAX-14", false, false, false, "real time signal 47");
AddSignal(113, "SIGRTMAX-13", false, false, false, "real time signal 48");
AddSignal(114, "SIGRTMAX-12", false, false, false, "real time signal 49");
AddSignal(115, "SIGRTMAX-11", false, false, false, "real time signal 50");
AddSignal(116, "SIGRTMAX-10", false, false, false, "real time signal 51");
AddSignal(117, "SIGRTMAX-9", false, false, false, "real time signal 52");
AddSignal(118, "SIGRTMAX-8", false, false, false, "real time signal 53");
AddSignal(119, "SIGRTMAX-7", false, false, false, "real time signal 54");
AddSignal(120, "SIGRTMAX-6", false, false, false, "real time signal 55");
AddSignal(121, "SIGRTMAX-5", false, false, false, "real time signal 56");
AddSignal(122, "SIGRTMAX-4", false, false, false, "real time signal 57");
AddSignal(123, "SIGRTMAX-3", false, false, false, "real time signal 58");
AddSignal(124, "SIGRTMAX-2", false, false, false, "real time signal 59");
AddSignal(125, "SIGRTMAX-1", false, false, false, "real time signal 60");
AddSignal(126, "SIGRTMAX", false, false, false, "real time signal 61");
}
| apache-2.0 |
denov/dojo-demo | src/main/webapp/js/dijit/_editor/plugins/EnterKeyHandling.js | 22062 | define([
"dojo/_base/declare", // declare
"dojo/dom-construct", // domConstruct.destroy domConstruct.place
"dojo/keys", // keys.ENTER
"dojo/_base/lang",
"dojo/on",
"dojo/sniff", // has("ie") has("mozilla") has("webkit")
"dojo/_base/window", // win.withGlobal
"dojo/window", // winUtils.scrollIntoView
"../_Plugin",
"../RichText",
"../range",
"../../_base/focus"
], function(declare, domConstruct, keys, lang, on, has, win, winUtils, _Plugin, RichText, rangeapi, baseFocus){
// module:
// dijit/_editor/plugins/EnterKeyHandling
return declare("dijit._editor.plugins.EnterKeyHandling", _Plugin, {
// summary:
// This plugin tries to make all browsers behave consistently with regard to
// how ENTER behaves in the editor window. It traps the ENTER key and alters
// the way DOM is constructed in certain cases to try to commonize the generated
// DOM and behaviors across browsers.
//
// description:
// This plugin has three modes:
//
// - blockNodeForEnter=BR
// - blockNodeForEnter=DIV
// - blockNodeForEnter=P
//
// In blockNodeForEnter=P, the ENTER key starts a new
// paragraph, and shift-ENTER starts a new line in the current paragraph.
// For example, the input:
//
// | first paragraph <shift-ENTER>
// | second line of first paragraph <ENTER>
// | second paragraph
//
// will generate:
//
// | <p>
// | first paragraph
// | <br/>
// | second line of first paragraph
// | </p>
// | <p>
// | second paragraph
// | </p>
//
// In BR and DIV mode, the ENTER key conceptually goes to a new line in the
// current paragraph, and users conceptually create a new paragraph by pressing ENTER twice.
// For example, if the user enters text into an editor like this:
//
// | one <ENTER>
// | two <ENTER>
// | three <ENTER>
// | <ENTER>
// | four <ENTER>
// | five <ENTER>
// | six <ENTER>
//
// It will appear on the screen as two 'paragraphs' of three lines each. Markupwise, this generates:
//
// BR:
// | one<br/>
// | two<br/>
// | three<br/>
// | <br/>
// | four<br/>
// | five<br/>
// | six<br/>
//
// DIV:
// | <div>one</div>
// | <div>two</div>
// | <div>three</div>
// | <div> </div>
// | <div>four</div>
// | <div>five</div>
// | <div>six</div>
// blockNodeForEnter: String
// This property decides the behavior of Enter key. It can be either P,
// DIV, BR, or empty (which means disable this feature). Anything else
// will trigger errors. The default is 'BR'
//
// See class description for more details.
blockNodeForEnter: 'BR',
constructor: function(args){
if(args){
if("blockNodeForEnter" in args){
args.blockNodeForEnter = args.blockNodeForEnter.toUpperCase();
}
lang.mixin(this, args);
}
},
setEditor: function(editor){
// Overrides _Plugin.setEditor().
if(this.editor === editor){
return;
}
this.editor = editor;
if(this.blockNodeForEnter == 'BR'){
// While Moz has a mode tht mostly works, it's still a little different,
// So, try to just have a common mode and be consistent. Which means
// we need to enable customUndo, if not already enabled.
this.editor.customUndo = true;
editor.onLoadDeferred.then(lang.hitch(this, function(d){
this.own(on(editor.document, "keydown", lang.hitch(this, function(e){
if(e.keyCode == keys.ENTER){
// Just do it manually. The handleEnterKey has a shift mode that
// Always acts like <br>, so just use it.
var ne = lang.mixin({}, e);
ne.shiftKey = true;
if(!this.handleEnterKey(ne)){
e.stopPropagation();
e.preventDefault();
}
}
})));
if(has("ie") >= 9 && has("ie") <= 10){
this.own(on(editor.document, "paste", lang.hitch(this, function(e){
setTimeout(lang.hitch(this, function(){
// Use the old range/selection code to kick IE 9 into updating
// its range by moving it back, then forward, one 'character'.
var r = this.editor.document.selection.createRange();
r.move('character', -1);
r.select();
r.move('character', 1);
r.select();
}), 0);
})));
}
return d;
}));
}else if(this.blockNodeForEnter){
// add enter key handler
var h = lang.hitch(this, "handleEnterKey");
editor.addKeyHandler(13, 0, 0, h); //enter
editor.addKeyHandler(13, 0, 1, h); //shift+enter
this.own(this.editor.on('KeyPressed', lang.hitch(this, 'onKeyPressed')));
}
},
onKeyPressed: function(){
// summary:
// Handler for after the user has pressed a key, and the display has been updated.
// Connected to RichText's onKeyPressed() method.
// tags:
// private
if(this._checkListLater){
if(win.withGlobal(this.editor.window, 'isCollapsed', baseFocus)){ // TODO: stop using withGlobal(), and baseFocus
var liparent = this.editor.selection.getAncestorElement('LI');
if(!liparent){
// circulate the undo detection code by calling RichText::execCommand directly
RichText.prototype.execCommand.call(this.editor, 'formatblock', this.blockNodeForEnter);
// set the innerHTML of the new block node
var block = this.editor.selection.getAncestorElement(this.blockNodeForEnter);
if(block){
block.innerHTML = this.bogusHtmlContent;
if(has("ie") <= 9){
// move to the start by moving backwards one char
var r = this.editor.document.selection.createRange();
r.move('character', -1);
r.select();
}
}else{
console.error('onKeyPressed: Cannot find the new block node'); // FIXME
}
}else{
if(has("mozilla")){
if(liparent.parentNode.parentNode.nodeName == 'LI'){
liparent = liparent.parentNode.parentNode;
}
}
var fc = liparent.firstChild;
if(fc && fc.nodeType == 1 && (fc.nodeName == 'UL' || fc.nodeName == 'OL')){
liparent.insertBefore(fc.ownerDocument.createTextNode('\xA0'), fc);
var newrange = rangeapi.create(this.editor.window);
newrange.setStart(liparent.firstChild, 0);
var selection = rangeapi.getSelection(this.editor.window, true);
selection.removeAllRanges();
selection.addRange(newrange);
}
}
}
this._checkListLater = false;
}
if(this._pressedEnterInBlock){
// the new created is the original current P, so we have previousSibling below
if(this._pressedEnterInBlock.previousSibling){
this.removeTrailingBr(this._pressedEnterInBlock.previousSibling);
}
delete this._pressedEnterInBlock;
}
},
// bogusHtmlContent: [private] String
// HTML to stick into a new empty block
bogusHtmlContent: ' ', //
// blockNodes: [private] Regex
// Regex for testing if a given tag is a block level (display:block) tag
blockNodes: /^(?:P|H1|H2|H3|H4|H5|H6|LI)$/,
handleEnterKey: function(e){
// summary:
// Handler for enter key events when blockNodeForEnter is DIV or P.
// description:
// Manually handle enter key event to make the behavior consistent across
// all supported browsers. See class description for details.
// tags:
// private
var selection, range, newrange, startNode, endNode, brNode, doc = this.editor.document, br, rs, txt;
if(e.shiftKey){ // shift+enter always generates <br>
var parent = this.editor.selection.getParentElement();
var header = rangeapi.getAncestor(parent, this.blockNodes);
if(header){
if(header.tagName == 'LI'){
return true; // let browser handle
}
selection = rangeapi.getSelection(this.editor.window);
range = selection.getRangeAt(0);
if(!range.collapsed){
range.deleteContents();
selection = rangeapi.getSelection(this.editor.window);
range = selection.getRangeAt(0);
}
if(rangeapi.atBeginningOfContainer(header, range.startContainer, range.startOffset)){
br = doc.createElement('br');
newrange = rangeapi.create(this.editor.window);
header.insertBefore(br, header.firstChild);
newrange.setStartAfter(br);
selection.removeAllRanges();
selection.addRange(newrange);
}else if(rangeapi.atEndOfContainer(header, range.startContainer, range.startOffset)){
newrange = rangeapi.create(this.editor.window);
br = doc.createElement('br');
header.appendChild(br);
header.appendChild(doc.createTextNode('\xA0'));
newrange.setStart(header.lastChild, 0);
selection.removeAllRanges();
selection.addRange(newrange);
}else{
rs = range.startContainer;
if(rs && rs.nodeType == 3){
// Text node, we have to split it.
txt = rs.nodeValue;
startNode = doc.createTextNode(txt.substring(0, range.startOffset));
endNode = doc.createTextNode(txt.substring(range.startOffset));
brNode = doc.createElement("br");
if(endNode.nodeValue == "" && has("webkit")){
endNode = doc.createTextNode('\xA0')
}
domConstruct.place(startNode, rs, "after");
domConstruct.place(brNode, startNode, "after");
domConstruct.place(endNode, brNode, "after");
domConstruct.destroy(rs);
newrange = rangeapi.create(this.editor.window);
newrange.setStart(endNode, 0);
selection.removeAllRanges();
selection.addRange(newrange);
return false;
}
return true; // let browser handle
}
}else{
selection = rangeapi.getSelection(this.editor.window);
if(selection.rangeCount){
range = selection.getRangeAt(0);
if(range && range.startContainer){
if(!range.collapsed){
range.deleteContents();
selection = rangeapi.getSelection(this.editor.window);
range = selection.getRangeAt(0);
}
rs = range.startContainer;
if(rs && rs.nodeType == 3){
// Text node, we have to split it.
var endEmpty = false;
var offset = range.startOffset;
if(rs.length < offset){
//We are not splitting the right node, try to locate the correct one
ret = this._adjustNodeAndOffset(rs, offset);
rs = ret.node;
offset = ret.offset;
}
txt = rs.nodeValue;
startNode = doc.createTextNode(txt.substring(0, offset));
endNode = doc.createTextNode(txt.substring(offset));
brNode = doc.createElement("br");
if(!endNode.length){
endNode = doc.createTextNode('\xA0');
endEmpty = true;
}
if(startNode.length){
domConstruct.place(startNode, rs, "after");
}else{
startNode = rs;
}
domConstruct.place(brNode, startNode, "after");
domConstruct.place(endNode, brNode, "after");
domConstruct.destroy(rs);
newrange = rangeapi.create(this.editor.window);
newrange.setStart(endNode, 0);
newrange.setEnd(endNode, endNode.length);
selection.removeAllRanges();
selection.addRange(newrange);
if(endEmpty && !has("webkit")){
this.editor.selection.remove();
}else{
this.editor.selection.collapse(true);
}
}else{
var targetNode;
if(range.startOffset >= 0){
targetNode = rs.childNodes[range.startOffset];
}
var brNode = doc.createElement("br");
var endNode = doc.createTextNode('\xA0');
if(!targetNode){
rs.appendChild(brNode);
rs.appendChild(endNode);
}else{
domConstruct.place(brNode, targetNode, "before");
domConstruct.place(endNode, brNode, "after");
}
newrange = rangeapi.create(this.editor.window);
newrange.setStart(endNode, 0);
newrange.setEnd(endNode, endNode.length);
selection.removeAllRanges();
selection.addRange(newrange);
this.editor.selection.collapse(true);
}
}
}else{
// don't change this: do not call this.execCommand, as that may have other logic in subclass
RichText.prototype.execCommand.call(this.editor, 'inserthtml', '<br>');
}
}
return false;
}
var _letBrowserHandle = true;
// first remove selection
selection = rangeapi.getSelection(this.editor.window);
range = selection.getRangeAt(0);
if(!range.collapsed){
range.deleteContents();
selection = rangeapi.getSelection(this.editor.window);
range = selection.getRangeAt(0);
}
var block = rangeapi.getBlockAncestor(range.endContainer, null, this.editor.editNode);
var blockNode = block.blockNode;
// if this is under a LI or the parent of the blockNode is LI, just let browser to handle it
if((this._checkListLater = (blockNode && (blockNode.nodeName == 'LI' || blockNode.parentNode.nodeName == 'LI')))){
if(has("mozilla")){
// press enter in middle of P may leave a trailing <br/>, let's remove it later
this._pressedEnterInBlock = blockNode;
}
// if this li only contains spaces, set the content to empty so the browser will outdent this item
if(/^(\s| | |\xA0|<span\b[^>]*\bclass=['"]Apple-style-span['"][^>]*>(\s| | |\xA0)<\/span>)?(<br>)?$/.test(blockNode.innerHTML)){
// empty LI node
blockNode.innerHTML = '';
if(has("webkit")){ // WebKit tosses the range when innerHTML is reset
newrange = rangeapi.create(this.editor.window);
newrange.setStart(blockNode, 0);
selection.removeAllRanges();
selection.addRange(newrange);
}
this._checkListLater = false; // nothing to check since the browser handles outdent
}
return true;
}
// text node directly under body, let's wrap them in a node
if(!block.blockNode || block.blockNode === this.editor.editNode){
try{
RichText.prototype.execCommand.call(this.editor, 'formatblock', this.blockNodeForEnter);
}catch(e2){ /*squelch FF3 exception bug when editor content is a single BR*/
}
// get the newly created block node
// FIXME
block = {blockNode: this.editor.selection.getAncestorElement(this.blockNodeForEnter),
blockContainer: this.editor.editNode};
if(block.blockNode){
if(block.blockNode != this.editor.editNode &&
(!(block.blockNode.textContent || block.blockNode.innerHTML).replace(/^\s+|\s+$/g, "").length)){
this.removeTrailingBr(block.blockNode);
return false;
}
}else{ // we shouldn't be here if formatblock worked
block.blockNode = this.editor.editNode;
}
selection = rangeapi.getSelection(this.editor.window);
range = selection.getRangeAt(0);
}
var newblock = doc.createElement(this.blockNodeForEnter);
newblock.innerHTML = this.bogusHtmlContent;
this.removeTrailingBr(block.blockNode);
var endOffset = range.endOffset;
var node = range.endContainer;
if(node.length < endOffset){
//We are not checking the right node, try to locate the correct one
var ret = this._adjustNodeAndOffset(node, endOffset);
node = ret.node;
endOffset = ret.offset;
}
if(rangeapi.atEndOfContainer(block.blockNode, node, endOffset)){
if(block.blockNode === block.blockContainer){
block.blockNode.appendChild(newblock);
}else{
domConstruct.place(newblock, block.blockNode, "after");
}
_letBrowserHandle = false;
// lets move caret to the newly created block
newrange = rangeapi.create(this.editor.window);
newrange.setStart(newblock, 0);
selection.removeAllRanges();
selection.addRange(newrange);
if(this.editor.height){
winUtils.scrollIntoView(newblock);
}
}else if(rangeapi.atBeginningOfContainer(block.blockNode,
range.startContainer, range.startOffset)){
domConstruct.place(newblock, block.blockNode, block.blockNode === block.blockContainer ? "first" : "before");
if(newblock.nextSibling && this.editor.height){
// position input caret - mostly WebKit needs this
newrange = rangeapi.create(this.editor.window);
newrange.setStart(newblock.nextSibling, 0);
selection.removeAllRanges();
selection.addRange(newrange);
// browser does not scroll the caret position into view, do it manually
winUtils.scrollIntoView(newblock.nextSibling);
}
_letBrowserHandle = false;
}else{ //press enter in the middle of P/DIV/Whatever/
if(block.blockNode === block.blockContainer){
block.blockNode.appendChild(newblock);
}else{
domConstruct.place(newblock, block.blockNode, "after");
}
_letBrowserHandle = false;
// Clone any block level styles.
if(block.blockNode.style){
if(newblock.style){
if(block.blockNode.style.cssText){
newblock.style.cssText = block.blockNode.style.cssText;
}
}
}
// Okay, we probably have to split.
rs = range.startContainer;
var firstNodeMoved;
if(rs && rs.nodeType == 3){
// Text node, we have to split it.
var nodeToMove, tNode;
endOffset = range.endOffset;
if(rs.length < endOffset){
//We are not splitting the right node, try to locate the correct one
ret = this._adjustNodeAndOffset(rs, endOffset);
rs = ret.node;
endOffset = ret.offset;
}
txt = rs.nodeValue;
startNode = doc.createTextNode(txt.substring(0, endOffset));
endNode = doc.createTextNode(txt.substring(endOffset, txt.length));
// Place the split, then remove original nodes.
domConstruct.place(startNode, rs, "before");
domConstruct.place(endNode, rs, "after");
domConstruct.destroy(rs);
// Okay, we split the text. Now we need to see if we're
// parented to the block element we're splitting and if
// not, we have to split all the way up. Ugh.
var parentC = startNode.parentNode;
while(parentC !== block.blockNode){
var tg = parentC.tagName;
var newTg = doc.createElement(tg);
// Clone over any 'style' data.
if(parentC.style){
if(newTg.style){
if(parentC.style.cssText){
newTg.style.cssText = parentC.style.cssText;
}
}
}
// If font also need to clone over any font data.
if(parentC.tagName === "FONT"){
if(parentC.color){
newTg.color = parentC.color;
}
if(parentC.face){
newTg.face = parentC.face;
}
if(parentC.size){ // this check was necessary on IE
newTg.size = parentC.size;
}
}
nodeToMove = endNode;
while(nodeToMove){
tNode = nodeToMove.nextSibling;
newTg.appendChild(nodeToMove);
nodeToMove = tNode;
}
domConstruct.place(newTg, parentC, "after");
startNode = parentC;
endNode = newTg;
parentC = parentC.parentNode;
}
// Lastly, move the split out tags to the new block.
// as they should now be split properly.
nodeToMove = endNode;
if(nodeToMove.nodeType == 1 || (nodeToMove.nodeType == 3 && nodeToMove.nodeValue)){
// Non-blank text and non-text nodes need to clear out that blank space
// before moving the contents.
newblock.innerHTML = "";
}
firstNodeMoved = nodeToMove;
while(nodeToMove){
tNode = nodeToMove.nextSibling;
newblock.appendChild(nodeToMove);
nodeToMove = tNode;
}
}
//lets move caret to the newly created block
newrange = rangeapi.create(this.editor.window);
var nodeForCursor;
var innerMostFirstNodeMoved = firstNodeMoved;
if(this.blockNodeForEnter !== 'BR'){
while(innerMostFirstNodeMoved){
nodeForCursor = innerMostFirstNodeMoved;
tNode = innerMostFirstNodeMoved.firstChild;
innerMostFirstNodeMoved = tNode;
}
if(nodeForCursor && nodeForCursor.parentNode){
newblock = nodeForCursor.parentNode;
newrange.setStart(newblock, 0);
selection.removeAllRanges();
selection.addRange(newrange);
if(this.editor.height){
winUtils.scrollIntoView(newblock);
}
if(has("mozilla")){
// press enter in middle of P may leave a trailing <br/>, let's remove it later
this._pressedEnterInBlock = block.blockNode;
}
}else{
_letBrowserHandle = true;
}
}else{
newrange.setStart(newblock, 0);
selection.removeAllRanges();
selection.addRange(newrange);
if(this.editor.height){
winUtils.scrollIntoView(newblock);
}
if(has("mozilla")){
// press enter in middle of P may leave a trailing <br/>, let's remove it later
this._pressedEnterInBlock = block.blockNode;
}
}
}
return _letBrowserHandle;
},
_adjustNodeAndOffset: function(/*DomNode*/node, /*Int*/offset){
// summary:
// In the case there are multiple text nodes in a row the offset may not be within the node. If the offset is larger than the node length, it will attempt to find
// the next text sibling until it locates the text node in which the offset refers to
// node:
// The node to check.
// offset:
// The position to find within the text node
// tags:
// private.
while(node.length < offset && node.nextSibling && node.nextSibling.nodeType == 3){
//Adjust the offset and node in the case of multiple text nodes in a row
offset = offset - node.length;
node = node.nextSibling;
}
return {"node": node, "offset": offset};
},
removeTrailingBr: function(container){
// summary:
// If last child of container is a `<br>`, then remove it.
// tags:
// private
var para = /P|DIV|LI/i.test(container.tagName) ?
container : this.editor.selection.getParentOfType(container, ['P', 'DIV', 'LI']);
if(!para){
return;
}
if(para.lastChild){
if((para.childNodes.length > 1 && para.lastChild.nodeType == 3 && /^[\s\xAD]*$/.test(para.lastChild.nodeValue)) ||
para.lastChild.tagName == 'BR'){
domConstruct.destroy(para.lastChild);
}
}
if(!para.childNodes.length){
para.innerHTML = this.bogusHtmlContent;
}
}
});
});
| apache-2.0 |
x-hansong/aSpice | src/com/iiordanov/bVNC/COLORMODEL.java | 3262 | /**
* Copyright (C) 2012 Iordan Iordanov
* Copyright (C) 2010 Michael A. MacDonald
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
package com.iiordanov.bVNC;
import java.io.IOException;
public enum COLORMODEL {
C24bit, C256, C64, C8, C4, C2;
public int bpp() {
switch (this) {
case C24bit:
return 4;
default:
return 1;
}
}
public int[] palette() {
switch (this) {
case C24bit:
return null;
case C256:
return ColorModel256.colors;
case C64:
return ColorModel64.colors;
case C8:
return ColorModel8.colors;
case C4:
return ColorModel64.colors;
case C2:
return ColorModel8.colors;
default:
return null;
}
}
public String nameString()
{
return super.toString();
}
public void setPixelFormat(RfbConnectable rfb) throws IOException {
switch (this) {
case C24bit:
// 24-bit color
rfb.writeSetPixelFormat(32, 24, false, true, 255, 255, 255, 16, 8, 0, false);
break;
case C256:
rfb.writeSetPixelFormat(8, 8, false, true, 7, 7, 3, 0, 3, 6, false);
break;
case C64:
rfb.writeSetPixelFormat(8, 6, false, true, 3, 3, 3, 4, 2, 0, false);
break;
case C8:
rfb.writeSetPixelFormat(8, 3, false, true, 1, 1, 1, 2, 1, 0, false);
break;
case C4:
// Greyscale
rfb.writeSetPixelFormat(8, 6, false, true, 3, 3, 3, 4, 2, 0, true);
break;
case C2:
// B&W
rfb.writeSetPixelFormat(8, 3, false, true, 1, 1, 1, 2, 1, 0, true);
break;
default:
// Default is 24 bit color
rfb.writeSetPixelFormat(32, 24, false, true, 255, 255, 255, 16, 8, 0, false);
break;
}
}
public String toString() {
switch (this) {
case C24bit:
return "24-bit color (4 bpp)";
case C256:
return "256 colors (1 bpp)";
case C64:
return "64 colors (1 bpp)";
case C8:
return "8 colors (1 bpp)";
case C4:
return "Greyscale (1 bpp)";
case C2:
return "Black & White (1 bpp)";
default:
return "24-bit color (4 bpp)";
}
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.