text:
/*
 *    GeoTools - The Open Source Java GIS Toolkit
 *    http://geotools.org
 *
 *    (C) 2011, Open Source Geospatial Foundation (OSGeo)
 *    (C) 2001-2007 TOPP - www.openplans.org.
 *
 *    Modified by Oskari.org 2014.
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation;
 *    version 2.1 of the License.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 */
package org.geoserver.wps.oskari;

import java.lang.String;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.geotools.data.collection.ListFeatureCollection;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.process.ProcessException;
import org.geotools.process.factory.DescribeParameter;
import org.geotools.process.factory.DescribeProcess;
import org.geotools.process.factory.DescribeResult;
import org.geotools.process.gs.GSProcess;
import org.geotools.referencing.CRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import org.opengis.util.ProgressListener;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.impl.PackedCoordinateSequenceFactory;

/**
 * Oskari Rendering Transformation process which aggregates features into a set of
 * visually non-conflicting point features.
 * The created points have attributes which provide the total number of points
 * aggregated, as well as the number of unique point locations.
 *

 * This is sometimes called "point clustering".
 * The term stacking is used instead, since clustering has multiple
 * meanings in geospatial processing - it is also used to
 * mean identifying groups defined by point proximity.
 *

 * The stacking is defined by specifying a grid to aggregate to.
 * The grid cell size is specified in pixels relative to the requested output image size.
 * This makes it more intuitive to pick an appropriate grid size,
 * and ensures that the aggregation works at all zoom levels.
 *

 * The output is a FeatureCollection containing the following attributes:
 *

 *
geom - the point representing the cluster
 *
count - the total number of points in the cluster
 *
countunique - the number of unique point locations in the cluster
 *

 * Note that as required by the Rendering Transformation API, the output
 * has the CRS of the input data.
 *
 */
@DescribeProcess(title = "Oskari Point Stacker", description = "Aggregates a collection of points over a grid into one point per grid cell.")
public class OskariPointStackerProcess implements GSProcess {

    public enum PreserveLocation {
        /**
         * Preserves the original point location in case there is a single point in the cell
         */
        Single,
        /**
         * Preserves the original point location in case there are multiple points, but all with the same coordinates in the cell
         */
        Superimposed,
        /**
         * Default value, averages the point locations with the cell center to try and avoid conflicts among the symbolizers for the
         */
        Never};

    public static final String ATTR_GEOM = "geom";
    public static final String ATTR_COUNT = "count";
    public static final String ATTR_COUNT_UNIQUE = "countunique";
    public static final String ATTR_NORM_COUNT = "normCount";
    public static final String ATTR_NORM_COUNT_UNIQUE = "normCountUnique";

    //TODO: add ability to pick index point selection strategy
    //TODO: add ability to set attribute name containing value to be aggregated
    //TODO: add ability to specify aggregation method (COUNT, SUM, AVG)
    //TODO: ultimately could allow aggregating multiple input attributes, with different methods for each
    //TODO: allow including attributes from input data (eg for use with points that are not aggregated)
    //TODO: expand query window to avoid edge effects?

    // no process state is defined, since RenderingTransformation processes must be stateless

    @DescribeResult(name = "result", description = "Aggregated feature collection")
    public SimpleFeatureCollection execute(

            // process data
            @DescribeParameter(name = "data", description = "Input feature collection") SimpleFeatureCollection data,

            // process parameters
            @DescribeParameter(name = "cellSize", description = "Grid cell size to aggregate to, in pixels") Integer cellSize,
            @DescribeParameter(name = "normalize", description = "Indicates whether to add fields normalized to the range 0-1.", defaultValue="false") Boolean argNormalize,
            @DescribeParameter(name = "preserveLocation", description = "Indicates wheter to preserve the original location of points for single/superimposed points", defaultValue="Never", min=0) PreserveLocation preserveLocation,

            // output image parameters
            @DescribeParameter(name = "outputBBOX", description = "Bounding box for target image extent") ReferencedEnvelope outputEnv,
            @DescribeParameter(name = "outputWidth", description = "Target image width in pixels", minValue = 1) Integer outputWidth,
            @DescribeParameter(name = "outputHeight", description = "Target image height in pixels", minValue = 1) Integer outputHeight,

            ProgressListener monitor) throws ProcessException, TransformException {

        CoordinateReferenceSystem srcCRS = data.getSchema().getCoordinateReferenceSystem();
        CoordinateReferenceSystem dstCRS = outputEnv.getCoordinateReferenceSystem();
        MathTransform crsTransform = null;
        MathTransform invTransform = null;
        try {
            crsTransform = CRS.findMathTransform(srcCRS, dstCRS);
            invTransform = crsTransform.inverse();
        } catch (FactoryException e) {
            throw new ProcessException(e);
        }

        boolean normalize = false;
        if(argNormalize!=null){
            normalize = argNormalize;
        }

        // TODO: allow output CRS to be different to data CRS
        // assume same CRS for now...
        double cellSizeSrc = cellSize * outputEnv.getWidth() / outputWidth;

        Collection<StackedPoint> stackedPts = stackPoints(data, crsTransform, cellSizeSrc,
                outputEnv.getMinX(), outputEnv.getMinY());

        SimpleFeatureType schema = createType(srcCRS, normalize);
        ListFeatureCollection result = new ListFeatureCollection(schema);
        SimpleFeatureBuilder fb = new SimpleFeatureBuilder(schema);

        GeometryFactory factory = new GeometryFactory(new PackedCoordinateSequenceFactory());

        double[] srcPt = new double[2];
        double[] dstPt = new double[2];

        // Find maxima of the point stacks if needed.
        int maxCount = 0;
        int maxCountUnique = 0;
        if(normalize){
            for (StackedPoint sp : stackedPts) {
                if(maxCount<sp.getCount()) maxCount = sp.getCount();
                if(maxCountUnique<sp.getCount()) maxCountUnique = sp.getCountUnique();
            }
        }

        for (StackedPoint sp : stackedPts) {
            // create feature for stacked point
            Coordinate pt = getStackedPointLocation(preserveLocation, sp);

            // transform back to src CRS, since RT rendering expects the output to be in the same CRS
            srcPt[0] = pt.x;
            srcPt[1] = pt.y;
            invTransform.transform(srcPt, 0, dstPt, 0, 1);
            Coordinate psrc = new Coordinate(dstPt[0], dstPt[1]);

            Geometry point = factory.createPoint(psrc);
            fb.add(point);
            fb.add(sp.getCount());
            fb.add(sp.getCountUnique());
            if(normalize){
                fb.add(((double)sp.getCount())/maxCount);
                fb.add(((double)sp.getCountUnique())/maxCountUnique);
            }
            fb.add(sp.getName());
            fb.add(sp.getAttention_text());
            fb.add(sp.getGeometryType());
            fb.add(sp.getStroke_width());
            fb.add(sp.getStroke_color());
            fb.add(sp.getFill_color());
            fb.add(sp.getDot_color());
            fb.add(sp.getDot_size());
            fb.add(sp.getDot_shape());
            fb.add(sp.getBorder_width());
            fb.add(sp.getBorder_color());
            fb.add(sp.getFill_pattern());
            fb.add(sp.getStroke_linejoin());
            fb.add(sp.getStroke_linecap());
            fb.add(sp.getStroke_dasharray());
            fb.add(sp.getBorder_linejoin());
            fb.add(sp.getBorder_dasharray());

            result.add(fb.buildFeature(null));
        }
        return result;
    }

    /**
     * Extract the geometry
     * @param preserveLocation
     * @param sp
     * @return
     */
    private Coordinate getStackedPointLocation(PreserveLocation preserveLocation, StackedPoint sp) {
        Coordinate pt;
        if (sp.getCount() == 1) {
            pt = sp.getOriginalLocation();
        } else {
            pt = sp.getLocation();
        }
        return pt;
    }

    /**
     * Computes the stacked points for the given data collection.
     * All geometry types are handled - for non-point geometries, the centroid is used.
     *
     * @param data
     * @param cellSize
     * @param minX
     * @param minY
     * @return
     * @throws TransformException
     */
    private Collection<StackedPoint> stackPoints(SimpleFeatureCollection data,
            MathTransform crsTransform,
            double cellSize, double minX, double minY) throws TransformException {
        SimpleFeatureIterator featureIt = data.features();

        Map<Coordinate, StackedPoint> stackedPts = new HashMap<Coordinate, StackedPoint>();

        double[] srcPt = new double[2];
        double[] dstPt = new double[2];

        Coordinate indexPt = new Coordinate();
        try {
            while (featureIt.hasNext()) {
                SimpleFeature feature = featureIt.next();
                // get the point location from the geometry
                Geometry geom = (Geometry) feature.getDefaultGeometry();

                // Lines and polygons are not included
                if (!(geom.getGeometryType().equals("Point"))&&!(geom.getGeometryType().equals("MultiPoint"))) {
                    continue;
                }

                Coordinate[] ps = getRepresentativePoints(geom);

                for (int j=0; j<ps.length; j++) {
                    Coordinate p = ps[j];
                    // reproject data point to output CRS, if required
                    srcPt[0] = p.x;
                    srcPt[1] = p.y;
                    crsTransform.transform(srcPt, 0, dstPt, 0, 1);
                    Coordinate pout = new Coordinate(dstPt[0], dstPt[1]);

                    indexPt.x = pout.x;
                    indexPt.y = pout.y;
                    gridIndex(indexPt, cellSize);

                    StackedPoint stkPt = stackedPts.get(indexPt);
                    if (stkPt == null) {

                        double centreX = indexPt.x * cellSize + cellSize / 2;
                        double centreY = indexPt.y * cellSize + cellSize / 2;

                        stkPt = new StackedPoint(indexPt, new Coordinate(centreX, centreY));
                        if (feature.getAttribute("name") != null) {
                            stkPt.setName(String.valueOf(feature.getAttribute("name")));
                        } else {
                            stkPt.setName("");
                        }
                        if (feature.getAttribute("attention_text") != null) {
                            stkPt.setAttention_text(String.valueOf(feature.getAttribute("attention_text")));
                        } else {
                            stkPt.setAttention_text("");
                        }
                        stkPt.setGeometryType(geom.getGeometryType());
                        stkPt.setStroke_width(Integer.valueOf(String.valueOf(feature.getAttribute("stroke_width"))));
                        stkPt.setStroke_color(String.valueOf(feature.getAttribute("stroke_color")));
                        stkPt.setFill_color(String.valueOf(feature.getAttribute("fill_color")));
                        stkPt.setDot_color(String.valueOf(feature.getAttribute("dot_color")));
                        stkPt.setDot_size(Integer.valueOf(String.valueOf(feature.getAttribute("dot_size"))));
                        stkPt.setDot_shape(String.valueOf(feature.getAttribute("dot_shape")));
                        stkPt.setBorder_width(Integer.valueOf(String.valueOf(feature.getAttribute("border_width"))));
                        stkPt.setBorder_color(String.valueOf(feature.getAttribute("border_color")));
                        stkPt.setFill_pattern(Integer.valueOf(String.valueOf(feature.getAttribute("fill_pattern"))));
                        stkPt.setStroke_linejoin(String.valueOf(feature.getAttribute("stroke_linejoin")));
                        stkPt.setStroke_linecap(String.valueOf(feature.getAttribute("stroke_linecap")));
                        stkPt.setStroke_dasharray(String.valueOf(feature.getAttribute("stroke_dasharray")));
                        stkPt.setBorder_linejoin(String.valueOf(feature.getAttribute("border_linejoin")));
                        stkPt.setBorder_dasharray(String.valueOf(feature.getAttribute("border_dasharray")));

                        stackedPts.put(stkPt.getKey(), stkPt);
                    }
                    stkPt.add(pout);
                }
            }

        } finally {
            featureIt.close();
        }
        return stackedPts.values();
    }

