text:
#if !NOFILEIO
using NBitcoin.DataEncoders;
using NBitcoin.Payment;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
#if !PORTABLE
using System.Net.Http;
#endif
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace NBitcoin.Tests
{
	//https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki
	//Their examples are broken
	public class PaymentTests
	{
		[Fact]
		[Trait("UnitTest", "UnitTest")]
		public void CanParsePaymentUrl()
		{
			Assert.Equal("bitcoin:", new BitcoinUrlBuilder().Uri.ToString());

			var url = CreateBuilder("bitcoin:129mVqKUmJ9uwPxKJBnNdABbuaaNfho4Ha");
			Assert.Equal("129mVqKUmJ9uwPxKJBnNdABbuaaNfho4Ha", url.Address.ToString());

			url = CreateBuilder("bitcoin:129mVqKUmJ9uwPxKJBnNdABbuaaNfho4Ha?amount=0.06");
			Assert.Equal("129mVqKUmJ9uwPxKJBnNdABbuaaNfho4Ha", url.Address.ToString());
			Assert.Equal(Money.Parse("0.06"), url.Amount);

			url = new BitcoinUrlBuilder("bitcoin:129mVqKUmJ9uwPxKJBnNdABbuaaNfho4Ha?amount=0.06&label=Tom%20%26%20Jerry");
			Assert.Equal("129mVqKUmJ9uwPxKJBnNdABbuaaNfho4Ha", url.Address.ToString());
			Assert.Equal(Money.Parse("0.06"), url.Amount);
			Assert.Equal("Tom & Jerry", url.Label);
			Assert.Equal(url.ToString(), new BitcoinUrlBuilder(url.ToString()).ToString());

			//Request 50 BTC with message:
			url = new BitcoinUrlBuilder("bitcoin:129mVqKUmJ9uwPxKJBnNdABbuaaNfho4Ha?amount=50&label=Luke-Jr&message=Donation%20for%20project%20xyz");
			Assert.Equal(Money.Parse("50"), url.Amount);
			Assert.Equal("Luke-Jr", url.Label);
			Assert.Equal("Donation for project xyz", url.Message);
			Assert.Equal(url.ToString(), new BitcoinUrlBuilder(url.ToString()).ToString());

			//Some future version that has variables which are (currently) not understood and required and thus invalid:
			url = new BitcoinUrlBuilder("bitcoin:129mVqKUmJ9uwPxKJBnNdABbuaaNfho4Ha?amount=50&label=Luke-Jr&message=Donation%20for%20project%20xyz&unknownparam=lol");

			//Some future version that has variables which are (currently) not understood but not required and thus valid:
			Assert.Throws<FormatException>(() => new BitcoinUrlBuilder("bitcoin:129mVqKUmJ9uwPxKJBnNdABbuaaNfho4Ha?amount=50&label=Luke-Jr&message=Donation%20for%20project%20xyz&req-unknownparam=lol"));
			Assert.Throws<FormatException>(() => new BitcoinUrlBuilder("bitcoin:129mVqKUmJ9uwPxKJBnNdABbuaaNfho4Ha?amount=50&amount=50"));

			url = new BitcoinUrlBuilder("bitcoin:mq7se9wy2egettFxPbmn99cK8v5AFq55Lx?amount=0.11&r=https://merchant.com/pay.php?h%3D2a8628fc2fbe");
			Assert.Equal("bitcoin:mq7se9wy2egettFxPbmn99cK8v5AFq55Lx?amount=0.11&r=https://merchant.com/pay.php?h%3d2a8628fc2fbe", url.ToString());
			Assert.Equal("https://merchant.com/pay.php?h=2a8628fc2fbe", url.PaymentRequestUrl.ToString());
			Assert.Equal(url.ToString(), new BitcoinUrlBuilder(url.ToString()).ToString());

			//Support no address
			url = new BitcoinUrlBuilder("bitcoin:?r=https://merchant.com/pay.php?h%3D2a8628fc2fbe");
			Assert.Equal("https://merchant.com/pay.php?h=2a8628fc2fbe", url.PaymentRequestUrl.ToString());
			Assert.Equal(url.ToString(), new BitcoinUrlBuilder(url.ToString()).ToString());
		}

		[Fact]
		[Trait("UnitTest", "UnitTest")]
		public void BitcoinUrlKeepUnknowParameter()
		{
			BitcoinUrlBuilder url = new BitcoinUrlBuilder("bitcoin:?r=https://merchant.com/pay.php?h%3D2a8628fc2fbe&idontknow=test");

			Assert.Equal("test", url.UnknowParameters["idontknow"]);
			Assert.Equal(1, url.UnknowParameters.Count);
		}

		private BitcoinUrlBuilder CreateBuilder(string uri)
		{
			var builder = new BitcoinUrlBuilder(uri);
			Assert.Equal(builder.Uri.ToString(), uri);
			builder = new BitcoinUrlBuilder(new Uri(uri, UriKind.Absolute));
			Assert.Equal(builder.ToString(), uri);
			return builder;
		}

		public PaymentRequest LoadPaymentRequest(string path)
		{
			using(var fs = File.OpenRead(path))
			{
				return PaymentRequest.Load(fs);
			}
		}
		public PaymentACK LoadPaymentACK(string path)
		{
			using(var fs = File.OpenRead(path))
			{
				return PaymentACK.Load(fs);
			}
		}

		[Fact]
		[Trait("UnitTest", "UnitTest")]
		public void CanReadPaymentRequest()
		{
			foreach(var provider in new ICertificateServiceProvider[]
			{
				new WindowsCertificateServiceProvider(X509VerificationFlags.IgnoreNotTimeValid |
						X509VerificationFlags.AllowUnknownCertificateAuthority |
						X509VerificationFlags.IgnoreRootRevocationUnknown |
						X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown |
						X509VerificationFlags.IgnoreEndRevocationUnknown)
			})
			{
				PaymentRequest.DefaultCertificateServiceProvider = provider;
				var request = LoadPaymentRequest("data/payreq1_sha1.paymentrequest");
				AssertEx.CollectionEquals(request.ToBytes(), File.ReadAllBytes("data/payreq1_sha1.paymentrequest"));
				Assert.True(request.VerifySignature());
				request.Details.Memo = "lol";
				Assert.False(request.VerifySignature());
				request.Details.Memo = "this is a memo";
				Assert.True(request.VerifySignature());
				Assert.True(request.VerifyChain());
				request = LoadPaymentRequest("data/payreq2_sha1.paymentrequest");
				AssertEx.CollectionEquals(request.ToBytes(), File.ReadAllBytes("data/payreq2_sha1.paymentrequest"));
				Assert.True(request.VerifySignature());
			}
		}

		[Fact]
		[Trait("UnitTest", "UnitTest")]
		public void CanVerifyValidChain()
		{
			foreach(var provider in new ICertificateServiceProvider[]
			{
				new WindowsCertificateServiceProvider(X509VerificationFlags.IgnoreNotTimeValid, X509RevocationMode.NoCheck)
			})
			{
				PaymentRequest.DefaultCertificateServiceProvider = provider;
				var req = LoadPaymentRequest("data/payreq3_validchain.paymentrequest");
				Assert.True(req.VerifyChain());
				Assert.True(req.VerifySignature());
			}
		}

		[Fact]
		[Trait("UnitTest", "UnitTest")]
		public void CanReadTestVectorPayments()
		{
			var tests = new[]
			{
				"data/payreq1_sha256_omitteddefault.paymentrequest",
				"data/payreq1_sha256.paymentrequest",
				"data/payreq2_sha256_omitteddefault.paymentrequest",
				"data/payreq2_sha256.paymentrequest",
				"data/payreq1_sha1_omitteddefault.paymentrequest",
				"data/payreq1_sha1.paymentrequest",
				"data/payreq2_sha1_omitteddefault.paymentrequest",
				"data/payreq2_sha1.paymentrequest",
			};

			foreach(var provider in new ICertificateServiceProvider[]
			{
				new WindowsCertificateServiceProvider(X509VerificationFlags.IgnoreNotTimeValid |
						X509VerificationFlags.AllowUnknownCertificateAuthority |
						X509VerificationFlags.IgnoreRootRevocationUnknown |
						X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown |
						X509VerificationFlags.IgnoreEndRevocationUnknown)
			})
			{
				PaymentRequest.DefaultCertificateServiceProvider = provider;
				foreach(var test in tests)
				{
					var bytes = File.ReadAllBytes(test);
					var request = PaymentRequest.Load(bytes);
					AssertEx.Equal(request.ToBytes(), bytes);

					Assert.True(request.VerifySignature());
					request = PaymentRequest.Load(PaymentRequest.Load(bytes).ToBytes());
					Assert.True(request.VerifySignature());
					Assert.True(request.VerifyChain());
				}
			}
		}

		[Fact]
		[Trait("UnitTest", "UnitTest")]
		public void CanCreatePaymentRequest()
		{
			foreach(var provider in new ICertificateServiceProvider[]
			{
				new WindowsCertificateServiceProvider(X509VerificationFlags.IgnoreNotTimeValid)
			})
			{
				PaymentRequest.DefaultCertificateServiceProvider = provider;
				var cert = File.ReadAllBytes("Data/NicolasDorierMerchant.pfx");
				CanCreatePaymentRequestCore(cert);
				if(provider is WindowsCertificateServiceProvider)
				{
					CanCreatePaymentRequestCore(new X509Certificate2(cert, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet));
				}
			}
		}

		private static void CanCreatePaymentRequestCore(object cert)
		{
			var request = new PaymentRequest();
			request.Details.Memo = "hello";
			request.Sign(cert, PKIType.X509SHA256);

			Assert.NotNull(request.MerchantCertificate);
			Assert.False(new X509Certificate2(request.MerchantCertificate, "", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable).HasPrivateKey);
			Assert.True(request.VerifySignature());
			Assert.False(request.VerifyChain());
			AssertEx.CollectionEquals(request.ToBytes(), PaymentRequest.Load(request.ToBytes()).ToBytes());
			Assert.True(PaymentRequest.Load(request.ToBytes()).VerifySignature());
		}
		[Fact]
		[Trait("UnitTest", "UnitTest")]
		public void CanParsePaymentACK()
		{
			var ack = LoadPaymentACK("data/paymentack.data");
			Assert.Equal("thanks customer !", ack.Memo);
			Assert.Equal("thanks merchant !", ack.Payment.Memo);
			Assert.Equal(2, ack.Payment.Transactions.Count);
			Assert.Equal(2, ack.Payment.RefundTo.Count);
			AssertEx.CollectionEquals(ack.ToBytes(), PaymentACK.Load(ack.ToBytes()).ToBytes());
			AssertEx.CollectionEquals(ack.ToBytes(), File.ReadAllBytes("data/paymentack.data"));
		}
		[Fact]
		[Trait("UnitTest", "UnitTest")]
		public void CanCreatePaymentMessageAndACK()
		{
			var request = LoadPaymentRequest("data/payreq1_sha1.paymentrequest");
			var payment = request.CreatePayment();
			AssertEx.CollectionEquals(request.Details.MerchantData, payment.MerchantData);
			AssertEx.CollectionEquals(payment.ToBytes(), PaymentMessage.Load(payment.ToBytes()).ToBytes());
			payment.Memo = "thanks merchant !";
			AssertEx.CollectionEquals(payment.ToBytes(), PaymentMessage.Load(payment.ToBytes()).ToBytes());
			var ack = payment.CreateACK();
			AssertEx.CollectionEquals(ack.Payment.ToBytes(), PaymentMessage.Load(payment.ToBytes()).ToBytes());
			AssertEx.CollectionEquals(ack.ToBytes(), PaymentACK.Load(ack.ToBytes()).ToBytes());
			ack.Memo = "thanks customer !";
			AssertEx.CollectionEquals(ack.ToBytes(), PaymentACK.Load(ack.ToBytes()).ToBytes());
		}
#if !NOHTTPCLIENT && !NOHTTPSERVER
		[Fact]
		[Trait("UnitTest", "UnitTest")]
		public void CanTalkToPaymentServer()
		{
			using(var server = new PaymentServerTester())
			{
				var uri = server.GetPaymentRequestUri(2);
				BitcoinUrlBuilder btcUri = new BitcoinUrlBuilder(uri);
				var request = btcUri.GetPaymentRequest();
				Assert.True(request.VerifySignature());
				Assert.Equal(2, BitConverter.ToInt32(request.Details.MerchantData, 0));
				var ack = request.CreatePayment().SubmitPayment();
				Assert.NotNull(ack);
			}
		}
#endif

	}
#if !NOHTTPSERVER
	public class PaymentServerTester : IDisposable
	{
		HttpListener _Listener;
		Random rand = new Random();
		string _Prefix;
		public PaymentServerTester()
		{
			while(true)
			{
				try
				{
					_Prefix = "http://127.0.0.1:" + rand.Next(2000, 50000) + "/";
					_Listener = new HttpListener();
					_Listener.Prefixes.Add(_Prefix);
					_Listener.Start();
					_Listener.BeginGetContext(ListenerCallback, null);
					break;
				}
				catch(HttpListenerException)
				{
				}
			}
		}

		void ListenerCallback(IAsyncResult ar)
		{
			try
			{
				var context = _Listener.EndGetContext(ar);
				var type = context.Request.QueryString.Get("type");
				var businessId = int.Parse(context.Request.QueryString.Get("id"));
				var now = DateTimeOffset.UtcNow;
				var expire = now + TimeSpan.FromDays(1);
				TxOut txOut = new TxOut(Money.Coins(1), new Key().ScriptPubKey);
				if(type == "Request")
				{
					Assert.Equal(PaymentRequest.MediaType, context.Request.AcceptTypes[0]);
					context.Response.ContentType = PaymentRequest.MediaType;
					PaymentRequest request = new PaymentRequest();
					request.Details.MerchantData = BitConverter.GetBytes(businessId);
					request.Details.Network = Network.RegTest;
					request.Details.Expires = expire;
					request.Details.Time = now;
					request.Details.PaymentUrl = new Uri(_Prefix + "?id=" + businessId + "&type=Payment");
					request.Details.Outputs.Add(new PaymentOutput(txOut));
					request.Sign(File.ReadAllBytes("data/NicolasDorierMerchant.pfx"), PKIType.X509SHA256);
					request.WriteTo(context.Response.OutputStream);
				}
				else if(type == "Payment")
				{
					Assert.Equal(PaymentMessage.MediaType, context.Request.ContentType);
					Assert.Equal(PaymentACK.MediaType, context.Request.AcceptTypes[0]);

					var payment = PaymentMessage.Load(context.Request.InputStream);
					Assert.Equal(businessId, BitConverter.ToInt32(payment.MerchantData, 0));

					context.Response.ContentType = PaymentACK.MediaType;
					var ack = payment.CreateACK();
					ack.Memo = "Thanks for your purchase";
					ack.WriteTo(context.Response.OutputStream);
				}
				else
					Assert.False(true, "Impossible");

				context.Response.Close();
				_Listener.BeginGetContext(ListenerCallback, null);
			}
			catch(Exception)
			{
				if(!_Stopped)
					throw;
			}
		}
		public Uri GetPaymentRequestUri(int businessId)
		{
			BitcoinUrlBuilder builder = new BitcoinUrlBuilder()
			{
				PaymentRequestUrl = new Uri(_Prefix + "?id=" + businessId + "&type=Request")
			};
			return builder.Uri;
		}

		volatile bool _Stopped;

		#region IDisposable Members

		public void Dispose()
		{
			_Stopped = true;
			_Listener.Close();
		}

		#endregion
	}
#endif
}
#endif


