text:
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * DB_Table_Generator - Generates DB_Table subclass skeleton code
 *
 * Parts of this class were adopted from the DB_DataObject PEAR package.
 *
 * PHP versions 4 and 5
 *
 * LICENSE:
 *
 * Copyright (c) 1997-2007, Paul M. Jones <pmjones@php.net>
 *                          Alan Knowles <alan@akbkhome.com>
 *                          David C. Morse <morse@php.net>
 *                          Mark Wiesemann <wiesemann@php.net>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *    * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *    * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *    * The names of the authors may not 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.
 *
 * @category Database
 * @package  DB_Table
 * @author   Alan Knowles <alan@akbkhome.com>
 * @author   David C. Morse <morse@php.net>
 * @license  http://opensource.org/licenses/bsd-license.php New BSD License
 * @version  CVS: $Id: Generator.php,v 1.17 2008/05/14 18:36:27 wiesemann Exp $
 * @link     http://pear.php.net/package/DB_Table
 */

// {{{ Includes

/**#@+
 * Include basic classes
 */
/**
 * The PEAR class (used for errors)
 */
require_once 'PEAR.php';

/**
 * DB_Table table abstraction class
 */
require_once 'DB/Table.php';

/**
 * DB_Table_Manager class (used to reverse engineer indices)
 */
require_once 'DB/Table/Manager.php';
/**#@-*/

// }}}
// {{{ Error code constants

/**#@+
 * Error codes
 */
/**
 * Parameter is not a DB/MDB2 object
 */
define('DB_TABLE_GENERATOR_ERR_DB_OBJECT', -301);

/**
 * Parameter is not a DB/MDB2 object
 */
define('DB_TABLE_GENERATOR_ERR_INDEX_COL', -302);

/**
 * Error while creating file/directory
 */
define('DB_TABLE_GENERATOR_ERR_FILE', -303);
/**#@-*/

// }}}
// {{{ Error messages
/**
 * US-English default error messages.
 */
$GLOBALS['_DB_TABLE_GENERATOR']['default_error'] = array(
        DB_TABLE_GENERATOR_ERR_DB_OBJECT =>
            'Invalid DB/MDB2 object parameter. Function',
        DB_TABLE_GENERATOR_ERR_INDEX_COL =>
            'Index column is not a valid column name. Index column',
        DB_TABLE_GENERATOR_ERR_FILE =>
            'Can\'t create file/directory:'
);

// merge default and user-defined error messages
if (!isset($GLOBALS['_DB_TABLE_GENERATOR']['error'])) {
    $GLOBALS['_DB_TABLE_GENERATOR']['error'] = array();
}
foreach ($GLOBALS['_DB_TABLE_GENERATOR']['default_error'] as $code => $message) {
    if (!array_key_exists($code, $GLOBALS['_DB_TABLE_GENERATOR']['error'])) {
        $GLOBALS['_DB_TABLE_GENERATOR']['error'][$code] = $message;
    }
}

// }}}
// {{{ class DB_Table_Generator

/**
 * class DB_Table_Generator - Generates DB_Table subclass skeleton code
 *
 * This class generates the php code necessary to use the DB_Table
 * package to interact with an existing database. This requires the
 * generation of a skeleton subclass definition be generated for each
 * table in the database, in which the $col, $idx, and $auto_inc_col
 * properties are constructed using a table schema that is obtained
 * by querying the database.
 *
 * The class can also generate a file, named 'Database.php' by default,
 * that includes (require_once) each of the table subclass definitions,
 * instantiates one object of each DB_Table subclass (i.e., one object
 * for each table), instantiates a parent DB_Table_Database object,
 * adds all the tables to that parent, attempts to guess foreign key
 * relationships between tables based on the column names, and adds
 * the inferred references to the parent object.
 *
 * All of the code is written to a directory whose path is given by
 * the property $class_write_path. By default, this is the current
 * directory.  By default, the name of the class constructed for a
 * table named 'thing' is "Thing_Table". That is, the class name is
 * the table name, with the first letter upper case, with a suffix
 * '_Table'.  This suffix can be changed by setting the $class_suffix
 * property. The file containing a subclass definition is the
 * subclass name with a php extension, e.g., 'Thing_Table.php'. The
 * object instantiated from that subclass is the same as the table
 * name, with no suffix, e.g., 'thing'.
 *
 * To generate the code for all of the tables in a database named
 * $database, instantiate a MDB2 or DB object named $db that connects
 * to the database of interest, and execute the following code:
 *
 *     $generator = new DB_Table_Generator($db, $database);
 *     $generator->class_write_path = $class_write_path;
 *     $generator->generateTableClassFiles();
 *     $generator->generateDatabaseFile();
 *
 * Here $class_write_path should be the path (without a trailing
 * separator) to a directory in which all of the code should be
 * written. If this directory does not exist, it will be created.
 * If the directory does already exist, exising files will not
 * be overwritten. If $class_write_path is not set (i.e., if this
 * line is omitted) all the code will be written to the current
 * directory.  If ->generateDatabaseFile() is called, it must be
 * called after ->generateTableClassFiles().
 *
 * By default, ->generateTableClassFiles() and ->generateDatabaseFiles()
 * generate code for all of the tables in the current database. To
 * generate code for a specified list of tables, set the value of the
 * public $tables property to a sequential list of table names before
 * calling either of these methods. Code can be generated for three
 * tables named 'table1', 'table2', and 'table3' as follows:
 *
 *     $generator = new DB_Table_Generator($db, $database);
 *     $generator->class_write_path = $class_write_path;
 *     $generator->tables = array('table1', 'table2', 'table3');
 *     $generator->generateTableClassFiles();
 *     $generator->generateDatabaseFile();
 *
 * If the $tables property is not set to a non-null value prior
 * to calling ->generateTableClassFiles() then, by default, the
 * database is queried for a list of all table names, by calling the
 * ->getTableNames() method from within ->generateTableClassFiles().
 *
 * PHP version 4 and 5
 *
 * @category Database
 * @package  DB_Table
 * @author   Alan Knowles <alan@akbkhome.com>
 * @author   David C. Morse <morse@php.net>
 * @license  http://www.gnu.org/copyleft/lesser.html LGPL
 * @version  Release: 1.5.6
 * @link     http://pear.php.net/package/DB_Table
 */
class DB_Table_Generator
{

    // {{{ Properties

    /**
     * Name of the database
     *
     * @var string
     * @access public
     */
    var $name = null;

    /**
     * The PEAR DB/MDB2 object that connects to the database.
     *
     * @var object
     * @access private
     */
    var $db = null;

    /**
     * The backend type. May have values 'db' or 'mdb2'
     *
     * @var string
     * @access private
     */
    var $backend = null;

    /**
    * If there is an error on instantiation, this captures that error.
    *
    * This property is used only for errors encountered in the constructor
    * at instantiation time.  To check if there was an instantiation error...
    *
    *
    *     $obj =& new DB_Table_Generator();
    *     if ($obj->error) {
    *         // ... error handling code here ...
    *     }
    *
    *
    * @var object PEAR_Error
    * @access public
    */
    var $error = null;

    /**
     * Numerical array of table name strings
     *
     * @var array
     * @access public
     */
    var $tables = array();

    /**
     * Class being extended (DB_Table or generic subclass)
     *
     * @var string
     * @access public
     */
    var $extends = 'DB_Table';

    /**
     * Path to definition of the class $this->extends
     *
     * @var string
     * @access public
     */
    var $extends_file = 'DB/Table.php';

    /**
     * Suffix to add to table names to obtain corresponding class names
     *
     * @var string
     * @access public
     */
    var $class_suffix = "_Table";

    /**
     * Path to directory in which subclass definitions should be written
     *
     * Value should not include a trailing "/".
     *
     * @var string
     * @access public
     */
    var $class_write_path = '';

    /**
     * Include path to subclass definition files from database file
     *
     * Used to create require_once statements in the Database.php file,
     * which is in the same directory as the class definition files. Leave
     * as empty string if your PHP include_path contains ".". The value
     * should not include a trailing "/", which is added automatically
     * to values other than the empty string.
     *
     * @var string
     * @access public
     */
    var $class_include_path = '';

    /**
     * Array of column definitions
     *
     * Array $this->col[table_name][column_name] = column definition.
     * Column definition is an array with the same format as the $col
     * property of a DB_Table object
     *
     * @var array
     * @access public
     */
    var $col = array();

    /**
     * Array of index/constraint definitions.
     *
     * Array $this->idx[table_table][index_name] = Index definition.
     * The index definition is an array with the same format as the
     * DB_Table $idx property property array.
     *
     * @var array
     * @access public
     */
     var $idx = array();

    /**
     * Array of auto_increment column names
     *
     * Array $this->auto_inc_col[table_name] = auto-increment column
     *
     * @var array
     * @access public
     */
     var $auto_inc_col = array();

    /**
     * Array of primary keys
     *
     * @var array
     * @access public
     */
     var $primary_key = array();

    /**
     * MDB2 'idxname_format' option, format of index names
     *
     * For use in printf() formatting. Use '%s' to use index names as
     * returned by getTableConstraints/Indexes, and '%s_idx' to add an
     * '_idx' suffix. For MySQL, use the default value '%'.
     *
     * @var string
     * @access public
     */
    var $idxname_format = '%s';

    // }}}
    // {{{ function DB_Table_Generator(&$db, $name)

    /**
     * Constructor
     *
     * If an error is encountered during instantiation, the error
     * message is stored in the $this->error property of the resulting
     * object. See $error property docblock for a discussion of error
     * handling.
     *
     * @param object &$db  DB/MDB2 database connection object
     * @param string $name database name string
     *
     * @return object DB_Table_Generator
     * @access public
     */
    function DB_Table_Generator(&$db, $name)
    {
        // Is $db an DB/MDB2 object or null?
        if (is_a($db, 'db_common')) {
            $this->backend = 'db';
        } elseif (is_a($db, 'mdb2_driver_common')) {
            $this->backend = 'mdb2';
        } else {
            $this->error =&
                DB_Table_Generator::throwError(DB_TABLE_GENERATOR_ERR_DB_OBJECT,
                'DB_Table_Generator');
            return;
        }
        $this->db   =& $db;
        $this->name =  $name;

    }

    // }}}
    // {{{ function &throwError($code, $extra = null)

    /**
     * Specialized version of throwError() modeled on PEAR_Error.
     *
     * Throws a PEAR_Error with a DB_Table_Generator error message based
     * on a DB_Table_Generator constant error code.
     *
     * @param string $code  A DB_Table_Generator error code constant.
     * @param string $extra Extra text for the error (in addition to the
     *                       regular error message).
     *
     * @return object PEAR_Error
     * @access public
     * @static
     */
    function &throwError($code, $extra = null)
    {
        // get the error message text based on the error code
        $text = 'DB_TABLE_GENERATOR ERROR - ' . "\n"
              . $GLOBALS['_DB_TABLE_GENERATOR']['error'][$code];

        // add any additional error text
        if ($extra) {
            $text .= ' ' . $extra;
        }

        // done!
        $error = PEAR::throwError($text, $code);
        return $error;
    }