    /**
     * Gets a point to represent the Geometry.
     * If the Geometry is a point, this is returned.
     * Otherwise, the centroid is used.
     *
     * @param g the geometry to find a point for
     * @return a point representing the Geometry
     */
    private static Coordinate getRepresentativePoint(Geometry g)
    {
        if (g.getNumPoints() == 1) {
            return g.getCoordinate();
        }
        return g.getCentroid().getCoordinate();
    }

    /**
     * Gets points representing the geometry.
     *
     * @param g the geometry to find points for
     * @return points representing the geometry
     */
    private static Coordinate[] getRepresentativePoints(Geometry g)
    {
        Coordinate[] coordinates;
        int numPoints = g.getNumPoints();
        if (g.getGeometryType().equals("MultiPoint")) {
            coordinates = g.getCoordinates();
        } else {
            coordinates = new Coordinate[1];
            if (numPoints == 1) {
                coordinates[0] = g.getCoordinate();
            } else {
                coordinates[0] = g.getCentroid().getCoordinate();
            }
        }
        return coordinates;
    }

    /**
     * Computes the grid index for a point for the grid determined by the cellsize.
     *
     * @param griddedPt the point to grid, and also holds the output value
     * @param cellSize the grid cell size
     */
    private void gridIndex(Coordinate griddedPt, double cellSize) {

        // TODO: is there any situation where this could result in too much loss of precision?
        /**
         * The grid is based at the origin of the entire data space,
         * not just the query window.
         * This makes gridding stable during panning.
         *
         * This should not lose too much precision for any reasonable coordinate system and map size.
         * The worst case is a CRS with small ordinate values, and a large cell size.
         * The worst case tested is a map in degrees, zoomed out to show about twice the globe - works fine.
         */
        // Use longs to avoid possible overflow issues (e.g. for a very small cell size)
        long ix = (long) ((griddedPt.x) / cellSize);
        long iy = (long) ((griddedPt.y) / cellSize);

        griddedPt.x = ix;
        griddedPt.y = iy;
    }

    private SimpleFeatureType createType(CoordinateReferenceSystem crs, boolean stretch) {
        SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
        tb.add(ATTR_GEOM, Point.class, crs);
        tb.add(ATTR_COUNT, Integer.class);
        tb.add(ATTR_COUNT_UNIQUE, Integer.class);
        if(stretch){
            tb.add(ATTR_NORM_COUNT, Double.class);
            tb.add(ATTR_NORM_COUNT_UNIQUE, Double.class);
        }
        tb.add("name",String.class);
        tb.add("attention_text",String.class);
        tb.add("geometryType",String.class);
        tb.add("stroke_width",Integer.class);
        tb.add("stroke_color",String.class);
        tb.add("fill_color",String.class);
        tb.add("dot_color",String.class);
        tb.add("dot_size",Integer.class);
        tb.add("dot_shape",String.class);
        tb.add("border_width",Integer.class);
        tb.add("border_color",String.class);
        tb.add("fill_pattern",Integer.class);
        tb.add("stroke_linejoin",String.class);
        tb.add("stroke_linecap",String.class);
        tb.add("stroke_dasharray",String.class);
        tb.add("border_linejoin",String.class);
        tb.add("border_dasharray",String.class);
        tb.setName("stackedPoint");
        SimpleFeatureType sfType = tb.buildFeatureType();
        return sfType;
    }

    private static class StackedPoint {
        private Coordinate key;
        private Coordinate centerPt;
        private Coordinate location = null;
        private int count = 0;
        private Set<Coordinate> uniquePts;
        private String name;
        private String attention_text;
        private String geometryType;
        private int stroke_width;
        private String stroke_color;
        private String fill_color;
        private String dot_color;
        private int dot_size;
        private String dot_shape;
        private int border_width;
        private String border_color;
        private int fill_pattern;
        private String stroke_linejoin;
        private String stroke_linecap;
        private String stroke_dasharray;
        private String border_linejoin;
        private String border_dasharray;

        /**
         * Creates a new stacked point grid cell.
         * The center point of the cell is supplied
         * so that it may be used as or influence the
         * location of the final display point
         *
         * @param key a key for the grid cell (using integer ordinates to avoid precision issues)
         * @param centerPt the center point of the grid cell
         */
        public StackedPoint(Coordinate key, Coordinate centerPt) {
            this.key = new Coordinate(key);
            this.centerPt = centerPt;
        }

        public Coordinate getKey() {
            return key;
        }

        public Coordinate getLocation() {
            return location;
        }

        public int getCount() {
            return count;
        }

        public int getCountUnique() {
            if (uniquePts == null)
                return 1;
            return uniquePts.size();
        }

        public String getBorder_dasharray() {
            return border_dasharray;
        }

        public void setBorder_dasharray(String border_dasharray) {
            this.border_dasharray = border_dasharray;
        }

        public String getBorder_linejoin() {
            return border_linejoin;
        }

        public void setBorder_linejoin(String border_linejoin) {
            this.border_linejoin = border_linejoin;
        }

        public String getStroke_dasharray() {
            return stroke_dasharray;
        }

        public void setStroke_dasharray(String stroke_dasharray) {
            this.stroke_dasharray = stroke_dasharray;
        }

        public String getStroke_linecap() {
            return stroke_linecap;
        }

        public void setStroke_linecap(String stroke_linecap) {
            this.stroke_linecap = stroke_linecap;
        }

        public String getStroke_linejoin() {
            return stroke_linejoin;
        }

        public void setStroke_linejoin(String stroke_linejoin) {
            this.stroke_linejoin = stroke_linejoin;
        }

        public int getFill_pattern() {
            return fill_pattern;
        }

        public void setFill_pattern(int fill_pattern) {
            this.fill_pattern = fill_pattern;
        }

        public String getBorder_color() {
            return border_color;
        }

        public void setBorder_color(String border_color) {
            this.border_color = border_color;
        }

        public int getBorder_width() {
            return border_width;
        }

        public void setBorder_width(int border_width) {
            this.border_width = border_width;
        }

        public String getDot_shape() {
            return dot_shape;
        }

        public void setDot_shape(String dot_shape) {
            this.dot_shape = dot_shape;
        }

        public int getDot_size() {
            return dot_size;
        }

        public void setDot_size(int dot_size) {
            this.dot_size = dot_size;
        }

        public String getDot_color() {
            return dot_color;
        }

        public void setDot_color(String dot_color) {
            this.dot_color = dot_color;
        }

        public String getFill_color() {
            return fill_color;
        }

        public void setFill_color(String fill_color) {
            this.fill_color = fill_color;
        }

        public String getStroke_color() {
            return stroke_color;
        }

        public void setStroke_color(String stroke_color) {
            this.stroke_color = stroke_color;
        }

        public int getStroke_width() {
            return stroke_width;
        }

        public void setStroke_width(int stroke_width) {
            this.stroke_width = stroke_width;
        }

        public String getGeometryType() {
            return geometryType;
        }

        public void setGeometryType(String geometryType) {
            this.geometryType = geometryType;
        }

        public String getAttention_text() {
            return attention_text;
        }

        public void setAttention_text(String attention_text) {
            this.attention_text = attention_text;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public void add(Coordinate pt) {
            count++;
            /**
             * Only create set if this is the second point seen
             * (and assum the first pt is in location)
             */
            if (uniquePts == null) {
                uniquePts = new HashSet<Coordinate>();
            }
            uniquePts.add(pt);

            pickNearestLocation(pt);
            //pickCenterLocation(pt);
        }

        /**
         * The original location of the points, in case they are all superimposed (or there is a single
         * point), otherwise null
         * @return
         */
        public Coordinate getOriginalLocation() {
            if(uniquePts != null && uniquePts.size() == 1) {
                return uniquePts.iterator().next();
            } else {
                return null;
            }
        }

        /**
         * Picks the location as the point
         * which is nearest to the center of the cell.
         * In addition, the nearest location is averaged with the cell center.
         * This gives the best chance of avoiding conflicts.
         *
         * @param pt
         */
        private void pickNearestLocation(Coordinate pt) {
            // strategy - pick most central point
            if (location == null) {
                location = average(centerPt, pt);
                return;
            }
            if (pt.distance(centerPt) < location.distance(centerPt)) {
                location = average(centerPt, pt);
            }
        }

        /**
         * Picks the location as the centre point of the cell.
         * This does not give a good visualization - the gridding is very obvious
         *
         * @param pt
         */
        private void pickCenterLocation(Coordinate pt) {
            // strategy - pick first point
            if (location == null) {
                location = new Coordinate(pt);
                return;
            }
            location = centerPt;
        }

        /**
         * Picks the first location encountered as the cell location.
         * This is sub-optimal, since if the first point is near the cell
         * boundary it is likely to collide with neighbouring points.
         *
         * @param pt
         */
        private void pickFirstLocation(Coordinate pt) {
            // strategy - pick first point
            if (location == null) {
                location = new Coordinate(pt);
            }
        }

        private static Coordinate average(Coordinate p1, Coordinate p2)
        {
            double x = (p1.x + p2.x) / 2;
            double y = (p1.y + p2.y) / 2;
            return new Coordinate(x, y);
        }
    }
}


text:
var path = require('path');
var fs = require('fs');
var webpack = require('webpack');
var env = process.env.NODE_ENV

var config = {
  entry: './src/index.js',

  output: {
    library: 'Recharts',
    libraryTarget: 'umd',
  },

  module: {
    loaders: [{
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      include: [
        path.resolve(__dirname, 'src')
      ],
      loader: 'babel',
    }],
    resolve: {
      alias: {
        'react': path.resolve(__dirname, './node_modules/react'),
        'react-dom': path.resolve(__dirname, './node_modules/react-dom'),
        'react-addons-transition-group': path.resolve(__dirname, './node_modules/react-addons-transition-group'),
      }
    },
  },

  externals: {
    "react": {
      root: 'React',
      commonjs2: 'react',
      commonjs: 'react',
      amd: 'react'
    },
    'react-dom': {
      root:'ReactDOM',
      commonjs2: 'react-dom',
      commonjs: 'react-dom',
      amd:'react-dom'
    },
    'react-dom/server': {
      root: 'ReactDOMServer',
      commonjs2: 'react-dom-server',
      commonjs: 'react-dom-server',
      amd:'react-dom-server'
    },
    'react-addons-transition-group': {
      root: ['React','addons','TransitionGroup'],
      commonjs2: 'react-addons-transition-group',
      commonjs: 'react-addons-transition-group',
      amd: 'react-addons-transition-group'
    }
  },

  plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(env),
    }),
  ],
};