text:
require 'spec_helper'
require 'domain/fixtures'

module Fountain::Domain
  describe AggregateRoot do

    subject { InventoryItem.new(SecureRandom.uuid) }

    describe '#commit_events' do
      it 'clears the journal and updates the last sequence number' do
        expect(subject.uncommitted_event_count).to eql(1)
        subject.commit_events
        expect(subject.uncommitted_event_count).to eql(0)
      end
    end

    describe 'serialization' do
      it 'excludes the journal from serialization' do
        expect(subject.marshal_dump).to_not include(:@journal)
      end
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
define(['lodash', 'log', './statement'], function (_, log, Statement) {

    /**
     * Class for throw statement in ballerina.
     * @param expression one expression for a throw statement.
     * @constructor
     */
    var ThrowStatement = function (args) {
        Statement.call(this, 'ThrowStatement');
        this.type = "ThrowStatement";
    };

    ThrowStatement.prototype = Object.create(Statement.prototype);
    ThrowStatement.prototype.constructor = ThrowStatement;

    ThrowStatement.prototype.setExpression = function (expression, options) {
        if (!_.isNil(expression)) {
            this.setAttribute('_expression', expression, options);
        } else {
            log.error("Cannot set undefined to the throw statement.");
        }
    };

    /**
     * Set the throw statement string
     * @param {string} throwString
     */
    ThrowStatement.prototype.setStatementString = function (statementString, options) {
        this.getChildren()[0].setExpression(statementString.split('throw ')[1]);
    };

    /**
     * Get the throw statement string
     * @return {string} throw statement string
     */
    ThrowStatement.prototype.getStatementString = function () {
        return 'throw ' + this.getChildren()[0].getExpression();
    };

    /**
     * initialize ThrowStatement from json object
     * @param {Object} jsonNode to initialize from
     */
    ThrowStatement.prototype.initFromJson = function (jsonNode) {
        var self = this;
        _.each(jsonNode.children, function (childNode) {
            var child = self.getFactory().createFromJson(childNode);
            self.addChild(child);
            child.initFromJson(childNode);
        });
    };

    return ThrowStatement;
});


text: export default (obj, keys) => keys.every(key => obj.hasOwnProperty && obj.hasOwnProperty(key));


text:
using BEPUphysics.Constraints.SolverGroups;
using BEPUphysics.Constraints.TwoEntity.JointLimits;
using BEPUphysics.Constraints.TwoEntity.Joints;
using BEPUphysics.Constraints.TwoEntity.Motors;
using BEPUphysics.Entities;
using BEPUphysics.Entities.Prefabs;
using BEPUphysics.CollisionRuleManagement;
using BEPUphysics.CollisionShapes;
using BEPUphysics.CollisionShapes.ConvexShapes;
using System.Collections.Generic;
using BEPUutilities;

namespace BEPUphysicsDemos.Demos.Extras
{
    /// <summary>
    /// A one-armed guy flops on the ground.  Involves a detailed ragdoll-like limb with appropriate limits.
    /// </summary>
    public class UnfortunateGuyDemo : StandardDemo
    {
        /// <summary>
        /// Constructs a new demo.
        /// </summary>
        /// <param name="game">Game owning this demo.</param>
        public UnfortunateGuyDemo(DemosGame game)
            : base(game)
        {
            Entity ground = new Box(Vector3.Zero, 10, 1, 10);
            Space.Add(ground);

            //Rather than add basically redundant code for every limb, this demo
            //focuses on a single arm, showing some extra details and limits.

            //Make the torso.
            var bodies = new List<CompoundShapeEntry>()
            {
                new CompoundShapeEntry(new BoxShape(2, 1.5f, 1), new Vector3(-1, 3, 0), 50),
                new CompoundShapeEntry(new SphereShape(.45f), new Vector3(.4f, 3, 0), 1),
                new CompoundShapeEntry(new SphereShape(.25f), new Vector3(-1.9f, 3.5f, 0), 1),
                new CompoundShapeEntry(new SphereShape(.25f), new Vector3(-1.9f, 2.5f, 0), 1),
                new CompoundShapeEntry(new SphereShape(.25f), new Vector3(-.3f, 2.3f, 0), 1)
            };

            var torso = new CompoundBody(bodies, 54);
            Space.Add(torso);

            //Make the upper arm.
            Entity upperArm = new Box(torso.Position + new Vector3(1, 1.4f, 0), .4f, 1.2f, .4f, 8);
            Space.Add(upperArm);

            //A ball socket joint will handle the linear degrees of freedom between the two entities.
            var ballSocketJoint = new BallSocketJoint(torso, upperArm, torso.Position + new Vector3(1, .7f, 0));
            Space.Add(ballSocketJoint);

            //Shoulders don't have a simple limit.  The EllipseSwingLimit allows angles within an ellipse, which is closer to how some joints function
            //than just flat planes (like two RevoluteLimits) or a single angle (like SwingLimits).
            var swingLimit = new EllipseSwingLimit(torso, upperArm, Vector3.Up, MathHelper.PiOver2, MathHelper.PiOver4 * 3);
            Space.Add(swingLimit);

            //Upper arms can't spin around forever.
            var twistLimit = new TwistLimit(torso, upperArm, Vector3.Up, Vector3.Up, -MathHelper.PiOver4 / 2, MathHelper.PiOver4);
            twistLimit.SpringSettings.Stiffness = 100;
            twistLimit.SpringSettings.Damping = 100;
            Space.Add(twistLimit);

            //Make the lower arm.
            Entity lowerArm = new Box(upperArm.Position + new Vector3(0, 1.4f, 0), .35f, 1.3f, .35f, 8);
            Space.Add(lowerArm);

            var elbow = new SwivelHingeJoint(upperArm, lowerArm, upperArm.Position + new Vector3(0, .6f, 0), Vector3.Forward);
            //Forearm can twist a little.
            elbow.TwistLimit.IsActive = true;
            elbow.TwistLimit.MinimumAngle = -MathHelper.PiOver4 / 2;
            elbow.TwistLimit.MaximumAngle = MathHelper.PiOver4 / 2;
            elbow.TwistLimit.SpringSettings.Damping = 100;
            elbow.TwistLimit.SpringSettings.Stiffness = 100;

            //The elbow is like a hinge, but it can't hyperflex.
            elbow.HingeLimit.IsActive = true;
            elbow.HingeLimit.MinimumAngle = 0;
            elbow.HingeLimit.MaximumAngle = MathHelper.Pi * .7f;
            Space.Add(elbow);

            Entity hand = new Box(lowerArm.Position + new Vector3(0, .9f, 0), .4f, .55f, .25f, 3);
            Space.Add(hand);

            ballSocketJoint = new BallSocketJoint(lowerArm, hand, lowerArm.Position + new Vector3(0, .7f, 0));
            Space.Add(ballSocketJoint);

            //Wrists can use an ellipse limit too.
            swingLimit = new EllipseSwingLimit(lowerArm, hand, Vector3.Up, MathHelper.PiOver4, MathHelper.PiOver2);
            Space.Add(swingLimit);

            //Allow a little extra twist beyond the forearm.
            twistLimit = new TwistLimit(lowerArm, hand, Vector3.Up, Vector3.Up, -MathHelper.PiOver4 / 2, MathHelper.PiOver4 / 2);
            twistLimit.SpringSettings.Stiffness = 100;
            twistLimit.SpringSettings.Damping = 100;
            Space.Add(twistLimit);

            //The hand is pretty floppy without some damping.
            var angularMotor = new AngularMotor(lowerArm, hand);
            angularMotor.Settings.VelocityMotor.Softness = .5f;
            Space.Add(angularMotor);

            //Make sure the parts of the arm don't collide.
            CollisionRules.AddRule(torso, upperArm, CollisionRule.NoBroadPhase);
            CollisionRules.AddRule(lowerArm, upperArm, CollisionRule.NoBroadPhase);
            CollisionRules.AddRule(lowerArm, hand, CollisionRule.NoBroadPhase);

            game.Camera.Position = new Vector3(0, 4, 20);
        }