    // }}}
    // {{{ function setErrorMessage($code, $message = null)

    /**
     * Overwrites one or more error messages, e.g., to internationalize them.
     *
     * @param mixed  $code    If string, the error message with code $code will be
     *                        overwritten by $message. If array, each key is a
     *                        code and each value is a new message.
     * @param string $message Only used if $key is not an array.
     *
     * @return void
     * @access public
     */
    function setErrorMessage($code, $message = null)
    {
        if (is_array($code)) {
            foreach ($code as $single_code => $single_message) {
                $GLOBALS['_DB_TABLE_GENERATOR']['error'][$single_code]
                    = $single_message;
            }
        } else {
            $GLOBALS['_DB_TABLE_GENERATOR']['error'][$code] = $message;
        }
    }

    // }}}
    // {{{ function getTableNames()

    /**
     * Gets a list of tables from the database
     *
     * Upon successful completion, names are stored in the $this->tables
     * array. If an error is encountered, a PEAR Error is returned, and
     * $this->tables is reset to null.
     *
     * @return mixed true on success, PEAR Error on failure
     * @access public
     */
    function getTableNames()
    {

        if ($this->backend == 'db') {
            // try getting a list of schema tables first. (postgres)
            $this->db->expectError(DB_ERROR_UNSUPPORTED);
            $this->tables = $this->db->getListOf('schema.tables');
            $this->db->popExpect();
            if (PEAR::isError($this->tables)) {
                // try a list of tables, not qualified by 'schema'
                $this->db->expectError(DB_ERROR_UNSUPPORTED);
                $this->tables = $this->db->getListOf('tables');
                $this->db->popExpect();
            }
        } else {
            // Temporarily change 'portability' MDB2 option
            $portability = $this->db->getOption('portability');
            $this->db->setOption('portability',
                MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_FIX_CASE);

            $this->db->loadModule('Manager');
            $this->db->loadModule('Reverse');

            // Get list of tables
            $this->tables = $this->db->manager->listTables();

            // Restore original MDB2 'portability'
            $this->db->setOption('portability', $portability);
        }
        if (PEAR::isError($this->tables)) {
            $error        = $this->tables;
            $this->tables = null;
            return $error;
        } else {
            $this->tables = array_map(array($this, 'tableName'),
                                      $this->tables);
            return true;
        }
    }

    // }}}
    // {{{ function getTableDefinition($table)

    /**
     * Gets column and index definitions by querying database
     *
     * Upon return, column definitions are stored in $this->col[$table],
     * and index definitions in $this->idx[$table].
     *
     * Calls DB/MDB2::tableInfo() for column definitions, and uses
     * the DB_Table_Manager class to obtain index definitions.
     *
     * @param string $table name of table
     *
     * @return mixed true on success, PEAR Error on failure
     * @access public
     */
    function getTableDefinition($table)
    {
        /*
        // postgres strip the schema bit from the
        if (!empty($options['generator_strip_schema'])) {
            $bits = explode('.', $table,2);
            $table = $bits[0];
            if (count($bits) > 1) {
                $table = $bits[1];
            }
        }
        */

        if ($this->backend == 'db') {

            $defs = $this->db->tableInfo($table);
            if (PEAR::isError($defs)) {
                return $defs;
            }
            $this->columns[$table] = $defs;

        } else {

            // Temporarily change 'portability' MDB2 option
            $portability = $this->db->getOption('portability');
            $this->db->setOption('portability',
                MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_FIX_CASE);

            $this->db->loadModule('Manager');
            $this->db->loadModule('Reverse');

            // Columns
            $defs = $this->db->reverse->tableInfo($table);
            if (PEAR::isError($defs)) {
                return $defs;
            }

            // rename the 'length' key, so it matches db's return.
            foreach ($defs as $k => $v) {
                if (isset($defs[$k]['length'])) {
                    $defs[$k]['len'] = $defs[$k]['length'];
                }
            }

            $this->columns[$table] = $defs;

            // Temporarily set 'idxname_format' MDB2 option to $this->idx_format
            $idxname_format = $this->db->getOption('idxname_format');
            $this->db->setOption('idxname_format', $this->idxname_format);
        }

        // Default - no auto increment column
        $this->auto_inc_col[$table] = null;

        // Loop over columns to create $this->col[$table]
        $this->col[$table] = array();
        foreach ($defs as $t) {

            $name = $t['name'];
            $col  = array();

            switch (strtoupper($t['type'])) {
            case 'INT2':     // postgres
            case 'TINYINT':
            case 'TINY':     //mysql
            case 'SMALLINT':
                $col['type'] = 'smallint';
                break;
            case 'INT4':      // postgres
            case 'SERIAL4':   // postgres
            case 'INT':
            case 'SHORT':     // mysql
            case 'INTEGER':
            case 'MEDIUMINT':
            case 'YEAR':
                $col['type'] = 'integer';
                break;
            case 'BIGINT':
            case 'LONG':    // mysql
            case 'INT8':    // postgres
            case 'SERIAL8': // postgres
                $col['type'] = 'bigint';
                break;
            case 'REAL':
            case 'NUMERIC':
            case 'NUMBER': // oci8
            case 'FLOAT':  // mysql
            case 'FLOAT4': // real (postgres)
                $col['type'] = 'single';
                break;
            case 'DOUBLE':
            case 'DOUBLE PRECISION': // double precision (firebird)
            case 'FLOAT8':           // double precision (postgres)
                $col['type'] = 'double';
                break;
            case 'DECIMAL':
            case 'MONEY':   // mssql and maybe others
                $col['type'] = 'decimal';
                break;
            case 'BIT':
            case 'BOOL':
            case 'BOOLEAN':
                $col['type'] = 'boolean';
                break;
            case 'STRING':
            case 'CHAR':
                $col['type'] = 'char';
                break;
            case 'VARCHAR':
            case 'VARCHAR2':
            case 'TINYTEXT':
                $col['type'] = 'varchar';
                break;
            case 'TEXT':
            case 'MEDIUMTEXT':
            case 'LONGTEXT':
                $col['type'] = 'clob';
                break;
            case 'DATE':
                $col['type'] = 'date';
                break;
            case 'TIME':
                $col['type'] = 'time';
                break;
            case 'DATETIME':  // mysql
            case 'TIMESTAMP':
                $col['type'] = 'timestamp';
                break;
            case 'ENUM':
            case 'SET':         // not really but oh well
            case 'TIMESTAMPTZ': // postgres
            case 'BPCHAR':      // postgres
            case 'INTERVAL':    // postgres (eg. '12 days')
            case 'CIDR':        // postgres IP net spec
            case 'INET':        // postgres IP
            case 'MACADDR':     // postgress network Mac address.
            case 'INTEGER[]':   // postgres type
            case 'BOOLEAN[]':   // postgres type
                $col['type'] = 'varchar';
                break;
            default:
                $col['type'] = $t['type'] . ' (Unknown type)';
                break;
            }

            // Set length and scope if required
            if (in_array($col['type'], array('char','varchar','decimal'))) {
                if (isset($t['len'])) {
                    $col['size'] = (int) $t['len'];
                } elseif ($col['type'] == 'varchar') {
                    $col['size'] = 255; // default length
                } elseif ($col['type'] == 'char') {
                    $col['size'] = 128; // default length
                } elseif ($col['type'] == 'decimal') {
                    $col['size'] = 15; // default length
                }
                if ($col['type'] == 'decimal') {
                    $col['scope'] = 2;
                }
            }
            if (isset($t['notnull'])) {
                if ($t['notnull']) {
                    $col['require'] = true;
                }
            }
            if (isset($t['autoincrement'])) {
                $this->auto_inc_col[$table] = $name;
            }
            if (isset($t['flags'])) {
                $flags = $t['flags'];
                if (preg_match('/not[ _]null/i', $flags)) {
                    $col['require'] = true;
                }
                if (preg_match("/(auto_increment|nextval\()/i", $flags)) {
                    $this->auto_inc_col[$table] = $name;
                }
            }
            $require = isset($col['require']) ? $col['require'] : false;
            if ($require) {
                if (isset($t['default'])) {
                    $default = $t['default'];
                    $type    = $col['type'];
                    if (in_array($type,
                                 array('smallint', 'integer', 'bigint'))) {
                        $default = (int) $default;
                    } elseif (in_array($type, array('single', 'double'))) {
                        $default = (float) $default;
                    } elseif ($type == 'boolean') {
                        $default = (int) $default ? 1 : 0;
                    }
                    $col['default'] = $default;
                }
            }
            $this->col[$table][$name] = $col;

        }

        // Make array with lower case column array names as keys
        $col_lc = array();
        foreach ($this->col[$table] as $name => $def) {
            $name_lc          = strtolower($name);
            $col_lc[$name_lc] = $name;
        }

        // Constraints/Indexes
        $DB_indexes = DB_Table_Manager::getIndexes($this->db, $table);
        if (PEAR::isError($DB_indexes)) {
            return $DB_indexes;
        }

        // Check that index columns correspond to valid column names.
        // Try to correct problems with capitalization, if necessary.
        foreach ($DB_indexes as $type => $indexes) {
            foreach ($indexes as $name => $fields) {
                foreach ($fields as $key => $field) {

                    // If index column is not a valid column name
                    if (!array_key_exists($field, $this->col[$table])) {

                        // Try a case-insensitive match
                        $field_lc = strtolower($field);
                        if (isset($col_lc[$field_lc])) {
                            $correct = $col_lc[$field_lc];
                            $DB_indexes[$type][$name][$key]
                                 = $correct;
                        } else {
                            $code   =  DB_TABLE_GENERATOR_ERR_INDEX_COL;
                            $return =&
                                DB_Table_Generator::throwError($code, $field);
                        }

                    }
                }
            }
        }

        // Generate index definitions, if any, as php code
        $n_idx = 0;
        $u     = array();

        $this->idx[$table]         = array();
        $this->primary_key[$table] = null;
        foreach ($DB_indexes as $type => $indexes) {
            if (count($indexes) > 0) {
                foreach ($indexes as $name => $fields) {
                    $this->idx[$table][$name]         = array();
                    $this->idx[$table][$name]['type'] = $type;
                    if (count($fields) == 1) {
                        $key = $fields[0];
                    } else {
                        $key = array();
                        foreach ($fields as $value) {
                            $key[] = $value;
                        }
                    }
                    $this->idx[$table][$name]['cols'] = $key;
                    if ($type == 'primary') {
                        $this->primary_key[$table] = $key;
                    }
                }
            }
        }

        if ($this->backend == 'mdb2') {
            // Restore original MDB2 'idxname_format' and 'portability'
            $this->db->setOption('idxname_format', $idxname_format);
            $this->db->setOption('portability', $portability);
        }

        return true;
    }