if (env === 'production') {
  config.plugins.push(
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        pure_getters: true,
        unsafe: true,
        unsafe_comps: true,
        warnings: false
      },
      output: {
        comments: false
      },
      sourceMap: false
    })
  );
}

module.exports = config;

redpajama_set_name: RedPajamaGithub


text:
package com.cave.metrics.data

import play.api.libs.json._
import play.api.libs.functional.syntax._

object Operation extends Enumeration {
  type Operation = Value

  val Create, Update, Delete = Value

  implicit val opReads = __.read[String].map(Operation.withName)
  implicit val opWrites = new Writes[Operation] {
    def writes(op: Operation) = JsString(op.toString)
  }
}

object Entity extends Enumeration {
  type Entity = Value

  val Organization, Team, Alert = Value

  implicit val entityReads = __.read[String].map(Entity.withName)
  implicit val entityWrites = new Writes[Entity] {
    def writes(entity: Entity) = JsString(entity.toString)
  }
}

import com.cave.metrics.data.Entity._
import com.cave.metrics.data.Operation._

/**
 * Class to encapsulate a notification that configuration has changed
 *
 * @param entityType  the type of changed entity
 * @param operation   the type of change that the entity has suffered
 * @param id          the identifier of the entity
 * @param extra       additional data for this notification event
 */
case class Update(entityType: Entity, operation: Operation, id: String, extra: String)

object Update {

  final val KeyEntity = "entity"
  final val KeyOperation = "operation"
  final val KeyId = "id"
  final val KeyExtra = "extra"

  implicit val updateReads: Reads[Update] = (
    (__ \ KeyEntity).read[Entity] and
    (__ \ KeyOperation).read[Operation] and
    (__ \ KeyId).read[String] and
    (__ \ KeyExtra).read[String]
  )(Update.apply _)

  implicit val updateWrites: Writes[Update] = (
    (__ \ KeyEntity).write[Entity] and
    (__ \ KeyOperation).write[Operation] and
    (__ \ KeyId).write[String] and
    (__ \ KeyExtra).write[String]
  )(unlift(Update.unapply))
}


text:
from aimacode.logic import associate
from aimacode.utils import expr

class FluentState():
    """ state object for planning problems as positive and negative fluents

    """

    def __init__(self, pos_list, neg_list):
        self.pos = pos_list
        self.neg = neg_list

    def sentence(self):
        return expr(conjunctive_sentence(self.pos, self.neg))

    def pos_sentence(self):
        return expr(conjunctive_sentence(self.pos, []))

def conjunctive_sentence(pos_list, neg_list):
    """ returns expr conjuntive sentence given positive and negative fluent lists

    :param pos_list: list of fluents
    :param neg_list: list of fluents
    :return: expr sentence of fluent conjunction
        e.g. "At(C1, SFO) ∧ ~At(P1, SFO)"
    """
    clauses = []
    for f in pos_list:
        clauses.append(expr("{}".format(f)))
    for f in neg_list:
        clauses.append(expr("~{}".format(f)))
    return associate('&', clauses)

def encode_state(fs: FluentState, fluent_map: list) -> str:
    """ encode fluents to a string of T/F using mapping

    :param fs: FluentState object
    :param fluent_map: ordered list of possible fluents for the problem
    :return: str eg. "TFFTFT" string of mapped positive and negative fluents
    """
    state_tf = []
    for fluent in fluent_map:
        if fluent in fs.pos:
            state_tf.append('T')
        else:
            state_tf.append('F')
    return "".join(state_tf)

def decode_state(state: str, fluent_map: list) -> FluentState:
    """ decode string of T/F as fluent per mapping

    :param state: str eg. "TFFTFT" string of mapped positive and negative fluents
    :param fluent_map: ordered list of possible fluents for the problem
    :return: fs: FluentState object

    lengths of state string and fluent_map list must be the same
    """
    fs = FluentState([], [])
    for idx, char in enumerate(state):
        if char == 'T':
            fs.pos.append(fluent_map[idx])
        else:
            fs.neg.append(fluent_map[idx])
    return fs


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Designkit-Buttons Default</title>
  <link rel="stylesheet" href="https://unpkg.com/designkit-global@1.1.2/dist/designkit-global.css">
  <link rel="stylesheet" href="https://unpkg.com/designkit-typography@1.1.3/dist/designkit-typography.css">
  <link rel="stylesheet" href="./docs.css">

    <button class="btn btn-default" type="button">Default Button</button>
    Default Link Button


text:
import * as o from '../output/output_ast';
import { OutputContext } from '../util';
/**
 * Convert an object map with `Expression` values into a `LiteralMapExpr`.
 */
export declare function mapToMapExpression(map: {
    [key: string]: o.Expression;
}): o.LiteralMapExpr;
/**
 * Convert metadata into an `Expression` in the given `OutputContext`.
 *
 * This operation will handle arrays, references to symbols, or literal `null` or `undefined`.
 */
export declare function convertMetaToOutput(meta: any, ctx: OutputContext): o.Expression;
export declare function typeWithParameters(type: o.Expression, numParams: number): o.ExpressionType;


text:
namespace blink {

namespace {  // anonymous namespace for ClipboardWriter's derived classes.

// Writes a blob with image/png content to the System Clipboard.
class ClipboardImageWriter final : public ClipboardWriter {
 public:
  ClipboardImageWriter(SystemClipboard* system_clipboard,
                       ClipboardPromise* promise)
      : ClipboardWriter(system_clipboard, promise) {}
  ~ClipboardImageWriter() override = default;

 private:
  void DecodeOnBackgroundThread(
      scoped_refptr<base::SingleThreadTaskRunner> task_runner,
      DOMArrayBuffer* png_data) override {
    DCHECK(!IsMainThread());
    std::unique_ptr<ImageDecoder> decoder = ImageDecoder::Create(
        SegmentReader::CreateFromSkData(SkData::MakeWithoutCopy(
            png_data->Data(), png_data->ByteLengthAsSizeT())),
        true, ImageDecoder::kAlphaPremultiplied, ImageDecoder::kDefaultBitDepth,
        ColorBehavior::Tag(), ImageDecoder::OverrideAllowDecodeToYuv::kDeny);
    sk_sp<SkImage> image = nullptr;
    // |decoder| is nullptr if |png_data| doesn't begin with the PNG signature.
    if (decoder)
      image = ImageBitmap::GetSkImageFromDecoder(std::move(decoder));

    PostCrossThreadTask(
        *task_runner, FROM_HERE,
        CrossThreadBindOnce(&ClipboardImageWriter::Write,
                            WrapCrossThreadPersistent(this), std::move(image)));
  }
  void Write(sk_sp<SkImage> image) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (!image) {
      promise_->RejectFromReadOrDecodeFailure();
      return;
    }
    SkBitmap bitmap;
    image->asLegacyBitmap(&bitmap);
    system_clipboard()->WriteImage(std::move(bitmap));
    promise_->CompleteWriteRepresentation();
  }
};

// Writes a blob with text/plain content to the System Clipboard.
class ClipboardTextWriter final : public ClipboardWriter {
 public:
  ClipboardTextWriter(SystemClipboard* system_clipboard,
                      ClipboardPromise* promise)
      : ClipboardWriter(system_clipboard, promise) {}
  ~ClipboardTextWriter() override = default;

 private:
  void DecodeOnBackgroundThread(
      scoped_refptr<base::SingleThreadTaskRunner> task_runner,
      DOMArrayBuffer* raw_data) override {
    DCHECK(!IsMainThread());

    String wtf_string =
        String::FromUTF8(reinterpret_cast<const LChar*>(raw_data->Data()),
                         raw_data->ByteLengthAsSizeT());
    DCHECK(wtf_string.IsSafeToSendToAnotherThread());
    PostCrossThreadTask(*task_runner, FROM_HERE,
                        CrossThreadBindOnce(&ClipboardTextWriter::Write,
                                            WrapCrossThreadPersistent(this),
                                            std::move(wtf_string)));
  }
  void Write(const String& text) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    system_clipboard()->WritePlainText(text);

    promise_->CompleteWriteRepresentation();
  }
};

// Writes a blob with arbitrary, unsanitized content to the System Clipboard.
class ClipboardRawDataWriter final : public ClipboardWriter {
 public:
  ClipboardRawDataWriter(RawSystemClipboard* raw_system_clipboard,
                         ClipboardPromise* promise,
                         String mime_type)
      : ClipboardWriter(raw_system_clipboard, promise), mime_type_(mime_type) {}
  ~ClipboardRawDataWriter() override = default;

 private:
  // Unfortunately, in order to use the same ClipboardWriter base,
  // ClipboardRawDataWriter does need to have these extra 2 thread hops.
  void DecodeOnBackgroundThread(
      scoped_refptr<base::SingleThreadTaskRunner> task_runner,
      DOMArrayBuffer* raw_data) override {
    DCHECK(!IsMainThread());

    PostCrossThreadTask(
        *task_runner, FROM_HERE,
        CrossThreadBindOnce(&ClipboardRawDataWriter::Write,
                            WrapCrossThreadPersistent(this),
                            WrapCrossThreadPersistent(raw_data)));
  }

  void Write(DOMArrayBuffer* raw_data) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    if (raw_data->ByteLengthAsSizeT() >=
        mojom::blink::RawClipboardHost::kMaxDataSize) {
      promise_->RejectFromReadOrDecodeFailure();
      return;
    }

