text:
#region License

#endregion

using System;

namespace Quartz.Impl.Triggers
{
	///
	/// A concrete <see cref="ITrigger" /> that is used to fire a <see cref="IJobDetail" />
	/// at a given moment in time, and optionally repeated at a specified interval.
	///
    /// <seealso cref="ITrigger" />
	/// <seealso cref="ICronTrigger" />
	/// <author>James House</author>
	/// <author>Contributions by Lieven Govaerts of Ebitec Nv, Belgium.</author>
	/// <author>Marko Lahma (.NET)</author>
	[Serializable]
	public class SimpleTriggerImpl : AbstractTrigger, ISimpleTrigger
	{
        ///
        /// Used to indicate the 'repeat count' of the trigger is indefinite. Or in
        /// other words, the trigger should repeat continually until the trigger's
        /// ending timestamp.
        ///
        public const int RepeatIndefinitely = -1;
        private const int YearToGiveupSchedulingAt = 2299;

        private DateTimeOffset? nextFireTimeUtc;
		private DateTimeOffset? previousFireTimeUtc;

        private int repeatCount;
        private TimeSpan repeatInterval = TimeSpan.Zero;
        private int timesTriggered;

        ///
        /// Create a <see cref="SimpleTriggerImpl" /> with no settings.
        ///
        public SimpleTriggerImpl()
        {
        }

        ///
        /// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
        /// not repeat.
        ///
        public SimpleTriggerImpl(string name) : this(name, null)
        {
        }

        ///
        /// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
        /// not repeat.
        ///
        public SimpleTriggerImpl(string name, string group)
            : this(name, group, SystemTime.UtcNow(), null, 0, TimeSpan.Zero)
        {
        }

        ///
        /// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
        /// repeat at the given interval the given number of times.
        ///
        public SimpleTriggerImpl(string name, int repeatCount, TimeSpan repeatInterval)
            : this(name, null, repeatCount, repeatInterval)
        {
        }

        ///
        /// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
        /// repeat at the given interval the given number of times.
        ///
        public SimpleTriggerImpl(string name, string group, int repeatCount, TimeSpan repeatInterval)
            : this(name, group, SystemTime.UtcNow(), null, repeatCount, repeatInterval)
        {
        }

        ///
        /// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
        /// and not repeat.
        ///
        public SimpleTriggerImpl(string name, DateTimeOffset startTimeUtc)
            : this(name, null, startTimeUtc)
        {
        }

        ///
        /// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
        /// and not repeat.
        ///
        public SimpleTriggerImpl(string name, string group, DateTimeOffset startTimeUtc)
            : this(name, group, startTimeUtc, null, 0, TimeSpan.Zero)
        {
        }

        ///
        /// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
        /// and repeat at the given interval the given number of times, or until
        /// the given end time.
        ///
        /// <param name="name">The name.</param>
        /// <param name="startTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param>
        /// <param name="endTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
        /// to quit repeat firing.</param>
        /// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
        /// firing, use <see cref="RepeatIndefinitely "/> for unlimited times.</param>
        /// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
        public SimpleTriggerImpl(string name, DateTimeOffset startTimeUtc,
            DateTimeOffset? endTimeUtc, int repeatCount, TimeSpan repeatInterval)
            : this(name, null, startTimeUtc, endTimeUtc, repeatCount, repeatInterval)
        {
        }

        ///
        /// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
        /// and repeat at the given interval the given number of times, or until
        /// the given end time.
        ///
        /// <param name="name">The name.</param>
        /// <param name="group">The group.</param>
        /// <param name="startTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param>
        /// <param name="endTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
        /// to quit repeat firing.</param>
        /// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
        /// firing, use <see cref="RepeatIndefinitely "/> for unlimited times.</param>
        /// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
        public SimpleTriggerImpl(string name, string group, DateTimeOffset startTimeUtc,
            DateTimeOffset? endTimeUtc, int repeatCount, TimeSpan repeatInterval)
            : base(name, group)
        {
            StartTimeUtc = startTimeUtc;
            EndTimeUtc = endTimeUtc;
            RepeatCount = repeatCount;
            RepeatInterval = repeatInterval;
        }

        ///
        /// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
        /// fire the identified <see cref="IJob" /> and repeat at the given
        /// interval the given number of times, or until the given end time.
        ///
        /// <param name="name">The name.</param>
        /// <param name="group">The group.</param>
        /// <param name="jobName">Name of the job.</param>
        /// <param name="jobGroup">The job group.</param>
        /// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
        /// to fire.</param>
        /// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
        /// to quit repeat firing.</param>
        /// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
        /// firing, use RepeatIndefinitely for unlimited times.</param>
        /// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
        public SimpleTriggerImpl(string name, string group, string jobName, string jobGroup, DateTimeOffset startTimeUtc,
                 DateTimeOffset? endTimeUtc,
                 int repeatCount, TimeSpan repeatInterval)
            : base(name, group, jobName, jobGroup)
        {
            StartTimeUtc = startTimeUtc;
            EndTimeUtc = endTimeUtc;
            RepeatCount = repeatCount;
            RepeatInterval = repeatInterval;
        }

        ///
        /// Get or set the number of times the <see cref="SimpleTriggerImpl" /> should
        /// repeat, after which it will be automatically deleted.
        ///
        /// <seealso cref="RepeatIndefinitely" />
        public int RepeatCount
        {
            get { return repeatCount; }

            set
            {
                if (value < 0 && value != RepeatIndefinitely)
                {
                    throw new ArgumentException("Repeat count must be >= 0, use the constant RepeatIndefinitely for infinite.");
                }

                repeatCount = value;
            }
        }

        ///
        /// Get or set the time interval at which the <see cref="ISimpleTrigger" /> should repeat.
        ///
        public TimeSpan RepeatInterval
        {
            get { return repeatInterval; }

            set
            {
                if (value < TimeSpan.Zero)
                {
                    throw new ArgumentException("Repeat interval must be >= 0");
                }

                repeatInterval = value;
            }
        }

        ///
        /// Get or set the number of times the <see cref="ISimpleTrigger" /> has already
        /// fired.
        ///
        public virtual int TimesTriggered
        {
            get { return timesTriggered; }
            set { timesTriggered = value; }
        }

	    public override IScheduleBuilder GetScheduleBuilder()
	    {
            SimpleScheduleBuilder sb = SimpleScheduleBuilder.Create()
            .WithInterval(RepeatInterval)
            .WithRepeatCount(RepeatCount);

            switch (MisfireInstruction)
            {
                case Quartz.MisfireInstruction.SimpleTrigger.FireNow: sb.WithMisfireHandlingInstructionFireNow();
                    break;
                case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount: sb.WithMisfireHandlingInstructionNextWithExistingCount();
                    break;
                case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount : sb.WithMisfireHandlingInstructionNextWithRemainingCount();
                    break;
                case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount : sb.WithMisfireHandlingInstructionNowWithExistingCount();
                    break;
                case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount: sb.WithMisfireHandlingInstructionNowWithRemainingCount();
                    break;
            }

            return sb;
	    }

	    ///
        /// Returns the final UTC time at which the <see cref="ISimpleTrigger" /> will
        /// fire, if repeatCount is RepeatIndefinitely, null will be returned.
        /// <para>
        /// Note that the return time may be in the past.
        /// </para>
        ///
        public override DateTimeOffset? FinalFireTimeUtc
        {
            get
            {
                if (repeatCount == 0)
                {
                    return StartTimeUtc;
                }

                if (repeatCount == RepeatIndefinitely && !EndTimeUtc.HasValue)
                {
                    return null;
                }

                if (repeatCount == RepeatIndefinitely && !EndTimeUtc.HasValue)
                {
                    return null;
                }
                else if (repeatCount == RepeatIndefinitely)
                {
                    return GetFireTimeBefore(EndTimeUtc);
                }

                DateTimeOffset lastTrigger = StartTimeUtc.AddMilliseconds(repeatCount * repeatInterval.TotalMilliseconds);

                if (!EndTimeUtc.HasValue || lastTrigger < EndTimeUtc.Value)
                {
                    return lastTrigger;
                }
                else
                {
                    return GetFireTimeBefore(EndTimeUtc);
                }
            }
        }

        ///
        /// Tells whether this Trigger instance can handle events
        /// in millisecond precision.
        ///
        /// <value></value>
        public override bool HasMillisecondPrecision
        {
            get { return true; }
        }

		///
		/// Validates the misfire instruction.
		///
		/// <param name="misfireInstruction">The misfire instruction.</param>
		/// <returns></returns>
		protected override bool ValidateMisfireInstruction(int misfireInstruction)
		{
            if (misfireInstruction < Quartz.MisfireInstruction.IgnoreMisfirePolicy)
            {
                return false;
            }

            if (misfireInstruction > Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount)
            {
                return false;
            }

            return true;

		}

		///
		/// Updates the <see cref="ISimpleTrigger" />'s state based on the
        /// MisfireInstruction value that was selected when the <see cref="ISimpleTrigger" />
		/// was created.
		///
		/// <remarks>
		/// If MisfireSmartPolicyEnabled is set to true,
		/// then the following scheme will be used:

		///

		///
If the Repeat Count is 0, then the instruction will
        /// be interpreted as <see cref="MisfireInstruction.SimpleTrigger.FireNow" />.

		///
If the Repeat Count is <see cref="RepeatIndefinitely" />, then
        /// the instruction will be interpreted as <see cref="MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount" />.
        /// WARNING: using MisfirePolicy.SimpleTrigger.RescheduleNowWithRemainingRepeatCount
		/// with a trigger that has a non-null end-time may cause the trigger to
		/// never fire again if the end-time arrived during the misfire time span.
		///

		///
If the Repeat Count is > 0, then the instruction
        /// will be interpreted as <see cref="MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount" />.
		///

