text:
<?php

namespace Doctrine\ORM\Internal\Hydration;

use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Events;
use Doctrine\ORM\Mapping\ClassMetadata;
use PDO;
use function array_map;
use function in_array;

/**
 * Base class for all hydrators. A hydrator is a class that provides some form
 * of transformation of an SQL result set into another structure.
 *
 * @since  2.0
 * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author Roman Borschel <roman@code-factory.org>
 * @author Guilherme Blanco <guilhermeblanoc@hotmail.com>
 */
abstract class AbstractHydrator
{
    /**
     * The ResultSetMapping.
     *
     * @var \Doctrine\ORM\Query\ResultSetMapping
     */
    protected $_rsm;

    /**
     * The EntityManager instance.
     *
     * @var EntityManagerInterface
     */
    protected $_em;

    /**
     * The dbms Platform instance.
     *
     * @var \Doctrine\DBAL\Platforms\AbstractPlatform
     */
    protected $_platform;

    /**
     * The UnitOfWork of the associated EntityManager.
     *
     * @var \Doctrine\ORM\UnitOfWork
     */
    protected $_uow;

    /**
     * Local ClassMetadata cache to avoid going to the EntityManager all the time.
     *
     * @var array
     */
    protected $_metadataCache = [];

    /**
     * The cache used during row-by-row hydration.
     *
     * @var array
     */
    protected $_cache = [];

    /**
     * The statement that provides the data to hydrate.
     *
     * @var \Doctrine\DBAL\Driver\Statement
     */
    protected $_stmt;

    /**
     * The query hints.
     *
     * @var array
     */
    protected $_hints;

    /**
     * Initializes a new instance of a class derived from <tt>AbstractHydrator</tt>.
     *
     * @param EntityManagerInterface $em The EntityManager to use.
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->_em       = $em;
        $this->_platform = $em->getConnection()->getDatabasePlatform();
        $this->_uow      = $em->getUnitOfWork();
    }

    /**
     * Initiates a row-by-row hydration.
     *
     * @param object $stmt
     * @param object $resultSetMapping
     * @param array  $hints
     *
     * @return IterableResult
     */
    public function iterate($stmt, $resultSetMapping, array $hints = [])
    {
        $this->_stmt  = $stmt;
        $this->_rsm   = $resultSetMapping;
        $this->_hints = $hints;

        $evm = $this->_em->getEventManager();

        $evm->addEventListener([Events::onClear], $this);

        $this->prepare();

        return new IterableResult($this);
    }

    /**
     * Hydrates all rows returned by the passed statement instance at once.
     *
     * @param object $stmt
     * @param object $resultSetMapping
     * @param array  $hints
     *
     * @return array
     */
    public function hydrateAll($stmt, $resultSetMapping, array $hints = [])
    {
        $this->_stmt  = $stmt;
        $this->_rsm   = $resultSetMapping;
        $this->_hints = $hints;

        $this->_em->getEventManager()->addEventListener([Events::onClear], $this);

        $this->prepare();

        $result = $this->hydrateAllData();

        $this->cleanup();

        return $result;
    }

    /**
     * Hydrates a single row returned by the current statement instance during
     * row-by-row hydration with {@link iterate()}.
     *
     * @return mixed
     */
    public function hydrateRow()
    {
        $row = $this->_stmt->fetch(PDO::FETCH_ASSOC);

        if ( ! $row) {
            $this->cleanup();

            return false;
        }

        $result = [];

        $this->hydrateRowData($row, $result);

        return $result;
    }

    /**
     * When executed in a hydrate() loop we have to clear internal state to
     * decrease memory consumption.
     *
     * @param mixed $eventArgs
     *
     * @return void
     */
    public function onClear($eventArgs)
    {
    }

    /**
     * Executes one-time preparation tasks, once each time hydration is started
     * through {@link hydrateAll} or {@link iterate()}.
     *
     * @return void
     */
    protected function prepare()
    {
    }

    /**
     * Executes one-time cleanup tasks at the end of a hydration that was initiated
     * through {@link hydrateAll} or {@link iterate()}.
     *
     * @return void
     */
    protected function cleanup()
    {
        $this->_stmt->closeCursor();

        $this->_stmt          = null;
        $this->_rsm           = null;
        $this->_cache         = [];
        $this->_metadataCache = [];

        $this
            ->_em
            ->getEventManager()
            ->removeEventListener([Events::onClear], $this);
    }

    /**
     * Hydrates a single row from the current statement instance.
     *
     * Template method.
     *
     * @param array $data   The row data.
     * @param array $result The result to fill.
     *
     * @return void
     *
     * @throws HydrationException
     */
    protected function hydrateRowData(array $data, array &$result)
    {
        throw new HydrationException("hydrateRowData() not implemented by this hydrator.");
    }

    /**
     * Hydrates all rows from the current statement instance at once.
     *
     * @return array
     */
    abstract protected function hydrateAllData();

    /**
     * Processes a row of the result set.
     *
     * Used for identity-based hydration (HYDRATE_OBJECT and HYDRATE_ARRAY).
     * Puts the elements of a result row into a new array, grouped by the dql alias
     * they belong to. The column names in the result set are mapped to their
     * field names during this procedure as well as any necessary conversions on
     * the values applied. Scalar values are kept in a specific key 'scalars'.
     *
     * @param array  $data               SQL Result Row.
     * @param array &$id                 Dql-Alias => ID-Hash.
     * @param array &$nonemptyComponents Does this DQL-Alias has at least one non NULL value?
     *
     * @return array  An array with all the fields (name => value) of the data row,
     *                grouped by their component alias.
     */
    protected function gatherRowData(array $data, array &$id, array &$nonemptyComponents)
    {
        $rowData = ['data' => []];

        foreach ($data as $key => $value) {
            if (($cacheKeyInfo = $this->hydrateColumnInfo($key)) === null) {
                continue;
            }

            $fieldName = $cacheKeyInfo['fieldName'];

            switch (true) {
                case (isset($cacheKeyInfo['isNewObjectParameter'])):
                    $argIndex = $cacheKeyInfo['argIndex'];
                    $objIndex = $cacheKeyInfo['objIndex'];
                    $type     = $cacheKeyInfo['type'];
                    $value    = $type->convertToPHPValue($value, $this->_platform);

                    $rowData['newObjects'][$objIndex]['class']           = $cacheKeyInfo['class'];
                    $rowData['newObjects'][$objIndex]['args'][$argIndex] = $value;
                    break;

                case (isset($cacheKeyInfo['isScalar'])):
                    $type  = $cacheKeyInfo['type'];
                    $value = $type->convertToPHPValue($value, $this->_platform);

                    $rowData['scalars'][$fieldName] = $value;
                    break;

                //case (isset($cacheKeyInfo['isMetaColumn'])):
                default:
                    $dqlAlias = $cacheKeyInfo['dqlAlias'];
                    $type     = $cacheKeyInfo['type'];

                    // If there are field name collisions in the child class, then we need
                    // to only hydrate if we are looking at the correct discriminator value
                    if (isset($cacheKeyInfo['discriminatorColumn'], $data[$cacheKeyInfo['discriminatorColumn']])
                        && ! in_array((string) $data[$cacheKeyInfo['discriminatorColumn']], $cacheKeyInfo['discriminatorValues'], true)
                    ) {
                        break;
                    }

                    // in an inheritance hierarchy the same field could be defined several times.
                    // We overwrite this value so long we don't have a non-null value, that value we keep.
                    // Per definition it cannot be that a field is defined several times and has several values.
                    if (isset($rowData['data'][$dqlAlias][$fieldName])) {
                        break;
                    }

                    $rowData['data'][$dqlAlias][$fieldName] = $type
                        ? $type->convertToPHPValue($value, $this->_platform)
                        : $value;

                    if ($cacheKeyInfo['isIdentifier'] && $value !== null) {
                        $id[$dqlAlias] .= '|' . $value;
                        $nonemptyComponents[$dqlAlias] = true;
                    }
                    break;
            }
        }

        return $rowData;
    }

    /**
     * Processes a row of the result set.
     *
     * Used for HYDRATE_SCALAR. This is a variant of _gatherRowData() that
     * simply converts column names to field names and properly converts the
     * values according to their types. The resulting row has the same number
     * of elements as before.
     *
     * @param array $data
     *
     * @return array The processed row.
     */
    protected function gatherScalarRowData(&$data)
    {
        $rowData = [];

        foreach ($data as $key => $value) {
            if (($cacheKeyInfo = $this->hydrateColumnInfo($key)) === null) {
                continue;
            }

            $fieldName = $cacheKeyInfo['fieldName'];

            // WARNING: BC break! We know this is the desired behavior to type convert values, but this
            // erroneous behavior exists since 2.0 and we're forced to keep compatibility.
            if ( ! isset($cacheKeyInfo['isScalar'])) {
                $dqlAlias  = $cacheKeyInfo['dqlAlias'];
                $type      = $cacheKeyInfo['type'];
                $fieldName = $dqlAlias . '_' . $fieldName;
                $value     = $type
                    ? $type->convertToPHPValue($value, $this->_platform)
                    : $value;
            }

            $rowData[$fieldName] = $value;
        }

        return $rowData;
    }