    uint8_t* raw_data_pointer = static_cast<uint8_t*>(raw_data->Data());
    mojo_base::BigBuffer buffer(std::vector<uint8_t>(
        raw_data_pointer, raw_data_pointer + raw_data->ByteLengthAsSizeT()));

    raw_system_clipboard()->Write(mime_type_, std::move(buffer));

    promise_->CompleteWriteRepresentation();
  }

  String mime_type_;
};

}  // anonymous namespace

// ClipboardWriter functions.

// static
ClipboardWriter* ClipboardWriter::Create(SystemClipboard* system_clipboard,
                                         const String& mime_type,
                                         ClipboardPromise* promise) {
  if (mime_type == kMimeTypeImagePng) {
    return MakeGarbageCollected<ClipboardImageWriter>(system_clipboard,
                                                      promise);
  }
  if (mime_type == kMimeTypeTextPlain)
    return MakeGarbageCollected<ClipboardTextWriter>(system_clipboard, promise);

  NOTREACHED() << "Type " << mime_type << " was not implemented";
  return nullptr;
}

// static
ClipboardWriter* ClipboardWriter::Create(
    RawSystemClipboard* raw_system_clipboard,
    const String& mime_type,
    ClipboardPromise* promise) {
  DCHECK(base::FeatureList::IsEnabled(features::kRawClipboard));

  return MakeGarbageCollected<ClipboardRawDataWriter>(raw_system_clipboard,
                                                      promise, mime_type);
}

ClipboardWriter::ClipboardWriter(SystemClipboard* system_clipboard,
                                 ClipboardPromise* promise)
    : ClipboardWriter(system_clipboard, nullptr, promise) {}

ClipboardWriter::ClipboardWriter(RawSystemClipboard* raw_system_clipboard,
                                 ClipboardPromise* promise)
    : ClipboardWriter(nullptr, raw_system_clipboard, promise) {}

ClipboardWriter::ClipboardWriter(SystemClipboard* system_clipboard,
                                 RawSystemClipboard* raw_system_clipboard,
                                 ClipboardPromise* promise)
    : promise_(promise),
      clipboard_task_runner_(promise->GetExecutionContext()->GetTaskRunner(
          TaskType::kUserInteraction)),
      file_reading_task_runner_(promise->GetExecutionContext()->GetTaskRunner(
          TaskType::kFileReading)),
      system_clipboard_(system_clipboard),
      raw_system_clipboard_(raw_system_clipboard) {}

ClipboardWriter::~ClipboardWriter() = default;

// static
bool ClipboardWriter::IsValidType(const String& type, bool is_raw) {
  if (is_raw)
    return type.length() < mojom::blink::RawClipboardHost::kMaxFormatSize;

  // TODO(https://crbug.com/931839): Add support for text/html and other
  // types.
  return type == kMimeTypeImagePng || type == kMimeTypeTextPlain;
}

void ClipboardWriter::WriteToSystem(Blob* blob) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(!file_reader_);
  file_reader_ = std::make_unique<FileReaderLoader>(
      FileReaderLoader::kReadAsArrayBuffer, this,
      std::move(file_reading_task_runner_));
  file_reader_->Start(blob->GetBlobDataHandle());
}

// FileReaderLoaderClient implementation.

void ClipboardWriter::DidStartLoading() {}
void ClipboardWriter::DidReceiveData() {}

void ClipboardWriter::DidFinishLoading() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DOMArrayBuffer* array_buffer = file_reader_->ArrayBufferResult();
  DCHECK(array_buffer);
  file_reader_.reset();

  worker_pool::PostTask(
      FROM_HERE, CrossThreadBindOnce(&ClipboardWriter::DecodeOnBackgroundThread,
                                     WrapCrossThreadPersistent(this),
                                     clipboard_task_runner_,
                                     WrapCrossThreadPersistent(array_buffer)));
}

void ClipboardWriter::DidFail(FileErrorCode error_code) {
  promise_->RejectFromReadOrDecodeFailure();
}

void ClipboardWriter::Trace(Visitor* visitor) {
  visitor->Trace(promise_);
  visitor->Trace(system_clipboard_);
  visitor->Trace(raw_system_clipboard_);
}

}  // namespace blink


text:
(function() {
  var Browsers, Declaration, Prefixer, utils, vendor,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  Prefixer = require('./prefixer');

  Browsers = require('./browsers');

  vendor = require('postcss/lib/vendor');

  utils = require('./utils');

  Declaration = (function(_super) {
    __extends(Declaration, _super);

    function Declaration() {
      return Declaration.__super__.constructor.apply(this, arguments);
    }

    Declaration.prototype.check = function(decl) {
      return true;
    };

    Declaration.prototype.prefixed = function(prop, prefix) {
      return prefix + prop;
    };

    Declaration.prototype.normalize = function(prop) {
      return prop;
    };

    Declaration.prototype.otherPrefixes = function(value, prefix) {
      var other, _i, _len, _ref;
      _ref = Browsers.prefixes();
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        other = _ref[_i];
        if (other === prefix) {
          continue;
        }
        if (value.indexOf(other) !== -1) {
          return true;
        }
      }
      return false;
    };

    Declaration.prototype.set = function(decl, prefix) {
      decl.prop = this.prefixed(decl.prop, prefix);
      return decl;
    };

    Declaration.prototype.needCascade = function(decl) {
      return decl._autoprefixerCascade || (decl._autoprefixerCascade = !!this.all.options.cascade && decl.before.indexOf("\n") !== -1);
    };

    Declaration.prototype.maxPrefixed = function(prefixes, decl) {
      var max, prefix, _i, _len;
      if (decl._autoprefixerMax) {
        return decl._autoprefixerMax;
      }
      max = 0;
      for (_i = 0, _len = prefixes.length; _i < _len; _i++) {
        prefix = prefixes[_i];
        prefix = utils.removeNote(prefix);
        if (prefix.length > max) {
          max = prefix.length;
        }
      }
      return decl._autoprefixerMax = max;
    };

    Declaration.prototype.calcBefore = function(prefixes, decl, prefix) {
      var before, diff, i, max, _i;
      if (prefix == null) {
        prefix = '';
      }
      before = decl.before;
      max = this.maxPrefixed(prefixes, decl);
      diff = max - utils.removeNote(prefix).length;
      for (i = _i = 0; 0 <= diff ? _i < diff : _i > diff; i = 0 <= diff ? ++_i : --_i) {
        before += ' ';
      }
      return before;
    };

    Declaration.prototype.restoreBefore = function(decl) {
      var lines, min;
      lines = decl.before.split("\n");
      min = lines[lines.length - 1];
      this.all.group(decl).up(function(prefixed) {
        var array, last;
        array = prefixed.before.split("\n");
        last = array[array.length - 1];
        if (last.length < min.length) {
          return min = last;
        }
      });
      lines[lines.length - 1] = min;
      return decl.before = lines.join("\n");
    };

    Declaration.prototype.insert = function(decl, prefix, prefixes) {
      var cloned;
      cloned = this.set(this.clone(decl), prefix);
      if (!cloned) {
        return;
      }
      if (this.needCascade(decl)) {
        cloned.before = this.calcBefore(prefixes, decl, prefix);
      }
      return decl.parent.insertBefore(decl, cloned);
    };

    Declaration.prototype.add = function(decl, prefix, prefixes) {
      var already, prefixed;
      prefixed = this.prefixed(decl.prop, prefix);
      already = this.all.group(decl).up(function(i) {
        return i.prop === prefixed;
      });
      if (already || this.otherPrefixes(decl.value, prefix)) {
        return;
      }
      return this.insert(decl, prefix, prefixes);
    };

    Declaration.prototype.process = function(decl) {
      var prefixes;
      if (this.needCascade(decl)) {
        this.restoreBefore(decl);
        if (prefixes = Declaration.__super__.process.apply(this, arguments)) {
          return decl.before = this.calcBefore(prefixes, decl);
        }
      } else {
        return Declaration.__super__.process.apply(this, arguments);
      }
    };

    Declaration.prototype.old = function(prop, prefix) {
      return [this.prefixed(prop, prefix)];
    };

    return Declaration;

  })(Prefixer);

  module.exports = Declaration;

}).call(this);


text:
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Chris Saari <saari@netscape.com>
 *   Apple Computer
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

/*
The Graphics Interchange Format(c) is the copyright property of CompuServe
Incorporated. Only CompuServe Incorporated is authorized to define, redefine,
enhance, alter, modify or change in any way the definition of the format.

CompuServe Incorporated hereby grants a limited, non-exclusive, royalty-free
license for the use of the Graphics Interchange Format(sm) in computer
software; computer software utilizing GIF(sm) must acknowledge ownership of the
Graphics Interchange Format and its Service Mark by CompuServe Incorporated, in
User and Technical Documentation. Computer software utilizing GIF, which is
distributed or may be distributed without User or Technical Documentation must
display to the screen or printer a message acknowledging ownership of the
Graphics Interchange Format and the Service Mark by CompuServe Incorporated; in
this case, the acknowledgement may be displayed in an opening screen or leading
banner, or a closing screen or trailing banner. A message such as the following
may be used:

    "The Graphics Interchange Format(c) is the Copyright property of
    CompuServe Incorporated. GIF(sm) is a Service Mark property of
    CompuServe Incorporated."

For further information, please contact :

    CompuServe Incorporated
    Graphics Technology Department
    5000 Arlington Center Boulevard
    Columbus, Ohio  43220
    U. S. A.

CompuServe Incorporated maintains a mailing list with all those individuals and
organizations who wish to receive copies of this document when it is corrected
or revised. This service is offered free of charge; please provide us with your
mailing address.
*/

#include "config.h"
#include "platform/image-decoders/gif/GIFImageReader.h"

#include <string.h>
#include "platform/graphics/ImageSource.h"

using blink::GIFImageDecoder;

// GETN(n, s) requests at least 'n' bytes available from 'q', at start of state 's'.
//
// Note, the hold will never need to be bigger than 256 bytes to gather up in the hold,
// as each GIF block (except colormaps) can never be bigger than 256 bytes.
// Colormaps are directly copied in the resp. global_colormap or dynamically allocated local_colormap.
// So a fixed buffer in GIFImageReader is good enough.
// This buffer is only needed to copy left-over data from one GifWrite call to the next
#define GETN(n, s) \
    do { \
        m_bytesToConsume = (n); \
        m_state = (s); \
    } while (0)

// Get a 16-bit value stored in little-endian format.
#define GETINT16(p)   ((p)[1]<<8|(p)[0])