		///

		/// </remarks>
		public override void UpdateAfterMisfire(ICalendar cal)
		{
			int instr = MisfireInstruction;
			if (instr == Quartz.MisfireInstruction.SmartPolicy)
			{
				if (RepeatCount == 0)
				{
                    instr = Quartz.MisfireInstruction.SimpleTrigger.FireNow;
				}
				else if (RepeatCount == RepeatIndefinitely)
				{
                    instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount;

				}
				else
				{
                    instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount;
				}
			}
            else if (instr == Quartz.MisfireInstruction.SimpleTrigger.FireNow && RepeatCount != 0)
			{
                instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount;
			}

            if (instr == Quartz.MisfireInstruction.SimpleTrigger.FireNow)
			{
				nextFireTimeUtc = SystemTime.UtcNow();
			}
			else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount)
			{
                DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow());

                while (newFireTime.HasValue && cal != null && !cal.IsTimeIncluded(newFireTime.Value))
				{
					newFireTime = GetFireTimeAfter(newFireTime);

                    if (!newFireTime.HasValue)
                    {
                        break;
                    }

                    //avoid infinite loop
                    if (newFireTime.Value.Year > YearToGiveupSchedulingAt)
                    {
                        newFireTime = null;
                    }
				}
				nextFireTimeUtc = newFireTime;
			}
			else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount)
			{
                DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow());

				while (newFireTime.HasValue && cal != null && !cal.IsTimeIncluded(newFireTime.Value))
				{
					newFireTime = GetFireTimeAfter(newFireTime);

                    if (!newFireTime.HasValue)
                    {
                        break;
                    }

                    //avoid infinite loop
                    if (newFireTime.Value.Year > YearToGiveupSchedulingAt)
                    {
                        newFireTime = null;
                    }
				}

				if (newFireTime.HasValue)
				{
					int timesMissed = ComputeNumTimesFiredBetween(nextFireTimeUtc, newFireTime);
					TimesTriggered = TimesTriggered + timesMissed;
				}

                nextFireTimeUtc = newFireTime;
			}
			else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount)
			{
				DateTimeOffset newFireTime = SystemTime.UtcNow();
				if (repeatCount != 0 && repeatCount != RepeatIndefinitely)
				{
					RepeatCount = RepeatCount - TimesTriggered;
					TimesTriggered = 0;
				}

				if (EndTimeUtc.HasValue && EndTimeUtc.Value < newFireTime)
				{
					nextFireTimeUtc = null; // We are past the end time
				}
				else
				{
					StartTimeUtc = newFireTime;
					nextFireTimeUtc = newFireTime;
				}
			}
			else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount)
			{
				DateTimeOffset newFireTime = SystemTime.UtcNow();
				int timesMissed = ComputeNumTimesFiredBetween(nextFireTimeUtc, newFireTime);

				if (repeatCount != 0 && repeatCount != RepeatIndefinitely)
				{
					int remainingCount = RepeatCount - (TimesTriggered + timesMissed);
					if (remainingCount <= 0)
					{
						remainingCount = 0;
					}
					RepeatCount = remainingCount;
					TimesTriggered = 0;
				}

				if (EndTimeUtc.HasValue && EndTimeUtc.Value < newFireTime)
				{
					nextFireTimeUtc = null; // We are past the end time
				}
				else
				{
					StartTimeUtc = newFireTime;
					nextFireTimeUtc = newFireTime;
				}
			}
		}

		///
		/// Called when the <see cref="IScheduler" /> has decided to 'fire'
		/// the trigger (Execute the associated <see cref="IJob" />), in order to
		/// give the <see cref="ITrigger" /> a chance to update itself for its next
		/// triggering (if any).
		///
		/// <seealso cref="JobExecutionException" />
		public override void Triggered(ICalendar cal)
		{
			timesTriggered++;
			previousFireTimeUtc = nextFireTimeUtc;
			nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);

			while (nextFireTimeUtc.HasValue && cal != null && !cal.IsTimeIncluded(nextFireTimeUtc.Value))
			{
				nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);

                if (!nextFireTimeUtc.HasValue)
                {
                     break;
                }

                //avoid infinite loop
                if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
                {
                    nextFireTimeUtc = null;
                }
			}
		}

        ///
        /// Updates the instance with new calendar.
        ///
        /// <param name="calendar">The calendar.</param>
        /// <param name="misfireThreshold">The misfire threshold.</param>
		public override void UpdateWithNewCalendar(ICalendar calendar, TimeSpan misfireThreshold)
		{
			nextFireTimeUtc = GetFireTimeAfter(previousFireTimeUtc);

            if (nextFireTimeUtc == null || calendar == null)
            {
                return;
            }

            DateTimeOffset now = SystemTime.UtcNow();
            while (nextFireTimeUtc.HasValue && !calendar.IsTimeIncluded(nextFireTimeUtc.Value))
            {
                nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);

                if (!nextFireTimeUtc.HasValue)
                {
                    break;
                }

                //avoid infinite loop
                if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
                {
                    nextFireTimeUtc = null;
                }

                if (nextFireTimeUtc != null && nextFireTimeUtc.Value < now)
                {
                    TimeSpan diff = now - nextFireTimeUtc.Value;
                    if (diff >= misfireThreshold)
                    {
                        nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
                    }
                }
            }
        }

		///
		/// Called by the scheduler at the time a <see cref="ITrigger" /> is first
		/// added to the scheduler, in order to have the <see cref="ITrigger" />
		/// compute its first fire time, based on any associated calendar.
		/// <para>
		/// After this method has been called, <see cref="GetNextFireTimeUtc" />
		/// should return a valid answer.
		/// </para>
		///
		/// <returns>
		/// The first time at which the <see cref="ITrigger" /> will be fired
		/// by the scheduler, which is also the same value <see cref="GetNextFireTimeUtc" />
		/// will return (until after the first firing of the <see cref="ITrigger" />).
		/// </returns>
        public override DateTimeOffset? ComputeFirstFireTimeUtc(ICalendar cal)
    	{
			nextFireTimeUtc = StartTimeUtc;

			while (cal != null && !cal.IsTimeIncluded(nextFireTimeUtc.Value))
			{
				nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);

                if (!nextFireTimeUtc.HasValue)
                {
                    break;
                }

                //avoid infinite loop
                if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
                {
                    return null;
                }
			}

			return nextFireTimeUtc;
		}

		///
		/// Returns the next time at which the <see cref="ISimpleTrigger" /> will
		/// fire. If the trigger will not fire again, <see langword="null" /> will be
		/// returned. The value returned is not guaranteed to be valid until after
		/// the <see cref="ITrigger" /> has been added to the scheduler.
		///
        public override DateTimeOffset? GetNextFireTimeUtc()
		{
			return nextFireTimeUtc;
		}

        public override void SetNextFireTimeUtc(DateTimeOffset? nextFireTime)
	    {
            nextFireTimeUtc = nextFireTime;
	    }

        public override void SetPreviousFireTimeUtc(DateTimeOffset? previousFireTime)
	    {
            previousFireTimeUtc = previousFireTime;
	    }

	    ///
	    /// Returns the previous time at which the <see cref="ISimpleTrigger" /> fired.
	    /// If the trigger has not yet fired, <see langword="null" /> will be
	    /// returned.
	    ///
	    public override DateTimeOffset? GetPreviousFireTimeUtc()
	    {
	        return previousFireTimeUtc;
	    }

		///
		/// Returns the next UTC time at which the <see cref="ISimpleTrigger" /> will
		/// fire, after the given UTC time. If the trigger will not fire after the given
		/// time, <see langword="null" /> will be returned.
		///
        public override DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTimeUtc)
		{
			if ((timesTriggered > repeatCount) && (repeatCount != RepeatIndefinitely))
			{
				return null;
			}

			if (!afterTimeUtc.HasValue)
			{
				afterTimeUtc = SystemTime.UtcNow();
			}

			if (repeatCount == 0 && afterTimeUtc.Value.CompareTo(StartTimeUtc) >= 0)
			{
				return null;
			}

			DateTimeOffset startMillis = StartTimeUtc;
			DateTimeOffset afterMillis = afterTimeUtc.Value;
			DateTimeOffset endMillis = !EndTimeUtc.HasValue ? DateTimeOffset.MaxValue : EndTimeUtc.Value;

			if (endMillis <= afterMillis)
			{
				return null;
			}

			if (afterMillis < startMillis)
			{
				return startMillis;
			}

			long numberOfTimesExecuted = (long) (((long) (afterMillis - startMillis).TotalMilliseconds / repeatInterval.TotalMilliseconds) + 1);

			if ((numberOfTimesExecuted > repeatCount) &&
				(repeatCount != RepeatIndefinitely))
			{
				return null;
			}

			DateTimeOffset time = startMillis.AddMilliseconds(numberOfTimesExecuted * repeatInterval.TotalMilliseconds);

			if (endMillis <= time)
			{
				return null;
			}

			return time;
		}

		///
		/// Returns the last UTC time at which the <see cref="ISimpleTrigger" /> will
		/// fire, before the given time. If the trigger will not fire before the
		/// given time, <see langword="null" /> will be returned.
		///
        public virtual DateTimeOffset? GetFireTimeBefore(DateTimeOffset? endUtc)
		{
			if (endUtc.Value < StartTimeUtc)
			{
				return null;
			}

			int numFires = ComputeNumTimesFiredBetween(StartTimeUtc, endUtc);
			return StartTimeUtc.AddMilliseconds(numFires*repeatInterval.TotalMilliseconds);
		}

        ///
        /// Computes the number of times fired between the two UTC date times.
        ///
        /// <param name="startTimeUtc">The UTC start date and time.</param>
        /// <param name="endTimeUtc">The UTC end date and time.</param>
        /// <returns></returns>
        public virtual int ComputeNumTimesFiredBetween(DateTimeOffset? startTimeUtc, DateTimeOffset? endTimeUtc)
		{
			long time = (long) (endTimeUtc.Value - startTimeUtc.Value).TotalMilliseconds;
			return (int) (time/repeatInterval.TotalMilliseconds);
		}

		///
		/// Determines whether or not the <see cref="ISimpleTrigger" /> will occur
		/// again.
		///
		public override bool GetMayFireAgain()
		{
			return GetNextFireTimeUtc().HasValue;
		}

		///
		/// Validates whether the properties of the <see cref="IJobDetail" /> are
		/// valid for submission into a <see cref="IScheduler" />.
		///
		public override void Validate()
		{
			base.Validate();

			if (repeatCount != 0 && repeatInterval.TotalMilliseconds < 1)
			{
				throw new SchedulerException("Repeat Interval cannot be zero.");
			}
		}
	}
}