        /// <summary>
        /// Gets the name of the simulation.
        /// </summary>
        public override string Name
        {
            get { return "Unfortunate One-armed Guy"; }
        }
    }
}


text:
class Admin::CategoriesController < Admin::ApplicationController
  before_action :set_category, only: [:show, :edit, :update, :destroy]

  def index
    @categories = Category.all
  end

  def show
  end

  def new
    @category = Category.new
  end

  def edit
  end

  def create
    @category = Category.new(category_params)
    authorize @category
    if @category.save
      redirect_to [:admin, @category], notice: 'Category was successfully created.'
    else
      render :new
    end
  end

  def update
    authorize @category
    if @category.update(category_params)
      redirect_to [:admin, @category], notice: 'Category was successfully updated.'
    else
      render :edit
    end
  end

  def destroy
    authorize @category
    @category.destroy
    redirect_to categories_url, notice: 'Category was successfully destroyed.'
  end

  private

  # Use callbacks re common setup or constraints between actions.
  def set_category
    @category = Category.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def category_params
    params.require(:category).permit(:name)
  end
end


text:
@interface ServiceDebugger_NetworkModel()
{
	NSUInteger			_totalCount;

	NSUInteger			_sendLowerBound;
	NSUInteger			_sendUpperBound;

	NSUInteger			_recvLowerBound;
	NSUInteger			_recvUpperBound;

	NSUInteger			_lastUploadBytes;
	NSUInteger			_lastDownloadBytes;

	NSUInteger			_uploadBytes;
	NSUInteger			_downloadBytes;

	NSMutableArray *	_sendPlots;
	NSMutableArray *	_recvPlots;

	NSMutableArray *	_history;
	NSUInteger			_bandWidth;
}
@end

#pragma mark -

@implementation ServiceDebugger_NetworkModel

@synthesize totalCount = _totalCount;

@synthesize sendLowerBound = _sendLowerBound;
@synthesize sendUpperBound = _sendUpperBound;
@synthesize recvLowerBound = _recvLowerBound;
@synthesize recvUpperBound = _recvUpperBound;

@synthesize sendPlots = _sendPlots;
@synthesize recvPlots = _recvPlots;

@synthesize uploadBytes = _uploadBytes;
@synthesize downloadBytes = _downloadBytes;

@synthesize history = _history;
@synthesize bandWidth = _bandWidth;

DEF_SINGLETON( ServiceDebugger_NetworkModel )

DEF_INT( BANDWIDTH_CURRENT,	0 )
DEF_INT( BANDWIDTH_GPRS,	1 )
DEF_INT( BANDWIDTH_EDGE,	2 )
DEF_INT( BANDWIDTH_3G,		3 )

- (void)load
{
	[super load];

	_history = [[NSMutableArray alloc] init];

	_uploadBytes = 0;
	_downloadBytes = 0;

	_sendPlots = [[NSMutableArray alloc] init];
	[_sendPlots pushTail:[NSNumber numberWithInt:0]];

	_recvPlots = [[NSMutableArray alloc] init];
	[_recvPlots pushTail:[NSNumber numberWithInt:0]];

	_sendLowerBound = 0;
	_sendUpperBound = 1;

	_recvLowerBound = 0;
	_recvUpperBound = 1;

	[BeeRequestQueue sharedInstance].whenCreate = ^( BeeRequest * req )
	{
		[_history insertObject:req atIndex:0];
		[_history keepHead:MAX_REQUEST_HISTORY];

		_totalCount = [BeeRequestQueue sharedInstance].requests.count;
	};

	[BeeRequestQueue sharedInstance].whenUpdate = ^( BeeRequest * req )
	{
		if ( req.sending )
		{
			_uploadBytes += [req uploadBytes];
		}
		else if ( req.succeed || req.failed || req.cancelled )
		{
			_downloadBytes += [req downloadBytes];
		}
	};

	[self observeTick];
}

- (void)unload
{
	[self unobserveTick];

	[_sendPlots removeAllObjects];
	[_sendPlots release];

	[_recvPlots removeAllObjects];
	[_recvPlots release];

	[_history removeAllObjects];
	[_history release];

	[super unload];
}

- (void)handleTick:(NSTimeInterval)elapsed
{
	[_sendPlots pushTail:__INT(_uploadBytes - _lastUploadBytes)];
	[_sendPlots keepTail:MAX_REQUEST_HISTORY];

	for ( NSNumber * n in _sendPlots )
	{
		if ( n.intValue > _sendUpperBound )
		{
			_sendUpperBound = n.intValue;
			if ( _sendUpperBound < _sendLowerBound )
			{
				_sendLowerBound = _sendUpperBound;
			}
		}
		else if ( n.intValue < _sendLowerBound )
		{
			_sendLowerBound = n.intValue;
		}
	}

	[_recvPlots pushTail:__INT(_downloadBytes - _lastDownloadBytes)];
	[_recvPlots keepTail:MAX_REQUEST_HISTORY];

	for ( NSNumber * n in _recvPlots )
	{
		if ( n.intValue > _recvUpperBound )
		{
			_recvUpperBound = n.intValue;
			if ( _recvUpperBound < _recvLowerBound )
			{
				_recvLowerBound = _recvUpperBound;
			}
		}
		else if ( n.intValue < _recvLowerBound )
		{
			_recvLowerBound = n.intValue;
		}
	}

	_lastUploadBytes = _uploadBytes;
	_lastDownloadBytes = _downloadBytes;
}

- (void)changeBandWidth:(NSUInteger)bw
{
	if ( bw == _bandWidth )
		return;

	_bandWidth = bw;

	if ( self.BANDWIDTH_CURRENT == _bandWidth )
	{
		[ASIHTTPRequest setForceThrottleBandwidth:NO];
		[ASIHTTPRequest setMaxBandwidthPerSecond:0];
	}
	else if ( self.BANDWIDTH_GPRS == _bandWidth )
	{
		[ASIHTTPRequest setForceThrottleBandwidth:YES];
		[ASIHTTPRequest setMaxBandwidthPerSecond:10 * 1024];
	}
	else if ( self.BANDWIDTH_EDGE == _bandWidth )
	{
		[ASIHTTPRequest setForceThrottleBandwidth:YES];
		[ASIHTTPRequest setMaxBandwidthPerSecond:30 * 1024];
	}
	else if ( self.BANDWIDTH_3G == _bandWidth )
	{
		[ASIHTTPRequest setForceThrottleBandwidth:YES];
		[ASIHTTPRequest setMaxBandwidthPerSecond:300 * 1024];
	}
}

@end

#endif	// #if (__ON__ == __BEE_DEVELOPMENT__)

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)


text:
FIND_PATH(CPPUTEST_INCLUDE_DIR NAMES CppUTest/TestHarness.h
    PATHS $ENV{CPPUTEST_DIR} ${CPPUTEST_DIR} /usr /usr/local /opt/local
    PATH_SUFFIXES include
)

FIND_PATH(CPPUTEST_EXT_INCLUDE_DIR NAMES CppUTestExt/MockSupport.h
    PATHS $ENV{CPPUTEST_DIR} ${CPPUTEST_DIR} /usr /usr/local /opt/local
    PATH_SUFFIXES include
)

FIND_LIBRARY(CPPUTEST_LIBRARY NAMES CppUTest
    PATHS $ENV{CPPUTEST_DIR} ${CPPUTEST_DIR} /usr /usr/local /opt/local
    PATH_SUFFIXES lib lib64
)

FIND_LIBRARY(CPPUTEST_EXT_LIBRARY NAMES CppUTestExt
    PATHS $ENV{CPPUTEST_DIR} ${CPPUTEST_DIR} /usr /usr/local /opt/local
    PATH_SUFFIXES lib lib64
)

# handle the QUIETLY and REQUIRED arguments and set CURL_FOUND to TRUE if
# all listed variables are TRUE
INCLUDE(FindPackageHandleStandardArgs)
set(FPHSA_NAME_MISMATCHED 1)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(CPPUTEST DEFAULT_MSG CPPUTEST_LIBRARY CPPUTEST_INCLUDE_DIR)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(CPPUTEST_EXT DEFAULT_MSG CPPUTEST_EXT_LIBRARY CPPUTEST_EXT_INCLUDE_DIR)
set(FPHSA_NAME_MISMATCHED 0)

mark_as_advanced(CPPUTEST_INCLUDE_DIR CPPUTEST_LIBRARY CPPUTEST_EXT_LIBRARY CPPUTEST_INCLUDE_DIR)

IF(CPPUTEST_FOUND)
    SET(CPPUTEST_LIBRARIES ${CPPUTEST_LIBRARY})
    SET(CPPUTEST_INCLUDE_DIRS ${CPPUTEST_INCLUDE_DIR})
ENDIF(CPPUTEST_FOUND)

IF(CPPUTEST_EXT_FOUND)
    SET(CPPUTEST_EXT_LIBRARIES ${CPPUTEST_EXT_LIBRARY})
    SET(CPPUTEST_EXT_INCLUDE_DIRS ${CPPUTEST_EXT_INCLUDE_DIR})
ENDIF(CPPUTEST_EXT_FOUND)


text:
package uk.joshiejack.settlements.npcs;

import com.google.common.collect.Maps;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.logging.log4j.util.Strings;
import uk.joshiejack.settlements.Settlements;
import uk.joshiejack.settlements.client.gui.NPCDisplayData;
import uk.joshiejack.settlements.client.renderer.entity.RenderNPC;
import uk.joshiejack.settlements.data.database.NPCLoader;
import uk.joshiejack.settlements.item.AdventureItems;
import uk.joshiejack.settlements.npcs.gifts.GiftQuality;
import uk.joshiejack.settlements.npcs.gifts.GiftRegistry;
import uk.joshiejack.settlements.util.SpeechHelper;
import uk.joshiejack.penguinlib.scripting.Scripting;
import uk.joshiejack.penguinlib.util.PenguinRegistry;
import uk.joshiejack.penguinlib.util.helpers.generic.StringHelper;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;

