text:
<?php

/**
 * Base class that represents a row from the 'sistema' table.
 *
 *
 *
 * @package    propel.generator.semp.om
 */
abstract class BaseSistema extends BaseObject implements Persistent
{
    /**
     * Peer class name
     */
    const PEER = 'SistemaPeer';

    /**
     * The Peer class.
     * Instance provides a convenient way of calling static methods on a class
     * that calling code may not be able to identify.
     * @var        SistemaPeer
     */
    protected static $peer;

    /**
     * The flag var to prevent infinit loop in deep copy
     * @var       boolean
     */
    protected $startCopy = false;

    /**
     * The value for the co_sistema field.
     * @var        int
     */
    protected $co_sistema;

    /**
     * The value for the no_empresa field.
     * @var        string
     */
    protected $no_empresa;

    /**
     * The value for the no_dominio field.
     * @var        string
     */
    protected $no_dominio;

    /**
     * @var        PropelObjectCollection|Colaborador[] Collection to store aggregation of Colaborador objects.
     */
    protected $collColaboradors;
    protected $collColaboradorsPartial;

    /**
     * Flag to prevent endless save loop, if this object is referenced
     * by another object which falls in this transaction.
     * @var        boolean
     */
    protected $alreadyInSave = false;

    /**
     * Flag to prevent endless validation loop, if this object is referenced
     * by another object which falls in this transaction.
     * @var        boolean
     */
    protected $alreadyInValidation = false;

    /**
     * Flag to prevent endless clearAllReferences($deep=true) loop, if this object is referenced
     * @var        boolean
     */
    protected $alreadyInClearAllReferencesDeep = false;

    /**
     * An array of objects scheduled for deletion.
     * @var		PropelObjectCollection
     */
    protected $colaboradorsScheduledForDeletion = null;

    /**
     * Get the [co_sistema] column value.
     *
     * @return int
     */
    public function getCoSistema()
    {
        return $this->co_sistema;
    }

    /**
     * Get the [no_empresa] column value.
     *
     * @return string
     */
    public function getNoEmpresa()
    {
        return $this->no_empresa;
    }

    /**
     * Get the [no_dominio] column value.
     *
     * @return string
     */
    public function getNoDominio()
    {
        return $this->no_dominio;
    }

    /**
     * Set the value of [co_sistema] column.
     *
     * @param int $v new value
     * @return Sistema The current object (for fluent API support)
     */
    public function setCoSistema($v)
    {
        if ($v !== null && is_numeric($v)) {
            $v = (int) $v;
        }

        if ($this->co_sistema !== $v) {
            $this->co_sistema = $v;
            $this->modifiedColumns[] = SistemaPeer::CO_SISTEMA;
        }

        return $this;
    } // setCoSistema()

    /**
     * Set the value of [no_empresa] column.
     *
     * @param string $v new value
     * @return Sistema The current object (for fluent API support)
     */
    public function setNoEmpresa($v)
    {
        if ($v !== null && is_numeric($v)) {
            $v = (string) $v;
        }

        if ($this->no_empresa !== $v) {
            $this->no_empresa = $v;
            $this->modifiedColumns[] = SistemaPeer::NO_EMPRESA;
        }

        return $this;
    } // setNoEmpresa()

    /**
     * Set the value of [no_dominio] column.
     *
     * @param string $v new value
     * @return Sistema The current object (for fluent API support)
     */
    public function setNoDominio($v)
    {
        if ($v !== null && is_numeric($v)) {
            $v = (string) $v;
        }

        if ($this->no_dominio !== $v) {
            $this->no_dominio = $v;
            $this->modifiedColumns[] = SistemaPeer::NO_DOMINIO;
        }

        return $this;
    } // setNoDominio()

    /**
     * Indicates whether the columns in this object are only set to default values.
     *
     * This method can be used in conjunction with isModified() to indicate whether an object is both
     * modified _and_ has some values set which are non-default.
     *
     * @return boolean Whether the columns in this object are only been set with default values.
     */
    public function hasOnlyDefaultValues()
    {
        // otherwise, everything was equal, so return true
        return true;
    } // hasOnlyDefaultValues()

    /**
     * Hydrates (populates) the object variables with values from the database resultset.
     *
     * An offset (0-based "start column") is specified so that objects can be hydrated
     * with a subset of the columns in the resultset rows.  This is needed, for example,
     * for results of JOIN queries where the resultset row includes columns from two or
     * more tables.
     *
     * @param array $row The row returned by PDOStatement->fetch(PDO::FETCH_NUM)
     * @param int $startcol 0-based offset column which indicates which restultset column to start with.
     * @param boolean $rehydrate Whether this object is being re-hydrated from the database.
     * @return int             next starting column
     * @throws PropelException - Any caught Exception will be rewrapped as a PropelException.
     */
    public function hydrate($row, $startcol = 0, $rehydrate = false)
    {
        try {

            $this->co_sistema = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null;
            $this->no_empresa = ($row[$startcol + 1] !== null) ? (string) $row[$startcol + 1] : null;
            $this->no_dominio = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null;
            $this->resetModified();

            $this->setNew(false);

            if ($rehydrate) {
                $this->ensureConsistency();
            }
            $this->postHydrate($row, $startcol, $rehydrate);
            return $startcol + 3; // 3 = SistemaPeer::NUM_HYDRATE_COLUMNS.

        } catch (Exception $e) {
            throw new PropelException("Error populating Sistema object", $e);
        }
    }

    /**
     * Checks and repairs the internal consistency of the object.
     *
     * This method is executed after an already-instantiated object is re-hydrated
     * from the database.  It exists to check any foreign keys to make sure that
     * the objects related to the current object are correct based on foreign key.
     *
     * You can override this method in the stub class, but you should always invoke
     * the base method from the overridden method (i.e. parent::ensureConsistency()),
     * in case your model changes.
     *
     * @throws PropelException
     */
    public function ensureConsistency()
    {

    } // ensureConsistency

    /**
     * Reloads this object from datastore based on primary key and (optionally) resets all associated objects.
     *
     * This will only work if the object has been saved and has a valid primary key set.
     *
     * @param boolean $deep (optional) Whether to also de-associated any related objects.
     * @param PropelPDO $con (optional) The PropelPDO connection to use.
     * @return void
     * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db
     */
    public function reload($deep = false, PropelPDO $con = null)
    {
        if ($this->isDeleted()) {
            throw new PropelException("Cannot reload a deleted object.");
        }

        if ($this->isNew()) {
            throw new PropelException("Cannot reload an unsaved object.");
        }

        if ($con === null) {
            $con = Propel::getConnection(SistemaPeer::DATABASE_NAME, Propel::CONNECTION_READ);
        }

        // We don't need to alter the object instance pool; we're just modifying this instance
        // already in the pool.

        $stmt = SistemaPeer::doSelectStmt($this->buildPkeyCriteria(), $con);
        $row = $stmt->fetch(PDO::FETCH_NUM);
        $stmt->closeCursor();
        if (!$row) {
            throw new PropelException('Cannot find matching row in the database to reload object values.');
        }
        $this->hydrate($row, 0, true); // rehydrate

        if ($deep) {  // also de-associate any related objects?

            $this->collColaboradors = null;

        } // if (deep)
    }