text:
<?php
$this->breadcrumbs=array(
	'Entities'=>array('index'),
	'Manage',
);

$this->menu=array(
	array('label'=>'List Entity',  'url'=>array('index')),
	array('label'=>'Create Entity','url'=>array('create')),
);

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
	$('.search-form').toggle();
	return false;
});
$('.search-form form').submit(function(){
	$.fn.yiiGridView.update('entity-grid', {
		data: $(this).serialize()
	});
	return false;
});
");
?>

Manage Entities

You may optionally enter a comparison operator (<, <=, >, >=, <>
or =) at the beginning of each of your search values to specify how the comparison should be done.

<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>

<?php $this->renderPartial('_search',array(
	'model'=>$model,
)); ?>

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'		  =>'entity-grid',
	'dataProvider'=>$model->search(),
	'filter'	  =>$model,
	'columns'	  =>array(
		'id',
		'entity_name',
		'description',
		array(
			'class'=>'CButtonColumn',
		),
	),
)); ?>

redpajama_set_name: RedPajamaGithub


text:
var jsonData = $.ajax({
	//aqui va la url del servicio
	url: "http://localhost:8080/votweet-backend-master/metricasCandidatos/13/aprobacionRegionalPromedio",
	dataType: "json",
	async: false
}).responseJSON;

function procesarArray(json) {
	var datos = [];
	for (var i = 0, l = json.length; i < l; i++) {
		datos.push({ State: json[i].Identificador, freq:{Aprobación: json[i].aprobacion, Desaprobación: json[i].desaprobacion}},);
	}
	return datos;
}

var datosPre = procesarArray(jsonData);
/*var freqData=[
	{State:'I',freq:{Aprobación:786, Desaprobación:131}}
	,{State:'II',freq:{Aprobación:401, Desaprobación:400}}
	,{State:'III',freq:{Aprobación:932, Desaprobación:114}}
	,{State:'IV',freq:{Aprobación:832, Desaprobación:115}}
	,{State:'V',freq:{Aprobación:448, Desaprobación:330}}
	,{State:'VI',freq:{Aprobación:261, Desaprobación:106}}
	,{State:'VII',freq:{Aprobación:381, Desaprobación:204}}
	,{State:'VIII',freq:{Aprobación:231, Desaprobación:385}}
	,{State:'IX',freq:{Aprobación:797, Desaprobación:184}}
	,{State:'X',freq:{Aprobación:162, Desaprobación:379}}
	,{State:'XI',freq:{Aprobación:123, Desaprobación:307}}
	,{State:'XII',freq:{Aprobación:130, Desaprobación:457}}
	,{State:'RM',freq:{Aprobación:503, Desaprobación:200}}
	,{State:'XIV',freq:{Aprobación:204, Desaprobación:432}}
	,{State:'XV',freq:{Aprobación:401, Desaprobación:107}}
	];

	console.log(freqData);*/
dashboard('#dashboard',datosPre);


text:
package com.mentation.fsm.state;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.mentation.fsm.action.IStateEntryAction;
import com.mentation.fsm.message.IMessage;

public class FiniteState {
	private IStateEntryAction _stateEntryAction;
	private HashMap<IMessage, FiniteState> _transitionTable = new HashMap<>();
	private String _name;

	public FiniteState(IStateEntryAction stateEntryAction, String name) {
		_stateEntryAction = stateEntryAction;
		_name = name;
	}

	public void enter() {
		if (_stateEntryAction != null) {
			_stateEntryAction.execute();
		}
	}

	public void addTransition(IMessage messageClass, FiniteState state) {
		_transitionTable.put(messageClass, state);
	}

	protected FiniteState processMessage(IMessage message) {
		FiniteState nextState = _transitionTable.get(message);

		if (nextState == null) {
			return this;
		}

		nextState.enter();
		return nextState;
	}

	public String getName() {
		return _name;
	}

	@Override
	public String toString() {
		return "FiniteState [" + _name
				+ ", _stateEntryAction=" + _stateEntryAction
				+ ", " + listTransitionTable()
				+ "]";
	}

	private String listTransitionTable() {
		StringBuilder sb = new StringBuilder("TransitionTable: ");

		Iterator<Map.Entry<IMessage, FiniteState>> it = _transitionTable.entrySet().iterator();

		while (it.hasNext()) {
			Entry<IMessage, FiniteState> c = it.next();
			sb.append(c.getKey()).append(" -> ").append(c.getValue().getName());
		}

		return sb.toString();
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CertApplicationRequest xmlns="http://op.fi/mlp/xmldata/">
  <CustomerId/>
  <Timestamp/>
  <Environment/>
  <SoftwareId/>
  <Command/>
  <Compression>false</Compression>
  <Service/>
</CertApplicationRequest>


text:
class AppController < ApplicationController
	def show
	end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>net.officefloor.benchmarks</groupId>
	<artifactId>benchmarks</artifactId>
	<version>1.0.0</version>
	<packaging>pom</packaging>
	<name>OfficeFloor Benchmarks</name>
	<properties>
		<maven.compiler.source>11</maven.compiler.source>
		<maven.compiler.target>11</maven.compiler.target>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<modules>
		<module>woof_benchmark</module>
		<module>woof_benchmark_woof</module>
		<module>woof_benchmark_micro</module>
		<module>woof_benchmark_thread_affinity</module>
		<module>woof_benchmark_async</module>
		<module>woof_benchmark_r2dbc</module>
		<module>woof_benchmark_sqlclient</module>
		<module>woof_benchmark_rawsqlclient</module>
		<module>woof_benchmark_netty</module>
		<module>woof_benchmark_undertow</module>
		<module>woof_benchmark_vertx</module>
		<module>woof_benchmark_spring</module>
	</modules>
	<repositories>
		<repository>
			<id>Central first</id>
			<name>List central first so is used first</name>
			<url>https://repo.maven.apache.org/maven2/</url>
		</repository>
		<repository>
			<id>maven2-repository.officefloor.net</id>
			<name>OfficeFloor staging repository for Maven</name>
			<url>https://github.com/officefloor/maven/raw/repository/</url>
		</repository>
	</repositories>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>net.officefloor</groupId>
				<artifactId>bom</artifactId>
				<version>3.38.0</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
			<dependency>
				<groupId>net.officefloor.benchmarks</groupId>
				<artifactId>woof_benchmark</artifactId>
				<version>${project.version}</version>
			</dependency>
			<dependency>
				<groupId>net.officefloor.benchmarks</groupId>
				<artifactId>woof_benchmark_micro</artifactId>
				<version>${project.version}</version>
			</dependency>
			<dependency>
				<groupId>net.officefloor.benchmarks</groupId>
				<artifactId>woof_benchmark_woof</artifactId>
				<version>${project.version}</version>
			</dependency>
			<dependency>
				<groupId>com.github.spullara.mustache.java</groupId>
				<artifactId>compiler</artifactId>
				<version>0.9.7</version>
			</dependency>
			<dependency>
				<groupId>com.google.guava</groupId>
				<artifactId>guava</artifactId>
				<version>29.0-jre</version>
			</dependency>

			<!-- Necessary for PostGresql -->
			<dependency>
				<groupId>com.ongres.scram</groupId>
				<artifactId>client</artifactId>
				<version>2.1</version>
			</dependency>

		</dependencies>
	</dependencyManagement>
	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>3.8.1</version>
					<configuration>
						<debug>false</debug>
					</configuration>
				</plugin>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-shade-plugin</artifactId>
					<version>3.2.4</version>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>


text:
from django.http import HttpRequest
from django.template import (
    Context, RequestContext, Template, Variable, VariableDoesNotExist,
)
from django.template.context import RenderContext
from django.test import RequestFactory, SimpleTestCase, override_settings

class ContextTests(SimpleTestCase):

    def test_context(self):
        c = Context({"a": 1, "b": "xyzzy"})
        self.assertEqual(c["a"], 1)
        self.assertEqual(c.push(), {})
        c["a"] = 2
        self.assertEqual(c["a"], 2)
        self.assertEqual(c.get("a"), 2)
        self.assertEqual(c.pop(), {"a": 2})
        self.assertEqual(c["a"], 1)
        self.assertEqual(c.get("foo", 42), 42)

        with c.push():
            c['a'] = 2
            self.assertEqual(c['a'], 2)
        self.assertEqual(c['a'], 1)

        with c.push(a=3):
            self.assertEqual(c['a'], 3)
        self.assertEqual(c['a'], 1)

    def test_setdefault(self):
        c = Context()

        x = c.setdefault('x', 42)
        self.assertEqual(x, 42)
        self.assertEqual(c['x'], 42)

        x = c.setdefault('x', 100)
        self.assertEqual(x, 42)
        self.assertEqual(c['x'], 42)

    def test_resolve_on_context_method(self):
        """
        #17778 -- Variable shouldn't resolve RequestContext methods
        """
        empty_context = Context()

        with self.assertRaises(VariableDoesNotExist):
            Variable('no_such_variable').resolve(empty_context)

        with self.assertRaises(VariableDoesNotExist):
            Variable('new').resolve(empty_context)

        self.assertEqual(
            Variable('new').resolve(Context({'new': 'foo'})),
            'foo',
        )

    def test_render_context(self):
        test_context = RenderContext({'fruit': 'papaya'})

        # Test that push() limits access to the topmost dict
        test_context.push()

        test_context['vegetable'] = 'artichoke'
        self.assertEqual(list(test_context), ['vegetable'])

        self.assertNotIn('fruit', test_context)
        with self.assertRaises(KeyError):
            test_context['fruit']
        self.assertIsNone(test_context.get('fruit'))

    def test_flatten_context(self):
        a = Context()
        a.update({'a': 2})
        a.update({'b': 4})
        a.update({'c': 8})

        self.assertEqual(a.flatten(), {
            'False': False, 'None': None, 'True': True,
            'a': 2, 'b': 4, 'c': 8
        })

    def test_context_comparable(self):
        """
        #21765 -- equality comparison should work
        """

        test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}}

        self.assertEqual(Context(test_data), Context(test_data))

        a = Context()
        b = Context()
        self.assertEqual(a, b)

        # update only a
        a.update({'a': 1})
        self.assertNotEqual(a, b)

        # update both to check regression
        a.update({'c': 3})
        b.update({'c': 3})
        self.assertNotEqual(a, b)

        # make contexts equals again
        b.update({'a': 1})
        self.assertEqual(a, b)

    def test_copy_request_context_twice(self):
        """
        #24273 -- Copy twice shouldn't raise an exception
        """
        RequestContext(HttpRequest()).new().new()