public final class NPC extends PenguinRegistry.Item<NPC> implements NPCDisplayData, NPCInfo {
    private static final ResourceLocation TEXTURE_DEFAULT = new ResourceLocation("textures/entity/steve.png");
    public static final Map<ResourceLocation, NPC> REGISTRY = Maps.newLinkedHashMap();
    public static final NPC NULL_NPC = new NPC(new ResourceLocation(Settlements.MODID, "null")).setOccupation(Strings.EMPTY).setNPCClass(NPCLoader.NPCClass.NULL);
    public static final NPC CUSTOM_NPC = new NPC(new ResourceLocation(Settlements.MODID, "custom")).setOccupation(Strings.EMPTY).setNPCClass(NPCLoader.NPCClass.NULL);
    private static List<NPC> ALL;

    private final Object2IntMap<String> data = new Object2IntOpenHashMap<>();
    private final String unlocalizedGreeting;
    private ResourceLocation lootTable;
    private ResourceLocation script;
    private String localizedName;
    private ResourceLocation skin;
    private String playerSkin;
    private String occupation;
    private NPCLoader.NPCClass clazz;
    private int insideColor;
    private int outsideColor;

    public NPC(ResourceLocation resource) {
        super("npc", REGISTRY, resource);
        this.skin = TEXTURE_DEFAULT;
        this.insideColor = 0xFFFFFF;
        this.outsideColor = 0x000000;
        this.unlocalizedGreeting = unlocalizedKey + ".greeting";
    }

    @Override
    public ItemStack getIcon() {
        return AdventureItems.NPC_SPAWNER.getStackFromResource(getRegistryName());
    }

    public void addData(String name, int value) {
        this.data.put(name, value);
    }

    //Set a resource skin
    public void setSkin(ResourceLocation resource) {
        //TODO: If resource domain is this mod and it's not the joshie npc, then search in the config folder instead
        this.skin = new ResourceLocation(resource.getNamespace(), "textures/entity/" + resource.getPath() + ".png");
    }

    public void setScript(ResourceLocation script) {
        this.script = script;
    }

    //Load a skin from the net
    public void setSkin(String playerSkin) {
        this.playerSkin = playerSkin;
    }

    public void setLocalizedName(String localizedName) {
        this.localizedName = localizedName;
    }

    public void setLootTable(ResourceLocation lootTable) {
        this.lootTable = lootTable;
    }

    public String getUnlocalizedKey() {
        return unlocalizedKey;
    }

    public int getData(String name) {
        return data.getInt(name);
    }

    @Nullable
    public ResourceLocation getLootTable() {
        return lootTable;
    }

    public void callScript(String function, Object... params) {
        if (script != null) {
            Scripting.get(script).callFunction(function, params);
        }
    }

    @Nonnull
    public static NPC getNPCFromRegistry(ResourceLocation resource) {
        NPC npc = REGISTRY.get(resource);
        return npc != null ? npc : NULL_NPC;
    }

    public static List<NPC> all() {
        if (ALL == null) {
            ALL = REGISTRY.values().stream().filter((npc -> npc != NULL_NPC)).collect(Collectors.toList());
        }

        return ALL;
    }

    @Override
    public String getOccupation() {
        return occupation;
    }

    public NPC setNPCClass(NPCLoader.NPCClass clazz) {
        this.clazz = clazz;
        return this;
    }

    public NPC setOccupation(String occupation) {
        this.occupation = occupation;
        return this;
    }

    public void setColors(int inside, int outside) {
        this.insideColor = inside;
        this.outsideColor = outside;
    }

    public NPCLoader.NPCClass getNPCClass() {
        return clazz;
    }

    public int getInsideColor() {
        return insideColor;
    }

    @Override
    public String getGreeting(Random random) {
        return SpeechHelper.getRandomSpeech(random, getUnlocalizedGreeting(), 20);
    }

    @Override
    public GiftQuality getGiftQuality(ItemStack stack) {
        return GiftRegistry.getQualityForNPC(this, stack);
    }

    @Override
    public String substring(String name) {
        return getUnlocalizedKey() + "." + name;
    }

    public int getOutsideColor() {
        return outsideColor;
    }

    public String getUnlocalizedGreeting() {
        return unlocalizedGreeting;
    }

    @Override
    public String getLocalizedName() {
        return localizedName != null ? localizedName : StringHelper.localize(unlocalizedName);
    }

    @SideOnly(Side.CLIENT)
    public ResourceLocation getSkin() {
        if (playerSkin != null && skin == null) {
            skin = RenderNPC.getSkinFromUsernameOrUUID(null, playerSkin);
            //We've loaded in the proper skin so let's remove this
            playerSkin = null;
        }

        return skin;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        NPC npc = (NPC) o;
        return Objects.equals(resource, npc.resource);
    }

    @Override
    public int hashCode() {
        return Objects.hash(resource);
    }
}


text:
package practice;

import java.util.*;

/**
 *

 *     Given a set of points (integers), find the number of ways in which they can be added to make up a given score.
 *     For example, if the points are 1, 2, 3, a score of 5 can be made in 13 different ways: (1, 1, 1, 1, 1),
 *     (1, 1, 1, 2), (1, 1, 2, 1), (1, 2, 1, 1), (1, 2, 2), (1, 1, 3), (1, 3, 1), (2, 1, 1, 1), (2, 1, 2), (2, 2, 1),
 *     (2, 3), (3, 1, 1), (3, 2).
 *

 *

 *     Clearly a DP problem; with memoization and bottom-up approach this boils down to a processing that is
 *     similar to that of the popular coin change problem.
 *

 * Created by kmhaswade on 8/20/16.
 */
public class AdditiveCombinations {

    /**
     * Implements a solution using a bottom-up, iterative approach.
     * @param set a set of points per attempt
     * @param score a score to get
     * @return number of ways to get to a score given the set of points per shot
     */
    static Integer countBottomUp(Set<Integer> set, Integer score) {
        List<Integer> xs = new ArrayList<>(set);
        xs.sort(null);
        List<Integer> comb = new ArrayList<>(score + 1); // just for clarity
        for (int i = 0; i <= score; i++) {
            comb.add(0);
        }
        for (int x : xs)
            if (x <= score)
                comb.set(x, 1);
        for (int i = 0; i <= score; i++) {
            int total = comb.get(i);
            for (Integer x : xs) {
                int idx = i - x;
                if (idx < 0)
                    break;
                total += comb.get(idx);
            }
            comb.set(i, total);
        }
        return comb.get(score);
    }

    static int countTopDown(Set<Integer> ps, int score) {
        int [] points = new int[ps.size()];
        int i = 0;
        for (int p : ps)
            points[i++] = p;
        Arrays.sort(points);
        Integer[] nWays = new Integer[score + 1];
        return countTopDown(points, nWays, score);
    }
    static int countTopDown(Integer[] ps, int score) {
        return countTopDown(new HashSet<>(Arrays.asList(ps)), score);
    }
    static int countTopDown(int[] points, Integer[] nWays, int score) {
        if (nWays[score] != null)
            return nWays[score];
        int total = 0;
        for (int pointsPerShot : points) {
            int prevScore = score - pointsPerShot;
            if (prevScore < 0)
                break; // sorted points, so other (higher) values can be skipped
            if (prevScore == 0) {
                total += 1; // this shot at current score, takes us to the given final score
                continue;
            }
            Integer nWaysPrevScore = nWays[prevScore];
            if (nWaysPrevScore == null) {
                nWaysPrevScore = countTopDown(points, nWays, prevScore);
                nWays[prevScore] = nWaysPrevScore;
            }
            total += nWaysPrevScore;
        }
        nWays[score] = total;
        return total;
    }
}


text:
def evaluate_design_space_level_one(arch_dict_list, orbits, instruments):
    # --> Create a matrix of --> row: architecture - col: orbit instrument pair
    bool_matrix = []
    for arch_dict in arch_dict_list:
        bool_matrix.append(arch_dict['inputs'])

    num_architectures = len(bool_matrix)

    # --> Create the list of summated column values
    summation_list = [0] * len(bool_matrix[0])
    for row in bool_matrix:
        for row_index in range(len(row)):
            if(row[row_index] is True):
                summation_list[row_index] = summation_list[row_index] + 1

    # --> Create the list of pairs(summated column values, index)
    summation_index_list = []
    for x in range(len(summation_list)):
        summation_index_list.append({'value': summation_list[x], 'index': x})

    summation_index_list = sorted(summation_index_list, key=lambda k: k['value'])

    print("Current Results")
    for x in summation_index_list:
        print(x)

    # --> Enumerate Combinations
    combination_key_list = []
    index = 0
    for orb in orbits:
        for inst in instruments:
            combination_key_list.append({'orbit': orb, 'instrument': inst, 'index': index})
            index = index + 1

    # --> Set the ground work for the final dict
    final_dict = {}
    for orb in orbits:
        final_dict[orb] = {}
        for inst in instruments:
            final_dict[orb][inst] = {}

    # --> Fill in the final dictionary
    combo_under_eval_index = 0
    for orb in orbits:
        for inst in instruments:
            value_dict = index_to_value(combo_under_eval_index, summation_index_list)
            value = value_dict['value']
            percent = round((value / num_architectures) * 100, 2)
            final_dict[orb][inst] = {'value': str(value), 'percent': str(percent)}
            combo_under_eval_index = combo_under_eval_index + 1

    #print(final_dict)

    final_list = []
    for entry in summation_index_list:
        index = entry['index']
        value = entry['value']
        obj = index_to_combination(index, combination_key_list)
        if not obj:
            continue
        percent = round((value / num_architectures) * 100, 2)
        final_list.append({'orbit': obj['orbit'], 'instrument': obj['instrument'], 'value': str(value), 'percent': str(percent)})
    return final_list

def index_to_value(index, values):
    for val in values:
        if val['index'] is index:
            return val
    return False

def index_to_combination(index, combinations):
    for combo in combinations:
        if combo['index'] is index:
            return combo
    return False

def summate_matrix_columns(bool_matrix, combination_index, combinations):
    num_architectures = len(bool_matrix)
    output = index_to_combination(combination_index, combinations)
    print("Evaluating: ", output['orbit'], output['instrument'])
    summation_list = {}
    for x in range(len(bool_matrix)):         # --> Iterate over each architecture
        if bool_matrix[x][combination_index] is True:
            index = 0
            for y in range(len(bool_matrix[0])):  # --> Iterate over each element in an architecture
                if y is combination_index:
                    index = index + 1
                    continue
                if bool_matrix[x][y] is True:
                    if str(index) not in summation_list:
                        summation_list[str(index)] = 1
                    else:
                        summation_list[str(index)] = summation_list[str(index)] + 1
                index = index + 1

    # --> Turn summation_list into a sorted list of dictoinaries with all of our information
    dictionary_list = []
    for key in summation_list:
        key_info = index_to_combination(int(key), combinations)
        percent_seen = round((summation_list[key] / num_architectures) * 100, 2)
        key_num = int(key)
        # --> {'index': index, 'orbit': orbit, 'inst': inst, 'value': value, 'percent': percent}
        temp_dictionary = {'index': str(key_num), 'orbit': key_info['orbit'], 'instrument': key_info['instrument'],
                           'value': str(summation_list[key]), 'percent': str(percent_seen)}
        dictionary_list.append(temp_dictionary)

    dictionary_list = sorted(dictionary_list, key=lambda k: k['percent'])
    return dictionary_list

