text:
========================
Service bus MTL
========================

To use this project follow these steps:

#. Create your working environment
#. Install Django
#. Create the new project using the django-two-scoops template
#. Install additional dependencies
#. Use the Django admin to create the project

*note: these instructions show creation of a project called "icecream".  You
should replace this name with the actual name of your project.*

Working Environment
===================

You have several options in setting up your working environment.  We recommend
using virtualenv to separate the dependencies of your project from your system's
python environment.  If on Linux or Mac OS X, you can also use virtualenvwrapper to help manage multiple virtualenvs across different projects.

Virtualenv Only
---------------

First, make sure you are using virtualenv (http://www.virtualenv.org). Once
that's installed, create your virtualenv::

    $ virtualenv --distribute icecream

You will also need to ensure that the virtualenv has the project directory
added to the path. Adding the project directory will allow `django-admin.py` to
be able to change settings using the `--settings` flag.

Virtualenv with virtualenvwrapper
--------------------------

In Linux and Mac OSX, you can install virtualenvwrapper (http://virtualenvwrapper.readthedocs.org/en/latest/),
which will take care of managing your virtual environments and adding the
project path to the `site-directory` for you::

    $ mkdir icecream
    $ mkvirtualenv -a icecream icecream-dev
    $ cd icecream && add2virtualenv `pwd`

Windows
----------

In Windows, or if you're not comfortable using the command line, you will need
to add a `.pth` file to the `site-packages` of your virtualenv. If you have
been following the book's example for the virtualenv directory (pg. 12), then
you will need to add a python pathfile named `_virtualenv_path_extensions.pth`
to the `site-packages`. If you have been following the book, then your
virtualenv folder will be something like::

`~/.virtualenvs/icecream/lib/python2.7/site-directory/`

In the pathfile, you will want to include the following code (from
virtualenvwrapper):

    import sys; sys.__plen = len(sys.path)
    /home/<youruser>/icecream/icecream/
    import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new)

Installing Django
=================

To install Django in the new virtual environment, run the following command::

    $ pip install django

Creating your project
=====================

To create a new Django project called '**icecream**' using
django-twoscoops-project, run the following command::

    $ django-admin.py startproject --template=https://github.com/twoscoops/django-twoscoops-project/archive/master.zip --extension=py,rst,html icecream

Installation of Dependencies
=============================

Depending on where you are installing dependencies:

In development::

    $ pip install -r requirements/local.txt

For production::

    $ pip install -r requirements.txt

*note: We install production requirements this way because many Platforms as a
Services expect a requirements.txt file in the root of projects.*

Acknowledgements
================

- Many thanks to Randall Degges for the inspiration to write the book and django-skel.
- All of the contributors_ to this project.

.. _contributors: https://github.com/twoscoops/django-twoscoops-project/blob/master/CONTRIBUTORS.txt

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Caxy\AuditLogBundle\Reader\Persister;

use Caxy\AuditLogBundle\Model\PropertyType;
use Caxy\AuditLogBundle\Model\UpdateType;
use Caxy\AuditLogBundle\Reader\Collection\PersistentCollection;
use Caxy\AuditLogBundle\Reader\ObjectManager;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\Proxy\Proxy;
use Doctrine\ORM\Query;
use PDO;

/**
 * Based off of Doctrine's class Doctrine\ORM\Persisters\BasicEntityPersister (Doctrine ORM 2.3).
 *
 * In order to use Doctrine's generated Proxy classes to allow for lazy-loading,
 * it was necessary to implement a persister that has the same loading functions
 * that could be injected into the Proxy class.
 *
 * Reasons we forked this class from Doctrine's instead of inheriting and enhancing:
 *     - The majority of logic in the original functions would need to be changed completely
 *         in order to work with AuditLog, and some of which are private access so we would
 *         need to create new functions that essentially produce similar results, but with
 *         tweaked logic.
 *     - Most functions in the base class would not be used, which would just make the
 *         object larger than it needed to be.
 *     - Since the entities being loaded from AuditLog are read-only, we did not want
 *         the insert/update/delete functions to be available.
 *
 * A persister is always responsible for a single entity type at a single version group.
 *
 * This BasicEntityPersister implementation provides the default behavior for
 * querying entities that are mapped to a single database table (in Doctrine),
 * from the CaxyAuditLog tables at a specific version group.
 *
 * The querying operations invoked, either through direct find requests or lazy-loading,
 * are the following:
 *
 *     - {@link load} : Loads (the state of) a single, managed entity.
 *     - {@link loadOneToOneEntity} : Loads a one/many-to-one entity association (lazy-loading).
 *     - {@link loadOneToManyCollection} : Loads a one-to-many entity association (lazy-loading).
 *     - {@link loadManyToManyCollection} : Loads a many-to-many entity association (lazy-loading).
 */
class BasicEntityPersister
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    protected $em;

    /**
     * Metadata object that describes the mapping of the mapped entity class.
     *
     * @var \Doctrine\ORM\Mapping\ClassMetadata
     */
    protected $class;

    /**
     * @var int
     */
    protected $versionGroupId;

    /**
     * The underlying DBAL Connection of the used EntityManager.
     *
     * @var \Doctrine\DBAL\Connection
     */
    protected $conn;

    /**
     * The database platform.
     *
     * @var [type]
     */
    protected $platform;

    /**
     * The ObjectManager instance.
     *
     * @var \Caxy\AuditLogBundle\Reader\ObjectManager
     */
    protected $om;

    /**
     * Map from class names to the corresponding table name.
     *
     * @var array
     */
    private $tableNames = array();

    /**
     * @param integer $versionGroupId
     */
    public function __construct(EntityManager $em, ClassMetadata $class, ObjectManager $om, $versionGroupId)
    {
        $this->em = $em;
        $this->conn = $em->getConnection();
        $this->platform = $this->conn->getDatabasePlatform();
        $this->class = $class;
        $this->om = $om;
        $this->versionGroupId = $versionGroupId;
    }

    /**
     * @return ClassMetadata
     */
    public function getClassMetadata()
    {
        return $this->class;
    }

    /**
     * Returns an array representing the entity identifier,
     * or false if the $criteria does not contain the
     * identifier fields.
     *
     * @param array $criteria *
     *
     * @return array
     */
    private function getIdentifier(array $criteria)
    {
        $id = array();
        foreach ($this->class->identifier as $field) {
            if (!isset($criteria[$field]) || $criteria[$field] === null) {
                return false;
            }
            $id[$field] = $criteria[$field];
        }

        return $id;
    }

    /**
     * Gets an array of all class names in this entity's
     * inheritance tree: parent classes, sub classes, and self.
     *
     * @return array
     */
    private function getAllClassNames()
    {
        return array_merge(
            array($this->class->name),
            $this->class->subClasses,
            $this->class->parentClasses
        );
    }

    /**
     * Gets the value of $fieldName for the entity at the current
     * version group.
     *
     * @param mixed  $identifier
     * @param string $fieldName  *
     *
     * @return string
     */
    public function getPropertyValue($identifier, $fieldName)
    {
        if (is_array($identifier)) {
            $identifier = reset($identifier);
        }

        $qb = $this->em->createQueryBuilder('cr');

        $qb->select('tc.content AS text_content, bc.content AS blob_content')
            ->from('CaxyAuditLogBundle:ContentRecord', 'cr')
            ->join('CaxyAuditLogBundle:Property', 'p', 'WITH', $qb->expr()->eq('p.name', ':field_name'))
            ->join('CaxyAuditLogBundle:PropertyType', 'pt', 'WITH', $qb->expr()->andX(
                $qb->expr()->eq('pt.property', 'p'),
                $qb->expr()->eq('cr.propertyType', 'pt')
            ))
            ->join('CaxyAuditLogBundle:Entity', 'e', 'WITH', $qb->expr()->in('e.name', ':class_names'))
            ->join('CaxyAuditLogBundle:EntityRecord', 'er', 'WITH', $qb->expr()->andX(
                $qb->expr()->eq('er.entity', 'e'),
                $qb->expr()->eq('er.loggedEntityId', ':entity_id')
            ))
            ->join('CaxyAuditLogBundle:UpdateType', 'ut', 'WITH', $qb->expr()->eq('ut.entityRecord', 'er'))
            ->join('CaxyAuditLogBundle:Version', 'v', 'WITH', $qb->expr()->andX(
                $qb->expr()->eq('v.updateType', 'ut'),
                $qb->expr()->eq('v', 'cr.version')
            ))
            ->join('CaxyAuditLogBundle:VersionGroup', 'vg', 'WITH', $qb->expr()->andX(
                $qb->expr()->eq('vg', 'v.versionGroup'),
                $qb->expr()->lte('vg.id', ':version_group_id')
            ))
            ->leftJoin('CaxyAuditLogBundle:TextContent', 'tc', 'WITH', $qb->expr()->eq('tc.contentRecord', 'cr'))
            ->leftJoin('CaxyAuditLogBundle:BlobContent', 'bc', 'WITH', $qb->expr()->eq('bc.contentRecord', 'cr'))

            ->orderBy('v.id', 'DESC')
            ->setMaxResults(1)
            ->setParameters(array(
                'field_name' => $fieldName,
                'class_names' => $this->getAllClassNames(),
                'entity_id' => $identifier,
                'version_group_id' => $this->versionGroupId,
            ));

        $result = $qb->getQuery()->getResult();

        if (empty($result)) {
            return;
        }

        return isset($result[0]['blob_content']) ? $result[0]['blob_content'] : $result[0]['text_content'];
    }

    /**
     * Loads the data of the entity with $identifier in the form
     * of a mapped array: fieldName => value.
     *
     * @param mixed $identifier *
     *
     * @return array
     */
    public function loadDataByIdentifier($identifier)
    {
        $data = array();
        $class = $this->class;

        // add discriminator column value to data array, if available
        if ($class->inheritanceType !== ClassMetadata::INHERITANCE_TYPE_NONE
            && isset($class->discriminatorColumn)
        ) {
            $discriminatorField = $class->discriminatorColumn['fieldName'];
            $discriminatorValue = $this->getPropertyValue($identifier, $discriminatorField);
            if ($discriminatorValue !== null) {
                $data[$discriminatorField] = $discriminatorValue;

                $className = $class->discriminatorMap[$discriminatorValue];

                if ($class->name !== $className) {
                    $class = $this->em->getClassMetadata($className);
                }
            }
        }

        foreach ($class->fieldNames as $field) {
            $data[$field] = $this->getPropertyValue($identifier, $field);
        }

        foreach ($class->associationMappings as $field => $assoc) {
            if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
                $data[$field] = $this->getPropertyValue($identifier, $field);
            }
        }

        if (!is_array($identifier)) {
            $identifier = array($class->identifier[0] => $identifier);
        }

        // add identifier values to data array
        foreach ($class->identifier as $fieldName) {
            $data[$fieldName] = isset($identifier[$fieldName]) ? $identifier[$fieldName] : null;
        }

        return $data;
    }

    /**
     * Returns true if the entity with given $identifier has
     * been logged in the auditlog tables, and therefore
     * has data available.
     *
     * @param mixed $identifier *
     *
     * @return bool
     */
    private function entityRecordExists($identifier)
    {
        if (is_array($identifier)) {
            $identifier = $identifier[$this->class->identifier[0]];
        }

        $qb = $this->em->createQueryBuilder('er');

        $qb->select('er.id')
            ->from('CaxyAuditLogBundle:EntityRecord', 'er')
            ->join('er.entity', 'e', 'WITH', $qb->expr()->in('e.name', ':classNames'))
            ->where($qb->expr()->eq('er.loggedEntityId', ':entityId'))
            ->setMaxResults(1)
            ->setParameters(array(
                'classNames' => $this->getAllClassNames(),
                'entityId' => $identifier,
            ));

        $result = $qb->getQuery()->getResult();

        return !empty($result);
    }

    /**
     * Checks if the entity is deleted at this version group.
     *
     * @param mixed $identifier
     *
     * @return bool
     */
    public function isEntityDeleted($identifier)
    {
        if (is_array($identifier)) {
            $identifier = $identifier[$this->class->identifier[0]];
        }

        $qb = $this->em->createQueryBuilder();

        $qb->select('ut.type')
            ->from('CaxyAuditLogBundle:UpdateType', 'ut')
            ->join('CaxyAuditLogBundle:Entity', 'e', 'WITH', $qb->expr()->in('e.name', ':classNames'))
            ->join('CaxyAuditLogBundle:EntityRecord', 'er', 'WITH', $qb->expr()->andX(
                $qb->expr()->eq('er', 'ut.entityRecord'),
                $qb->expr()->eq('er.entity', 'e'),
                $qb->expr()->eq('er.loggedEntityId', ':identifier')
            ))
            ->join('CaxyAuditLogBundle:Version', 'v', 'WITH', $qb->expr()->eq('v.updateType', 'ut'))
            ->join('CaxyAuditLogBundle:VersionGroup', 'vg', 'WITH', $qb->expr()->andX(
                $qb->expr()->eq('vg', 'v.versionGroup'),
                $qb->expr()->lte('vg.id', ':versionGroupId')
            ))
            ->orderBy('v.id', 'DESC')
            ->setMaxResults(1)
            ->setParameters(array(
                'classNames' => $this->getAllClassNames(),
                'versionGroupId' => $this->versionGroupId,
                'identifier' => $identifier,
            ));

        $result = $qb->getQuery()->getResult();

        return empty($result) ? false : $result[0]['type'] == UpdateType::DELETE;
    }

    /**
     * Loads the current actual data of the entity with given $identifier
     * from the Doctrine entity table. Returns false if entity not found.
     *
     * @param mixed $identifier *
     *
     * @return array|bool Array of entity data, or false if not found.
     */
    private function loadCurrentData($identifier)
    {
        if (is_array($identifier)) {
            $identifier = $identifier[$this->class->identifier[0]];
        }
        $qb = $this->em->getRepository($this->class->name)->createQueryBuilder('e');

        $qb->select('e')
            ->where($qb->expr()->eq('e.'.$this->class->identifier[0], ':id'))
            ->setParameter('id', $identifier);

        $result = $qb->getQuery()->getArrayResult();

        if (!empty($result)) {
            return $result[0];
        }

        return false;
    }

    /**
     * Expand the parameters from the given criteria and use
     * the correct binding types if found. Returns an array
     * with the parameters as first item, and the types as
     * the second item.     *.
     *
     * @param array $criteria *
     *
     * @return array
     */
    private function expandParameters($criteria)
    {
        $params = $types = array();

        foreach ($criteria as $field => $value) {
            if ($value === null) {
                continue; // skip null values
            }

            $types[] = $this->getType($field, $value);
            $params[] = $this->getValue($field, $value);
        }

        return array($params, $types);
    }

    /**
     * Infer field type to be used by parameter type casting.
     *
     * @param string $field
     * @param mixed  $value
     *
     * @return int
     */
    private function getType($field, $value)
    {
        // Since we store all values as text,
        // we'll force the type to be string or
        // array of strings
        $type = PDO::PARAM_STR;

        if (is_array($value)) {
            $type = Type::getType($type)->getBindingType();
            $type += Connection::ARRAY_PARAM_OFFSET;
        }

        return $type;
    }

    /**
     * Retrieve the parameter value.
     *
     * @param string $field
     * @param mixed  $value
     *
     * @return mixed
     */
    private function getValue($field, $value)
    {
        if (is_array($value)) {
            $newValue = array();

            foreach ($value as $itemValue) {
                $newValue[] = $this->getIndividualValue($field, $itemValue);
            }

            return $newValue;
        }

        return $this->getIndividualValue($field, $value);
    }

    /**
     * Retrieves an individual parameter value.
     *
     * @param string $field
     * @param mixed  $value
     *
     * @return mixed
     */
    private function getIndividualValue($field, $value)
    {
        if (is_object($value) && $this->em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($value))) {
            $class = $this->em->getClassMetadata(get_class($value));
            $idValues = $class->getIdentifierValues($value);

            $key = key($idValues);

            if (null !== $key) {
                $value = $idValues[$key];
            }
        } elseif ($value instanceof \DateTime) {
            $value = $value->getTimestamp();
        } else {
            try {
                $value = (string) Type::getType($this->class->getTypeOfField($field))->convertToDatabaseValue($value, $this->platform);
            } catch (\Exception $e) {
            }
        }

        return $value;
    }

    /**
     * Returns the mapped table name for the given class.
     *
     * @param string $className
     *
     * @return string
     */
    private function getTableName($className)
    {
        if (!isset($this->tableNames[$className])) {
            $this->tableNames[$className] = $this->em->getClassMetadata($className)->getTableName();
        }

        return $this->tableNames[$className];
    }

    /**
     * Returns a comma-separated string of class names returned
     * from getAllClassNames, to be used in a SQL query.
     *
     * @return string
     */
    private function getAllClassNamesSQL()
    {
        $names = array();

        foreach ($this->getAllClassNames() as $name) {
            $names[] = $this->conn->quote($name);
        }

        return implode(',', $names);
    }

    /**
     * Gets the SQL string for joining the TextContent table in order
     * to get the property value at the given version group.
     *
     * Because the latest property value for an entity at a version group
     * could be stored at any version group prior, a complicated JOIN query is
     * required to get the values of multiple properties in the same SQL statement.
     *
     * In order for the SQL parameters to match their placeholders, an index is supplied
     * is used in the aliases.
     *
     * @param string $field
     * @param int    $index
     * @param mixed  $id
     *
     * @return string
     */
    private function getPropertyJoinSQL($field, $index, $id = null)
    {
        $contentAlias = 'f'.$index;
        $maxAlias = $contentAlias.'_max';

        if (is_array($id)) {
            $id = $id[$this->class->identifier[0]];
        }

        $filterId = $id !== null;

        $sql = 'INNER JOIN '.$this->getTableName('CaxyAuditLogBundle:TextContent').' '.$contentAlias.' '
            .'INNER JOIN ('
                .'SELECT ut.entity_record_id, MAX(tc.id) AS max_text_content_id '
                .'FROM '.$this->getTableName('CaxyAuditLogBundle:TextContent').' tc '
                .'INNER JOIN '.$this->getTableName('CaxyAuditLogBundle:Entity').' e '
                    .'ON e.name IN ('.$this->getAllClassNamesSQL().') '
                .($filterId
                    ? 'INNER JOIN '.$this->getTableName('CaxyAuditLogBundle:EntityRecord').' er '
                        .'ON er.loggedEntityId = '.$this->conn->quote($id).' '
                        .'AND er.entity_id = e.id '
                    : '')
                .'INNER JOIN '.$this->getTableName('CaxyAuditLogBundle:Property').' p '
                    .'ON p.name = '.$this->conn->quote($field).' '
                    .'AND p.entity_id = e.id '
                .'INNER JOIN '.$this->getTableName('CaxyAuditLogBundle:PropertyType').' pt '
                    .'ON pt.type = '.$this->conn->quote(PropertyType::TEXT).' '
                    .'AND pt.property_id = p.id '
                .'INNER JOIN '.$this->getTableName('CaxyAuditLogBundle:ContentRecord').' cr '
                    .'ON cr.id = tc.content_record_id '
                    .'AND cr.property_type_id = pt.id '
                .'INNER JOIN '.$this->getTableName('CaxyAuditLogBundle:Version').' v '
                    .'ON v.id = cr.version_id '
                .'INNER JOIN '.$this->getTableName('CaxyAuditLogBundle:VersionGroup').' vg '
                    .'ON vg.id <= '.$this->conn->quote($this->versionGroupId, PDO::PARAM_INT).' '
                    .'AND vg.id = v.version_group_id '
                .'INNER JOIN '.$this->getTableName('CaxyAuditLogBundle:UpdateType').' ut '
                    .'ON ut.id = v.update_type_id '
                .($filterId
                    ? 'AND ut.entity_record_id = er.id '
                    : '')
                .'GROUP BY ut.entity_record_id'
            .') '.$maxAlias.' '
                .'ON '.$maxAlias.'.entity_record_id = er.id '
                .'AND '.$maxAlias.'.max_text_content_id = '.$contentAlias.'.id ';

        return $sql;
    }

    /**
     * Gets the identifiers of the entities that match $criteria.
     *
     * TODO: Add limit, offset, and orderBy for this function
     *
     * @param array $criteria
     *
     * @return array
     */
    private function getIdsByCriteria(array $criteria)
    {
        $joinSql = $this->getCriteriaJoinSQL($criteria);

        $conditionSql = $this->getSelectConditionSQL($criteria);

        $sql = 'SELECT er.loggedEntityId AS '.$this->class->identifier[0].' FROM '.$this->getTableName('CaxyAuditLogBundle:EntityRecord').' er '
            .$joinSql
            .($conditionSql ? ' WHERE '.$conditionSql : '');

        list($params, $types) = $this->expandParameters($criteria);

        $stmt = $this->conn->executeQuery(trim($sql), $params, $types);

        return $stmt->fetchAll();
    }

    /**
     * Gets the SQL WHERE clause for matching the $criteria.
     *
     * @param array $criteria
     *
     * @return string
     */
    private function getSelectConditionSQL(array $criteria)
    {
        $conditionSql = '';

        $fieldIndex = 0;

        $placeholder = '?';

        foreach ($criteria as $field => $value) {
            $conditionSql .= $conditionSql ? ' AND ' : '';
            $conditionSql .= 'f'.$fieldIndex++.'.content'.(($value === null) ? ' IS NULL' : ' = '.$placeholder);
        }

        return $conditionSql;
    }

    /**
     * Gets the JOIN SQL in order to lookup the fields in $criteria
     * at the version group.
     *
     * @param array $criteria
     *
     * @return string
     */
    private function getCriteriaJoinSQL(array $criteria)
    {
        $joinSql = '';

        $fieldIndex = 0;

        foreach ($criteria as $field => $value) {
            $joinSql .= $this->getPropertyJoinSQL($field, $fieldIndex++);
        }

        return trim($joinSql);
    }

    /**
     * Loads an entity by a list of field criteria.
     *
     * @param array  $criteria The criteria by which to load the entity.
     * @param object $entity   The entity to load the data into. If not specified,
     *                         a new entity is created.
     * @param array  $assoc    The association that connects the entity to load to another entity, if any.
     * @param array  $hints    Hints for entity creation.
     * @param int    $lockmode
     * @param int    $limit    Limit number of results.
     * @param array  $orderBy  Criteria to order by.
     *
     * @return object The loaded entity instance or NULL if the entity can not be found.
     */
    public function load(array $criteria, $entity = null, $assoc = null, array $hints = array(), $lockmode = 0, $limit = null, array $orderBy = null)
    {
        if ($entity !== null) {
            $hints[Query::HINT_REFRESH] = true;
            $hints[Query::HINT_REFRESH_ENTITY] = $entity;
        }

        if (false === ($id = $this->getIdentifier($criteria))) {
            // find id of the entity at version group
            // based on the criteria given
            $results = $this->getIdsByCriteria($criteria);

            if (empty($results)) {
                return;
            }

            $id = $results[0];
        }

        // Return null if entity is deleted at version group
        if ($this->isEntityDeleted($id)) {
            return;
        }

        if (!(isset($hints[Query::HINT_REFRESH]) && $hints[Query::HINT_REFRESH]) &&
            false !== ($newEntity = $this->om->tryGetById($id, $this->class->rootEntityName, $this->versionGroupId))
        ) {
            return $newEntity;
        }

        if ($this->entityRecordExists($id)) {
            $data = $this->loadDataByIdentifier($id);
        } else {
            $data = $this->loadCurrentData($id);
        }

        if ($this->class->inheritanceType !== ClassMetadataInfo::INHERITANCE_TYPE_NONE) {
            if (isset($data[$this->class->discriminatorColumn['fieldName']])) {
                $className = $this->class->discriminatorMap[$data[$this->class->discriminatorColumn['fieldName']]];
            } elseif (isset($this->class->discriminatorValue)) {
                $className = $this->class->discriminatorMap[$this->class->discriminatorValue];
            } else {
                $className = reset($this->class->discriminatorMap);
            }
        } else {
            $className = $this->class->name;
        }
        $newEntity = $this->om->getEntityAtVersionGroup($className, $data, $this->versionGroupId, $hints);

        return $newEntity;
    }

    /**
     * Loads an entity by identifier.
     *
     * @param array       $identifier   The entity identifier.
     * @param object|null $entity       The entity to load the data into. If not specified, a new entity is created.
     *
     * @return object The loaded and managed entity instance or NULL if the entity can not be found.
     */
    public function loadById(array $identifier, $entity = null)
    {
        return $this->load($identifier, $entity);
    }

    /**
     * Loads an entity of this persister's mapped class as part of a single-valued
     * association from another entity.
     *
     * @param array  $assoc        The association to load.
     * @param object $sourceEntity The entity that owns the association (not necessarily the "owning side").
     * @param array  $identifier   The identifier of the entity to load. Must be provided if
     *                             the association to load represents the owning side, otherwise
     *                             the identifier is derived from the $sourceEntity.
     *
     * @return object The loaded entity instance or NULL if the entity can not be found.
     */
    public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = array())
    {
        if (($foundEntity = $this->om->tryGetById($identifier, $assoc['targetEntity'], $this->versionGroupId)) != false) {
            return $foundEntity;
        }

        $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);

        if ($assoc['isOwningSide']) {
            $isInverseSingleValued = $assoc['inversedBy'] && !$targetClass->isCollectionValuedAssociation($assoc['inversedBy']);

            // Mark inverse side as fetched in the hints, otherwise the UoW would
            // try to load it in a separate query (remember: to-one inverse sides can not be lazy).
            $hints = array();

            if ($isInverseSingleValued) {
                $hints['fetched']['r'][$assoc['inversedBy']] = true;
            }

            $targetEntity = $this->load($identifier, null, $assoc, $hints);

            // Complete bidirectional association, if necessary
            if ($targetEntity !== null && $isInverseSingleValued) {
                $targetClass->reflFields[$assoc['inversedBy']]->setValue($targetEntity, $sourceEntity);
            }
        } else {
            $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']);
            $owningAssoc = $targetClass->getAssociationMapping($assoc['mappedBy']);

            // TRICKY: since the association is specular source and target are flipped
            foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) {
                if (!isset($sourceClass->fieldNames[$sourceKeyColumn])) {
                    throw MappingException::joinColumnMustPointToMappedField(
                        $sourceClass->name, $sourceKeyColumn
                    );
                }

                $identifier[$assoc['mappedBy']] =
                    $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity);
            }

            $targetEntity = $this->load($identifier, null, $assoc);

            if ($targetEntity !== null) {
                $targetClass->setFieldValue($targetEntity, $assoc['mappedBy'], $sourceEntity);
            }
        }

        return $targetEntity;
    }

    /**
     * Loads a collection of entities in a one-to-many association.
     *
     * @param array                $assoc
     * @param [type]               $sourceEntity
     * @param PersistentCollection $coll         The collection to load/fill.
     *
     * @return array
     */
    public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentCollection $coll)
    {
        $criteria = array();

        $owningAssoc = $this->class->associationMappings[$assoc['mappedBy']];
        $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']);

        foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) {
            if ($sourceClass->containsForeignIdentifier) {
                $field = $sourceClass->getFieldForColumn($sourceKeyColumn);
                $value = $sourceClass->reflFields[$field]->getValue($sourceEntity);

                if (isset($sourceClass->associationMappings[$field])) {
                    $value = $this->om->getEntityIdentifier($value);
                    $value = $value[$this->em->getClassMetadata($sourceClass->associationMappings[$field]['targetEntity'])->identifier[0]];
                }

                $criteria[$this->class->getFieldForColumn($targetKeyColumn)] = $value;
            } else {
                $criteria[$this->class->getFieldForColumn($targetKeyColumn)] = $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity);
            }
        }

        $ids = $this->getIdsByCriteria($criteria);

        $entities = array();

        foreach ($ids as $id) {
            $entity = $this->load($id);
            if ($entity) {
                $coll->hydrateAdd($entity);
                $entities[] = $entity;
            }
        }

        return $entities;
    }

    /**
     * Loads a collection of entities of a many-to-many association.
     *
     * @param array                $assoc        The association mapping of the association being loaded.
     * @param object               $sourceEntity The entity that owns the collection.
     * @param PersistentCollection $coll         The collection to fill.
     *
     * @return array
     *
     * @todo Support composite keys
     */
    public function loadManyToManyCollection(array $assoc, $sourceEntity, PersistentCollection $coll)
    {
        $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']);
        $arrayType = Type::getType(Type::TARRAY);

        $field = $assoc['fieldName'];

        $sourceId = $sourceClass->getIdentifierValues($sourceEntity);

        $fieldValue = $this->om->getEntityPersister($sourceClass->name, $this->versionGroupId)->getPropertyValue($sourceId, $field);

        $entities = array();

        if ($fieldValue) {
            // Use collection IDs from AL
            $ids = $arrayType->convertToPHPValue($fieldValue, $this->platform);
        } else {
            // Collection IDs not stored, so use current set of IDs
            // The only reason we are doing this is because ManyToMany collections were not logging correctly initially
            // @todo Remove this else block when preparing bundle for public distribution
            $qb = $this->em->createQueryBuilder();

            $qb->select('assoc.'.$this->class->identifier[0])
                ->from($sourceClass->name, 'e')
                ->join('e.'.$field, 'assoc')
                ->where($qb->expr()->eq('e.'.$sourceClass->identifier[0], $sourceId[$sourceClass->identifier[0]]));

            $ids = $qb->getQuery()->getResult();
        }

        foreach ($ids as $id) {
            if (!is_array($id)) {
                $id = array($this->class->identifier[0] => $id);
            }
            $entity = $this->load($id);
            if ($entity) {
                $coll->hydrateAdd($entity);
                $entities[] = $entity;
            }
        }

        return $entities;
    }
}