class RequestContextTests(SimpleTestCase):

    @override_settings(TEMPLATES=[{
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'OPTIONS': {
            'loaders': [
                ('django.template.loaders.locmem.Loader', {
                    'child': '{{ var|default:"none" }}',
                }),
            ],
        },
    }])
    def test_include_only(self):
        """
        #15721 -- ``{% include %}`` and ``RequestContext`` should work
        together.
        """
        request = RequestFactory().get('/')
        ctx = RequestContext(request, {'var': 'parent'})
        self.assertEqual(Template('{% include "child" %}').render(ctx), 'parent')
        self.assertEqual(Template('{% include "child" only %}').render(ctx), 'none')

    def test_stack_size(self):
        """
        #7116 -- Optimize RequetsContext construction
        """
        request = RequestFactory().get('/')
        ctx = RequestContext(request, {})
        # The stack should now contain 3 items:
        # [builtins, supplied context, context processor]
        self.assertEqual(len(ctx.dicts), 3)

    def test_context_comparable(self):
        # Create an engine without any context processors.
        test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}}

        # test comparing RequestContext to prevent problems if somebody
        # adds __eq__ in the future
        request = RequestFactory().get('/')

        self.assertEqual(
            RequestContext(request, dict_=test_data),
            RequestContext(request, dict_=test_data),
        )


text:
package org.elasticsearch.cluster.routing;

import org.elasticsearch.index.shard.ShardId;

import java.util.List;

/**
 *
 */
public class PlainShardIterator extends PlainShardsIterator implements ShardIterator {

    private final ShardId shardId;

    public PlainShardIterator(ShardId shardId, List<ShardRouting> shards) {
        super(shards);
        this.shardId = shardId;
    }

    public PlainShardIterator(ShardId shardId, List<ShardRouting> shards, int index) {
        super(shards, index);
        this.shardId = shardId;
    }

    @Override
    public ShardIterator reset() {
        super.reset();
        return this;
    }

    @Override
    public ShardId shardId() {
        return this.shardId;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        ShardIterator that = (ShardIterator) o;
        return shardId.equals(that.shardId());
    }

    @Override
    public int hashCode() {
        return shardId.hashCode();
    }
}


text:
name = "Dulio"
age = 35 # Not a lie
height = 71 # inches
weight = 190 # lbs
eyes = "Black"
hair = "Red"
teeth = "white"

# The String Outputs with format specifiers
print "Let's talk about %s." % name
print "He's %d inches tall." % height
print "He's %d pounds heavy." % weight
print "Actually, that's not too heavy."

print "He's got %s eyes and %s hair." % (eyes, hair)
print "His teeth are usually %s depending on the tea." % teeth

# The tricky line
print "If I add %d, %d, and %d I get %d." %(age, height, weight, age+height+weight)

# The %r format specifier
print "The raw value of weight is %r" % weight

# Some unit conversion: height into feet and inches
feet = height / 12
inches = height % 12
print "I am %d feet and %d inches tall." % (feet, inches)