    /**
     * Retrieve column information from ResultSetMapping.
     *
     * @param string $key Column name
     *
     * @return array|null
     */
    protected function hydrateColumnInfo($key)
    {
        if (isset($this->_cache[$key])) {
            return $this->_cache[$key];
        }

        switch (true) {
            // NOTE: Most of the times it's a field mapping, so keep it first!!!
            case (isset($this->_rsm->fieldMappings[$key])):
                $classMetadata = $this->getClassMetadata($this->_rsm->declaringClasses[$key]);
                $fieldName     = $this->_rsm->fieldMappings[$key];
                $fieldMapping  = $classMetadata->fieldMappings[$fieldName];
                $ownerMap      = $this->_rsm->columnOwnerMap[$key];
                $columnInfo    = [
                    'isIdentifier' => \in_array($fieldName, $classMetadata->identifier, true),
                    'fieldName'    => $fieldName,
                    'type'         => Type::getType($fieldMapping['type']),
                    'dqlAlias'     => $ownerMap,
                ];

                // the current discriminator value must be saved in order to disambiguate fields hydration,
                // should there be field name collisions
                if ($classMetadata->parentClasses && isset($this->_rsm->discriminatorColumns[$ownerMap])) {
                    return $this->_cache[$key] = \array_merge(
                        $columnInfo,
                        [
                            'discriminatorColumn' => $this->_rsm->discriminatorColumns[$ownerMap],
                            'discriminatorValue'  => $classMetadata->discriminatorValue,
                            'discriminatorValues' => $this->getDiscriminatorValues($classMetadata),
                        ]
                    );
                }

                return $this->_cache[$key] = $columnInfo;

            case (isset($this->_rsm->newObjectMappings[$key])):
                // WARNING: A NEW object is also a scalar, so it must be declared before!
                $mapping = $this->_rsm->newObjectMappings[$key];

                return $this->_cache[$key] = [
                    'isScalar'             => true,
                    'isNewObjectParameter' => true,
                    'fieldName'            => $this->_rsm->scalarMappings[$key],
                    'type'                 => Type::getType($this->_rsm->typeMappings[$key]),
                    'argIndex'             => $mapping['argIndex'],
                    'objIndex'             => $mapping['objIndex'],
                    'class'                => new \ReflectionClass($mapping['className']),
                ];

            case (isset($this->_rsm->scalarMappings[$key])):
                return $this->_cache[$key] = [
                    'isScalar'  => true,
                    'fieldName' => $this->_rsm->scalarMappings[$key],
                    'type'      => Type::getType($this->_rsm->typeMappings[$key]),
                ];

            case (isset($this->_rsm->metaMappings[$key])):
                // Meta column (has meaning in relational schema only, i.e. foreign keys or discriminator columns).
                $fieldName = $this->_rsm->metaMappings[$key];
                $dqlAlias  = $this->_rsm->columnOwnerMap[$key];
                $type      = isset($this->_rsm->typeMappings[$key])
                    ? Type::getType($this->_rsm->typeMappings[$key])
                    : null;

                // Cache metadata fetch
                $this->getClassMetadata($this->_rsm->aliasMap[$dqlAlias]);

                return $this->_cache[$key] = [
                    'isIdentifier' => isset($this->_rsm->isIdentifierColumn[$dqlAlias][$key]),
                    'isMetaColumn' => true,
                    'fieldName'    => $fieldName,
                    'type'         => $type,
                    'dqlAlias'     => $dqlAlias,
                ];
        }

        // this column is a left over, maybe from a LIMIT query hack for example in Oracle or DB2
        // maybe from an additional column that has not been defined in a NativeQuery ResultSetMapping.
        return null;
    }

    /**
     * @return string[]
     */
    private function getDiscriminatorValues(ClassMetadata $classMetadata) : array
    {
        $values = array_map(
            function (string $subClass) : string {
                return (string) $this->getClassMetadata($subClass)->discriminatorValue;
            },
            $classMetadata->subClasses
        );

        $values[] = (string) $classMetadata->discriminatorValue;

        return $values;
    }

    /**
     * Retrieve ClassMetadata associated to entity class name.
     *
     * @param string $className
     *
     * @return \Doctrine\ORM\Mapping\ClassMetadata
     */
    protected function getClassMetadata($className)
    {
        if ( ! isset($this->_metadataCache[$className])) {
            $this->_metadataCache[$className] = $this->_em->getClassMetadata($className);
        }

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

    /**
     * Register entity as managed in UnitOfWork.
     *
     * @param ClassMetadata $class
     * @param object        $entity
     * @param array         $data
     *
     * @return void
     *
     * @todo The "$id" generation is the same of UnitOfWork#createEntity. Remove this duplication somehow
     */
    protected function registerManaged(ClassMetadata $class, $entity, array $data)
    {
        if ($class->isIdentifierComposite) {
            $id = [];

            foreach ($class->identifier as $fieldName) {
                $id[$fieldName] = isset($class->associationMappings[$fieldName])
                    ? $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']]
                    : $data[$fieldName];
            }
        } else {
            $fieldName = $class->identifier[0];
            $id        = [
                $fieldName => isset($class->associationMappings[$fieldName])
                    ? $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']]
                    : $data[$fieldName]
            ];
        }

        $this->_em->getUnitOfWork()->registerManaged($entity, $id, $data);
    }
}


text: RangefinderConfig rangefinder_config;

redpajama_set_name: RedPajamaGithub


text:
from django.db import models
from constants import APPLICATION_LABEL
from django.contrib.auth.models import User, Group
import django.dispatch

# Object holding user requests to join a group
class MembershipRequest(models.Model):

    user = models.ForeignKey(User)
    group = models.ForeignKey(Group)
    date = models.DateTimeField('Request Date', auto_now=True)

    class Meta:
        unique_together = (("user", "group"),)
        app_label = APPLICATION_LABEL


text:
class TokyoMetro::Factory::Convert::Customize::Api::TrainTimetable::ToeiMitaLine::Info < TokyoMetro::Factory::Convert::Common::Api::MetaClass::TrainInfos::ToeiMitaLine::Info

  def process
    convert_station_name
    convert_operator
    super
  end

  private

  def convert_operator
    object.instance_variable_set( :@operator , "odpt.Operator:Toei" )
  end

  def convert_station_name
    TokyoMetro::Factory::Convert::Customize::Api::TrainTimetable::ReplaceStationName::Info.process(
      object ,
      ::TokyoMetro::Factory::Convert::Dictionary::RegexpForReplace.namboku_and_toei_mita_line_common_stations ,
      "Toei.Mita"
    )
  end

end


text:
cask 'font-tienne' do
  # version '1.000'
  version :latest
  sha256 :no_check

  # github.com/google/fonts was verified as official when first introduced to the cask
  url 'https://github.com/google/fonts/trunk/ofl/tienne',
      using:      :svn,
      revision:   '50',
      trust_cert: true
  name 'Tienne'
  homepage 'http://www.google.com/fonts/specimen/Tienne'

  font 'Tienne-Bold.ttf'
  font 'Tienne-Heavy.ttf'
  font 'Tienne-Regular.ttf'
end


text:
> Array is collection of homogeneous elements.
> List is collection of heterogeneous elements.

> For Array memory allocated is static and continuous.
> For List memory allocated is dynamic and Random.

> In Arrays, User need not have to keep in track of next memory allocation.
> In List, User has to keep in Track of next location where memory is allocated.

> Array uses direct access of stored members.
> List uses sequencial access for members.

```
//With Array you have direct access to memory position 5
Object x = a[5];
```

```
//With the list you have to cross all previous nodes in order to get the 5th node:
list mylist;
list::iterator it;

for( it = list.begin() ; it != list.end() ; it++ )
{
if( i==5)
{
x = *it;
break;
}
i++;
}
```

#Will push the patches as soon as possible :)


text:
require 'test_helper'

describe ApiResponder::Formattable do
  let(:resource)  { Object.new }
  let(:cls)       { Class.new.tap { |c| c.send :include, ApiResponder::Formattable }}
  let(:decorator) { cls.new }

  describe "#api_formats" do
    it "should have active json as default" do
      assert_equal [ :json ], cls.api_formats
    end

    it "should return list of active formats" do
      cls.api_formats :xml
      assert_equal [ :json, :xml ], cls.api_formats
    end

    it "should have as_json method that delegates to as_api" do
      decorator.expects(:as_api).with({:format => :json}).returns(resource)
      resource.expects(:as_json).with({}).returns({})
      decorator.as_json({})
    end

    it "should create to_format method that delegates to as_api" do
      cls.api_formats :xml
      decorator.expects(:as_api).with({:format => :xml}).returns(resource)
      resource.expects(:to_xml).with({}).returns("")

      decorator.to_xml({})
    end
  end

  describe "#to_format" do
    it "should merge options" do
      cls.api_formats :xml
      decorator.expects(:as_api).with({:format => :xml, :include_root => true}).returns(resource)
      resource.expects(:to_xml).with({:include_root => true}).returns("")

      decorator.to_xml({:include_root => true})
    end
  end

  describe "#as_api" do
    it "should delegate to to_api_v{api_version}" do
      decorator.expects(:as_api_v2).with({:format => :json}).returns({})

      decorator.as_api({:format => :json, :api_version => 2})
    end

    it "should raise exception if no version is given" do
      assert_raises ApiResponder::Formattable::UnsupportedVersion do
        decorator.as_api({:format => :json})
      end
    end

    it "should raise exception if no version helper exists" do
      assert_raises ApiResponder::Formattable::UnsupportedVersion do
        decorator.as_api({:format => :json, :api_version => 4})
      end
    end
  end
end


text:
#ifndef TENSORFLOW_C_EXPERIMENTAL_SAVED_MODEL_CORE_SIGNATURE_DEF_FUNCTION_H_
#define TENSORFLOW_C_EXPERIMENTAL_SAVED_MODEL_CORE_SIGNATURE_DEF_FUNCTION_H_

#include <memory>
#include <vector>

#include "absl/types/span.h"
#include "tensorflow/c/eager/immediate_execution_operation.h"
#include "tensorflow/c/eager/immediate_execution_tensor_handle.h"
#include "tensorflow/c/experimental/saved_model/core/signature_def_function_metadata.h"

namespace tensorflow {

// See tensorflow/cc/experimental/saved_model/public/signature_def_function.h
// for SignatureDefFunction's intended user-facing semantics.
// This class is the "implementation" C++ part of the C++/C/C++ sandwich for
// a SignatureDefFunction.
// Note(bmzhao): Implementation-wise, SignatureDefFunctions are always saved as
// a "BareConcreteFunction", w/o a FunctionSpec, rather than a SavedFunction:
// https://github.com/tensorflow/tensorflow/blob/9bcefa44cd335c1db4a703a13da09f29ae1bbdb2/tensorflow/core/protobuf/saved_object_graph.proto#L60
// Additionally they are guaranteed to be children of the .signatures attribute
// of the root object, where the child object "name" is the signature_def key:
// https://github.com/tensorflow/tensorflow/blob/9bcefa44cd335c1db4a703a13da09f29ae1bbdb2/tensorflow/python/saved_model/signature_serialization.py#L181-L230
// One of the critical requirements of SignatureDef functions is that their
// inputs and outputs are "named". For example, a `.signatures` function:
// a. Requires users to pass: kwargs of all inputs:
// https://github.com/tensorflow/tensorflow/blob/26c4ee0c833e74f94d0102d8b005c41a28b44445/tensorflow/python/saved_model/signature_serialization.py#L119-L126
// b. Returns a dictionary of named outputs.
// https://github.com/tensorflow/tensorflow/blob/26c4ee0c833e74f94d0102d8b005c41a28b44445/tensorflow/python/saved_model/signature_serialization.py#L153-L161
// Since SignatureDefFunctions do not have FunctionSpecs, but guarantee the
// dictionary of inputs/outputs, we can parse these dictionaries' keys to obtain
// the input/output names of the SignatureDef:
// https://github.com/tensorflow/tensorflow/blob/9bcefa44cd335c1db4a703a13da09f29ae1bbdb2/tensorflow/core/protobuf/meta_graph.proto#L318-L321
class SignatureDefFunction {
 public:
  virtual ~SignatureDefFunction() = default;

  // Creates a "Call" Op used to execute the function.
  virtual Status MakeCallOp(absl::Span<AbstractTensorHandle* const> inputs,
                            ImmediateOpPtr* out) const = 0;