text:
/// <amd-module name="@angular/core/schematics/migrations/template-var-assignment/analyze_template" />
import { PropertyWrite } from '@angular/compiler';
import { ResolvedTemplate } from '../../utils/ng_component_template';
export interface TemplateVariableAssignment {
    node: PropertyWrite;
    start: number;
    end: number;
}
/**
 * Analyzes a given resolved template by looking for property assignments to local
 * template variables within bound events.
 */
export declare function analyzeResolvedTemplate(template: ResolvedTemplate): TemplateVariableAssignment[] | null;


text:
#include <stdbool.h>

#include "hwpl.h"
#include "link_flags.h"

int link_open_stdio(link_phy_t handle /*, const char * name */){
	return 0;
}

int link_close_stdio(link_phy_t handle){
	return 0;
}

int link_read_stdout(link_phy_t handle, void * buf, int nbyte){
	return link_phy_read(handle, buf, nbyte);
}

int link_write_stdin(link_phy_t handle, const void * buf, int nbyte){
	return link_phy_write(handle, buf, nbyte);
}


text:
<?php
/**
 * About This Version administration panel.
 *
 * @package WordPress
 * @subpackage Administration
 */

/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );

wp_enqueue_style( 'wp-mediaelement' );
wp_enqueue_script( 'wp-mediaelement' );
wp_localize_script( 'mediaelement', '_wpmejsSettings', array(
	'pluginPath' => includes_url( 'js/mediaelement/', 'relative' ),
	'pauseOtherPlayers' => ''
) );