# --> Evaluates the least used orbit - instrument combination for a given orbit - instrument combination
# --> Calculates the percent each combination is seen for a given combination (num times seen / total architectures)
def evaluate_design_space_level_two(arch_dict_list, orbits, instruments):
    # --> Create a matrix of --> row: architecture - col: orbit instrument pair
    bool_matrix = []
    for arch_dict in arch_dict_list:
        bool_matrix.append(arch_dict['inputs'])

    # --> Enumerate Combinations
    combination_key_list = []
    index = 0
    for orb in orbits:
        for inst in instruments:
            combination_key_list.append({'orbit': orb, 'instrument': inst, 'index': index})
            index = index + 1

    # --> Set the ground work for the final dict
    final_dict = {}
    for orb in orbits:
        final_dict[orb] = {}
        for inst in instruments:
            final_dict[orb][inst] = []

    combo_under_eval_index = 0
    for orb in orbits:
        for inst in instruments:
            # --> now we create create the summation_list
            final_dict[orb][inst] = summate_matrix_columns(bool_matrix, combo_under_eval_index, combination_key_list)
            combo_under_eval_index = combo_under_eval_index + 1

    return final_dict


text:
export * from './fixed-size-virtual-scroll';
export * from './scroll-dispatcher';
export * from './scrollable';
export * from './scrolling-module';
export * from './viewport-ruler';
export * from './virtual-for-of';
export * from './virtual-scroll-strategy';
export * from './virtual-scroll-viewport';


text:
'use strict';

var util = require('util');
var msRest = require('ms-rest');
var WebResource = msRest.WebResource;

/**
 * @class
 * Paths
 * __NOTE__: An instance of this class is automatically created for an
 * instance of the AutoRestParameterizedHostTestClient.
 * Initializes a new instance of the Paths class.
 * @constructor
 *
 * @param {AutoRestParameterizedHostTestClient} client Reference to the service client.
 */
function Paths(client) {
  this.client = client;
}

/**
 * Get a 200 to test a valid base uri
 *
 * @param {string} accountName Account Name
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {null} [result]   - The deserialized result object.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
Paths.prototype.getEmpty = function (accountName, options, callback) {
  var client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (accountName === null || accountName === undefined || typeof accountName.valueOf() !== 'string') {
      throw new Error('accountName cannot be null or undefined and it must be of type string.');
    }
    if (this.client.host === null || this.client.host === undefined || typeof this.client.host.valueOf() !== 'string') {
      throw new Error('this.client.host cannot be null or undefined and it must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var baseUrl = this.client.baseUri;
  var requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'customuri';
  requestUrl = requestUrl.replace('{accountName}', accountName);
  requestUrl = requestUrl.replace('{host}', this.client.host);

  // Create HTTP transport objects
  var httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  if(options) {
    for(var headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, function (err, response, responseBody) {
    if (err) {
      return callback(err);
    }
    var statusCode = response.statusCode;
    if (statusCode !== 200) {
      var error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      var parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          var resultMapper = new client.models['ErrorModel']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = util.format('Error "%s" occurred in deserializing the responseBody ' +
                         '- "%s" for the default response.', defaultError.message, responseBody);
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    var result = null;
    if (responseBody === '') responseBody = null;

    return callback(null, result, httpRequest, response);
  });
};

module.exports = Paths;


text:
"""Test the init file of IFTTT."""
from homeassistant import data_entry_flow
from homeassistant.components import ifttt
from homeassistant.core import callback

from tests.async_mock import patch

async def test_config_flow_registers_webhook(hass, aiohttp_client):
    """Test setting up IFTTT and sending webhook."""
    with patch("homeassistant.util.get_local_ip", return_value="example.com"):
        result = await hass.config_entries.flow.async_init(
            "ifttt", context={"source": "user"}
        )
    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM, result

    result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
    assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    webhook_id = result["result"].data["webhook_id"]

    ifttt_events = []

    @callback
    def handle_event(event):
        """Handle IFTTT event."""
        ifttt_events.append(event)

    hass.bus.async_listen(ifttt.EVENT_RECEIVED, handle_event)

    client = await aiohttp_client(hass.http.app)
    await client.post(f"/api/webhook/{webhook_id}", json={"hello": "ifttt"})

    assert len(ifttt_events) == 1
    assert ifttt_events[0].data["webhook_id"] == webhook_id
    assert ifttt_events[0].data["hello"] == "ifttt"

    # Invalid JSON
    await client.post(f"/api/webhook/{webhook_id}", data="not a dict")
    assert len(ifttt_events) == 1

    # Not a dict
    await client.post(f"/api/webhook/{webhook_id}", json="not a dict")
    assert len(ifttt_events) == 1


text:
import {Component} from '@angular/core';
import {ConfigService} from '../../../services/config.service';

/**
 * The /about/how-opentender-works component displays a information on the data processing and the usage of the page
 */

@Component({
	moduleId: __filename,
	selector: 'how',
	templateUrl: 'how.component.html'
})
export class AboutHowPage {
	public contactmail: string;

	constructor(private config: ConfigService) {
		this.contactmail = config.contactmail;
	}
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class com.github.maven_nar.cpptasks.gcc.GccLinker (CPPTasks (parallel) 1.1.1-SNAPSHOT API)
</TITLE>

<META NAME="date" CONTENT="2013-09-13">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
com.github.maven_nar.cpptasks.gcc.GccLinker

Packages that use GccLinker

com.github.maven_nar.cpptasks.gcc

Uses of GccLinker in com.github.maven_nar.cpptasks.gcc

Methods in com.github.maven_nar.cpptasks.gcc that return GccLinker

static GccLinker
GccLinker.getInstance()

Constructors in com.github.maven_nar.cpptasks.gcc with parameters of type GccLinker

GccLinker(String command,
          String[] extensions,
          String[] ignoredExtensions,
          String outputPrefix,
          String outputSuffix,
          boolean isLibtool,
          GccLinker libtoolLinker)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2001-2013. All Rights Reserved.


text:
package fr.acxio.tools.agia.alfresco;

import java.rmi.RemoteException;

import org.alfresco.webservice.repository.RepositoryServiceSoapBindingStub;
import org.alfresco.webservice.types.Node;
import org.alfresco.webservice.types.Store;
import org.alfresco.webservice.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * <p>
 * Abstract Alfresco service consumer.
 * </p>
 *
 * @author pcollardez
 *
 */
public class AlfrescoServicesConsumer {

    private static final Logger LOGGER = LoggerFactory.getLogger(AlfrescoServicesConsumer.class);

    public static final Store STORE = new Store(Constants.WORKSPACE_STORE, "SpacesStore");

    private AlfrescoService alfrescoService;
    private NodePathResolver nodePathResolver;

    public NodePathResolver getNodePathResolver() {
        return nodePathResolver;
    }

    public void setNodePathResolver(NodePathResolver sNodePathResolver) {
        nodePathResolver = sNodePathResolver;
    }

    public AlfrescoService getAlfrescoService() {
        return alfrescoService;
    }

    public void setAlfrescoService(AlfrescoService sAlfrescoService) {
        alfrescoService = sAlfrescoService;
    }

    public void init() throws RemoteException {
        Assert.notNull(alfrescoService, "AlfrescoService is required.");
        Assert.notNull(alfrescoService.getEndpointAddress(), "A endpoint address is required.");
        Assert.notNull(alfrescoService.getUsername(), "A username is required.");

        alfrescoService.startSession();
    }

    public void cleanup() {
        alfrescoService.endSession();
    }

    public Node[] getRepositoryMatchingNodes(RepositoryServiceSoapBindingStub sRepositoryService, String sPath) throws NodePathException {
        return nodePathResolver.getRepositoryMatchingNodes(sRepositoryService, sPath);
    }

    public Node[] setLocalMatchingNodes(String sPath, Node[] sNodes) throws NodePathException {
        return nodePathResolver.setLocalMatchingNodes(sPath, sNodes);
    }

    public void evictRepositoryNode(String sPath) {
        nodePathResolver.evictRepositoryNode(sPath);
    }

    public void evictRepositoryNodes() {
        nodePathResolver.evictRepositoryNodes();
    }

}


text:
<?php
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;

AppAsset::register($this);

/* @var $this yii\web\View */
/* @var $content string */
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">

    <meta charset="<?= Yii::$app->charset ?>">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?= Html::csrfMetaTags() ?>
    <meta name="description" content="">
    <meta name="author" content="">

    <title><?= Html::encode($this->title) ?> | Yii admin</title>

    <?= Html::cssFile('@web/admin/vendor/bootstrap/css/bootstrap.min.css') ?>

    <?= Html::cssFile('@web/admin/vendor/metisMenu/metisMenu.min.css') ?>

    <?= Html::cssFile('@web/admin/dist/css/sb-admin-2.css') ?>

    <?= Html::cssFile('@web/admin/vendor/font-awesome/css/font-awesome.min.css') ?>

    <?php $this->head() ?>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>
                Yii Admin

 User Profile

 Settings

 Logout

            <?= $this->render('../elements/admin/sidebar') ?>

<?= Html::encode($this->title) ?>

                        <?= $content ?>

    <?= Html::jsFile('@web/admin/vendor/jquery/jquery.min.js') ?>

    <?= Html::jsFile('@web/admin/vendor/bootstrap/js/bootstrap.min.js') ?>

    <?= Html::jsFile('@web/admin/vendor/metisMenu/metisMenu.min.js') ?>

    <?= Html::jsFile('@web/admin/dist/js/sb-admin-2.js') ?>

    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />

    <?= Html::jsFile('@web/js/ckeditor/ckeditor.js') ?>

    <?= Html::cssFile('@web/js/summernote/summernote.css') ?>
    <?= Html::jsFile('@web/js/summernote/summernote.js') ?>

<?php $this->endPage() ?>


text:
class CreateReviews < ActiveRecord::Migration
  def change
    create_table :reviews do |t|
      t.references :member, index: true