  virtual const SignatureDefFunctionMetadata& GetFunctionMetadata() const = 0;
};

}  // namespace tensorflow

#endif  // TENSORFLOW_C_EXPERIMENTAL_SAVED_MODEL_CORE_SIGNATURE_DEF_FUNCTION_H_


text:
namespace QueueAsDynamicLinkedList
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    public class Queue<T> : IEnumerable<T>
    {
        private readonly LinkedList<T> items = new LinkedList<T>();

        public void Enqueue(T element)
        {
            this.items.AddLast(element);
        }

        public void Dequeue()
        {
            this.items.RemoveFirst();
        }

        public IEnumerator<T> GetEnumerator()
        {
            var node = this.items.First;

            for (int i = 0; i < this.items.Count; i++)
            {

                if (!EqualityComparer<T>.Default.Equals(node.Value, default(T)))
                {
                    yield return node.Value;
                }

                var newNode = node.Next;
                node = newNode;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}


text:
namespace brotli {

struct HistogramPair {
  int idx1;
  int idx2;
  bool valid;
  double cost_combo;
  double cost_diff;
};

struct HistogramPairComparator {
  bool operator()(const HistogramPair& p1, const HistogramPair& p2) {
    if (p1.cost_diff != p2.cost_diff) {
      return p1.cost_diff > p2.cost_diff;
    }
    return abs(p1.idx1 - p1.idx2) > abs(p2.idx1 - p2.idx2);
  }
};

// Returns entropy reduction of the context map when we combine two clusters.
inline double ClusterCostDiff(int size_a, int size_b) {
  int size_c = size_a + size_b;
  return size_a * FastLog2(size_a) + size_b * FastLog2(size_b) -
      size_c * FastLog2(size_c);
}

// Computes the bit cost reduction by combining out[idx1] and out[idx2] and if
// it is below a threshold, stores the pair (idx1, idx2) in the *pairs heap.
template<int kSize>
void CompareAndPushToHeap(const Histogram<kSize>* out,
                          const int* cluster_size,
                          int idx1, int idx2,
                          std::vector<HistogramPair>* pairs) {
  if (idx1 == idx2) {
    return;
  }
  if (idx2 < idx1) {
    int t = idx2;
    idx2 = idx1;
    idx1 = t;
  }
  bool store_pair = false;
  HistogramPair p;
  p.idx1 = idx1;
  p.idx2 = idx2;
  p.valid = true;
  p.cost_diff = 0.5 * ClusterCostDiff(cluster_size[idx1], cluster_size[idx2]);
  p.cost_diff -= out[idx1].bit_cost_;
  p.cost_diff -= out[idx2].bit_cost_;

  if (out[idx1].total_count_ == 0) {
    p.cost_combo = out[idx2].bit_cost_;
    store_pair = true;
  } else if (out[idx2].total_count_ == 0) {
    p.cost_combo = out[idx1].bit_cost_;
    store_pair = true;
  } else {
    double threshold = pairs->empty() ? 1e99 :
        std::max(0.0, (*pairs)[0].cost_diff);
    Histogram<kSize> combo = out[idx1];
    combo.AddHistogram(out[idx2]);
    double cost_combo = PopulationCost(combo);
    if (cost_combo < threshold - p.cost_diff) {
      p.cost_combo = cost_combo;
      store_pair = true;
    }
  }
  if (store_pair) {
    p.cost_diff += p.cost_combo;
    pairs->push_back(p);
    push_heap(pairs->begin(), pairs->end(), HistogramPairComparator());
  }
}

template<int kSize>
void HistogramCombine(Histogram<kSize>* out,
                      int* cluster_size,
                      int* symbols,
                      int symbols_size,
                      int max_clusters) {
  double cost_diff_threshold = 0.0;
  int min_cluster_size = 1;
  std::set<int> all_symbols;
  std::vector<int> clusters;
  for (int i = 0; i < symbols_size; ++i) {
    if (all_symbols.find(symbols[i]) == all_symbols.end()) {
      all_symbols.insert(symbols[i]);
      clusters.push_back(symbols[i]);
    }
  }

  // We maintain a heap of histogram pairs, ordered by the bit cost reduction.
  std::vector<HistogramPair> pairs;
  for (int idx1 = 0; idx1 < clusters.size(); ++idx1) {
    for (int idx2 = idx1 + 1; idx2 < clusters.size(); ++idx2) {
      CompareAndPushToHeap(out, cluster_size, clusters[idx1], clusters[idx2],
                           &pairs);
    }
  }

  while (clusters.size() > min_cluster_size) {
    if (pairs[0].cost_diff >= cost_diff_threshold) {
      cost_diff_threshold = 1e99;
      min_cluster_size = max_clusters;
      continue;
    }
    // Take the best pair from the top of heap.
    int best_idx1 = pairs[0].idx1;
    int best_idx2 = pairs[0].idx2;
    out[best_idx1].AddHistogram(out[best_idx2]);
    out[best_idx1].bit_cost_ = pairs[0].cost_combo;
    cluster_size[best_idx1] += cluster_size[best_idx2];
    for (int i = 0; i < symbols_size; ++i) {
      if (symbols[i] == best_idx2) {
        symbols[i] = best_idx1;
      }
    }
    for (int i = 0; i + 1 < clusters.size(); ++i) {
      if (clusters[i] >= best_idx2) {
        clusters[i] = clusters[i + 1];
      }
    }
    clusters.pop_back();
    // Invalidate pairs intersecting the just combined best pair.
    for (int i = 0; i < pairs.size(); ++i) {
      HistogramPair& p = pairs[i];
      if (p.idx1 == best_idx1 || p.idx2 == best_idx1 ||
          p.idx1 == best_idx2 || p.idx2 == best_idx2) {
        p.valid = false;
      }
    }
    // Pop invalid pairs from the top of the heap.
    while (!pairs.empty() && !pairs[0].valid) {
      pop_heap(pairs.begin(), pairs.end(), HistogramPairComparator());
      pairs.pop_back();
    }
    // Push new pairs formed with the combined histogram to the heap.
    for (int i = 0; i < clusters.size(); ++i) {
      CompareAndPushToHeap(out, cluster_size, best_idx1, clusters[i], &pairs);
    }
  }
}

// -----------------------------------------------------------------------------
// Histogram refinement

// What is the bit cost of moving histogram from cur_symbol to candidate.
template<int kSize>
double HistogramBitCostDistance(const Histogram<kSize>& histogram,
                                const Histogram<kSize>& candidate) {
  if (histogram.total_count_ == 0) {
    return 0.0;
  }
  Histogram<kSize> tmp = histogram;
  tmp.AddHistogram(candidate);
  return PopulationCost(tmp) - candidate.bit_cost_;
}

// Find the best 'out' histogram for each of the 'in' histograms.
// Note: we assume that out[]->bit_cost_ is already up-to-date.
template<int kSize>
void HistogramRemap(const Histogram<kSize>* in, int in_size,
                    Histogram<kSize>* out, int* symbols) {
  std::set<int> all_symbols;
  for (int i = 0; i < in_size; ++i) {
    all_symbols.insert(symbols[i]);
  }
  for (int i = 0; i < in_size; ++i) {
    int best_out = i == 0 ? symbols[0] : symbols[i - 1];
    double best_bits = HistogramBitCostDistance(in[i], out[best_out]);
    for (std::set<int>::const_iterator k = all_symbols.begin();
         k != all_symbols.end(); ++k) {
      const double cur_bits = HistogramBitCostDistance(in[i], out[*k]);
      if (cur_bits < best_bits) {
        best_bits = cur_bits;
        best_out = *k;
      }
    }
    symbols[i] = best_out;
  }

  // Recompute each out based on raw and symbols.
  for (std::set<int>::const_iterator k = all_symbols.begin();
       k != all_symbols.end(); ++k) {
    out[*k].Clear();
  }
  for (int i = 0; i < in_size; ++i) {
    out[symbols[i]].AddHistogram(in[i]);
  }
}

// Reorder histograms in *out so that the new symbols in *symbols come in
// increasing order.
template<int kSize>
void HistogramReindex(std::vector<Histogram<kSize> >* out,
                      std::vector<int>* symbols) {
  std::vector<Histogram<kSize> > tmp(*out);
  std::map<int, int> new_index;
  int next_index = 0;
  for (int i = 0; i < symbols->size(); ++i) {
    if (new_index.find((*symbols)[i]) == new_index.end()) {
      new_index[(*symbols)[i]] = next_index;
      (*out)[next_index] = tmp[(*symbols)[i]];
      ++next_index;
    }
  }
  out->resize(next_index);
  for (int i = 0; i < symbols->size(); ++i) {
    (*symbols)[i] = new_index[(*symbols)[i]];
  }
}

// Clusters similar histograms in 'in' together, the selected histograms are
// placed in 'out', and for each index in 'in', *histogram_symbols will
// indicate which of the 'out' histograms is the best approximation.
template<int kSize>
void ClusterHistograms(const std::vector<Histogram<kSize> >& in,
                       int num_contexts, int num_blocks,
                       int max_histograms,
                       std::vector<Histogram<kSize> >* out,
                       std::vector<int>* histogram_symbols) {
  const int in_size = num_contexts * num_blocks;
  std::vector<int> cluster_size(in_size, 1);
  out->resize(in_size);
  histogram_symbols->resize(in_size);
  for (int i = 0; i < in_size; ++i) {
    (*out)[i] = in[i];
    (*out)[i].bit_cost_ = PopulationCost(in[i]);
    (*histogram_symbols)[i] = i;
  }

  // Collapse similar histograms within a block type.
  if (num_contexts > 1) {
    for (int i = 0; i < num_blocks; ++i) {
      HistogramCombine(&(*out)[0], &cluster_size[0],
                       &(*histogram_symbols)[i * num_contexts], num_contexts,
                       max_histograms);
    }
  }

  // Collapse similar histograms.
  HistogramCombine(&(*out)[0], &cluster_size[0],
                   &(*histogram_symbols)[0], in_size,
                   max_histograms);

  // Find the optimal map from original histograms to the final ones.
  HistogramRemap(&in[0], in_size, &(*out)[0], &(*histogram_symbols)[0]);

  // Convert the context map to a canonical form.
  HistogramReindex(out, histogram_symbols);
}

}  // namespace brotli

#endif  // BROTLI_ENC_CLUSTER_H_


text:
package com.google.gerrit.acceptance.api.group;

import static com.google.common.truth.Truth8.assertThat;

import com.google.common.collect.ImmutableSet;
import com.google.gerrit.common.data.GroupReference;
import com.google.gerrit.common.errors.NoSuchGroupException;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.server.ServerInitiated;
import com.google.gerrit.server.group.db.Groups;
import com.google.gerrit.server.group.db.GroupsUpdate;
import com.google.gerrit.server.group.db.InternalGroupCreation;
import com.google.gerrit.server.group.db.InternalGroupUpdate;
import com.google.gerrit.testing.InMemoryTestEnvironment;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.io.IOException;
import java.util.Set;
import java.util.stream.Stream;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class GroupsUpdateIT {
  @Rule public InMemoryTestEnvironment testEnvironment = new InMemoryTestEnvironment();
  @Rule public ExpectedException expectedException = ExpectedException.none();

  @Inject @ServerInitiated private Provider<GroupsUpdate> groupsUpdateProvider;
  @Inject private Groups groups;

  @Test
  public void groupCreationIsRetriedWhenFailedDueToConcurrentNameModification() throws Exception {
    InternalGroupCreation groupCreation = getGroupCreation("users", "users-UUID");
    InternalGroupUpdate groupUpdate =
        InternalGroupUpdate.builder()
            .setMemberModification(
                new CreateAnotherGroupOnceAsSideEffectOfMemberModification("verifiers"))
            .build();
    createGroup(groupCreation, groupUpdate);

    Stream<String> allGroupNames = getAllGroupNames();
    assertThat(allGroupNames).containsAllOf("users", "verifiers");
  }

  @Test
  public void groupRenameIsRetriedWhenFailedDueToConcurrentNameModification() throws Exception {
    createGroup("users", "users-UUID");

    InternalGroupUpdate groupUpdate =
        InternalGroupUpdate.builder()
            .setName(new AccountGroup.NameKey("contributors"))
            .setMemberModification(
                new CreateAnotherGroupOnceAsSideEffectOfMemberModification("verifiers"))
            .build();
    updateGroup(new AccountGroup.UUID("users-UUID"), groupUpdate);

    Stream<String> allGroupNames = getAllGroupNames();
    assertThat(allGroupNames).containsAllOf("contributors", "verifiers");
  }

  @Test
  public void groupUpdateFailsWithExceptionForNotExistingGroup() throws Exception {
    InternalGroupUpdate groupUpdate =
        InternalGroupUpdate.builder().setDescription("A description for the group").build();

    expectedException.expect(NoSuchGroupException.class);
    updateGroup(new AccountGroup.UUID("nonexistent-group-UUID"), groupUpdate);
  }

  private void createGroup(String groupName, String groupUuid) throws Exception {
    InternalGroupCreation groupCreation = getGroupCreation(groupName, groupUuid);
    InternalGroupUpdate groupUpdate = InternalGroupUpdate.builder().build();

    createGroup(groupCreation, groupUpdate);
  }

  private void createGroup(InternalGroupCreation groupCreation, InternalGroupUpdate groupUpdate)
      throws OrmException, IOException, ConfigInvalidException {
    groupsUpdateProvider.get().createGroup(groupCreation, groupUpdate);
  }

  private void updateGroup(AccountGroup.UUID groupUuid, InternalGroupUpdate groupUpdate)
      throws Exception {
    groupsUpdateProvider.get().updateGroup(groupUuid, groupUpdate);
  }

  private Stream<String> getAllGroupNames() throws IOException, ConfigInvalidException {
    return groups.getAllGroupReferences().map(GroupReference::getName);
  }

  private static InternalGroupCreation getGroupCreation(String groupName, String groupUuid) {
    return InternalGroupCreation.builder()
        .setGroupUUID(new AccountGroup.UUID(groupUuid))
        .setNameKey(new AccountGroup.NameKey(groupName))
        .setId(new AccountGroup.Id(Math.abs(groupName.hashCode())))
        .build();
  }

  private class CreateAnotherGroupOnceAsSideEffectOfMemberModification
      implements InternalGroupUpdate.MemberModification {

    private boolean groupCreated = false;
    private String groupName;

    public CreateAnotherGroupOnceAsSideEffectOfMemberModification(String groupName) {
      this.groupName = groupName;
    }

    @Override
    public Set<Account.Id> apply(ImmutableSet<Account.Id> members) {
      if (!groupCreated) {
        createGroup();
        groupCreated = true;
      }

      return members;
    }

    private void createGroup() {
      InternalGroupCreation groupCreation = getGroupCreation(groupName, groupName + "-UUID");
      InternalGroupUpdate groupUpdate = InternalGroupUpdate.builder().build();
      try {
        groupsUpdateProvider.get().createGroup(groupCreation, groupUpdate);
      } catch (OrmException | IOException | ConfigInvalidException e) {
        throw new IllegalStateException(e);
      }
    }
  }
}


text:
**I no longer maintain this project. Since it is a demonstration, you can still fork and play with it**

## Installation

```
npm install --global babel
npm install
```

## Running

Start a local server:

```
npm start
```

## Developing

Any changes you make to files in the `js/` directory will cause the server to
automatically rebuild the app and refresh your browser.

If at any time you make changes to `data/schema.js`, stop the server,
regenerate `data/schema.json`, and restart the server:

```
npm run update-schema
npm start
```

## Feature Highlight:

1. use with [relay-nested-routes](https://github.com/devknoll/relay-nested-routes) and [react-router](https://github.com/rackt/react-router) to let multiple routes work and route params as query params

2. using route params as global state variable (ex: currentThreadID), not ideal for now, but it shows a different possibility

3. and a more complicated model structure as `user-> threads-> messages`
4. [pagination for messages](https://github.com/transedward/relay-chat/tree/add-pagination)

## Advice

If you don't know much about GraphQL and Relay, I suggest you:

1. [To know GraphQL first](https://github.com/facebook/graphql/blob/master/README.md)
(at least things before introspection part)
2. [Know how Relay connect to GraphQL](http://facebook.github.io/relay/docs/graphql-relay-specification.html#content)
(and the series below)
3. [Last, learn Relay](http://facebook.github.io/relay/docs/guides-containers.html#content)
(and the series below)

I tried these 3 steps in reverse, and I went step by step again.


text:
class Admin::TagsController < Admin::BaseController
  def index
    @tags = ActsAsTaggableOn::Tag.all.sort_by {|tag| tag.name.downcase}
  end

  def edit
    @tag = ActsAsTaggableOn::Tag.find(params[:id])
  end

  def update
    @tag = ActsAsTaggableOn::Tag.find(params[:id])
    if @tag.update_attributes(params[:tag])
      redirect_to admin_tags_path, notice: (I18n.t("flash.tags.updated"))
    else
      render action: "edit"
    end
  end

  def destroy
    @tag = ActsAsTaggableOn::Tag.find(params[:id])
    @tag.destroy
    redirect_to admin_tags_path, notice: (I18n.t("flash.tags.destroyed"))
  end
end


text:
requirejs.config({
    baseUrl: 'js/vendor',
    paths: {
		jquery: 'jquery/jquery-2.1.1.min',
        client: '../client'
    }
});

// Start loading the main app file. Put all of
// your application logic in there.
requirejs(['client/main']);


text:
#include "aztec/AZEncoder.h"
#include "aztec/AZHighLevelEncoder.h"
#include "BitArray.h"
#include "ReedSolomonEncoder.h"
#include "GenericGF.h"
#include "ZXStrConvWorkaround.h"
#include "ZXTestSupport.h"

#include <cstdlib>

namespace ZXing {
namespace Aztec {

static const int MAX_NB_BITS = 32;
static const int MAX_NB_BITS_COMPACT = 4;

static const int WORD_SIZE[] = {
	4, 6, 6, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
	12, 12, 12, 12, 12, 12, 12, 12, 12, 12
};

static void DrawBullsEye(BitMatrix& matrix, int center, int size)
{
	for (int i = 0; i < size; i += 2) {
		for (int j = center - i; j <= center + i; j++) {
			matrix.set(j, center - i);
			matrix.set(j, center + i);
			matrix.set(center - i, j);
			matrix.set(center + i, j);
		}
	}
	matrix.set(center - size, center - size);
	matrix.set(center - size + 1, center - size);
	matrix.set(center - size, center - size + 1);
	matrix.set(center + size, center - size);
	matrix.set(center + size, center - size + 1);
	matrix.set(center + size, center + size - 1);
}

static const GenericGF& GetGFFromWordSize(int wordSize)
{
	switch (wordSize) {
	case 4:
		return GenericGF::AztecParam();
	case 6:
		return GenericGF::AztecData6();
	case 8:
		return GenericGF::AztecData8();
	case 10:
		return GenericGF::AztecData10();
	case 12:
		return GenericGF::AztecData12();
	default:
		throw std::invalid_argument("Unsupported word size " + std::to_string(wordSize));
	}
}

static std::vector<int> BitsToWords(const BitArray& stuffedBits, int wordSize, int totalWords)
{
	std::vector<int> message(totalWords, 0);
	int i;
	int n;
	for (i = 0, n = stuffedBits.size() / wordSize; i < n; i++) {
		int value = 0;
		for (int j = 0; j < wordSize; j++) {
			value |= stuffedBits.get(i * wordSize + j) ? (1 << (wordSize - j - 1)) : 0;
		}
		message[i] = value;
	}
	return message;
}

static void GenerateCheckWords(const BitArray& bitArray, int totalBits, int wordSize, BitArray& messageBits)
{
	// bitArray is guaranteed to be a multiple of the wordSize, so no padding needed
	int messageSizeInWords = bitArray.size() / wordSize;
	ReedSolomonEncoder rs(GetGFFromWordSize(wordSize));
	int totalWords = totalBits / wordSize;
	std::vector<int> messageWords = BitsToWords(bitArray, wordSize, totalWords);
	rs.encode(messageWords, totalWords - messageSizeInWords);
	int startPad = totalBits % wordSize;
	messageBits = BitArray();
	messageBits.appendBits(0, startPad);
	for (int messageWord : messageWords) {
		messageBits.appendBits(messageWord, wordSize);
	}
}

ZXING_EXPORT_TEST_ONLY
void GenerateModeMessage(bool compact, int layers, int messageSizeInWords, BitArray& modeMessage)
{
	modeMessage = BitArray();
	if (compact) {
		modeMessage.appendBits(layers - 1, 2);
		modeMessage.appendBits(messageSizeInWords - 1, 6);
		GenerateCheckWords(modeMessage, 28, 4, modeMessage);
	}
	else {
		modeMessage.appendBits(layers - 1, 5);
		modeMessage.appendBits(messageSizeInWords - 1, 11);
		GenerateCheckWords(modeMessage, 40, 4, modeMessage);
	}
}

static void DrawModeMessage(BitMatrix& matrix, bool compact, int matrixSize, const BitArray& modeMessage)
{
	int center = matrixSize / 2;
	if (compact) {
		for (int i = 0; i < 7; i++) {
			int offset = center - 3 + i;
			if (modeMessage.get(i)) {
				matrix.set(offset, center - 5);
			}
			if (modeMessage.get(i + 7)) {
				matrix.set(center + 5, offset);
			}
			if (modeMessage.get(20 - i)) {
				matrix.set(offset, center + 5);
			}
			if (modeMessage.get(27 - i)) {
				matrix.set(center - 5, offset);
			}
		}
	}
	else {
		for (int i = 0; i < 10; i++) {
			int offset = center - 5 + i + i / 5;
			if (modeMessage.get(i)) {
				matrix.set(offset, center - 7);
			}
			if (modeMessage.get(i + 10)) {
				matrix.set(center + 7, offset);
			}
			if (modeMessage.get(29 - i)) {
				matrix.set(offset, center + 7);
			}
			if (modeMessage.get(39 - i)) {
				matrix.set(center - 7, offset);
			}
		}
	}
}

ZXING_EXPORT_TEST_ONLY
void StuffBits(const BitArray& bits, int wordSize, BitArray& out)
{
	out = BitArray();
	int n = bits.size();
	int mask = (1 << wordSize) - 2;
	for (int i = 0; i < n; i += wordSize) {
		int word = 0;
		for (int j = 0; j < wordSize; j++) {
			if (i + j >= n || bits.get(i + j)) {
				word |= 1 << (wordSize - 1 - j);
			}
		}
		if ((word & mask) == mask) {
			out.appendBits(word & mask, wordSize);
			i--;
		}
		else if ((word & mask) == 0) {
			out.appendBits(word | 1, wordSize);
			i--;
		}
		else {
			out.appendBits(word, wordSize);
		}
	}
}

static int TotalBitsInLayer(int layers, bool compact)
{
	return ((compact ? 88 : 112) + 16 * layers) * layers;
}

/**
* Encodes the given binary content as an Aztec symbol
*
* @param data input data string
* @param minECCPercent minimal percentage of error check words (According to ISO/IEC 24778:2008,
*                      a minimum of 23% + 3 words is recommended)
* @param userSpecifiedLayers if non-zero, a user-specified value for the number of layers
* @return Aztec symbol matrix with metadata
*/
EncodeResult
Encoder::Encode(const std::string& data, int minECCPercent, int userSpecifiedLayers)
{
	// High-level encode
	BitArray bits = HighLevelEncoder::Encode(data);

	// stuff bits and choose symbol size
	int eccBits = bits.size() * minECCPercent / 100 + 11;
	int totalSizeBits = bits.size() + eccBits;
	bool compact;
	int layers;
	int totalBitsInLayer;
	int wordSize;
	BitArray stuffedBits;
	if (userSpecifiedLayers != DEFAULT_AZTEC_LAYERS) {
		compact = userSpecifiedLayers < 0;
		layers = std::abs(userSpecifiedLayers);
		if (layers > (compact ? MAX_NB_BITS_COMPACT : MAX_NB_BITS)) {
			throw std::invalid_argument("Illegal value for layers: " + std::to_string(userSpecifiedLayers));
		}
		totalBitsInLayer = TotalBitsInLayer(layers, compact);
		wordSize = WORD_SIZE[layers];
		int usableBitsInLayers = totalBitsInLayer - (totalBitsInLayer % wordSize);
		StuffBits(bits, wordSize, stuffedBits);
		if (stuffedBits.size() + eccBits > usableBitsInLayers) {
			throw std::invalid_argument("Data to large for user specified layer");
		}
		if (compact && stuffedBits.size() > wordSize * 64) {
			// Compact format only allows 64 data words, though C4 can hold more words than that
			throw std::invalid_argument("Data to large for user specified layer");
		}
	}
	else {
		wordSize = 0;
		// We look at the possible table sizes in the order Compact1, Compact2, Compact3,
		// Compact4, Normal4,...  Normal(i) for i < 4 isn't typically used since Compact(i+1)
		// is the same size, but has more data.
		for (int i = 0; ; i++) {
			if (i > MAX_NB_BITS) {
				throw std::invalid_argument("Data too large for an Aztec code");
			}
			compact = i <= 3;
			layers = compact ? i + 1 : i;
			totalBitsInLayer = TotalBitsInLayer(layers, compact);
			if (totalSizeBits > totalBitsInLayer) {
				continue;
			}
			// [Re]stuff the bits if this is the first opportunity, or if the
			// wordSize has changed
			if (wordSize != WORD_SIZE[layers]) {
				wordSize = WORD_SIZE[layers];
				StuffBits(bits, wordSize, stuffedBits);
			}
			int usableBitsInLayers = totalBitsInLayer - (totalBitsInLayer % wordSize);
			if (compact && stuffedBits.size() > wordSize * 64) {
				// Compact format only allows 64 data words, though C4 can hold more words than that
				continue;
			}
			if (stuffedBits.size() + eccBits <= usableBitsInLayers) {
				break;
			}
		}
	}
	BitArray messageBits;
	GenerateCheckWords(stuffedBits, totalBitsInLayer, wordSize, messageBits);

	// generate mode message
	int messageSizeInWords = stuffedBits.size() / wordSize;
	BitArray modeMessage;
	GenerateModeMessage(compact, layers, messageSizeInWords, modeMessage);

	// allocate symbol
	int baseMatrixSize = (compact ? 11 : 14) + layers * 4; // not including alignment lines
	std::vector<int> alignmentMap(baseMatrixSize, 0);
	int matrixSize;
	if (compact) {
		// no alignment marks in compact mode, alignmentMap is a no-op
		matrixSize = baseMatrixSize;
		for (int i = 0; i < (int)alignmentMap.size(); i++) {
			alignmentMap[i] = i;
		}
	}
	else {
		matrixSize = baseMatrixSize + 1 + 2 * ((baseMatrixSize / 2 - 1) / 15);
		int origCenter = baseMatrixSize / 2;
		int center = matrixSize / 2;
		for (int i = 0; i < origCenter; i++) {
			int newOffset = i + i / 15;
			alignmentMap[origCenter - i - 1] = center - newOffset - 1;
			alignmentMap[origCenter + i] = center + newOffset + 1;
		}
	}

	EncodeResult output{compact, matrixSize, layers, messageSizeInWords, BitMatrix(matrixSize)};

	BitMatrix& matrix = output.matrix;

	// draw data bits
	for (int i = 0, rowOffset = 0; i < layers; i++) {
		int rowSize = (layers - i) * 4 + (compact ? 9 : 12);
		for (int j = 0; j < rowSize; j++) {
			int columnOffset = j * 2;
			for (int k = 0; k < 2; k++) {
				if (messageBits.get(rowOffset + columnOffset + k)) {
					matrix.set(alignmentMap[i * 2 + k], alignmentMap[i * 2 + j]);
				}
				if (messageBits.get(rowOffset + rowSize * 2 + columnOffset + k)) {
					matrix.set(alignmentMap[i * 2 + j], alignmentMap[baseMatrixSize - 1 - i * 2 - k]);
				}
				if (messageBits.get(rowOffset + rowSize * 4 + columnOffset + k)) {
					matrix.set(alignmentMap[baseMatrixSize - 1 - i * 2 - k], alignmentMap[baseMatrixSize - 1 - i * 2 - j]);
				}
				if (messageBits.get(rowOffset + rowSize * 6 + columnOffset + k)) {
					matrix.set(alignmentMap[baseMatrixSize - 1 - i * 2 - j], alignmentMap[i * 2 + k]);
				}
			}
		}
		rowOffset += rowSize * 8;
	}

	// draw mode message
	DrawModeMessage(matrix, compact, matrixSize, modeMessage);

	// draw alignment marks
	if (compact) {
		DrawBullsEye(matrix, matrixSize / 2, 5);
	}
	else {
		DrawBullsEye(matrix, matrixSize / 2, 7);
		for (int i = 0, j = 0; i < baseMatrixSize / 2 - 1; i += 15, j += 16) {
			for (int k = (matrixSize / 2) & 1; k < matrixSize; k += 2) {
				matrix.set(matrixSize / 2 - j, k);
				matrix.set(matrixSize / 2 + j, k);
				matrix.set(k, matrixSize / 2 - j);
				matrix.set(k, matrixSize / 2 + j);
			}
		}
	}
	return output;
}

} // Aztec
} // ZXing


text:
{%extends 'base.html' %}
{% load staticfiles %}
{% load crispy_forms_tags %}

{% block head_title %}Pool - {% endblock %}

{% block style %}

{% endblock %}
{% block Calendar_Support %}
{#        #}
{#        <link href="{% static 'css/bootstrap.css'%}" rel="stylesheet">#}
{#        #}

    {{ form.media }}
{% endblock %}
 {%  block content %}

					<span id="refresh" class="btn btn-ribbon" data-action="resetWidgets" data-title="refresh"  rel="tooltip" data-placement="bottom" data-original-title=" Warning! This will reset all your widget settings." data-html="true">

Home

Pools

Add/Edit Pools

                Configuration
							>
								Add/Edit Configuration

             Help

Add/Edit Configuration

                            <input class="form-control" type="text">

                                    <form method="POST" action=""> {% csrf_token %}
                                        {{ form | crispy }}
                                        <input type="submit" name="_submit" value="Save" class="btn btn-primary btn-primary">
                                        <input type="submit" name="_stay" value="Continue" class="btn ">
                                        <input type="submit" name="_cancel" value="Cancel" class="btn" >

                                    </form>

 {% endblock %}


text:
===========
dj-paas-env
===========

.. image:: https://travis-ci.org/pbacterio/dj-paas-env.png?branch=master
   :target: https://travis-ci.org/pbacterio/dj-paas-env

Helper methods to configure Django database and static files in a PAAS environment.
The platforms currently supported are: Heroko, OpenShift, dotCloud and Gondor

--------
Database
--------

Basic example
=============

In ``settings.py``::

    DATABASES = {
        'default': dj_paas_env.database.config()
    }

This example tries to figure out the database configuration from the following environment variables:
``DATABASE_URL``, ``HEROKU_POSTGRESQL_<color>_URL``, ``CLEARDB_DATABASE_URL``, ``OPENSHIFT_POSTGRESQL_DB_URL``,
``OPENSHIFT_MYSQL_DB_URL``, ``GONDOR_DATABASE_URL`` and dotcloud environment file.

Local database
==============

For develop/testing in local environments, it's recomend to use a default configuration. With this option the
application works in local and remote (PAAS) environments::

    DATABASES = {
        'default': dj_paas_env.database.config(default='mysql://user@pass:localhost/testdb')
    }

Develop with SQLite
===================

::

    DATABASES = {
        'default': dj_paas_env.database.sqlite_dev()
    }

-----------------------
PAAS provider detection
-----------------------

The method ``dj_paas_env.provider.detect()`` returns the provider name (heroku, openshift, dotcloud, gondor) where the
application is running::

    >>> import dj_paas_env
    >>> dj_paas_env.provider.detect()
    'openshift'


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

{% block title %}Error - {{ block.super }}{% endblock %}

{% block content %}

Error. :(

        The page  could not be found on this server.

{% include 'includes/newsletter.html' %}
{% endblock %}

{% block scripts %}
{{ block.super }}

{% include 'includes/newsletter-analytics.html' %}
{% endblock scripts %}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Transactions ;

using NUnit.Framework ;

using NW = alby.northwind.codegen  ;

namespace alby.northwind.codegen.test.query
{
	[TestFixture]
	public class TestTestQuery01 : NW.test.TransactionScopeTestBase
	{
		public TestTestQuery01()
		{
			_connectionString = Settings.ConnectionString();
		}

		[Test]
		public void TestLoadByTheKey()
		{
			Console.WriteLine("LoadByTheKey");

			NW.query.TestQuery01Factory factory = new NW.query.TestQuery01Factory();

			int theKey = 1 ;
			List<NW.query.TestQuery01> rowset = factory.LoadByTheKey( _connection, theKey ) ;

			Console.WriteLine(rowset.Count);
			Assert.Greater(rowset.Count, 0); // should get some rows back

			// test fields of first row
			NW.query.TestQuery01 tq = rowset[0];

			Assert.AreEqual(tq.The_Key, theKey);
			Assert.AreEqual(tq.The_Value, "test value 1");
		}

	}
}


text:
require 'rails_helper'

describe 'Dropdown emoji', :js do
  include FilteredSearchHelpers

  let!(:project) { create(:project, :public) }
  let!(:user) { create(:user, name: 'administrator', username: 'root') }
  let!(:issue) { create(:issue, project: project) }
  let!(:award_emoji_star) { create(:award_emoji, name: 'star', user: user, awardable: issue) }
  let(:filtered_search) { find('.filtered-search') }
  let(:js_dropdown_emoji) { '#js-dropdown-my-reaction' }

  def send_keys_to_filtered_search(input)
    input.split("").each do |i|
      filtered_search.send_keys(i)
    end

    sleep 0.5
    wait_for_requests
  end

  def dropdown_emoji_size
    page.all('#js-dropdown-my-reaction .filter-dropdown .filter-dropdown-item').size
  end

  def click_emoji(text)
    find('#js-dropdown-my-reaction .filter-dropdown .filter-dropdown-item', text: text).click
  end

  before do
    project.add_maintainer(user)
    create_list(:award_emoji, 2, user: user, name: 'thumbsup')
    create_list(:award_emoji, 1, user: user, name: 'thumbsdown')
    create_list(:award_emoji, 3, user: user, name: 'star')
    create_list(:award_emoji, 1, user: user, name: 'tea')
  end

  context 'when user not logged in' do
    before do
      visit project_issues_path(project)
    end

    describe 'behavior' do
      it 'does not open when the search bar has my-reaction:' do
        filtered_search.set('my-reaction:')

        expect(page).not_to have_css(js_dropdown_emoji)
      end
    end
  end

  context 'when user loggged in' do
    before do
      sign_in(user)

      visit project_issues_path(project)
    end

    describe 'behavior' do
      it 'opens when the search bar has my-reaction:' do
        filtered_search.set('my-reaction:')

        expect(page).to have_css(js_dropdown_emoji, visible: true)
      end

      it 'closes when the search bar is unfocused' do
        find('body').click()

        expect(page).to have_css(js_dropdown_emoji, visible: false)
      end

      it 'should show loading indicator when opened' do
        slow_requests do
          filtered_search.set('my-reaction:')

          expect(page).to have_css('#js-dropdown-my-reaction .filter-dropdown-loading', visible: true)
        end
      end

      it 'should hide loading indicator when loaded' do
        send_keys_to_filtered_search('my-reaction:')

        expect(page).not_to have_css('#js-dropdown-my-reaction .filter-dropdown-loading')
      end

      it 'should load all the emojis when opened' do
        send_keys_to_filtered_search('my-reaction:')

        expect(dropdown_emoji_size).to eq(4)
      end

      it 'shows the most populated emoji at top of dropdown' do
        send_keys_to_filtered_search('my-reaction:')

        expect(first('#js-dropdown-my-reaction li')).to have_content(award_emoji_star.name)
      end
    end

    describe 'filtering' do
      before do
        filtered_search.set('my-reaction')
        send_keys_to_filtered_search(':')
      end

      it 'filters by name' do
        send_keys_to_filtered_search('up')

        expect(dropdown_emoji_size).to eq(1)
      end

      it 'filters by case insensitive name' do
        send_keys_to_filtered_search('Up')

        expect(dropdown_emoji_size).to eq(1)
      end
    end

    describe 'selecting from dropdown' do
      before do
        filtered_search.set('my-reaction')
        send_keys_to_filtered_search(':')
      end

      it 'fills in the my-reaction name' do
        click_emoji('thumbsup')

        wait_for_requests

        expect(page).to have_css(js_dropdown_emoji, visible: false)
        expect_tokens([emoji_token('thumbsup')])
        expect_filtered_search_input_empty
      end
    end

    describe 'input has existing content' do
      it 'opens my-reaction dropdown with existing search term' do
        filtered_search.set('searchTerm my-reaction:')

        expect(page).to have_css(js_dropdown_emoji, visible: true)
      end

      it 'opens my-reaction dropdown with existing assignee' do
        filtered_search.set('assignee:@user my-reaction:')

        expect(page).to have_css(js_dropdown_emoji, visible: true)
      end

      it 'opens my-reaction dropdown with existing label' do
        filtered_search.set('label:~bug my-reaction:')

        expect(page).to have_css(js_dropdown_emoji, visible: true)
      end

      it 'opens my-reaction dropdown with existing milestone' do
        filtered_search.set('milestone:%v1.0 my-reaction:')

        expect(page).to have_css(js_dropdown_emoji, visible: true)
      end

      it 'opens my-reaction dropdown with existing my-reaction' do
        filtered_search.set('my-reaction:star my-reaction:')

        expect(page).to have_css(js_dropdown_emoji, visible: true)
      end
    end

    describe 'caching requests' do
      it 'caches requests after the first load' do
        filtered_search.set('my-reaction')
        send_keys_to_filtered_search(':')
        initial_size = dropdown_emoji_size

        expect(initial_size).to be > 0

        create_list(:award_emoji, 1, user: user, name: 'smile')
        find('.filtered-search-box .clear-search').click
        filtered_search.set('my-reaction')
        send_keys_to_filtered_search(':')

        expect(dropdown_emoji_size).to eq(initial_size)
      end
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.slf4j.dummyExt (SLF4J 1.7.21 Test API)
</TITLE>

<META NAME="date" CONTENT="2016-04-04">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package org.slf4j.dummyExt

Tests related to the org.slf4j.ext package.

See:

          Description

Class Summary

EventLoggerTest

ListAppender

MDCStrLookupTest

PackageTest

XLoggerTest

Package org.slf4j.dummyExt Description

Tests related to the org.slf4j.ext package. However, location information code
required the caller class (XLogger) to have a different prefix than
the test class XLoggerTest. This is ensured by having the test class
placed in a different package.

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2005–2016 QOS.ch. All rights reserved.


text:
using UnityEngine;
using CreateThis.VR.UI.Interact;

namespace MeshEngine.Controller {
    public class AlignmentToolController : Triggerable {
        public Mesh mesh;
        public string type;

        public override void OnTriggerDown(Transform controller, int controllerIndex) {
            base.OnTriggerDown(controller, controllerIndex);
            if (Mode.mode == ModeType.AlignmentDelete) Delete();
        }

        public void Delete() {
            mesh.alignmentTools.alignmentTools.Remove(gameObject);
            Destroy(gameObject);
        }

        // Use this for initialization
        void Start() {

        }
    }
}


text:
from numpy import array, allclose, zeros, newaxis, isnan, nonzero
from minL2PenalizedLossOverSimplex import weightsForMultipleLosses2TimedStreams
import utility
import pdb

def lloydsInitialStates(data, model, k=0, modelParameters=None):
    #print('Generating initial losses from random models.')
    while True:
        L = model.randomModelLosses(data, k, modelParameters)
        newW = lloydsIteration(L)
        if not isnan(newW).any():
            break

    return [model(data, w, modelParameters) for w in newW]

def lloydsIteration(L):
    bestModelPerPoint = L.argmin(0)
    newW = zeros(L.shape)
    for (b, i) in zip(bestModelPerPoint, utility.naturals()):
        newW[b, i - 1] = 1
    while 0 in newW.sum(1):
        badRows = nonzero(newW.sum(1) == 0)
        badRow = badRows[0]
        aGoodRow = bestModelPerPoint[badRow]
        newW[aGoodRow, badRow] = 0
        newW[badRow, badRow] = 1

    newW = newW / newW.sum(1)[newaxis].T
    return newW

def lloydsAlgorithm(initialStates, maxSteps=10):
    return multipleModelEvolution(initialStates,
                                  lambda L, W, s: (lloydsIteration(L), s),
                                  maxSteps=maxSteps)

#@profile
def jointlyPenalizedInitialStates(data, model, alpha, k=0, modelParameters=None, dualityGapGoal=1e-5):
    #print('Generating initial losses from random models.')
    L = model.randomModelLosses(data, k, modelParameters)
    W, _ = weightsForMultipleLosses2TimedStreams(L, alpha, dualityGapGoal=dualityGapGoal)

    return [model(data, w, modelParameters) for w in W]

def learnJointlyPenalizedMultipleModels(initialStates, alpha, maxSteps=10, dualityGapGoal=1e-5):
    return multipleModelEvolution(initialStates,
                                  lambda L, W, l2: weightsForMultipleLosses2TimedStreams(L, alpha, W=W, l2=l2,
                                                                                dualityGapGoal=dualityGapGoal),
                                  maxSteps=maxSteps)

def weightsClose(w1, w2):
    k, q = w1.shape
    return allclose(w1, w2, rtol=10 ** -2, atol=((1 / q) * 10 ** -2))

def multipleModelEvolution(initialStates, weightMapping, maxSteps=10):
    print "starting mme"
    es = initialStates[0]
    W = array([s.weights for s in initialStates])
    sideInformation = None
    # bound computation time
    for _ in range(maxSteps):
        print('Fitting new models')
        currStates = [es.nextState(w) for w in W]
        L = array([currState.squaredLosses() for currState in currStates])
        newW, sideInformation = weightMapping(L, W, sideInformation)
        if weightsClose(newW, W):
            break
        W = newW
    print "done mme"
    return currStates


text:
<?php
function testDoWhileStatementWithoutScopeStatementChild()
{
    do
        if (!isset($i)) $i = 0;
    while (++$i < 5);

    return $i;
}

echo testDoWhileStatementWithoutScopeStatementChild();


text:
"""
Routes all the requests to the task manager.
"""

from oslo import messaging
from trove.common import cfg
from trove.common import exception
from trove.common.strategies.cluster import strategy
import trove.common.rpc.version as rpc_version
from trove.guestagent import models as agent_models
from trove import rpc
from trove.openstack.common import log as logging

CONF = cfg.CONF
LOG = logging.getLogger(__name__)

class API(object):
    """API for interacting with the task manager."""

    def __init__(self, context):
        self.context = context
        super(API, self).__init__()

        target = messaging.Target(topic=CONF.taskmanager_queue,
                                  version=rpc_version.RPC_API_VERSION)

        self.version_cap = rpc_version.VERSION_ALIASES.get(
            CONF.upgrade_levels.taskmanager)
        self.client = self.get_client(target, self.version_cap)

    def get_client(self, target, version_cap, serializer=None):
        return rpc.get_client(target,
                              version_cap=version_cap,
                              serializer=serializer)

    def _transform_obj(self, obj_ref):
        # Turn the object into a dictionary and remove the mgr
        if "__dict__" in dir(obj_ref):
            obj_dict = obj_ref.__dict__
            # We assume manager contains a object due to the *clients
            if obj_dict.get('manager'):
                del obj_dict['manager']
            return obj_dict
        raise ValueError("Could not transform %s" % obj_ref)

    def _delete_heartbeat(self, instance_id):
        agent_heart_beat = agent_models.AgentHeartBeat()
        try:
            heartbeat = agent_heart_beat.find_by_instance_id(instance_id)
            heartbeat.delete()
        except exception.ModelNotFoundError as e:
            LOG.error(e.message)

    def resize_volume(self, new_size, instance_id):
        LOG.debug("Making async call to resize volume for instance: %s"
                  % instance_id)

        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "resize_volume",
                   new_size=new_size,
                   instance_id=instance_id)

    def resize_flavor(self, instance_id, old_flavor, new_flavor):
        LOG.debug("Making async call to resize flavor for instance: %s" %
                  instance_id)

        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "resize_flavor",
                   instance_id=instance_id,
                   old_flavor=self._transform_obj(old_flavor),
                   new_flavor=self._transform_obj(new_flavor))

    def reboot(self, instance_id):
        LOG.debug("Making async call to reboot instance: %s" % instance_id)

        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "reboot", instance_id=instance_id)

    #rds-start
    def restore_instance(self, packages, flavor, datastore_manager, instance_id, image_id, backup_id):
        LOG.debug("Making async call to restore instance: %s" % instance_id)
        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "restore_instance", packages=packages,
                   flavor=self._transform_obj(flavor),
                   datastore_manager=datastore_manager,
                   instance_id=instance_id,
                   image_id=image_id,
                   backup_id=backup_id)
    #rds-end

    def restart(self, instance_id):
        LOG.debug("Making async call to restart instance: %s" % instance_id)

        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "restart", instance_id=instance_id)

    def detach_replica(self, instance_id):
        LOG.debug("Making async call to detach replica: %s" % instance_id)

        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "detach_replica", instance_id=instance_id)

    def promote_to_replica_source(self, instance_id):
        LOG.debug("Making async call to promote replica to source: %s" %
                  instance_id)
        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "promote_to_replica_source",
                   instance_id=instance_id)

    def eject_replica_source(self, instance_id):
        LOG.debug("Making async call to eject replica source: %s" %
                  instance_id)
        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "eject_replica_source",
                   instance_id=instance_id)

    def migrate(self, instance_id, host):
        LOG.debug("Making async call to migrate instance: %s" % instance_id)

        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "migrate", instance_id=instance_id, host=host)

    def delete_instance(self, instance_id):
        LOG.debug("Making async call to delete instance: %s" % instance_id)

        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "delete_instance", instance_id=instance_id)

    def create_backup(self, backup_info, instance_id):
        LOG.debug("Making async call to create a backup for instance: %s" %
                  instance_id)

        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "create_backup",
                   backup_info=backup_info,
                   instance_id=instance_id)