text:
Out little project to show the current and past wind power generated in the UK in a graphical manner.
[View project](http://winderful.diascreative.net).

## Installation instructions
1. clone the repository into a folder called winderful

    `git clone https://github.com/diascreative/winderful.git`

2. enter the project folder

    `cd winderful`

3. create a new database

    `mysql > CREATE DATABASE power;`

4. set up the database structure

    `mysql power < /assets/power.db.schema.sql`

5. define the project settings

    * copy config.sample.php into config.php

      `cp inc/config.sample.php inc/config.php`
    * edit config.php so that it has the correct DB settings

## Initial setup
1. populate the DB with the latest data

    `php scripts/update-db.php`

    (you can also run this from the browser)

2. For  development purposes you will need to
    1. install npm

    2. install the project dependencies

        `npm install`
    3. run gulp

        `gulp`

        Keep this terminal open so that it automatically lints, concatenates and compresses our JS and SASS.

## TODO - help us out with a PR if you can
1. Change the update script to get data from BM reports directly instead of gridwatch

## Dev notes
All front-end changes should be made to the files in `/assets` **never** to those in `static`. Gulp will clean `static`regularly and any changes made there will be lost.


text:
package org.apache.hadoop.hbase.thrift;

import org.apache.hadoop.hbase.metrics.ExceptionTrackingSourceImpl;
import org.apache.hadoop.metrics2.MetricHistogram;
import org.apache.hadoop.metrics2.lib.MutableFastCounter;
import org.apache.hadoop.metrics2.lib.MutableGaugeLong;
import org.apache.hadoop.metrics2.lib.MutableHistogram;
import org.apache.yetus.audience.InterfaceAudience;

/**
 * Hadoop 2 version of {@link org.apache.hadoop.hbase.thrift.MetricsThriftServerSource}
 *
 * Implements BaseSource through BaseSourceImpl, following the pattern
 */
@InterfaceAudience.Private
public class MetricsThriftServerSourceImpl extends ExceptionTrackingSourceImpl implements
    MetricsThriftServerSource {

  private MetricHistogram batchGetStat;
  private MetricHistogram batchMutateStat;
  private MetricHistogram queueTimeStat;

  private MetricHistogram thriftCallStat;
  private MetricHistogram thriftSlowCallStat;

  private MutableGaugeLong callQueueLenGauge;

  private MutableGaugeLong activeWorkerCountGauge;

  // pause monitor metrics
  private final MutableFastCounter infoPauseThresholdExceeded;
  private final MutableFastCounter warnPauseThresholdExceeded;
  private final MetricHistogram pausesWithGc;
  private final MetricHistogram pausesWithoutGc;

  public MetricsThriftServerSourceImpl(String metricsName,
                                       String metricsDescription,
                                       String metricsContext,
                                       String metricsJmxContext) {
    super(metricsName, metricsDescription, metricsContext, metricsJmxContext);

    // pause monitor metrics
    infoPauseThresholdExceeded = getMetricsRegistry().newCounter(INFO_THRESHOLD_COUNT_KEY,
      INFO_THRESHOLD_COUNT_DESC, 0L);
    warnPauseThresholdExceeded = getMetricsRegistry().newCounter(WARN_THRESHOLD_COUNT_KEY,
      WARN_THRESHOLD_COUNT_DESC, 0L);
    pausesWithGc = getMetricsRegistry().newTimeHistogram(PAUSE_TIME_WITH_GC_KEY);
    pausesWithoutGc = getMetricsRegistry().newTimeHistogram(PAUSE_TIME_WITHOUT_GC_KEY);
  }

  @Override
  public void init() {
    super.init();
    batchGetStat = getMetricsRegistry().newTimeHistogram(BATCH_GET_KEY);
    batchMutateStat = getMetricsRegistry().newTimeHistogram(BATCH_MUTATE_KEY);
    queueTimeStat = getMetricsRegistry().newTimeHistogram(TIME_IN_QUEUE_KEY);
    thriftCallStat = getMetricsRegistry().newTimeHistogram(THRIFT_CALL_KEY);
    thriftSlowCallStat = getMetricsRegistry().newTimeHistogram(SLOW_THRIFT_CALL_KEY);
    callQueueLenGauge = getMetricsRegistry().getGauge(CALL_QUEUE_LEN_KEY, 0);
    activeWorkerCountGauge = getMetricsRegistry().getGauge(ACTIVE_WORKER_COUNT_KEY, 0);
  }

  @Override
  public void incTimeInQueue(long time) {
    queueTimeStat.add(time);
  }

  @Override
  public void setCallQueueLen(int len) {
    callQueueLenGauge.set(len);
  }

  @Override
  public void incNumRowKeysInBatchGet(int diff) {
    batchGetStat.add(diff);
  }

  @Override
  public void incNumRowKeysInBatchMutate(int diff) {
    batchMutateStat.add(diff);
  }

  @Override
  public void incMethodTime(String name, long time) {
    MutableHistogram s = getMetricsRegistry().getHistogram(name);
    s.add(time);
  }

  @Override
  public void incCall(long time) {
    thriftCallStat.add(time);
  }

  @Override
  public void incSlowCall(long time) {
    thriftSlowCallStat.add(time);
  }

  @Override
  public void incActiveWorkerCount() {
    activeWorkerCountGauge.incr();
  }

  @Override
  public void decActiveWorkerCount() {
    activeWorkerCountGauge.decr();
  }

  @Override
  public void incInfoThresholdExceeded(int count) {
    infoPauseThresholdExceeded.incr(count);
  }

  @Override
  public void incWarnThresholdExceeded(int count) {
    warnPauseThresholdExceeded.incr(count);
  }

  @Override
  public void updatePauseTimeWithGc(long t) {
    pausesWithGc.add(t);
  }

  @Override
  public void updatePauseTimeWithoutGc(long t) {
    pausesWithoutGc.add(t);
  }
}


text:
//: exceptions/AlwaysFinally.java
package exceptions; /* Added by Eclipse.py */
// Finally is always executed.
import static net.mindview.util.Print.*;

class FourException extends Exception {}

public class AlwaysFinally {
  public static void main(String[] args) {
    print("Entering first try block");
    try {
      print("Entering second try block");
      try {
        throw new FourException();
      } finally {
        print("finally in 2nd try block");
      }
    } catch(FourException e) {
      System.out.println(
        "Caught FourException in 1st try block");
    } finally {
      System.out.println("finally in 1st try block");
    }
  }
} /* Output:
Entering first try block
Entering second try block
finally in 2nd try block
Caught FourException in 1st try block
finally in 1st try block
*///:~


text:
<button data-dojo-type="dijit/form/Button" data-dojo-props="label: '${buttonSave}', 'class': 'saveButton'"
			data-dojo-attach-point="saveButton" data-dojo-attach-event="onClick:save"></button
		><button data-dojo-type="dijit/form/Button"  data-dojo-props="label: '${buttonCancel}', 'class': 'cancelButton'"
			data-dojo-attach-point="cancelButton" data-dojo-attach-event="onClick:cancel"></button
	>


text:
<?xml version="1.0" encoding="UTF-8"?>
<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <parameters>
        <parameter key="sonata.order.admin.order.class">Sonata\OrderBundle\Admin\OrderAdmin</parameter>
        <parameter key="sonata.order.admin.order.controller">SonataOrderBundle:OrderCRUD</parameter>
        <parameter key="sonata.order.admin.order_element.class">Sonata\OrderBundle\Admin\OrderElementAdmin</parameter>
        <parameter key="sonata.order.admin.order_element.controller">SonataAdminBundle:CRUD</parameter>
    </parameters>
    <services>
        <service id="sonata.order.admin.order" class="%sonata.order.admin.order.class%">
            <tag name="sonata.admin" manager_type="orm" group="sonata_ecommerce" label="order" label_translator_strategy="sonata.admin.label.strategy.underscore"/>
            <argument/>
            <argument>%sonata.order.admin.order.entity%</argument>
            <argument>%sonata.order.admin.order.controller%</argument>
            <call method="addChild">
                <argument type="service" id="sonata.order.admin.order_element"/>
            </call>
            <call method="setCurrencyDetector">
                <argument type="service" id="sonata.price.currency.detector"/>
            </call>
            <call method="setInvoiceManager">
                <argument type="service" id="sonata.invoice.manager"/>
            </call>
            <call method="setOrderManager">
                <argument type="service" id="sonata.order.manager"/>
            </call>
        </service>
        <service id="sonata.order.admin.order_element" class="%sonata.order.admin.order_element.class%">
            <tag name="sonata.admin" manager_type="orm" group="sonata_ecommerce" label="orderElement" show_in_dashboard="false" label_translator_strategy="sonata.admin.label.strategy.underscore"/>
            <argument/>
            <argument>%sonata.order.admin.order_element.entity%</argument>
            <argument>%sonata.order.admin.order_element.controller%</argument>
            <call method="setCurrencyDetector">
                <argument type="service" id="sonata.price.currency.detector"/>
            </call>
            <call method="setProductPool">
                <argument type="service" id="sonata.product.pool"/>
            </call>
        </service>
    </services>
</container>


text:
using Microsoft.Data.Edm;
using Nuwa;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.OData;
using System.Web.Http.OData.Builder;
using System.Web.Http.OData.Extensions;
using WebStack.QA.Common.WebHost;
using Xunit;

namespace WebStack.QA.Test.OData.Formatter.JsonLight.Metadata
{
    [NuwaFramework]
    public class MinimalMetadataSpecificTests
    {
        [NuwaBaseAddress]
        public string BaseAddress { get; set; }

        [NuwaHttpClient]
        public HttpClient Client { get; set; }

        [NuwaConfiguration]
        public static void UpdateConfiguration(HttpConfiguration config)
        {
            config.Routes.Clear();
            config.Routes.MapODataServiceRoute("odata", "odata", GetModel());
        }

        [NuwaWebConfig]
        public static void UpdateWebConfig(WebConfigHelper webConfig)
        {
            webConfig.AddRAMFAR(true);
        }

        private static IEdmModel GetModel()
        {
            ODataModelBuilder builder = new ODataConventionModelBuilder();
            var pets = builder.EntitySet<Pet>("Pets");
            builder.Entity<BigPet>();
            return builder.GetEdmModel();
        }

        [Fact]
        public void QueryWithCastDoesntContainODataType()
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, BaseAddress + "/odata/Pets(5)/WebStack.QA.Test.OData.Formatter.JsonLight.Metadata.BigPet");
            HttpResponseMessage response = Client.SendAsync(request).Result;
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            string payload = response.Content.ReadAsStringAsync().Result;
            Assert.DoesNotContain("odata.type", payload);
            Assert.DoesNotContain("WebStack.QA.Test.OData.Formatter.JsonLight.Metadata.BigPet", payload);
        }

        [Fact]
        public void QueryWithoutCastContainsODataType()
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, BaseAddress + "/odata/Pets(5)");
            HttpResponseMessage response = Client.SendAsync(request).Result;
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            string payload = response.Content.ReadAsStringAsync().Result;
            Assert.Contains("odata.type", payload);
            Assert.Contains("WebStack.QA.Test.OData.Formatter.JsonLight.Metadata.BigPet", payload);
        }
    }

    public class Pet
    {
        public int Id { get; set; }
    }

    public class BigPet : Pet
    {
    }

    public class PetsController : ODataController
    {
        [EnableQuery(PageSize = 10, MaxExpansionDepth = 2)]
        public IHttpActionResult Get()
        {
            return Ok(Enumerable.Range(0, 10).Select(i =>
            {
                if (i % 2 == 0)
                    return new Pet { Id = i };
                else
                    return new BigPet { Id = i };
            }));
        }

        [EnableQuery(PageSize = 10, MaxExpansionDepth = 2)]
        public IHttpActionResult Get([FromODataUri] int key)
        {
            return Ok(new BigPet { Id = key });
        }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: andranik
 * Date: 11/20/14
 * Time: 11:24 PM
 */
namespace nxtcar\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Class CarProperty
 * @package nxtcar\MainBundle\Entity
 *
 * @ORM\Entity
 * @ORM\Table(name="car_property")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({"brand" = "CarBrand", "model" = "CarModel", "color" = "CarColor", "type" = "CarType"})
 */
class CarProperty
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\COlumn(name="title", type="string", length=25, nullable=false)
     */
    protected $title;

    /**
     * @return string
     */
    public function __toString()
    {
        return ($this->title) ? $this->title : '';
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return CarProperty
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }
}


text:
package com.xlg.forkids.memory;

import java.io.FileDescriptor;

import com.xlg.forkids.BuildConfig;

import android.annotation.TargetApi;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;

/** BitmapѹËõÀà */
public class BitmapResizer {
	// private static final String TAG = BitmapResizer.class.getSimpleName();
	protected int mImageWidth;
	protected int mImageHeight;

	/**
	 * Set the target image width and height.
	 *
	 * @param width
	 * @param height
	 */
	public void setImageSize(int width, int height) {
		mImageWidth = width;
		mImageHeight = height;
	}

	/**
	 * Set the target image size (width and height will be the same).
	 *
	 * @param size
	 */
	public void setImageSize(int size) {
		setImageSize(size, size);
	}

	/** ĬÈÏѹËõΪԭ'³ß´çµÄ 1/10 */
	// private static int defaultInSampleSize = 2;

	/**
	 * Decode and sample down a bitmap from resources to the requested width and
	 * height.
	 *
	 * @param resource
	 *            The resources object containing the image data
	 * @param resourceId
	 *            The resource id of the image data
	 * @param requestWidth
	 *            The requested width of the resulting bitmap
	 * @param requestHeight
	 *            The requested height of the resulting bitmap
	 * @return A bitmap sampled down from the original with the same aspect
	 *         ratio and dimensions that are equal to or greater than the
	 *         requested width and height
	 */
	public static Bitmap decodeSampledBitmapFromResource(Resources resource,
			int resourceId, int requestWidth, int requestHeight,
			BitmapCache cache) {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeResource(resource, resourceId, options);
		// if (requestWidth == 0 || requestHeight == 0) {
		//
		// Log.v(TAG,
		// "request resource("
		// + resource.getResourceEntryName(resourceId)
		// + ") size: " + requestWidth + "x" + requestHeight);
		// }
		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, requestWidth,
				requestHeight);

		// if (BuildConfig.DEBUG) {
		// Log.v(TAG, "decode resource " + resourceId + ", width: "
		// + requestWidth + ", height: " + requestHeight);
		// }
		// If we're running on Honeycomb or newer, try to use inBitmap
		if (DebugUtility.hasHoneycomb()) {
			addInBitmapOptions(options, cache);
		}

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		// Set java to recycle the memory when need
		// options.inPurgeable = true;
		// InputStream is = resource.openRawResource(resourceId);
		// return BitmapFactory.decodeStream(is, null, options);