      t.timestamps
    end
  end
end


text:
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
          id="filterMultipartResolver">
        <property name="maxUploadSize" value="100000000"/>
        <property name="defaultEncoding" value="utf-8"/>
    </bean>
</beans>


text:
// Copyright 2010-2015, Google Inc.
// 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 Google Inc. 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
// OWNER OR CONTRIBUTORS 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.

package org.mozc.android.inputmethod.japanese.preference;

import org.mozc.android.inputmethod.japanese.session.SessionExecutor;
import org.mozc.android.inputmethod.japanese.session.SessionHandlerFactory;

import android.content.Context;
import android.content.DialogInterface;
import android.preference.DialogPreference;
import android.util.AttributeSet;

/**
 * A DialogPreference to clear entire history of conversions.
 * This preference command clears all the kind of conversion histories including
 * predictions and suggestions.
 *
 */
public class ClearConversionHistoryDialogPreference extends DialogPreference {
  public ClearConversionHistoryDialogPreference(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  public ClearConversionHistoryDialogPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  @Override
  public void onClick(DialogInterface dialog, int which) {
    if (which == DialogInterface.BUTTON_POSITIVE) {
      SessionExecutor sessionExecutor = SessionExecutor.getInstanceInitializedIfNecessary(
          new SessionHandlerFactory(getContext()), getContext());
      sessionExecutor.clearUserHistory();
      sessionExecutor.clearUserPrediction();
    }
  }
}


text:
include $(HCLIB_ROOT)/../modules/system/inc/hclib_system.pre.mak
include $(HCLIB_ROOT)/include/hclib.mak
include $(HCLIB_ROOT)/../modules/system/inc/hclib_system.post.mak
include ../../custom.mak
#makefile

HCLIB_PERF_CXX?=icpc
CC = $(HCLIB_PERF_CXX)

particle_filter: ex_particle_OPENMP_seq.c
	$(CC) -c -O3 ex_particle_OPENMP_seq.c -o particle_filter.o $(HCLIB_CXXFLAGS)
	$(CC) -O3 particle_filter.o -o particle_filter -lm  $(HCLIB_LDFLAGS) $(HCLIB_LDLIBS)

clean:
	rm -f particle_filter *.o


text:
/*global describe, it*/
"use strict";

var fs = require("fs"),
	es = require("event-stream"),
	gulp = require('gulp'),
	should = require("should");

require("mocha");

delete require.cache[require.resolve("../")];

var gutil = require("gulp-util"),
	imageSilhouette = require("../");

describe("gulp-image-silhouette", function () {

	var expectedFile = new gutil.File({
		path: "test/expected/octcat.png",
		cwd: "test/",
		base: "test/expected",
		contents: fs.readFileSync("test/expected/octcat.png")
	});

	it("should produce expected file via buffer", function (done) {

		var srcFile = new gutil.File({
			path: "test/fixtures/octcat.png",
			cwd: "test/",
			base: "test/fixtures",
			contents: fs.readFileSync("test/fixtures/octcat.png")
		});

		var stream = imageSilhouette({
			color: 'white'
		});

		stream.on("error", function(err) {
			should.exist(err);
			done(err);
		});

		stream.on("data", function (newFile) {
			should.exist(newFile);
			should.exist(newFile.contents);
			done();
		});

		stream.write(srcFile);
		stream.end();
	});

	it("should error on stream", function (done) {

		var srcFile = new gutil.File({
			path: "test/fixtures/octcat.png",
			cwd: "test/",
			base: "test/fixtures",
			contents: fs.createReadStream("test/fixtures/octcat.png")
		});

		var stream = imageSilhouette();

		stream.on("error", function(err) {
			should.exist(err);
			done();
		});

		stream.on("data", function (newFile) {
			newFile.contents.pipe(es.wait(function(err, data) {
				done(err);
			}));
		});

		stream.write(srcFile);
		stream.end();
	});

});


text:
package org.apache.commons.ssl.rmi;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Date;

/**
 * @author Credit Union Central of British Columbia
 * @author www.cucbc.com
 * @author juliusdavies@cucbc.com
 * @since 22-Feb-2007
 */
public interface RemoteDate extends Remote {
    public Date getDate() throws RemoteException;
}


text:
package ar.edu.itba.pedestriansim.back.entity.mision;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.newdawn.slick.geom.Line;
import org.newdawn.slick.geom.Shape;
import org.newdawn.slick.geom.Vector2f;

import ar.edu.itba.pedestriansim.back.entity.PedestrianArea;

public class PedestrianTargetArea implements PedestrianTarget {

	private Line _targetArea;
	private Vector2f _result = new Vector2f();
	private int _id;

	public PedestrianTargetArea(Line targetArea) {
		_targetArea = targetArea;
	}

	public PedestrianTargetArea setId(int id) {
		_id = id;
		return this;
	}

	public int id() {
		return _id;
	}

	@Override
	public boolean intersects(Shape shape) {
		return _targetArea.intersects(shape);
	}

	@Override
	public Vector2f getClosesPoint(Vector2f point) {
		_targetArea.getClosestPoint(point, _result);
		return _result;
	}

	@Override
	public String toString() {
		return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
	}
}


text:
package org.elassandra.shard.aggregations.bucket.token;

import org.elassandra.shard.aggregations.bucket.token.AbstractRangeBuilder;

/**
 * Builder for the {@link DateRange} aggregation.
 */
public class TokenRangeBuilder extends AbstractRangeBuilder<TokenRangeBuilder> {
    /**
     * Sole constructor.
     */
    public TokenRangeBuilder(String name) {
        super(name, InternalTokenRange.TYPE.name());
    }

    /**
     * Add a new range to this aggregation.
     *
     * @param key  the key to use for this range in the response
     * @param from the lower bound on the distances, inclusive
     * @parap to   the upper bound on the distances, exclusive
     */
    public TokenRangeBuilder addRange(String key, Object from, Object to) {
        ranges.add(new Range(key, from, to));
        return this;
    }

    /**
     * Same as {@link #addRange(String, double, double)} but the key will be
     * automatically generated based on from and to.
     */
    public TokenRangeBuilder addRange(Object from, Object to) {
        return addRange(null, from, to);
    }

}


text:
import React from 'react'

import {
  mockModification,
  mockStores,
  mockWithProvider
} from '../../utils/mock-data'
import ModificationEditor from '../modification-editor'

// Parameters that the Editor would get from the Router
const params = {
  modificationId: mockModification._id,
  projectId: mockModification.projectId
}

const {describe, expect, it} = global
describe('Container > Modification Editor', () => {
  it('renders correctly', () => {
    const {snapshot} = mockWithProvider(<ModificationEditor params={params} />)
    expect(snapshot()).toMatchSnapshot()
  })

  it('renders and can change the name', () => {
    // mount component
    const {
      store,
      wrapper
    } = mockWithProvider(<ModificationEditor params={params} />)

    wrapper
      .find('a[name="Edit modification name"]')
      .simulate('click')

    wrapper
      .find('input[name="Modification Name"]')
      .simulate('change', {currentTarget: {value: 'New Modification Name'}})

    expect(store.getActions()).toMatchSnapshot()
  })

  it('render just the title if not loaded', () => {
    const init = {...mockStores.init}
    init.project = {feeds: [], feedsById: {}, ...init.project}
    const {snapshot} = mockWithProvider(<ModificationEditor params={params} />, init)
    expect(snapshot()).toMatchSnapshot()
  })
})


text:
{% load staticfiles %}
<link rel="stylesheet" href="{% static "facebox/css/facebox.css" %}" type="text/css" media="screen"/>


text:
<?php

namespace KoolKode\Meta\Annotation;

/**
 * @author Martin Schröder
 */
class IncompleteAnnotationException extends AnnotationException { }


text:
from google.appengine.ext import db

from kay.utils import forms, get_request, validators

from kutils import slugify

from przepisy import *
from przepisy import models

class RecipeForm(forms.Form):
  title = forms.TextField(required=True, label=u'Nazwa', max_length=60, min_length=4,
                          help_text=u'Nazwa przepisu powinna być możliwie jednoznaczna.')
  ingr = forms.Multiple(forms.Mapping(
      product=forms.TextField(required=True, label=u'Produkt', max_length=50, min_length=3),
      portion=forms.FloatField(required=True, label=u'Porcja', min_value=0.0, max_value=10000.0),
      weight=forms.ChoiceField(required=True, choices=PORTION_WEIGHTS, label=u'')
    ),
    required=False, label=u'Składniki', min_size=1, max_size=21,
    help_text=u'Wprowadź nazwy i ilość wymaganych składników. Opcjonalne składniki podaj w sposobie przyrządzenia. W miarę możliwości podawaj wartość w gramach!'
  )
  recipe = forms.TextField(required=True, label=u'Sposób przyrządzenia', min_length=10, max_length=2000,
                          help_text=u'Opisz, najlepiej w punktach, sposób przyrządzenia dania.',
                          widget=forms.Textarea)

  tags = forms.TextField(label=u'Etykiety', max_length=50, required=False,
                          help_text=u'Dodaj etykiety (np. dla dzieci, przyjęcia) ułatwiające odnalezienie przepisu w przyszłości. Staraj się nie stosować określeń dotyczących jego nazwy, składników, kategorii, fazy itp. ')
  category = forms.ChoiceField(required=True, choices=CATEGORIES, label=u'Kategoria')
  phase = forms.ChoiceField(required=True, choices=PHASES, label=u'Faza', widget=forms.RadioButtonGroup)
  type = forms.ChoiceField(required=True, choices=TYPES, label=u'Typ', widget=forms.RadioButtonGroup)
  time = forms.ChoiceField(required=True, choices=TIMES, label=u'Czas przygotowania')
  ig = forms.IntegerField(min_value=0, max_value=200, label=u'Przewidywany IG',
                          help_text=u'Jeśli nie potrafisz określić prawdopodobnego IG gotowego dania, pozostaw pole pustym.')
  rec_vis = forms.ChoiceField(default=True, label=u'Widoczny dla',
                              widget=forms.RadioButtonGroup, choices=VISIBILITY,
                              help_text=u'Określ widoczność przepisu dla innych. Tylko publiczne przepisy można wyszukiwać poleceniem szukaj!')

  def __init__(self, initial=None, edit=False):
    self.edit = edit
    super(RecipeForm, self).__init__(initial)

  def validate_title(self, value):
    if self.edit:
      return

    slug = slugify(value)
    obj = db.get(db.Key.from_path('Recipe', slug, parent=get_request().user.key()))

    if obj:
      raise validators.ValidationError(u"Masz już przepis o zbliżonej nazwie. Użyj innej.")

  def validate_tags(self, value):
    splited = models.Tag.split_elements(value)
    for s in splited:
      if len(s) < 3:
        raise validators.ValidationError(u"Wszystkie etykiety muszą mieć przynajmniej trzy znaki.")

    if len(splited) != len(set(splited)):
      raise validators.ValidationError(u"Etykiety nie mogą się powtarzać.")


text:
package org.jetbrains.plugins.scala.lang.parser.parsing.statements

import org.jetbrains.plugins.scala.ScalaBundle
import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes
import org.jetbrains.plugins.scala.lang.parser.parsing.builder.ScalaPsiBuilder
import org.jetbrains.plugins.scala.lang.parser.parsing.params.TypeParamClause
import org.jetbrains.plugins.scala.lang.parser.parsing.types.Type

/**
* @author Alexander Podkhalyuzin
* Date: 11.02.2008
*/

/*
 * TypeDcl ::= id [TypeParamClause] ['>:' Type] ['<:' Type]
 */
object TypeDcl extends TypeDcl {
  override protected def `type` = Type
  override protected def typeParamClause = TypeParamClause
}

trait TypeDcl {
  protected def `type`: Type
  protected def typeParamClause: TypeParamClause

  def parse(builder: ScalaPsiBuilder): Boolean = {
    val returnMarker = builder.mark
    builder.getTokenType match {
      case ScalaTokenTypes.kTYPE =>
        builder.advanceLexer() //Ate type
      case _ =>
        returnMarker.drop()
        return false
    }
    builder.getTokenType match {
      case ScalaTokenTypes.tIDENTIFIER =>
        builder.advanceLexer() //Ate identifier
      case _ =>
        builder error ScalaBundle.message("identifier.expected")
        returnMarker.drop()
        return false
    }
    typeParamClause parse builder
    builder.getTokenText match {
      case ">:" =>
        builder.advanceLexer()
        if (!`type`.parse(builder)) {
          builder error ScalaBundle.message("wrong.type")
        }
      case _ => //nothing
    }
    builder.getTokenText match {
      case "<:" =>
        builder.advanceLexer()
        if (!`type`.parse(builder)) {
          builder error ScalaBundle.message("wrong.type")
        }
      case _ => //nothing
    }
    returnMarker.drop()
    builder.getTokenType match {
      case ScalaTokenTypes.tASSIGN =>
        builder.advanceLexer()
        builder error ScalaBundle.message("wrong.type")
        true
      case _ => true
    }
  }
}


text:
typedef layer route_layer;

route_layer make_route_layer(int batch, int n, int *input_layers, int *input_size);
void forward_route_layer(const route_layer l, network_state state);
void backward_route_layer(const route_layer l, network_state state);
void resize_route_layer(route_layer *l, network *net);

#ifdef GPU
void forward_route_layer_gpu(const route_layer l, network_state state);
void backward_route_layer_gpu(const route_layer l, network_state state);
#endif

#endif


text:
package com.huaqin.punan.shakedemo;

import java.util.Date;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class ShakeActivity extends Activity implements SensorEventListener{

    private static final String TAG = "ShakeActivity";
    private float mTempX, mTempY, mTempZ, x, y, z;
    private long mtime = new Date().getTime();
    private int flagGravityOver = 0;
    private int flagGravityLow = 0;
    private float mtemrGravity = 0;
    private float MtemrGravity = 100000;
    float mX[] = {-5,5};
    long timeX[] = {0,0};
    SensorManager mSensorManager;
    TextView mtv;
    private int i = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shake_activity);