    /**
     * Removes this object from datastore and sets delete attribute.
     *
     * @param PropelPDO $con
     * @return void
     * @throws PropelException
     * @throws Exception
     * @see        BaseObject::setDeleted()
     * @see        BaseObject::isDeleted()
     */
    public function delete(PropelPDO $con = null)
    {
        if ($this->isDeleted()) {
            throw new PropelException("This object has already been deleted.");
        }

        if ($con === null) {
            $con = Propel::getConnection(SistemaPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
        }

        $con->beginTransaction();
        try {
            $deleteQuery = SistemaQuery::create()
                ->filterByPrimaryKey($this->getPrimaryKey());
            $ret = $this->preDelete($con);
            if ($ret) {
                $deleteQuery->delete($con);
                $this->postDelete($con);
                $con->commit();
                $this->setDeleted(true);
            } else {
                $con->commit();
            }
        } catch (Exception $e) {
            $con->rollBack();
            throw $e;
        }
    }

    /**
     * Persists this object to the database.
     *
     * If the object is new, it inserts it; otherwise an update is performed.
     * All modified related objects will also be persisted in the doSave()
     * method.  This method wraps all precipitate database operations in a
     * single transaction.
     *
     * @param PropelPDO $con
     * @return int             The number of rows affected by this insert/update and any referring fk objects' save() operations.
     * @throws PropelException
     * @throws Exception
     * @see        doSave()
     */
    public function save(PropelPDO $con = null)
    {
        if ($this->isDeleted()) {
            throw new PropelException("You cannot save an object that has been deleted.");
        }

        if ($con === null) {
            $con = Propel::getConnection(SistemaPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
        }

        $con->beginTransaction();
        $isInsert = $this->isNew();
        try {
            $ret = $this->preSave($con);
            if ($isInsert) {
                $ret = $ret && $this->preInsert($con);
            } else {
                $ret = $ret && $this->preUpdate($con);
            }
            if ($ret) {
                $affectedRows = $this->doSave($con);
                if ($isInsert) {
                    $this->postInsert($con);
                } else {
                    $this->postUpdate($con);
                }
                $this->postSave($con);
                SistemaPeer::addInstanceToPool($this);
            } else {
                $affectedRows = 0;
            }
            $con->commit();

            return $affectedRows;
        } catch (Exception $e) {
            $con->rollBack();
            throw $e;
        }
    }

    /**
     * Performs the work of inserting or updating the row in the database.
     *
     * If the object is new, it inserts it; otherwise an update is performed.
     * All related objects are also updated in this method.
     *
     * @param PropelPDO $con
     * @return int             The number of rows affected by this insert/update and any referring fk objects' save() operations.
     * @throws PropelException
     * @see        save()
     */
    protected function doSave(PropelPDO $con)
    {
        $affectedRows = 0; // initialize var to track total num of affected rows
        if (!$this->alreadyInSave) {
            $this->alreadyInSave = true;

            if ($this->isNew() || $this->isModified()) {
                // persist changes
                if ($this->isNew()) {
                    $this->doInsert($con);
                } else {
                    $this->doUpdate($con);
                }
                $affectedRows += 1;
                $this->resetModified();
            }

            if ($this->colaboradorsScheduledForDeletion !== null) {
                if (!$this->colaboradorsScheduledForDeletion->isEmpty()) {
                    ColaboradorQuery::create()
                        ->filterByPrimaryKeys($this->colaboradorsScheduledForDeletion->getPrimaryKeys(false))
                        ->delete($con);
                    $this->colaboradorsScheduledForDeletion = null;
                }
            }

            if ($this->collColaboradors !== null) {
                foreach ($this->collColaboradors as $referrerFK) {
                    if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) {
                        $affectedRows += $referrerFK->save($con);
                    }
                }
            }

            $this->alreadyInSave = false;

        }

        return $affectedRows;
    } // doSave()

    /**
     * Insert the row in the database.
     *
     * @param PropelPDO $con
     *
     * @throws PropelException
     * @see        doSave()
     */
    protected function doInsert(PropelPDO $con)
    {
        $modifiedColumns = array();
        $index = 0;

        $this->modifiedColumns[] = SistemaPeer::CO_SISTEMA;
        if (null !== $this->co_sistema) {
            throw new PropelException('Cannot insert a value for auto-increment primary key (' . SistemaPeer::CO_SISTEMA . ')');
        }
        if (null === $this->co_sistema) {
            try {
                $stmt = $con->query("SELECT nextval('sistema_co_sistema_seq')");
                $row = $stmt->fetch(PDO::FETCH_NUM);
                $this->co_sistema = $row[0];
            } catch (Exception $e) {
                throw new PropelException('Unable to get sequence id.', $e);
            }
        }

         // check the columns in natural order for more readable SQL queries
        if ($this->isColumnModified(SistemaPeer::CO_SISTEMA)) {
            $modifiedColumns[':p' . $index++]  = 'co_sistema';
        }
        if ($this->isColumnModified(SistemaPeer::NO_EMPRESA)) {
            $modifiedColumns[':p' . $index++]  = 'no_empresa';
        }
        if ($this->isColumnModified(SistemaPeer::NO_DOMINIO)) {
            $modifiedColumns[':p' . $index++]  = 'no_dominio';
        }

        $sql = sprintf(
            'INSERT INTO sistema (%s) VALUES (%s)',
            implode(', ', $modifiedColumns),
            implode(', ', array_keys($modifiedColumns))
        );

        try {
            $stmt = $con->prepare($sql);
            foreach ($modifiedColumns as $identifier => $columnName) {
                switch ($columnName) {
                    case 'co_sistema':
                        $stmt->bindValue($identifier, $this->co_sistema, PDO::PARAM_INT);
                        break;
                    case 'no_empresa':
                        $stmt->bindValue($identifier, $this->no_empresa, PDO::PARAM_STR);
                        break;
                    case 'no_dominio':
                        $stmt->bindValue($identifier, $this->no_dominio, PDO::PARAM_STR);
                        break;
                }
            }
            $stmt->execute();
        } catch (Exception $e) {
            Propel::log($e->getMessage(), Propel::LOG_ERR);
            throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), $e);
        }