    // }}}
    // {{{ function buildTableClass($table, $indent = '')

    /**
     * Returns one skeleton DB_Table subclass definition, as php code
     *
     * The returned subclass definition string contains values for the
     * $col (column), $idx (index) and $auto_inc_col properties, with
     * no method definitions.
     *
     * @param string $table  name of table
     * @param string $indent string of whitespace for base indentation
     *
     * @return string skeleton DB_Table subclass definition
     * @access public
     */
    function buildTableClass($table, $indent = '')
    {
        $s   = array();
        $idx = array();
        $u   = array();
        $v   = array();
        $l   = 0;

        $s[]     = $indent . '/*';
        $s[]     = $indent . ' * Create the table object';
        $s[]     = $indent . ' */';
        $s[]     = $indent . 'class ' . $this->className($table)
                 . " extends {$this->extends} {\n";
        $indent .= '    ';

        $s[]     = $indent . '/*';
        $s[]     = $indent . ' * Column definitions';
        $s[]     = $indent . ' */';
        $s[]     = $indent . 'var $col = array(' . "\n";
        $indent .= '    ';

        // Begin loop over columns
        foreach ($this->col[$table] as $name => $col) {

            // Generate DB_Table column definitions as php code
            $t  = array();
            $t1 = array();
            $l1 = 0;

            $name     = $indent . "'{$name}'";
            $l        = max($l, strlen($name));
            $v[$name] = "array(\n";
            $indent  .= '    ';
            foreach ($col as $key => $value) {
                if (is_string($value)) {
                    $value = "'{$value}'";
                } elseif (is_bool($value)) {
                    $value = $value ? 'true' : 'false';
                } else {
                    $value = (string) $value;
                }
                $l1   = max($l1, strlen($key) + 2);
                $t1[] = array("'{$key}'", $value) ;
            }
            foreach ($t1 as $value) {
                $t[] = $indent . str_pad($value[0], $l1, ' ', STR_PAD_RIGHT)
                     . ' => ' . $value[1];
            }
            $v[$name] .= implode(",\n", $t) . "\n";
            $indent    = substr($indent, 0, -4);
            $v[$name] .= $indent . ')';
        } //end loop over columns

        foreach ($v as $key => $value) {
            $u[] = str_pad($key, $l, ' ', STR_PAD_RIGHT)
                 . ' => ' . $value;
        }
        $s[]    = implode(",\n\n", $u) . "\n";
        $indent = substr($indent, 0, -4);
        $s[]    = $indent . ");\n";

        // Generate index definitions, if any, as php code
        if (count($this->idx[$table]) > 0) {
            $u = array();
            $v = array();
            $l = 0;

            $s[]     = $indent . '/*';
            $s[]     = $indent . ' * Index definitions';
            $s[]     = $indent . ' */';
            $s[]     = $indent . 'var $idx = array(' . "\n";
            $indent .= '    ';
            foreach ($this->idx[$table] as $name => $def) {
                $type      = $def['type'];
                $cols      = $def['cols'];
                $name      = $indent . "'{$name}'";
                $l         = max($l, strlen($name));
                $v[$name]  = "array(\n";
                $indent   .= '    ';
                $v[$name] .= $indent . "'type' => '{$type}',\n";
                if (is_array($cols)) {
                    $v[$name] .= $indent . "'cols' => array(\n";
                    $indent   .= '    ';
                    $t         = array();
                    foreach ($cols as $value) {
                        $t[] = $indent . "'{$value}'";
                    }
                    $v[$name] .= implode(",\n", $t) . "\n";
                    $indent    = substr($indent, 0, -4);
                    $v[$name] .= $indent . ")\n";
                } else {
                    $v[$name] = $v[$name] . $indent . "'cols' => '{$cols}'\n";
                }
                $indent    = substr($indent, 0, -4);
                $v[$name] .= $indent . ")";
            }

            foreach ($v as $key => $value) {
                $u[] = str_pad($key, $l, ' ', STR_PAD_RIGHT)
                     . ' => ' . $value;
            }
            $s[]    = implode(",\n\n", $u) . "\n";
            $indent = substr($indent, 0, -4);
            $s[]    = $indent . ");\n";
        } // end index generation

        // Write auto_inc_col
        if (isset($this->auto_inc_col[$table])) {
            $s[] = $indent . '/*';
            $s[] = $indent . ' * Auto-increment declaration';
            $s[] = $indent . ' */';
            $s[] = $indent . 'var $auto_inc_col = '
                           . "'{$this->auto_inc_col[$table]}';\n";
        }
        $indent = substr($indent, 0, -4);
        $s[]    = $indent . '}';

        // Implode and return lines of class definition
        return implode("\n", $s) . "\n";

    }

    // }}}
    // {{{ function buildTableClasses()

    /**
     * Returns a string containing all table class definitions in one file
     *
     * The returned string contains the contents of a single php file with
     * definitions of DB_Table subclasses associated with all of the tables
     * in $this->tables. If $this->tables is initially null, method
     * $this->getTableNames() is called internally to generate a list of
     * table names.
     *
     * The returned string includes the opening and closing <?php and ?>
     * script elements, and the require_once line needed to include the
     * $this->extend_class (i.e., DB_Table or a subclass) that is being
     * extended. To use, write this string to a new php file.
     *
     * Usage:
     *
     *     $generator = new DB_Table_Generator($db, $database);
     *     echo $generator->buildTablesClasses();
     *
     *
     * @return mixed a string with all table class definitions,
     *                PEAR Error on failure
     * @access public
     */
    function buildTableClasses()
    {
        // If $this->tables is null, call getTableNames()
        if (!$this->tables) {
            $return = $this->getTableNames();
            if (PEAR::isError($return)) {
                return $return;
            }
        }

        $s   = array();
        $s[] = '<?php';
        $s[] = '/*';
        $s[] = ' * Include basic class';
        $s[] = ' */';
        $s[] = "require_once '{$this->extends_file}';\n";
        foreach ($this->tables as $table) {
            $return = $this->getTableDefinition($table);
            if (PEAR::isError($return)) {
                return $return;
            }
            $s[] = $this->buildTableClass($table) . "\n";
        }
        $s[] = '?>';
        return implode("\n", $s);
    }

    // }}}
    // {{{ function generateTableClassFiles()

    /**
     * Writes all table class definitions to separate files
     *
     * Usage:
     *
     *     $generator = new DB_Table_Generator($db, $database);
     *     $generator->generateTableClassFiles();
     *
     *
     * @return mixed true on success, PEAR Error on failure
     * @access public
     */
    function generateTableClassFiles()
    {
        // If $this->tables is null, call getTableNames()
        if (!$this->tables) {
            $return = $this->getTableNames();
            if (PEAR::isError($return)) {
                return $return;
            }
        }

        // Write all table class definitions to separate files
        foreach ($this->tables as $table) {
            $classname = $this->className($table);
            $filename  = $this->classFileName($classname);
            $base      = $this->class_write_path;
            if ($base) {
                if (!file_exists($base)) {
                    include_once 'System.php';
                    if (!@System::mkdir(array('-p', $base))) {
                        return $this->throwError(DB_TABLE_GENERATOR_ERR_FILE,
                            $base);
                    }

                }
                $filename = "{$base}/{$filename}";
            }
            if (!file_exists($filename)) {
                $s      = array();
                $s[]    = '<?php';
                $s[]    = '/*';
                $s[]    = ' * Include basic class';
                $s[]    = ' */';
                $s[]    = "require_once '{$this->extends_file}';\n";
                $return = $this->getTableDefinition($table);
                if (PEAR::isError($return)) {
                    return $return;
                }
                $s[] = $this->buildTableClass($table);
                $s[] = '?>';
                $s[] = '';
                $out = implode("\n", $s);
                if (!$file = @fopen($filename, 'wb')) {
                    return $this->throwError(DB_TABLE_GENERATOR_ERR_FILE,
                            $filename);
                }
                fputs($file, $out);
                fclose($file);
            }
        }

        return true;
    }

    // }}}
    // {{{ function generateDatabaseFile($object_name = null)