    def delete_backup(self, backup_id):
        LOG.debug("Making async call to delete backup: %s" % backup_id)

        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "delete_backup", backup_id=backup_id)

    def create_instance(self, instance_id, name, flavor,
                        image_id, databases, users, datastore_manager,
                        packages, volume_size, backup_id=None,
                        availability_zone=None, root_password=None,
                        nics=None, overrides=None, slave_of_id=None,
                        cluster_config=None):

        LOG.debug("Making async call to create instance %s " % instance_id)

        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "create_instance",
                   instance_id=instance_id, name=name,
                   flavor=self._transform_obj(flavor),
                   image_id=image_id,
                   databases=databases,
                   users=users,
                   datastore_manager=datastore_manager,
                   packages=packages,
                   volume_size=volume_size,
                   backup_id=backup_id,
                   availability_zone=availability_zone,
                   root_password=root_password,
                   nics=nics,
                   overrides=overrides,
                   slave_of_id=slave_of_id,
                   cluster_config=cluster_config)

    def update_overrides(self, instance_id, overrides=None):
        LOG.debug("Making async call to update datastore configurations for "
                  "instance %s" % instance_id)

        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "update_overrides",
                   instance_id=instance_id,
                   overrides=overrides)

    def unassign_configuration(self, instance_id, flavor, configuration_id):
        LOG.debug("Making async call to remove datastore configurations for "
                  "instance %s" % instance_id)

        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "unassign_configuration",
                   instance_id=instance_id,
                   flavor=self._transform_obj(flavor),
                   configuration_id=configuration_id)

    def create_cluster(self, cluster_id):
        LOG.debug("Making async call to create cluster %s " % cluster_id)

        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "create_cluster",
                   cluster_id=cluster_id)

    def delete_cluster(self, cluster_id):
        LOG.debug("Making async call to delete cluster %s " % cluster_id)

        cctxt = self.client.prepare(version=self.version_cap)
        cctxt.cast(self.context, "delete_cluster",
                   cluster_id=cluster_id)