        $this->setNew(false);
    }

    /**
     * Update the row in the database.
     *
     * @param PropelPDO $con
     *
     * @see        doSave()
     */
    protected function doUpdate(PropelPDO $con)
    {
        $selectCriteria = $this->buildPkeyCriteria();
        $valuesCriteria = $this->buildCriteria();
        BasePeer::doUpdate($selectCriteria, $valuesCriteria, $con);
    }

    /**
     * Array of ValidationFailed objects.
     * @var        array ValidationFailed[]
     */
    protected $validationFailures = array();

    /**
     * Gets any ValidationFailed objects that resulted from last call to validate().
     *
     *
     * @return array ValidationFailed[]
     * @see        validate()
     */
    public function getValidationFailures()
    {
        return $this->validationFailures;
    }

    /**
     * Validates the objects modified field values and all objects related to this table.
     *
     * If $columns is either a column name or an array of column names
     * only those columns are validated.
     *
     * @param mixed $columns Column name or an array of column names.
     * @return boolean Whether all columns pass validation.
     * @see        doValidate()
     * @see        getValidationFailures()
     */
    public function validate($columns = null)
    {
        $res = $this->doValidate($columns);
        if ($res === true) {
            $this->validationFailures = array();

            return true;
        }

        $this->validationFailures = $res;

        return false;
    }

    /**
     * This function performs the validation work for complex object models.
     *
     * In addition to checking the current object, all related objects will
     * also be validated.  If all pass then true is returned; otherwise
     * an aggreagated array of ValidationFailed objects will be returned.
     *
     * @param array $columns Array of column names to validate.
     * @return mixed true if all validations pass; array of ValidationFailed objets otherwise.
     */
    protected function doValidate($columns = null)
    {
        if (!$this->alreadyInValidation) {
            $this->alreadyInValidation = true;
            $retval = null;

            $failureMap = array();

            if (($retval = SistemaPeer::doValidate($this, $columns)) !== true) {
                $failureMap = array_merge($failureMap, $retval);
            }

                if ($this->collColaboradors !== null) {
                    foreach ($this->collColaboradors as $referrerFK) {
                        if (!$referrerFK->validate($columns)) {
                            $failureMap = array_merge($failureMap, $referrerFK->getValidationFailures());
                        }
                    }
                }

            $this->alreadyInValidation = false;
        }

        return (!empty($failureMap) ? $failureMap : true);
    }

    /**
     * Retrieves a field from the object by name passed in as a string.
     *
     * @param string $name name
     * @param string $type The type of fieldname the $name is of:
     *               one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
     *               BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM.
     *               Defaults to BasePeer::TYPE_PHPNAME
     * @return mixed Value of field.
     */
    public function getByName($name, $type = BasePeer::TYPE_PHPNAME)
    {
        $pos = SistemaPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
        $field = $this->getByPosition($pos);

        return $field;
    }

    /**
     * Retrieves a field from the object by Position as specified in the xml schema.
     * Zero-based.
     *
     * @param int $pos position in xml schema
     * @return mixed Value of field at $pos
     */
    public function getByPosition($pos)
    {
        switch ($pos) {
            case 0:
                return $this->getCoSistema();
                break;
            case 1:
                return $this->getNoEmpresa();
                break;
            case 2:
                return $this->getNoDominio();
                break;
            default:
                return null;
                break;
        } // switch()
    }

    /**
     * Exports the object as an array.
     *
     * You can specify the key type of the array by passing one of the class
     * type constants.
     *
     * @param     string  $keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME,
     *                    BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM.
     *                    Defaults to BasePeer::TYPE_PHPNAME.
     * @param     boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to true.
     * @param     array $alreadyDumpedObjects List of objects to skip to avoid recursion
     * @param     boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE.
     *
     * @return array an associative array containing the field names (as keys) and field values
     */
    public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false)
    {
        if (isset($alreadyDumpedObjects['Sistema'][$this->getPrimaryKey()])) {
            return '*RECURSION*';
        }
        $alreadyDumpedObjects['Sistema'][$this->getPrimaryKey()] = true;
        $keys = SistemaPeer::getFieldNames($keyType);
        $result = array(
            $keys[0] => $this->getCoSistema(),
            $keys[1] => $this->getNoEmpresa(),
            $keys[2] => $this->getNoDominio(),
        );
        if ($includeForeignObjects) {
            if (null !== $this->collColaboradors) {
                $result['Colaboradors'] = $this->collColaboradors->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects);
            }
        }

        return $result;
    }

    /**
     * Sets a field from the object by name passed in as a string.
     *
     * @param string $name peer name
     * @param mixed $value field value
     * @param string $type The type of fieldname the $name is of:
     *                     one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
     *                     BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM.
     *                     Defaults to BasePeer::TYPE_PHPNAME
     * @return void
     */
    public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME)
    {
        $pos = SistemaPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);

        $this->setByPosition($pos, $value);
    }

    /**
     * Sets a field from the object by Position as specified in the xml schema.
     * Zero-based.
     *
     * @param int $pos position in xml schema
     * @param mixed $value field value
     * @return void
     */
    public function setByPosition($pos, $value)
    {
        switch ($pos) {
            case 0:
                $this->setCoSistema($value);
                break;
            case 1:
                $this->setNoEmpresa($value);
                break;
            case 2:
                $this->setNoDominio($value);
                break;
        } // switch()
    }

    /**
     * Populates the object using an array.
     *
     * This is particularly useful when populating an object from one of the
     * request arrays (e.g. $_POST).  This method goes through the column
     * names, checking to see whether a matching key exists in populated
     * array. If so the setByName() method is called for that column.
     *
     * You can specify the key type of the array by additionally passing one
     * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME,
     * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM.
     * The default key type is the column's BasePeer::TYPE_PHPNAME
     *
     * @param array  $arr     An array to populate the object from.
     * @param string $keyType The type of keys the array uses.
     * @return void
     */
    public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME)
    {
        $keys = SistemaPeer::getFieldNames($keyType);

        if (array_key_exists($keys[0], $arr)) $this->setCoSistema($arr[$keys[0]]);
        if (array_key_exists($keys[1], $arr)) $this->setNoEmpresa($arr[$keys[1]]);
        if (array_key_exists($keys[2], $arr)) $this->setNoDominio($arr[$keys[2]]);
    }

    /**
     * Build a Criteria object containing the values of all modified columns in this object.
     *
     * @return Criteria The Criteria object containing all modified values.
     */
    public function buildCriteria()
    {
        $criteria = new Criteria(SistemaPeer::DATABASE_NAME);

        if ($this->isColumnModified(SistemaPeer::CO_SISTEMA)) $criteria->add(SistemaPeer::CO_SISTEMA, $this->co_sistema);
        if ($this->isColumnModified(SistemaPeer::NO_EMPRESA)) $criteria->add(SistemaPeer::NO_EMPRESA, $this->no_empresa);
        if ($this->isColumnModified(SistemaPeer::NO_DOMINIO)) $criteria->add(SistemaPeer::NO_DOMINIO, $this->no_dominio);

        return $criteria;
    }

    /**
     * Builds a Criteria object containing the primary key for this object.
     *
     * Unlike buildCriteria() this method includes the primary key values regardless
     * of whether or not they have been modified.
     *
     * @return Criteria The Criteria object containing value(s) for primary key(s).
     */
    public function buildPkeyCriteria()
    {
        $criteria = new Criteria(SistemaPeer::DATABASE_NAME);
        $criteria->add(SistemaPeer::CO_SISTEMA, $this->co_sistema);

        return $criteria;
    }

    /**
     * Returns the primary key for this object (row).
     * @return int
     */
    public function getPrimaryKey()
    {
        return $this->getCoSistema();
    }

    /**
     * Generic method to set the primary key (co_sistema column).
     *
     * @param  int $key Primary key.
     * @return void
     */
    public function setPrimaryKey($key)
    {
        $this->setCoSistema($key);
    }

    /**
     * Returns true if the primary key for this object is null.
     * @return boolean
     */
    public function isPrimaryKeyNull()
    {

        return null === $this->getCoSistema();
    }

    /**
     * Sets contents of passed object to values from current object.
     *
     * If desired, this method can also make copies of all associated (fkey referrers)
     * objects.
     *
     * @param object $copyObj An object of Sistema (or compatible) type.
     * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
     * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new.
     * @throws PropelException
     */
    public function copyInto($copyObj, $deepCopy = false, $makeNew = true)
    {
        $copyObj->setNoEmpresa($this->getNoEmpresa());
        $copyObj->setNoDominio($this->getNoDominio());

        if ($deepCopy && !$this->startCopy) {
            // important: temporarily setNew(false) because this affects the behavior of
            // the getter/setter methods for fkey referrer objects.
            $copyObj->setNew(false);
            // store object hash to prevent cycle
            $this->startCopy = true;

            foreach ($this->getColaboradors() as $relObj) {
                if ($relObj !== $this) {  // ensure that we don't try to copy a reference to ourselves
                    $copyObj->addColaborador($relObj->copy($deepCopy));
                }
            }

            //unflag object copy
            $this->startCopy = false;
        } // if ($deepCopy)

        if ($makeNew) {
            $copyObj->setNew(true);
            $copyObj->setCoSistema(NULL); // this is a auto-increment column, so set to default value
        }
    }

    /**
     * Makes a copy of this object that will be inserted as a new row in table when saved.
     * It creates a new object filling in the simple attributes, but skipping any primary
     * keys that are defined for the table.
     *
     * If desired, this method can also make copies of all associated (fkey referrers)
     * objects.
     *
     * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
     * @return Sistema Clone of current object.
     * @throws PropelException
     */
    public function copy($deepCopy = false)
    {
        // we use get_class(), because this might be a subclass
        $clazz = get_class($this);
        $copyObj = new $clazz();
        $this->copyInto($copyObj, $deepCopy);

        return $copyObj;
    }

    /**
     * Returns a peer instance associated with this om.
     *
     * Since Peer classes are not to have any instance attributes, this method returns the
     * same instance for all member of this class. The method could therefore
     * be static, but this would prevent one from overriding the behavior.
     *
     * @return SistemaPeer
     */
    public function getPeer()
    {
        if (self::$peer === null) {
            self::$peer = new SistemaPeer();
        }

        return self::$peer;
    }

    /**
     * Initializes a collection based on the name of a relation.
     * Avoids crafting an 'init[$relationName]s' method name
     * that wouldn't work when StandardEnglishPluralizer is used.
     *
     * @param string $relationName The name of the relation to initialize
     * @return void
     */
    public function initRelation($relationName)
    {
        if ('Colaborador' == $relationName) {
            $this->initColaboradors();
        }
    }

    /**
     * Clears out the collColaboradors collection
     *
     * This does not modify the database; however, it will remove any associated objects, causing
     * them to be refetched by subsequent calls to accessor method.
     *
     * @return Sistema The current object (for fluent API support)
     * @see        addColaboradors()
     */
    public function clearColaboradors()
    {
        $this->collColaboradors = null; // important to set this to null since that means it is uninitialized
        $this->collColaboradorsPartial = null;

        return $this;
    }

    /**
     * reset is the collColaboradors collection loaded partially
     *
     * @return void
     */
    public function resetPartialColaboradors($v = true)
    {
        $this->collColaboradorsPartial = $v;
    }

    /**
     * Initializes the collColaboradors collection.
     *
     * By default this just sets the collColaboradors collection to an empty array (like clearcollColaboradors());
     * however, you may wish to override this method in your stub class to provide setting appropriate
     * to your application -- for example, setting the initial array to the values stored in database.
     *
     * @param boolean $overrideExisting If set to true, the method call initializes
     *                                        the collection even if it is not empty
     *
     * @return void
     */
    public function initColaboradors($overrideExisting = true)
    {
        if (null !== $this->collColaboradors && !$overrideExisting) {
            return;
        }
        $this->collColaboradors = new PropelObjectCollection();
        $this->collColaboradors->setModel('Colaborador');
    }

    /**
     * Gets an array of Colaborador objects which contain a foreign key that references this object.
     *
     * If the $criteria is not null, it is used to always fetch the results from the database.
     * Otherwise the results are fetched from the database the first time, then cached.
     * Next time the same method is called without $criteria, the cached collection is returned.
     * If this Sistema is new, it will return
     * an empty collection or the current collection; the criteria is ignored on a new object.
     *
     * @param Criteria $criteria optional Criteria object to narrow the query
     * @param PropelPDO $con optional connection object
     * @return PropelObjectCollection|Colaborador[] List of Colaborador objects
     * @throws PropelException
     */
    public function getColaboradors($criteria = null, PropelPDO $con = null)
    {
        $partial = $this->collColaboradorsPartial && !$this->isNew();
        if (null === $this->collColaboradors || null !== $criteria  || $partial) {
            if ($this->isNew() && null === $this->collColaboradors) {
                // return empty collection
                $this->initColaboradors();
            } else {
                $collColaboradors = ColaboradorQuery::create(null, $criteria)
                    ->filterBySistema($this)
                    ->find($con);
                if (null !== $criteria) {
                    if (false !== $this->collColaboradorsPartial && count($collColaboradors)) {
                      $this->initColaboradors(false);

                      foreach($collColaboradors as $obj) {
                        if (false == $this->collColaboradors->contains($obj)) {
                          $this->collColaboradors->append($obj);
                        }
                      }

                      $this->collColaboradorsPartial = true;
                    }

                    $collColaboradors->getInternalIterator()->rewind();
                    return $collColaboradors;
                }

                if($partial && $this->collColaboradors) {
                    foreach($this->collColaboradors as $obj) {
                        if($obj->isNew()) {
                            $collColaboradors[] = $obj;
                        }
                    }
                }

                $this->collColaboradors = $collColaboradors;
                $this->collColaboradorsPartial = false;
            }
        }

        return $this->collColaboradors;
    }

    /**
     * Sets a collection of Colaborador objects related by a one-to-many relationship
     * to the current object.
     * It will also schedule objects for deletion based on a diff between old objects (aka persisted)
     * and new objects from the given Propel collection.
     *
     * @param PropelCollection $colaboradors A Propel collection.
     * @param PropelPDO $con Optional connection object
     * @return Sistema The current object (for fluent API support)
     */
    public function setColaboradors(PropelCollection $colaboradors, PropelPDO $con = null)
    {
        $colaboradorsToDelete = $this->getColaboradors(new Criteria(), $con)->diff($colaboradors);

        $this->colaboradorsScheduledForDeletion = unserialize(serialize($colaboradorsToDelete));

        foreach ($colaboradorsToDelete as $colaboradorRemoved) {
            $colaboradorRemoved->setSistema(null);
        }

        $this->collColaboradors = null;
        foreach ($colaboradors as $colaborador) {
            $this->addColaborador($colaborador);
        }

        $this->collColaboradors = $colaboradors;
        $this->collColaboradorsPartial = false;

        return $this;
    }

    /**
     * Returns the number of related Colaborador objects.
     *
     * @param Criteria $criteria
     * @param boolean $distinct
     * @param PropelPDO $con
     * @return int             Count of related Colaborador objects.
     * @throws PropelException
     */
    public function countColaboradors(Criteria $criteria = null, $distinct = false, PropelPDO $con = null)
    {
        $partial = $this->collColaboradorsPartial && !$this->isNew();
        if (null === $this->collColaboradors || null !== $criteria || $partial) {
            if ($this->isNew() && null === $this->collColaboradors) {
                return 0;
            }

            if($partial && !$criteria) {
                return count($this->getColaboradors());
            }
            $query = ColaboradorQuery::create(null, $criteria);
            if ($distinct) {
                $query->distinct();
            }

            return $query
                ->filterBySistema($this)
                ->count($con);
        }

        return count($this->collColaboradors);
    }

    /**
     * Method called to associate a Colaborador object to this object
     * through the Colaborador foreign key attribute.
     *
     * @param    Colaborador $l Colaborador
     * @return Sistema The current object (for fluent API support)
     */
    public function addColaborador(Colaborador $l)
    {
        if ($this->collColaboradors === null) {
            $this->initColaboradors();
            $this->collColaboradorsPartial = true;
        }
        if (!in_array($l, $this->collColaboradors->getArrayCopy(), true)) { // only add it if the **same** object is not already associated
            $this->doAddColaborador($l);
        }

        return $this;
    }

    /**
     * @param	Colaborador $colaborador The colaborador object to add.
     */
    protected function doAddColaborador($colaborador)
    {
        $this->collColaboradors[]= $colaborador;
        $colaborador->setSistema($this);
    }

    /**
     * @param	Colaborador $colaborador The colaborador object to remove.
     * @return Sistema The current object (for fluent API support)
     */
    public function removeColaborador($colaborador)
    {
        if ($this->getColaboradors()->contains($colaborador)) {
            $this->collColaboradors->remove($this->collColaboradors->search($colaborador));
            if (null === $this->colaboradorsScheduledForDeletion) {
                $this->colaboradorsScheduledForDeletion = clone $this->collColaboradors;
                $this->colaboradorsScheduledForDeletion->clear();
            }
            $this->colaboradorsScheduledForDeletion[]= clone $colaborador;
            $colaborador->setSistema(null);
        }

        return $this;
    }

    /**
     * Clears the current object and sets all attributes to their default values
     */
    public function clear()
    {
        $this->co_sistema = null;
        $this->no_empresa = null;
        $this->no_dominio = null;
        $this->alreadyInSave = false;
        $this->alreadyInValidation = false;
        $this->alreadyInClearAllReferencesDeep = false;
        $this->clearAllReferences();
        $this->resetModified();
        $this->setNew(true);
        $this->setDeleted(false);
    }

    /**
     * Resets all references to other model objects or collections of model objects.
     *
     * This method is a user-space workaround for PHP's inability to garbage collect
     * objects with circular references (even in PHP 5.3). This is currently necessary
     * when using Propel in certain daemon or large-volumne/high-memory operations.
     *
     * @param boolean $deep Whether to also clear the references on all referrer objects.
     */
    public function clearAllReferences($deep = false)
    {
        if ($deep && !$this->alreadyInClearAllReferencesDeep) {
            $this->alreadyInClearAllReferencesDeep = true;
            if ($this->collColaboradors) {
                foreach ($this->collColaboradors as $o) {
                    $o->clearAllReferences($deep);
                }
            }

            $this->alreadyInClearAllReferencesDeep = false;
        } // if ($deep)

        if ($this->collColaboradors instanceof PropelCollection) {
            $this->collColaboradors->clearIterator();
        }
        $this->collColaboradors = null;
    }

    /**
     * return the string representation of this object
     *
     * @return string
     */
    public function __toString()
    {
        return (string) $this->exportTo(SistemaPeer::DEFAULT_STRING_FORMAT);
    }

    /**
     * return true is the object is in saving state
     *
     * @return boolean
     */
    public function isAlreadyInSave()
    {
        return $this->alreadyInSave;
    }

}