		return BitmapFactory.decodeResource(resource, resourceId, options);
		// ¾¡Á¿²»ÒªÊ¹Óà setImageBitmap »ò setImageResource »ò
		// BitmapFactory.decodeResource
		// À´ÉèÖÃÒ»ÕÅ´óͼ£¬ÒòΪÕâЩº¯ÊýÔÚÍê³É decode ºó£¬×îÖÕ¶¼ÊÇͨ¹ý java ²ãµÄ createBitmap
		// À´Íê³ÉµÄ£¬ÐèÒªÏûºÄ¸ü¶àµÄÄÚ´æ¡£
	}

	/**
	 * Decode and sample down a bitmap from a file input stream to the requested
	 * width and height.
	 *
	 * @param fileDescriptor
	 *            The file descriptor to read from
	 * @param reqWidth
	 *            The requested width of the resulting bitmap
	 * @param reqHeight
	 *            The requested height of the resulting bitmap
	 * @param cache
	 *            The ImageCache used to find candidate bitmaps for use with
	 *            inBitmap
	 * @return A bitmap sampled down from the original with the same aspect
	 *         ratio and dimensions that are equal to or greater than the
	 *         requested width and height
	 */
	public static Bitmap decodeSampledBitmapFromDescriptor(
			FileDescriptor fileDescriptor, int requestWidth, int requestHeight,
			BitmapCache cache) {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
		// if (requestWidth == 0 || requestHeight == 0) {
		// Log.v(TAG, "request descriptor size: " + requestWidth + "x"
		// + requestHeight);
		// }
		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, requestWidth,
				requestHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;

		// If we're running on Honeycomb or newer, try to use inBitmap
		if (DebugUtility.hasHoneycomb()) {
			addInBitmapOptions(options, cache);
		}
		// Set java to recycle the memory when need
		// options.inPurgeable = true;

		return BitmapFactory
				.decodeFileDescriptor(fileDescriptor, null, options);
	}

	/**
	 * Decode and sample down a bitmap from a file to the requested width and
	 * height.
	 *
	 * @param filename
	 *            The full path of the file to decode
	 * @param requestWidth
	 *            The requested width of the resulting bitmap
	 * @param requestHeight
	 *            The requested height of the resulting bitmap
	 * @return A bitmap sampled down from the original with the same aspect
	 *         ratio and dimensions that are equal to or greater than the
	 *         requested width and height
	 */
	public static Bitmap decodeSampledBitmapFromFile(String filename,
			int requestWidth, int requestHeight, BitmapCache cache) {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filename, options);
		// if (requestWidth == 0 || requestHeight == 0) {
		// Log.v(TAG, "request file size: " + requestWidth + "x"
		// + requestHeight);
		// }
		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, requestWidth,
				requestHeight);

		// if (BuildConfig.DEBUG) {
		// Log.v(TAG, "decode file " + filename + ", width: " + requestWidth
		// + ", height: " + requestHeight);
		// }
		// If we're running on Honeycomb or newer, try to use inBitmap
		if (DebugUtility.hasHoneycomb()) {
			addInBitmapOptions(options, cache);
		}

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;

		return BitmapFactory.decodeFile(filename, options);
	}

	/** ѹËõͼƬ²¢Ö¸¶¨Ëõ·Å±ÈÂÊ */
	public static Bitmap decodeSampledBitmapFromFile(String filename,
			int sampleSize) {
		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filename, options);

		// Calculate inSampleSize
		options.inSampleSize = sampleSize;
		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;

		return BitmapFactory.decodeFile(filename, options);
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private static void addInBitmapOptions(BitmapFactory.Options options,
			BitmapCache cache) {
		// inBitmap only works with mutable bitmaps so force the decoder to
		// return mutable bitmaps.
		options.inMutable = true;

		if (cache != null) {
			// Try and find a bitmap to use for inBitmap
			Bitmap inBitmap = cache.getBitmapFromReusableSet(options);

			if (inBitmap != null) {
				if (BuildConfig.DEBUG) {
					// Log.d(TAG, "Found bitmap to use for inBitmap");
				}
				options.inBitmap = inBitmap;
			}
		}
	}

	/**
	 * Calculate an inSampleSize for use in a {@link BitmapFactory.Options}
	 * object when decoding bitmaps using the decode* methods from
	 * {@link BitmapFactory}. This implementation calculates the closest
	 * inSampleSize that will result in the final decoded bitmap having a width
	 * and height equal to or larger than the requested width and height. This
	 * implementation does not ensure a power of 2 is returned for inSampleSize
	 * which can be faster when decoding but results in a larger bitmap which
	 * isn't as useful for caching purposes.
	 *
	 * @param options
	 *            An options object with out* params already populated (run
	 *            through a decode* method with inJustDecodeBounds==true
	 * @param reqWidth
	 *            The requested width of the resulting bitmap
	 * @param reqHeight
	 *            The requested height of the resulting bitmap
	 * @return The value to be used for inSampleSize
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;
		// Èç¹ûÐèÒªµÄÊÇԭ'´óСÔòÖ±½Ó·µ»Ø1±¶ÂÊ
		if (reqWidth <= 0 || reqHeight <= 0)
			return inSampleSize;

		if (height > reqHeight || width > reqWidth) {

			// Calculate ratios of height and width to requested height and
			// width
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);

			// Choose the smallest ratio as inSampleSize value, this will
			// guarantee a final image
			// with both dimensions larger than or equal to the requested height
			// and width.
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

			// This offers some additional logic in case the image has a strange
			// aspect ratio. For example, a panorama may have a much larger
			// width than height. In these cases the total pixels might still
			// end up being too large to fit comfortably in memory, so we should
			// be more aggressive with sample down the image (=larger
			// inSampleSize).

			final float totalPixels = width * height;

			// Anything more than 2x the requested pixels we'll sample down
			// further
			final float totalReqPixelsCap = reqWidth * reqHeight * 2;

			while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
				inSampleSize++;
			}
		}
		return inSampleSize;
	}
}


text:
Home Assistant |Build Status| |Coverage Status| |Join the chat at https://gitter.im/home-assistant/home-assistant| |Join the dev chat at https://gitter.im/home-assistant/home-assistant/devs|
==============================================================================================================================================================================================

Home Assistant is a home automation platform running on Python 3. The
goal of Home Assistant is to be able to track and control all devices at
home and offer a platform for automating control.

To get started:

.. code:: bash

    python3 -m pip install homeassistant
    hass --open-ui

Check out `the website <https://home-assistant.io>`__ for `a
demo <https://home-assistant.io/demo/>`__, installation instructions,
tutorials and documentation.

|screenshot-states|

Examples of devices Home Assistant can interface with:

-  Monitoring connected devices to a wireless router:
   `OpenWrt <https://openwrt.org/>`__,
   `Tomato <http://www.polarcloud.com/tomato>`__,
   `Netgear <http://netgear.com>`__,
   `DD-WRT <http://www.dd-wrt.com/site/index>`__,
   `TPLink <http://www.tp-link.us/>`__,
   `ASUSWRT <http://event.asus.com/2013/nw/ASUSWRT/>`__,
   `Xiaomi <http://miwifi.com/>`__ and any SNMP
   capable Linksys WAP/WRT
-  `Philips Hue <http://meethue.com>`__ lights,
   `WeMo <http://www.belkin.com/us/Products/home-automation/c/wemo-home-automation/>`__
   switches, `Edimax <http://www.edimax.com/>`__ switches,
   `Efergy <https://efergy.com>`__ energy monitoring, and
   `Tellstick <http://www.telldus.se/products/tellstick>`__ devices and
   sensors
-  `Google
   Chromecasts <http://www.google.com/intl/en/chrome/devices/chromecast>`__,
   `Music Player Daemon <http://www.musicpd.org/>`__, `Logitech
   Squeezebox <https://en.wikipedia.org/wiki/Squeezebox_%28network_music_player%29>`__,
   `Plex <https://plex.tv/>`__, `Kodi (XBMC) <http://kodi.tv/>`__,
   iTunes (by way of
   `itunes-api <https://github.com/maddox/itunes-api>`__), and Amazon
   Fire TV (by way of
   `python-firetv <https://github.com/happyleavesaoc/python-firetv>`__)
-  Support for
   `ISY994 <https://www.universal-devices.com/residential/isy994i-series/>`__
   (Insteon and X10 devices), `Z-Wave <http://www.z-wave.com/>`__, `Nest
   Thermostats <https://nest.com/>`__,
   `RFXtrx <http://www.rfxcom.com/>`__,
   `Arduino <https://www.arduino.cc/>`__, `Raspberry
   Pi <https://www.raspberrypi.org/>`__, and
   `Modbus <http://www.modbus.org/>`__
-  Interaction with `IFTTT <https://ifttt.com/>`__
-  Integrate data from the `Bitcoin <https://bitcoin.org>`__ network,
   meteorological data from
   `OpenWeatherMap <http://openweathermap.org/>`__ and
   `Forecast.io <https://forecast.io/>`__,
   `Transmission <http://www.transmissionbt.com/>`__, or
   `SABnzbd <http://sabnzbd.org>`__.
-  `See full list of supported
   devices <https://home-assistant.io/components/>`__

Build home automation on top of your devices:

-  Keep a precise history of every change to the state of your house
-  Turn on the lights when people get home after sunset
-  Turn on lights slowly during sunset to compensate for less light
-  Turn off all lights and devices when everybody leaves the house
-  Offers a `REST API <https://home-assistant.io/developers/rest_api/>`__
   and can interface with MQTT for easy integration with other projects
   like `OwnTracks <http://owntracks.org/>`__
-  Allow sending notifications using
   `Instapush <https://instapush.im>`__, `Notify My Android
   (NMA) <http://www.notifymyandroid.com/>`__,
   `PushBullet <https://www.pushbullet.com/>`__,
   `PushOver <https://pushover.net/>`__, `Slack <https://slack.com/>`__,
   `Telegram <https://telegram.org/>`__, `Join <http://joaoapps.com/join/>`__, and `Jabber
   (XMPP) <http://xmpp.org>`__

The system is built using a modular approach so support for other devices or actions can
be implemented easily. See also the `section on
architecture <https://home-assistant.io/developers/architecture/>`__
and the `section on creating your own
components <https://home-assistant.io/developers/creating_components/>`__.

If you run into issues while using Home Assistant or during development
of a component, check the `Home Assistant help
section <https://home-assistant.io/help/>`__ of our website for further help and information.

.. |Build Status| image:: https://travis-ci.org/home-assistant/home-assistant.svg?branch=master
   :target: https://travis-ci.org/home-assistant/home-assistant
.. |Coverage Status| image:: https://img.shields.io/coveralls/home-assistant/home-assistant.svg
   :target: https://coveralls.io/r/home-assistant/home-assistant?branch=master
.. |Join the chat at https://gitter.im/home-assistant/home-assistant| image:: https://img.shields.io/badge/gitter-general-blue.svg
   :target: https://gitter.im/home-assistant/home-assistant?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
.. |Join the dev chat at https://gitter.im/home-assistant/home-assistant/devs| image:: https://img.shields.io/badge/gitter-development-yellowgreen.svg
   :target: https://gitter.im/home-assistant/home-assistant/devs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
.. |screenshot-states| image:: https://raw.github.com/home-assistant/home-assistant/master/docs/screenshots.png
   :target: https://home-assistant.io/demo/


text:
<?php

namespace TunaCMS\Bundle\GalleryBundle\Tests\Validator\Constraints;

use Symfony\Component\Validator\Constraints\Blank;
use Symfony\Component\Validator\Tests\Constraints\AbstractConstraintValidatorTest;
use TunaCMS\Bundle\FileBundle\Entity\Image;
use TunaCMS\Bundle\GalleryBundle\Entity\GalleryItem;
use TunaCMS\Bundle\GalleryBundle\Validator\Constraints\GalleryItemFileNotNull;
use TunaCMS\Bundle\GalleryBundle\Validator\Constraints\GalleryItemFileNotNullValidator;

class GalleryItemFileNotNullValidatorTest extends AbstractConstraintValidatorTest
{
    protected function createValidator()
    {
        return new GalleryItemFileNotNullValidator();
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     * @expectedExceptionMessage Expected argument of type "TunaCMS\Bundle\GalleryBundle\Validator\Constraints\GalleryItemFileNotNull", "Symfony\Component\Validator\Constraints\Blank" given
     */
    public function testInvalidConstraint()
    {
        $this->validator->validate(new GalleryItem(), new Blank());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     * @expectedExceptionMessage Expected argument of type "TunaCMS\Bundle\GalleryBundle\Entity\GalleryItem", "string" given
     */
    public function testInvalidObject()
    {
        $this->validator->validate('foo', new GalleryItemFileNotNull());
    }

    public function testTypeIsNotImage()
    {
        $object = new GalleryItem();
        $object->setType(GalleryItem::VIDEO_TYPE);

        $this->validator->validate($object, new GalleryItemFileNotNull());

        $this->assertNoViolation();
    }

    public function testImageIsEmpty()
    {
        $object = new GalleryItem();
        $object->setType(GalleryItem::IMAGE_TYPE);

        $this->validator->validate($object, new GalleryItemFileNotNull());

        $this->buildViolation('error.file.empty')
            ->setInvalidValue('InvalidValue')
            ->atPath('property.path.image')
            ->assertRaised()
        ;
    }

    public function testImageIsValid()
    {
        $image = new Image();
        $image->setPath('/foo/test.bar');

        $object = new GalleryItem();
        $object
            ->setType(GalleryItem::IMAGE_TYPE)
            ->setImage($image)
        ;

        $this->validator->validate($object, new GalleryItemFileNotNull());

        $this->assertNoViolation();
    }
}