$title = __( 'About' );

list( $display_version ) = explode( '-', $wp_version );

include( ABSPATH . 'wp-admin/admin-header.php' );
?>

<?php printf( __( 'Welcome to WordPress %s' ), $display_version ); ?>

<?php printf( __( 'Thank you for updating! WordPress %s brings you a smoother writing and management experience.' ), $display_version ); ?>

<?php printf( __( 'Version %s' ), $display_version ); ?>

		<?php _e( 'What’s New' ); ?>

		<?php _e( 'Credits' ); ?>

		<?php _e( 'Freedoms' ); ?>

<?php echo _n( 'Maintenance and Security Release', 'Maintenance and Security Releases', 9 ); ?>

<?php printf( _n( 'Version %1$s addressed a security issue.',
         'Version %1$s addressed some security issues.', 1 ), '4.0.9' ); ?>
		<?php printf( __( 'For more information, see the release notes.' ), 'https://codex.wordpress.org/Version_4.0.9' ); ?>

<?php printf( _n( 'Version %1$s addressed some security issues and fixed %2$s bug.',
         'Version %1$s addressed some security issues and fixed %2$s bugs.', 2 ), '4.0.8', number_format_i18n( 2 ) ); ?>
		<?php printf( __( 'For more information, see the release notes.' ), 'https://codex.wordpress.org/Version_4.0.8' ); ?>