text:
import numpy as np
import pytest

from sklearn.compose import make_column_transformer
from sklearn.datasets import load_breast_cancer, make_classification
from sklearn.exceptions import NotFittedError
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, precision_recall_curve
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC, SVR
from sklearn.utils import shuffle

from sklearn.metrics import PrecisionRecallDisplay, plot_precision_recall_curve

# TODO: Remove when https://github.com/numpy/numpy/issues/14397 is resolved
pytestmark = pytest.mark.filterwarnings(
    "ignore:In future, it will be an error for 'np.bool_':DeprecationWarning:"
    "matplotlib.*"
)

def test_precision_recall_display_validation(pyplot):
    """Check that we raise the proper error when validating parameters."""
    X, y = make_classification(
        n_samples=100, n_informative=5, n_classes=5, random_state=0
    )

    with pytest.raises(NotFittedError):
        PrecisionRecallDisplay.from_estimator(SVC(), X, y)

    regressor = SVR().fit(X, y)
    y_pred_regressor = regressor.predict(X)
    classifier = SVC(probability=True).fit(X, y)
    y_pred_classifier = classifier.predict_proba(X)[:, -1]

    err_msg = "PrecisionRecallDisplay.from_estimator only supports classifiers"
    with pytest.raises(ValueError, match=err_msg):
        PrecisionRecallDisplay.from_estimator(regressor, X, y)

    err_msg = "Expected 'estimator' to be a binary classifier, but got SVC"
    with pytest.raises(ValueError, match=err_msg):
        PrecisionRecallDisplay.from_estimator(classifier, X, y)

    err_msg = "{} format is not supported"
    with pytest.raises(ValueError, match=err_msg.format("continuous")):
        # Force `y_true` to be seen as a regression problem
        PrecisionRecallDisplay.from_predictions(y + 0.5, y_pred_classifier, pos_label=1)
    with pytest.raises(ValueError, match=err_msg.format("multiclass")):
        PrecisionRecallDisplay.from_predictions(y, y_pred_regressor, pos_label=1)

    err_msg = "Found input variables with inconsistent numbers of samples"
    with pytest.raises(ValueError, match=err_msg):
        PrecisionRecallDisplay.from_predictions(y, y_pred_classifier[::2])

    X, y = make_classification(n_classes=2, n_samples=50, random_state=0)
    y += 10
    classifier.fit(X, y)
    y_pred_classifier = classifier.predict_proba(X)[:, -1]
    err_msg = r"y_true takes value in {10, 11} and pos_label is not specified"
    with pytest.raises(ValueError, match=err_msg):
        PrecisionRecallDisplay.from_predictions(y, y_pred_classifier)

# FIXME: Remove in 1.2
def test_plot_precision_recall_curve_deprecation(pyplot):
    """Check that we raise a FutureWarning when calling
    `plot_precision_recall_curve`."""

    X, y = make_classification(random_state=0)
    clf = LogisticRegression().fit(X, y)
    deprecation_warning = "Function plot_precision_recall_curve is deprecated"
    with pytest.warns(FutureWarning, match=deprecation_warning):
        plot_precision_recall_curve(clf, X, y)

@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"])
@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"])
def test_precision_recall_display_plotting(pyplot, constructor_name, response_method):
    """Check the overall plotting rendering."""
    X, y = make_classification(n_classes=2, n_samples=50, random_state=0)
    pos_label = 1

    classifier = LogisticRegression().fit(X, y)
    classifier.fit(X, y)

    y_pred = getattr(classifier, response_method)(X)
    y_pred = y_pred if y_pred.ndim == 1 else y_pred[:, pos_label]

    # safe guard for the binary if/else construction
    assert constructor_name in ("from_estimator", "from_predictions")

    if constructor_name == "from_estimator":
        display = PrecisionRecallDisplay.from_estimator(
            classifier, X, y, response_method=response_method
        )
    else:
        display = PrecisionRecallDisplay.from_predictions(
            y, y_pred, pos_label=pos_label
        )

    precision, recall, _ = precision_recall_curve(y, y_pred, pos_label=pos_label)
    average_precision = average_precision_score(y, y_pred, pos_label=pos_label)

    np.testing.assert_allclose(display.precision, precision)
    np.testing.assert_allclose(display.recall, recall)
    assert display.average_precision == pytest.approx(average_precision)

    import matplotlib as mpl

    assert isinstance(display.line_, mpl.lines.Line2D)
    assert isinstance(display.ax_, mpl.axes.Axes)
    assert isinstance(display.figure_, mpl.figure.Figure)

    assert display.ax_.get_xlabel() == "Recall (Positive label: 1)"
    assert display.ax_.get_ylabel() == "Precision (Positive label: 1)"

    # plotting passing some new parameters
    display.plot(alpha=0.8, name="MySpecialEstimator")
    expected_label = f"MySpecialEstimator (AP = {average_precision:0.2f})"
    assert display.line_.get_label() == expected_label
    assert display.line_.get_alpha() == pytest.approx(0.8)

@pytest.mark.parametrize(
    "constructor_name, default_label",
    [
        ("from_estimator", "LogisticRegression (AP = {:.2f})"),
        ("from_predictions", "Classifier (AP = {:.2f})"),
    ],
)
def test_precision_recall_display_name(pyplot, constructor_name, default_label):
    """Check the behaviour of the name parameters"""
    X, y = make_classification(n_classes=2, n_samples=100, random_state=0)
    pos_label = 1

    classifier = LogisticRegression().fit(X, y)
    classifier.fit(X, y)

    y_pred = classifier.predict_proba(X)[:, pos_label]

    # safe guard for the binary if/else construction
    assert constructor_name in ("from_estimator", "from_predictions")

    if constructor_name == "from_estimator":
        display = PrecisionRecallDisplay.from_estimator(classifier, X, y)
    else:
        display = PrecisionRecallDisplay.from_predictions(
            y, y_pred, pos_label=pos_label
        )

    average_precision = average_precision_score(y, y_pred, pos_label=pos_label)

    # check that the default name is used
    assert display.line_.get_label() == default_label.format(average_precision)

    # check that the name can be set
    display.plot(name="MySpecialEstimator")
    assert (
        display.line_.get_label()
        == f"MySpecialEstimator (AP = {average_precision:.2f})"
    )

@pytest.mark.parametrize(
    "clf",
    [
        make_pipeline(StandardScaler(), LogisticRegression()),
        make_pipeline(
            make_column_transformer((StandardScaler(), [0, 1])), LogisticRegression()
        ),
    ],
)
def test_precision_recall_display_pipeline(pyplot, clf):
    X, y = make_classification(n_classes=2, n_samples=50, random_state=0)
    with pytest.raises(NotFittedError):
        PrecisionRecallDisplay.from_estimator(clf, X, y)
    clf.fit(X, y)
    display = PrecisionRecallDisplay.from_estimator(clf, X, y)
    assert display.estimator_name == clf.__class__.__name__

def test_precision_recall_display_string_labels(pyplot):
    # regression test #15738
    cancer = load_breast_cancer()
    X, y = cancer.data, cancer.target_names[cancer.target]

    lr = make_pipeline(StandardScaler(), LogisticRegression())
    lr.fit(X, y)
    for klass in cancer.target_names:
        assert klass in lr.classes_
    display = PrecisionRecallDisplay.from_estimator(lr, X, y)

    y_pred = lr.predict_proba(X)[:, 1]
    avg_prec = average_precision_score(y, y_pred, pos_label=lr.classes_[1])

    assert display.average_precision == pytest.approx(avg_prec)
    assert display.estimator_name == lr.__class__.__name__

    err_msg = r"y_true takes value in {'benign', 'malignant'}"
    with pytest.raises(ValueError, match=err_msg):
        PrecisionRecallDisplay.from_predictions(y, y_pred)

    display = PrecisionRecallDisplay.from_predictions(
        y, y_pred, pos_label=lr.classes_[1]
    )
    assert display.average_precision == pytest.approx(avg_prec)