text:
import json
import logging
import sys
import traceback

from django.core.urlresolvers import resolve

from silk import models
from silk.collector import DataCollector
from silk.config import SilkyConfig

Logger = logging.getLogger('silk')

content_types_json = ['application/json',
                      'application/x-javascript',
                      'text/javascript',
                      'text/x-javascript',
                      'text/x-json']
content_type_form = ['multipart/form-data',
                     'application/x-www-form-urlencoded']
content_type_html = ['text/html']
content_type_css = ['text/css']

def _parse_content_type(content_type):
    """best efforts on pulling out the content type and encoding from Content-Type header"""
    try:
        content_type = content_type.strip()
    except AttributeError:
        pass
    char_set = None
    if content_type.strip():
        splt = content_type.split(';')
        content_type = splt[0]
        try:
            raw_char_set = splt[1].strip()
            key, char_set = raw_char_set.split('=')
            if key != 'charset':
                char_set = None
        except (IndexError, ValueError):
            pass
    return content_type, char_set

class RequestModelFactory(object):
    """Produce Request models from Django request objects"""

    def __init__(self, request):
        super(RequestModelFactory, self).__init__()
        self.request = request

    def content_type(self):
        content_type = self.request.META.get('CONTENT_TYPE', '')
        return _parse_content_type(content_type)

    def encoded_headers(self):
        """
        From Django docs (https://docs.djangoproject.com/en/1.6/ref/request-response/#httprequest-objects):

        "With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to
        META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix
        to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER."
        """
        headers = {}
        for k, v in self.request.META.items():
            if k.startswith('HTTP') or k in ('CONTENT_TYPE', 'CONTENT_LENGTH'):
                splt = k.split('_')
                if splt[0] == 'HTTP':
                    splt = splt[1:]
                k = '-'.join(splt)
                headers[k] = v
        if SilkyConfig().SILKY_HIDE_COOKIES:
            try:
                del headers['COOKIE']
            except KeyError:
                pass
        return json.dumps(headers)

    def _body(self, raw_body, content_type):
        """
        Encode body as JSON if possible so can be used as a dictionary in generation
        of curl/django test client code
        """
        body = ''
        if content_type in content_type_form:
            body = self.request.POST
            body = json.dumps(dict(body), sort_keys=True, indent=4)
        elif content_type in content_types_json:
            try:
                body = json.dumps(json.loads(raw_body), sort_keys=True, indent=4)
            except:
                body = raw_body
        return body

    def body(self):
        content_type, char_set = self.content_type()
        raw_body = self.request.body
        if char_set:
            try:
                raw_body = raw_body.decode(char_set)
            except AttributeError:
                pass
            except LookupError:  # If no encoding exists, default to UTF-8
                try:
                    raw_body = raw_body.decode('UTF-8')
                except AttributeError:
                    pass
                except UnicodeDecodeError:
                    raw_body = ''
            except Exception as e:
                Logger.error('Unable to decode request body using char_set %s due to error: %s. Will ignore. Stacktrace:' % (char_set, e))
                traceback.print_exc()
        else:
            # Default to an attempt at UTF-8 decoding.
            try:
                raw_body = raw_body.decode('UTF-8')
            except AttributeError:
                pass
            except UnicodeDecodeError:
                raw_body = ''
        max_size = SilkyConfig().SILKY_MAX_REQUEST_BODY_SIZE
        body = ''
        if raw_body:
            if max_size > -1:
                Logger.debug('A max request size is set so checking size')
                size = sys.getsizeof(raw_body, default=None)
                request_identifier = self.request.path
                if not size:
                    Logger.error('No way in which to get size of request body for %s, will ignore it', request_identifier)
                elif size <= max_size:
                    Logger.debug('Request %s has body of size %d which is less than %d so will save the body' % (request_identifier, size, max_size))
                    body = self._body(raw_body, content_type)
                else:
                    Logger.debug('Request %s has body of size %d which is greater than %d, therefore ignoring' % (request_identifier, size, max_size))
                    raw_body = None
            else:
                Logger.debug('No maximum request body size is set, continuing.')
                body = self._body(raw_body, content_type)
        return body, raw_body

    def query_params(self):
        query_params = self.request.GET
        encoded_query_params = ''
        if query_params:
            query_params_dict = dict(zip(query_params.keys(), query_params.values()))
            encoded_query_params = json.dumps(query_params_dict)
        return encoded_query_params

    def construct_request_model(self):
        body, raw_body = self.body()
        query_params = self.query_params()
        path = self.request.path
        resolved = resolve(path)
        namespace = resolved.namespace
        view_name = resolved.url_name
        if namespace:
            view_name = namespace + ':' + view_name

        request_model = models.Request.objects.create(
            path=path,
            encoded_headers=self.encoded_headers(),
            method=self.request.method,
            query_params=query_params,
            view_name=view_name,
            body=body)

        # Text fields are encoded as UTF-8 in Django and hence will try to coerce
        # anything to we pass to UTF-8. Some stuff like binary will fail.
        try:
            request_model.raw_body = raw_body
        except UnicodeDecodeError:
            Logger.debug('NYI: Binary request bodies')  # TODO
        Logger.debug('Created new request model with pk %s' % request_model.pk)
        return request_model