<?php printf( _n( 'Version %1$s addressed some security issues and fixed %2$s bug.',
         'Version %1$s addressed some security issues and fixed %2$s bugs.', 2 ), '4.0.7', number_format_i18n( 2 ) ); ?>
		<?php printf( __( 'For more information, see the release notes.' ), 'https://codex.wordpress.org/Version_4.0.7' ); ?>

<?php printf( _n( 'Version %1$s addressed a security issue.',
         'Version %1$s addressed some security issues.', 2 ), '4.0.6' ); ?>
		<?php printf( __( 'For more information, see the release notes.' ), 'https://codex.wordpress.org/Version_4.0.6' ); ?>

<?php printf( _n( 'Version %1$s addressed some security issues and fixed %2$s bug.',
         'Version %1$s addressed some security issues and fixed %2$s bugs.', 3 ), '4.0.5', number_format_i18n( 3 ) ); ?>
		<?php printf( __( 'For more information, see the release notes.' ), 'https://codex.wordpress.org/Version_4.0.5' ); ?>

<?php printf( _n( 'Version %1$s addressed a security issue.',
         'Version %1$s addressed some security issues.', 1 ), '4.0.4' ); ?>
		<?php printf( __( 'For more information, see the release notes.' ), 'https://codex.wordpress.org/Version_4.0.4' ); ?>

<?php printf( _n( 'Version %1$s addressed %2$s bug.',
         'Version %1$s addressed %2$s bugs.', 1 ), '4.0.3', number_format_i18n( 1 ) ); ?>
		<?php printf( __( 'For more information, see the release notes.' ), 'https://codex.wordpress.org/Version_4.0.3' ); ?>

<?php printf( _n( 'Version %1$s addressed a security issue.',
         'Version %1$s addressed some security issues.', 8 ), '4.0.2' ); ?>
		<?php printf( __( 'For more information, see the release notes.' ), 'https://codex.wordpress.org/Version_4.0.2' ); ?>

<?php printf( _n( 'Version %1$s addressed some security issues and fixed %2$s bug.',
         'Version %1$s addressed some security issues and fixed %2$s bugs.', 23 ), '4.0.1', number_format_i18n( 23 ) ); ?>
		<?php printf( __( 'For more information, see the release notes.' ), 'https://codex.wordpress.org/Version_4.0.1' ); ?>

		<?php if ( ( $locale = get_locale() ) && 'en_' === substr( $locale, 0, 3 ) ) : ?>
			<embed src="//v.wordpress.com/bUdzKMro" type="application/x-shockwave-flash" width="640" height="360" allowscriptaccess="always" allowfullscreen="true" wmode="transparent"></embed>
		<?php else : ?>

		<?php endif; ?>

<?php _e( 'Manage your media with style' ); ?>

<?php _e( 'Explore your uploads in a beautiful, endless grid. A new details preview makes viewing and editing any amount of media in sequence a snap.' ); ?>

				<?php
					echo wp_video_shortcode( array(
						'mp4'      => '//s.w.org/images/core/4.0/embed.mp4',
						'ogv'      => '//s.w.org/images/core/4.0/embed.ogv',
						'webm'      => '//s.w.org/images/core/4.0/embed.webm',
						'loop'     => true,
						'autoplay' => true,
						'width'    => 500,
						'height'   => 352
					) );
				?>

<?php _e( 'Working with embeds has never been easier' ); ?>

<?php _e( 'Paste in a YouTube URL on a new line, and watch it magically become an embedded video. Now try it with a tweet. Oh yeah — embedding has become a visual experience. The editor shows a true preview of your embedded content, saving you time and giving you confidence.' ); ?>

<?php _e( 'We’ve expanded the services supported by default, too — you can embed videos from CollegeHumor, playlists from YouTube, and talks from TED. Check out all of the embeds that WordPress supports.' ); ?>

<?php _e( 'Focus on your content' ); ?>

<?php _e( 'Writing and editing is smoother and more immersive with an editor that expands to fit your content as you write, and keeps the formatting tools available at all times.' ); ?>

				<?php
					echo wp_video_shortcode( array(
						'mp4'      => '//s.w.org/images/core/4.0/focus.mp4',
						'ogv'      => '//s.w.org/images/core/4.0/focus.ogv',
						'webm'      => '//s.w.org/images/core/4.0/focus.webm',
						'loop'     => true,
						'autoplay' => true,
						'width'    => 500,
						'height'   => 281
					) );
				?>

<?php _e( 'Finding the right plugin' ); ?>

<?php _e( 'There are more than 30,000 free and open source plugins in the WordPress plugin directory. WordPress 4.0 makes it easier to find the right one for your needs, with new metrics, improved search, and a more visual browsing experience.' ); ?>

			<a href="<?php echo admin_url( 'plugin-install.php' ); ?>" class="button button-large button-primary"><?php _e( 'Browse plugins' ); ?>

<?php _e( 'Under the Hood' ); ?>

<?php _e( 'Customizer API' ); ?>

<?php _e( 'Contexts, panels, and a wider array of controls are now supported in the customizer.' ); ?>

<?php _e( 'Query Ordering' ); ?>

<?php
				/* translators: 1: "ORDER BY" (SQL), 2: "WP_Query" */
				printf( __( 'Developers have more flexibility creating %1$s clauses through %2$s.' ), 'ORDER BY', 'WP_Query' );
			?>

<?php _e( 'External Libraries' ); ?>

<?php _e( 'Updated libraries: TinyMCE 4.1.3, jQuery 1.11.1, MediaElement 2.15.' ); ?>

		<?php if ( current_user_can( 'update_core' ) && isset( $_GET['updated'] ) ) : ?>
		<a href="<?php echo esc_url( self_admin_url( 'update-core.php' ) ); ?>"><?php
			is_multisite() ? _e( 'Return to Updates' ) : _e( 'Return to Dashboard → Updates' );
		?> |
		<?php endif; ?>
		<a href="<?php echo esc_url( self_admin_url() ); ?>"><?php
			is_blog_admin() ? _e( 'Go to Dashboard → Home' ) : _e( 'Go to Dashboard' ); ?>

<?php

include( ABSPATH . 'wp-admin/admin-footer.php' );

// These are strings we may use to describe maintenance/security releases, where we aim for no new strings.
return;

_n_noop( 'Maintenance Release', 'Maintenance Releases' );
_n_noop( 'Security Release', 'Security Releases' );
_n_noop( 'Maintenance and Security Release', 'Maintenance and Security Releases' );