// Send the data to the display front-end.
bool GIFLZWContext::outputRow(GIFRow::const_iterator rowBegin)
{
    int drowStart = irow;
    int drowEnd = irow;

    // Haeberli-inspired hack for interlaced GIFs: Replicate lines while
    // displaying to diminish the "venetian-blind" effect as the image is
    // loaded. Adjust pixel vertical positions to avoid the appearance of the
    // image crawling up the screen as successive passes are drawn.
    if (m_frameContext->progressiveDisplay() && m_frameContext->interlaced() && ipass < 4) {
        unsigned rowDup = 0;
        unsigned rowShift = 0;

        switch (ipass) {
        case 1:
            rowDup = 7;
            rowShift = 3;
            break;
        case 2:
            rowDup = 3;
            rowShift = 1;
            break;
        case 3:
            rowDup = 1;
            rowShift = 0;
            break;
        default:
            break;
        }

        drowStart -= rowShift;
        drowEnd = drowStart + rowDup;

        // Extend if bottom edge isn't covered because of the shift upward.
        if (((m_frameContext->height() - 1) - drowEnd) <= rowShift)
            drowEnd = m_frameContext->height() - 1;

        // Clamp first and last rows to upper and lower edge of image.
        if (drowStart < 0)
            drowStart = 0;

        if ((unsigned)drowEnd >= m_frameContext->height())
            drowEnd = m_frameContext->height() - 1;
    }

    // Protect against too much image data.
    if ((unsigned)drowStart >= m_frameContext->height())
        return true;

    // CALLBACK: Let the client know we have decoded a row.
    if (!m_client->haveDecodedRow(m_frameContext->frameId(), rowBegin, m_frameContext->width(),
        drowStart, drowEnd - drowStart + 1, m_frameContext->progressiveDisplay() && m_frameContext->interlaced() && ipass > 1))
        return false;

    if (!m_frameContext->interlaced())
        irow++;
    else {
        do {
            switch (ipass) {
            case 1:
                irow += 8;
                if (irow >= m_frameContext->height()) {
                    ipass++;
                    irow = 4;
                }
                break;

            case 2:
                irow += 8;
                if (irow >= m_frameContext->height()) {
                    ipass++;
                    irow = 2;
                }
                break;

            case 3:
                irow += 4;
                if (irow >= m_frameContext->height()) {
                    ipass++;
                    irow = 1;
                }
                break;

            case 4:
                irow += 2;
                if (irow >= m_frameContext->height()) {
                    ipass++;
                    irow = 0;
                }
                break;

            default:
                break;
            }
        } while (irow > (m_frameContext->height() - 1));
    }
    return true;
}

// Perform Lempel-Ziv-Welch decoding.
// Returns true if decoding was successful. In this case the block will have been completely consumed and/or rowsRemaining will be 0.
// Otherwise, decoding failed; returns false in this case, which will always cause the GIFImageReader to set the "decode failed" flag.
bool GIFLZWContext::doLZW(const unsigned char* block, size_t bytesInBlock)
{
    const size_t width = m_frameContext->width();

    if (rowIter == rowBuffer.end())
        return true;

    for (const unsigned char* ch = block; bytesInBlock-- > 0; ch++) {
        // Feed the next byte into the decoder's 32-bit input buffer.
        datum += ((int) *ch) << bits;
        bits += 8;

        // Check for underflow of decoder's 32-bit input buffer.
        while (bits >= codesize) {
            // Get the leading variable-length symbol from the data stream.
            int code = datum & codemask;
            datum >>= codesize;
            bits -= codesize;

            // Reset the dictionary to its original state, if requested.
            if (code == clearCode) {
                codesize = m_frameContext->dataSize() + 1;
                codemask = (1 << codesize) - 1;
                avail = clearCode + 2;
                oldcode = -1;
                continue;
            }

            // Check for explicit end-of-stream code.
            if (code == (clearCode + 1)) {
                // end-of-stream should only appear after all image data.
                if (!rowsRemaining)
                    return true;
                return false;
            }

            const int tempCode = code;
            unsigned short codeLength = 0;
            if (code < avail) {
                // This is a pre-existing code, so we already know what it
                // encodes.
                codeLength = suffixLength[code];
                rowIter += codeLength;
            } else if (code == avail && oldcode != -1) {
                // This is a new code just being added to the dictionary.
                // It must encode the contents of the previous code, plus
                // the first character of the previous code again.
                codeLength = suffixLength[oldcode] + 1;
                rowIter += codeLength;
                *--rowIter = firstchar;
                code = oldcode;
            } else {
                // This is an invalid code. The dictionary is just initialized
                // and the code is incomplete. We don't know how to handle
                // this case.
                return false;
            }

            while (code >= clearCode) {
                *--rowIter = suffix[code];
                code = prefix[code];
            }

            *--rowIter = firstchar = suffix[code];

            // Define a new codeword in the dictionary as long as we've read
            // more than one value from the stream.
            if (avail < MAX_DICTIONARY_ENTRIES && oldcode != -1) {
                prefix[avail] = oldcode;
                suffix[avail] = firstchar;
                suffixLength[avail] = suffixLength[oldcode] + 1;
                ++avail;

                // If we've used up all the codewords of a given length
                // increase the length of codewords by one bit, but don't
                // exceed the specified maximum codeword size.
                if (!(avail & codemask) && avail < MAX_DICTIONARY_ENTRIES) {
                    ++codesize;
                    codemask += avail;
                }
            }
            oldcode = tempCode;
            rowIter += codeLength;

            // Output as many rows as possible.
            GIFRow::iterator rowBegin = rowBuffer.begin();
            for (; rowBegin + width <= rowIter; rowBegin += width) {
                if (!outputRow(rowBegin))
                    return false;
                rowsRemaining--;
                if (!rowsRemaining)
                    return true;
            }

            if (rowBegin != rowBuffer.begin()) {
                // Move the remaining bytes to the beginning of the buffer.
                const size_t bytesToCopy = rowIter - rowBegin;
                memcpy(rowBuffer.begin(), rowBegin, bytesToCopy);
                rowIter = rowBuffer.begin() + bytesToCopy;
            }
        }
    }
    return true;
}

void GIFColorMap::buildTable(const unsigned char* data, size_t length)
{
    if (!m_isDefined || !m_table.isEmpty())
        return;

    RELEASE_ASSERT(m_position + m_colors * BYTES_PER_COLORMAP_ENTRY <= length);
    const unsigned char* srcColormap = data + m_position;
    m_table.resize(m_colors);
    for (Table::iterator iter = m_table.begin(); iter != m_table.end(); ++iter) {
        *iter = SkPackARGB32NoCheck(255, srcColormap[0], srcColormap[1], srcColormap[2]);
        srcColormap += BYTES_PER_COLORMAP_ENTRY;
    }
}

// Perform decoding for this frame. frameDecoded will be true if the entire frame is decoded.
// Returns false if a decoding error occurred. This is a fatal error and causes the GIFImageReader to set the "decode failed" flag.
// Otherwise, either not enough data is available to decode further than before, or the new data has been decoded successfully; returns true in this case.
bool GIFFrameContext::decode(const unsigned char* data, size_t length, blink::GIFImageDecoder* client, bool* frameDecoded)
{
    m_localColorMap.buildTable(data, length);

    *frameDecoded = false;
    if (!m_lzwContext) {
        // Wait for more data to properly initialize GIFLZWContext.
        if (!isDataSizeDefined() || !isHeaderDefined())
            return true;

        m_lzwContext = adoptPtr(new GIFLZWContext(client, this));
        if (!m_lzwContext->prepareToDecode()) {
            m_lzwContext.clear();
            return false;
        }

        m_currentLzwBlock = 0;
    }

    // Some bad GIFs have extra blocks beyond the last row, which we don't want to decode.
    while (m_currentLzwBlock < m_lzwBlocks.size() && m_lzwContext->hasRemainingRows()) {
        size_t blockPosition = m_lzwBlocks[m_currentLzwBlock].blockPosition;
        size_t blockSize = m_lzwBlocks[m_currentLzwBlock].blockSize;
        if (blockPosition + blockSize > length)
            return false;
        if (!m_lzwContext->doLZW(data + blockPosition, blockSize))
            return false;
        ++m_currentLzwBlock;
    }

    // If this frame is data complete then the previous loop must have completely decoded all LZW blocks.
    // There will be no more decoding for this frame so it's time to cleanup.
    if (isComplete()) {
        *frameDecoded = true;
        m_lzwContext.clear();
    }
    return true;
}

// Decode a frame.
// This method uses GIFFrameContext:decode() to decode the frame; decoding error is reported to client as a critical failure.
// Return true if decoding has progressed. Return false if an error has occurred.
bool GIFImageReader::decode(size_t frameIndex)
{
    m_globalColorMap.buildTable(data(0), m_data->size());

    bool frameDecoded = false;
    GIFFrameContext* currentFrame = m_frames[frameIndex].get();

    return currentFrame->decode(data(0), m_data->size(), m_client, &frameDecoded)
        && (!frameDecoded || m_client->frameComplete(frameIndex));
}

bool GIFImageReader::parse(GIFImageDecoder::GIFParseQuery query)
{
    ASSERT(m_bytesRead <= m_data->size());

    return parseData(m_bytesRead, m_data->size() - m_bytesRead, query);
}