class ResponseModelFactory(object):
    """given a response object, craft the silk response model"""

    def __init__(self, response):
        super(ResponseModelFactory, self).__init__()
        self.response = response
        self.request = DataCollector().request

    def body(self):
        body = ''
        content_type, char_set = _parse_content_type(self.response.get('Content-Type', ''))
        content = getattr(self.response, 'content', '')
        if char_set and content:
            try:
                content = content.decode(char_set)
            except AttributeError:
                pass
            except LookupError:  # If no encoding exists, default to UTF-8
                try:
                    content = content.decode('UTF-8')
                except AttributeError:
                    pass
                except UnicodeDecodeError:
                    content = ''
            except Exception as e:
                Logger.error('Unable to decode response body using char_set %s due to error: %s. Will ignore. Stacktrace:' % (char_set, e))
                traceback.print_exc()
        else:
            # Default to an attempt at UTF-8 decoding.
            try:
                content = content.decode('UTF-8')
            except AttributeError:
                pass
            except UnicodeDecodeError:
                content = ''
        if content:
            max_body_size = SilkyConfig().SILKY_MAX_RESPONSE_BODY_SIZE
            if max_body_size > -1:
                Logger.debug('Max size of response body defined so checking')
                size = sys.getsizeof(content, None)
                if not size:
                    Logger.error('Could not get size of response body. Ignoring')
                    content = ''
                else:
                    if size > max_body_size:
                        content = ''
                        Logger.debug('Size of %d for %s is bigger than %d so ignoring response body' % (size, self.request.path, max_body_size))
                    else:
                        Logger.debug('Size of %d for %s is less than %d so saving response body' % (size, self.request.path, max_body_size))
            if content_type in content_types_json:
                # TODO: Perhaps theres a way to format the JSON without parsing it?
                try:
                    body = json.dumps(json.loads(content), sort_keys=True, indent=4)
                except (TypeError, ValueError):
                    Logger.warn('Response to request with pk %s has content type %s but was unable to parse it' % (self.request.pk, content_type))
        return body, content

    def construct_response_model(self):
        assert self.request, 'Cant construct a response model if there is no request model'
        Logger.debug('Creating response model for request model with pk %s' % self.request.pk)
        b, content = self.body()
        raw_headers = self.response._headers
        headers = {}
        for k, v in raw_headers.items():
            try:
                header, val = v
            except ValueError:
                header, val = k, v
            finally:
                headers[header] = val

        silky_response = models.Response.objects.create(request=self.request,
                                                        status_code=self.response.status_code,
                                                        encoded_headers=json.dumps(headers),
                                                        body=b)
        # Text fields are encoded as UTF-8 in Django and hence will try to coerce
        # anything to we pass to UTF-8. Some stuff like binary will fail.
        try:
            silky_response.raw_body = content
        except UnicodeDecodeError:
            Logger.debug('NYI: Saving of binary response body')  # TODO
        self.request.response = silky_response
        self.request.save()

        return silky_response


text:
var DeepModel = require('../');
var expect = require('chai').expect;
var bioData = require('./fixtures/bioData.json');

describe('DeepModel', function() {
	describe('#has', function() {
		it('should has: Check if model has deep key', function() {
			var model = new DeepModel(bioData);
			expect(model.has('user.name.last')).to.be.true;
		})

		it("has: Don't find nonexistent key", function() {
			var model = new DeepModel(bioData);
			expect(model.has('user.turtleneck')).to.be.false;
		});
	});
});


text:
import {NextFunction, Request, Response} from "express";
import {Db} from "mongodb";
import {Formio} from "./Formio";

export interface FormioUpdate {
  db: Db;
  version: string;

  /**
   *
   * @param cb
   */
  initialize(cb: (err: unknown, db: any) => void): Promise<Formio>;

  /**
   *
   * @param req
   * @param res
   * @param next
   */
  sanityCheck(req: Request, res: Response, next: NextFunction): void;
}


text:
<?php

namespace Elixir\DI;

/**
 * @author Cédric Tanghe <ced.tanghe@gmail.com>
 */
abstract class ProviderAbstract implements ProviderInterface
{
    /**
     * @var bool
     */
    protected $deferred = false;

    /**
     * @var array
     */
    protected $provides = [];

    /**
     * {@inheritdoc}
     */
    public function isDeferred()
    {
        return $this->deferred;
    }

    /**
     * {@inheritdoc}
     */
    public function provided($service)
    {
        return in_array($service, $this->provides());
    }

    /**
     * {@inheritdoc}
     */
    public function provides()
    {
        return $this->provides;
    }
}


text:
function f = parseformula(f, token, repl, dim, tr)
% parseformula  - parse a formula
%
% FORMAT:       f = parseformula(f, token, repl, dim, tr)
%
% Input fields:
%
%       f           formula
%       token       string to be matched
%       repl        replacement string
%       dim         concatenation dimension for output
%       tr          target indices (also used for available range)
%
% Output fields:
%
%       f           patched formula
%
% Note: this works for direct access and 1-level subfields using cat!

% Version:  v0.9b
% Build:    11050712
% Date:     Apr-09 2011, 11:08 PM EST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://neuroelf.net/

% Copyright (c) 2010, 2011, Jochen Weber
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in the
%       documentation and/or other materials provided with the distribution.
%     * Neither the name of Columbia University nor the
%       names of its contributors may be used to endorse or promote products
%       derived from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

% argument check
if nargin < 5 || ...
   ~ischar(f) || ...
   ~ischar(token) || ...
    isempty(token) || ...
   ~ischar(repl) || ...
    isempty(repl) || ...
    isempty(strfind(repl(:)', token(:)')) || ...
   ~isa(dim, 'double') || ...
    numel(dim) ~= 1 || ...
    isinf(dim) || ...
    isnan(dim) || ...
   ~any(1:63 == dim) || ...
   ~isa(tr, 'double') || ...
    isempty(tr) || ...
    any(isinf(tr(:)) | isnan(tr(:)) | tr(:) < 0 | tr(:) ~= fix(tr(:)))
    error( ...
        'neuroelf:BadArgument', ...
        'Invalid combination of arguments.' ...
    );
end

% get good versions first
f = f(:)';
token = token(:)';
ftoken = reshape([token; token], 1, 2 * numel(token));
ftoken(1:2:end) = '\';
itoken = '([1-9]\d*)';
stoken = ['(\-?' itoken(2:end)];
repl = repl(:)';
tr = tr(:);
cats = sprintf('cat(%d,', dim);

% replace i1:s:i2 encounters (in reverse order!)
[rs, re, rt] = regexp(f, [ftoken itoken '\:' stoken '\:' itoken]);
for rc = numel(rt):-1:1

    % make sure all indices are valid
    i1 = str2double(f(rt{rc}(1, 1):rt{rc}(1, 2)));
    st = str2double(f(rt{rc}(2, 1):rt{rc}(2, 2)));
    i2 = str2double(f(rt{rc}(3, 1):rt{rc}(3, 2)));
    try
        ti = tr(i1:st:i2);
    catch ne_eo;
        neuroelf_lasterr(ne_eo);
        error( ...
            'neuroelf:BadArgument', ...
            'The following expression couldn''t be resolved: %s.', ...
            f(rs(rc):re(rc)) ...
        );
    end

    % and disallow empty expressions
    if isempty(ti)
        error( ...
            'neuroelf:BadArgument', ...
            'Empty expressions cannot be resolved!' ...
        );
    end

    % for one index, don't use cat
    if numel(ti) == 1
        f = [f(1:rs(rc)-1) ...
            strrep(repl, token, sprintf('%d', ti)) ...
            f(rt{rc}(end)+1:end)];
    else
        % make string
        ti = sprintf('%d,', ti);
        f = [f(1:rs(rc)-1) ...
            cats strrep(repl, token, ['[' ti(1:end-1) ']']) ')' ...
            f(rt{rc}(end)+1:end)];
    end
end

% replace i1:i2 encounters (in reverse order!)
[rs, re, rt] = regexp(f, [ftoken itoken '\:' itoken]);
for rc = numel(rt):-1:1

    % make sure all indices are valid
    i1 = str2double(f(rt{rc}(1, 1):rt{rc}(1, 2)));
    i2 = str2double(f(rt{rc}(2, 1):rt{rc}(2, 2)));

    % allow simple reversing!
    if i2 < i1
        i2o = i2;
        i2 = i1;
        i1 = i2o;
    end

    % test expression
    try
        ti = tr(i1:i2);
    catch ne_eo;
        neuroelf_lasterr(ne_eo);
        error( ...
            'neuroelf:BadArgument', ...
            'The following expression couldn''t be resolved: %s.', ...
            f(rs(rc):re(rc)) ...
        );
    end

    % and disallow empty expressions
    if isempty(ti)
        error( ...
            'neuroelf:BadArgument', ...
            'Empty expressions cannot be resolved!' ...
        );
    end

    % for one index, don't use cat
    if numel(ti) == 1
        f = [f(1:rs(rc)-1) ...
            strrep(repl, token, sprintf('%d', ti)) ...
            f(rt{rc}(end)+1:end)];
    else
        % make string
        ti = sprintf('%d,', ti);
        f = [f(1:rs(rc)-1) ...
            cats strrep(repl, token, ['[' ti(1:end-1) ']']) ')' ...
            f(rt{rc}(end)+1:end)];
    end
end

% replace i1 encounters (in reverse order!)
[rs, re, rt] = regexp(f, [ftoken itoken]);
for rc = numel(rt):-1:1

    % make sure all indices are valid
    i1 = str2double(f(rt{rc}(1, 1):rt{rc}(1, 2)));
    try
        ti = tr(i1);
    catch ne_eo;
        neuroelf_lasterr(ne_eo);
        error( ...
            'neuroelf:BadArgument', ...
            'The following expression couldn''t be resolved: %s.', ...
            f(rs(rc):re(rc)) ...
        );
    end

    % replace
    f = [f(1:rs(rc)-1) ...
        strrep(repl, token, sprintf('%d', ti)) ...
        f(rt{rc}(end)+1:end)];
end


text:
    {% for gallery_hash in site.data.galleries %}
    {% assign gallery = gallery_hash[1] %}
        {% if gallery.id == page.gallery-id %}
            {% for image in gallery.images %}

                    {% if page.no-google == true %}

                    {% else %}

                    {% endif %}

            {% endfor %}
        {% endif %}
    {% endfor %}