/* translators: 1: WordPress version number. */
_n_noop( 'Version %1$s addressed a security issue.',
         'Version %1$s addressed some security issues.' );

/* translators: 1: WordPress version number, 2: plural number of bugs. */
_n_noop( 'Version %1$s addressed %2$s bug.',
         'Version %1$s addressed %2$s bugs.' );

/* translators: 1: WordPress version number, 2: plural number of bugs. Singular security issue. */
_n_noop( 'Version %1$s addressed a security issue and fixed %2$s bug.',
         'Version %1$s addressed a security issue and fixed %2$s bugs.' );

/* translators: 1: WordPress version number, 2: plural number of bugs. More than one security issue. */
_n_noop( 'Version %1$s addressed some security issues and fixed %2$s bug.',
         'Version %1$s addressed some security issues and fixed %2$s bugs.' );

__( 'For more information, see the release notes.' );


text:
'use strict';

// MODULES //

var isArray = require( 'validate.io-array' ),
	isObject = require( 'validate.io-object' ),
	isNonNegativeInteger = require( 'validate.io-nonnegative-integer' ),
	isNumber = require( 'validate.io-number' ),
	isBoolean = require( 'validate.io-boolean' );

// FUNCTIONS //

/**
* FUNCTION: ascending( a, b )
*	Comparator function used to sort values in ascending order.
*
* @private
* @param {Number} a
* @param {Number} b
* @returns {Number} difference between `a` and `b`
*/
function ascending( a, b ) {
	return a - b;
} // end FUNCTION ascending()

// NANQUANTILES //

/**
* FUNCTION: nanquantiles( arr, num[, opts] )
*	Computes quantiles for an array ignoring non-numeric values.
*
* @param {Array} arr - array of values
* @param {Number} num - number of quantiles
* @param {Object} [opts] - function options
* @param {Boolean} [opts.sorted=false] - boolean flag indicating if the input array is sorted in ascending order.
* @param {Function} [opts.accessor] - accessor function for accessing array values
* @returns {Array|null} array of quantiles or null
*/
function nanquantiles( arr, num, opts ) {
	var sorted,
		clbk,
		qValues,
		id,
		val,
		len,
		d,
		x,
		i;

	if ( !isArray( arr ) ) {
		throw new TypeError( 'nanquantiles()::invalid input argument. First argument must be an array. Value: `' + arr + '`.' );
	}
	if ( !isNonNegativeInteger( num ) ) {
		throw new TypeError( 'nanquantiles()::invalid input argument. Number of quantiles must be a nonnegative integer. Value: `' + num + '`.' );
	}
	if ( arguments.length > 2 ) {
		if ( !isObject( opts ) ) {
			throw new TypeError( 'nanquantiles()::invalid input argument. Options must be an object. Value: `' + opts + '`.' );
		}
		if ( opts.hasOwnProperty( 'sorted' ) ) {
			sorted = opts.sorted;
			if ( !isBoolean( sorted ) ) {
				throw new TypeError( 'nanquantiles()::invalid option. Sorted flag must be a boolean. Option: `' + sorted + '`.' );
			}
		}
		if ( opts.hasOwnProperty( 'accessor' ) ) {
			clbk = opts.accessor;
			if ( typeof clbk !== 'function' ) {
				throw new TypeError( 'nanquantiles()::invalid option. Accessor must be a function. Option: `' + clbk + '`.' );
			}
		}
	}
	d = [];
	for ( i = 0; i < arr.length; i++ ) {
		x = ( clbk ) ? clbk( arr[i] ) : arr[ i ];
		if ( isNumber( x ) ) {
			d.push( x );
		}
	}
	len = d.length;
	if ( !len ) {
		return null;
	}
	if ( !sorted ) {
		d.sort( ascending );
	}
	qValues = new Array( num+1 );

	// 0th quantile is the min:
	qValues[ 0 ] = d[ 0 ];

	// Max defines the quantile upper bound:
	qValues[ num ] = d[ len-1 ];

	// Get the quantiles...
	for ( i = 1; i < num; i++ ) {
		// Calculate the vector index marking the quantile:
		id = ( len * i / num ) - 1;

		// Is the index an integer?
		if ( id%1 === 0 ) {
			// Value is the average between the value at id and id+1:
			val = ( d[ id ] + d[ id+1 ] ) / 2.0;
		} else {
			// Round up to the next index:
			id = Math.ceil( id );
			val = d[ id ];
		}
		qValues[ i ] = val;
	} // end FOR i
	return qValues;
} // end FUNCTION nanquantiles()

// EXPORTS //

module.exports = nanquantiles;


text:
from django.contrib.auth.base_user import BaseUserManager

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """
        Creates and saves a User with given email and password
        :param email: User Email
        :param password: User Password
        :param extra_fields: Other fields in User model
        :return: User model
        """
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        """
        Get user params and pass it to _create_user
        :param email: User Email
        :param password: User Password
        :param extra_fields: Other fields in User model
        :return: _create_user
        """
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        """
        Get user params and pass it to _create_user with is_superuser=true
        :param email: User Email
        :param password: User Password
        :param extra_fields: Other fields in User model
        :return: _create_user
        """
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)


text:
{% extends "admin/base.html" %}

{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}

{% block branding %}

OpenGenfri Administration

{% endblock %}

{% block nav-global %}{% endblock %}


text:
package archimulator.uncore.cache.replacement.partitioned.setDueling;

import archimulator.common.report.ReportNode;
import archimulator.uncore.cache.EvictableCache;
import archimulator.uncore.cache.partitioning.Partitioner;
import archimulator.uncore.cache.replacement.partitioned.PartitionedLRUPolicy;
import archimulator.uncore.cache.setDueling.AbstractSetDuelingUnit;
import archimulator.uncore.cache.setDueling.MainThreadL2MissBasedSetDuelingUnit;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Set dueling partitioned least recently used (LRU) policy based on helper thread L2 request breakdown.
 *
 * @param <StateT> the state type of the parent evictable cache
 * @author Min Cai
 */
public class SetDuelingPartitionedLRUPolicy<StateT extends Serializable> extends PartitionedLRUPolicy<StateT> {
    private List<Partitioner> partitioners;
    private AbstractSetDuelingUnit setDuelingUnit;

    private List<Long> numCachePartitioningHelpersUsed;

    /**
     * Create a set dueling partitioned least recently used (LRU) policy for the specified evictable cache.
     *
     * @param cache        the parent evictable cache
     * @param partitioners the array of partitioners
     */
    public SetDuelingPartitionedLRUPolicy(
            final EvictableCache<StateT> cache,
            Partitioner... partitioners
    ) {
        this(cache, Arrays.asList(partitioners));
    }

    /**
     * Create a set dueling partitioned least recently used (LRU) policy for the specified evictable cache.
     *
     * @param cache        the parent evictable cache
     * @param partitioners the list of partitioners
     */
    public SetDuelingPartitionedLRUPolicy(
            final EvictableCache<StateT> cache,
            List<Partitioner> partitioners
    ) {
        super(cache);

        this.numCachePartitioningHelpersUsed = new ArrayList<>();

        this.partitioners = partitioners;

        for (int i = 0; i < this.partitioners.size(); i++) {
            this.numCachePartitioningHelpersUsed.add(0L);

            Partitioner cachePartitioningHelper = this.partitioners.get(i);

            final int tempI = i;
            cachePartitioningHelper.setShouldIncludePredicate(set -> setDuelingUnit.getPolicyId(set, 0) == tempI);
        }

        this.setDuelingUnit = new MainThreadL2MissBasedSetDuelingUnit(cache, this.partitioners.size(), 6);
    }

    @Override
    protected List<Integer> getPartition(int set) {
        int policyId = setDuelingUnit.getPolicyId(set, 0);

        Partitioner partitioningHelper = this.partitioners.get(policyId);
        this.numCachePartitioningHelpersUsed.set(policyId, this.numCachePartitioningHelpersUsed.get(policyId) + 1);

        return partitioningHelper.getPartition();
    }

    @Override
    public void dumpStats(final ReportNode reportNode) {
        reportNode.getChildren().add(new ReportNode(reportNode, "setDuelingPartitionedLRUPolicy") {{
            for (int i = 0; i < partitioners.size(); i++) {
                getChildren().add(new ReportNode(this, "numCachePartitioningHelperUsed[" + i + "]", numCachePartitioningHelpersUsed.get(i) + ""));
            }

            for (int way : getNumPartitionsPerWay().keySet()) {
                getChildren().add(new ReportNode(this, "numPartitionsPerWay[" + way + "]", getNumPartitionsPerWay().get(way) + ""));
            }

            for (Partitioner cachePartitioningHelper : partitioners) {
                cachePartitioningHelper.dumpStats(reportNode);
            }
        }});
    }

    /**
     * get the list of partitioners.
     *
     * @return the list of partitioners
     */
    public List<Partitioner> getPartitioners() {
        return partitioners;
    }
}


text:
package org.synyx.urlaubsverwaltung.web;

import org.junit.Assert;
import org.junit.Test;

import java.math.BigDecimal;

import java.util.Locale;

/**
 * Unit test for {@link org.synyx.urlaubsverwaltung.web.DecimalNumberPropertyEditor}.
 *
 * @author  Aljona Murygina - murygina@synyx.de
 */
public class DecimalNumberPropertyEditorTest {