def load(context, manager=None):
    if manager:
        task_manager_api_class = (strategy.load_taskmanager_strategy(manager)
                                  .task_manager_api_class)
    else:
        task_manager_api_class = API
    return task_manager_api_class(context)


text:
package txml.parser;
import org.antlr.v4.runtime.tree.ParseTreeListener;

/**
 * This interface defines a complete listener for a parse tree produced by
 * {@link XQueryParser}.
 */
public interface XQueryListener extends ParseTreeListener {
	/**
	 * Enter a parse tree produced by {@link XQueryParser#main}.
	 * @param ctx the parse tree
	 */
	void enterMain(XQueryParser.MainContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#main}.
	 * @param ctx the parse tree
	 */
	void exitMain(XQueryParser.MainContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#prolog}.
	 * @param ctx the parse tree
	 */
	void enterProlog(XQueryParser.PrologContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#prolog}.
	 * @param ctx the parse tree
	 */
	void exitProlog(XQueryParser.PrologContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#declareOption}.
	 * @param ctx the parse tree
	 */
	void enterDeclareOption(XQueryParser.DeclareOptionContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#declareOption}.
	 * @param ctx the parse tree
	 */
	void exitDeclareOption(XQueryParser.DeclareOptionContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#declareOptionConnection}.
	 * @param ctx the parse tree
	 */
	void enterDeclareOptionConnection(XQueryParser.DeclareOptionConnectionContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#declareOptionConnection}.
	 * @param ctx the parse tree
	 */
	void exitDeclareOptionConnection(XQueryParser.DeclareOptionConnectionContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#declareOptionTimeFormat}.
	 * @param ctx the parse tree
	 */
	void enterDeclareOptionTimeFormat(XQueryParser.DeclareOptionTimeFormatContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#declareOptionTimeFormat}.
	 * @param ctx the parse tree
	 */
	void exitDeclareOptionTimeFormat(XQueryParser.DeclareOptionTimeFormatContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#declareOptionSort}.
	 * @param ctx the parse tree
	 */
	void enterDeclareOptionSort(XQueryParser.DeclareOptionSortContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#declareOptionSort}.
	 * @param ctx the parse tree
	 */
	void exitDeclareOptionSort(XQueryParser.DeclareOptionSortContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#documentName}.
	 * @param ctx the parse tree
	 */
	void enterDocumentName(XQueryParser.DocumentNameContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#documentName}.
	 * @param ctx the parse tree
	 */
	void exitDocumentName(XQueryParser.DocumentNameContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#schemaName}.
	 * @param ctx the parse tree
	 */
	void enterSchemaName(XQueryParser.SchemaNameContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#schemaName}.
	 * @param ctx the parse tree
	 */
	void exitSchemaName(XQueryParser.SchemaNameContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#timeFormat}.
	 * @param ctx the parse tree
	 */
	void enterTimeFormat(XQueryParser.TimeFormatContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#timeFormat}.
	 * @param ctx the parse tree
	 */
	void exitTimeFormat(XQueryParser.TimeFormatContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#sort}.
	 * @param ctx the parse tree
	 */
	void enterSort(XQueryParser.SortContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#sort}.
	 * @param ctx the parse tree
	 */
	void exitSort(XQueryParser.SortContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#connectionUrl}.
	 * @param ctx the parse tree
	 */
	void enterConnectionUrl(XQueryParser.ConnectionUrlContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#connectionUrl}.
	 * @param ctx the parse tree
	 */
	void exitConnectionUrl(XQueryParser.ConnectionUrlContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#fileFullName}.
	 * @param ctx the parse tree
	 */
	void enterFileFullName(XQueryParser.FileFullNameContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#fileFullName}.
	 * @param ctx the parse tree
	 */
	void exitFileFullName(XQueryParser.FileFullNameContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#body}.
	 * @param ctx the parse tree
	 */
	void enterBody(XQueryParser.BodyContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#body}.
	 * @param ctx the parse tree
	 */
	void exitBody(XQueryParser.BodyContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#statement}.
	 * @param ctx the parse tree
	 */
	void enterStatement(XQueryParser.StatementContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#statement}.
	 * @param ctx the parse tree
	 */
	void exitStatement(XQueryParser.StatementContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#initSchema}.
	 * @param ctx the parse tree
	 */
	void enterInitSchema(XQueryParser.InitSchemaContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#initSchema}.
	 * @param ctx the parse tree
	 */
	void exitInitSchema(XQueryParser.InitSchemaContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#deinitSchema}.
	 * @param ctx the parse tree
	 */
	void enterDeinitSchema(XQueryParser.DeinitSchemaContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#deinitSchema}.
	 * @param ctx the parse tree
	 */
	void exitDeinitSchema(XQueryParser.DeinitSchemaContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#storeDocument}.
	 * @param ctx the parse tree
	 */
	void enterStoreDocument(XQueryParser.StoreDocumentContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#storeDocument}.
	 * @param ctx the parse tree
	 */
	void exitStoreDocument(XQueryParser.StoreDocumentContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#storeDocumentWithName}.
	 * @param ctx the parse tree
	 */
	void enterStoreDocumentWithName(XQueryParser.StoreDocumentWithNameContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#storeDocumentWithName}.
	 * @param ctx the parse tree
	 */
	void exitStoreDocumentWithName(XQueryParser.StoreDocumentWithNameContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#storeDocumentWithoutName}.
	 * @param ctx the parse tree
	 */
	void enterStoreDocumentWithoutName(XQueryParser.StoreDocumentWithoutNameContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#storeDocumentWithoutName}.
	 * @param ctx the parse tree
	 */
	void exitStoreDocumentWithoutName(XQueryParser.StoreDocumentWithoutNameContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#doc}.
	 * @param ctx the parse tree
	 */
	void enterDoc(XQueryParser.DocContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#doc}.
	 * @param ctx the parse tree
	 */
	void exitDoc(XQueryParser.DocContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#snapshotQuery}.
	 * @param ctx the parse tree
	 */
	void enterSnapshotQuery(XQueryParser.SnapshotQueryContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#snapshotQuery}.
	 * @param ctx the parse tree
	 */
	void exitSnapshotQuery(XQueryParser.SnapshotQueryContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#absPathExprWithDoc}.
	 * @param ctx the parse tree
	 */
	void enterAbsPathExprWithDoc(XQueryParser.AbsPathExprWithDocContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#absPathExprWithDoc}.
	 * @param ctx the parse tree
	 */
	void exitAbsPathExprWithDoc(XQueryParser.AbsPathExprWithDocContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#xPathQuery}.
	 * @param ctx the parse tree
	 */
	void enterXPathQuery(XQueryParser.XPathQueryContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#xPathQuery}.
	 * @param ctx the parse tree
	 */
	void exitXPathQuery(XQueryParser.XPathQueryContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#update}.
	 * @param ctx the parse tree
	 */
	void enterUpdate(XQueryParser.UpdateContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#update}.
	 * @param ctx the parse tree
	 */
	void exitUpdate(XQueryParser.UpdateContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#forClause}.
	 * @param ctx the parse tree
	 */
	void enterForClause(XQueryParser.ForClauseContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#forClause}.
	 * @param ctx the parse tree
	 */
	void exitForClause(XQueryParser.ForClauseContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#updateExpr}.
	 * @param ctx the parse tree
	 */
	void enterUpdateExpr(XQueryParser.UpdateExprContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#updateExpr}.
	 * @param ctx the parse tree
	 */
	void exitUpdateExpr(XQueryParser.UpdateExprContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#insertExpr}.
	 * @param ctx the parse tree
	 */
	void enterInsertExpr(XQueryParser.InsertExprContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#insertExpr}.
	 * @param ctx the parse tree
	 */
	void exitInsertExpr(XQueryParser.InsertExprContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#deleteExpr}.
	 * @param ctx the parse tree
	 */
	void enterDeleteExpr(XQueryParser.DeleteExprContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#deleteExpr}.
	 * @param ctx the parse tree
	 */
	void exitDeleteExpr(XQueryParser.DeleteExprContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#parentExpr}.
	 * @param ctx the parse tree
	 */
	void enterParentExpr(XQueryParser.ParentExprContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#parentExpr}.
	 * @param ctx the parse tree
	 */
	void exitParentExpr(XQueryParser.ParentExprContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#parentXPathExpression}.
	 * @param ctx the parse tree
	 */
	void enterParentXPathExpression(XQueryParser.ParentXPathExpressionContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#parentXPathExpression}.
	 * @param ctx the parse tree
	 */
	void exitParentXPathExpression(XQueryParser.ParentXPathExpressionContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#childXPathExpression}.
	 * @param ctx the parse tree
	 */
	void enterChildXPathExpression(XQueryParser.ChildXPathExpressionContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#childXPathExpression}.
	 * @param ctx the parse tree
	 */
	void exitChildXPathExpression(XQueryParser.ChildXPathExpressionContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#simpleXPathExpression}.
	 * @param ctx the parse tree
	 */
	void enterSimpleXPathExpression(XQueryParser.SimpleXPathExpressionContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#simpleXPathExpression}.
	 * @param ctx the parse tree
	 */
	void exitSimpleXPathExpression(XQueryParser.SimpleXPathExpressionContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#insertXPathExpression}.
	 * @param ctx the parse tree
	 */
	void enterInsertXPathExpression(XQueryParser.InsertXPathExpressionContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#insertXPathExpression}.
	 * @param ctx the parse tree
	 */
	void exitInsertXPathExpression(XQueryParser.InsertXPathExpressionContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#absPathExpr}.
	 * @param ctx the parse tree
	 */
	void enterAbsPathExpr(XQueryParser.AbsPathExprContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#absPathExpr}.
	 * @param ctx the parse tree
	 */
	void exitAbsPathExpr(XQueryParser.AbsPathExprContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#steps}.
	 * @param ctx the parse tree
	 */
	void enterSteps(XQueryParser.StepsContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#steps}.
	 * @param ctx the parse tree
	 */
	void exitSteps(XQueryParser.StepsContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#undirectStep}.
	 * @param ctx the parse tree
	 */
	void enterUndirectStep(XQueryParser.UndirectStepContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#undirectStep}.
	 * @param ctx the parse tree
	 */
	void exitUndirectStep(XQueryParser.UndirectStepContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#directStep}.
	 * @param ctx the parse tree
	 */
	void enterDirectStep(XQueryParser.DirectStepContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#directStep}.
	 * @param ctx the parse tree
	 */
	void exitDirectStep(XQueryParser.DirectStepContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#predicate}.
	 * @param ctx the parse tree
	 */
	void enterPredicate(XQueryParser.PredicateContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#predicate}.
	 * @param ctx the parse tree
	 */
	void exitPredicate(XQueryParser.PredicateContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#xPathInExpr}.
	 * @param ctx the parse tree
	 */
	void enterXPathInExpr(XQueryParser.XPathInExprContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#xPathInExpr}.
	 * @param ctx the parse tree
	 */
	void exitXPathInExpr(XQueryParser.XPathInExprContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#expr}.
	 * @param ctx the parse tree
	 */
	void enterExpr(XQueryParser.ExprContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#expr}.
	 * @param ctx the parse tree
	 */
	void exitExpr(XQueryParser.ExprContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#position}.
	 * @param ctx the parse tree
	 */
	void enterPosition(XQueryParser.PositionContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#position}.
	 * @param ctx the parse tree
	 */
	void exitPosition(XQueryParser.PositionContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#last}.
	 * @param ctx the parse tree
	 */
	void enterLast(XQueryParser.LastContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#last}.
	 * @param ctx the parse tree
	 */
	void exitLast(XQueryParser.LastContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#integerNumber}.
	 * @param ctx the parse tree
	 */
	void enterIntegerNumber(XQueryParser.IntegerNumberContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#integerNumber}.
	 * @param ctx the parse tree
	 */
	void exitIntegerNumber(XQueryParser.IntegerNumberContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#operator}.
	 * @param ctx the parse tree
	 */
	void enterOperator(XQueryParser.OperatorContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#operator}.
	 * @param ctx the parse tree
	 */
	void exitOperator(XQueryParser.OperatorContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#variable}.
	 * @param ctx the parse tree
	 */
	void enterVariable(XQueryParser.VariableContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#variable}.
	 * @param ctx the parse tree
	 */
	void exitVariable(XQueryParser.VariableContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#nodeGenerator}.
	 * @param ctx the parse tree
	 */
	void enterNodeGenerator(XQueryParser.NodeGeneratorContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#nodeGenerator}.
	 * @param ctx the parse tree
	 */
	void exitNodeGenerator(XQueryParser.NodeGeneratorContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#currentNodes}.
	 * @param ctx the parse tree
	 */
	void enterCurrentNodes(XQueryParser.CurrentNodesContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#currentNodes}.
	 * @param ctx the parse tree
	 */
	void exitCurrentNodes(XQueryParser.CurrentNodesContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#parentNodes}.
	 * @param ctx the parse tree
	 */
	void enterParentNodes(XQueryParser.ParentNodesContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#parentNodes}.
	 * @param ctx the parse tree
	 */
	void exitParentNodes(XQueryParser.ParentNodesContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#childsElements}.
	 * @param ctx the parse tree
	 */
	void enterChildsElements(XQueryParser.ChildsElementsContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#childsElements}.
	 * @param ctx the parse tree
	 */
	void exitChildsElements(XQueryParser.ChildsElementsContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#nodesByType}.
	 * @param ctx the parse tree
	 */
	void enterNodesByType(XQueryParser.NodesByTypeContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#nodesByType}.
	 * @param ctx the parse tree
	 */
	void exitNodesByType(XQueryParser.NodesByTypeContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#textNodes}.
	 * @param ctx the parse tree
	 */
	void enterTextNodes(XQueryParser.TextNodesContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#textNodes}.
	 * @param ctx the parse tree
	 */
	void exitTextNodes(XQueryParser.TextNodesContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#elementName}.
	 * @param ctx the parse tree
	 */
	void enterElementName(XQueryParser.ElementNameContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#elementName}.
	 * @param ctx the parse tree
	 */
	void exitElementName(XQueryParser.ElementNameContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#attributeName}.
	 * @param ctx the parse tree
	 */
	void enterAttributeName(XQueryParser.AttributeNameContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#attributeName}.
	 * @param ctx the parse tree
	 */
	void exitAttributeName(XQueryParser.AttributeNameContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#value}.
	 * @param ctx the parse tree
	 */
	void enterValue(XQueryParser.ValueContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#value}.
	 * @param ctx the parse tree
	 */
	void exitValue(XQueryParser.ValueContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#insert_pos}.
	 * @param ctx the parse tree
	 */
	void enterInsert_pos(XQueryParser.Insert_posContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#insert_pos}.
	 * @param ctx the parse tree
	 */
	void exitInsert_pos(XQueryParser.Insert_posContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#time}.
	 * @param ctx the parse tree
	 */
	void enterTime(XQueryParser.TimeContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#time}.
	 * @param ctx the parse tree
	 */
	void exitTime(XQueryParser.TimeContext ctx);
	/**
	 * Enter a parse tree produced by {@link XQueryParser#format}.
	 * @param ctx the parse tree
	 */
	void enterFormat(XQueryParser.FormatContext ctx);
	/**
	 * Exit a parse tree produced by {@link XQueryParser#format}.
	 * @param ctx the parse tree
	 */
	void exitFormat(XQueryParser.FormatContext ctx);
}