        mtv = (TextView)findViewById(R.id.mytv);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    }

    @Override
    protected void onResume() {
        mSensorManager.registerListener(this,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_GAME);
        super.onResume();
    }

    @Override
    protected void onStop() {
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.shake, menu);
        return true;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        float[] values = event.values;
        x = values[0];
        y = values[1];
        z = values[2];

        float rGravity = x*x + y*y + z*z;

        if(x > mX[0]){
            mX[0] = x;
            timeX[0] = new Date().getTime();
        }

        if(x < mX[1]){
            mX[1] = x;
            timeX[1] = new Date().getTime();
        }

        if(new Date().getTime() -mtime >700){
            flagGravityOver = 0;
            flagGravityOver = 0;
            mtime = new Date().getTime();
        }

        if(flagGravityLow != 0 & (int)rGravity > 700){
            flagGravityOver++;
            mtime = new Date().getTime();
        }

        if((int)rGravity < 70){
            flagGravityLow++;
            mtime = new Date().getTime();
        }

        if(flagGravityLow > 0 & flagGravityOver > 0){
            i++;
            mtv.setText("Shake Times = " + i);

            flagGravityOver = 0;
            flagGravityOver = 0;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}


text:
layout: default
title: Home
---

{% include intro.html %}

 © The Time Now

    {% for post in site.posts %}
      {% unless post.next %}

{{ post.date | date: '%Y' }}

      {% else %}
        {% capture year %}{{ post.date | date: '%Y' }}{% endcapture %}
        {% capture nyear %}{{ post.next.date | date: '%Y' }}{% endcapture %}
        {% if year != nyear %}

{{ post.date | date: '%Y' }}

        {% endif %}
      {% endunless %}

        {{ post.date | date: "%b %d" }}

{{ post.title }}

    {% endfor %}


text:
package org.killbill.billing.beatrix.integration.overdue;

import javax.inject.Named;

import org.killbill.billing.lifecycle.api.BusService;
import org.killbill.billing.overdue.OverdueProperties;
import org.killbill.billing.overdue.OverdueUserApi;
import org.killbill.billing.overdue.glue.DefaultOverdueModule;
import org.killbill.billing.overdue.listener.OverdueListener;
import org.killbill.billing.overdue.notification.OverdueNotifier;
import org.killbill.billing.overdue.service.DefaultOverdueService;
import org.killbill.billing.overdue.wrapper.OverdueWrapperFactory;

import com.google.inject.Inject;

public class MockOverdueService extends DefaultOverdueService {

    @Inject
    public MockOverdueService(final OverdueUserApi userApi, final OverdueProperties properties,
                              @Named(DefaultOverdueModule.OVERDUE_NOTIFIER_CHECK_NAMED) final OverdueNotifier checkNotifier,
                              @Named(DefaultOverdueModule.OVERDUE_NOTIFIER_ASYNC_BUS_NAMED) final OverdueNotifier asyncNotifier,
                              final BusService busService, final OverdueListener listener, final OverdueWrapperFactory factory) {
        super(userApi, properties, checkNotifier, asyncNotifier, busService, listener, factory);
    }

    public synchronized void loadConfig() throws ServiceException {
    }
}


text:
<?php

namespace Apps\Model\Admin\Main;

use Apps\Model\Front\Search\AbstractSearchResult;
use Ffcms\Templex\Url\Url;

/**
 * Class AbstractSearchItem. Search item element instance
 * @package Apps\Model\Admin\Main
 */
class AbstractSearchItem extends AbstractSearchResult
{
    protected $marker = 'Unknown';
    protected $url;

    /**
     * Set item instance type
     * @param string $marker
     */
    public function setMarker(string $marker): void
    {
        $this->marker = $marker;
    }

    /**
     * Get item instance type
     * @return string
     */
    public function getMarker(): string
    {
        return $this->marker;
    }

    /**
     * Build url
     * @param string $controllerAction
     * @param array|null $arguments
     * @param array|null $query
     */
    public function setUrl(string $controllerAction, ?array $arguments = null, ?array $query = null)
    {
        $this->url = Url::to($controllerAction, $arguments, $query);
    }

    /**
     * Get url result
     * @return string|null
     */
    public function getUrl(): ?string
    {
        return $this->url;
    }
}


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/centaur/procedures/hwp/memory/p9c_mss_scominit.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/// @file p9c_mss_scominit.C
/// @brief Calls the various memory initfiles
///
/// *HWP HWP Owner: Luke Mulkey <lwmulkey@us.ibm.com>
/// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
/// *HWP Team: Memory
/// *HWP Level: 2
/// *HWP Consumed by: HB

//----------------------------------------------------------------------
//  My Includes
//----------------------------------------------------------------------
#include <p9c_mss_scominit.H>
#include <centaur_mba_scom.H>
#include <centaur_mbs_scom.H>
#include <centaur_ddrphy_scom.H>
#include <fapi2.H>
#include <dimmConsts.H>
#include <generic/memory/lib/utils/c_str.H>

extern "C" {
    /// @brief p9c_mss_scominit procedure: Calls the various memory initfiles
    /// @param[in] i_target [Reference to target, expecting centaur(MEMBUF) target]
    /// @return ReturnCode
    fapi2::ReturnCode p9c_mss_scominit(const fapi2::Target<fapi2::TARGET_TYPE_MEMBUF_CHIP>& i_target)
    {
        fapi2::buffer<uint64_t> l_scom_buffer;
        fapi2::ReturnCode l_rc;
        fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
        uint8_t l_unitPos = 0;
        FAPI_DBG("Performing HWP: mss_scominit");

        // Get a vector of the functional MBA targets
        const auto l_mba_targets = i_target.getChildren<fapi2::TARGET_TYPE_MBA>();
        const auto l_l4_targets = i_target.getChildren<fapi2::TARGET_TYPE_L4>(fapi2::TARGET_STATE_PRESENT);

        FAPI_ASSERT(l_l4_targets.size() > 0,
                    fapi2::CEN_MSS_SCOMINIT_NUM_L4_ERROR().
                    set_MEMBUF(i_target).
                    set_NUM_L4S(l_l4_targets.size()),
                    "No present L4 found on centaur %s", mss::c_str(i_target));

        //################ DDRPHY ######################
        for (const auto& mba : l_mba_targets)
        {
            // Find the position of the MBA chiplet
            FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, mba, l_unitPos));
            FAPI_DBG("MBA%i valid\n", l_unitPos);

            FAPI_EXEC_HWP(l_rc, centaur_ddrphy_scom, mba , FAPI_SYSTEM, i_target);

            if (l_rc)
            {
                FAPI_ERR("  !!!  Error running ddrphy scom initfile on %s, RC = 0x%x\n",
                         mss::c_str(mba), static_cast<uint32_t>(l_rc));
                return (l_rc);
            }
            else
            {
                FAPI_DBG("%s ddrphy scom initfile passed\n", mss::c_str(mba));
            }

        }

        //################ MBS ######################
        for (const auto& mba : l_mba_targets)
        {
            FAPI_DBG("Running MBS scom initfile\n");
            FAPI_EXEC_HWP(l_rc, centaur_mbs_scom, i_target, mba, l_l4_targets[0], FAPI_SYSTEM);

            if (l_rc)
            {
                FAPI_ERR("  !!!  Error running MBS scom initfile on %s\n", mss::c_str(i_target));
                return (l_rc);
            }
            else
            {
                FAPI_DBG("MBS scom initfile passed on %s\n", mss::c_str(i_target));
            }
        }

        //################ MBA ######################
        // Iterate through the returned chiplets
        for (const auto& mba : l_mba_targets)
        {
            // Find the position of the MBA chiplet
            FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, mba, l_unitPos));
            FAPI_DBG("MBA%i valid\n", l_unitPos);

            FAPI_EXEC_HWP(l_rc, centaur_mba_scom, mba, i_target, FAPI_SYSTEM);

            if (l_rc)
            {
                FAPI_ERR("  !!!  Error running MBA %s, RC = 0x%x\n",
                         mss::c_str(mba), static_cast<uint32_t>(l_rc));
                return (l_rc);
            }
            else
            {
                FAPI_DBG("%s MBA scom initfile passed\n", mss::c_str(mba));
            }
        }

    fapi_try_exit:
        return fapi2::current_err;
    } // end mss_scominit
} // extern "C"


text:
<?php

namespace Mage\Wishlist\Test\Constraint;

use Mage\Cms\Test\Page\CmsIndex;
use Mage\Wishlist\Test\Page\WishlistIndex;
use Magento\Mtf\Constraint\AbstractConstraint;
use Magento\Mtf\Fixture\InjectableFixture;

/**
 * Assert that product is present in default wishlist.
 */
class AssertProductIsPresentInWishlist extends AbstractConstraint
{
    /* tags */
    const SEVERITY = 'low';
    /* end tags */

    /**
     * Assert that product is present in default wishlist.
     *
     * @param CmsIndex $cmsIndex
     * @param WishlistIndex $wishlistIndex
     * @param InjectableFixture $product
     * @return void
     */
    public function processAssert(CmsIndex $cmsIndex, WishlistIndex $wishlistIndex, InjectableFixture $product)
    {
        $cmsIndex->getTopLinksBlock()->openAccount();
        $cmsIndex->getLinksBlock()->openLink("My Wishlist");

        \PHPUnit_Framework_Assert::assertTrue(
            $wishlistIndex->getItemsBlock()->getItemProductBlock($product)->isVisible(),
            $product->getName() . ' is not visible on wishlist page.'
        );
    }

    /**
     * Returns a string representation of the object.
     *
     * @return string
     */
    public function toString()
    {
        return 'Product is present in default wishlist.';
    }
}


text:
import DS from 'ember-data';
import BackboneElement from 'ember-fhir/models/backbone-element';

const { attr, belongsTo } = DS;

export default BackboneElement.extend({
  code: belongsTo('codeable-concept', { async: false }),
  value: attr('date')
});


text:
type: quote
title: "NG nominerad"
date: 2013-10-17 00:00:00 UTC
author: samuel
meta_title: ""
description: ""
quote: "Den här tidningen är med när det händer, där det händer. De följer pulsen i nyhets- och nöjesvärlden med en egen idé. Sajten utvecklas hela tiden med både tekniska framsteg och en extremt tydlig redaktionell röst."
cite: 'Juryns motivering av Nöjesguiden.se:s nominering till Årets Tidskrift Digitala Medier'
lang: sv
---