    @Test
    public void ensureCorrectNumberFormattingForGermanLocale() {

        DecimalNumberPropertyEditor propertyEditor = new DecimalNumberPropertyEditor(Locale.GERMAN);

        propertyEditor.setValue(new BigDecimal("3"));
        Assert.assertEquals("Wrong text representation", "3", propertyEditor.getAsText());

        propertyEditor.setValue(new BigDecimal("3.5"));
        Assert.assertEquals("Wrong text representation", "3,5", propertyEditor.getAsText());

        propertyEditor.setValue(new BigDecimal("3.50"));
        Assert.assertEquals("Wrong text representation", "3,5", propertyEditor.getAsText());

        propertyEditor.setValue(new BigDecimal("3.75"));
        Assert.assertEquals("Wrong text representation", "3,75", propertyEditor.getAsText());

        propertyEditor.setValue(BigDecimal.valueOf(3.001));
        Assert.assertEquals("Wrong text representation", "3", propertyEditor.getAsText());

        propertyEditor.setValue(BigDecimal.valueOf(3.2342));
        Assert.assertEquals("Wrong text representation", "3,23", propertyEditor.getAsText());
    }

    @Test
    public void ensureCorrectNumberFormattingForEnglishLocale() {

        DecimalNumberPropertyEditor propertyEditor = new DecimalNumberPropertyEditor(Locale.ENGLISH);

        propertyEditor.setValue(new BigDecimal("3"));
        Assert.assertEquals("Wrong text representation", "3", propertyEditor.getAsText());

        propertyEditor.setValue(new BigDecimal("3.5"));
        Assert.assertEquals("Wrong text representation", "3.5", propertyEditor.getAsText());

        propertyEditor.setValue(new BigDecimal("3.50"));
        Assert.assertEquals("Wrong text representation", "3.5", propertyEditor.getAsText());

        propertyEditor.setValue(new BigDecimal("3.75"));
        Assert.assertEquals("Wrong text representation", "3.75", propertyEditor.getAsText());

        propertyEditor.setValue(BigDecimal.valueOf(3.001));
        Assert.assertEquals("Wrong text representation", "3", propertyEditor.getAsText());

        propertyEditor.setValue(BigDecimal.valueOf(3.2342));
        Assert.assertEquals("Wrong text representation", "3.23", propertyEditor.getAsText());
    }

    @Test
    public void ensureCorrectNumberParsingForGermanLocale() {

        DecimalNumberPropertyEditor propertyEditor = new DecimalNumberPropertyEditor(Locale.GERMAN);

        propertyEditor.setAsText("6");
        Assert.assertEquals("Wrong number", new BigDecimal("6.00"), propertyEditor.getValue());

        propertyEditor.setAsText("6,5");
        Assert.assertEquals("Wrong number", new BigDecimal("6.50"), propertyEditor.getValue());

        propertyEditor.setAsText("6,75");
        Assert.assertEquals("Wrong number", new BigDecimal("6.75"), propertyEditor.getValue());

        propertyEditor.setAsText("6,4223");
        Assert.assertEquals("Wrong number", new BigDecimal("6.42"), propertyEditor.getValue());
    }

    @Test
    public void ensureCorrectNumberParsingForEnglishLocale() {

        DecimalNumberPropertyEditor propertyEditor = new DecimalNumberPropertyEditor(Locale.ENGLISH);

        propertyEditor.setAsText("6");
        Assert.assertEquals("Wrong number", new BigDecimal("6.00"), propertyEditor.getValue());

        propertyEditor.setAsText("6.5");
        Assert.assertEquals("Wrong number", new BigDecimal("6.50"), propertyEditor.getValue());

        propertyEditor.setAsText("6.75");
        Assert.assertEquals("Wrong number", new BigDecimal("6.75"), propertyEditor.getValue());

        propertyEditor.setAsText("6.4223");
        Assert.assertEquals("Wrong number", new BigDecimal("6.42"), propertyEditor.getValue());
    }

    @Test
    public void ensureNumberParsingWorksWithCommaSeparatedNumberForGermanLocale() {

        DecimalNumberPropertyEditor propertyEditor = new DecimalNumberPropertyEditor(Locale.GERMAN);

        propertyEditor.setAsText("6,75");
        Assert.assertEquals("Wrong number", new BigDecimal("6.75"), propertyEditor.getValue());
    }

    @Test
    public void ensureNumberParsingWorksWithDotSeparatedNumberForGermanLocale() {

        DecimalNumberPropertyEditor propertyEditor = new DecimalNumberPropertyEditor(Locale.GERMAN);

        propertyEditor.setAsText("6.75");
        Assert.assertEquals("Wrong number", new BigDecimal("6.75"), propertyEditor.getValue());
    }

    @Test
    public void ensureNumberParsingWorksWithCommaSeparatedNumberForEnglishLocale() {

        DecimalNumberPropertyEditor propertyEditor = new DecimalNumberPropertyEditor(Locale.ENGLISH);

        propertyEditor.setAsText("6,75");
        Assert.assertEquals("Wrong number", new BigDecimal("6.75"), propertyEditor.getValue());
    }

    @Test
    public void ensureNumberParsingWorksWithDotSeparatedNumberForEnglishLocale() {

        DecimalNumberPropertyEditor propertyEditor = new DecimalNumberPropertyEditor(Locale.ENGLISH);

        propertyEditor.setAsText("6.75");
        Assert.assertEquals("Wrong number", new BigDecimal("6.75"), propertyEditor.getValue());
    }

    @Test
    public void ensureEmptyTextForNullNumber() {

        DecimalNumberPropertyEditor propertyEditor = new DecimalNumberPropertyEditor(Locale.GERMAN);

        propertyEditor.setValue(null);
        Assert.assertEquals("Wrong text representation", "", propertyEditor.getAsText());
    }

    @Test(expected = IllegalArgumentException.class)
    public void ensureFormattingThrowsIfProvidingAnInvalidNumber() {

        DecimalNumberPropertyEditor propertyEditor = new DecimalNumberPropertyEditor(Locale.GERMAN);

        propertyEditor.setValue("foo");
        propertyEditor.getAsText();
    }

    @Test
    public void ensureSettingEmptyTextResultsInNullNumber() {

        DecimalNumberPropertyEditor propertyEditor = new DecimalNumberPropertyEditor(Locale.ENGLISH);

        propertyEditor.setAsText("");
        Assert.assertNull("Should be null", propertyEditor.getValue());
    }

    @Test
    public void ensureSettingNullTextResultsInNullNumber() {

        DecimalNumberPropertyEditor propertyEditor = new DecimalNumberPropertyEditor(Locale.ENGLISH);

        propertyEditor.setAsText(null);
        Assert.assertNull("Should be null", propertyEditor.getValue());
    }

    @Test(expected = IllegalArgumentException.class)
    public void ensureSettingTextNotRepresentingANumberThrows() {

        DecimalNumberPropertyEditor propertyEditor = new DecimalNumberPropertyEditor(Locale.ENGLISH);

        propertyEditor.setAsText("foo");
    }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<base href="../../" />

		<link type="text/css" rel="stylesheet" href="page.css" />

		[page:LineSegments] →

[name]

			Helper object to show the world-axis-aligned bounding box around an object.

			Note that the object must have a [page:Geometry] or [page:BufferGeometry] for this to work,
			so it won't work with [page:Sprite Sprites].

Example

[example:webgl_helpers WebGL / helpers]

[example:webgl_loader_nrrd WebGL / loader / nrrd]

[example:webgl_buffergeometry_drawcalls advanced / buffergeometry / drawcalls]

		var sphere = new THREE.SphereGeometry();
		var object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
		var box = new THREE.BoxHelper( object, 0xffff00 );
		scene.add( box );

Constructor

[name]( [page:Object3D object], [page:Color color] )

		[page:Object3D object]  -- (optional) the object3D to show the world-axis-aligned boundingbox.

		[page:Color color] --  (optional) hexadecimal value that defines the box's color. Default is 0xffff00.

		Creates a new wireframe box that bounds the passed object. Internally this uses [page:Box3.setFromObject]
		to calculate the dimensions. Note that this includes any children.

Properties

See the base [page:LineSegments] class for common properties.

Methods

See the base [page:LineSegments] class for common methods.

[method:null update]( [page:Object3D object] )

			Updates the helper's geometry to match the dimensions of the
		 	of the passed object, including any children. See [page:Box3.setFromObject].

Source