    /**
     * Writes a file to instantiate Table and Database objects
     *
     * After successful completion, a file named 'Database.php' will be
     * have been created in the $this->class_write_path directory. This
     * file should normally be included in application php scripts. It
     * can be renamed by the user.
     *
     * Usage:
     *
     *     $generator = new DB_Table_Generator($db, $database);
     *     $generator->generateTableClassFiles();
     *     $generator->generateDatabaseFile();
     *
     *
     * @param string $object_name variable name for DB_Table_Database object
     *
     * @return mixed true on success, PEAR Error on failure
     * @access public
     */
    function generateDatabaseFile($object_name = null)
    {
        // Set name for DB_Table_Database object
        if ($object_name) {
            $object_name = "\${$object_name}";
        } else {
            $object_name = '$db'; //default
        }
        $backend = strtoupper($this->backend); // 'DB' or 'MDB2'

        if ('DB' == $backend) {
            $dsn = $this->db->dsn;
        } else {
            $dsn = $this->db->getDSN('array');
        }

        // Create array d[] containing lines of database php file
        $d   = array();
        $d[] = '<?php';
        $d[] = '/*';
        $d[] = ' * Include basic classes';
        $d[] = ' */';
        $d[] = "require_once '{$backend}.php';";
        $d[] = "require_once 'DB/Table/Database.php';";

        // Require_once statements for subclass definitions
        foreach ($this->tables as $table) {
            $classname      = $this->className($table);
            $class_filename = $this->classFileName($classname);
            if ($this->class_include_path) {
                $d[] = 'require_once '
                     . "'{$this->class_include_path}/{$class_filename}';";
            } else {
                $d[] = "require_once '{$class_filename}';";
            }
        }
        $d[] = '';

        $d[] = '/*';
        $d[] = ' * NOTE: User must uncomment & edit code to create $dsn';
        $d[] = ' */';
        $d[] = "//\$phptype  = '{$dsn['phptype']}';";
        $d[] = "//\$username = '{$dsn['username']}';";
        $d[] = "//\$password = ''; // put your password here";
        $d[] = "//\$hostname = '{$dsn['hostspec']}';";
        $d[] = "//\$database = '{$dsn['database']}';";
        $d[] = "//\$create   = false; // 'drop', 'safe', 'verify', 'alter'";
        $d[] = '//$dsn      = "{$phptype}://{$username}:{$password}@{$hostname}'
             . '/{$database}";';
        $d[] = '';

        $d[] = '/*';
        $d[] = " * Instantiate {$backend} connection object \$conn";
        $d[] = ' */';
        $d[] = "\$conn =& {$backend}::connect(\$dsn);";
        $d[] = 'if (PEAR::isError($conn)) {';
        $d[] = '    echo "Error connecting to database server\n";';
        $d[] = '    echo $conn->getMessage();';
        $d[] = '    die;';
        $d[] = '}';
        $d[] = '';

        $d[] = '/*';
        $d[] = ' * Create one instance of each DB_Table subclass';
        $d[] = ' */';
        foreach ($this->tables as $table) {
            $classname = $this->className($table);

            $d[] = "\${$table} = new {$classname}("
                 . '$conn, ' . "'{$table}'" . ', $create);';
            $d[] = "if (PEAR::isError(\${$table}->error)) {";
            $d[] = '    echo "Can\'t create table object.\n";';
            $d[] = "    echo \${$table}->error->getMessage();";
            $d[] = '    die;';
            $d[] = '}';

        }
        $d[] = '';

        $d[] = '/*';
        $d[] = ' * Instantiate a parent DB_Table_Database object';
        $d[] = ' */';
        $d[] = "{$object_name} = new DB_Table_Database(\$conn, \$database);";
        $d[] = "if (PEAR::isError({$object_name}->error)) {";
        $d[] = '    echo "Can\'t create database object.\n";';
        $d[] = "    echo {$object_name}->error->getMessage();";
        $d[] = '    die;';
        $d[] = '}';
        $d[] = '';

        $d[] = '/*';
        $d[] = ' * Add DB_Table objects to parent DB_Table_Database object';
        $d[] = ' */';
        foreach ($this->tables as $table) {
            $classname = $this->className($table);

            $d[] = "\$result = {$object_name}->addTable(\${$table});";
            $d[] = 'if (PEAR::isError($result)) {';
            $d[] = '    echo "Can\'t add table object to database object.\n";';
            $d[] = '    echo $result->getMessage();';
            $d[] = '    die;';
            $d[] = '}';
        }
        $d[] = '';

        // Add foreign key references: If the name of an integer column
        // matches "/id$/i" (i.e., the names ends with id, ID, or Id), the
        // remainder of the name matches the name $rtable of another table,
        // and $rtable has an integer primary key, then the column is
        // assumed to be a foreign key that references $rtable.

        $d[] = '/*';
        $d[] = ' * Add auto-guessed foreign references';
        $d[] = ' */';
        foreach ($this->col as $table => $col) {
            foreach ($col as $col_name => $def) {

                // Only consider integer columns
                $ftype = $def['type'];
                if (!in_array($ftype, array('integer','smallint','bigint'))) {
                    continue;
                }
                if (preg_match("/id$/i", $col_name)) {
                    $column_base = preg_replace('/_?id$/i', '', $col_name);
                    foreach ($this->tables as $rtable) {
                        if (!preg_match("/^{$rtable}$/i", $column_base)) {
                            continue;
                        }
                        if (preg_match("/^{$table}$/i", $column_base)) {
                            continue;
                        }
                        if (!isset($this->primary_key[$rtable])) {
                            continue;
                        }
                        $rkey = $this->primary_key[$rtable];
                        if (is_array($rkey)) {
                            continue;
                        }
                        $rtype = $this->col[$rtable][$rkey]['type'];
                        if (!in_array($rtype,
                            array('integer','smallint','bigint'))) {
                            continue;
                        }
                        $d[] = "\$result = {$object_name}->addRef('{$table}', "
                             . "'{$col_name}', '{$rtable}');";
                        $d[] = 'if (PEAR::isError($result)) {';
                        $d[] = '    echo "Can\'t add foreign key reference.\n";';
                        $d[] = '    echo $result->getMessage();';
                        $d[] = '    die;';
                        $d[] = '}';
                    }
                }
            }
        }
        $d[] = '';
        $d[] = '/*';
        $d[] = ' * Add any additional foreign key references here';
        $d[] = ' *';
        $d[] = ' * Add any linking table declarations here';
        $d[] = ' * Uncomment next line to add all possible linking tables;';
        $d[] = ' */';
        $d[] = "//\$result = {$object_name}->addAllLinks();";
        $d[] = '//if (PEAR::isError($result)) {';
        $d[] = '//    echo "Can\'t add linking tables.\n";';
        $d[] = '//    echo $result->getMessage();';
        $d[] = '//    die;';
        $d[] = '//}';
        $d[] = '';

        // Closing script element
        $d[] = '?>';
        $d[] = '';

        // Open and write file
        $base = $this->class_write_path;
        if ($base) {
            if (!file_exists($base)) {
                include_once 'System.php';
                if (!@System::mkdir(array('-p', $base))) {
                    return $this->throwError(DB_TABLE_GENERATOR_ERR_FILE, $base);
                }
            }
            $filename = $base . '/Database.php';
        } else {
            $filename = 'Database.php';
        }
        if (!$file = @fopen($filename, 'wb')) {
            return $this->throwError(DB_TABLE_GENERATOR_ERR_FILE, $filename);
        }
        $out = implode("\n", $d);
        fputs($file, $out);
        fclose($file);

        return true;
    }

    // }}}
    // {{{ function className($table)

    /**
     * Convert a table name into a class name
     *
     * Converts all non-alphanumeric characters to '_', capitalizes
     * first letter, and adds $this->class_suffix to end. Override
     * this if you want something else.
     *
     * @param string $table name of table
     *
     * @return string class name;
     * @access public
     */
    function className($table)
    {
        $name = preg_replace('/[^A-Z0-9]/i', '_', ucfirst(trim($table)));
        return  $name . $this->class_suffix;
    }

    // }}}
    // {{{ function tableName($table)

    /**
     * Returns a valid variable name from a table name
     *
     * Converts all non-alphanumeric characters to '_'. Override
     * this if you want something else.
     *
     * @param string $table name of table
     *
     * @return string variable name;
     * @access public
     */
    function tableName($table)
    {
        return preg_replace('/[^A-Z0-9]/i', '_', trim($table));
    }

    // }}}
    // {{{ function classFileName($class_name)

    /**
     * Returns the path to a file containing a class definition
     *
     * Appends '.php' to class name.
     *
     * @param string $class_name name of class
     *
     * @return string file name
     * @access public
     */
    function classFileName($class_name)
    {
        $filename = $class_name . '.php';
        return $filename;
    }

    // }}}

}
// }}}


text:
<?php

namespace Monohook\Test;

use Monohook\Provider\GitProvider;

/**
 * Git provider test.
 *
 * @author Jad Bitar <jadbitar@mac.com>
 */
class GitProviderTest extends \PHPUnit_Framework_TestCase
{
    const PROVIDER = 'Monohook\Provider\GitProvider';

    public function testGetAddedCode()
    {
        $provider = $this->getMock(self::PROVIDER, array('execute', 'getHead'));

        $provider->expects($this->at(0))
            ->method('getHead')
            ->with()
            ->will($this->returnValue('HEAD'));

        $provider->expects($this->at(1))
            ->method('execute')
            ->with('git diff-index --cached HEAD', '');

        $provider->expects($this->at(2))
            ->method('execute')
            ->with('git diff-index --cached HEAD^', '');

        $result = $provider->getAddedCode();
        $this->assertTrue(is_string($result));

    }

    public function testGetAddedCodeShallowRepository()
    {
        $provider = $this->getMock(self::PROVIDER, array('execute', 'getHead'));

        $provider->expects($this->once())
            ->method('getHead')
            ->with()
            ->will($this->returnValue(GitProvider::HEAD));

        $provider->expects($this->once())
            ->method('execute')
            ->with('git diff-index --cached ' . GitProvider::HEAD, '');

        $result = $provider->getAddedCode();
        $this->assertTrue(is_string($result));
    }

    public function testGetAddedFiles()
    {
        $provider = $this->getMock(self::PROVIDER, array('execute', 'getHead'));

        $provider->expects($this->at(0))
            ->method('getHead')
            ->with()
            ->will($this->returnValue('HEAD'));

        $provider->expects($this->at(1))
            ->method('execute')
            ->with('git diff-index --cached --name-only HEAD', array());

        $provider->expects($this->at(2))
            ->method('execute')
            ->with('git diff-index --cached --name-only HEAD^', array());

        $result = $provider->getAddedFiles();
        $this->assertTrue(is_array($result));
    }

    public function testGetAddedFilesShallowRepository()
    {
        $provider = $this->getMock(self::PROVIDER, array('execute', 'getHead'));

        $provider->expects($this->once())
            ->method('getHead')
            ->with()
            ->will($this->returnValue(GitProvider::HEAD));

        $provider->expects($this->once())
            ->method('execute')
            ->with('git diff-index --cached --name-only ' . GitProvider::HEAD, array());

        $result = $provider->getAddedFiles();
        $this->assertTrue(is_array($result));
    }

    public function testGetHead()
    {
        $provider = $this->getMock(self::PROVIDER, array('execute'));

        $provider->expects($this->once())
            ->method('execute')
            ->with('git rev-parse --verify HEAD 2> /dev/null', null, null);

        $result = $provider->getHead();
        $expected = GitProvider::HEAD;
        $this->assertEquals($expected, $result);
    }

    public function testGetHeadOfShallowRepository()
    {
        $provider = $this->getMock(self::PROVIDER, array('execute'));

        $provider->expects($this->once())
            ->method('execute');

        $result = $provider->getHead();
        $this->assertEquals($result, GitProvider::HEAD);
    }

    public function testGetHook()
    {
        $provider = $this->getMock(self::PROVIDER, array('execute'));

        $_SERVER['SCRIPT_FILENAME'] = '.git/hooks/pre-commit';

        $result = $provider->getHook();
        $expected = 'pre-commit';
        $this->assertEquals($expected, $result);
    }

    public function testIsShallow()
    {
        $provider = $this->getMock(self::PROVIDER, array('execute', 'getHead'));

        $provider->expects($this->exactly(2))
            ->method('getHead')
            ->with()
            ->will($this->onConsecutiveCalls(GitProvider::HEAD, ''));

        $this->assertTrue($provider->isShallow());
        $this->assertFalse($provider->isShallow());
    }

    public function testStash()
    {
        $this->markTestIncomplete();
    }

    public function testStashOfShallowRepository()
    {
        $this->markTestIncomplete();
    }

    public function testUnstash()
    {
        $this->markTestIncomplete();
    }

    public function testUnstashOfShallowRepository()
    {
        $this->markTestIncomplete();
    }
}

redpajama_set_name: RedPajamaGithub


text:
'''
Created on 9 jan. 2013

@author: sander
'''
from bitstring import BitStream, ConstBitStream, Bits
from ipaddress import IPv4Address, IPv6Address
from pylisp.packet.ip import protocol_registry
from pylisp.packet.ip.protocol import Protocol
from pylisp.utils import checksum
import numbers