// Parse incoming GIF data stream into internal data structures.
// Return true if parsing has progressed or there is not enough data.
// Return false if a fatal error is encountered.
bool GIFImageReader::parseData(size_t dataPosition, size_t len, GIFImageDecoder::GIFParseQuery query)
{
    if (!len) {
        // No new data has come in since the last call, just ignore this call.
        return true;
    }

    if (len < m_bytesToConsume)
        return true;

    // This loop reads as many components from |m_data| as possible.
    // At the beginning of each iteration, dataPosition will be advanced by m_bytesToConsume to
    // point to the next component. len will be decremented accordingly.
    while (len >= m_bytesToConsume) {
        const size_t currentComponentPosition = dataPosition;
        const unsigned char* currentComponent = data(dataPosition);

        // Mark the current component as consumed. Note that currentComponent will remain pointed at this
        // component until the next loop iteration.
        dataPosition += m_bytesToConsume;
        len -= m_bytesToConsume;

        switch (m_state) {
        case GIFLZW:
            ASSERT(!m_frames.isEmpty());
            // m_bytesToConsume is the current component size because it hasn't been updated.
            m_frames.last()->addLzwBlock(currentComponentPosition, m_bytesToConsume);
            GETN(1, GIFSubBlock);
            break;

        case GIFLZWStart: {
            ASSERT(!m_frames.isEmpty());
            m_frames.last()->setDataSize(*currentComponent);
            GETN(1, GIFSubBlock);
            break;
        }

        case GIFType: {
            // All GIF files begin with "GIF87a" or "GIF89a".
            if (!strncmp((char*)currentComponent, "GIF89a", 6))
                m_version = 89;
            else if (!strncmp((char*)currentComponent, "GIF87a", 6))
                m_version = 87;
            else
                return false;
            GETN(7, GIFGlobalHeader);
            break;
        }

        case GIFGlobalHeader: {
            // This is the height and width of the "screen" or frame into which
            // images are rendered. The individual images can be smaller than
            // the screen size and located with an origin anywhere within the
            // screen.
            // Note that we don't inform the client of the size yet, as it might
            // change after we read the first frame's image header.
            m_screenWidth = GETINT16(currentComponent);
            m_screenHeight = GETINT16(currentComponent + 2);

            const size_t globalColorMapColors = 2 << (currentComponent[4] & 0x07);

            if ((currentComponent[4] & 0x80) && globalColorMapColors > 0) { /* global map */
                m_globalColorMap.setTablePositionAndSize(dataPosition, globalColorMapColors);
                GETN(BYTES_PER_COLORMAP_ENTRY * globalColorMapColors, GIFGlobalColormap);
                break;
            }

            GETN(1, GIFImageStart);
            break;
        }

        case GIFGlobalColormap: {
            m_globalColorMap.setDefined();
            GETN(1, GIFImageStart);
            break;
        }

        case GIFImageStart: {
            if (*currentComponent == '!') { // extension.
                GETN(2, GIFExtension);
                break;
            }

            if (*currentComponent == ',') { // image separator.
                GETN(9, GIFImageHeader);
                break;
            }

            // If we get anything other than ',' (image separator), '!'
            // (extension), or ';' (trailer), there is extraneous data
            // between blocks. The GIF87a spec tells us to keep reading
            // until we find an image separator, but GIF89a says such
            // a file is corrupt. We follow Mozilla's implementation and
            // proceed as if the file were correctly terminated, so the
            // GIF will display.
            GETN(0, GIFDone);
            break;
        }

        case GIFExtension: {
            size_t bytesInBlock = currentComponent[1];
            GIFState exceptionState = GIFSkipBlock;

            switch (*currentComponent) {
            case 0xf9:
                exceptionState = GIFControlExtension;
                // The GIF spec mandates that the GIFControlExtension header block length is 4 bytes,
                // and the parser for this block reads 4 bytes, so we must enforce that the buffer
                // contains at least this many bytes. If the GIF specifies a different length, we
                // allow that, so long as it's larger; the additional data will simply be ignored.
                bytesInBlock = std::max(bytesInBlock, static_cast<size_t>(4));
                break;

            // The GIF spec also specifies the lengths of the following two extensions' headers
            // (as 12 and 11 bytes, respectively). Because we ignore the plain text extension entirely
            // and sanity-check the actual length of the application extension header before reading it,
            // we allow GIFs to deviate from these values in either direction. This is important for
            // real-world compatibility, as GIFs in the wild exist with application extension headers
            // that are both shorter and longer than 11 bytes.
            case 0x01:
                // ignoring plain text extension
                break;

            case 0xff:
                exceptionState = GIFApplicationExtension;
                break;

            case 0xfe:
                exceptionState = GIFConsumeComment;
                break;
            }

            if (bytesInBlock)
                GETN(bytesInBlock, exceptionState);
            else
                GETN(1, GIFImageStart);
            break;
        }

        case GIFConsumeBlock: {
            if (!*currentComponent)
                GETN(1, GIFImageStart);
            else
                GETN(*currentComponent, GIFSkipBlock);
            break;
        }

        case GIFSkipBlock: {
            GETN(1, GIFConsumeBlock);
            break;
        }

        case GIFControlExtension: {
            addFrameIfNecessary();
            GIFFrameContext* currentFrame = m_frames.last().get();
            if (*currentComponent & 0x1)
                currentFrame->setTransparentPixel(currentComponent[3]);

            // We ignore the "user input" bit.

            // NOTE: This relies on the values in the FrameDisposalMethod enum
            // matching those in the GIF spec!
            int disposalMethod = ((*currentComponent) >> 2) & 0x7;
            if (disposalMethod < 4) {
                currentFrame->setDisposalMethod(static_cast<blink::ImageFrame::DisposalMethod>(disposalMethod));
            } else if (disposalMethod == 4) {
                // Some specs say that disposal method 3 is "overwrite previous", others that setting
                // the third bit of the field (i.e. method 4) is. We map both to the same value.
                currentFrame->setDisposalMethod(blink::ImageFrame::DisposeOverwritePrevious);
            }
            currentFrame->setDelayTime(GETINT16(currentComponent + 1) * 10);
            GETN(1, GIFConsumeBlock);
            break;
        }

        case GIFCommentExtension: {
            if (*currentComponent)
                GETN(*currentComponent, GIFConsumeComment);
            else
                GETN(1, GIFImageStart);
            break;
        }

        case GIFConsumeComment: {
            GETN(1, GIFCommentExtension);
            break;
        }

        case GIFApplicationExtension: {
            // Check for netscape application extension.
            if (m_bytesToConsume == 11
                && (!strncmp((char*)currentComponent, "NETSCAPE2.0", 11) || !strncmp((char*)currentComponent, "ANIMEXTS1.0", 11)))
                GETN(1, GIFNetscapeExtensionBlock);
            else
                GETN(1, GIFConsumeBlock);
            break;
        }

        // Netscape-specific GIF extension: animation looping.
        case GIFNetscapeExtensionBlock: {
            // GIFConsumeNetscapeExtension always reads 3 bytes from the stream; we should at least wait for this amount.
            if (*currentComponent)
                GETN(std::max(3, static_cast<int>(*currentComponent)), GIFConsumeNetscapeExtension);
            else
                GETN(1, GIFImageStart);
            break;
        }

        // Parse netscape-specific application extensions
        case GIFConsumeNetscapeExtension: {
            int netscapeExtension = currentComponent[0] & 7;

            // Loop entire animation specified # of times. Only read the loop count during the first iteration.
            if (netscapeExtension == 1) {
                m_loopCount = GETINT16(currentComponent + 1);

                // Zero loop count is infinite animation loop request.
                if (!m_loopCount)
                    m_loopCount = blink::cAnimationLoopInfinite;

                GETN(1, GIFNetscapeExtensionBlock);
            } else if (netscapeExtension == 2) {
                // Wait for specified # of bytes to enter buffer.

                // Don't do this, this extension doesn't exist (isn't used at all)
                // and doesn't do anything, as our streaming/buffering takes care of it all...
                // See: http://semmix.pl/color/exgraf/eeg24.htm
                GETN(1, GIFNetscapeExtensionBlock);
            } else {
                // 0,3-7 are yet to be defined netscape extension codes
                return false;
            }
            break;
        }

        case GIFImageHeader: {
            unsigned height, width, xOffset, yOffset;

            /* Get image offsets, with respect to the screen origin */
            xOffset = GETINT16(currentComponent);
            yOffset = GETINT16(currentComponent + 2);

            /* Get image width and height. */
            width  = GETINT16(currentComponent + 4);
            height = GETINT16(currentComponent + 6);

            // Some GIF files have frames that don't fit in the specified
            // overall image size. For the first frame, we can simply enlarge
            // the image size to allow the frame to be visible.  We can't do
            // this on subsequent frames because the rest of the decoding
            // infrastructure assumes the image size won't change as we
            // continue decoding, so any subsequent frames that are even
            // larger will be cropped.
            // Luckily, handling just the first frame is sufficient to deal
            // with most cases, e.g. ones where the image size is erroneously
            // set to zero, since usually the first frame completely fills
            // the image.
            if (currentFrameIsFirstFrame()) {
                m_screenHeight = std::max(m_screenHeight, yOffset + height);
                m_screenWidth = std::max(m_screenWidth, xOffset + width);
            }

            // Inform the client of the final size.
            if (!m_sentSizeToClient && m_client && !m_client->setSize(m_screenWidth, m_screenHeight))
                return false;
            m_sentSizeToClient = true;

            if (query == GIFImageDecoder::GIFSizeQuery) {
                // The decoder needs to stop. Hand back the number of bytes we consumed from
                // buffer minus 9 (the amount we consumed to read the header).
                setRemainingBytes(len + 9);
                GETN(9, GIFImageHeader);
                return true;
            }

            addFrameIfNecessary();
            GIFFrameContext* currentFrame = m_frames.last().get();

            currentFrame->setHeaderDefined();

            // Work around more broken GIF files that have zero image width or
            // height.
            if (!height || !width) {
                height = m_screenHeight;
                width = m_screenWidth;
                if (!height || !width)
                    return false;
            }
            currentFrame->setRect(xOffset, yOffset, width, height);
            currentFrame->setInterlaced(currentComponent[8] & 0x40);

            // Overlaying interlaced, transparent GIFs over
            // existing image data using the Haeberli display hack
            // requires saving the underlying image in order to
            // avoid jaggies at the transparency edges. We are
            // unprepared to deal with that, so don't display such
            // images progressively. Which means only the first
            // frame can be progressively displayed.
            // FIXME: It is possible that a non-transparent frame
            // can be interlaced and progressively displayed.
            currentFrame->setProgressiveDisplay(currentFrameIsFirstFrame());

            const bool isLocalColormapDefined = currentComponent[8] & 0x80;
            if (isLocalColormapDefined) {
                // The three low-order bits of currentComponent[8] specify the bits per pixel.
                const size_t numColors = 2 << (currentComponent[8] & 0x7);
                currentFrame->localColorMap().setTablePositionAndSize(dataPosition, numColors);
                GETN(BYTES_PER_COLORMAP_ENTRY * numColors, GIFImageColormap);
                break;
            }

            GETN(1, GIFLZWStart);
            break;
        }

        case GIFImageColormap: {
            ASSERT(!m_frames.isEmpty());
            m_frames.last()->localColorMap().setDefined();
            GETN(1, GIFLZWStart);
            break;
        }

        case GIFSubBlock: {
            const size_t bytesInBlock = *currentComponent;
            if (bytesInBlock)
                GETN(bytesInBlock, GIFLZW);
            else {
                // Finished parsing one frame; Process next frame.
                ASSERT(!m_frames.isEmpty());
                // Note that some broken GIF files do not have enough LZW blocks to fully
                // decode all rows but we treat it as frame complete.
                m_frames.last()->setComplete();
                GETN(1, GIFImageStart);
            }
            break;
        }

        case GIFDone: {
            m_parseCompleted = true;
            return true;
        }

        default:
            // We shouldn't ever get here.
            return false;
            break;
        }
    }

    setRemainingBytes(len);
    return true;
}