@pytest.mark.parametrize(
    "average_precision, estimator_name, expected_label",
    [
        (0.9, None, "AP = 0.90"),
        (None, "my_est", "my_est"),
        (0.8, "my_est2", "my_est2 (AP = 0.80)"),
    ],
)
def test_default_labels(pyplot, average_precision, estimator_name, expected_label):
    """Check the default labels used in the display."""
    precision = np.array([1, 0.5, 0])
    recall = np.array([0, 0.5, 1])
    display = PrecisionRecallDisplay(
        precision,
        recall,
        average_precision=average_precision,
        estimator_name=estimator_name,
    )
    display.plot()
    assert display.line_.get_label() == expected_label

@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"])
@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"])
def test_plot_precision_recall_pos_label(pyplot, constructor_name, response_method):
    # check that we can provide the positive label and display the proper
    # statistics
    X, y = load_breast_cancer(return_X_y=True)
    # create an highly imbalanced version of the breast cancer dataset
    idx_positive = np.flatnonzero(y == 1)
    idx_negative = np.flatnonzero(y == 0)
    idx_selected = np.hstack([idx_negative, idx_positive[:25]])
    X, y = X[idx_selected], y[idx_selected]
    X, y = shuffle(X, y, random_state=42)
    # only use 2 features to make the problem even harder
    X = X[:, :2]
    y = np.array(["cancer" if c == 1 else "not cancer" for c in y], dtype=object)
    X_train, X_test, y_train, y_test = train_test_split(
        X,
        y,
        stratify=y,
        random_state=0,
    )

    classifier = LogisticRegression()
    classifier.fit(X_train, y_train)

    # sanity check to be sure the positive class is classes_[0] and that we
    # are betrayed by the class imbalance
    assert classifier.classes_.tolist() == ["cancer", "not cancer"]

    y_pred = getattr(classifier, response_method)(X_test)
    # we select the correcponding probability columns or reverse the decision
    #  function otherwise
    y_pred_cancer = -1 * y_pred if y_pred.ndim == 1 else y_pred[:, 0]
    y_pred_not_cancer = y_pred if y_pred.ndim == 1 else y_pred[:, 1]

    if constructor_name == "from_estimator":
        display = PrecisionRecallDisplay.from_estimator(
            classifier,
            X_test,
            y_test,
            pos_label="cancer",
            response_method=response_method,
        )
    else:
        display = PrecisionRecallDisplay.from_predictions(
            y_test,
            y_pred_cancer,
            pos_label="cancer",
        )
    # we should obtain the statistics of the "cancer" class
    avg_prec_limit = 0.65
    assert display.average_precision < avg_prec_limit
    assert -np.trapz(display.precision, display.recall) < avg_prec_limit

    # otherwise we should obtain the statistics of the "not cancer" class
    if constructor_name == "from_estimator":
        display = PrecisionRecallDisplay.from_estimator(
            classifier,
            X_test,
            y_test,
            response_method=response_method,
            pos_label="not cancer",
        )
    else:
        display = PrecisionRecallDisplay.from_predictions(
            y_test,
            y_pred_not_cancer,
            pos_label="not cancer",
        )
    avg_prec_limit = 0.95
    assert display.average_precision > avg_prec_limit
    assert -np.trapz(display.precision, display.recall) > avg_prec_limit

redpajama_set_name: RedPajamaGithub


text:
package org.conqat.lib.commons.collections;

/**
 * Offers the ability to perform lookahead on an ordered collection.
 *
 * @author $Author: kinnen $
 * @version $Rev: 41751 $
 * @ConQAT.Rating GREEN Hash: 7B5BD6E848F8DB7C1E86B5E375BB029E
 */
public interface ILookahead<Data, X extends Exception> {

	/**
	 * Returned elements remain in the underlying data structure and are still
	 * accessible.
	 *
	 * @param index
	 *            Number of elements that are looked ahead
	 *
	 * @return Element at index, or null, if the provider doesn't contain that
	 *         many elements anymore
	 */
	public Data lookahead(int index) throws X;
}


text:
package de.brendamour.jpasskit.passes;

import com.google.common.collect.Lists;
import de.brendamour.jpasskit.IPKValidateable;
import de.brendamour.jpasskit.PKField;
import org.apache.commons.lang3.builder.ToStringBuilder;

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

public class PKGenericPass implements IPKValidateable {

    private static final long serialVersionUID = 3408389190364251557L;

    protected List<PKField> headerFields;
    protected List<PKField> primaryFields;
    protected List<PKField> secondaryFields;
    protected List<PKField> auxiliaryFields;
    protected List<PKField> backFields;

    public List<PKField> getPrimaryFields() {
        return primaryFields;
    }

    public void setPrimaryFields(final List<PKField> primaryFields) {
        this.primaryFields = primaryFields;
    }

    public List<PKField> getSecondaryFields() {
        return secondaryFields;
    }

    public void setSecondaryFields(final List<PKField> secondaryFields) {
        this.secondaryFields = secondaryFields;
    }

    public List<PKField> getAuxiliaryFields() {
        return auxiliaryFields;
    }

    public void setAuxiliaryFields(final List<PKField> auxiliaryFields) {
        this.auxiliaryFields = auxiliaryFields;
    }

    public List<PKField> getBackFields() {
        return backFields;
    }

    public void setBackFields(final List<PKField> backFields) {
        this.backFields = backFields;
    }

    public List<PKField> getHeaderFields() {
        return headerFields;
    }

    public void setHeaderFields(final List<PKField> headerFields) {
        this.headerFields = headerFields;
    }

    public boolean isValid() {
        return getValidationErrors().isEmpty();
    }

    public List<String> getValidationErrors() {

        List<String> validationErrors = new ArrayList<String>();

        List<List<PKField>> lists = Lists.newArrayList();
        lists.add(primaryFields);
        lists.add(secondaryFields);
        lists.add(headerFields);
        lists.add(backFields);

        for (List<PKField> list : lists) {
            if (list != null) {
                for (PKField pkField : list) {
                    if (!pkField.isValid()) {
                        validationErrors.addAll(pkField.getValidationErrors());
                    }
                }
            }
        }

        return validationErrors;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}


text:
<?php

/*
 * For instructions on how to run the full sample:
 *
 * @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/secretmanager/README.md
 */

declare(strict_types=1);

namespace Google\Cloud\Samples\SecretManager;

// [START secretmanager_enable_secret_version]
// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\SecretManagerServiceClient;

/**
 * @param string $projectId Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $secretId  Your secret ID (e.g. 'my-secret')
 * @param string $versionId Your version ID (e.g. 'latest' or '5');
 */
function enable_secret_version(string $projectId, string $secretId, string $versionId): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

    // Build the resource name of the secret version.
    $name = $client->secretVersionName($projectId, $secretId, $versionId);

    // Enable the secret version.
    $response = $client->enableSecretVersion($name);

    // Print a success message.
    printf('Enabled secret version: %s', $response->getName());
}
// [END secretmanager_enable_secret_version]

// The following 2 lines are only needed to execute the samples on the CLI
require_once __DIR__ . '/../../testing/sample_helpers.php';
\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);


text:
package qin.javaee8.core;

import qin.javaee65.core.hibernate.SuperEntity65;

import java.io.Serializable;
import java.util.Comparator;

/**
 * JavaEE8版的超级实体类
 *
 * @param <T> 实现<code>{@link Serializable}</code>的实体类
 * @author qinzhengying
 * @since 1.8
 */
public interface SuperEntity8<T extends Serializable>
          extends SuperEntity65<T>, JavaEE8BaseSupport,
          Comparator<T>, Comparable<T>
{
    @Override
    default int compare(T o1, T o2)
    {
        return 1;
    }

    @Override
    default int compareTo(T o)
    {
        return 1;
    }
}


text:
My first Projekt with Python just something that creates, saves and use a list for Informations that you can throw in there.
I hope that you can find many ways to improve the Script and if you do so please let me knwo this.
Thanks :)


text:
<?php
# Copyright (c) 2014  MantisBT Team - mantisbt-dev@lists.sourceforge.net
# Licensed under the MIT license

form_security_validate( 'plugin_XmlImportExport_config' );
access_ensure_global_level( config_get( 'manage_plugin_threshold' ) );

/**
 * Sets plugin config option if value is different from current/default
 * @param string $p_name  option name
 * @param string $p_value value to set
 * @return void
 */
function config_set_if_needed( $p_name, $p_value ) {
	if ( $p_value != plugin_config_get( $p_name ) ) {
		plugin_config_set( $p_name, $p_value );
	}
}

$t_redirect_url = plugin_page( 'config_page', true );
layout_page_header( null, $t_redirect_url );
layout_page_begin();

config_set_if_needed( 'import_threshold' , gpc_get_int( 'import_threshold' ) );
config_set_if_needed( 'export_threshold' , gpc_get_int( 'export_threshold' ) );

form_security_purge( 'plugin_XmlImportExport_config' );

html_operation_successful( $t_redirect_url );
layout_page_end();


text:
#ifndef APRINTER_CONFIGURATION_H
#define APRINTER_CONFIGURATION_H

#include <aprinter/meta/WrapValue.h>
#include <aprinter/meta/WrapDouble.h>
#include <aprinter/meta/TypeListBuilder.h>
#include <aprinter/meta/Expr.h>
#include <aprinter/base/Object.h>
#include <aprinter/meta/IndexElemList.h>
#include <aprinter/meta/FuncUtils.h>
#include <aprinter/meta/WrapValue.h>
#include <aprinter/meta/TypeListUtils.h>
#include <aprinter/meta/If.h>
#include <aprinter/meta/ListForEach.h>
#include <aprinter/meta/TypeList.h>
#include <aprinter/base/DebugObject.h>
#include <aprinter/base/ProgramMemory.h>

#define APRINTER_CONFIG_START \
APRINTER_START_LIST(ConfigList)

#define APRINTER_CONFIG_OPTION_GENERIC(Name, Type, DefaultValue, Properties) \
constexpr char AMBRO_PROGMEM const Name##__OptionName[] = #Name; \
struct Name : public APrinter::ConfigOption<Name, Type, DefaultValue, Name##__OptionName, Properties> {}; \
APRINTER_ADD_TO_LIST(ConfigList, Name)