Vi är oerhört glada över att ha chansen att försvara segern från i fjol!

Glädjande är även att Nöjesguiden dessutom finns nominerade i kategorin Årets Innovativa Satsning för c/o Nöjesguiden.


text:
import os

_ = gettext = lambda s: s
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__)) + '/../'

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Warsaw'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'pl'

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '50qwz*@_w**hcydw&o&tlbw%041gs_ftw!qo%dog%)_0py#w9&'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.doc.XViewMiddleware',
)

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
)

ROOT_URLCONF = '{{ project_name }}.urls'
WSGI_APPLICATION = '{{ project_name }}.wsgi.application'

TEMPLATE_DIRS = (
    os.path.join(PROJECT_PATH) + '/templates/',
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'south',
    '{{ project_name }}.apps.common',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.i18n',
    'django.core.context_processors.request',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
)

LANGUAGES = [
    ('pl', 'Polski'),
]

SITE_ID = 1

LOGIN_REDIRECT_URL = '/'


text:
import * as React from "react";
import { CleaveOptions } from "../options";

type InitHandler = (owner: React.ReactInstance) => void;

interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
    onInit?: InitHandler;
    options: CleaveOptions;
}

declare var Cleave: React.ComponentClass<Props>;
export = Cleave;


text:
'use strict';

module.exports = {
  client: {
    lib: {
      css: [
        'public/lib/bootstrap/dist/css/bootstrap.css',
        //'public/lib/bootstrap/dist/css/bootstrap-theme.css',
        'public/lib/flat-ui/dist/css/flat-ui.css',
        'public/lib/angularPrint/angularPrint.css'
        //'public/lib/FlipClock/compiled/flipclock.css'
      ],
      js: [
        'public/lib/angular/angular.js',
        'public/lib/angular-resource/angular-resource.js',
        'public/lib/angular-animate/angular-animate.js',
        'public/lib/angular-messages/angular-messages.js',
        'public/lib/angular-ui-router/release/angular-ui-router.js',
        'public/lib/angular-ui-utils/ui-utils.js',
        'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
        'public/lib/angular-file-upload/angular-file-upload.js',
        'public/lib/owasp-password-strength-test/owasp-password-strength-test.js',
        'public/lib/moment/moment.js',
        'public/lib/angular-moment/angular-moment.js',
        'public/lib/jquery/dist/jquery.js',
        'public/lib/angularPrint/angularPrint.js',
        'public/lib/checklist-model/checklist-model.js'
        //'public/lib/FlipClock/compiled/flipclock.js',
        //'public/lib/angular-flipclock/angular-flipclock.js'
      ],
      tests: ['public/lib/angular-mocks/angular-mocks.js']
    },
    css: [
      'modules/*/client/css/*.css'
    ],
    less: [
      'modules/*/client/less/*.less'
    ],
    sass: [
      'modules/*/client/scss/*.scss'
    ],
    js: [
      'modules/core/client/app/config.js',
      'modules/core/client/app/init.js',
      'modules/*/client/*.js',
      'modules/*/client/**/*.js'
    ],
    img: [
      'modules/**/*/img/**/*.jpg',
      'modules/**/*/img/**/*.png',
      'modules/**/*/img/**/*.gif',
      'modules/**/*/img/**/*.svg'
    ],
    views: ['modules/*/client/views/**/*.html'],
    templates: ['build/templates.js']
  },
  server: {
    gruntConfig: ['gruntfile.js'],
    gulpConfig: ['gulpfile.js'],
    allJS: ['server.js', 'config/**/*.js', 'modules/*/server/**/*.js'],
    models: 'modules/*/server/models/**/*.js',
    routes: ['modules/!(core)/server/routes/**/*.js', 'modules/core/server/routes/**/*.js'],
    sockets: 'modules/*/server/sockets/**/*.js',
    config: ['modules/*/server/config/*.js'],
    policies: 'modules/*/server/policies/*.js',
    views: ['modules/*/server/views/*.html']
  }
};


text:
<?php

require_once 'modules/com_vtiger_workflow/VTEventHandler.inc';
require_once 'modules/Emails/mail.php';
require_once 'modules/HelpDesk/HelpDesk.php';

class ModCommentsHandler extends VTEventHandler {

	function handleEvent($eventName, $data) {

		if($eventName == 'vtiger.entity.beforesave') {
			// Entity is about to be saved, take required action
		}

		if($eventName == 'vtiger.entity.aftersave') {
			$db = PearDatabase::getInstance();

			$relatedToId = $data->get('related_to');
			if ($relatedToId) {
				$moduleName = getSalesEntityType($relatedToId);
				$focus = CRMEntity::getInstance($moduleName);
				$focus->retrieve_entity_info($relatedToId, $moduleName);
				$focus->id = $relatedToId;
				$fromPortal = $data->get('from_portal');
				if ($fromPortal) {
					$focus->column_fields['from_portal'] = $fromPortal;
				}
				$entityData = VTEntityData::fromCRMEntity($focus);

				$wfs = new VTWorkflowManager($db);
				$relatedToEventHandler = new VTWorkflowEventHandler();
				$relatedToEventHandler->workflows = $wfs->getWorkflowsForModuleSupportingComments($entityData->getModuleName());

				$wsId = vtws_getWebserviceEntityId($entityData->getModuleName(), $entityData->getId());
				$fromPortal = $entityData->get('from_portal');

				$util = new VTWorkflowUtils();
				$entityCache = new VTEntityCache($util->adminUser());

				$entityCacheData = $entityCache->forId($wsId);
				$entityCacheData->set('from_portal', $fromPortal);
				$entityCache->cache[$wsId] = $entityCacheData;

				$relatedToEventHandler->handleEvent($eventName, $entityData, $entityCache);
				$util->revertUser();
			}
		}
	}
}

function CustomerCommentFromPortal($entityData) {
	$adb = PearDatabase::getInstance();

	$data = $entityData->getData();
	$customerWSId = $data['customer'];

	$relatedToWSId = $data['related_to'];
	$relatedToId = explode('x', $relatedToWSId);
	$moduleName = getSalesEntityType($relatedToId[1]);

	if($moduleName == 'HelpDesk' && !empty($customerWSId)) {
		$ownerIdInfo = getRecordOwnerId($relatedToId[1]);
		if(!empty($ownerIdInfo['Users'])) {
			$ownerId = $ownerIdInfo['Users'];
			$ownerName = getOwnerName($ownerId);
			$toEmail = getUserEmailId('id',$ownerId);
		}
		if(!empty($ownerIdInfo['Groups'])) {
			$ownerId = $ownerIdInfo['Groups'];
			$groupInfo = getGroupName($ownerId);
			$ownerName = $groupInfo[0];
			$toEmail = implode(',', getDefaultAssigneeEmailIds($ownerId));
		}
		$subject = getTranslatedString('LBL_RESPONDTO_TICKETID', $moduleName)."##". $relatedToId[1]."## ". getTranslatedString('LBL_CUSTOMER_PORTAL', $moduleName);
		$contents = getTranslatedString('Dear', $moduleName)." ".$ownerName.","."

"
					.getTranslatedString('LBL_CUSTOMER_COMMENTS', $moduleName)."

					".$data['commentcontent']."

"
					.getTranslatedString('LBL_RESPOND', $moduleName)."

"
					.getTranslatedString('LBL_REGARDS', $moduleName)."
"
					.getTranslatedString('LBL_SUPPORT_ADMIN', $moduleName);

		$customerId = explode('x', $customerWSId);

		$result = $adb->pquery("SELECT email FROM vtiger_contactdetails WHERE contactid=?", array($customerId[0]));
		$fromEmail = $adb->query_result($result,0,'email');

		send_mail('HelpDesk', $toEmail,'', $fromEmail, $subject, $contents);
	}
}

function TicketOwnerComments($entityData) {
	global $HELPDESK_SUPPORT_NAME, $HELPDESK_SUPPORT_EMAIL_ID;
	$adb = PearDatabase::getInstance();

	//if commented from portal by the customer, then ignore this
	$customer = $entityData->get('customer');
	if(!empty($customer)) return;

	$wsParentId = $entityData->get('related_to');
	$parentIdParts = explode('x', $wsParentId);
	$parentId = $parentIdParts[1];
	$moduleName = getSalesEntityType($parentId);

	$isNew = $entityData->isNew();

	if($moduleName == 'HelpDesk') {
		$ticketFocus = CRMEntity::getInstance($moduleName);
		$ticketFocus->retrieve_entity_info($parentId, $moduleName);
		$ticketFocus->id = $parentId;

		if(!$isNew) {
			$reply = 'Re : ';
		} else {
			$reply = '';
		}

		$subject = $ticketFocus->column_fields['ticket_no'] . ' [ '.getTranslatedString('LBL_TICKET_ID', $moduleName)
							.' : '.$parentId.' ] '.$reply.$ticketFocus->column_fields['ticket_title'];

		$emailOptOut = 0;
		$contactId = $ticketFocus->column_fields['contact_id'];
		$accountId = $ticketFocus->column_fields['parent_id'];
		//To get the emailoptout vtiger_field value and then decide whether send mail about the tickets or not
		if(!empty($contactId)) {
			$result = $adb->pquery('SELECT email, emailoptout FROM vtiger_contactdetails WHERE contactid=?',
										array($contactId));
			$emailOptOut = $adb->query_result($result,0,'emailoptout');
			$parentEmail = $contactMailId = $adb->query_result($result,0,'email');
			$displayValueArray = getEntityName('Contacts', $contactId);
			if (!empty($displayValueArray)) {
				foreach ($displayValueArray as $key => $value) {
					$contactName = $value;
				}
			}
			$parentName = $contactName;

			//Get the status of the vtiger_portal user. if the customer is active then send the vtiger_portal link in the mail
			if($parentEmail != '') {
				$sql = "SELECT * FROM vtiger_portalinfo WHERE user_name=?";
				$isPortalUser = $adb->query_result($adb->pquery($sql, array($parentEmail)),0,'isactive');
			}
		} else if(!empty($accountId)) {
			$result = $adb->pquery("SELECT accountname, emailoptout, email1 FROM vtiger_account WHERE accountid=?",
										array($accountId));
			$emailOptOut = $adb->query_result($result,0,'emailoptout');
			$parentEmail = $adb->query_result($result,0,'email1');
			$parentName = $adb->query_result($result,0,'accountname');

		}
		//added condition to check the emailoptout
		if($emailOptOut == 0) {
			$entityData = VTEntityData::fromCRMEntity($ticketFocus);

			if($isPortalUser == 1){
				$bodysubject = getTranslatedString('Ticket No', $moduleName) .": " . $ticketFocus->column_fields['ticket_no']
					. "
" . getTranslatedString('LBL_TICKET_ID', $moduleName).' : '.$parentId.'
 '
					.getTranslatedString('LBL_SUBJECT', $moduleName).$ticketFocus->column_fields['ticket_title'];

				$emailBody = $bodysubject.'

'.HelpDesk::getPortalTicketEmailContents($entityData);
			} else {
				$emailBody = HelpDesk::getTicketEmailContents($entityData);
			}

			send_mail('HelpDesk', $parentEmail, $HELPDESK_SUPPORT_NAME, $HELPDESK_SUPPORT_EMAIL_ID, $subject, $emailBody);
		}
	}
}