		[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]


text:
package org.drools.workbench.screens.workitems.backend.server;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.inject.Named;

import org.drools.core.process.core.ParameterDefinition;
import org.drools.core.process.core.WorkDefinition;
import org.drools.core.process.core.datatype.DataType;
import org.drools.core.process.core.datatype.impl.type.BooleanDataType;
import org.drools.core.process.core.datatype.impl.type.FloatDataType;
import org.drools.core.process.core.datatype.impl.type.IntegerDataType;
import org.drools.core.process.core.datatype.impl.type.ObjectDataType;
import org.drools.core.process.core.datatype.impl.type.StringDataType;
import org.drools.workbench.models.datamodel.workitems.PortableBooleanParameterDefinition;
import org.drools.workbench.models.datamodel.workitems.PortableFloatParameterDefinition;
import org.drools.workbench.models.datamodel.workitems.PortableIntegerParameterDefinition;
import org.drools.workbench.models.datamodel.workitems.PortableObjectParameterDefinition;
import org.drools.workbench.models.datamodel.workitems.PortableParameterDefinition;
import org.drools.workbench.models.datamodel.workitems.PortableStringParameterDefinition;
import org.drools.workbench.models.datamodel.workitems.PortableWorkDefinition;
import org.drools.workbench.screens.workitems.model.WorkItemDefinitionElements;
import org.drools.workbench.screens.workitems.model.WorkItemsModelContent;
import org.drools.workbench.screens.workitems.service.WorkItemsEditorService;
import org.drools.workbench.screens.workitems.type.WorkItemsTypeDefinition;
import org.guvnor.common.services.backend.exceptions.ExceptionUtilities;
import org.guvnor.common.services.backend.file.FileDiscoveryService;
import org.guvnor.common.services.backend.file.FileExtensionsFilter;
import org.guvnor.common.services.shared.message.Level;
import org.guvnor.common.services.shared.metadata.model.Metadata;
import org.guvnor.common.services.shared.metadata.model.Overview;
import org.guvnor.common.services.shared.validation.model.ValidationMessage;
import org.guvnor.structure.server.config.ConfigGroup;
import org.guvnor.structure.server.config.ConfigItem;
import org.guvnor.structure.server.config.ConfigType;
import org.guvnor.structure.server.config.ConfigurationService;
import org.jboss.errai.bus.server.annotations.Service;
import org.jbpm.process.workitem.WorkDefinitionImpl;
import org.kie.workbench.common.services.backend.service.KieService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uberfire.backend.server.util.Paths;
import org.uberfire.backend.vfs.Path;
import org.uberfire.ext.editor.commons.service.CopyService;
import org.uberfire.ext.editor.commons.service.DeleteService;
import org.uberfire.ext.editor.commons.service.RenameService;
import org.uberfire.io.IOService;
import org.uberfire.java.nio.file.FileAlreadyExistsException;
import org.uberfire.workbench.events.ResourceOpenedEvent;

@Service
@ApplicationScoped
public class WorkItemsEditorServiceImpl
        extends KieService<WorkItemsModelContent>
        implements WorkItemsEditorService {

    private static final Logger log = LoggerFactory.getLogger( WorkItemsEditorServiceImpl.class );

    @Inject
    @Named("ioStrategy")
    private IOService ioService;

    @Inject
    private CopyService copyService;

    @Inject
    private DeleteService deleteService;

    @Inject
    private RenameService renameService;

    @Inject
    private Event<ResourceOpenedEvent> resourceOpenedEvent;

    @Inject
    private ConfigurationService configurationService;

    @Inject
    private FileDiscoveryService fileDiscoveryService;

    @Inject
    private ResourceWorkDefinitionsLoader resourceWorkDefinitionsLoader;

    @Inject
    private ConfigWorkDefinitionsLoader configWorkDefinitionsLoader;

    @Inject
    private WorkItemsTypeDefinition resourceTypeDefinition;

    private WorkItemDefinitionElements workItemDefinitionElements;
    private FileExtensionsFilter imageFilter = new FileExtensionsFilter( new String[]{ "png", "gif", "jpg" } );

    @PostConstruct
    public void setupWorkItemDefinitionElements() {
        workItemDefinitionElements = new WorkItemDefinitionElements( loadWorkItemDefinitionElements() );
    }

    private Map<String, String> loadWorkItemDefinitionElements() {
        final Map<String, String> workItemDefinitionElements = new HashMap<String, String>();
        final List<ConfigGroup> editorConfigGroups = configurationService.getConfiguration( ConfigType.EDITOR );
        for ( ConfigGroup editorConfigGroup : editorConfigGroups ) {
            if ( WORK_ITEMS_EDITOR_SETTINGS.equals( editorConfigGroup.getName() ) ) {
                for ( ConfigItem item : editorConfigGroup.getItems() ) {
                    final String itemName = item.getName();
                    final String itemValue = editorConfigGroup.getConfigItemValue( itemName );
                    workItemDefinitionElements.put( itemName,
                                                    itemValue );
                }
            }
        }
        return workItemDefinitionElements;
    }

    @Override
    public Path create( final Path context,
                        final String fileName,
                        final String content,
                        final String comment ) {
        try {
            //Get the template for new Work Item Definitions, stored as a configuration item
            String defaultDefinition = workItemDefinitionElements.getDefinitionElements().get( WORK_ITEMS_EDITOR_SETTINGS_DEFINITION );
            if ( defaultDefinition == null ) {
                defaultDefinition = "";
            }
            defaultDefinition = defaultDefinition.replaceAll( "\\|",
                                                              "" );

            //Write file to VFS
            final org.uberfire.java.nio.file.Path nioPath = Paths.convert( context ).resolve( fileName );
            final Path newPath = Paths.convert( nioPath );

            if ( ioService.exists( nioPath ) ) {
                throw new FileAlreadyExistsException( nioPath.toString() );
            }

            ioService.write( nioPath,
                             defaultDefinition,
                             makeCommentedOption( comment ) );

            return newPath;

        } catch ( Exception e ) {
            throw ExceptionUtilities.handleException( e );
        }
    }

    @Override
    public String load( final Path path ) {
        try {
            final String content = ioService.readAllString( Paths.convert( path ) );

            return content;

        } catch ( Exception e ) {
            throw ExceptionUtilities.handleException( e );
        }
    }

    @Override
    public WorkItemsModelContent loadContent( final Path path ) {
        return super.loadContent(path);
    }

    @Override
    protected WorkItemsModelContent constructContent(Path path, Overview overview) {
        final String definition = load(path);
        final List<String> workItemImages = loadWorkItemImages(path);

        //Signal opening to interested parties
        resourceOpenedEvent.fire(new ResourceOpenedEvent(path,
                                                         sessionInfo));

        return new WorkItemsModelContent(definition,
                                         overview,
                                         workItemImages);

    }

    private List<String> loadWorkItemImages( final Path resourcePath ) {
        final Path projectRoot = projectService.resolveProject( resourcePath ).getRootPath();
        final org.uberfire.java.nio.file.Path nioProjectPath = Paths.convert( projectRoot );
        final org.uberfire.java.nio.file.Path nioResourceParent = Paths.convert( resourcePath ).getParent();

        final Collection<org.uberfire.java.nio.file.Path> imagePaths = fileDiscoveryService.discoverFiles( nioProjectPath,
                                                                                imageFilter,
                                                                                true );
        final List<String> images = new ArrayList<String>();
        for ( org.uberfire.java.nio.file.Path imagePath : imagePaths ) {
            final org.uberfire.java.nio.file.Path relativePath = nioResourceParent.relativize( imagePath );
            images.add( relativePath.toString() );
        }
        return images;
    }

    @Override
    public WorkItemDefinitionElements loadDefinitionElements() {
        return workItemDefinitionElements;
    }

    @Override
    public Path save( final Path resource,
                      final String content,
                      final Metadata metadata,
                      final String comment ) {
        try {
            Metadata currentMetadata = metadataService.getMetadata( resource );
            ioService.write( Paths.convert( resource ),
                             content,
                             metadataService.setUpAttributes( resource,
                                                              metadata ),
                             makeCommentedOption( comment ) );

            fireMetadataSocialEvents( resource, currentMetadata, metadata );
            return resource;

        } catch ( Exception e ) {
            throw ExceptionUtilities.handleException( e );
        }
    }

    @Override
    public void delete( final Path path,
                        final String comment ) {
        try {
            deleteService.delete( path,
                                  comment );

        } catch ( Exception e ) {
            throw ExceptionUtilities.handleException( e );
        }
    }

    @Override
    public Path rename( final Path path,
                        final String newName,
                        final String comment ) {
        try {
            return renameService.rename( path,
                                         newName,
                                         comment );

        } catch ( Exception e ) {
            throw ExceptionUtilities.handleException( e );
        }
    }

    @Override
    public Path copy( final Path path,
                      final String newName,
                      final String comment ) {
        try {
            return copyService.copy( path,
                                     newName,
                                     comment );

        } catch ( Exception e ) {
            throw ExceptionUtilities.handleException( e );
        }
    }

    @Override
    public boolean accepts( final Path path ) {
        return resourceTypeDefinition.accept( path );
    }

    @Override
    public List<ValidationMessage> validate( final Path path ) {
        try {
            final String content = ioService.readAllString( Paths.convert( path ) );
            return validate( path,
                             content );

        } catch ( Exception e ) {
            throw ExceptionUtilities.handleException( e );
        }
    }

    @Override
    public List<ValidationMessage> validate( final Path path,
                                             final String content ) {
        return doValidation( path,
                             content );
    }

    private List<ValidationMessage> doValidation( final Path path,
                                                  final String content ) {
        final List<ValidationMessage> validationMessages = new ArrayList<ValidationMessage>();
        final List<String> workItemDefinitions = new ArrayList<String>();
        workItemDefinitions.add( content );
        try {
            WorkDefinitionsParser.parse( workItemDefinitions );

        } catch ( Exception e ) {
            final ValidationMessage msg = new ValidationMessage();
            msg.setPath( path );
            msg.setLevel( Level.ERROR );
            msg.setText( e.getMessage() );
            validationMessages.add( msg );
        }
        return validationMessages;
    }

    @Override
    public Set<PortableWorkDefinition> loadWorkItemDefinitions( final Path path ) {
        final Map<String, WorkDefinition> workDefinitions = new HashMap<String, WorkDefinition>();

        try {
            //Load WorkItemDefinitions from VFS
            final Path projectRoot = projectService.resolveProject( path ).getRootPath();
            workDefinitions.putAll( resourceWorkDefinitionsLoader.loadWorkDefinitions( projectRoot ) );

            //Load WorkItemDefinitions from ConfigurationService
            workDefinitions.putAll( configWorkDefinitionsLoader.loadWorkDefinitions() );

            //Copy the Work Items into Structures suitable for GWT
            final Set<PortableWorkDefinition> workItems = new HashSet<PortableWorkDefinition>();
            for ( Map.Entry<String, WorkDefinition> entry : workDefinitions.entrySet() ) {
                final PortableWorkDefinition wid = new PortableWorkDefinition();
                final WorkDefinitionImpl wd = (WorkDefinitionImpl) entry.getValue();
                wid.setName( wd.getName() );
                wid.setDisplayName( wd.getDisplayName() );
                wid.setParameters( convertWorkItemParameters( entry.getValue().getParameters() ) );
                wid.setResults( convertWorkItemParameters( entry.getValue().getResults() ) );
                workItems.add( wid );
            }
            return workItems;

        } catch ( Exception e ) {
            throw ExceptionUtilities.handleException( e );
        }
    }

    private Set<PortableParameterDefinition> convertWorkItemParameters( final Set<ParameterDefinition> parameters ) {
        final Set<PortableParameterDefinition> pps = new HashSet<PortableParameterDefinition>();
        for ( ParameterDefinition pd : parameters ) {
            final DataType pdt = pd.getType();
            PortableParameterDefinition ppd = null;
            if ( pdt instanceof BooleanDataType ) {
                ppd = new PortableBooleanParameterDefinition();
            } else if ( pdt instanceof FloatDataType ) {
                ppd = new PortableFloatParameterDefinition();
            } else if ( pdt instanceof IntegerDataType ) {
                ppd = new PortableIntegerParameterDefinition();
            } else if ( pdt instanceof ObjectDataType ) {
                ppd = new PortableObjectParameterDefinition();
                final PortableObjectParameterDefinition oppd = (PortableObjectParameterDefinition) ppd;
                final ObjectDataType odt = (ObjectDataType) pdt;
                oppd.setClassName( odt.getClassName() );
            } else if ( pd.getType() instanceof StringDataType ) {
                ppd = new PortableStringParameterDefinition();
            }
            if ( ppd != null ) {
                ppd.setName( pd.getName() );
                pps.add( ppd );
            }
        }
        return pps;
    }

}


text:
% Example input:
% outdir = './out/';
% PREFIX = 'taylorswift_query';
% queriesToRefFilelist = './audio/taylorswift_querytoref.list';
function MRR = calculateMRR(queriesToRefFilelist, PREFIX, outdir)
% This function calculates the MRR value. The input parameters are
%       queriesToRefFilelist - indicates the expected matched between
%                              queries and references
%       PREFIX - indicates the prefix of the hypothesis files before number
%       outdir - indicates the directory of hypothesis file
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    fid = fopen(queriesToRefFilelist);
    count = 0;