#define APRINTER_CONFIG_OPTION_SIMPLE(Name, Type, DefaultValue, Properties) \
using Name##__DefaultValue = APrinter::WrapValue<Type, (DefaultValue)>; \
APRINTER_CONFIG_OPTION_GENERIC(Name, Type, Name##__DefaultValue, Properties)

#define APRINTER_CONFIG_OPTION_BOOL(Name, DefaultValue, Properties) \
APRINTER_CONFIG_OPTION_SIMPLE(Name, bool, DefaultValue, Properties)

#define APRINTER_CONFIG_OPTION_DOUBLE(Name, DefaultValue, Properties) \
using Name##__DefaultValue = AMBRO_WRAP_DOUBLE(DefaultValue); \
APRINTER_CONFIG_OPTION_GENERIC(Name, double, Name##__DefaultValue, Properties)

#define APRINTER_CONFIG_END \
APRINTER_END_LIST(ConfigList)

#define APRINTER_CFG(TheConfig, TheExpr, c) ( \
    decltype(TheConfig::getExpr(TheExpr()))::IsConstexpr ? \
    decltype(TheConfig::getHelper(TheExpr()))::value() : \
    decltype(TheConfig::getHelper(TheExpr()))::eval(c) \
)

#include <aprinter/BeginNamespace.h>

template <typename TIdentity, typename TType, typename TDefaultValue, char AMBRO_PROGMEM const *TOptionName, typename TProperties>
struct ConfigOption {
    using Identity = TIdentity;
    using Type = TType;
    using DefaultValue = TDefaultValue;
    using Properties = TProperties;

    static constexpr Identity i ();
    static constexpr char AMBRO_PROGMEM const * name () { return TOptionName; }
};

using ConfigNoProperties = EmptyTypeList;

template <typename... Properties>
using ConfigProperties = MakeTypeList<Properties...>;

struct ConfigPropertyConstant {};

template <typename Context, typename ParentObject, typename DelayedExprsList>
class ConfigCache {
public:
    struct Object;

private:
    AMBRO_DECLARE_LIST_FOREACH_HELPER(Foreach_update, update)

    using TheDebugObject = DebugObject<Context, Object>;
    using MyExprsList = typename DelayedExprsList::List;
    template <typename TheExpr>
    using ExprIsConstexpr = WrapBool<TheExpr::IsConstexpr>;
    using ExprIsConstexprFunc = TemplateFunc<ExprIsConstexpr>;
    using ConstexprExprsList = FilterTypeList<MyExprsList, ExprIsConstexprFunc>;
    using CachedExprsList = TypeListRemoveDuplicates<FilterTypeList<MyExprsList, ComposeFunctions<NotFunc, ExprIsConstexprFunc>>>;

    template <int CachedExprIndex>
    struct CachedExprState {
        using TheExpr = TypeListGet<CachedExprsList, CachedExprIndex>;
        using Type = typename TheExpr::Type;

        static void update (Context c)
        {
            auto *o = Object::self(c);
            o->value = TheExpr::eval(c);
        }

        static Type call (Context c)
        {
            auto *o = Object::self(c);
            return o->value;
        }

        struct Object : public ObjBase<CachedExprState, typename ConfigCache::Object, EmptyTypeList> {
            Type value;
        };
    };

    using CachedExprStateList = IndexElemList<CachedExprsList, CachedExprState>;

    template <typename TheExpr>
    struct CheckExpr {
        static_assert(TypeListFind<MyExprsList, TheExpr>::Found, "Expression is not in cache.");
        using Expr = TheExpr;
    };

    template <typename TheExpr>
    using GetExprVariableHelper = VariableExpr<
        typename TheExpr::Type,
        CachedExprState<TypeListIndex<CachedExprsList, TheExpr>::Value>
    >;

    template <typename TheExpr>
    using GetExpr = FuncCall<
        IfFunc<
            ConstantFunc<WrapBool<CheckExpr<TheExpr>::Expr::IsConstexpr>>,
            ConstantFunc<TheExpr>,
            TemplateFunc<GetExprVariableHelper>
        >,
        TheExpr
    >;

    template <bool IsConstexpr, typename TheGetExpr>
    struct GetHelper;

    template <typename TheGetExpr>
    struct GetHelper<true, TheGetExpr> {
        static constexpr typename TheGetExpr::Type value ()
        {
            return TheGetExpr::value();
        }

        static typename TheGetExpr::Type eval (Context c);
    };

    template <typename TheGetExpr>
    struct GetHelper<false, TheGetExpr> {
        static typename TheGetExpr::Type value ();

        static typename TheGetExpr::Type eval (Context c)
        {
            return TheGetExpr::eval(c);
        }
    };

public:
    static void init (Context c)
    {
        ListForEachForward<CachedExprStateList>(Foreach_update(), c);

        TheDebugObject::init(c);
    }

    static void deinit (Context c)
    {
        TheDebugObject::deinit(c);
    }

    static void update (Context c)
    {
        TheDebugObject::access(c);

        ListForEachForward<CachedExprStateList>(Foreach_update(), c);
    }

    template <typename TheExpr>
    static GetExpr<TheExpr> getExpr (TheExpr);

    template <typename TheExpr>
    static GetHelper<GetExpr<TheExpr>::IsConstexpr, GetExpr<TheExpr>> getHelper (TheExpr);

public:
    struct Object : public ObjBase<ConfigCache, ParentObject, JoinTypeLists<
        CachedExprStateList,
        MakeTypeList<TheDebugObject>
    >> {};
};

template <typename TheConfigManager, typename TheConfigCache>
struct ConfigFramework {
    template <typename Option>
    static decltype(TheConfigManager::e(Option())) e (Option);

    template <typename TheExpr, typename TheConfigCacheLazy = TheConfigCache>
    static decltype(TheConfigCacheLazy::getExpr(TheExpr())) getExpr (TheExpr);

    template <typename TheExpr, typename TheConfigCacheLazy = TheConfigCache>
    static decltype(TheConfigCacheLazy::getHelper(TheExpr())) getHelper (TheExpr);
};

#include <aprinter/EndNamespace.h>

#endif


text:
from .models_escherMaps_postgresql_models import *

from SBaaS_base.sbaas_base_query_update import sbaas_base_query_update
from SBaaS_base.sbaas_base_query_drop import sbaas_base_query_drop
from SBaaS_base.sbaas_base_query_initialize import sbaas_base_query_initialize
from SBaaS_base.sbaas_base_query_insert import sbaas_base_query_insert
from SBaaS_base.sbaas_base_query_select import sbaas_base_query_select
from SBaaS_base.sbaas_base_query_delete import sbaas_base_query_delete

from SBaaS_base.sbaas_template_query import sbaas_template_query

class models_escherMaps_query(sbaas_template_query):
    def initialize_supportedTables(self):
        '''Set the supported tables dict for
        '''
        tables_supported = {'models_eschermaps':models_eschermaps,
                        };
        self.set_supportedTables(tables_supported);
    #table initializations:
    def drop_models_eschermaps(self):
        try:
            models_eschermaps.__table__.drop(engine,True);
        except SQLAlchemyError as e:
            print(e);
    def reset_models_eschermaps(self,eschermap_id_I = None):
        try:
            if eschermaps_id_I:
                reset = self.session.query(models_eschermaps).filter(models_eschermaps.eschermap_id.like(eschermap_id_I)).delete(synchronize_session=False);
            else:
                reset = self.session.query(models_eschermaps).delete(synchronize_session=False);
            self.session.commit();
        except SQLAlchemyError as e:
            print(e);
    def initialize_models_eschermaps(self):
        try:
            models_eschermaps.__table__.create(engine,True);
        except SQLAlchemyError as e:
            print(e);
    def add_modelsEschermaps(self, data_I):
        '''add rows of models_eschermaps'''
        if data_I:
            for d in data_I:
                try:
                    data_add = models_eschermaps(
                                    d['used_'],
                                    d['comment_']);
                    self.session.add(data_add);
                except SQLAlchemyError as e:
                    print(e);
            self.session.commit();

    def update_modelsEschermaps(self,data_I):
        '''update rows of models_eschermaps'''
        if data_I:
            for d in data_I:
                try:
                    data_update = self.session.query(models_eschermaps).filter(
                            models_eschermaps.id == d['id']).update(
                            {
                            'used_':d['used_'],
                            'comment_':d['comment_']},
                            synchronize_session=False);
                except SQLAlchemyError as e:
                    print(e);
            self.session.commit();
    # query data from models_eschermaps
    def get_rows_eschermapID_modelsEschermaps(self,eschermap_id_I):
        '''Query rows that are used from the eschermaps'''
        try:
            data = self.session.query(models_eschermaps).filter(
                    models_eschermaps.eschermaps_id.like(eschermap_id_I),
                    models_eschermaps.used_.is_(True)).order_by(
                    models_eschermaps.eschermap_id.asc()).all();
            data_O = [];
            if data:
                for d in data:
                    data_O.append({
                        'model_id':d.model_id,
                        'eschermap_id':d.eschermap_id,
                        'eschermap_json':d.eschermap_json,
                        'used_':d.used_,
                        'comment_':d.comment_
                    });
            return  data_O;
        except SQLAlchemyError as e:
            print(e);
    def get_rows_modelID_modelsEschermaps(self,model_id_I):
        '''Query rows that are used from the eschermaps'''
        try:
            data = self.session.query(models_eschermaps).filter(
                    models_eschermaps.model_id.like(model_id_I),
                    models_eschermaps.used_.is_(True)).order_by(
                    models_eschermaps.eschermap_id.asc()).all();
            data_O = [];
            if data:
                for d in data:
                    data_O.append({
                        'model_id':d.model_id,
                        'eschermap_id':d.eschermap_id,
                        'eschermap_json':d.eschermap_json,
                        'used_':d.used_,
                        'comment_':d.comment_
                    });
            return  data_O;
        except SQLAlchemyError as e:
            print(e);


text:
/*

Note that we're testing with plantbox, not pagebox, since the aspects of a page that are testable
are in the plant, not the page.  The page adds CSS, server-side stuff, etc., which are either
not testable or are tested in other ways.

*/

var plantbox = require('plantbox')(module)

var test = require("tap").test

var indexPlant = plantbox('./../js/indexplant')

test('make sure OK button works properly', function(t){

	var plant = indexPlant.run()

	plant.click('.ok')
	t.ok(plant.exists('.msg'), 'Clicking OK should cause a message to show.')

	plant.end()
	t.end()
})


text:
The main target of this project, its to be used as a tool for generate
csv based files to training artificial neural network.

## Getting Started

To start with this project, you gonna need:

   * JDK - at least 1.5
   * Maven
   * An IDE

To import this project in eclipse you can import as a Maven Project

## Built With

* [Maven](https://maven.apache.org/) - Dependency Management
* [MMLIB-4j](https://github.com/wonderalexandre/mmlib4j) - Core library of image processing

## How to Run

* java -Dout=outputfile -Doriginal=folder_with_original_images -Dmark=folder_with_mark_images -Dlabel=label_of_images -jar training.jar


text:
<?php
include ('header.php');
?>

A custom, open-source WebUI for Momentum 4.2.28+

Version 2 of this Web-UI is designed to be installed in a detatched environment specifically for reporting on Momentum 4.2.28+.  Any other use may have unpredictable results.  Use at your own risk.  **THIS IS UNSUPPORTED CODE**.  Feel free to contribute or replicate, but dont complain if it does not work, as I may not have time to fix it.

== HOW IT WORKS ==

There is a telemetry module that installs in every momentum node in a cluster.  The module can provide environmental and log data from delivery nodes as well as the log aggregator / cluster manager.  Telemetry data is shipped to the WebUI for reporting.  Optionally, Webhook data can be streamed to the WebUI as well for real-time event reporting.

== INSTALLATION ==

First install the WebUI in a separate environment.  This can be an Azure or AWS instance, or another server in the Momentum cluster's network.  It can be Linux or Windows based, Apache or Nginx, but is expected to be a standard Web environment with the ability to support PHP.  If you want to use Git for deployment and updates, you should install the latest version.

After you build the server and install and test Apache or Nginx, change directories to /var/www/html/ and clone/fetch this Git repo to that location.

Once the initial install is done, the updater should just pull the current version of the UI from this repo.  The package includes the telemetry module that is intended to run on the Momentum nodes.  Copy that file (telemetry.sh) to /opt/msys/ecelerity/etc/conf/default then add a cron job to execue it every 5 minutes.  Alternately cp telem.ins to /tmp on each node then execute it and it will do the install for you.

<?php
include ('footer.php');
?>


text:
- Added a new output, *foundIncidents.incidentLink*, which is a list containing URL links to all incidents that were found.
- Updated docker image from `3.8.6.13358` to `3.8.6.14516`.


text:
import unittest

import numpy

import chainer
from chainer.backends import cuda
from chainer import gradient_check
from chainer import links
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition

def relu(x):
    return x * (x > 0)

@testing.parameterize(*testing.product({
    'hidden_none': [True, False],
    'activation': ['tanh', 'relu'],
}))
class TestNStepRNN(unittest.TestCase):

    lengths = [3, 1, 2]
    n_layer = 2
    in_size = 3
    out_size = 2
    dropout = 0.0

    def setUp(self):
        shape = (self.n_layer, len(self.lengths), self.out_size)
        if self.hidden_none:
            self.h = numpy.zeros(shape, 'f')
        else:
            self.h = numpy.random.uniform(-1, 1, shape).astype('f')
        self.xs = [
            numpy.random.uniform(-1, 1, (l, self.in_size)).astype('f')
            for l in self.lengths]

        self.gh = numpy.random.uniform(-1, 1, shape).astype('f')
        self.gys = [
            numpy.random.uniform(-1, 1, (l, self.out_size)).astype('f')
            for l in self.lengths]
        if self.activation == 'tanh':
            rnn_link_class = links.NStepRNNTanh
        elif self.activation == 'relu':
            rnn_link_class = links.NStepRNNReLU
        self.rnn = rnn_link_class(
            self.n_layer, self.in_size, self.out_size, self.dropout)

        for layer in self.rnn:
            for p in layer.params():
                p.array[...] = numpy.random.uniform(-1, 1, p.shape)
        self.rnn.cleargrads()

    def check_forward(self, h_data, xs_data):
        if self.hidden_none:
            h = None
        else:
            h = chainer.Variable(h_data)
        xs = [chainer.Variable(x) for x in xs_data]
        hy, ys = self.rnn(h, xs)

        assert hy.shape == h_data.shape
        assert len(xs) == len(ys)
        for x, y in zip(xs, ys):
            assert len(x) == len(y)
            assert y.shape[1] == self.out_size

        self.rnn.to_cpu()

        for batch, seq in enumerate(self.xs):
            for layer in range(self.n_layer):
                p = self.rnn[layer]
                h_prev = self.h[layer, batch]
                hs = []
                for x in seq:
                    if self.activation == 'tanh':
                        activation_func = numpy.tanh
                    elif self.activation == 'relu':
                        activation_func = relu

                    h_prev = activation_func(x.dot(p.w0.array.T) +
                                             h_prev.dot(p.w1.array.T) +
                                             p.b0.array + p.b1.array)

                    hs.append(h_prev)

                seq = hs
                testing.assert_allclose(hy.data[layer, batch], h_prev)

            for y, ey in zip(ys[batch].array, seq):
                testing.assert_allclose(y, ey)

    def test_forward_cpu_train(self):
        with chainer.using_config('train', True):
            self.check_forward(self.h, self.xs)

    @attr.gpu
    def test_forward_gpu_train(self):
        self.rnn.to_gpu()
        with chainer.using_config('use_cudnn', 'always'), \
                chainer.using_config('train', True):
            self.check_forward(
                cuda.to_gpu(self.h),
                [cuda.to_gpu(x) for x in self.xs])

    def test_forward_cpu_test(self):
        with chainer.using_config('train', False):
            self.check_forward(self.h, self.xs)

    @attr.gpu
    def test_forward_gpu_test(self):
        self.rnn.to_gpu()
        with chainer.using_config('use_cudnn', 'always'), \
                chainer.using_config('train', False):
            self.check_forward(
                cuda.to_gpu(self.h),
                [cuda.to_gpu(x) for x in self.xs])

    def check_multi_gpu_forward(self, train=True):
        # See chainer/chainer#6262
        # NStepRNNTanh and NStepRNNReLU w/ cudnn & dropout should work on
        # not current device
        msg = None
        rnn = self.rnn.copy('copy')
        rnn.dropout = .5
        with cuda.get_device_from_id(1):
            if self.hidden_none:
                h = None
            else:
                h = cuda.to_gpu(self.h)
            xs = [cuda.to_gpu(x) for x in self.xs]
            rnn = rnn.to_gpu()
        with cuda.get_device_from_id(0),\
                chainer.using_config('train', train),\
                chainer.using_config('use_cudnn', 'always'):
            try:
                rnn(h, xs)
            except Exception as e:
                msg = e
        assert msg is None

    @attr.cudnn
    @attr.multi_gpu(2)
    def test_multi_gpu_forward_training(self):
        self.check_multi_gpu_forward(True)

    @attr.cudnn
    @attr.multi_gpu(2)
    def test_multi_gpu_forward_test(self):
        self.check_multi_gpu_forward(False)

    def check_backward(
            self, h_data, xs_data, gh_data, gys_data):

        def fun(*args):
            if self.hidden_none:
                h = None
                xs = args
            else:
                h, = args[:1]
                xs = args[1:]
            hy, ys = self.rnn(h, xs)
            return tuple([hy, ] + list(ys))

        params = []
        for layer in self.rnn:
            for p in layer.params():
                params.append(p)

        if self.hidden_none:
            in_data = xs_data
        else:
            in_data = [h_data, ] + xs_data
        gradient_check.check_backward(
            fun, tuple(in_data),
            tuple([gh_data, ] + gys_data),
            tuple(params), rtol=1e-2, atol=5e-2)

    @condition.retry(3)
    def test_backward_cpu(self):
        self.check_backward(
            self.h, self.xs, self.gh, self.gys)

    @attr.gpu
    @condition.retry(3)
    def test_backward_gpu(self):
        self.rnn.to_gpu()
        with chainer.using_config('use_cudnn', 'auto'):
            self.check_backward(
                cuda.to_gpu(self.h),
                [cuda.to_gpu(x) for x in self.xs],
                cuda.to_gpu(self.gh),
                [cuda.to_gpu(gy) for gy in self.gys])

    def test_n_cells(self):
        assert self.rnn.n_cells == 1

@testing.parameterize(*testing.product({
    'hidden_none': [True, False],
    'activation': ['tanh', 'relu'],
}))
class TestNStepBiRNN(unittest.TestCase):

    lengths = [3, 1, 2]
    n_layer = 2
    in_size = 3
    out_size = 2
    dropout = 0.0

    def setUp(self):
        shape = (self.n_layer * 2, len(self.lengths), self.out_size)
        if self.hidden_none:
            self.h = numpy.zeros(shape, 'f')
        else:
            self.h = numpy.random.uniform(-1, 1, shape).astype('f')
        self.xs = [
            numpy.random.uniform(-1, 1, (l, self.in_size)).astype('f')
            for l in self.lengths]

        self.gh = numpy.random.uniform(-1, 1, shape).astype('f')
        self.gys = [
            numpy.random.uniform(-1, 1, (l, self.out_size * 2)).astype('f')
            for l in self.lengths]
        if self.activation == 'tanh':
            rnn_link_class = links.NStepBiRNNTanh
        elif self.activation == 'relu':
            rnn_link_class = links.NStepBiRNNReLU
        self.rnn = rnn_link_class(
            self.n_layer, self.in_size, self.out_size, self.dropout)

        for layer in self.rnn:
            for p in layer.params():
                p.array[...] = numpy.random.uniform(-1, 1, p.array.shape)
        self.rnn.cleargrads()

    def check_forward(self, h_data, xs_data):
        if self.hidden_none:
            h = None
        else:
            h = chainer.Variable(h_data)
        xs = [chainer.Variable(x) for x in xs_data]
        hy, ys = self.rnn(h, xs)

        assert hy.shape == h_data.shape
        assert len(xs) == len(ys)
        for x, y in zip(xs, ys):
            assert len(x) == len(y)
            assert y.shape[1] == self.out_size * 2

        self.rnn.to_cpu()

        for batch, seq in enumerate(self.xs):
            for layer in range(self.n_layer):
                # forward
                di = 0
                layer_idx = layer * 2 + di
                p = self.rnn[layer_idx]
                h_prev = self.h[layer_idx, batch]
                hs_f = []
                for x in seq:
                    if self.activation == 'tanh':
                        activation_func = numpy.tanh
                    elif self.activation == 'relu':
                        activation_func = relu

                    h_prev = activation_func(x.dot(p.w0.array.T) +
                                             h_prev.dot(p.w1.array.T) +
                                             p.b0.array + p.b1.array)
                    hs_f.append(h_prev)

                testing.assert_allclose(hy.array[layer_idx, batch], h_prev)

                # backward
                di = 1
                layer_idx = layer * 2 + di
                p = self.rnn[layer_idx]
                h_prev = self.h[layer_idx, batch]
                hs_b = []
                for x in reversed(seq):
                    if self.activation == 'tanh':
                        activation_func = numpy.tanh
                    elif self.activation == 'relu':
                        activation_func = relu
                    h_prev = activation_func(x.dot(p.w0.array.T) +
                                             h_prev.dot(p.w1.array.T) +
                                             p.b0.array + p.b1.array)
                    hs_b.append(h_prev)
                testing.assert_allclose(hy.data[layer_idx, batch], h_prev)

                hs_b.reverse()
                seq = [numpy.concatenate([hfi, hbi], axis=0) for (hfi, hbi)
                       in zip(hs_f, hs_b)]

            for y, ey in zip(ys[batch].array, seq):
                testing.assert_allclose(y, ey)

    def test_forward_cpu_train(self):
        with chainer.using_config('train', True):
            self.check_forward(self.h, self.xs)

    @attr.gpu
    def test_forward_gpu_train(self):
        self.rnn.to_gpu()
        with chainer.using_config('use_cudnn', 'always'), \
                chainer.using_config('train', True):
            self.check_forward(
                cuda.to_gpu(self.h),
                [cuda.to_gpu(x) for x in self.xs])

    def test_forward_cpu_test(self):
        with chainer.using_config('train', False):
            self.check_forward(self.h, self.xs)

    @attr.gpu
    def test_forward_gpu_test(self):
        self.rnn.to_gpu()
        with chainer.using_config('use_cudnn', 'always'), \
                chainer.using_config('train', False):
            self.check_forward(
                cuda.to_gpu(self.h),
                [cuda.to_gpu(x) for x in self.xs])

    def check_multi_gpu_forward(self, train=True):
        # See chainer/chainer#6262
        # NStepBiRNNTanh and NStepBiRNNReLU w/ cudnn & dropout should work on
        # not current device
        msg = None
        rnn = self.rnn.copy('copy')
        rnn.dropout = .5
        with cuda.get_device_from_id(1):
            if self.hidden_none:
                h = None
            else:
                h = cuda.to_gpu(self.h)
            xs = [cuda.to_gpu(x) for x in self.xs]
            rnn = rnn.to_gpu()
        with cuda.get_device_from_id(0),\
                chainer.using_config('train', train),\
                chainer.using_config('use_cudnn', 'always'):
            try:
                rnn(h, xs)
            except Exception as e:
                msg = e
        assert msg is None

    @attr.cudnn
    @attr.multi_gpu(2)
    def test_multi_gpu_forward_training(self):
        self.check_multi_gpu_forward(True)

    @attr.cudnn
    @attr.multi_gpu(2)
    def test_multi_gpu_forward_test(self):
        self.check_multi_gpu_forward(False)

    def check_backward(
            self, h_data, xs_data, gh_data, gys_data):

        def fun(*args):
            if self.hidden_none:
                h = None
                xs = args
            else:
                h, = args[:1]
                xs = args[1:]
            hy, ys = self.rnn(h, xs)
            return tuple([hy, ] + list(ys))

        params = []
        for layer in self.rnn:
            for p in layer.params():
                params.append(p)

        if self.hidden_none:
            in_data = xs_data
        else:
            in_data = [h_data, ] + xs_data
        gradient_check.check_backward(
            fun, tuple(in_data),
            tuple([gh_data, ] + gys_data),
            tuple(params), rtol=1e-2, atol=5e-2)

    @condition.retry(3)
    def test_backward_cpu(self):
        self.check_backward(
            self.h, self.xs, self.gh, self.gys)

    @attr.gpu
    @condition.retry(3)
    def test_backward_gpu(self):
        self.rnn.to_gpu()
        with chainer.using_config('use_cudnn', 'auto'):
            self.check_backward(
                cuda.to_gpu(self.h),
                [cuda.to_gpu(x) for x in self.xs],
                cuda.to_gpu(self.gh),
                [cuda.to_gpu(gy) for gy in self.gys])

    def test_n_cells(self):
        assert self.rnn.n_cells == 1

testing.run_module(__name__, __file__)


text:
3d.city
=======

3d city builder [LAUNCH](http://lo-th.github.io/3d.city/index.html)

The goal is create 3d city builder to test performance for webgl games

With minimum size impact and maximum speed.

(world.sea:161 ko, view.min.js:71 ko, city.3d.min.js:130 ko)

Webgl 3d side use [Three.js](https://github.com/mrdoob/three.js), 3d model use [Sea3d](https://github.com/sunag/sea3d) format.

This game use simulation source micropolisJS by Graememcc

[https://github.com/graememcc/micropolisJS](https://github.com/graememcc/micropolisJS). Is a port of Micropolis to JS/HTML5.

Licensed under the GPLv3 with some additional terms please be mindful of these.

I have remove all thirdparty library, compact the code and push game simulation in a web worker.

Work in progress

[building destroy](http://lo-th.github.io/3d.city/test_destruct.html)

[helicopter test](http://lo-th.github.io/3d.city/test_helicopter.html)

[low version](http://lo-th.github.io/3d.city/index_low.html)


text:
import os
from string import digits

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured

def get_setting(name, default=None):
    return getattr(settings, f"LIPPUKALA_{name}", default)

def get_integer_setting(name, default=0):
    try:
        value = get_setting(name, default)
        return int(value)
    except ValueError:  # pragma: no cover
        raise ImproperlyConfigured(f"LIPPUKALA_{name} must be an integer (got {value!r})")

PREFIXES = get_setting("PREFIXES", {})
LITERATE_KEYSPACES = get_setting("LITERATE_KEYSPACES", {})
CODE_MIN_N_DIGITS = get_integer_setting("CODE_MIN_N_DIGITS", 10)
CODE_MAX_N_DIGITS = get_integer_setting("CODE_MAX_N_DIGITS", 10)
CODE_ALLOW_LEADING_ZEROES = bool(get_setting("CODE_ALLOW_LEADING_ZEROES", True))
PRINT_LOGO_PATH = get_setting("PRINT_LOGO_PATH")
PRINT_LOGO_SIZE_CM = get_setting("PRINT_LOGO_SIZE_CM")

if PREFIXES:
    PREFIX_CHOICES = [(p, f"{p} [{t}]") for (p, t) in sorted(PREFIXES.items())]
    PREFIX_MAY_BE_BLANK = False
else:
    PREFIX_CHOICES = [("", "---")]
    PREFIX_MAY_BE_BLANK = True

def validate_settings():  # pragma: no cover
    _validate_code()
    _validate_prefixes()
    _validate_print()

def _validate_code():
    if CODE_MIN_N_DIGITS <= 5 or CODE_MAX_N_DIGITS < CODE_MIN_N_DIGITS:
        raise ImproperlyConfigured(
            "The range (%d .. %d) for Lippukala code digits is invalid"
            % (CODE_MIN_N_DIGITS, CODE_MAX_N_DIGITS)
        )

def _validate_prefixes():
    key_lengths = [len(k) for k in PREFIXES]
    if key_lengths and not all(k == key_lengths[0] for k in key_lengths):
        raise ImproperlyConfigured("All LIPPUKALA_PREFIXES keys must be the same length!")
    for prefix in PREFIXES:
        if not all(c in digits for c in prefix):
            raise ImproperlyConfigured(
                f"The prefix {prefix!r} has invalid characters. Only digits are allowed."
            )
    for prefix, literate_keyspace in list(LITERATE_KEYSPACES.items()):
        if isinstance(literate_keyspace, str):
            raise ImproperlyConfigured(
                f"A string ({literate_keyspace!r}) was passed as the literate keyspace for prefix {prefix!r}"
            )
        too_short_keys = any(len(key) <= 1 for key in literate_keyspace)
        maybe_duplicate = len(set(literate_keyspace)) != len(literate_keyspace)
        if too_short_keys or maybe_duplicate:
            raise ImproperlyConfigured(
                f"The literate keyspace for prefix {prefix!r} has invalid or duplicate entries."
            )

def _validate_print():
    if PRINT_LOGO_PATH:
        if not os.path.isfile(PRINT_LOGO_PATH):
            raise ImproperlyConfigured(
                f"PRINT_LOGO_PATH was defined, but does not exist ({PRINT_LOGO_PATH!r})"
            )
        if not all(float(s) > 0 for s in PRINT_LOGO_SIZE_CM):
            raise ImproperlyConfigured(
                f"PRINT_LOGO_SIZE_CM values not valid: {PRINT_LOGO_SIZE_CM!r}"
            )

validate_settings()
del validate_settings  # aaaand it's gone


text:
class Skill < ActiveRecord::Base
  has_many :skill_effects, foreign_key: 'skill_reference', primary_key: 'reference'
  belongs_to :skill_type
  include Taggable
end


text:
package com.hp.autonomy.frontend.find.hod.search;

import com.hp.autonomy.frontend.find.HodFindApplication;
import com.hp.autonomy.frontend.find.core.search.AbstractDocumentServiceIT;
import org.springframework.boot.test.SpringApplicationConfiguration;

@SpringApplicationConfiguration(classes = HodFindApplication.class)
public class HodDocumentServiceIT extends AbstractDocumentServiceIT {
}