void GIFImageReader::setRemainingBytes(size_t remainingBytes)
{
    ASSERT(remainingBytes <= m_data->size());
    m_bytesRead = m_data->size() - remainingBytes;
}

void GIFImageReader::addFrameIfNecessary()
{
    if (m_frames.isEmpty() || m_frames.last()->isComplete())
        m_frames.append(adoptPtr(new GIFFrameContext(m_frames.size())));
}

// FIXME: Move this method to close to doLZW().
bool GIFLZWContext::prepareToDecode()
{
    ASSERT(m_frameContext->isDataSizeDefined() && m_frameContext->isHeaderDefined());

    // Since we use a codesize of 1 more than the datasize, we need to ensure
    // that our datasize is strictly less than the MAX_DICTIONARY_ENTRY_BITS.
    if (m_frameContext->dataSize() >= MAX_DICTIONARY_ENTRY_BITS)
        return false;
    clearCode = 1 << m_frameContext->dataSize();
    avail = clearCode + 2;
    oldcode = -1;
    codesize = m_frameContext->dataSize() + 1;
    codemask = (1 << codesize) - 1;
    datum = bits = 0;
    ipass = m_frameContext->interlaced() ? 1 : 0;
    irow = 0;

    // We want to know the longest sequence encodable by a dictionary with
    // MAX_DICTIONARY_ENTRIES entries. If we ignore the need to encode the base
    // values themselves at the beginning of the dictionary, as well as the need
    // for a clear code or a termination code, we could use every entry to
    // encode a series of multiple values. If the input value stream looked
    // like "AAAAA..." (a long string of just one value), the first dictionary
    // entry would encode AA, the next AAA, the next AAAA, and so forth. Thus
    // the longest sequence would be MAX_DICTIONARY_ENTRIES + 1 values.
    //
    // However, we have to account for reserved entries. The first |datasize|
    // bits are reserved for the base values, and the next two entries are
    // reserved for the clear code and termination code. In theory a GIF can
    // set the datasize to 0, meaning we have just two reserved entries, making
    // the longest sequence (MAX_DICTIONARY_ENTIRES + 1) - 2 values long. Since
    // each value is a byte, this is also the number of bytes in the longest
    // encodable sequence.
    const size_t maxBytes = MAX_DICTIONARY_ENTRIES - 1;

    // Now allocate the output buffer. We decode directly into this buffer
    // until we have at least one row worth of data, then call outputRow().
    // This means worst case we may have (row width - 1) bytes in the buffer
    // and then decode a sequence |maxBytes| long to append.
    rowBuffer.resize(m_frameContext->width() - 1 + maxBytes);
    rowIter = rowBuffer.begin();
    rowsRemaining = m_frameContext->height();

    // Clearing the whole suffix table lets us be more tolerant of bad data.
    for (int i = 0; i < clearCode; ++i) {
        suffix[i] = i;
        suffixLength[i] = 1;
    }
    return true;
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
       >

	 <context:annotation-config/>
	 <context:component-scan base-package="com.app.domain.model.types"/>

	<!-- User accounts -->

	<bean id="userAccount1" class="com.app.infrastructure.security.UserAccount">
		<property name="username" value="profesor10" />
		<property name="password" value="21232f297a57a5a743894a0e4a801fc3" />
		<property name="authorities">
			<list>
				<bean class="com.app.infrastructure.security.Authority">
					<property name="authority" value="PROFESOR" />
				</bean>
			</list>
		</property>
	</bean>
	<bean id="userAccount3" class="com.app.infrastructure.security.UserAccount">
		<property name="username" value="profesor2" />
		<property name="password" value="21232f297a57a5a743894a0e4a801fc3" />
		<property name="authorities">
			<list>
				<bean class="com.app.infrastructure.security.Authority">
					<property name="authority" value="PROFESOR" />
				</bean>
			</list>
		</property>
	</bean>
	<bean id="userAccount4" class="com.app.infrastructure.security.UserAccount">
		<property name="username" value="profesor3" />
		<property name="password" value="21232f297a57a5a743894a0e4a801fc3" />
		<property name="authorities">
			<list>
				<bean class="com.app.infrastructure.security.Authority">
					<property name="authority" value="PROFESOR" />
				</bean>
			</list>
		</property>
	</bean>

	<bean id="userAccount2" class="com.app.infrastructure.security.UserAccount">
		<property name="username" value="tutor1" />
		<property name="password" value="91ec1f9324753048c0096d036a694f86" />
		<property name="authorities">
			<list>
				<bean class="com.app.infrastructure.security.Authority">
					<property name="authority" value="TUTOR" />
				</bean>
			</list>
		</property>
	</bean>
	<bean id="userAccount5" class="com.app.infrastructure.security.UserAccount">
		<property name="username" value="tutor2" />
		<property name="password" value="91ec1f9324753048c0096d036a694f86" />
		<property name="authorities">
			<list>
				<bean class="com.app.infrastructure.security.Authority">
					<property name="authority" value="TUTOR" />
				</bean>
			</list>
		</property>
	</bean>
	<bean id="userAccount6" class="com.app.infrastructure.security.UserAccount">
		<property name="username" value="tutor3" />
		<property name="password" value="91ec1f9324753048c0096d036a694f86" />
		<property name="authorities">
			<list>
				<bean class="com.app.infrastructure.security.Authority">
					<property name="authority" value="TUTOR" />
				</bean>
			</list>
		</property>
	</bean>
	<bean id="userAccount7" class="com.app.infrastructure.security.UserAccount">
		<property name="username" value="tutor4" />
		<property name="password" value="91ec1f9324753048c0096d036a694f86" />
		<property name="authorities">
			<list>
				<bean class="com.app.infrastructure.security.Authority">
					<property name="authority" value="TUTOR" />
				</bean>
			</list>
		</property>
	</bean>

	<bean id="userAccount8" class="com.app.infrastructure.security.UserAccount">
		<property name="username" value="admin1" />
		<property name="password" value="21232f297a57a5a743894a0e4a801fc3" />
		<property name="authorities">
			<list>
				<bean class="com.app.infrastructure.security.Authority">
					<property name="authority" value="ADMINISTRADOR" />
				</bean>
			</list>
		</property>
	</bean>

	<bean id="userAccount9" class="com.app.infrastructure.security.UserAccount">
		<property name="username" value="profesor1" />
		<property name="password" value="21232f297a57a5a743894a0e4a801fc3" />
		<property name="authorities">
			<list>
				<bean class="com.app.infrastructure.security.Authority">
					<property name="authority" value="PROFESOR" />
				</bean>
			</list>
		</property>
	</bean>

	<!-- Other domain beans come here -->

	<bean id="admin1" class="com.app.domain.model.types.Administrador">
		<property name="nombre" value="David" />
		<property name="userAccount" ref="userAccount8"></property>
		<property name="identidadConfirmada" value="True" ></property>
		<property name="apellidos" value="Romero Alcaide"></property>
		<property name="DNI" value="12345678Z"></property>
		<property name="notas" value=""></property>
	</bean>

	<!-- Other domain beans come here -->

	<bean id="profesor1" class="com.app.domain.model.types.Profesor">
		<property name="nombre" value="Ana" />
		<property name="userAccount" ref="userAccount9"></property>
		<property name="identidadConfirmada" value="True" ></property>
		<property name="apellidos" value="Romero Bomba"></property>
		<property name="DNI" value="77953335X"></property>
		<property name="preferenciasCita" value="Martes a las 9:00; Jueves a las 15:00"></property>
		<property name="notas" value=""></property>
	</bean>

	<bean id="tutor1" class="com.app.domain.model.types.PadreMadreOTutor">
		<property name="nombre" value="Paco" />
		<property name="apellidos" value="Alba"></property>
		<property name="userAccount" ref="userAccount2"></property>
		<property name="DNI" value="28842171X"></property>
		<property name="notas" value=""></property>
		<property name="tutorandos">
			<list>
				<ref bean="alumno1"></ref>
			</list>
		</property>
	</bean>
	<bean id="instituto1" class="com.app.domain.model.types.Instituto">
		<property name="calle" value="Plaza de Doña Elvira" />
		<property name="ciudad" value="Aracena"></property>
		<property name="cp" value="21200"></property>
		<property name="numero" value="1"></property>
		<property name="provincia" value="Huelva"></property>
		<property name="nombre" value="Instituto Aracena" />
		<property name="apellidos" value="Secundaria"></property>
		<property name="notas" value="Esto es un instituto"></property>
		<property name="complementoDireccion" value="No peatonal"></property>
		<property name="userAccount" ref="userAccount1"></property>
		<property name="DNI" value="12345678Z"></property>
		<property name="matriculas">
			<list>
			</list>
		</property>
		<property name="relacionesLaborales">
			<list>
			</list>
		</property>
	</bean>
	<bean id="tutor2" class="com.app.domain.model.types.PadreMadreOTutor">
		<property name="nombre" value="Terelu" />
		<property name="apellidos" value="Campos"></property>
		<property name="userAccount" ref="userAccount5"></property>
		<property name="DNI" value="12345678Z"></property>
		<property name="notas" value=""></property>
		<property name="tutorandos">
			<list>
				<ref bean="alumno1"></ref>
			</list>
		</property>
	</bean>
	<bean id="tutor3" class="com.app.domain.model.types.PadreMadreOTutor">
		<property name="nombre" value="Juan Carlos" />
		<property name="apellidos" value="Aragon"></property>
		<property name="userAccount" ref="userAccount6"></property>
		<property name="DNI" value="48993752A"></property>
		<property name="notas" value=""></property>
		<property name="tutorandos">

			<list>
			</list>
		</property>
	</bean>
	<bean id="tutor4" class="com.app.domain.model.types.PadreMadreOTutor">
		<property name="nombre" value="David" />
		<property name="apellidos" value="Romero Alcaide"></property>
		<property name="userAccount" ref="userAccount7"></property>
		<property name="DNI" value="48950972A"></property>
		<property name="notas" value=""></property>
		<property name="tutorandos">
			<list>
			</list>
		</property>
	</bean>

	<bean id="cursoAcademico1" class="com.app.domain.model.types.CursoAcademico">
		<property name="inicio">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="2014-09-22" />
			</bean>
		</property>
		<property name="fin">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="2015-08-22" />
			</bean>
		</property>
		<property name="denominacion" value="13/14"></property>
	</bean>
	<bean id="curso2" class="com.app.domain.model.types.Curso">
		<property name="nivel" value="3"></property>
		<property name="nivelEducativo" value="E.S.O."></property>
		<property name="identificador" value="B"></property>
		<property name="asignaturas">
			<list>
				<ref bean="asignatura5"></ref>
			</list>
		</property>
		<property name="instituto" ref="instituto1"></property>
	</bean>
	<bean id="instanciaCurso2" class="com.app.domain.model.types.InstanciaCurso" >
		<property name="alumnos">
			<list>
				<ref bean="alumno3"></ref>
				<ref bean="alumno1"></ref>
				<ref bean="alumno2"></ref>
			</list>
		</property>
		<property name="profesor" ref="profesor1" />
		<property name="curso" ref="curso2" />
		<property name="cursoAcademico" ref="cursoAcademico1" />
	</bean>
	<bean id="alumno1" class="com.app.domain.model.types.Alumno">
		<property name="nombre" value="Mari Angeles" />
		<property name="apellidos" value="Mañas"></property>
		<property name="fechaNacimiento">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="1990-6-22" />
			</bean>
		</property>
		<property name="cursos">
			<list>
				<ref bean="instanciaCurso2"></ref>
			</list>
		</property>
		<property name="padresMadresOTutores">
			<list>
				<ref bean="tutor1"></ref>
			</list>
		</property>
		<property name="itemsEvaluables">
			<list>
			</list>
		</property>
		<property name="matriculas">
			<list>
			</list>
		</property>
	</bean>
	<bean id="alumno2" class="com.app.domain.model.types.Alumno">
		<property name="nombre" value="Antonio" ></property>
		<property name="apellidos" value="Mañas"></property>
		<property name="cursos">
			<list>
				<ref bean="instanciaCurso2"></ref>
			</list>
		</property>
		<property name="padresMadresOTutores">
			<list>
				<ref bean="tutor3"></ref>
			</list>
		</property>
		<property name="fechaNacimiento">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="1990-6-22" />
			</bean>
		</property>
		<property name="itemsEvaluables">
			<list>
			</list>
		</property>
		<property name="matriculas">
			<list>
			</list>
		</property>
	</bean>
	<bean id="alumno3" class="com.app.domain.model.types.Alumno">
		<property name="nombre" value="Laura" />
		<property name="apellidos" value="Mañas"></property>
		<property name="cursos">
			<list>
				<ref bean="instanciaCurso2"></ref>
			</list>
		</property>
		<property name="padresMadresOTutores">
			<list>
				<ref bean="tutor4"></ref>
			</list>
		</property>
		<property name="fechaNacimiento">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="1990-6-22" />
			</bean>
		</property>
		<property name="itemsEvaluables">
			<list>
			</list>
		</property>
		<property name="matriculas">
			<list>
			</list>
		</property>
	</bean>
	<bean id="asignatura5" class="com.app.domain.model.types.Asignatura">
		<property name="nombre" value="Lengua Castellana"></property>

		<property name="curso" ref="curso2"></property>

	</bean>
	<bean id="materia1" class="com.app.domain.model.types.Materia" >
		<property name="profesor" ref="profesor1"></property>
		<property name="criteriosDeEvaluacion">
			<map>
				<entry key="com.app.domain.model.types.itemsevaluables.Examen" value="80"></entry>
				<entry key="com.app.domain.model.types.itemsevaluables.Trabajo" value="10"></entry>
				<entry key="com.app.domain.model.types.itemsevaluables.Cuaderno" value="10"></entry>
			</map>
		</property>
		<property name="asignatura" ref="asignatura5"></property>
		<property name="curso" ref="instanciaCurso2"></property>
		<property name="cursoAcademico" ref="cursoAcademico1"></property>
		<property name="itemsEvaluables">
			<list>
			</list>
		</property>
	</bean>
	<bean id="evaluacion1" class="com.app.domain.model.types.Evaluacion">
		<property name="inicio">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="2015-3-21" />
			</bean>
		</property>
		<property name="fin">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="2015-6-30" />
			</bean>
		</property>
		<property name="indicador" value="3"></property>
		<property name="itemsEvaluable">
			<list>
			</list>
		</property>
	</bean>
	<bean id="evaluacion2" class="com.app.domain.model.types.Evaluacion">
		<property name="inicio">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="2015-1-7" />
			</bean>
		</property>
		<property name="fin">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="2015-3-22" />
			</bean>
		</property>
		<property name="indicador" value="2"></property>
		<property name="itemsEvaluable">
			<list>
			</list>
		</property>
	</bean>
	<bean id="evaluacion3" class="com.app.domain.model.types.Evaluacion">
		<property name="fin">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="2014-12-22" />
			</bean>
		</property>
		<property name="inicio">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="2014-9-22" />
			</bean>
		</property>
		<property name="indicador" value="1"></property>
		<property name="itemsEvaluable">
			<list>
			</list>
		</property>
	</bean>

	<bean id="notaPorEvaluacion4" class="com.app.domain.model.types.NotaPorEvaluacion">
		<property name="alumno" ref="alumno2"></property>
		<property name="notaFinal" value="2"></property>
		<property name="materia" ref="materia1"></property>
		<property name="evaluacion" ref="evaluacion2"></property>
	</bean>

	<bean id="notaPorEvaluacion5" class="com.app.domain.model.types.NotaPorEvaluacion">
		<property name="alumno" ref="alumno2"></property>
		<property name="notaFinal" value="6"></property>
		<property name="materia" ref="materia1"></property>
		<property name="evaluacion" ref="evaluacion1"></property>
	</bean>

	<bean id="notaPorEvaluacion6" class="com.app.domain.model.types.NotaPorEvaluacion">
		<property name="alumno" ref="alumno2"></property>
		<property name="notaFinal" value="7"></property>
		<property name="materia" ref="materia1"></property>
		<property name="evaluacion" ref="evaluacion3"></property>
	</bean>

	<bean id="cita1" class="com.app.domain.model.types.Cita">
		<property name="confirmadoProfesor" value="false"></property>
		<property name="confirmadoTutor" value="false"></property>
		<property name="leida" value="false"></property>
		<property name="contenido" value="Cita entre personas"></property>
		<property name="emisor" value="Profesor"></property>
		<property name="fecha">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="2015-05-12" />
			</bean>
		</property>
		<property name="titulo" value="Cita entre un profesor y un tutor"></property>
		<property name="profesor" ref="profesor1"></property>
		<property name="padreMadreOTutor" ref="tutor1"></property>
	</bean>

	<bean id="dateFormat" class="java.text.SimpleDateFormat">
		<constructor-arg value="yyyy-MM-dd" />
	</bean>
</beans>


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="@color/black_light">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/AddHabitTitle"
        android:textSize="30dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:textColor="#2D9DC8" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/habit_date"
        android:layout_below="@+id/AddHabitTitle"
        android:textColor="#FFFFFF"
        android:textSize="20dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/habitCount"
        android:layout_below="@+id/habit_date"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:textColor="#FFFFFF"
        android:textSize="20dp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Completed"
        android:id="@+id/button3"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:onClick="raiseCount"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Delete"
        android:id="@+id/button4"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:onClick="delete"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Done"
        android:id="@+id/button5"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:onClick="done"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/days"
        android:textColor="#FFFFFF"
        android:text="Days Habit Occurs: "
        android:layout_marginTop="47dp"
        android:layout_below="@+id/habitCount"
        android:layout_alignEnd="@+id/button4" />

    <CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="?android:attr/listPreferredItemHeightSmall"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:gravity="center_vertical"
        android:checkMark="?android:attr/listChoiceIndicatorMultiple"
        android:paddingStart="?android:attr/listPreferredItemPaddingStart"
        android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
        android:textColor="#2D9DC8"
        android:text="Completed Today"
        android:clickable="false"
        android:layout_above="@+id/button3"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="29dp" />

</RelativeLayout>


text:
var cdb = require('cartodb.js-v3');

/**
 * View for a flash message to be displayed at the header.
 */
module.exports = cdb.core.View.extend({

  className: 'FlashMessage FlashMessage--error CDB-Text',

  initialize: function () {
    if (!this.model) throw new Error('model is required');

    this._template = cdb.templates.getTemplate('organization/flash_message');

    this.model.on('change', this.render, this);
  },

  render: function () {
    this.$el.toggle(this.model.shouldDisplay());
    this.$el.html(this._html());

    return this;
  },

  _html: function () {
    return this._template({
      str: this.model.get('msg')
    });
  }

});


text:
<?php

use lithium\util\Inflector;

?>
<!doctype html>

		<title></title>
		<?php $base = $request->env('base'); ?>
		<meta charset="utf-8" />
		<link rel="stylesheet" href="<?php echo $base; ?>/css/debug.css" />
		<link rel="stylesheet" href="<?php echo $base; ?>/css/testified.css" />
		<link href="<?php echo $base; ?>/favicon.ico" type="image/x-icon" rel="icon" />
		<link href="<?php echo $base; ?>/favicon.ico" type="image/x-icon" rel="shortcut icon" />

					<a href="<?php echo $base ?>/test/">
						 Lithium Test Dashboard

				<a class="test-all" href="<?php echo $base ?>/test/all">run all tests

					<?php echo $report->render("menu", ["menu" => $menu, "base" => $base]) ?>

					<?php if ($report->title) { ?>

test results for <?php echo $report->title; ?>

					<?php } ?>

						<?php echo join('', array_map(
							function($class) use ($request) {
								$url = "?filters[]={$class}";
								$name = join('', array_slice(explode("\\", $class), -1));
								$key = Inflector::underscore($name);
								$isActive = (
									isset($request->query['filters']) &&
									array_search($class, $request->query['filters']) !== false
								);
								$active = $isActive ? 'active' : null;
								return "{$name}";
							},
							$filters
						)); ?>

					<?php
					echo $report->render("stats");

					foreach ($report->filters() as $filter => $options) {
						$data = $report->results['filters'][$filter];
						echo $report->render($options['name'], compact('data', 'base'));
					}
					?>


text:
import MySQLdb as mdb
from decimal import Decimal
from config import *

try:
	con = mdb.connect(
		host=db_host,
		user=db_username,
		passwd=db_password,
		db=db_database,
		port=db_port)

	cur = con.cursor()

	# read in the main SQL analytics
	with open ("research.sql", "r") as sql_file:
		sql = sql_file.read()

	cur.execute(sql)

	desc = cur.description

	rows = cur.fetchall()

	col_processor = {
		0:lambda x: x,
		1:lambda x: round(x,2),
		2:lambda x: int(x),
		3:lambda x: int(x),
		4:lambda x: round(x,2)
	}

	# output the LaTeX table
	for row in rows:
		for i in range(0,5):
			print col_processor[i](row[i]),
			print ' \\\\' if i == 4 else ' & ',
		print

except Exception as e:
	print e

finally:
	con.close()