class UDPMessage(Protocol):
    header_type = 17

    def __init__(self, source_port=0, destination_port=0, checksum=0,
                 payload=''):
        # Call the superclass constructor
        super(UDPMessage, self).__init__(payload=payload)

        self.source_port = source_port
        self.destination_port = destination_port
        self.checksum = checksum

    def sanitize(self):
        '''
        Check if the current settings conform to the RFC and fix where possible
        '''
        # Check ports
        if not isinstance(self.source_port, numbers.Integral) \
        or self.source_port < 0 \
        or self.source_port >= 2 ** 16:
            raise ValueError('Invalid source port')

        if not isinstance(self.destination_port, numbers.Integral) \
        or self.destination_port < 0 \
        or self.destination_port >= 2 ** 16:
            raise ValueError('Invalid destination port')

        # We can't calculate the checksum because we don't know enough by
        # ourself to construct the pseudo-header

    def generate_pseudo_header(self, source, destination):
        # Calculate the length of the UDP layer
        udp_length = 8 + len(bytes(self.payload))

        if isinstance(source, IPv4Address) \
        and isinstance(destination, IPv4Address):
            # Generate an IPv4 pseudo-header
            header = BitStream('uint:32=%d, '
                               'uint:32=%d, '
                               'uint:16=17, '
                               'uint:16=%d' % (int(source),
                                               int(destination),
                                               udp_length))

        elif isinstance(source, IPv6Address) \
        and isinstance(destination, IPv6Address):
            # Generate an IPv6 pseudo-header
            header = BitStream('uint:128=%d, '
                               'uint:128=%d, '
                               'uint:32=%d, '
                               'uint:32=17' % (int(source),
                                               int(destination),
                                               udp_length))
        else:
            raise ValueError('Source and destination must belong to the same '
                             'IP version')

        # Return the header bytes
        return header.bytes

    def calculate_checksum(self, source, destination):
        # Calculate the pseudo-header for the checksum calculation
        pseudo_header = self.generate_pseudo_header(source, destination)

        # Remember the current checksum, generate a message and restore the
        # original checksum
        old_checksum = self.checksum
        self.checksum = 0
        message = self.to_bytes()
        self.checksum = old_checksum

        # Calculate the checksum
        my_checksum = checksum.ones_complement(pseudo_header + message)

        # If the computed checksum is zero, it is transmitted as all ones (the
        # equivalent in one's complement arithmetic).  An all zero transmitted
        # checksum value means that the transmitter generated no checksum (for
        # debugging or for higher level protocols that don't care).
        if my_checksum == 0:
            my_checksum = 0xffff

        return my_checksum

    def verify_checksum(self, source, destination):
        # An all zero transmitted checksum value means that the transmitter
        # generated no checksum (for debugging or for higher level protocols
        # that don't care).
        if self.checksum == 0:
            return True

        return self.checksum == self.calculate_checksum(source, destination)

    def get_lisp_message(self, only_data=False, only_control=False):
        # Check the UDP ports
        lisp_data = (self.source_port == 4341
                     or self.destination_port == 4341)
        lisp_control = (self.source_port == 4342
                        or self.destination_port == 4342)

        if lisp_data and lisp_control:
            raise ValueError("Cannot mix LISP data and control ports")

        from pylisp.packet.lisp.control.base import ControlMessage
        from pylisp.packet.lisp.data import DataPacket

        if lisp_data or only_data:
            if not isinstance(self.payload, DataPacket):
                raise ValueError("Payload is not a LISP data packet")
            return self.payload

        elif lisp_control or only_control:
            if not isinstance(self.payload, ControlMessage):
                raise ValueError("Payload is not a LISP control message")
            return self.payload

        else:
            raise ValueError("No LISP content found")

    def get_lisp_data_packet(self):
        return self.get_lisp_message(only_data=True)

    def get_lisp_control_message(self):
        return self.get_lisp_message(only_control=True)

    @classmethod
    def from_bytes(cls, bitstream):
        '''
        Parse the given packet and update properties accordingly
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the source and destination ports
        (packet.source_port,
         packet.destination_port) = bitstream.readlist('2*uint:16')

        # Store the length
        length = bitstream.read('uint:16')
        if length < 8:
            raise ValueError('Invalid UDP length')

        # Read the checksum
        packet.checksum = bitstream.read('uint:16')

        # And the rest is payload
        payload_bytes = length - 8
        packet.payload = bitstream.read('bytes:%d' % payload_bytes)

        # LISP-specific handling
        if packet.source_port == 4341 or packet.destination_port == 4341:
            # Payload is a LISP data packet
            from pylisp.packet.lisp.data import DataPacket
            packet.payload = DataPacket.from_bytes(packet.payload)
        elif packet.source_port == 4342 or packet.destination_port == 4342:
            # Payload is a LISP control message
            from pylisp.packet.lisp.control.base import ControlMessage
            packet.payload = ControlMessage.from_bytes(packet.payload)

        # There should be no remaining bits
        if bitstream.pos != bitstream.len:
            raise ValueError('Bits remaining after processing packet')

        # Verify that the properties make sense
        packet.sanitize()

        return packet

    def to_bytes(self):
        '''
        Create bytes from properties
        '''
        # Verify that the properties make sense
        self.sanitize()

        # Write the source and destination ports
        bitstream = BitStream('uint:16=%d, '
                              'uint:16=%d' % (self.source_port,
                                              self.destination_port))

        # Write the length
        payload_bytes = bytes(self.payload)
        length = len(payload_bytes) + 8
        bitstream += BitStream('uint:16=%d' % length)

        # Write the checksum
        bitstream += BitStream('uint:16=%d' % self.checksum)

        return bitstream.bytes + payload_bytes

# Register this header type
protocol_registry.register_type_class(UDPMessage)


text:
if (Meteor.setting && Meteor.settings.ACCOUNTS_PHONE){
	Accounts._options.adminPhoneNumbers = Meteor.settings.ACCOUNTS_PHONE.ADMIN_NUMBERS;
	Accounts._options.phoneVerificationMasterCode = Meteor.settings.ACCOUNTS_PHONE.MASTER_CODE;
}

// ADD with real twilio account
/*

SMS.twilio = {
	ACCOUNT_SID: Meteor.settings.TWILIO.SID,
	AUTH_TOKEN: Meteor.settings.TWILIO.TOKEN
};
*/

if (Meteor.isServer) {
	if (Meteor.settings && Meteor.settings.ACCOUNTS_PHONE) {
		Accounts._options.adminPhoneNumbers = Meteor.settings.ACCOUNTS_PHONE.ADMIN_NUMBERS;
		Accounts._options.phoneVerificationMasterCode = Meteor.settings.ACCOUNTS_PHONE.MASTER_CODE;
	}
}


text:
package org.terasology.audio.openAL.staticSound;

import org.lwjgl.openal.AL10;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.assets.AssetType;
import org.terasology.assets.ResourceUrn;
import org.terasology.audio.StaticSound;
import org.terasology.audio.StaticSoundData;
import org.terasology.audio.openAL.OpenALException;
import org.terasology.audio.openAL.OpenALManager;
import org.terasology.engine.GameThread;

import java.lang.ref.WeakReference;

import static org.lwjgl.openal.AL10.AL_BITS;
import static org.lwjgl.openal.AL10.AL_CHANNELS;
import static org.lwjgl.openal.AL10.AL_FREQUENCY;
import static org.lwjgl.openal.AL10.AL_SIZE;
import static org.lwjgl.openal.AL10.alDeleteBuffers;
import static org.lwjgl.openal.AL10.alGenBuffers;
import static org.lwjgl.openal.AL10.alGetBufferi;

public final class OpenALSound extends StaticSound {

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

    protected float length;
    private final OpenALManager audioManager;

    private DisposalAction disposalAction;

    // TODO: Do we have proper support for unloading sounds (as mods are changed?)
    private int bufferId;

    public OpenALSound(ResourceUrn urn, AssetType<?, StaticSoundData> assetType, StaticSoundData data, OpenALManager audioManager) {
        super(urn, assetType);
        this.audioManager = audioManager;
        disposalAction = new DisposalAction(urn, this);
        getDisposalHook().setDisposeAction(disposalAction);
        reload(data);
    }

    @Override
    public float getLength() {
        return length;
    }

    @Override
    public int getChannels() {
        return alGetBufferi(bufferId, AL_CHANNELS);
    }

    @Override
    public int getSamplingRate() {
        return alGetBufferi(bufferId, AL_FREQUENCY);
    }

    public int getBufferId() {
        return bufferId;
    }

    public int getBufferBits() {
        return alGetBufferi(bufferId, AL_BITS);
    }

    @Override
    public int getBufferSize() {
        return alGetBufferi(bufferId, AL_SIZE);
    }

    @Override
    public void play() {
        audioManager.playSound(this);
    }

    @Override
    public void play(float volume) {
        audioManager.playSound(this, volume);
    }

    @Override
    protected void doReload(StaticSoundData newData) {
        try {
            GameThread.synch(() -> {
                if (bufferId == 0) {
                    bufferId = alGenBuffers();
                    disposalAction.bufferId = bufferId;
                } else {
                    audioManager.purgeSound(this);
                }

                AL10.alBufferData(bufferId, newData.getChannels() == 1 ? AL10.AL_FORMAT_MONO16 : AL10.AL_FORMAT_STEREO16, newData.getData(), newData.getSampleRate());
                OpenALException.checkState("Allocating sound buffer");

                int bits = newData.getBufferBits();
                int size = getBufferSize();
                int channels = getChannels();
                int frequency = getSamplingRate();
                length = (float) size / channels / (bits / 8) / frequency;
            });
        } catch (InterruptedException e) {
            logger.error("Failed to reload {}", getUrn(), e);
        }
    }

    private static class DisposalAction implements Runnable {
        private final ResourceUrn urn;
        private int bufferId;
        private final WeakReference<OpenALSound> asset;

        public DisposalAction(ResourceUrn urn, OpenALSound openALSound) {
            this.urn = urn;
             asset = new WeakReference<>(openALSound);
        }

        @Override
        public void run() {
            try {
                GameThread.synch(() -> {
                    OpenALSound sound = asset.get();
                    if (bufferId != 0) {
                        if (sound != null) {
                            sound.audioManager.purgeSound(sound);
                        }
                        alDeleteBuffers(bufferId);
                        OpenALException.checkState("Deleting buffer data");
                    }
                });
            } catch (InterruptedException e) {
                logger.error("Failed to dispose {}", urn, e);
            }
        }
    }
}


text:
keystone
~~~~~~~~

Synopsis
--------
Manage OpenStack Identity (keystone) users, projects, roles, and endpoints.

Examples
--------
.. literalinclude:: ../../../library/keystone
   :language: yaml
   :start-after: EXAMPLES = """
   :end-before: """


text:
shared_examples_for "scoped query" do
  it 'scopes by exact match with a string' do
    search do
      with :title, 'My Pet Post'
    end
    connection.should have_last_search_including(:fq, 'title_ss:My\ Pet\ Post')
  end

  it 'scopes by exact match with a special string' do
    search do
      with :title, 'OR'
    end
    connection.should have_last_search_including(:fq, 'title_ss:"OR"')
  end

  it 'scopes by exact match with time' do
    time = Time.parse('1983-07-08 05:00:00 -0400')
    search do
      with :published_at, time
    end
    connection.should have_last_search_including(
      :fq,
      'published_at_dt:1983\-07\-08T09\:00\:00Z'
    )
  end

  it 'scopes by exact match with date' do
    date = Date.new(1983, 7, 8)
    search do
      with :expire_date, date
    end
    connection.should have_last_search_including(
      :fq,
      'expire_date_d:1983\-07\-08T00\:00\:00Z'
    )
  end

  it 'scopes by exact match with boolean' do
    search do
      with :featured, false
    end
    connection.should have_last_search_including(:fq, 'featured_bs:false')
  end

  it 'scopes by less than match with float' do
    search do
      with(:average_rating).less_than 3.0
    end
    connection.should have_last_search_including(:fq, 'average_rating_ft:[* TO 3\.0]')
  end

  it 'should quote string with space in a less than match' do
    search do
      with(:title).less_than('test value')
    end
    connection.should have_last_search_including(:fq, 'title_ss:[* TO "test\ value"]')
  end

  it 'scopes by greater than match with float' do
    search do
      with(:average_rating).greater_than 3.0
    end
    connection.should have_last_search_including(:fq, 'average_rating_ft:[3\.0 TO *]')
  end

  it 'scopes by short-form between match with integers' do
    search do
      with :blog_id, 2..4
    end
    connection.should have_last_search_including(:fq, 'blog_id_i:[2 TO 4]')
  end

  it 'scopes by between match with float' do
    search do
      with(:average_rating).between 2.0..4.0
    end
    connection.should have_last_search_including(:fq, 'average_rating_ft:[2\.0 TO 4\.0]')
  end

  it 'scopes by any match with integer' do
    search do
      with(:category_ids).any_of [2, 7, 12]
    end
    connection.should have_last_search_including(:fq, 'category_ids_im:(2 OR 7 OR 12)')
  end

  it 'scopes by short-form any-of match with integers' do
    search do
      with :category_ids, [2, 7, 12]
    end
    connection.should have_last_search_including(:fq, 'category_ids_im:(2 OR 7 OR 12)')
  end

  it 'scopes by all match with integer' do
    search do
      with(:category_ids).all_of [2, 7, 12]
    end
    connection.should have_last_search_including(:fq, 'category_ids_im:(2 AND 7 AND 12)')
  end

  it 'scopes by prefix match with string' do
    search do
      with(:title).starting_with('tes')
    end
    connection.should have_last_search_including(:fq, 'title_ss:tes*')
  end

  it 'scopes by not equal match with string' do
    search do
      without :title, 'Bad Post'
    end
    connection.should have_last_search_including(:fq, '-title_ss:Bad\ Post')
  end

  it 'scopes by not less than match with float' do
    search do
      without(:average_rating).less_than 3.0
    end
    connection.should have_last_search_including(:fq, '-average_rating_ft:[* TO 3\.0]')
  end

  it 'scopes by not greater than match with float' do
    search do
      without(:average_rating).greater_than 3.0
    end
    connection.should have_last_search_including(:fq, '-average_rating_ft:[3\.0 TO *]')
  end

  it 'scopes by not between match with shorthand' do
    search do
      without(:blog_id, 2..4)
    end
    connection.should have_last_search_including(:fq, '-blog_id_i:[2 TO 4]')
  end

  it 'scopes by not between match with float' do
    search do
      without(:average_rating).between 2.0..4.0
    end
    connection.should have_last_search_including(:fq, '-average_rating_ft:[2\.0 TO 4\.0]')
  end

  it 'scopes by not any match with integer' do
    search do
      without(:category_ids).any_of [2, 7, 12]
    end
    connection.should have_last_search_including(:fq, '-category_ids_im:(2 OR 7 OR 12)')
  end

  it 'scopes by not all match with integer' do
    search do
      without(:category_ids).all_of [2, 7, 12]
    end
    connection.should have_last_search_including(:fq, '-category_ids_im:(2 AND 7 AND 12)')
  end

  it 'scopes by empty field' do
    search do
      with :average_rating, nil
    end
    connection.should have_last_search_including(:fq, '-average_rating_ft:[* TO *]')
  end

  it 'scopes by non-empty field' do
    search do
      without :average_rating, nil
    end
    connection.should have_last_search_including(:fq, 'average_rating_ft:[* TO *]')
  end

  it 'includes by object identity' do
    post = Post.new
    search do
      with post
    end
    connection.should have_last_search_including(:fq, "id:(Post\\ #{post.id})")
  end

  it 'includes multiple objects passed as varargs by object identity' do
    post1, post2 = Post.new, Post.new
    search do
      with post1, post2
    end
    connection.should have_last_search_including(
      :fq, "id:(Post\\ #{post1.id} OR Post\\ #{post2.id})"
    )
  end

  it 'includes multiple objects passed as array by object identity' do
    posts = [Post.new, Post.new]
    search do
      with posts
    end
    connection.should have_last_search_including(
      :fq, "id:(Post\\ #{posts.first.id} OR Post\\ #{posts.last.id})"
    )
  end

  it 'excludes by object identity' do
    post = Post.new
    search do
      without post
    end
    connection.should have_last_search_including(:fq, "-id:(Post\\ #{post.id})")
  end

  it 'excludes multiple objects passed as varargs by object identity' do
    post1, post2 = Post.new, Post.new
    search do
      without post1, post2
    end
    connection.should have_last_search_including(
      :fq,
      "-id:(Post\\ #{post1.id} OR Post\\ #{post2.id})"
    )
  end

  it 'excludes multiple objects passed as array by object identity' do
    posts = [Post.new, Post.new]
    search do
      without posts
    end
    connection.should have_last_search_including(
      :fq,
      "-id:(Post\\ #{posts.first.id} OR Post\\ #{posts.last.id})"
    )
  end

  it 'allows scoping on fields common to all types' do
    time = Time.parse('1983-07-08 05:00:00 -0400')
    search Post, Namespaced::Comment do
      with :published_at, time
    end
    connection.should have_last_search_including(:fq, 'published_at_dt:1983\-07\-08T09\:00\:00Z')
  end

  it 'allows scoping on field not common to all types' do
    search Post, Namespaced::Comment do
      with :blog_id, 1
    end
    connection.should have_last_search_including(:fq, 'blog_id_i:1')
  end

  it 'raises Sunspot::UnrecognizedFieldError if search scoped to field configured differently between types' do
    lambda do
      search Post, Namespaced::Comment do
        with :average_rating, 2.2 # this is a float in Post but an integer in Comment
      end
    end.should raise_error(Sunspot::UnrecognizedFieldError)
  end

  it 'raises Sunspot::UnrecognizedFieldError for nonexistant fields in block scope' do
    lambda do
      search do
        with :bogus, 'Field'
      end
    end.should raise_error(Sunspot::UnrecognizedFieldError)
  end

  it 'raises NoMethodError if bogus operator referenced' do
    lambda do
      search do
        with(:category_ids).resembling :bogus_condition
      end
    end.should raise_error(NoMethodError)
  end

  it 'should raise ArgumentError if more than two arguments passed to scope method' do
    lambda do
      search do
        with(:category_ids, 4, 5)
      end
    end.should raise_error(ArgumentError)
  end
end


text:
package me.lazerka.gae.jersey.oauth2;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.utils.SystemProperty;
import com.google.appengine.api.utils.SystemProperty.Environment.Value;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableSet;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponseFilter;
import me.lazerka.gae.jersey.oauth2.google.GoogleUserPrincipal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.io.IOException;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Set;

import static com.google.appengine.api.utils.SystemProperty.Environment.Value.Development;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

/**
 * Checks requests whether they are authenticated using either GAE or OAuth authentication.
 *
 * You'll probably want to reuse this class to add your own business logic, like using HttpSession or guest accounts.
 *
 * @author Dzmitry Lazerka
 */
public class GaeOauthAuthFilter implements AuthFilter {
	private static final Logger logger = LoggerFactory.getLogger(GaeOauthAuthFilter.class);

	public static final String GAE_AUTH_SCHEME = "GAE";
	public static final String UNAUTHENTICATED_AUTH_SCHEME = "Unauthenticated";

	@Inject
	protected Set<TokenVerifier> tokenVerifiers;

	@Inject
	@Named("default")
	protected TokenVerifier defaultTokenVerifier;

	@Inject
	protected UserService userService;

	protected Set<String> rolesAllowed;

	public void setRolesAllowed(Set<String> rolesAllowed) {
		this.rolesAllowed = rolesAllowed;
	}

	public static boolean isDevServer() {
		Value env = SystemProperty.environment.value();
		return env.equals(Development);
	}

	@Override
	@Nonnull
	public ContainerRequest filter(ContainerRequest request) {
		checkNotNull(rolesAllowed);
		checkState(!tokenVerifiers.isEmpty(), "No tokenVerifiers configured");

		AuthSecurityContext securityContext = getSecurityContext(request);

		for(String roleAllowed : rolesAllowed) {
			if (securityContext.isUserInRole(roleAllowed)) {
				request.setSecurityContext(securityContext);
				return request;
			}
		}

		UserPrincipal principal = securityContext.getUserPrincipal();
		logger.warn("User {} not in roles {}", principal, rolesAllowed);

		throw new WebApplicationException(getForbiddenResponse("Not Authorized"));
	}

	protected AuthSecurityContext getSecurityContext(ContainerRequest request) {
		// Deny all insecure requests on production (@PermitAll requests do not come here at all).
		if (!request.isSecure() && !isDevServer()) {
			logger.warn("Insecure auth, Deny: " + request);
			return throwUnauthenticatedIfNotOptional(request, "Request insecure", null);
		}

		// Check regular GAE authentication.
		if (userService.isUserLoggedIn()) {
			return useGaeAuthentication(request);
		}

		// Check OAuth authentication.
		return useOauthAuthentication(request);
	}

	protected AuthSecurityContext useOauthAuthentication(ContainerRequest request) {
		String authorizationHeader = request.getHeaderValue("Authorization");
		if (authorizationHeader == null) {
			logger.warn("No credentials provided for {}", request.getPath());
			return throwUnauthenticatedIfNotOptional(request, "No credentials provided", null);
		}

		if (authorizationHeader.startsWith("Bearer ")) {
			String token = authorizationHeader.substring("Bearer ".length());
			return useBearerAuthentication(request, token);
		} else {
			logger.warn("Authorization should use Bearer protocol {}", request.getPath());
			return throwUnauthenticatedIfNotOptional(request, "Not Bearer Authorization", null);
		}
	}

	protected AuthSecurityContext useBearerAuthentication(ContainerRequest request, String token) {
		TokenVerifier tokenVerifier = findTokenVerifier(request);

		logger.trace("Authenticating using {} scheme...", tokenVerifier.getAuthenticationScheme());
		try {
			UserPrincipal userPrincipal = tokenVerifier.verify(token);
			return new AuthSecurityContext(
					userPrincipal,
					request.isSecure(),
					ImmutableSet.of(Role.USER, Role.OPTIONAL),
					tokenVerifier.getAuthenticationScheme()
			);
		} catch (GeneralSecurityException e) {
			logger.info(e.getClass().getName() + ": " + e.getMessage());
			return throwUnauthenticatedIfNotOptional(request, "Invalid OAuth2.0 token", e);
		} catch (IOException e) {
			logger.error("IOException verifying OAuth token", e);
			return throwUnauthenticatedIfNotOptional(request, "Error verifying OAuth2.0 token", e);
		}
	}

	protected TokenVerifier findTokenVerifier(ContainerRequest request) {
		for (TokenVerifier tokenVerifier : tokenVerifiers) {
			if (tokenVerifier.canHandle(request)) {
				return tokenVerifier;
			}
		}

		return defaultTokenVerifier;
	}

	protected AuthSecurityContext useGaeAuthentication(ContainerRequest request) {
		Set<String> roles = userService.isUserAdmin()
				? ImmutableSet.of(Role.USER, Role.ADMIN, Role.OPTIONAL)
				: ImmutableSet.of(Role.USER, Role.OPTIONAL);

		User user = userService.getCurrentUser();
		UserPrincipal userPrincipal = new GoogleUserPrincipal(user.getUserId(), user.getEmail());
		return new AuthSecurityContext(
				userPrincipal,
				request.isSecure(),
				roles,
				GAE_AUTH_SCHEME
		);
	}

	/**
	 * Throws 401 Unauthorized, or, if {@link #rolesAllowed} contains {@link Role#OPTIONAL}, returns context.
	 *
	 * @throws WebApplicationException with Status.UNAUTHORIZED (401).
	 */
	protected AuthSecurityContext throwUnauthenticatedIfNotOptional(
			ContainerRequest request,
			String reason,
			@Nullable Exception cause
	) {
		// In case request is AJAX, we want to tell client how to authenticate user.
		String loginUrl = composeLoginUrl(request);

		Response response = Response
				.status(Status.UNAUTHORIZED)
				.type(MediaType.TEXT_PLAIN_TYPE)
				.header("X-Login-URL", loginUrl)
				.entity(reason)
				.build();

		if (rolesAllowed.contains(Role.OPTIONAL)) {
			return new AuthSecurityContext(
					null,
					request.isSecure(),
					ImmutableSet.of(Role.OPTIONAL),
					UNAUTHENTICATED_AUTH_SCHEME
			);
		}

		throw new WebApplicationException(cause, response);
	}

	protected Response getForbiddenResponse(String reason) {
		return Response
				.status(Status.FORBIDDEN)
				.type(MediaType.TEXT_PLAIN_TYPE)
				.entity(reason)
				.build();
	}

	protected String composeLoginUrl(ContainerRequest request) {
		List<String> loginReturnUrls = request.getRequestHeader("X-Login-Return-Url");
		String loginReturnUrl;
		if (loginReturnUrls == null || loginReturnUrls.isEmpty()) {
			loginReturnUrl = request.getRequestUri().toASCIIString();
		} else {
			loginReturnUrl = URI.create(loginReturnUrls.get(0)).toASCIIString();
		}
		return userService.createLoginURL(loginReturnUrl);
	}

	@Override
	public ContainerRequestFilter getRequestFilter() {
		return this;
	}

	@Override
	public ContainerResponseFilter getResponseFilter() {
		return null;
	}

	@Override
	public String toString() {
		return MoreObjects.toStringHelper(this)
				.add("rolesAllowed", rolesAllowed)
				.toString();
	}
}


text:
const MyModal = React.createClass({
  render() {
    return (
      <Modal {...this.props} title='Modal heading' animation={false}>

Text in a modal

Duis mollis, est non commodo luctus, nisi erat porttitor ligula.

Popover in a modal

TODO

Tooltips in a modal

TODO

Overflowing text to show scroll behavior

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

          <Button onClick={this.props.onRequestHide}>Close</Button>

      </Modal>
    );
  }
});

const overlayTriggerInstance = (
  <ModalTrigger modal={<MyModal />}>
    <Button bsStyle='primary' bsSize='large'>Launch demo modal</Button>
  </ModalTrigger>
);

React.render(overlayTriggerInstance, mountNode);


text:
% arara: pdflatex
% arara: bibtex
% arara: pdflatex
% arara: pdflatex

\documentclass[a4paper,11pt]{article}
\pdfoutput=1 % if your are submitting a pdflatex (i.e. if you have
             % images in pdf, png or jpg format)

\usepackage[a4paper,
total={170mm,257mm},
left=20mm,
top=20mm,]{geometry}

\usepackage[dvipsnames]{xcolor}
\usepackage{longtable}
\usepackage{authblk}
\usepackage{hyperref}

\usepackage{titlesec}
\titleformat{\section}[block]{\color{blue}\Large\bfseries\filcenter}{}{1em}{}
\titleformat{\subsection}[hang]{\bfseries}{}{1em}{}

\title{\textcolor{red}{\texttt{\Huge TpMp}} - topology mapping}

\author{Andrey Pikelner}
\affil{II.~Institut f\"ur Theoretische Physik, Universit\"at Hamburg,\\
Luruper Chaussee 149, 22761 Hamburg, Germany}

% \emailAdd{andrey.pikelner@desy.de}

% Mathematica commands in blue
\newcommand{\mma}[1]{\textcolor{BlueGreen}{\texttt{#1}}}
% Color tt
\newcommand{\ctt}[1]{\textcolor{OliveGreen}{\texttt{#1}}}

\setcounter{secnumdepth}{0}
\begin{document}
\maketitle

\abstract{We present program for diagram generation and mapping on
  topology working with \texttt{Mathematica} interface. Available from
  \url{https://github.com/apik/TpMp}}

\section*{Design ideas}

\subsection*{QGRAF input conventions}
\begin{itemize}
\item We use all particles as internal in QGRAF and having momentum
  $p_1,\dots,p_n$. Field out kept blank.
\begin{verbatim}
   in  = q, Q ;
   out = ;
\end{verbatim}

\item All fields in model file must contain field \ctt{type} with
  possible values \ctt{F,M,S,C,A} in addition to
  comutativity flag $\pm$.
\begin{verbatim}
   [ phi, phi, + ; type='S']
\end{verbatim}

\item We set internal momentum to be \ctt{k}
\end{itemize}

\subsection*{DB storage}
\label{sec:dbstore}

\section*{Main commands available in package }

\subsection*{Loading diagrams}
\begingroup
\renewcommand\arraystretch{2}
\begin{longtable}{p{4cm}|p{11cm}}
  \mma{LoadQGRAF["qlist"]}
  & Load \texttt{QGRAF}\cite{Nogueira:1991ex} output \texttt{qlist.yaml} in YAML format produced with the help of
    yaml.sty style file and produce SQLite 3 DB with generated
    diagrams and name \texttt{qlist.sqlite3}.\\
  \mma{nDB=LoadDB["db"]}
  & Load SQLite 3 DB from file \texttt{db.sqlite3} with diagrams and
    return numeric descriptor \texttt{nDB} of open DB.\\
  \mma{GetDia[nDia,nDB]}
  & Retrive diagram with number \texttt{nDia} from DB with descriptor
    \texttt{nDB}.\\
\end{longtable}
\endgroup

When DB loaded all commands need DB decriptor to be specified. If DB
descriptor not specified explicitly - all commands applyed to first
open DB.

\subsection*{Selecting diagrams}

\begingroup
\renewcommand\arraystretch{2}
\begin{longtable}{p{4cm}|p{11cm}}
  \mma{WithField["f"]}
  & Select diagrams with field named "f".\\
  \mma{WithFieldType[T]}
  & Select diagrams with field type \texttt{T}, where \texttt{T} is
  one of: \texttt{F} - for Dirac fermion, \texttt{M} - for Majorana
  fermion, \texttt{S} - for scalar, \texttt{C} - for ghost and
  \texttt{A} - for auxiliary field type.\\
\end{longtable}
\endgroup

\subsection*{Plotting diagrams}

\section{Mapping}
\subsection{\boldmath $U$ and $F$ polynomials}

If we define $P_i=-q_j^2+m_j^2$, than:
\begin{equation}
  \label{eq:MQJdefMass}
  \sum\limits_{j=1}^{n}x_j(-q_j^2+m_j^2)=-\sum\limits_{r=1}^{l}\sum\limits_{s=1}^{l}k_rM_{rs}k_s+\sum\limits_{r=1}^{l}2k_r\cdot
  Q_r+J
\end{equation}
Term $J$ contain all dependence on external momentum products and
masses and can be decomposed:

\begin{equation}
  \label{eq:Jdecompose}
  J=J^{p}+J^{m} = J^{p}(p_i^2,p_i\cdot p_j)+\sum\limits_{j=1}^{n}x_jm_j^2
\end{equation}

If only information about momentum distribution needed we can neglect
masses and use $P$ polynomial instead of $F$

\begin{equation}
  \label{eq:MQJdefNoMass}
  -\sum\limits_{j=1}^{n}x_jq_j^2=-\sum\limits_{r=1}^{l}\sum\limits_{s=1}^{l}k_rM_{rs}k_s+\sum\limits_{r=1}^{l}2k_r\cdot
  Q_r+J^{p}
\end{equation}

And Feynman graph polymnomials defined as
\begin{equation}
  \label{eq:UFMdef}
  U=\det(M),\quad P=\det(M)(J^p+QM^{-1}Q),\quad F=\det(M)(J+QM^{-1}Q).
\end{equation}

$U$ polynomial determine internal structure of diagram, $P$ polynomial
determines external momenta distribution and kinematic of the diagram
and $F$-polynomial determines how masses are distributed between lines.

\begin{verbatim}
<|-x[1] ->
        <|{} -> <|{1} -> {{{}, T12[{1, k1, m1}]}}|>|>,

-x[1] - x[2] ->
        <|{{1, 1}} ->
             <|{1,  1} -> {{{{1, 1} -> -p1^2}, T12[{1, k1,      m1}, {2, k1 + p1, m2}]}},
               {0,  1} -> {{{{1, 1} -> -p1^2}, T02[{2, k1 + p1, m2}, {1, k1, 0}]}},
               {1,  0} -> {{{{1, 1} -> -p1^2}, T10[{1, k1,      m1}, {2, k1 + p1, 0}]}},
               {0,  0} -> {{{{1, 1} -> -p1^2}, T00[{1, k1,       0}, {2, k1 + p1, 0}]}}|>|>|>
\end{verbatim}

\subsection{External momentum flow}
\label{sec:extflow}

It is possible to map diagram with $p_1,\dots,p_n$ external momentum on topology
with $p_1,\dots,p_k,k<n$ external momenta. This mean that momenta flow
for $p_{k+1},\dots,p_n$ kept according to flow in original
diagram. Momentum to be kept should be marked as optional parameter of
\ctt{MapOnAux} function as \ctt{SplitMomenta->\{p2,p3,...\}}.

\subsection{Internal structure}

For set of diagrams it is possible to define ``projections'' i.e.
diagrams with contraints on kinematical variables: masses and external
momentums.

Projections created with the help of command \texttt{Project["pr",subs]} where
parameters \texttt{"pr"} - unique name of projection and \texttt{subs}
- substitution rules.

% \appendix
% \section{Additions}
% \acknowledgments

\bibliographystyle{plain}
\bibliography{TpMp}

\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End:


text:
package com.mongodb.internal.selector;

import com.mongodb.ServerAddress;
import com.mongodb.connection.ClusterDescription;
import com.mongodb.connection.ServerDescription;
import com.mongodb.connection.ServerType;
import org.junit.Test;

import java.net.UnknownHostException;
import java.util.Arrays;

import static com.mongodb.connection.ClusterConnectionMode.MULTIPLE;
import static com.mongodb.connection.ClusterType.REPLICA_SET;
import static com.mongodb.connection.ServerConnectionState.CONNECTED;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class ServerAddressSelectorTest {
    @Test
    public void testAll() throws UnknownHostException {
        ServerAddressSelector selector = new ServerAddressSelector(new ServerAddress("localhost:27018"));

        assertTrue(selector.toString().startsWith("ServerAddressSelector"));

        assertEquals(selector.getServerAddress(), selector.getServerAddress());

        ServerDescription primary = ServerDescription.builder()
                                                     .state(CONNECTED)
                                                     .address(new ServerAddress())
                                                     .ok(true)
                                                     .type(ServerType.REPLICA_SET_PRIMARY)
                                                     .build();
        ServerDescription secondary = ServerDescription.builder()
                                                       .state(CONNECTED)
                                                       .address(new ServerAddress("localhost:27018"))
                                                       .ok(true)
                                                       .type(ServerType.REPLICA_SET_SECONDARY)
                                                       .build();
        assertEquals(Arrays.asList(secondary), selector.select(new ClusterDescription(MULTIPLE, REPLICA_SET,
                                                                                Arrays.asList(primary, secondary))));
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Stilbomyces diptericis Bat. & J.L. Bezerra

### Remarks
null


text:
package co.edu.uniandes.csw.company.persistence;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import co.edu.uniandes.csw.company.entities.DepartmentEntity;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

@Stateless
public class DepartmentPersistence {

    private static final Logger LOGGER = Logger.getLogger(DepartmentPersistence.class.getName());

    @PersistenceContext(unitName = "CompanyPU")
    protected EntityManager em;

    public DepartmentEntity find(Long id) {
        LOGGER.log(Level.INFO, "Consultando department con id={0}", id);
        return em.find(DepartmentEntity.class, id);
    }

    public DepartmentEntity findByName(Long companyId, String departmentName) {
        TypedQuery q = em.createQuery("select d from DepartmentEntity d  where d.company.id = :companyId and d.name = :departmentName", DepartmentEntity.class);
        q = q.setParameter("companyId", companyId);
        q = q.setParameter("departmentName", departmentName);

        List<DepartmentEntity> departmentsSimilarName = q.getResultList();
        if (departmentsSimilarName.isEmpty()) {
            return null;
        } else {
            return departmentsSimilarName.get(0);
        }

    }

    public List<DepartmentEntity> findAll() {
        LOGGER.info("Consultando todos los departments");
        Query q = em.createQuery("select u from DepartmentEntity u");
        return q.getResultList();
    }

    public List<DepartmentEntity> findAllInCompany(Long companyId) {
        LOGGER.log(Level.INFO, "Consultando todos los departments de la company id={0}", companyId);
        TypedQuery q = em.createQuery("select d from DepartmentEntity d  where d.company.id = :companyId", DepartmentEntity.class);
        q = q.setParameter("companyId", companyId);
        return q.getResultList();
    }

    public DepartmentEntity create(DepartmentEntity entity) {
        LOGGER.info("Creando un department nuevo");
        em.persist(entity);
        LOGGER.info("Department creado");
        return entity;
    }

    public DepartmentEntity update(DepartmentEntity entity) {
        LOGGER.log(Level.INFO, "Actualizando department con id={0}", entity.getId());
        return em.merge(entity);
    }

    /**
     *
     * @param id: corresponde a un id válido que existe el deptarment
     * crrespondiente en la base de datos.
     */
    public void delete(Long id) {
        LOGGER.log(Level.INFO, "Borrando department con id={0}", id);
        DepartmentEntity entity = em.find(DepartmentEntity.class, id);
        assert entity != null;
        em.remove(entity);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="Webpixels">

    <title>Purpose Website UI Kit - Professional Website UI Kit by Webpixels</title>

    <link rel="icon" href="../assets/img/brand/favicon.png" type="image/png">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito:300,400,600,700,800">

    <link rel="stylesheet" href="../assets/vendor/@fortawesome/fontawesome-free/css/all.min.css">

    <link href="https://fonts.googleapis.com/css?family=Oswald:400,700" rel="stylesheet">
    <link type="text/css" href="../assets/vendor/@fancyapps/fancybox/dist/jquery.fancybox.min.css" rel="stylesheet">
    <link type="text/css" href="../assets/vendor/swiper/dist/css/swiper.min.css" rel="stylesheet">

    <link rel="stylesheet" href="../assets/css/theme.css">

                <form class="navbar-search-form" role="form">

                            <input type="text" class="form-control" placeholder="Type and hit enter ...">

                </form>

Search Suggestions

                                        macbook pro in Laptops

                                        iphone 8 in Smartphones

                                        macbook pro in Laptops

                                        beats pro solo 3 in Headphones

                                        smasung galaxy 10 in Phones

                        Purpose - Website UI Kit

                                    United States
                                    EN

                                        Spanish

                                        Romanian

                                        Greek

                                Support

                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-main-collapse" aria-controls="navbar-main-collapse" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                            Overview

                            Pages

Landing Pages

A great point to start from.

Secondary Pages

Build your website with these demos.

Account Pages

Account management made easy.

Shop Pages

Explore the full ecommerce website flow.

                            Components

                            Docs

                            Changelog

                            Purchase now

                                Purchase now

Festivals of 2018

Good music only

                                <button type="button" class="btn btn-dark btn-circle" disabled style="cursor: default;">

                                </button>
                                Buy tickets

Next event

15 Apr 2018

Cluj Napoca

Confirmed line-up

You get all Bootstrap components fully customized. Besides, you receive another 5 plugins out of the box and ready to use.

Afrojack

Alesso

Oliver Heldens

Steve Aoki

Bonobo

This month

                                        June
                                        20

Isle of Wight Festival

Meet at United Kingdom on June 20th at 20:00

                                        Get tickets

                                        June
                                        22

Isle of Wight Festival

Meet at United Kingdom on June 20th at 20:00

                                        Get tickets

                                        June
                                        25

Isle of Wight Festival

Meet at United Kingdom on June 20th at 20:00

                                        Get tickets

                                        June
                                        27

Isle of Wight Festival

Meet at United Kingdom on June 20th at 20:00

                                        Get tickets

July

                                        July
                                        03

Isle of Wight Festival

Meet at United Kingdom on June 20th at 20:00

                                        Get tickets

                                        July
                                        05

Isle of Wight Festival

Meet at United Kingdom on June 20th at 20:00

                                        Get tickets

                                        July
                                        13

Isle of Wight Festival

Meet at United Kingdom on June 20th at 20:00

                                        Get tickets

                                        July
                                        15

Isle of Wight Festival

Meet at United Kingdom on June 20th at 20:00

                                        Get tickets

Waves don't die

With Boomerang you get components and examples, including tons of variables that will help you customize this theme with ease.

                            Find out more

You are one step away

I am ready to start a new project with Purpose UI Kit.

                            Purchase now
                            Have an issue?

A unique and beautiful collection of UI elements that are all flexible and modular. A complete and customizable solution to building the website of your dreams.

Account

Profile

Settings

Billing

Notifications

About

Services

Contact

Careers

Company

Terms

Privacy

Support

                        © 2018 Webpixels. All rights reserved.


text:
package ru.job4j;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Класс для тестирования SortUser.
 * @author agavrikov
 * @since 13.07.2017
 * @version 1
 */
public class SortUserTest {
    /**
     * Метод для тестирования сортировки.
     */
    @Test
    public void sort() {
        List<User> list = new ArrayList<User>();
        list.add(new User("Anton", 25));
        list.add(new User("Ivan", 18));
        list.add(new User("Aleksey", 30));
        SortUser sortUser = new SortUser();
        Set<User> sortSet = sortUser.sort(list);

        for (User user : sortSet) {
            String result = user.getName();
            String expected = "Ivan";
            assertThat(result, is(expected));
            break;
        }
    }

    /**
     * Метод для тестирования сортировки по длинне имени.
     */
    @Test
    public void sortNameLength() {
        List<User> list = new ArrayList<User>();
        list.add(new User("Anton", 25));
        list.add(new User("Ivan", 18));
        list.add(new User("Aleksey", 30));
        SortUser sortUser = new SortUser();
        List<User> sortlist = sortUser.sortNameLength(list);

        int result = sortlist.get(2).getName().length();
        int expected = 7;
        assertThat(result, is(expected));
    }

    /**
     * Метод для тестирования сортировки по двум полям.
     */
    @Test
    public void whenSortListThen3ElementWithAge24() {
        List<User> list = new ArrayList<User>();
        list.add(new User("Ivan", 30));
        list.add(new User("Anton", 25));
        list.add(new User("Ivan", 24));
        list.add(new User("Anton", 18));

        SortUser sortUser = new SortUser();
        List<User> sortList = sortUser.sortByAllFields(list);

        int result = sortList.get(2).getAge();
        int expected = 24;
        assertThat(result, is(expected));

    }

    /**
     * Метод для тестирования сортировки по двум полям.
     */
    @Test
    public void sortByAllField1s() {
        List<User> list = new ArrayList<User>();
        list.add(new User("Ivan", 30));
        list.add(new User("Anton", 25));
        list.add(new User("Ivan", 24));
        list.add(new User("Anton", 18));

        SortUser sortUser = new SortUser();
        List<User> sortList = sortUser.sortByAllFields(list);

        String result = sortList.get(0).getName();
        String expected = "Anton";
        assertThat(result, is(expected));

    }

    /**
     * Метод для тестирования сортировки по двум полям.
     */
    @Test
    public void sortByAllField1sWithameAge() {
        List<User> list = new ArrayList<User>();
        list.add(new User("Tim", 30));
        list.add(new User("Anton", 25));
        list.add(new User("Alex", 30));
        list.add(new User("Anton", 25));

        SortUser sortUser = new SortUser();
        Set<User> sortList = sortUser.sort(list);

        int result = sortList.size();
        int expected = 4;
        assertThat(result, is(expected));

    }
}


text:
@interface GameSceneViewController : UIViewController

@end