text:
This directory holds the content used to produce the Rez Wiki documentation
found [here](https://github.com/nerdvegas/rez/wiki). The wiki is updated by the
`Wiki` Github workflow, on release.

You should include relevant wiki updates with your code PRs.

## Testing

To test wiki updates locally:

* Make your changes to any pages/* or media/* files;
* Run `python ./generate-wiki.py`
* View the resulting content in the `out` directory using your markdown viewer
  of choice (we suggest [grip](https://github.com/joeyespo/grip)).


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kiss.Data.Expression;
using System.Data.Common;
using System.Data;
using Kiss.Data.Schema;
using System.Text.RegularExpressions;

namespace Kiss.Data.Driver
{
    /// <summary>
    /// DbDriver
    /// </summary>
    public class SqlDriver
    {
        #region provider

        /// <summary>
        /// SupportNamedParameter
        /// </summary>
        public virtual bool SupportNamedParameter
        {
            get { return false; }
        }

        /// <summary>
        /// ParameterPlaceHolder
        /// </summary>
        /// <returns></returns>
        public virtual string ParameterPlaceHolder(string name)
        {
            if (!SupportNamedParameter)
            {
                return Dialecter.QuoteParameter(name);
            }
            return " ? ";
        }

        /// <summary>
        /// DbProviderFactory
        /// </summary>
        protected DbProviderFactory factory = null;

        /// <summary>
        /// ProviderName
        /// </summary>
        public virtual string ProviderName { get; set; }

        /// <summary>
        /// return DbProviderFactory
        /// </summary>
        /// <returns></returns>
        public DbProviderFactory GetFactory()
        {
            if(factory == null)
            {
                factory = DbProviderFactories.GetFactory(ProviderName);
            }

            if(factory == null)
            {
                throw new Exception("can not get provider factory:" + ProviderName);
            }
            return factory;
        }

        /// <summary>
        /// create DbConnection
        /// </summary>
        /// <returns></returns>
        public virtual DbConnection CreateConnection()
        {
            return GetFactory().CreateConnection();
        }

        /// <summary>
        /// create DbCommand
        /// </summary>
        /// <returns></returns>
        public virtual DbCommand CreateCommand()
        {
            return GetFactory().CreateCommand();
        }

        /// <summary>
        /// create DbParameter
        /// </summary>
        /// <returns></returns>
        public virtual DbParameter CreateParameter()
        {
            return GetFactory().CreateParameter();
        }

        /// <summary>
        /// CreateParameter
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public virtual DbParameter CreateParameter(string name, object value)
        {
            DbParameter p = CreateParameter();
            p.ParameterName = name;
            if (value == null)
            {
                p.Value = DBNull.Value;
            }
            else
            {
                p.Value = value;
            }
            return p;
        }

        /// <summary>
        /// CreateCommandBuilder
        /// </summary>
        /// <returns></returns>
        public virtual DbCommandBuilder CreateCommandBuilder()
        {
            return GetFactory().CreateCommandBuilder();
        }

        /// <summary>
        /// CreateDataAdapter
        /// </summary>
        /// <returns></returns>
        public virtual DbDataAdapter CreateDataAdapter()
        {
            return GetFactory().CreateDataAdapter();
        }

        /// <summary>
        /// parameterRegex
        /// </summary>
        protected Regex parameterRegex;

        /// <summary>
        /// ParameterRegex
        /// </summary>
        /// <returns></returns>
        public virtual Regex ParameterRegex()
        {
            if(parameterRegex == null)
            {
                var c = Dialecter.ParameterPrefix();
                if (c == '?')
                {
                    parameterRegex = new Regex(@"\" + c + @"\w*");
                }
                else
                {
                    parameterRegex = new Regex(c + @"\w*");
                }

            }
            return parameterRegex;
        }

        #endregion ProviderName

        #region compile

        /// <summary>
        /// SetParameterPrecision
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="sqlType"></param>
        protected virtual void SetParameterPrecision(DbParameter parameter, byte? precision, byte? scale)
        {

        }

        /// <summary>
        /// SetParameterType
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="sqlType"></param>
        public virtual void SetParameterType(DbParameter parameter, DbType dbType, int? size, byte? precision, byte? scale)
        {
            parameter.DbType = dbType;
            if (size.HasValue)
            {
                parameter.Size = size.Value;
            }
            else
            {
                if (parameter.DbType.IsString() || parameter.DbType == DbType.Binary)
                {
                    parameter.Size = Int32.MaxValue;
                }
            }
            SetParameterPrecision(parameter, precision, scale);
        }

        /// <summary>
        /// SetParameterType
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="sqlType"></param>
        public virtual void SetParameterType(DbParameter parameter, DbType dbType)
        {
            parameter.DbType = dbType;
            if (parameter.DbType.IsString() || parameter.DbType == DbType.Binary)
            {
                parameter.Size = Int32.MaxValue;
            }
        }

        /// <summary>
        /// SetParameterNullValue
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="value"></param>
        protected virtual void SetParameterNullValue(DbParameter parameter)
        {
            if (parameter.IsNullable)
            {
                parameter.Value = DBNull.Value;
            }
            else if (parameter.DbType.IsString())
            {
                parameter.Value = string.Empty;
            }
            else if (parameter.DbType.IsNumeric())
            {
                parameter.Value = 0;
            }
            else if (parameter.DbType.IsDateTime())
            {
                parameter.Value = Defaults.DateTime;
            }
            else if (parameter.DbType == DbType.Guid)
            {
                parameter.Value = Defaults.Guid;
            }
            else
            {
                parameter.Value = DBNull.Value;
            }
        }

        /// <summary>
        /// SetParameterDateTime
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="value"></param>
        protected virtual void SetParameterDateTime(DbParameter parameter, object value)
        {
            DateTime v;
            if (value is DateTime)
            {
                v = (DateTime)value;
            }
            else
            {
                v = Convert.ToDateTime(value);
            }

            if (v.Year < Defaults.DateTimeMinYear)
            {
                parameter.Value = Defaults.DateTime;
            }
            else
            {
                parameter.Value = v;
            }
        }

        /// <summary>
        /// SetParameterGuid
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="value"></param>
        protected virtual void SetParameterGuid(DbParameter parameter, object value)
        {
            if (value is Guid)
            {
                parameter.Value = value;
                return;
            }

            parameter.Value = Guid.Parse(value.ToString());
        }

        /// <summary>
        /// SetParameterString
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="value"></param>
        protected virtual void SetParameterString(DbParameter parameter, object value)
        {
            if (value == null)
            {
                parameter.Value = value;
            }
            else
            {
                parameter.Value = value.ToString();
            }
        }

        /// <summary>
        /// SetParameterBinary
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="value"></param>
        protected virtual void SetParameterBinary(DbParameter parameter, object value)
        {
            parameter.Value = value;
        }

        /// <summary>
        /// SetParameterNumeric
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="value"></param>
        protected virtual void SetParameterNumeric(DbParameter parameter, object value)
        {
            parameter.Value = value;
        }

        /// <summary>
        /// SetParameterValue
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="value"></param>
        public virtual void SetParameterValue(DbParameter parameter, object value)
        {
            if (value == null)
            {
                SetParameterNullValue(parameter);
                return;
            }
            if (parameter.DbType.IsDateTime())
            {
                SetParameterDateTime(parameter, value);
                return;
            }

            //set sieze for string??

            switch (parameter.DbType)
            {
                case DbType.Guid:
                    SetParameterGuid(parameter, value);
                    return;
                case DbType.Binary:
                    SetParameterBinary(parameter, value);
                    return;
                case DbType.String:
                case DbType.StringFixedLength:
                case DbType.AnsiString:
                case DbType.AnsiStringFixedLength:
                    SetParameterString(parameter, value);
                    return;
                case DbType.Decimal:
                case DbType.Double:
                case DbType.Single:
                    SetParameterNumeric(parameter, value);
                    return;
                default:
                    break;
            }

            parameter.Value = value;
        }

        /// <summary>
        /// default ansi IDialecter
        /// </summary>
        private static IDialecter ansiDialecter = new SqlDialecter();

        /// <summary>
        /// Dialecter
        /// </summary>
        public virtual IDialecter Dialecter
        {
            get { return ansiDialecter; }
        }

        /// <summary>
        /// compile expression to DbCommand
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="schemaProvider"></param>
        /// <returns></returns>
        public virtual DbCommand Compile(ISqlExpression expression, IDbSchemaProvider schemaProvider)
        {
            if(expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            switch(expression.NodeType())
            {
                case NodeType.Text:
                    return CompileText(expression as Text);
                case NodeType.Procedure:
                    return CompileProcedure(expression as Procedure);
                case NodeType.Query:
                case NodeType.Delete:
                case NodeType.Insert:
                case NodeType.Update:
                    return CompileStatement(expression, schemaProvider);
            }

            throw new NotSupportedException("not support expression type:" + expression.NodeType().ToString());
        }

        /// <summary>
        /// CreateCompiler
        /// </summary>
        /// <returns></returns>
        public virtual SqlCompiler CreateCompiler()
        {
            return new SqlCompiler();
        }

        /// <summary>
        /// CompileStatement
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="schemaProvider"></param>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
        protected virtual DbCommand CompileStatement(ISqlExpression expression, IDbSchemaProvider schemaProvider)
        {
            DbCommand command = CreateCommand();
            command.CommandType = CommandType.Text;
            SqlWriter writer = new SqlWriter();
            SqlCompiler c = CreateCompiler();
            c.Driver = this;
            c.Writer = writer;
            c.Command = command;
            //c.Schema = schemaProvider;
            c.Compile(expression);
            command.CommandText = writer.String();
            //writer.Reset();
            return command;
        }

        /// <summary>
        /// compile text command expression
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
        protected virtual DbCommand CompileText(Text text)
        {
            if (string.IsNullOrEmpty(text.CommandText))
            {
                throw new Exception("command text can not be empty.");
            }

            DbCommand command = CreateCommand();
            command.CommandText = text.CommandText;
            command.CommandType = CommandType.Text;
            var dialecter = Dialecter;

            if (text.Parameters != null)
            {
                foreach (var p in text.Parameters)
                {
                    DbParameter parameter = CreateParameter(p);
                    command.Parameters.Add(parameter);
                }
            }

            return command;
        }

        /// <summary>
        /// SetParameterProviderType
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="providerDbType"></param>
        /// <param name="size"></param>
        /// <param name="precision"></param>
        /// <param name="scale"></param>
        public virtual void SetParameterProviderType(DbParameter parameter, int providerDbType, int? size, byte? precision, byte? scale)
        {
            SetParameterProviderDbType(parameter, providerDbType);
            if (size.HasValue)
            {
                parameter.Size = size.Value;
            }
            else
            {
                if (parameter.DbType.IsString() || parameter.DbType == DbType.Binary)
                {
                    parameter.Size = Int32.MaxValue;
                }
            }
            SetParameterPrecision(parameter, precision, scale);
        }

        /// <summary>
        /// SetParameterProviderDbType
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="providerDbType"></param>
        public virtual void SetParameterProviderDbType(DbParameter parameter, int providerDbType)
        {

        }

        /// <summary>
        /// CreateParameter
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        protected DbParameter CreateParameter(Parameter p)
        {
            var dialecter = Dialecter;
            DbParameter parameter = null;
            if (p.DbType.HasValue)
            {
                parameter = CreateParameter();
                parameter.ParameterName = dialecter.QuoteParameter(p.Name);
                if (p.ProviderDbType.HasValue && p.ProviderDbType.Value > 0)
                {
                    SetParameterProviderType(parameter, p.ProviderDbType.Value, p.Size, p.Precision, p.Scale);
                }
                else
                {
                    SetParameterType(parameter, p.DbType.Value, p.Size, p.Precision, p.Scale);
                }
                SetParameterValue(parameter, p.Value);
            }
            else
            {
                parameter = CreateParameter(dialecter.QuoteParameter(p.Name), p.Value);
            }
            parameter.Direction = p.Direction;
            return parameter;
        }

        /// <summary>
        /// compile procedure
        /// </summary>
        /// <param name="procedure"></param>
        /// <param name="schemaProvider"></param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
        protected virtual DbCommand CompileProcedure(Procedure procedure)
        {
            if (string.IsNullOrEmpty(procedure.Name))
            {
                throw new ArgumentException("procedure name can not be empty");
            }

            DbCommand command = CreateCommand();
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = procedure.Name;

            if (procedure.Parameters != null)
            {
                foreach (var p in procedure.Parameters)
                {
                    DbParameter parameter = CreateParameter(p);
                    command.Parameters.Add(parameter);
                }
            }
            return command;
        }

        #endregion

        #region schema

        protected SqlSchema schemaProvider;

        public SqlSchema GetSchemaProvider()
        {
            if (schemaProvider == null)
            {
                schemaProvider = CreateSchemaProvider();
            }
            return schemaProvider;
        }

        protected virtual SqlSchema CreateSchemaProvider()
        {
            return new SqlSchema();
        }

        public virtual SqlTable GetTable(string tableName, string connectionString)
        {
            return GetSchemaProvider().GetTable(this, tableName, connectionString);
        }

        public virtual SqlProcedure GetProcedure(string procedureName, string connectionString)
        {
            return GetSchemaProvider().GetProcedure(this, procedureName, connectionString);
        }

        #endregion

        #region type mapping
        public virtual DbType NativeTypeToDbType(string dataType)
        {
            switch(dataType.ToLowerInvariant())
            {
                case "name":
                case "oidvector":
                case "refcursor":
                case "ref":
                case "char":
                case "character":
                case "longchar":
                case "nchar":
                case "varchar":
                case "varchar2":
                case "varyingcharacter":
                case "nvarchar":
                case "nvarchar2":
                case "longvarchar":
                case "nativecharacter":
                case "native character":
                case  "nativevaryingcharacter":
                case "character varying":
                case "text":
                case "ntext":
                case "longtext":
                case "mediumtext":
                case "tinytext":
                case "bpchar":
                case "clob":
                case "nclob":
                case "rowid":
                case "urowid":
                case "xmltype":
                case "sysname":
                case "long":
                case "sql_variant":
                case "note":
                case "memo":
                case "string":
                    return DbType.String;
                case "long raw":
                    return DbType.Binary;
                case "bytea":
                case "bit varying":
                case "binary":
                case "varbinary":
                case "rowversion":
                case "blob":
                case "tinyblob":
                case "mediumblob":
                case "oleobject":
                case "longblob":
                case "raw":
                case "image":
                case "general":
                    return DbType.Binary;
                case "bit":
                case "bool":
                case "boolean":
                case "yesno":
                case "logical":
                    return DbType.Boolean;
                case "tinyint":
                    return DbType.Byte;
                case "tinyint unsigned":
                    return DbType.SByte;
                case "int2":
                case "smallint":
                    return DbType.Int16;
                case "uint16":
                case "smallint unsigned":
                    return DbType.UInt16;
                case "int4":
                case "int":
                case "mediumint":
                    return DbType.Int32;
                case "uint32":
                case "integer unsigned":
                    return DbType.UInt32;
                case "int8":
                case "bigint":
                case "integer":
                case "bigserial":
                case "serial":
                case "smallserial":
                    return DbType.Int64;
                case "uint64":
                case "bigint unsigned":
                    return DbType.UInt64;
                case "autoincrement":
                case "identity":
                case "counter":
                    return DbType.Int64;
                case "float4":
                case "real":
                    return DbType.Single;
                case "float8":
                case "float":
                case "double":
                case "double precision":
                    return DbType.Double;
                case "numeric":
                case "decimal":
                case "newdecimal":
                case "number":
                    return DbType.Decimal;
                case "binary_double":
                case "binary_float":
                case "binary_integer":
                    return DbType.Decimal;
                case "money":
                case "smallmoney":
                    return DbType.Decimal;
                case "currency":
                    return DbType.Currency;
                case "date":
                case "smalldate":
                    return DbType.DateTime;
                case "timetz":
                case "abstime":
                case "datetime":
                case "smalldatetime":
                    return DbType.DateTime;
                case "timestamp":
                case "timestamp with time zone":
                case "timestamp without time zone":
                case "timestamp with local time zone":
                    return DbType.DateTime;
                case "time":
                    return DbType.Time;
                case "timestamptz":
                    return DbType.DateTime;
                case "datetime2":
                    return DbType.DateTime2;
                case "datetimeoffset":
                    return DbType.DateTimeOffset;
                case "year":
                    return DbType.Int32;
                case "interval day to second":
                    return DbType.Int64;
                case "interval year to month":
                    return DbType.Int64;
                case "uuid":
                case "guid":
                case "uniqueidentifier":
                    return DbType.Guid;
                case "xml":
                    return DbType.Xml;
                case "interval":
                    return DbType.Object;
                case "array":
                    return DbType.Object;
                case "point":
                case "box":
                case "path":
                case "lseg":
                case "polygon":
                case "circle":
                case "line":
                case "inet":
                case "macaddr":
                    return DbType.Object;
            }

            return DbType.Object;
        }

        #endregion

        public SqlDriver()
        {

        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
using NationBuilderConnect.Client.Utilities;
using NationBuilderConnect.Model;

namespace NationBuilderConnect.Client.Services.Parameters
{
    /// <summary>
    ///     The values used to search for people near a certain location
    /// </summary>
    public class GetNearbyPeopleParameters
    {
        /// <summary>
        ///     Initializes a new instance of the <see cref="GetNearbyPeopleParameters" /> class
        /// </summary>
        /// <param name="location">The location to search</param>
        /// <param name="distance">The distance to search around the location in miles</param>
        public GetNearbyPeopleParameters(Coordinates location, int distance)
        {
            Location = location;
            Distance = distance;
        }

        /// <summary>
        ///     The location to search
        /// </summary>
        [QueryStringParameter("location")]
        public Coordinates Location { get; private set; }

        /// <summary>
        ///     The distance to search around the location in miles
        /// </summary>
        [QueryStringParameter("distance")]
        public int Distance { get; private set; }
    }
}


text:
package cn.springmvc.model;

public class PaginationParams {

	private int limit;

	private int offset;

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getOffset() {
		return offset;
	}

	public void setOffset(int offset) {
		this.offset = offset;
	}

	public PaginationParams(int limit, int offset) {
		super();
		this.limit = limit;
		this.offset = offset;
	}

	public PaginationParams() {
		super();
	}

	@Override
	public String toString() {
		return "PaginationParams [limit=" + limit + ", offset=" + offset + "]";
	}

}


text:
import os
import sys
if sys.platform == 'win32':
    pybabel = 'env\\Scripts\\pybabel'
else:
    pybabel = 'env/bin/pybabel'
if len(sys.argv) != 2:
    print "usage: tr_init <language-code>"
    sys.exit(1)
os.system(pybabel +
          ' extract -F babel.cfg -k lazy_gettext -o messages.pot rrd')
os.system(pybabel +
          ' init -i messages.pot -d rrd/translations -l ' + sys.argv[1])
os.unlink('messages.pot')


text:
package orange

import (
	"fmt"

	"github.com/skratchdot/open-golang/open"
)

const (
	MarkdownChanSize = 3
	Version          = "0.2.2-dev"
)

func NewOrange(port int) *Orange {
	return &Orange{port, nil, make(chan bool)}
}

type Orange struct {
	port       int
	httpServer *HTTPServer
	stop       chan bool
}

func (o *Orange) UseBasic() {
	MdConverter.UseBasic()
}

func (o *Orange) Run(files ...string) {
	o.httpServer = NewHTTPServer(o.port)
	o.httpServer.Listen()

	for _, file := range files {
		addr := fmt.Sprintf("http://localhost:%d/%s", o.port, file)
		open.Run(addr)
	}

	<-o.stop
}

func (o *Orange) Stop() {
	o.httpServer.Stop()
	o.stop <- true
}


text:
package com.microsoft.azure.management.mediaservices.v2018_07_01;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonSubTypes;

/**
 * Base class for inputs to a Job.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@odata\\.type", defaultImpl = JobInput.class)
@JsonTypeName("JobInput")
@JsonSubTypes({
    @JsonSubTypes.Type(name = "#Microsoft.Media.JobInputClip", value = JobInputClip.class),
    @JsonSubTypes.Type(name = "#Microsoft.Media.JobInputs", value = JobInputs.class)
})
public class JobInput {
}


text:
namespace inet {

namespace visualizer {

Define_Module(NetworkConnectionOsgVisualizer);

#ifdef WITH_OSG

void NetworkConnectionOsgVisualizer::initialize(int stage)
{
    NetworkConnectionVisualizerBase::initialize(stage);
    if (!hasGUI()) return;
    if (stage == INITSTAGE_LOCAL) {
    }
}

void NetworkConnectionOsgVisualizer::createNetworkConnectionVisualization(cModule *startNetworkNode, cModule *endNetworkNode)
{
    auto geode = new osg::Geode();
    auto drawable = inet::osg::createLineGeometry(getPosition(startNetworkNode), getPosition(endNetworkNode));
    geode->addDrawable(drawable);
    auto stateSet = inet::osg::createLineStateSet(lineColor, lineStyle, lineWidth);
    stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
    geode->setStateSet(stateSet);
    auto lineWidth = new osg::LineWidth();
    lineWidth->setWidth(this->lineWidth);
    stateSet->setAttributeAndModes(lineWidth, osg::StateAttribute::ON);
    auto scene = inet::osg::TopLevelScene::getSimulationScene(visualizerTargetModule);
    scene->addChild(geode);
}

#endif // ifdef WITH_OSG

} // namespace visualizer

} // namespace inet


text:
    TypeName(const TypeName&) = delete;    \
  void operator=(const TypeName&) = delete
#else
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
    TypeName(const TypeName&);             \
  void operator=(const TypeName&)
#endif

// this is better than use two sizeof(array) / sizeof(array[0]).
template<typename T, size_t N>
char (&ArraySizeHelper(T (&array)[N]))[N];
#define arraysize(array) (sizeof(ArraySizeHelper(array)))

// for debug info.
// the reason I use two macro here.
// #define ABC CBA
// AS_STRING(ABC)         --> "CBA"
// AS_STRINGINTERNAL(ABC) --> "ABC"
#define AS_STRING(x)   AS_STRING_INTERNAL(x)
#define AS_STRING_INTERNAL(x)   #x

#endif  // BASE_MACROS_H_


text:
package com.rey.material.drawable;

import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.support.v4.graphics.drawable.DrawableCompat;

/**
 * Created by Rey on 8/19/2015.
 */
public class PaddingDrawable extends Drawable implements Drawable.Callback {

	private Drawable mDrawable;

	private int mPaddingLeft;
	private int mPaddingTop;
	private int mPaddingRight;
	private int mPaddingBottom;

	public PaddingDrawable(Drawable drawable) {
		setWrappedDrawable(drawable);
	}

	public void setPadding(int paddingLeft, int paddingTop, int paddingRight, int paddingBottom) {
		mPaddingLeft = paddingLeft;
		mPaddingTop = paddingTop;
		mPaddingRight = paddingRight;
		mPaddingBottom = paddingBottom;
	}

	public int getPaddingLeft() {
		return mPaddingLeft;
	}

	public int getPaddingTop() {
		return mPaddingTop;
	}

	public int getPaddingRight() {
		return mPaddingRight;
	}

	public int getPaddingBottom() {
		return mPaddingBottom;
	}

	@Override
	public void draw(Canvas canvas) {
		if (mDrawable != null)
			mDrawable.draw(canvas);
	}

	@Override
	protected void onBoundsChange(Rect bounds) {
		if (mDrawable != null)
			mDrawable.setBounds(bounds.left + mPaddingLeft, bounds.top + mPaddingTop, bounds.right - mPaddingRight, bounds.bottom - mPaddingBottom);
	}

	@Override
	public void setChangingConfigurations(int configs) {
		if (mDrawable != null)
			mDrawable.setChangingConfigurations(configs);
	}

	@Override
	public int getChangingConfigurations() {
		return mDrawable != null ? mDrawable.getChangingConfigurations() : 0;
	}

	@Override
	public void setDither(boolean dither) {
		if (mDrawable != null)
			mDrawable.setDither(dither);
	}

	@Override
	public void setFilterBitmap(boolean filter) {
		if (mDrawable != null)
			mDrawable.setFilterBitmap(filter);
	}

	@Override
	public void setAlpha(int alpha) {
		if (mDrawable != null)
			mDrawable.setAlpha(alpha);
	}

	@Override
	public void setColorFilter(ColorFilter cf) {
		if (mDrawable != null)
			mDrawable.setColorFilter(cf);
	}

	@Override
	public boolean isStateful() {
		return mDrawable != null && mDrawable.isStateful();
	}

	@Override
	public boolean setState(final int[] stateSet) {
		return mDrawable != null && mDrawable.setState(stateSet);
	}

	@Override
	public int[] getState() {
		return mDrawable != null ? mDrawable.getState() : null;
	}

	public void jumpToCurrentState() {
		if (mDrawable != null)
			DrawableCompat.jumpToCurrentState(mDrawable);
	}

	@Override
	public Drawable getCurrent() {
		return mDrawable != null ? mDrawable.getCurrent() : null;
	}

	@Override
	public boolean setVisible(boolean visible, boolean restart) {
		return super.setVisible(visible, restart) || (mDrawable != null && mDrawable.setVisible(visible, restart));
	}

	@Override
	public int getOpacity() {
		return mDrawable != null ? mDrawable.getOpacity() : PixelFormat.UNKNOWN;
	}

	@Override
	public Region getTransparentRegion() {
		return mDrawable != null ? mDrawable.getTransparentRegion() : null;
	}

	@Override
	public int getIntrinsicWidth() {
		return (mDrawable != null ? mDrawable.getIntrinsicWidth() : 0) + mPaddingLeft + mPaddingRight;
	}

	@Override
	public int getIntrinsicHeight() {
		return (mDrawable != null ? mDrawable.getIntrinsicHeight() : 0) + mPaddingTop + mPaddingBottom;
	}

	@Override
	public int getMinimumWidth() {
		return (mDrawable != null ? mDrawable.getMinimumWidth() : 0) + mPaddingLeft + mPaddingRight;
	}

	@Override
	public int getMinimumHeight() {
		return (mDrawable != null ? mDrawable.getMinimumHeight() : 0) + mPaddingTop + mPaddingBottom;
	}

	@Override
	public boolean getPadding(Rect padding) {
		boolean hasPadding = mDrawable != null && mDrawable.getPadding(padding);
		if (hasPadding) {
			padding.left += mPaddingLeft;
			padding.top += mPaddingTop;
			padding.right += mPaddingRight;
			padding.bottom += mPaddingBottom;
		} else {
			padding.set(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
			hasPadding = mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 || mPaddingBottom != 0;
		}

		return hasPadding;
	}

	/**
	 * {@inheritDoc}
	 */
	public void invalidateDrawable(Drawable who) {
		invalidateSelf();
	}

	/**
	 * {@inheritDoc}
	 */
	public void scheduleDrawable(Drawable who, Runnable what, long when) {
		scheduleSelf(what, when);
	}

	/**
	 * {@inheritDoc}
	 */
	public void unscheduleDrawable(Drawable who, Runnable what) {
		unscheduleSelf(what);
	}

	@Override
	protected boolean onLevelChange(int level) {
		return mDrawable != null && mDrawable.setLevel(level);
	}

	@Override
	public void setAutoMirrored(boolean mirrored) {
		if (mDrawable != null)
			DrawableCompat.setAutoMirrored(mDrawable, mirrored);
	}

	@Override
	public boolean isAutoMirrored() {
		return mDrawable != null && DrawableCompat.isAutoMirrored(mDrawable);
	}

	@Override
	public void setTint(int tint) {
		if (mDrawable != null)
			DrawableCompat.setTint(mDrawable, tint);
	}

	@Override
	public void setTintList(ColorStateList tint) {
		if (mDrawable != null)
			DrawableCompat.setTintList(mDrawable, tint);
	}

	@Override
	public void setTintMode(PorterDuff.Mode tintMode) {
		if (mDrawable != null)
			DrawableCompat.setTintMode(mDrawable, tintMode);
	}

	@Override
	public void setHotspot(float x, float y) {
		if (mDrawable != null)
			DrawableCompat.setHotspot(mDrawable, x, y);
	}

	@Override
	public void setHotspotBounds(int left, int top, int right, int bottom) {
		if (mDrawable != null)
			DrawableCompat.setHotspotBounds(mDrawable, left, top, right, bottom);
	}

	public Drawable getWrappedDrawable() {
		return mDrawable;
	}

	public void setWrappedDrawable(Drawable drawable) {
		if (mDrawable != null) {
			mDrawable.setCallback(null);
		}

		mDrawable = drawable;

		if (drawable != null) {
			drawable.setCallback(this);
		}

		onBoundsChange(getBounds());
		invalidateSelf();
	}
}


text:
<?php
/**
 * MyVendorName (http://example.io)
 *
 * @package   MyPackageName
 * @link      https://github.com/user/repo
 * @license   http://opensource.org/licenses/MIT MIT
 */
namespace MyVendorName\MyPackageName;

use MyVendorName\MyPackageName\MyTrait;
use InvalidArgumentException;

/**
 * MyClass: Example class.
 *
 * A short description.
 */
class MyClass implements MyClassInterface
{
    use MyTrait;

    const MYCONST = 'EXAMPLE';

    /**
     * @access protected
     * @var    array
     */
    protected $_config;

    /**
     * Constructor.
     *
     */
    public function __construct(array $config)
    {
        $this->_config = $config;
    }

    /**
     * My Method.
     *
     */
    public function myMethod($var)
    {
        if(!is_string($var))
            throw new InvalidArgumentException(
                "Expected string ...",
                1
            );
        else
            echo "myMethod (str): $var\n";
    }

    /**
     * My Final Method.
     *
     */
    final public static function myFinalMethod($var)
    {
        if(!is_bool($var))
            throw new InvalidArgumentException(
                "Expected bool ...",
                1
            );
        else
            echo "myFinalMethod (bool): $var\n";
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/dk_color_aa000000" />
    <stroke
        android:width="1px"
        android:color="@color/dk_color_aa000000" />
    <padding
        android:bottom="1px"
        android:left="1px"
        android:right="1px"
        android:top="1px" />

    <corners android:radius="4dp" />
</shape>


text:
<?php

/**
 * Subclass for performing query and update operations on the 'mlm_customer_enquiry' table.
 *
 *
 *
 * @package lib.model
 */
class MlmCustomerEnquiryPeer extends BaseMlmCustomerEnquiryPeer
{
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using Microsoft.PythonTools.Analysis.Analyzer;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Project;

namespace Microsoft.PythonTools {
    internal class InterpreterView : DependencyObject, INotifyPropertyChanged {
        private readonly string _identifier;
        private DateTime _expectFirstUpdateBy;
        private bool _isRunning;

        public static readonly IEqualityComparer<InterpreterView> EqualityComparer = new InterpreterViewComparer();
        public static readonly IComparer<InterpreterView> Comparer = (IComparer<InterpreterView>)EqualityComparer;

        public static IEnumerable<InterpreterView> GetInterpreters(
            IServiceProvider serviceProvider,
            IInterpreterOptionsService interpreterService = null
        ) {
            if (interpreterService == null) {
                interpreterService = serviceProvider.GetComponentModel().GetService<IInterpreterOptionsService>();
                if (interpreterService == null) {
                    return Enumerable.Empty<InterpreterView>();
                }
            }

            return interpreterService.KnownProviders
                .Where(p => !(p is LoadedProjectInterpreterFactoryProvider))
                .SelectMany(p => p.GetInterpreterFactories())
                .Where(PythonInterpreterFactoryExtensions.IsUIVisible)
                .OrderBy(fact => fact.Description)
                .ThenBy(fact => fact.Configuration.Version)
                .Select(i => new InterpreterView(i, i.Description, i == interpreterService.DefaultInterpreter));
        }

        public InterpreterView(IPythonInterpreterFactory interpreter, string name, PythonProjectNode project)
            : this(interpreter, name, false) {
            Project = project;
            if (Project != null) {
                CanBeDefault = false;
                SubName = project.Caption;
            }
        }

        public InterpreterView(IPythonInterpreterFactory interpreter, string name, bool isDefault) {
            Interpreter = interpreter;
            Name = name;
            SubName = string.Empty;
            Identifier = _identifier = AnalyzerStatusListener.GetIdentifier(interpreter);

            var withDb = interpreter as IPythonInterpreterFactoryWithDatabase;
            if (withDb != null) {
                CanRefresh = File.Exists(interpreter.Configuration.InterpreterPath) &&
                    Directory.Exists(interpreter.Configuration.LibraryPath);
                withDb.IsCurrentChanged += Interpreter_IsCurrentChanged;
                IsCurrent = withDb.IsCurrent;
                IsCurrentReason = withDb.GetFriendlyIsCurrentReason(CultureInfo.CurrentUICulture);
            }
            IsRunning = false;
            IsDefault = isDefault;
        }

        public InterpreterView(string name) {
            Name = name;
        }

        public override string ToString() {
            return Name;
        }

        private void Interpreter_IsCurrentChanged(object sender, EventArgs e) {
            var withDb = sender as IPythonInterpreterFactoryWithDatabase;
            if (withDb != null) {
                IsCurrent = withDb.IsCurrent;
                IsCurrentReason = withDb.GetFriendlyIsCurrentReason(CultureInfo.CurrentUICulture);
                IsCheckingDatabase = withDb.IsCheckingDatabase;
            }
        }

        public void ProgressUpdate(Dictionary<string, AnalysisProgress> updateInfo) {
            var withDb = Interpreter as IPythonInterpreterFactoryWithDatabase;
            if (withDb == null) {
                return;
            }

            AnalysisProgress update;
            if (updateInfo.TryGetValue(_identifier, out update)) {
                if (!IsRunning) {
                    // We're analyzing, but we weren't started by this process.
                    IsRunning = true;
                }

                // We've received a message, so stop worrying about the timeout.
                _expectFirstUpdateBy = DateTime.MinValue;

                if (update.Progress < int.MaxValue) {
                    Dispatcher.BeginInvoke((Action)(() => {
                        if (update.Progress > Progress || update.Maximum != Maximum) {
                            Progress = update.Progress;
                            Maximum = update.Maximum;
                        }
                        Message = update.Message;
                    }));
                } else {
                    Dispatcher.BeginInvoke((Action)(() => {
                        Progress = 0;
                        Message = "Starting refresh DB";
                    }));
                }
            } else if (IsRunning && DateTime.Now > _expectFirstUpdateBy) {
                IsRunning = false;
            }
        }

        internal void DefaultInterpreterUpdate(IPythonInterpreterFactory newDefault) {
            if (Dispatcher.CheckAccess()) {
                IsDefault = (Interpreter == newDefault);
            } else {
                Dispatcher.BeginInvoke((Action)(() => DefaultInterpreterUpdate(newDefault)));
            }
        }

        public void Start() {
            if (Dispatcher.CheckAccess()) {
                var withDb = Interpreter as IPythonInterpreterFactoryWithDatabase;
                if (withDb != null) {
                    // Expect the first update within 10 seconds or else stop
                    // running.
                    _expectFirstUpdateBy = DateTime.Now + TimeSpan.FromSeconds(10);
                    IsRunning = true;
                    Message = "Starting refresh DB";
                    withDb.GenerateDatabase(GenerateDatabaseOptions.SkipUnchanged, exitCode => {
                        if (exitCode != PythonTypeDatabase.AlreadyGeneratingExitCode) {
                            IsRunning = false;
                        }
                    });
                }
            } else {
                Dispatcher.BeginInvoke((Action)(() => Start()));
            }
        }

        public void Abort() {
            throw new NotImplementedException();
        }

        public IPythonInterpreterFactory Interpreter {
            get;
            private set;
        }

        public string Identifier {
            get;
            private set;
        }

        public PythonProjectNode Project {
            get;
            private set;
        }

        public string Name {
            get { return (string)GetValue(NameProperty); }
            private set { SafeSetValue(NamePropertyKey, value); }
        }

        public string SubName {
            get { return (string)GetValue(SubNameProperty); }
            private set { SafeSetValue(SubNamePropertyKey, value); }
        }

        public bool CanRefresh {
            get { return (bool)SafeGetValue(CanRefreshProperty); }
            private set { SetValue(CanRefreshPropertyKey, value); }
        }

        public string IsCurrentReason {
            get { return (string)GetValue(IsCurrentReasonProperty); }
            private set { SafeSetValue(IsCurrentReasonPropertyKey, value); }
        }

        public bool IsRunning {
            get { return _isRunning; }
            private set { SafeSetValue(IsRunningPropertyKey, value); }
        }

        public bool IsCheckingDatabase {
            get { return (bool)GetValue(IsCheckingDatabaseProperty); }
            private set { SafeSetValue(IsCheckingDatabasePropertyKey, value); }
        }

        public bool IsCurrent {
            get { return (bool)SafeGetValue(IsCurrentProperty); }
            private set { SafeSetValue(IsCurrentPropertyKey, value); }
        }

        public int Progress {
            get { return (int)GetValue(ProgressProperty); }
            private set { SetValue(ProgressPropertyKey, value); }
        }

        public string Message {
            get { return (string)GetValue(MessageProperty); }
            private set { SafeSetValue(MessagePropertyKey, value); }
        }

        public int Maximum {
            get { return (int)GetValue(MaximumProperty); }
            private set { SetValue(MaximumPropertyKey, value); }
        }

        public bool IsDefault {
            get { return (bool)GetValue(IsDefaultProperty); }
            private set { SetValue(IsDefaultPropertyKey, value); }
        }

        public bool CanBeDefault {
            get { return (bool)GetValue(CanBeDefaultProperty); }
            private set { SetValue(CanBeDefaultPropertyKey, value); }
        }

        public bool IsSelected {
            get { return (bool)SafeGetValue(IsSelectedProperty); }
            set { SetValue(IsSelectedProperty, value); }
        }

        private object SafeGetValue(DependencyProperty property) {
            if (Dispatcher.CheckAccess()) {
                return GetValue(property);
            } else {
                return Dispatcher.Invoke((Func<object>)(() => GetValue(property)));
            }
        }

        private void SafeSetValue(DependencyPropertyKey property, object value) {
            if (Dispatcher.CheckAccess()) {
                SetValue(property, value);
            } else {
                Dispatcher.BeginInvoke((Action)(() => SetValue(property, value)));
            }
        }

        private static readonly DependencyPropertyKey NamePropertyKey = DependencyProperty.RegisterReadOnly("Name", typeof(string), typeof(InterpreterView), new PropertyMetadata());
        private static readonly DependencyPropertyKey SubNamePropertyKey = DependencyProperty.RegisterReadOnly("SubName", typeof(string), typeof(InterpreterView), new PropertyMetadata());
        private static readonly DependencyPropertyKey IsCurrentReasonPropertyKey = DependencyProperty.RegisterReadOnly("IsCurrentReason", typeof(string), typeof(InterpreterView), new PropertyMetadata());
        private static readonly DependencyPropertyKey IsCurrentPropertyKey = DependencyProperty.RegisterReadOnly("IsCurrent", typeof(bool), typeof(InterpreterView), new PropertyMetadata(true));
        private static readonly DependencyPropertyKey IsRunningPropertyKey = DependencyProperty.RegisterReadOnly("IsRunning", typeof(bool), typeof(InterpreterView), new PropertyMetadata(false, IsRunning_Changed));
        private static readonly DependencyPropertyKey IsCheckingDatabasePropertyKey = DependencyProperty.RegisterReadOnly("IsCheckingDatabase", typeof(bool), typeof(InterpreterView), new PropertyMetadata(false));
        private static readonly DependencyPropertyKey ProgressPropertyKey = DependencyProperty.RegisterReadOnly("Progress", typeof(int), typeof(InterpreterView), new PropertyMetadata(0));
        private static readonly DependencyPropertyKey MessagePropertyKey = DependencyProperty.RegisterReadOnly("Message", typeof(string), typeof(InterpreterView), new PropertyMetadata());
        private static readonly DependencyPropertyKey MaximumPropertyKey = DependencyProperty.RegisterReadOnly("Maximum", typeof(int), typeof(InterpreterView), new PropertyMetadata(0));
        private static readonly DependencyPropertyKey IsDefaultPropertyKey = DependencyProperty.RegisterReadOnly("IsDefault", typeof(bool), typeof(InterpreterView), new PropertyMetadata(false));
        private static readonly DependencyPropertyKey CanBeDefaultPropertyKey = DependencyProperty.RegisterReadOnly("CanBeDefault", typeof(bool), typeof(InterpreterView), new PropertyMetadata(true));
        private static readonly DependencyPropertyKey CanRefreshPropertyKey = DependencyProperty.RegisterReadOnly("CanRefresh", typeof(bool), typeof(InterpreterView), new PropertyMetadata(false));

        public static readonly DependencyProperty NameProperty = NamePropertyKey.DependencyProperty;
        public static readonly DependencyProperty SubNameProperty = SubNamePropertyKey.DependencyProperty;
        public static readonly DependencyProperty IsCurrentReasonProperty = IsCurrentReasonPropertyKey.DependencyProperty;
        public static readonly DependencyProperty IsCurrentProperty = IsCurrentPropertyKey.DependencyProperty;
        public static readonly DependencyProperty IsCheckingDatabaseProperty = IsCheckingDatabasePropertyKey.DependencyProperty;
        public static readonly DependencyProperty IsRunningProperty = IsRunningPropertyKey.DependencyProperty;
        public static readonly DependencyProperty ProgressProperty = ProgressPropertyKey.DependencyProperty;
        public static readonly DependencyProperty MessageProperty = MessagePropertyKey.DependencyProperty;
        public static readonly DependencyProperty MaximumProperty = MaximumPropertyKey.DependencyProperty;
        public static readonly DependencyProperty IsDefaultProperty = IsDefaultPropertyKey.DependencyProperty;
        public static readonly DependencyProperty CanBeDefaultProperty = CanBeDefaultPropertyKey.DependencyProperty;
        public static readonly DependencyProperty CanRefreshProperty = CanRefreshPropertyKey.DependencyProperty;

        public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register("IsSelected", typeof(bool), typeof(InterpreterView), new PropertyMetadata(false));

        private static void IsRunning_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e) {
            if (!(e.NewValue as bool? ?? true)) {
                d.SetValue(ProgressPropertyKey, 0);
                d.SetValue(MaximumPropertyKey, 0);
            }
            var iv = d as InterpreterView;
            if (iv != null) {
                iv._isRunning = (e.NewValue as bool?) ?? false;
            }
        }

        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) {
            base.OnPropertyChanged(e);
            var evt = PropertyChanged;
            if (evt != null) {
                evt(this, new PropertyChangedEventArgs(e.Property.Name));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private sealed class InterpreterViewComparer : IEqualityComparer<InterpreterView>, IComparer<InterpreterView> {
            public bool Equals(InterpreterView x, InterpreterView y) {
                return ReferenceEquals(
                    x == null ? null : x.Interpreter,
                    y == null ? null : y.Interpreter
                );
            }

            public int GetHashCode(InterpreterView obj) {
                return obj == null || obj.Interpreter == null ? 0 : obj.Interpreter.GetHashCode();
            }

            public int Compare(InterpreterView x, InterpreterView y) {
                return StringComparer.CurrentCultureIgnoreCase.Compare(
                    x == null ? "" : x.Name,
                    y == null ? "" : y.Name
                );
            }
        }
    }
}


text:
package com.creditease.dbus.commons;

import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.CommonClientConfigs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * 加载zookeeper配置中心中的配置文件
 * Created by Shrimp on 16/6/6.
 */
public class ZkPropertiesProvider implements PropertiesProvider {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private IZkService zookeeper;
    private String path;
    private String url;
    private static Boolean isSecurity = null;

    public ZkPropertiesProvider(String url, String path) throws Exception {
        this.url = url;
        this.path = path;
        zookeeper = new ZkService(url, 30000);
    }

    @Override
    public Properties loadProperties(String node) throws Exception {
        if (path == null) {
            throw new IllegalArgumentException();
        }
        String nodePath = buildPath(node);
        if (zookeeper.isExists(nodePath)) {
            Properties properties = zookeeper.getProperties(nodePath);
            if (node.contains("consumer-config") || node.contains("producer-config") || node.contains("producer-control")) {
                addSecurityConf(properties);
            }
            listValues(properties, nodePath);
            return properties;
        } else {
            return new Properties();
        }
    }

    private void addSecurityConf(Properties properties) throws Exception {
        if (isSecurity == null) {
            synchronized (this.getClass()) {
                if (isSecurity == null) {
                    String path = Constants.COMMON_ROOT + "/" + Constants.GLOBAL_SECURITY_CONF;
                    if (zookeeper.isExists(path)) {
                        Properties pro = zookeeper.getProperties(path);
                        if (StringUtils.equals(pro.getProperty("AuthenticationAndAuthorization"), Constants.SECURITY_CONFIG_TRUE_VALUE)) {
                            isSecurity = true;
                        } else {
                            isSecurity = false;
                        }
                    } else {
                        isSecurity = false;
                    }
                }
            }
        }
        if (isSecurity) {
            properties.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, "SASL_PLAINTEXT");
        }
    }

    private String buildPath(String node) {
        String nodePath;
        if (node.startsWith("/")) {
            nodePath = node;
        } else {
            nodePath = path + "/" + node;
        }
        if (!nodePath.endsWith(EXT_PATTERN)) {
            nodePath += EXT_PATTERN;
        }
        return nodePath;
    }

    private void listValues(Properties properties, String path) {
        logger.info("properties:{}, values:{}", path, properties.toString());

//        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
//            logger.info(String.format("%s=%s", entry.getKey(), entry.getValue().toString()));
//        }
    }
}


text:
<?php

namespace Richpolis\GalMonBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * SemanaVotacionesRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class SemanaVotacionesRepository extends EntityRepository {

    public function getMaxPosicion() {
        $em = $this->getEntityManager();
        $query = $em->createQuery('
            SELECT COUNT(s.posicion) as value
            FROM RichpolisGalMonBundle:SemanaVotaciones s
            ORDER BY s.posicion ASC
            ');
        $max = $query->getResult();
        return $max[0]['value'];
    }

    public function getSemanaActual($em=null) {
        if($em==null){
            $em = $this->getEntityManager();
        }
        /*
        $query = $em->createQuery('
                   SELECT s,v
                   FROM RichpolisGalMonBundle:SemanaVotaciones s
                   JOIN s.votaciones v
                   WHERE s.isActive=:active
                   ORDER BY s.posicion DESC,v.posicion ASC
                ')->setParameters(array('active' => true));
        $semanas=$query->getResult();
        */

        $query=$this->createQueryBuilder('s')
                    //->select(array('s','v'))
                    //->from('RichpolisGalMonBundle:SemanaVotaciones','s')
                    //->leftJoin('s.votaciones', 'v')
                    ->where('s.isActive=:active')
                    ->setParameter('active', true)
                    ->orderBy('s.posicion','DESC')
                    //->addOrderBy('v.posicion','ASC')
               ;
        $semanas=$query->getQuery()->getResult();
        return $semanas[0];
    }

    public function getSemanaConGaleriaPorId($semana) {
        $em = $this->getEntityManager();
        $semanas=null;
        if($semana>0){
            $query = $em->createQuery('
                    SELECT s,v
                    FROM RichpolisGalMonBundle:SemanaVotaciones s
                    LEFT JOIN s.votaciones v
                    WHERE s.id = :semana
                    ORDER BY v.posicion ASC
                ')->setParameters(array('semana' => $semana));

        }else{
            return $this->getSemanaActual($em);
        }

    }

    public function getSemanasExceptoSemanaActual($semana_actual = 0, $activas = true) {
        $em = $this->getEntityManager();
        $query = $em->createQuery('
                    SELECT s
                    FROM RichpolisGalMonBundle:SemanaVotaciones s
                    WHERE s.id <> :actual
                    AND s.isActive = :active
                    ORDER BY s.posicion DESC
                ')->setParameters(array("actual" => $semana_actual, 'active' => $activas));
        return $query->getResult();
    }

    public function getQuerySemanasActivas($todos = true) {
        $query=$this->createQueryBuilder('s')
                    ->orderBy('s.posicion', 'DESC');
        if(!$todos){
            $query->where('s.isActive=:active')
                  ->setParameter('active', true);
        }
        return $query->getQuery();
    }

    public function getSemanasActivas($todos = false) {
        $query = $this->getQuerySemanasActivas($active);
        return $query->getResult();
    }

    public function getImagenSemanaAnterior(){
        //crear la consulta de solo semanas activas
        $query=$this->getQuerySemanasActivas(false);
        $semanas=$query->setMaxResults(2)->getResult();
        if(count($semanas)>1){
            //semana actual indice 0, semana anterior indice 1
            $semana_anterior=$semanas[1];
            //recuperar la imagen de la semana pasada
            $em = $this->getEntityManager();
            $query = $em->createQuery('
                    SELECT v, f
                    FROM RichpolisGalMonBundle:Votaciones v
                    LEFT JOIN v.fan f
                    WHERE v.semana = :actual
                    ORDER BY v.votacion DESC, v.createdAt
                ')->setParameters(array("actual" => $semana_anterior));
            $imagen=$query->getFirstResult();
            /*$queryImagen=$this->createQueryBuilder('v')
                              ->from('RichpolisGalMonBundle:Votaciones','v')
                              ->where('v.semana=:semana_anterior')
                              ->setParameter('semana_anterior', $semana_anterior)
                              ->orderBy('v.votacion DESC, v.createdAt');
            $imagen=$queryImagen->setMaxResults(1)->getQuery()->getFirstResult();*/
            return $imagen;
        }else{
            // no hay semana anterior
            return null;
        }
    }

    public function getVotacionesAleatorias(\Richpolis\GalMonBundle\Entity\SemanaVotaciones $semana_actual){
        if($semana_actual){
            //recuperamos las votaciones de la semana
            $em = $this->getEntityManager();
            $query = $em->createQuery('
                    SELECT v, f
                    FROM RichpolisGalMonBundle:Votaciones v
                    LEFT JOIN v.fan f
                    WHERE v.semana = :actual
                    AND v.isActive=:active
                    ORDER BY v.votacion DESC, v.createdAt
                ')->setParameters(array("actual" => $semana_actual,"active"=>true));

            /*
            $query=$this->createQueryBuilder('v')
                        ->from('RichpolisGalMonBundle:Votaciones','v')
                        ->where('v.semana=:semana_actual')
                        ->setParameter('semana_actual', $semana_actual)
                        ->orderBy('v.votacion DESC, v.createdAt');
            $votaciones=$query->getQuery()->getArrayResult();
             */
            $votaciones=$query->getResult();
            //mezclamos el arreglo e instanciamos un arreglo para los resultados
            shuffle($votaciones);
            $votacionesShow=array();
            //solo nos llevamos los tres primeros resultados
            $cont=0;
            foreach($votaciones as $votacion){
                if($cont<3){
                    $votacionesShow[]=$votacion;
                    $cont++;
                }else{
                    break;
                }
            }
            return $votacionesShow;
        }else{
            return null;
        }
    }

}


text:
<?php

/**
 * Class that works with PayPal Instant fpPayment Notification. It takes what was
 * sent from PayPal and sends an indentical response back to PayPal, then waits
 * for verification from PayPal
 *
 * NOTE it is wrong one don't use it!!!
 *
 * @package    fpPayment
 * @subpackage PayPal
 * @author		 Ton Sharp <Forma-PRO@66ton99.org.ua>
 */
class fpPaymentPayPalIpnStandard extends fpPaymentPayPalIpnBase
{

  protected $connection;

  protected $options = array(
    'url' => 'www.paypal.com',
    'url_path' => '/cgi-bin/webscr?',
    'form_fields' => array(
      'amount_1' => 0,
      'item_name_1' => '',
      'quantity_1' => 0,
    ),
    'form_hidden_fields' => array(
      '_info' => 'Array',
      'cmd' => '_cart',
      'upload' => 1,
      'shipping' => 0.00,
      'cancel_return' => '@fpPaymentPayPalPlugin_cancelled',
      'notify_url' => '@fpPaymentPayPalPlugin_callback',
      'return' => '@fpPaymentPayPalPlugin_success',
      'redirect_cmd' => '_xclick',
      # other:
      'currency_code' => '',
//    'custom' => '',
      'invoice' => 0,
      # required:
      'business' => ''
    )

  );

  protected $urlsKeys = array('cancel_return', 'notify_url', 'return');

  /**
   * Constructor
   *
   * @param unknown_type $paypalPostVars
   * @param int $timeout
   *
   * @return void
   */
  public function __construct($options = array())
  {
    $configOptions = sfConfig::get('fp_payment_paypal_ipn', array('standard' => $this->options));

    $configOptions = $configOptions['standard'];
    $this->options = array_merge($configOptions, $options);
    $this->url = 'https://' . $this->options['url'] . $this->options['url_path'];

    $data = array_merge($this->options['form_fields'], $this->options['form_hidden_fields']);

    parent::setData($this->convertRoutesToUrls($data));
    $this->getContext()
      ->getDispatcher()
        ->connect('fp_payment_order.after_create', array($this, 'addOrderToValues'));
    $this->getContext()
      ->getDispatcher()
        ->connect('fp_payment.on_process', array($this, 'addItemsToValues'));
  }

  /**
   * Retrun keys of urls
   *
   * @return array
   */
  public function getUrlKeys()
  {
    return $this->urlsKeys;
  }

  /**
   * returns the paypal payment status
   *
   * @TODO complet
   *
   * @return string
   */
  public function getPaymentStatus()
  {
    return $this->paypalPostVars['payment_status'];
  }

  /**
   * (non-PHPdoc)
   * @see fpPaymentIpnBase::process()
   */
  public function process()
  {
    $connection = new fpPaymentConnection($this->url);
    $orderId = fpPaymentContext::getInstance()->getOrderModel()->getId();
    foreach ($this->getUrlKeys() as $key) {
      $this->data[$key] = $this->data[$key] . urlencode('?orderId=' . $orderId);
    }
    $this->redirectUrl =  $this->url . $this->getProtocol()->fromArray($this->data);
    $this->getLoger()
      ->addArray($this->data, 'Send data to ' . $this->redirectUrl);
    return $this;
  }

	/**
   * Event handler. Add items to the values
   *
   * @param sfEvent $event - Keys: context, values
   *
   * @return viod
   */
  public function addItemsToValues(sfEvent $event)
  {
    /* @var $context fpPaymentContext */
    $context = $event['context'];
    $values = $event['values'];
    $i = 1;
    $taxes = 0.0;
    /* @var $val fpPaymentOrderItem */
    foreach ($context->getOrderModel()->getFpPaymentOrderItem() as $val) {
      $values['amount_' . $i] = $val->getPrice();
      $values['item_number_' . $i] = $val->getObjectId();
      $values['item_name_' . $i] = $val->getName();
      $values['quantity_' . $i] = $val->getQuantity();
      $values['shipping_' . $i] = $val->getShipping();
      if ($tax = $val->getTax()) {
        $taxes += $tax;
      }
      $i++;
    }
    if (!empty($taxes)) {
      $values['tax_cart'] = round($taxes, 2);
    }
    $values['currency_code'] = $context->getOrderModel()->getCurrency();
  }

  /**
   * Event handler. Add order to values
   *
   * @param sfEvent $event - Keys: values, context
   *
   * @return viod
   */
  public function addOrderToValues(sfEvent $event)
  {
    /* @var $context fpPaymentContext */
    $context = $event['context'];
    $order = $context->getOrderModel();
    $values = $event['values'];
    $values['invoice'] = $order->getId();
    $values['payer_id'] = $context->getCustomer()->getId();
    $order->setType(fpPaymentPayPalContext::NAME);
    $order->setStatus(fpPaymentOrderStatusEnum::IN_PROCESS);
    $order->save();
  }

  /**
   * (non-PHPdoc)
   * @see fpPaymentPayPalIpnBase::processNotifyValidate()
   */
  public function processNotifyValidate()
  {
    $this->addData(array('receiver_email' => $this->options['form_hidden_fields']['business']));
    return parent::processNotifyValidate();
  }
}


text:
/**
 * class SweepPruneBehavior < Behavior
 *
 * `Physics.behavior('sweep-prune')`.
 *
 * Sweep and Prune implementation for broad phase collision detection.
 *
 * This massively improves the speed of collision detection. It's set up to always be used with [[BodyCollisionDetection]], and [[BodyImpulseResponse]].
 *
 * Additional options include:
 * - channel: The channel to publish collision candidates to. (default: `collisions:candidates`)
 **/
Physics.behavior('sweep-prune', function( parent ){

    var uid = 1;

    // Get a unique numeric id for internal use
    var getUniqueId = function getUniqueId(){

        return uid++;
    };

    // add z: 2 to get this to work in 3D
    var dof = { x: 0, y: 1 }; // degrees of freedom
    // change to "3" to get it to work in 3D
    var maxDof = 2;

    var pairHash = Physics.util.pairHash;

    return {

        // extended
        init: function( options ){

            parent.init.call( this );
            this.options.defaults({
                channel: 'collisions:candidates' //default channel
            });
            this.options( options );

            this.encounters = [];
            this.candidates = [];

            this.partitionWidth = 0;
            this.partitionHeight = 0;

            this.clear();
        },

        /**
         * SweepPruneBehavior#clear()
         *
         * Refresh tracking data
         **/
        clear: function(){

            this.tracked = [];
            this.pairs = []; // pairs selected as candidate collisions by broad phase
            this.intervalSections = [[]];
            this.scratchSections = [];
            this.sectionMinX = 0;
            this.sectionMinY = 0;
            this.sectionMaxX = 0;
            this.sectionMaxY = 0;
            this.addIntervalSection( 0, 0 );
        },

        addIntervalSection: function ( x, y ){

            this.sectionMinX = Math.min(this.sectionMinX, x);
            this.sectionMinY = Math.min(this.sectionMinY, y);
            this.sectionMaxX = Math.max(this.sectionMaxX, x);
            this.sectionMaxY = Math.max(this.sectionMaxY, y);

            if (this.intervalSections[x] === undefined) {
                this.intervalSections[x] = [];
            }
            if (this.intervalSections[x][y] === undefined) {
                var intervalList = [];
                for ( var xyz = 0; xyz < maxDof; ++xyz ){

                    intervalList[ xyz ] = [];
                }

                this.intervalSections[x][y] = intervalList;
            }
        },

        addIntervalSectionFillEmpty: function ( x, y ){

            var i, il, j, jl;

            this.sectionMinX = Math.min(this.sectionMinX, x);
            this.sectionMinY = Math.min(this.sectionMinY, y);
            this.sectionMaxX = Math.max(this.sectionMaxX, x);
            this.sectionMaxY = Math.max(this.sectionMaxY, y);

            for (i = this.sectionMinX, il = this.sectionMaxX; i <= il; i++) {
                for (j = this.sectionMinY, jl = this.sectionMaxY; j <= jl; j++) {
                    if (this.intervalSections[i] === undefined) {
                        this.intervalSections[i] = [];
                    }
                    if (this.intervalSections[i][j] === undefined) {
                        var intervalList = [];
                        for ( var xyz = 0; xyz < maxDof; ++xyz ){

                            intervalList[ xyz ] = [];
                        }

                        this.intervalSections[i][j] = intervalList;
                    }
                }
            }
        },

        findIntersectingSections: function ( min, max, createEmpty ){
            var i, j, xmin, xmax, ymin, ymax, section;

            Physics.util.clearArray( this.scratchSections );

            if (this.isWorldPartitioned()) {
                xmin = Math.floor(min.x / this.partitionWidth);
                ymin = Math.floor(min.y / this.partitionHeight);
                xmax = Math.floor(max.x / this.partitionWidth);
                ymax = Math.floor(max.y / this.partitionHeight);

                for (j = ymin; j <= ymax; j++) {
                    for (i = xmin; i <= xmax; i++) {
                        section = this.intervalSections[i] !== undefined ? this.intervalSections[i][j] : undefined;
                        if (section === undefined && createEmpty) {
                            this.addIntervalSectionFillEmpty(i, j);
                            section = this.intervalSections[i][j];
                        }
                        if (section !== undefined) {
                            this.scratchSections.push(section);
                        }
                    }
                }
            } else {
                this.scratchSections.push(this.intervalSections[0][0]);
            }

            return this.scratchSections;
        },

        /**
         * SweepPruneBehavior#setPartitionDimensions( x, y )
         *
         * Setting dimensions to any value other than 0 will cause
         * the interval lists to be split over a set of dimensions
         * each equal to the size set. This can be used to partition
         * the world in to sections and only perform collision detection
         * in specific sections.
         **/
        setPartitionDimensions: function( x, y ){

            if ( (x === 0 && y === 0) || (x !== 0 && y !== 0) ) {
                this.partitionWidth = x;
                this.partitionHeight = y;
                if (this.tracked.length > 0) {
                    throw 'Error: Attempt to change dimensions with body data present.';
                }
                this.intervalSections = [[]];
                this.addIntervalSection( 0, 0 );
            } else {
                throw 'Error: Attempt to set invalid partition dimensions. Both dimensions must be either zero or both non-zero.';
            }
        },

        isWorldPartitioned: function (){
            return !(this.partitionWidth === 0 && this.partitionHeight === 0);
        },

        // extended
        connect: function( world ){

            world.on( 'add:body', this.trackBody, this );
            world.on( 'remove:body', this.untrackBody, this );
            world.on( 'integrate:positions', this.sweep, this, 1 );

            // add current bodies
            var bodies = world.getBodies();
            for ( var i = 0, l = bodies.length; i < l; ++i ){

                this.trackBody({ body: bodies[ i ] });
            }
        },

        // extended
        disconnect: function( world ){

            world.off( 'add:body', this.trackBody, this );
            world.off( 'remove:body', this.untrackBody, this );
            world.off( 'integrate:positions', this.sweep, this, 1 );
            this.clear();
        },

        /** internal
         * SweepPruneBehavior#broadPhase() -> Array
         * + (Array): The candidate data of overlapping aabbs
         *
         * Execute the broad phase and get candidate collisions
         **/
        broadPhase: function(){
            this.updateIntervals();
            this.sortIntervalLists();

            Physics.util.clearArray( this.candidates );
            var i, l, j, lj;
            for ( i = this.sectionMinX, l = this.sectionMaxX; i <= l; i++ ){
                for ( j = this.sectionMinY, lj = this.sectionMaxY; j <= lj; j++) {
                    this.checkOverlaps( i, j );
                }
            }

            return this.candidates;
        },

        /** internal
         * SweepPruneBehavior#sortIntervalLists()
         *
         * Simple insertion sort for each axis
         **/
        sortIntervalLists: function(){

            var list
                ,section
                ,len
                ,i
                ,hole
                ,bound
                ,boundVal
                ,left
                ,leftVal
                ,axis
                ,sx
                ,sy
                ,sxl
                ,syl
                ;

            for ( sx = this.sectionMinX, sxl = this.sectionMaxX; sx <= sxl; sx++ ){

                for ( sy = this.sectionMinY, syl = this.sectionMaxY; sy <= syl; sy++ ) {
                    section = this.intervalSections[ sx ][ sy ];

                    // for each axis...
                    for ( var xyz = 0; xyz < maxDof; ++xyz ){

                        // get the intervals for that axis
                        list = section[ xyz ];
                        i = 0;
                        len = list.length;
                        axis = xyz;

                        // for each interval bound...
                        while ( (++i) < len ){

                            // store bound
                            bound = list[ i ];
                            boundVal = bound.val.get( axis );
                            hole = i;

                            left = list[ hole - 1 ];
                            leftVal = left && left.val.get( axis );

                            // while others are greater than bound...
                            while (
                                hole > 0 &&
                                (
                                    leftVal > boundVal ||
                                    // if it's an equality, only move it over if
                                    // the hole was created by a minimum
                                    // and the previous is a maximum
                                    // so that we detect contacts also
                                    leftVal === boundVal &&
                                    ( left.type && !bound.type )
                                )
                            ) {

                                // move others greater than bound to the right
                                list[ hole ] = left;
                                hole--;
                                left = list[ hole - 1 ];
                                leftVal = left && left.val.get( axis );
                            }

                            // insert bound in the hole
                            list[ hole ] = bound;
                        }
                    }
                }
            }
        },

        /** internal
         * SweepPruneBehavior#getPair( tr1, tr2, doCreate ) -> Object
         * - tr1 (Object): First tracker
         * - tr2 (Object): Second tracker
         * - doCreate (Boolean): Create if not found
         * + (Object): Pair object or null if not found
         *
         * Get a pair object for the tracker objects
         **/
        getPair: function(tr1, tr2, doCreate){

            if ( tr1.body.treatment === 'static' && tr2.body.treatment === 'static' ) {
                return null;
            }

            var hash = pairHash( tr1.id, tr2.id );

            if ( hash === false ){
                return null;
            }

            var c = this.pairs[ hash ];

            if ( c === undefined ){

                if ( !doCreate ){
                    return null;
                }

                c = this.pairs[ hash ] = {
                    bodyA: tr1.body,
                    bodyB: tr2.body,
                    flag: 1
                };
            }

            if ( doCreate ){
                c.flag = 1;
            }

            return c;
        },

        /** internal
         * SweepPruneBehavior#checkOverlaps( x, y ) -> Array
         * + (Array): List of candidate collisions
         *
         * Check each axis for overlaps of bodies AABBs and adds to the current list of candidates.
         **/
        checkOverlaps: function( x, y ){

            var isX
                ,hash
                ,tr1
                ,tr2
                ,bound
                ,list
                ,len
                ,i
                ,j
                ,c
                // determine which axis is the last we need to check
                ,collisionFlag = 1 << (dof.z + 1) << (dof.y + 1) << (dof.x + 1)
                ,encounters = this.encounters
                ,enclen = 0
                ,candidates = this.candidates
                ;

            Physics.util.clearArray( encounters );

            for ( var xyz = 0; xyz < maxDof; ++xyz ){

                // is the x coord
                isX = (xyz === 0);
                // get the interval list for this axis
                list = this.intervalSections[ x ][ y ][ xyz ];

                // for each interval bound
                for ( i = 0, len = list.length; i < len; i++ ){

                    bound = list[ i ];
                    tr1 = bound.tracker;

                    if ( bound.type ){

                        // is a max

                        j = enclen;

                        for ( j = enclen - 1; j >= 0; j-- ){

                            tr2 = encounters[ j ];

                            // if they are the same tracked interval
                            if ( tr2 === tr1 ){

                                // remove the interval from the encounters list
                                // faster than .splice()
                                if ( j < enclen - 1 ) {

                                    encounters[ j ] = encounters.pop();

                                } else {

                                    // encountered a max right after a min... no overlap
                                    encounters.pop();
                                }

                                enclen--;

                            } else {

                                // check if we have flagged this pair before
                                // if it's the x axis, create a pair
                                c = this.getPair( tr1, tr2, isX );

                                if ( c && c.flag < collisionFlag ){

                                    // if it's greater than the axis index, set the flag
                                    // to = 0.
                                    // if not, increment the flag by one.
                                    c.flag = c.flag << (xyz + 1);

                                    // c.flag will equal collisionFlag
                                    // if we've incremented the flag
                                    // enough that all axes are overlapping
                                    if ( c.flag === collisionFlag ){

                                        // overlaps on all axes.
                                        // add it to possible collision
                                        // candidates list for narrow phase

                                        candidates.push( c );
                                    }
                                }
                            }
                        }

                    } else {

                        // is a min
                        // just add this minimum to the encounters list
                        enclen = encounters.push( tr1 );
                    }
                }
            }

            return candidates;
        },

        /** internal
         * SweepPruneBehavior#updateIntervals()
         *
         * Update position intervals on each axis
         **/
        updateIntervals: function(){

            var tr
                ,intr
                ,aabb
                ,list = this.tracked
                ,i = list.length
                ,crossedBoundary = false
                ,sections
                ,sectionsQuery
                ,sc
                ,sl
                ;

            // for all tracked bodies
            while ( (--i) >= 0 ){

                tr = list[ i ];
                intr = tr.interval;
                sections = tr.sections;
                aabb = tr.body.aabb();

                if ( this.isWorldPartitioned() ){
                    if (
                        (Math.floor(intr.min.val.x / this.partitionWidth) !== Math.floor((aabb.x - aabb.hw) / this.partitionWidth)) ||
                        (Math.floor(intr.max.val.x / this.partitionWidth) !== Math.floor((aabb.x + aabb.hw) / this.partitionWidth)) ||
                        (Math.floor(intr.min.val.y / this.partitionHeight) !== Math.floor((aabb.y - aabb.hh) / this.partitionHeight)) ||
                        (Math.floor(intr.max.val.y / this.partitionHeight) !== Math.floor((aabb.y + aabb.hh) / this.partitionHeight))
                    ){
                        crossedBoundary = true;
                    }
                }

                // copy the position (plus or minus) the aabb half-dimensions
                // into the min/max intervals
                intr.min.val.clone( aabb ).sub( aabb.hw, aabb.hh );
                intr.max.val.clone( aabb ).add( aabb.hw, aabb.hh );

                if ( crossedBoundary ){
                    sectionsQuery = this.findIntersectingSections( intr.min.val, intr.max.val, true );

                    for ( sc = 0, sl = sections.length; sc < sl; sc++ ){
                        if ( sectionsQuery.indexOf( sections[ sc ] ) === -1 ){
                            // we moved out of this section
                            this.removeFromIntervalList( tr, sections[ sc ] );
                            sections.splice(sc, 1);
                            sc--;
                            sl--;
                        }
                    }

                    for ( sc = 0, sl = sectionsQuery.length; sc < sl; sc++ ){
                        if ( sections.indexOf( sectionsQuery[ sc ] ) === -1 ){
                            // we moved into a new section
                            this.addToIntervalList( tr, sectionsQuery[ sc ] );
                            sections.push(sectionsQuery[ sc ]);
                        }
                    }
                }
            }
        },

        /** internal
         * SweepPruneBehavior#trackBody( data )
         * - data (Object): Event data
         *
         * Event callback to add body to list of those tracked by sweep and prune
         **/
        trackBody: function( data ){

            var body = data.body
                ,aabb = data.body.aabb()
                ,tracker = {

                    id: getUniqueId(),
                    body: body
                }
                ,intr = {

                    min: {
                        type: false, //min
                        val: new Physics.vector(),
                        tracker: tracker
                    },

                    max: {
                        type: true, //max
                        val: new Physics.vector(),
                        tracker: tracker
                    }
                }
                ,lists
                ;

            lists = this.findIntersectingSections( intr.min.val, intr.max.val, true );

            tracker.interval = intr;
            tracker.sections = lists.slice();
            this.tracked.push( tracker );

            for ( var i = 0; i < lists.length; i++ ){
                this.addToIntervalList( tracker, lists[ i ] );
            }
        },

        /** internal
         * SweepPruneBehavior#untrackBody( data )
         * - data (Object): Event data
         *
         * Event callback to remove body from list of those tracked
         **/
        untrackBody: function( data ){

            var body = data.body
                ,list
                ,minmax
                ,trackedList = this.tracked
                ,tracker
                ,count
                ,sections
                ;

            for ( var i = 0, l = trackedList.length; i < l; ++i ){

                tracker = trackedList[ i ];

                if ( tracker.body === body ){

                    // remove the tracker at this index
                    trackedList.splice(i, 1);

                    sections = tracker.sections;

                    for ( var listNum = 0; listNum < sections.length; listNum++ ){

                        this.removeFromIntervalList( tracker, sections[listNum] );
                    }

                    break;
                }
            }
        },

        addToIntervalList: function ( tracker, list ) {
            var intr = tracker.interval;
            for ( var xyz = 0; xyz < maxDof; ++xyz ){
                list[ xyz ].push( intr.min, intr.max );
            }
        },

        removeFromIntervalList: function ( tracker, list ) {

            var innerlist, count, minmax;

            for ( var xyz = 0; xyz < maxDof; ++xyz ){

                count = 0;
                innerlist = list[ xyz ];

                for ( var j = 0, m = innerlist.length; j < m; ++j ){

                    minmax = innerlist[ j ];

                    if ( minmax === tracker.interval.min || minmax === tracker.interval.max ){

                        // remove interval from list
                        innerlist.splice(j, 1);
                        j--;
                        m--;

                        if (count > 0){
                            break;
                        }

                        count++;
                    }
                }
            }
        },

        /** internal
         * SweepPruneBehavior#sweep( data )
         * - data (Object): Event data
         *
         * Event callback to sweep and publish event if any candidate collisions are found
         **/
        sweep: function( data ){

            var self = this
                ,candidates
                ;

            candidates = self.broadPhase();

            if ( candidates.length ){

                this._world.emit( this.options.channel, {
                    candidates: candidates
                });
            }
        }
    };
});