    sum_RR = 0;
    while true
        line = fgetl(fid);
        if(~ischar(line))
            break
        end
        data = sscanf(line, '%g %g', 2);
        query_id = data(1);
        targetRef_id = data(2);
        count = count + 1;
        hypothesis_file = strcat(outdir, PREFIX, num2str(count), '.hyp');
        sum_RR = sum_RR + 1.0 / findRank(hypothesis_file, targetRef_id);
    end
    MRR = sum_RR / count;
end

function rank = findRank(hypothesis_file, expected)
    fid = fopen(hypothesis_file);
    currentLineNo = 0;
    while true
       line = fgetl(fid);
       if(~ischar(line))
           break
       end
       currentLineNo = currentLineNo + 1;
       currentPrediction = sscanf(line, '%g',1);
       if (currentPrediction == expected)
           rank = currentLineNo;
           break
       end
    end
end


text:
OUTFILE=""
WORKDIR=""
TEST=""
FORCE=""
WARN=""
SORTARG=""

PATH=/sbin:/usr/sbin:/bin:/usr/bin

## Well, if there's ever a bad way to do things, Nexenta has it.
## http://nexenta.org/projects/site/wiki/Personalities
unset SUN_PERSONALITY

while getopts "o:s:d:tnw:f" options; do
	case $options in
		o ) OUTFILE=$OPTARG;;
		d ) WORKDIR=$OPTARG;;
		n ) SORTARG="-n";;
		w ) WARNMSG="$OPTARG";;
		f ) FORCE="true";;
		t ) TEST="true";;
		* ) echo "Specify output file with -o and fragments directory with -d"
		    exit 1;;
	esac
done

# do we have -o?
if [ x${OUTFILE} = "x" ]; then
	echo "Please specify an output file with -o"
	exit 1
fi

# do we have -d?
if [ x${WORKDIR} = "x" ]; then
	echo "Please fragments directory with -d"
	exit 1
fi

# can we write to -o?
if [ -f ${OUTFILE} ]; then
	if [ ! -w ${OUTFILE} ]; then
		echo "Cannot write to ${OUTFILE}"
		exit 1
	fi
else
	if [ ! -w `dirname ${OUTFILE}` ]; then
		echo "Cannot write to `dirname ${OUTFILE}` to create ${OUTFILE}"
		exit 1
	fi
fi

# do we have a fragments subdir inside the work dir?
if [ ! -d "${WORKDIR}/fragments" ]  && [ ! -x "${WORKDIR}/fragments" ]; then
	echo "Cannot access the fragments directory"
	exit 1
fi

# are there actually any fragments?
if [ ! "$(ls -A ${WORKDIR}/fragments)" ]; then
	if [ x${FORCE} = "x" ]; then
		echo "The fragments directory is empty, cowardly refusing to make empty config files"
		exit 1
	fi
fi

cd ${WORKDIR}

if [ x${WARNMSG} = "x" ]; then
	: > "fragments.concat"
else
	printf '%s\n' "$WARNMSG" > "fragments.concat"
fi

# find all the files in the fragments directory, sort them numerically and concat to fragments.concat in the working dir
find fragments/ -type f -follow | LANG=C sort ${SORTARG} | while read -r fragfile; do
	cat "$fragfile" >> "fragments.concat"
done

if [ x${TEST} = "x" ]; then
	# This is a real run, copy the file to outfile
	cp fragments.concat ${OUTFILE}
	RETVAL=$?
else
	# Just compare the result to outfile to help the exec decide
	cmp ${OUTFILE} fragments.concat
	RETVAL=$?
fi

exit $RETVAL


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using EnvDTE;

namespace WickedSick.Thea.VisualStudioInterop
{
    public class VisualStudioInstance
    {
        private _DTE _DTEInstance;

        protected dynamic GetDebugger()
        {
            if (_DTEInstance == null)
                return null;

            ComMessageFilter.Register();
            try
            {
                return _DTEInstance.Debugger;
            }
            finally
            {
                ComMessageFilter.Revoke();
            }
        }

        public VisualStudioInstance(int processID)
        {
            ProcessID = processID;
        }

        public int ProcessID { get; protected set; }
        public string ProcessTitle { get; set; }
        public bool IsProcessAlive
        {
            get
            {
                var process = System.Diagnostics.Process.GetProcessById(ProcessID);
                return process != null;
            }
        }
        public bool IsDebugging
        {
            get
            {
                try
                {
                    var debugger = GetDebugger();
                    if (debugger == null)
                        return false;
                    var processes = debugger.DebuggedProcesses;
                    if (processes == null)
                        return false;
                    return processes.Count > 0;
                }
                catch (COMException cex)
                {
                    //if user is interacting with visual studio debugger visualizer, the call will be rejected
                    if (IsRejectedCall(cex))
                    {
                        Debug.WriteLine("Rejected call.");
                        return true;
                    }
                    return false;
                }
            }
        }

        public bool Attach()
        {
            IntPtr numFetched = IntPtr.Zero;
            IRunningObjectTable runningObjectTable;
            IEnumMoniker monikerEnumerator;
            IMoniker[] monikers = new IMoniker[1];

            NativeMethods.GetRunningObjectTable(0, out runningObjectTable);
            runningObjectTable.EnumRunning(out monikerEnumerator);
            monikerEnumerator.Reset();

            while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
            {
                IBindCtx ctx;
                NativeMethods.CreateBindCtx(0, out ctx);

                string runningObjectName;
                monikers[0].GetDisplayName(ctx, null, out runningObjectName);

                object runningObjectVal;
                runningObjectTable.GetObject(monikers[0], out runningObjectVal);

                if (runningObjectVal is _DTE && runningObjectName.StartsWith("!VisualStudio"))
                {
                    int currentProcessId = int.Parse(runningObjectName.Split(':')[1]);

                    if (currentProcessId == ProcessID)
                    {
                        _DTEInstance = (_DTE)runningObjectVal;
                        return true;
                    }
                }
            }
            _DTEInstance = null;
            return false;
        }

        public string GetExpression(string expression)
        {
            var debugger = GetDebugger();
            if (debugger == null)
                return null;
            EnvDTE.Expression obj;
            try
            {
                obj = debugger.GetExpression(string.Format("({0}).toString()", expression), false, 1000);
                if (obj == null)
                    return null;
                if (!obj.IsValidValue)
                    return null;
                var value = obj.Value;
                switch (obj.Type)
                {
                    case "String":
                        if (value.StartsWith("\""))
                            value = value.Substring(1);
                        if (value.EndsWith("\""))
                            value = value.Length > 1 ? value.Substring(0, value.Length - 1) : "";
                        break;
                }
                return value;
            }
            catch (COMException cex)
            {
                HandleCOMException(cex);
            }
            return null;
        }

        public void ExecuteStatement(string expression)
        {
            var debugger = GetDebugger();
            if (debugger == null)
                return;
            try
            {
                debugger.ExecuteStatement(expression, 1000, true);
            }
            catch (COMException cex)
            {
                HandleCOMException(cex);
            }
        }

        public IEnumerable<EnvDTE.Process> GetDebuggedProcesses()
        {
            var debugger = GetDebugger();
            if (debugger != null)
            {
                dynamic processes = debugger.DebuggedProcesses;
                if (processes != null)
                {
                    for (int i = 1; i <= processes.Count; i++)
                    {
                        var p = processes.Item(i);
                        //p.Name.ToString();
                        //p.ProcessID.ToString();
                        yield return processes.Item(i);
                    }
                }
            }
        }

        private void HandleCOMException(COMException cex)
        {
            if (IsContextNotAvailable(cex))
            {
                Debug.WriteLine("Context not available.");
                throw new ContextNotAvailableException(cex);
            }
            if (IsRejectedCall(cex))
            {
                Debug.WriteLine("Rejected call.");
                throw new ContextNotAvailableException(cex);
            }

            try { System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(cex.ErrorCode); }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }

        private static bool IsContextNotAvailable(COMException cex)
        {
            unchecked
            {
                return cex.ErrorCode == (int)0x89711006;
            }
        }

        private static bool IsRejectedCall(COMException cex)
        {
            // "Call was rejected by callee. (Exception from HRESULT: 0x80010001 (RPC_E_CALL_REJECTED))"
            unchecked
            {
                return cex.ErrorCode == (int)0x80010001;
            }
        }
    }
}