text:
<?php

namespace Ecotronik\Bundle\EcopointBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class productosType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('codigo')
            ->add('nombre')
            ->add('marca')
            ->add('material')
            ->add('capacidad')
            ->add('foto')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Ecotronik\Bundle\EcopointBundle\Entity\productos'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'ecotronik_bundle_ecopointbundle_productos';
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Package webhook implements the authenticator.Token interface using HTTP webhooks.
package webhook

import (
	"context"
	"errors"
	"time"

	authentication "k8s.io/api/authentication/v1beta1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apiserver/pkg/authentication/authenticator"
	"k8s.io/apiserver/pkg/authentication/user"
	"k8s.io/apiserver/pkg/util/webhook"
	"k8s.io/client-go/kubernetes/scheme"
	authenticationclient "k8s.io/client-go/kubernetes/typed/authentication/v1beta1"
	"k8s.io/klog"
)

var (
	groupVersions = []schema.GroupVersion{authentication.SchemeGroupVersion}
)

const retryBackoff = 500 * time.Millisecond

// Ensure WebhookTokenAuthenticator implements the authenticator.Token interface.
var _ authenticator.Token = (*WebhookTokenAuthenticator)(nil)

type WebhookTokenAuthenticator struct {
	tokenReview    authenticationclient.TokenReviewInterface
	initialBackoff time.Duration
	implicitAuds   authenticator.Audiences
}

// NewFromInterface creates a webhook authenticator using the given tokenReview
// client. It is recommend to wrap this authenticator with the token cache
// authenticator implemented in
// k8s.io/apiserver/pkg/authentication/token/cache.
func NewFromInterface(tokenReview authenticationclient.TokenReviewInterface, implicitAuds authenticator.Audiences) (*WebhookTokenAuthenticator, error) {
	return newWithBackoff(tokenReview, retryBackoff, implicitAuds)
}

// New creates a new WebhookTokenAuthenticator from the provided kubeconfig
// file. It is recommend to wrap this authenticator with the token cache
// authenticator implemented in
// k8s.io/apiserver/pkg/authentication/token/cache.
func New(kubeConfigFile string, implicitAuds authenticator.Audiences) (*WebhookTokenAuthenticator, error) {
	tokenReview, err := tokenReviewInterfaceFromKubeconfig(kubeConfigFile)
	if err != nil {
		return nil, err
	}
	return newWithBackoff(tokenReview, retryBackoff, implicitAuds)
}

// newWithBackoff allows tests to skip the sleep.
func newWithBackoff(tokenReview authenticationclient.TokenReviewInterface, initialBackoff time.Duration, implicitAuds authenticator.Audiences) (*WebhookTokenAuthenticator, error) {
	return &WebhookTokenAuthenticator{tokenReview, initialBackoff, implicitAuds}, nil
}

// AuthenticateToken implements the authenticator.Token interface.
func (w *WebhookTokenAuthenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error) {
	// We take implicit audiences of the API server at WebhookTokenAuthenticator
	// construction time. The outline of how we validate audience here is:
	//
	// * if the ctx is not audience limited, don't do any audience validation.
	// * if ctx is audience-limited, add the audiences to the tokenreview spec
	//   * if the tokenreview returns with audiences in the status that intersect
	//     with the audiences in the ctx, copy into the response and return success
	//   * if the tokenreview returns without an audience in the status, ensure
	//     the ctx audiences intersect with the implicit audiences, and set the
	//     intersection in the response.
	//   * otherwise return unauthenticated.
	wantAuds, checkAuds := authenticator.AudiencesFrom(ctx)
	r := &authentication.TokenReview{
		Spec: authentication.TokenReviewSpec{
			Token:     token,
			Audiences: wantAuds,
		},
	}
	var (
		result *authentication.TokenReview
		err    error
		auds   authenticator.Audiences
	)
	webhook.WithExponentialBackoff(ctx, w.initialBackoff, func() error {
		result, err = w.tokenReview.CreateContext(ctx, r)
		return err
	})
	if err != nil {
		// An error here indicates bad configuration or an outage. Log for debugging.
		klog.Errorf("Failed to make webhook authenticator request: %v", err)
		return nil, false, err
	}

	if checkAuds {
		gotAuds := w.implicitAuds
		if len(result.Status.Audiences) > 0 {
			gotAuds = result.Status.Audiences
		}
		auds = wantAuds.Intersect(gotAuds)
		if len(auds) == 0 {
			return nil, false, nil
		}
	}

	r.Status = result.Status
	if !r.Status.Authenticated {
		var err error
		if len(r.Status.Error) != 0 {
			err = errors.New(r.Status.Error)
		}
		return nil, false, err
	}

	var extra map[string][]string
	if r.Status.User.Extra != nil {
		extra = map[string][]string{}
		for k, v := range r.Status.User.Extra {
			extra[k] = v
		}
	}

	return &authenticator.Response{
		User: &user.DefaultInfo{
			Name:   r.Status.User.Username,
			UID:    r.Status.User.UID,
			Groups: r.Status.User.Groups,
			Extra:  extra,
		},
		Audiences: auds,
	}, true, nil
}

// tokenReviewInterfaceFromKubeconfig builds a client from the specified kubeconfig file,
// and returns a TokenReviewInterface that uses that client. Note that the client submits TokenReview
// requests to the exact path specified in the kubeconfig file, so arbitrary non-API servers can be targeted.
func tokenReviewInterfaceFromKubeconfig(kubeConfigFile string) (authenticationclient.TokenReviewInterface, error) {
	localScheme := runtime.NewScheme()
	if err := scheme.AddToScheme(localScheme); err != nil {
		return nil, err
	}
	if err := localScheme.SetVersionPriority(groupVersions...); err != nil {
		return nil, err
	}

	gw, err := webhook.NewGenericWebhook(localScheme, scheme.Codecs, kubeConfigFile, groupVersions, 0)
	if err != nil {
		return nil, err
	}
	return &tokenReviewClient{gw}, nil
}

type tokenReviewClient struct {
	w *webhook.GenericWebhook
}

func (t *tokenReviewClient) Create(tokenReview *authentication.TokenReview) (*authentication.TokenReview, error) {
	return t.CreateContext(context.Background(), tokenReview)
}

func (t *tokenReviewClient) CreateContext(ctx context.Context, tokenReview *authentication.TokenReview) (*authentication.TokenReview, error) {
	result := &authentication.TokenReview{}
	err := t.w.RestClient.Post().Context(ctx).Body(tokenReview).Do().Into(result)
	return result, err
}


text:
var blessed = require('blessed'),
    Node = blessed.Node,
    contrib = require('blessed-contrib'),
    Canvas = contrib.canvas,
    utils = require('blessed-contrib/lib/utils.js');

function Line(options) {
  var self = this

  if (!(this instanceof Node)) {
    return new Line(options);
  }

  options.showNthLabel = options.showNthLabel || 1
  options.style = options.style || {}
  options.style.line = options.style.line || "yellow"
  options.style.text = options.style.text || "green"
  options.style.baseline = options.style.baseline || "black"
  options.xLabelPadding = options.xLabelPadding || 5
  options.xPadding = options.xPadding || 10
  options.numYLabels = options.numYlabels || 5
  options.legend = options.legend || {}
  options.wholeNumbersOnly = options.wholeNumbersOnly || false
  Canvas.call(this, options);
}

Line.prototype.calcSize = function() {
    this.canvasSize = {width: this.width*2-12, height: this.height*4-8}
}

Line.prototype.__proto__ = Canvas.prototype;

Line.prototype.type = 'line';

Line.prototype.setData = function(data) {

    if (!this.ctx) {
      throw "error: canvas context does not exist. setData() for line charts must be called after the chart has been added to the screen via screen.append()"
    }

    //compatability with older api
    if (!Array.isArray(data)) data = [data]

    var self = this
    var xLabelPadding = this.options.xLabelPadding
    var yLabelPadding = 3
    var xPadding = this.options.xPadding
    var yPadding = 7
    var c = this.ctx
    var labels = data[0].x

    function addLegend() {
      if (!self.options.showLegend) return
      if (self.legend) self.remove(self.legend)
      self.legend = blessed.text({
            left: 0,
            bottom: 0,
            padding: {left: 5},
            width: self.width-2,
            content: '',
            fg: "green",
            tags: true,
            screen: self.screen
          });

      var legendText = ""
      for (var i=0; i<data.length; i++) {
        var style = data[i].style || {}
        var color = style.line || self.options.style.line
        legendText += '{'+color+'-fg}'+ data[i].title+'{/'+color+'-fg} '
      }
      self.legend.setContent(legendText)
      self.append(self.legend)
    }

    function getMaxY() {

      var max = 0;

      for(var i = 0; i < data.length; i++) {
          for(var j = 0; j < data[i].y.length; j++) {
            if(data[i].y[j] > max) {
              max = data[i].y[j];
            }
        }
      }

      //max += 25 - max % 25;
      max*=1.2

      //max = Math.round(max);

      if (self.options.maxY) {
        return Math.max(max, self.options.maxY)
      }

      return max;
    }

    function formatYLabel(value, max, numLabels, wholeNumbersOnly) {
      var fixed = (max/numLabels<1 && value!=0 && !wholeNumbersOnly) ? 2 : 0
      return value.toFixed(fixed)
    }

    function getMaxXLabelPadding(numLabels, wholeNumbersOnly) {
      var max = getMaxY()

      return formatYLabel(max, max, numLabels, wholeNumbersOnly).length * 2;
    }

    if (getMaxXLabelPadding(this.options.numYLabels, this.options.wholeNumbersOnly) > xLabelPadding) {
      xLabelPadding = getMaxXLabelPadding(this.options.numYLabels);
    };

    if ((xPadding - xLabelPadding) < 0) {
      xPadding = xLabelPadding;
    }

    function getMaxX() {
      var maxLength = 0;

      for(var i = 0; i < labels.length; i++) {
        if(labels[i] === undefined) {
          console.log("label[" + i + "] is undefined");
        } else if(labels[i].length > maxLength) {
          maxLength = labels[i].length;
        }
      }

      return maxLength;
    }

    function getXPixel(val) {
        return ((self.canvasSize.width - xPadding) / labels.length) * val + (xPadding * 1.0) + 2;
    }

    function getYPixel(val) {
        var res = self.canvasSize.height - yPadding - (((self.canvasSize.height - yPadding) / getMaxY()) * val);
        res-=2 //to separate the baseline and the data line to separate chars so canvas will show separate colors
        return res
    }

    // Draw the line graph
    function drawLine(values, style) {
      style = style || {}
      var color = self.options.style.line
      c.strokeStyle = style.line || color

      c.moveTo(0, 0)
      c.beginPath();
      c.lineTo(getXPixel(0), getYPixel(values[0]));

      for(var k = 1; k < values.length; k++) {
          c.lineTo(getXPixel(k), getYPixel(values[k]));
      }

      c.stroke();
    }

    addLegend()

    c.fillStyle = this.options.style.text

    c.clearRect(0, 0, this.canvasSize.width, this.canvasSize.height);

    var yLabelIncrement = getMaxY()/this.options.numYLabels
    if (this.options.wholeNumbersOnly) yLabelIncrement = Math.floor(yLabelIncrement)
    //if (getMaxY()>=10) {
    //  yLabelIncrement = yLabelIncrement + (10 - yLabelIncrement % 10)
    //}

    //yLabelIncrement = Math.max(yLabelIncrement, 1) // should not be zero

    if (yLabelIncrement==0) yLabelIncrement = 1

    // Draw the Y value texts
    var maxY = getMaxY()
    for(var i = 0; i < maxY; i += yLabelIncrement) {
        c.fillText(formatYLabel(i, maxY, this.options.numYLabels, this.options.wholeNumbersOnly), xPadding - xLabelPadding, getYPixel(i));
    }

    for (var h=0; h<data.length; h++) {
      drawLine(data[h].y, data[h].style)
    }

    c.strokeStyle = this.options.style.baseline

    // Draw the axises
    c.beginPath();

    c.lineTo(xPadding, 0);
    c.lineTo(xPadding, this.canvasSize.height - yPadding);
    c.lineTo(this.canvasSize.width, this.canvasSize.height - yPadding);

    c.stroke();

    // Draw the X value texts
    var charsAvailable = (this.canvasSize.width - xPadding) / 2;
    var maxLabelsPossible = charsAvailable / (getMaxX() + 2);
    var pointsPerMaxLabel = Math.ceil(data[0].y.length / maxLabelsPossible);
    var showNthLabel = this.options.showNthLabel;
    if (showNthLabel < pointsPerMaxLabel) {
      showNthLabel = pointsPerMaxLabel;
    }

    for(var i = 0; i < labels.length; i += showNthLabel) {
      if((getXPixel(i) + (labels[i].length * 2)) <= this.canvasSize.width) {
        c.fillText(labels[i], getXPixel(i), this.canvasSize.height - yPadding + yLabelPadding);
      }
    }

}

Line.prototype.destroy = function()
{
    if (this.legend) {
        this.legend.destroy();
        this.remove(this.legend);
    }

    Canvas.prototype.destroy.call(this)
}

module.exports = Line


text:
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.Mapping;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Web.BackOffice.Controllers;
using Umbraco.Extensions;

namespace Umbraco.Cms.Web.BackOffice.ModelBinders;

/// <summary>
///     The model binder for <see cref="T:Umbraco.Web.Models.ContentEditing.ContentItemSave" />
/// </summary>
internal class ContentItemBinder : IModelBinder
{
    private readonly IContentService _contentService;
    private readonly IContentTypeService _contentTypeService;
    private readonly IHostingEnvironment _hostingEnvironment;
    private readonly IJsonSerializer _jsonSerializer;
    private readonly IUmbracoMapper _umbracoMapper;
    private readonly ContentModelBinderHelper _modelBinderHelper;

    public ContentItemBinder(
        IJsonSerializer jsonSerializer,
        IUmbracoMapper umbracoMapper,
        IContentService contentService,
        IContentTypeService contentTypeService,
        IHostingEnvironment hostingEnvironment)
    {
        _jsonSerializer = jsonSerializer ?? throw new ArgumentNullException(nameof(jsonSerializer));
        _umbracoMapper = umbracoMapper ?? throw new ArgumentNullException(nameof(umbracoMapper));
        _contentService = contentService ?? throw new ArgumentNullException(nameof(contentService));
        _contentTypeService = contentTypeService ?? throw new ArgumentNullException(nameof(contentTypeService));
        _hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));
        _modelBinderHelper = new ContentModelBinderHelper();
    }

    public async Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        ContentItemSave? model =
            await _modelBinderHelper.BindModelFromMultipartRequestAsync<ContentItemSave>(_jsonSerializer,
                _hostingEnvironment, bindingContext);

        if (model is null)
        {
            return;
        }

        IContent? persistedContent =
            ContentControllerBase.IsCreatingAction(model.Action) ? CreateNew(model) : GetExisting(model);
        BindModel(model, persistedContent!, _modelBinderHelper, _umbracoMapper);

        bindingContext.Result = ModelBindingResult.Success(model);
    }

    protected virtual IContent? GetExisting(ContentItemSave model) => _contentService.GetById(model.Id);

    private IContent CreateNew(ContentItemSave model)
    {
        IContentType? contentType = _contentTypeService.Get(model.ContentTypeAlias);
        if (contentType == null)
        {
            throw new InvalidOperationException("No content type found with alias " + model.ContentTypeAlias);
        }

        return new Content(
            contentType.VariesByCulture() ? null : model.Variants.First().Name,
            model.ParentId,
            contentType);
    }

    internal static void BindModel(ContentItemSave model, IContent persistedContent,
        ContentModelBinderHelper modelBinderHelper, IUmbracoMapper umbracoMapper)
    {
        model.PersistedContent = persistedContent;

        //create the dto from the persisted model
        if (model.PersistedContent != null)
        {
            foreach (ContentVariantSave variant in model.Variants)
            {
                //map the property dto collection with the culture of the current variant
                variant.PropertyCollectionDto = umbracoMapper.Map<ContentPropertyCollectionDto>(
                    model.PersistedContent,
                    context =>
                    {
                        // either of these may be null and that is ok, if it's invariant they will be null which is what is expected
                        context.SetCulture(variant.Culture);
                        context.SetSegment(variant.Segment);
                    });

                //now map all of the saved values to the dto
                modelBinderHelper.MapPropertyValuesFromSaved(variant, variant.PropertyCollectionDto);
            }
        }
    }
}


text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var enums = require("ui/enums");
var platformModule = require("platform");
var common = require("./nativescript-geolocation-common");
global.moduleMerge(common, exports);
var locationManagers = {};
var watchId = 0;
var minRangeUpdate = 0;
var defaultGetLocationTimeout = 5 * 60 * 1000;
var LocationListenerImpl = (function (_super) {
    __extends(LocationListenerImpl, _super);
    function LocationListenerImpl() {
        _super.apply(this, arguments);
    }
    LocationListenerImpl.new = function () {
        var result = _super.new.call(this);
        watchId++;
        result.id = watchId;
        return result;
    };
    LocationListenerImpl.prototype.initWithLocationErrorOptions = function (location, error, options) {
        this._onLocation = location;
        if (error) {
            this._onError = error;
        }
        if (options) {
            this._options = options;
        }
        return this;
    };
    LocationListenerImpl.prototype.locationManagerDidUpdateLocations = function (manager, locations) {
        for (var i = 0; i < locations.count; i++) {
            var location = locationFromCLLocation(locations.objectAtIndex(i));
            if (this._onLocation) {
                this._onLocation(location);
            }
        }
    };
    LocationListenerImpl.prototype.locationManagerDidFailWithError = function (manager, error) {
        if (this._onError) {
            this._onError(new Error(error.localizedDescription));
        }
    };
    LocationListenerImpl.ObjCProtocols = [CLLocationManagerDelegate];
    return LocationListenerImpl;
})(NSObject);
function locationFromCLLocation(clLocation) {
    var location = new common.Location();
    location.latitude = clLocation.coordinate.latitude;
    location.longitude = clLocation.coordinate.longitude;
    location.altitude = clLocation.altitude;
    location.horizontalAccuracy = clLocation.horizontalAccuracy;
    location.verticalAccuracy = clLocation.verticalAccuracy;
    location.speed = clLocation.speed;
    location.direction = clLocation.course;
    var timeIntervalSince1970 = NSDate.dateWithTimeIntervalSinceDate(0, clLocation.timestamp).timeIntervalSince1970;
    location.timestamp = new Date(timeIntervalSince1970 * 1000);
    location.ios = clLocation;
    return location;
}
function clLocationFromLocation(location) {
    var hAccuracy = location.horizontalAccuracy ? location.horizontalAccuracy : -1;
    var vAccuracy = location.verticalAccuracy ? location.verticalAccuracy : -1;
    var speed = location.speed ? location.speed : -1;
    var course = location.direction ? location.direction : -1;
    var altitude = location.altitude ? location.altitude : -1;
    var timestamp = location.timestamp ? NSDate.dateWithTimeIntervalSince1970(location.timestamp.getTime() / 1000) : null;
    var iosLocation = CLLocation.alloc().initWithCoordinateAltitudeHorizontalAccuracyVerticalAccuracyCourseSpeedTimestamp(CLLocationCoordinate2DMake(location.latitude, location.longitude), altitude, hAccuracy, vAccuracy, course, speed, timestamp);
    return iosLocation;
}
var LocationMonitor = (function () {
    function LocationMonitor() {
    }
    LocationMonitor.getLastKnownLocation = function () {
        var iosLocation;
        for (var locManagerId in locationManagers) {
            if (locationManagers.hasOwnProperty(locManagerId)) {
                var tempLocation = locationManagers[locManagerId].location;
                if (!iosLocation) {
                    iosLocation = tempLocation;
                }
                else {
                    if (tempLocation.timestamp > iosLocation.timestamp) {
                        iosLocation = tempLocation;
                    }
                }
            }
        }
        if (iosLocation) {
            return locationFromCLLocation(iosLocation);
        }
        var locListener = new LocationListenerImpl();
        locListener.initWithLocationErrorOptions(null, null, null);
        iosLocation = LocationMonitor.createiOSLocationManager(locListener, null).location;
        if (iosLocation) {
            return locationFromCLLocation(iosLocation);
        }
        return null;
    };
    LocationMonitor.stopLocationMonitoring = function (iosLocManagerId) {
        if (locationManagers[iosLocManagerId]) {
            locationManagers[iosLocManagerId].stopUpdatingLocation();
            locationManagers[iosLocManagerId].delegate = null;
            delete locationManagers[iosLocManagerId];
        }
    };
    LocationMonitor.startLocationMonitoring = function (options, locListener) {
        var iosLocManager = LocationMonitor.createiOSLocationManager(locListener, options);
        locationManagers[locListener.id] = iosLocManager;
        iosLocManager.startUpdatingLocation();
    };
    LocationMonitor.createListenerWithCallbackAndOptions = function (successCallback, options) {
        var locListener = new LocationListenerImpl();
        locListener.initWithLocationErrorOptions(successCallback, null, options);
        return locListener;
    };
    LocationMonitor.createiOSLocationManager = function (locListener, options) {
        var iosLocManager = new CLLocationManager();
        iosLocManager.delegate = locListener;
        iosLocManager.desiredAccuracy = options ? options.desiredAccuracy : enums.Accuracy.high;
        iosLocManager.distanceFilter = options ? options.updateDistance : minRangeUpdate;
        locationManagers[locListener.id] = iosLocManager;
        return iosLocManager;
    };
    return LocationMonitor;
})();
exports.LocationMonitor = LocationMonitor;
function isEnabled() {
    if (CLLocationManager.locationServicesEnabled()) {
        return (CLLocationManager.authorizationStatus() === CLAuthorizationStatus.kCLAuthorizationStatusAuthorizedWhenInUse
            || CLLocationManager.authorizationStatus() === CLAuthorizationStatus.kCLAuthorizationStatusAuthorizedAlways
            || CLLocationManager.authorizationStatus() === CLAuthorizationStatus.kCLAuthorizationStatusAuthorized);
    }
    return false;
}
exports.isEnabled = isEnabled;
function distance(loc1, loc2) {
    if (!loc1.ios) {
        loc1.ios = clLocationFromLocation(loc1);
    }
    if (!loc2.ios) {
        loc2.ios = clLocationFromLocation(loc2);
    }
    return loc1.ios.distanceFromLocation(loc2.ios);
}
exports.distance = distance;
function enableLocationRequest(always) {
    if (platformModule.device.osVersion.indexOf("8") === 0) {
        var iosLocationManager = CLLocationManager.alloc().init();
        if (always) {
            iosLocationManager.requestAlwaysAuthorization();
        }
        else {
            iosLocationManager.requestWhenInUseAuthorization();
        }
    }
}
exports.enableLocationRequest = enableLocationRequest;
function watchLocation(successCallback, errorCallback, options) {
    var locListener = new LocationListenerImpl();
    locListener.initWithLocationErrorOptions(successCallback, errorCallback, options);
    try {
        var iosLocManager = LocationMonitor.createiOSLocationManager(locListener, options);
        iosLocManager.startUpdatingLocation();
        return locListener.id;
    }
    catch (e) {
        LocationMonitor.stopLocationMonitoring(locListener.id);
        errorCallback(e);
        return null;
    }
}
exports.watchLocation = watchLocation;
function clearWatch(watchId) {
    LocationMonitor.stopLocationMonitoring(watchId);
}
exports.clearWatch = clearWatch;


text:
package eu.derbed.openmu.gs.muObjects;

public class MuPetInstance extends MuObject {

	public MuPetInstance(short obiectId, byte _x, byte _y, byte _m) {
		super(obiectId, _x, _y, _m);
		// TODO Auto-generated constructor stub
	}

}


text:
<?php

namespace Acme\SimpleCMSBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Tag
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Acme\SimpleCMSBundle\Entity\TagRepository")
 */
class Tag
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @var \Doctrine\ORM\PersistentCollection
     * @ORM\ManyToMany(targetEntity="Post", mappedBy="tags")
     */
    protected $posts;

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

    /**
     * Set name
     *
     * @param string $name
     * @return Tag
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->posts = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add posts
     *
     * @param \Acme\SimpleCMSBundle\Entity\Post $posts
     * @return Tag
     */
    public function addPost(\Acme\SimpleCMSBundle\Entity\Post $posts)
    {
        $this->posts[] = $posts;

        return $this;
    }

    /**
     * Remove posts
     *
     * @param \Acme\SimpleCMSBundle\Entity\Post $posts
     */
    public function removePost(\Acme\SimpleCMSBundle\Entity\Post $posts)
    {
        $this->posts->removeElement($posts);
    }

    /**
     * Get posts
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getPosts()
    {
        return $this->posts;
    }
}


text:
import Joi from 'joi-full'

export default Joi.object({
  serial: Joi.string().required().label('Número de série'),
  name: Joi.string().required().label('Nome'),
  relay1: Joi.string().required().label('Relé 1'),
  relay2: Joi.string().required().label('Relé 2'),
  location: Joi.string().required().label('Tipo'),
})


text:
require 'cocoapods-core/specification/linter/result'

module Pod
  class Specification
    class Linter
      class Analyzer
        def initialize(consumer, results)
          @consumer = consumer
          @results = results
          @results.consumer = @consumer
        end

        # Analyzes the consumer adding a {Result} for any failed check to
        # the {#results} object.
        #
        # @return [Results] the results of the analysis.
        #
        def analyze
          check_attributes
          validate_file_patterns
          check_if_spec_is_empty
          results
        end

        private

        attr_reader :consumer

        attr_reader :results

        # @return [Array<String>] Keys that are valid but have been deprecated.
        #
        DEPRECATED_KEYS = ['swift_version'].freeze

        # @return [Array<String>] Keys that are only used for internal purposes.
        #
        INTERNAL_KEYS = ['configuration_pod_whitelist'].freeze

        # Checks the attributes hash for any unknown key which might be the
        # result of a misspelling in a JSON file.
        #
        # @note Sub-keys are not checked per-platform as
        #       there is no attribute supporting this combination.
        #
        # @note The keys of sub-keys are not checked as they are only used by
        #       the `source` attribute and they are subject
        #       to change according to the support in the
        #       `cocoapods-downloader` gem.
        #
        def check_attributes
          attributes_keys = Pod::Specification::DSL.attributes.keys.map(&:to_s)
          platform_keys = Specification::DSL::PLATFORMS.map(&:to_s)
          valid_keys = attributes_keys + platform_keys + DEPRECATED_KEYS + INTERNAL_KEYS
          attributes_hash = consumer.spec.attributes_hash
          keys = attributes_hash.keys
          Specification::DSL::PLATFORMS.each do |platform|
            if attributes_hash[platform.to_s]
              keys += attributes_hash[platform.to_s].keys
            end
          end
          unknown_keys = keys - valid_keys

          unknown_keys.each do |key|
            results.add_warning('attributes', "Unrecognized `#{key}` key.")
          end

          Pod::Specification::DSL.attributes.each do |_key, attribute|
            declared_value = consumer.spec.attributes_hash[attribute.name.to_s]
            validate_attribute_occurrence(attribute, declared_value)
            validate_attribute_type(attribute, declared_value)
            if attribute.name != :platforms
              value = value_for_attribute(attribute)
              validate_attribute_value(attribute, value) if value
            end
          end
        end

        # Checks the attributes that represent file patterns.
        #
        # @todo Check the attributes hash directly.
        #
        def validate_file_patterns
          attributes = DSL.attributes.values.select(&:file_patterns?)
          attributes.each do |attrb|
            patterns = consumer.send(attrb.name)

            if patterns.is_a?(Hash)
              patterns = patterns.values.flatten(1)
            end

            if patterns.respond_to?(:each)
              patterns.each do |pattern|
                pattern = pattern[:paths].join if attrb.name == :on_demand_resources
                if pattern.respond_to?(:start_with?) && pattern.start_with?('/')
                  results.add_error('File Patterns', 'File patterns must be ' \
                    "relative and cannot start with a slash (#{attrb.name}).")
                end
              end
            end
          end
        end

        # Check empty subspec attributes
        #
        def check_if_spec_is_empty
          methods = %w( source_files on_demand_resources resources resource_bundles preserve_paths
                        dependencies vendored_libraries vendored_frameworks )
          empty_patterns = methods.all? { |m| consumer.send(m).empty? }
          empty = empty_patterns && consumer.spec.subspecs.empty?
          if empty
            results.add_error('File Patterns', "The #{consumer.spec} spec is " \
              'empty (no source files, resources, resource_bundles, ' \
              'preserve paths, vendored_libraries, vendored_frameworks, ' \
              'dependencies, nor subspecs).')
          end
        end

        private

        # Returns the own or inherited (if applicable) value of the
        # given attribute.
        #
        # @param  [Spec::DSL::Attribute] attribute
        #         The attribute.
        #
        # @return [mixed]
        #
        def value_for_attribute(attribute)
          if attribute.root_only?
            consumer.spec.send(attribute.name)
          else
            consumer.send(attribute.name) if consumer.respond_to?(attribute.name)
          end
        rescue => e
          results.add_error('attributes', "Unable to validate `#{attribute.name}` (#{e}).")
          nil
        end

        # Validates that root attributes don't occur in subspecs.
        #
        # @param  [Spec::DSL::Attribute] attribute
        #         The attribute.

        # @param  [Object] value
        #         The value of the attribute.
        #
        def validate_attribute_occurrence(attribute, value)
          if attribute.root_only? && !value.nil? && !consumer.spec.root?
            results.add_error('attributes', "Can't set `#{attribute.name}` attribute for " \
              "subspecs (in `#{consumer.spec.name}`).")
          end
          if attribute.test_only? && !value.nil? && !consumer.spec.test_specification?
            results.add_error('attributes', "Attribute `#{attribute.name}` can only be set " \
              "within test specs (in `#{consumer.spec.name}`).")
          end
        end

        # Validates the given value for the given attribute.
        #
        # @param  [Spec::DSL::Attribute] attribute
        #         The attribute.
        #
        # @param  [Object] value
        #         The value of the attribute.
        #
        def validate_attribute_value(attribute, value)
          if attribute.keys.is_a?(Array)
            validate_attribute_array_keys(attribute, value)
          elsif attribute.keys.is_a?(Hash)
            validate_attribute_hash_keys(attribute, value)
          end
        end

        def validate_attribute_type(attribute, value)
          return unless value
          types = attribute.supported_types
          if types.none? { |klass| value.class == klass }
            results.add_error('attributes', 'Unacceptable type ' \
              "`#{value.class}` for `#{attribute.name}`. Allowed values: `#{types.inspect}`.")
          end
        end

        def validate_attribute_array_keys(attribute, value)
          unknown_keys = value.keys.map(&:to_s) - attribute.keys.map(&:to_s)
          unknown_keys.each do |unknown_key|
            results.add_warning('keys', "Unrecognized `#{unknown_key}` key for " \
              "`#{attribute.name}` attribute.")
          end
        end

        def validate_attribute_hash_keys(attribute, value)
          unless value.is_a?(Hash)
            results.add_error(attribute.name, "Unsupported type `#{value.class}`, expected `Hash`")
            return
          end
          major_keys = value.keys & attribute.keys.keys
          if major_keys.count.zero?
            results.add_warning('keys', "Missing primary key for `#{attribute.name}` " \
              'attribute. The acceptable ones are: ' \
              "`#{attribute.keys.keys.map(&:to_s).sort.join(', ')}`.")
          elsif major_keys.count == 1
            acceptable = attribute.keys[major_keys.first] || []
            unknown = value.keys - major_keys - acceptable
            unless unknown.empty?
              results.add_warning('keys', "Incompatible `#{unknown.sort.join(', ')}` " \
                "key(s) with `#{major_keys.first}` primary key for " \
                "`#{attribute.name}` attribute.")
            end
          else
            sorted_keys = major_keys.map(&:to_s).sort
            results.add_warning('keys', "Incompatible `#{sorted_keys.join(', ')}` " \
              "keys for `#{attribute.name}` attribute.")
          end
        end
      end
    end
  end
end


text:
define([
  'backbone', 'models/GenericModel', 'controllers/util/FetchController'
], function (backbone, GenericModel, FetchController) {
    return backbone.Collection.extend({
        model: GenericModel,

		initialize: function(options) {
			this.fetchController = new FetchController();

			if(!options)
				return;

			this.name = options.name;
			this.url = options.url;
		},

		fetch: function (options) {
			backbone.Model.prototype.fetch.call(this, this.fetchController.extendModelOptions(options));
		},

    });
});


text:
package ch.bind.philib.validation;

import java.util.Collection;

/**
 * @author Philipp Meinen
 */
public final class ValidationUtil {

	private ValidationUtil() {
	}

	public static ValidationResults validate(final Validatable validatable) {
		final ValidationResults results = new ValidationResults();
		validatable.validate(results); // NPE is intended!
		return results;
	}

	public static <T extends Validatable> ValidationResults validate(final Collection<T> validatables) {
		final ValidationResults results = new ValidationResults();
		for (Validatable validatable : validatables) {
			validatable.validate(results); // NPE is intended!
		}
		return results;
	}

	public static <T extends Validatable> ValidationResults validate(final T[] validatables) {
		final ValidationResults results = new ValidationResults();
		for (Validatable validatable : validatables) {
			validatable.validate(results); // NPE is intended!
		}
		return results;
	}
}


text:
package org.apache.geode.internal.cache.tier.sockets;

import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static java.lang.Thread.sleep;
import static org.apache.geode.cache.InterestResultPolicy.NONE;
import static org.apache.geode.cache.client.PoolManager.createFactory;
import static org.apache.geode.distributed.internal.DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT;
import static org.apache.geode.internal.cache.tier.sockets.CacheServerTestUtil.TYPE_CREATE;
import static org.apache.geode.internal.cache.tier.sockets.CacheServerTestUtil.createCacheClient;
import static org.apache.geode.internal.cache.tier.sockets.CacheServerTestUtil.createCacheServer;
import static org.apache.geode.test.dunit.NetworkUtils.getServerHostName;
import static org.apache.geode.test.dunit.Wait.pause;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.concurrent.TimeUnit;

import org.awaitility.Awaitility;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.cache.CacheException;
import org.apache.geode.cache.ClientSession;
import org.apache.geode.cache.InterestResultPolicy;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.Pool;
import org.apache.geode.cache.client.PoolManager;
import org.apache.geode.cache.client.ServerRefusedConnectionException;
import org.apache.geode.cache.client.internal.PoolImpl;
import org.apache.geode.cache30.CacheSerializableRunnable;
import org.apache.geode.distributed.internal.DistributionConfig;
import org.apache.geode.internal.cache.PoolFactoryImpl;
import org.apache.geode.internal.cache.ha.HARegionQueue;
import org.apache.geode.internal.cache.ha.HARegionQueueStats;
import org.apache.geode.test.dunit.SerializableRunnableIF;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.junit.categories.ClientSubscriptionTest;

@Category({ClientSubscriptionTest.class})
public class DurableClientSimpleDUnitTest extends DurableClientTestBase {

  /**
   * Test that a durable client correctly receives updates.
   */
  @Test
  public void testSimpleDurableClientUpdate() {
    // Start a server
    server1Port = this.server1VM
        .invoke(() -> CacheServerTestUtil.createCacheServer(regionName, Boolean.TRUE));

    // Start a durable client that is not kept alive on the server when it stops
    // normally
    final String durableClientId = getName() + "_client";
    this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
        getClientPool(getServerHostName(), server1Port, true), regionName,
        getClientDistributedSystemProperties(durableClientId), Boolean.TRUE));

    // Send clientReady message
    sendClientReady(this.durableClientVM);

    registerInterest(durableClientVM, regionName, true, InterestResultPolicy.NONE);

    // Start normal publisher client
    this.publisherClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
        getClientPool(getServerHostName(), server1Port, false),
        regionName));

    // Publish some entries
    final int numberOfEntries = 10;
    publishEntries(0, 10);

    // Verify the durable client received the updates
    checkListenerEvents(numberOfEntries, 1, -1, this.durableClientVM);

    // Stop the durable client
    this.durableClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop the publisher client
    this.publisherClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop the server
    this.server1VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
  }

  /**
   * Test that a durable client VM with multiple BridgeClients correctly registers on the server.
   */
  @Test
  public void testMultipleBridgeClientsInSingleDurableVM() {
    // Start a server
    server1Port = this.server1VM
        .invoke(() -> CacheServerTestUtil.createCacheServer(regionName, Boolean.TRUE));

    // Start a durable client with 2 regions (and 2 BridgeClients) that is not
    // kept alive on the server when it stops normally
    final String durableClientId = getName() + "_client";
    final String regionName1 = regionName + "1";
    final String regionName2 = regionName + "2";
    this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClients(
        getClientPool(getServerHostName(), server1Port, true), regionName1,
        regionName2, getClientDistributedSystemProperties(durableClientId)));

    // Send clientReady message
    this.durableClientVM.invoke(new CacheSerializableRunnable("Send clientReady") {
      @Override
      public void run2() throws CacheException {
        assertEquals(2, PoolManager.getAll().size());
        CacheServerTestUtil.getClientCache().readyForEvents();
      }
    });

    // Verify durable clients on server
    this.server1VM.invoke(new CacheSerializableRunnable("Verify durable client") {
      @Override
      public void run2() throws CacheException {
        // Get the CacheClientNotifier
        CacheClientNotifier notifier = getBridgeServer().getAcceptor().getCacheClientNotifier();

        // Iterate the CacheClientProxies
        checkNumberOfClientProxies(2);
        String firstProxyRegionName = null;
        for (CacheClientProxy proxy : notifier.getClientProxies()) {
          assertTrue(proxy.isDurable());
          assertEquals(durableClientId, proxy.getDurableId());
          assertEquals(DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT,
              proxy.getDurableTimeout());

          // Verify the two HA region names aren't the same
          if (firstProxyRegionName == null) {
            firstProxyRegionName = proxy.getHARegionName();
          } else {
            assertTrue(!firstProxyRegionName.equals(proxy.getHARegionName()));
          }
        }
      }
    });

    // Stop the durable client
    this.durableClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Verify the durable client is no longer on the server
    this.server1VM.invoke(new CacheSerializableRunnable("Verify durable client") {
      @Override
      public void run2() throws CacheException {
        // Find the proxy
        checkNumberOfClientProxies(0);
      }
    });

    // Stop the server
    this.server1VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
  }

  /**
   * Test that a second VM with the same durable id cannot connect to the server while the first VM
   * is connected. Also, verify that the first client is not affected by the second one attempting
   * to connect.
   */
  @Ignore("TODO: test is disabled")
  @Test
  public void testMultipleVMsWithSameDurableId() {
    // Start a server
    server1Port = this.server1VM
        .invoke(() -> createCacheServer(regionName, TRUE));

    // Start a durable client that is not kept alive on the server when it
    // stops normally
    final String durableClientId = getName() + "_client";
    this.durableClientVM.invoke(() -> createCacheClient(
        getClientPool(getServerHostName(), server1Port, true), regionName,
        getClientDistributedSystemProperties(durableClientId), TRUE));

    // Send clientReady message
    sendClientReady(this.durableClientVM);

    registerInterest(durableClientVM, regionName, true, NONE);

    // Attempt to start another durable client VM with the same id.
    this.publisherClientVM.invoke(new CacheSerializableRunnable("Create another durable client") {
      @Override
      public void run2() throws CacheException {
        getSystem(getClientDistributedSystemProperties(durableClientId));
        PoolFactoryImpl pf = (PoolFactoryImpl) createFactory();
        pf.init(getClientPool(getServerHostName(), server1Port, true));
        try {
          pf.create("uncreatablePool");
          fail("Should not have been able to create the pool");
        } catch (ServerRefusedConnectionException expected) {
          // expected exception
          disconnectFromDS();
        } catch (Exception e) {
          fail("Should not have gotten here", e);
        }
      }
    });

    // Verify durable client on server
    verifyDurableClientPresent(DEFAULT_DURABLE_CLIENT_TIMEOUT, durableClientId,
        server1VM);

    // Start normal publisher client
    this.publisherClientVM.invoke(() -> createCacheClient(
        getClientPool(getServerHostName(), server1Port, false),
        regionName));

    // Publish some entries
    final int numberOfEntries = 10;
    publishEntries(0, numberOfEntries);

    // Verify the durable client received the updates
    checkListenerEvents(numberOfEntries, 1, -1, this.durableClientVM);

    // Stop the publisher client
    this.publisherClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop the durable client
    this.durableClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop the server
    this.server1VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
  }

  /**
   * Test that the server correctly processes starting two durable clients.
   */
  @Test
  public void testSimpleTwoDurableClients() {
    // Start a server
    server1Port = this.server1VM
        .invoke(() -> CacheServerTestUtil.createCacheServer(regionName, Boolean.TRUE));

    // Start a durable client that is not kept alive on the server when it
    // stops normally
    final String durableClientId = getName() + "_client";
    this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
        getClientPool(getServerHostName(), server1Port, true), regionName,
        getClientDistributedSystemProperties(durableClientId)));

    // Send clientReady message
    sendClientReady(this.durableClientVM);

    // Start another durable client that is not kept alive on the server when
    // it stops normally. Use the 'publisherClientVM' as a durable client.
    VM durableClient2VM = this.publisherClientVM;
    final String durableClientId2 = getName() + "_client2";
    durableClient2VM.invoke(() -> CacheServerTestUtil.createCacheClient(
        getClientPool(getServerHostName(), server1Port, true), regionName,
        getClientDistributedSystemProperties(durableClientId2)));

    // Send clientReady message
    sendClientReady(durableClient2VM);

    // Verify durable clients on server
    this.server1VM.invoke(new CacheSerializableRunnable("Verify durable client") {
      @Override
      public void run2() throws CacheException {
        // Get the CacheClientNotifier
        CacheClientNotifier notifier = getBridgeServer().getAcceptor().getCacheClientNotifier();

        // Iterate the CacheClientProxies and verify they are correct
        checkNumberOfClientProxies(2);
        boolean durableClient1Found = false, durableClient2Found = false;
        for (CacheClientProxy proxy : notifier.getClientProxies()) {
          assertTrue(proxy.isDurable());
          if (proxy.getDurableId().equals(durableClientId)) {
            durableClient1Found = true;
          }
          if (proxy.getDurableId().equals(durableClientId2)) {
            durableClient2Found = true;
          }
          assertEquals(DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT,
              proxy.getDurableTimeout());
        }
        assertTrue(durableClient1Found);
        assertTrue(durableClient2Found);
      }
    });

    // Stop the durable clients
    this.durableClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
    durableClient2VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop the server
    this.server1VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
  }

  /**
   * Test that starting a durable client on multiple servers (one live and one not live) is
   * processed correctly.
   */
  @Ignore("TODO: test is disabled for bug 52043")
  @Test
  public void testDurableClientMultipleServersOneLive() throws InterruptedException {
    // Start server 1
    server1Port = this.server1VM
        .invoke(() -> createCacheServer(regionName, TRUE));

    // Start server 2
    final int server2Port = this.server2VM
        .invoke(() -> createCacheServer(regionName, TRUE));

    // Stop server 2
    this.server2VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Start a durable client that is kept alive on the server when it stops
    // normally
    final String durableClientId = getName() + "_client";
    final int durableClientTimeout = 60; // keep the client alive for 60 seconds
    // final boolean durableClientKeepAlive = true; // keep the client alive when it stops normally
    this.durableClientVM.invoke(() -> createCacheClient(
        getClientPool(getServerHostName(), server1Port, server2Port, true),
        regionName, getClientDistributedSystemProperties(durableClientId, durableClientTimeout),
        TRUE));

    // Send clientReady message
    sendClientReady(this.durableClientVM);

    registerInterest(durableClientVM, regionName, true, NONE);

    // Verify durable client on server1
    verifyDurableClientPresent(durableClientTimeout, durableClientId, server1VM);
    // Start normal publisher client
    this.publisherClientVM.invoke(() -> createCacheClient(getClientPool(getServerHostName(),
        server1Port, server2Port, false), regionName));

    // Publish some entries
    final int numberOfEntries = 10;
    publishEntries(0, numberOfEntries);

    // Verify the durable client received the updates
    checkListenerEvents(numberOfEntries, 1, -1, this.durableClientVM);

    sleep(10000);

    // Stop the durable client
    this.durableClientVM.invoke(() -> CacheServerTestUtil.closeCache(TRUE));

    // Verify the durable client still exists on the server
    this.server1VM.invoke(new CacheSerializableRunnable("Verify durable client") {
      @Override
      public void run2() throws CacheException {
        // Find the proxy
        CacheClientProxy proxy = getClientProxy();
        assertNotNull(proxy);
      }
    });

    // Publish some more entries
    publishEntries(10, numberOfEntries);

    // Re-start the durable client
    this.durableClientVM.invoke(() -> createCacheClient(
        getClientPool(getServerHostName(), server1Port, server2Port, true),
        regionName, getClientDistributedSystemProperties(durableClientId), TRUE));

    // Send clientReady message
    sendClientReady(this.durableClientVM);

    // Verify durable client on server
    verifyDurableClientPresent(durableClientTimeout, durableClientId, server1VM);

    // Verify the durable client received the updates held for it on the server
    checkListenerEvents(numberOfEntries, 1, -1, this.durableClientVM);

    // Stop the durable client
    this.durableClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop the publisher client
    this.publisherClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop server 1
    this.server1VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
  }

  /**
   * Test that updates to two durable clients are processed correctly.
   */
  @Test
  public void testTwoDurableClientsStartStopUpdate() throws InterruptedException {
    // Start a server
    server1Port = this.server1VM
        .invoke(() -> createCacheServer(regionName, TRUE));

    // Start a durable client that is kept alive on the server when it stops
    // normally
    final String durableClientId = getName() + "_client";
    final int durableClientTimeout = 60; // keep the client alive for 60 seconds
    // final boolean durableClientKeepAlive = true; // keep the client alive when it stops normally
    this.durableClientVM.invoke(() -> createCacheClient(
        getClientPool(getServerHostName(), server1Port, true), regionName,
        getClientDistributedSystemProperties(durableClientId, durableClientTimeout),
        TRUE));

    // Send clientReady message
    sendClientReady(this.durableClientVM);

    registerInterest(durableClientVM, regionName, true, NONE);

    // Start another durable client that is not kept alive on the server when
    // it stops normally. Use the 'server2VM' as the second durable client.
    VM durableClient2VM = this.server2VM;
    final String durableClientId2 = getName() + "_client2";
    durableClient2VM.invoke(() -> createCacheClient(
        getClientPool(getServerHostName(), server1Port, true), regionName,
        getClientDistributedSystemProperties(durableClientId2, durableClientTimeout),
        TRUE));

    // Send clientReady message
    sendClientReady(durableClient2VM);

    registerInterest(durableClient2VM, regionName, true, NONE);

    // Verify durable clients on server
    verifyMultupleDurableClients(durableClientId, durableClientTimeout, durableClientId2);

    // Start normal publisher client
    this.publisherClientVM.invoke(() -> createCacheClient(
        getClientPool(getServerHostName(), server1Port, false),
        regionName));

    // Publish some entries
    final int numberOfEntries = 10;
    publishEntries(0, numberOfEntries);

    // Verify durable client 1 received the updates
    checkListenerEvents(numberOfEntries, 1, -1, this.durableClientVM);

    // Verify durable client 2 received the updates
    checkListenerEvents(numberOfEntries, 1, -1, durableClient2VM);

    // ARB: Wait for queue ack to arrive at server.
    sleep(1000);

    // Stop the durable clients
    this.durableClientVM.invoke(() -> CacheServerTestUtil.closeCache(TRUE));
    durableClient2VM.invoke(() -> CacheServerTestUtil.closeCache(TRUE));

    // Verify the durable clients still exist on the server
    verifyMultupleDurableClients(durableClientId, durableClientTimeout, durableClientId2);

    // Publish some more entries
    publishEntries(10, numberOfEntries);

    sleep(1000);

    // Verify the durable clients' queues contain the entries
    this.server1VM.invoke(new CacheSerializableRunnable("Verify durable client") {
      @Override
      public void run2() throws CacheException {
        // Get the CacheClientNotifier
        CacheClientNotifier notifier = getBridgeServer().getAcceptor().getCacheClientNotifier();

        // Iterate the CacheClientProxies and verify the queue sizes
        checkNumberOfClientProxies(2);
        for (CacheClientProxy proxy : notifier.getClientProxies()) {
          assertEquals(numberOfEntries, proxy.getQueueSize());
        }
      }
    });

    // Re-start durable client 1
    this.durableClientVM.invoke(() -> createCacheClient(
        getClientPool(getServerHostName(), server1Port, true), regionName,
        getClientDistributedSystemProperties(durableClientId), TRUE));

    // Send clientReady message
    sendClientReady(this.durableClientVM);

    // Re-start durable client 2
    durableClient2VM.invoke(() -> createCacheClient(
        getClientPool(getServerHostName(), server1Port, true), regionName,
        getClientDistributedSystemProperties(durableClientId2), TRUE));

    // Send clientReady message
    sendClientReady(durableClient2VM);

    // Verify durable client 1 received the updates held for it on the server
    checkListenerEvents(numberOfEntries, 1, -1, this.durableClientVM);

    // Verify durable client 2 received the updates held for it on the server
    checkListenerEvents(numberOfEntries, 1, -1, this.durableClientVM);

    // Stop durable client 1
    this.durableClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop durable client 2
    durableClient2VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop the publisher client
    this.publisherClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop the server
    this.server1VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
  }

  private void verifyMultupleDurableClients(String durableClientId, int durableClientTimeout,
      String durableClientId2) {
    this.server1VM.invoke(new CacheSerializableRunnable("Verify durable client") {
      @Override
      public void run2() throws CacheException {
        // Get the CacheClientNotifier
        CacheClientNotifier notifier = getBridgeServer().getAcceptor().getCacheClientNotifier();

        // Iterate the CacheClientProxies and verify they are correct
        checkNumberOfClientProxies(2);
        boolean durableClient1Found = false, durableClient2Found = false;
        for (CacheClientProxy proxy : notifier.getClientProxies()) {
          assertTrue(proxy.isDurable());
          if (proxy.getDurableId().equals(durableClientId)) {
            durableClient1Found = true;
          }
          if (proxy.getDurableId().equals(durableClientId2)) {
            durableClient2Found = true;
          }
          assertEquals(durableClientTimeout, proxy.getDurableTimeout());
        }
        assertTrue(durableClient1Found);
        assertTrue(durableClient2Found);
      }
    });
  }

  /**
   * Tests whether a durable client reconnects properly to two servers.
   */
  @Test
  public void testDurableClientReconnectTwoServers() throws InterruptedException {
    // Start server 1
    server1Port = this.server1VM.invoke(
        () -> createCacheServer(regionName, TRUE));

    // on test flag for periodic ack
    this.server1VM
        .invoke(() -> setTestFlagToVerifyActForMarker(TRUE));

    // Start server 2 using the same mcast port as server 1
    final int server2Port = this.server2VM
        .invoke(() -> createCacheServer(regionName, TRUE));

    // Stop server 2
    this.server2VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Start a durable client that is kept alive on the server when it stops
    // normally
    final String durableClientId = getName() + "_client";
    final int durableClientTimeout = 60; // keep the client alive for 60 seconds
    // final boolean durableClientKeepAlive = true; // keep the client alive when it stops normally
    this.durableClientVM.invoke(() -> createCacheClient(
        getClientPool(getServerHostName(), server1Port, server2Port, true),
        regionName, getClientDistributedSystemProperties(durableClientId, durableClientTimeout),
        TRUE));

    // Send clientReady message
    sendClientReady(this.durableClientVM);

    registerInterest(durableClientVM, regionName, true, NONE);

    // Verify durable client on server 1
    this.server1VM.invoke(new CacheSerializableRunnable("Verify durable client") {
      @Override
      public void run2() throws CacheException {
        // Find the proxy
        checkNumberOfClientProxies(1);
        CacheClientProxy proxy = getClientProxy();
        assertNotNull(proxy);

        // Verify that it is durable and its properties are correct
        assertTrue(proxy.isDurable());
        assertEquals(durableClientId, proxy.getDurableId());
        assertEquals(durableClientTimeout, proxy.getDurableTimeout());
        verifyReceivedMarkerAck();
      }
    });

    // VJR: wait for ack to go out
    pause(5000);

    // Stop the durable client
    this.durableClientVM.invoke(() -> CacheServerTestUtil.closeCache(TRUE));

    // Verify durable client on server 1
    this.server1VM.invoke(new CacheSerializableRunnable("Verify durable client") {
      @Override
      public void run2() throws CacheException {
        // Find the proxy
        checkNumberOfClientProxies(1);
        CacheClientProxy proxy = getClientProxy();
        assertNotNull(proxy);
      }
    });

    // Re-start server2
    this.server2VM.invoke(() -> createCacheServer(regionName, TRUE,
        server2Port));

    // Start normal publisher client
    this.publisherClientVM.invoke(() -> createCacheClient(getClientPool(getServerHostName(),
        server1Port, server2Port, false), regionName));

    // Publish some entries
    final int numberOfEntries = 10;
    publishEntries(0, numberOfEntries);

    sleep(1000);

    // Verify the durable client's queue contains the entries
    this.server1VM.invoke(new CacheSerializableRunnable("Verify durable client") {
      @Override
      public void run2() throws CacheException {
        // Find the proxy
        CacheClientProxy proxy = getClientProxy();
        assertNotNull(proxy);

        // Verify the queue size
        assertEquals(numberOfEntries, proxy.getQueueSize());
      }
    });

    // Re-start the durable client that is kept alive on the server when it stops
    // normally
    this.durableClientVM.invoke(() -> createCacheClient(
        getClientPool(getServerHostName(), server1Port, server2Port, true),
        regionName, getClientDistributedSystemProperties(durableClientId, durableClientTimeout),
        TRUE));

    // Send clientReady message
    sendClientReady(this.durableClientVM);

    // Verify durable client on server 1
    verifyDurableClientPresence(durableClientTimeout, durableClientId, server1VM, 1);

    // Verify durable client on server 2
    verifyDurableClientPresence(durableClientTimeout, durableClientId, server2VM, 1);

    // Verify the HA region names are the same on both servers
    String server1HARegionQueueName =
        this.server1VM.invoke(DurableClientTestBase::getHARegionQueueName);
    String server2HARegionQueueName =
        this.server2VM.invoke(DurableClientTestBase::getHARegionQueueName);
    assertEquals(server1HARegionQueueName, server2HARegionQueueName);

    // Verify the durable client received the updates
    checkListenerEvents(numberOfEntries, 1, -1, this.durableClientVM);

    // Stop the durable client
    this.durableClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop the publisher client
    this.publisherClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // off test flag for periodic ack
    this.server1VM
        .invoke(() -> setTestFlagToVerifyActForMarker(FALSE));

    // Stop server 1
    this.server1VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop server 2
    this.server2VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
  }

  @Test
  public void testReadyForEventsNotCalledImplicitly() {
    // Start a server
    server1Port = this.server1VM
        .invoke(() -> CacheServerTestUtil.createCacheServer(regionName, Boolean.TRUE));

    // Start a durable client that is not kept alive on the server when it
    // stops normally
    final String durableClientId = getName() + "_client";
    // make the client use ClientCacheFactory so it will have a default pool
    this.durableClientVM.invoke(() -> CacheServerTestUtil.createClientCache(
        getClientPool(getServerHostName(), server1Port, true), regionName,
        getClientDistributedSystemProperties(durableClientId)));

    // verify that readyForEvents has not yet been called on the client's default pool
    this.durableClientVM.invoke(new CacheSerializableRunnable("check readyForEvents not called") {
      @Override
      public void run2() throws CacheException {
        for (Pool p : PoolManager.getAll().values()) {
          assertFalse(((PoolImpl) p).getReadyForEventsCalled());
        }
      }
    });

    // Send clientReady message
    sendClientReady(this.durableClientVM);

    // Verify durable clients on server
    this.server1VM.invoke(new CacheSerializableRunnable("Verify durable client") {
      @Override
      public void run2() throws CacheException {
        // Get the CacheClientNotifier
        CacheClientNotifier notifier = getBridgeServer().getAcceptor().getCacheClientNotifier();

        // Iterate the CacheClientProxies and verify they are correct
        checkNumberOfClientProxies(1);
        boolean durableClient1Found = false;
        for (CacheClientProxy proxy : notifier.getClientProxies()) {
          assertTrue(proxy.isDurable());
          if (proxy.getDurableId().equals(durableClientId)) {
            durableClient1Found = true;
          }
          assertEquals(DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT,
              proxy.getDurableTimeout());
        }
        assertTrue(durableClient1Found);
      }
    });

    // Stop the durable clients
    this.durableClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop the server
    this.server1VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
  }

  @Test
  public void testReadyForEventsNotCalledImplicitlyForRegisterInterestWithCacheXML() {
    regionName = "testReadyForEventsNotCalledImplicitlyWithCacheXML_region";
    // Start a server
    server1Port =
        this.server1VM.invoke(() -> CacheServerTestUtil.createCacheServerFromXmlN(
            DurableClientTestBase.class.getResource("durablecq-server-cache.xml")));

    // Start a durable client that is not kept alive on the server when it
    // stops normally
    final String durableClientId = getName() + "_client";

    // create client cache from xml
    this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClientFromXmlN(
        DurableClientTestBase.class.getResource("durablecq-client-cache.xml"), "client",
        durableClientId, DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT, Boolean.TRUE));

    // verify that readyForEvents has not yet been called on all the client's pools
    this.durableClientVM.invoke(new CacheSerializableRunnable("check readyForEvents not called") {
      @Override
      public void run2() throws CacheException {
        for (Pool p : PoolManager.getAll().values()) {
          assertFalse(((PoolImpl) p).getReadyForEventsCalled());
        }
      }
    });

    // Send clientReady message
    sendClientReady(this.durableClientVM);

    // Durable client registers durable cq on server
    registerInterest(durableClientVM, regionName, true, InterestResultPolicy.KEYS_VALUES);

    // Verify durable client on server1
    verifyDurableClientPresent(DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT, durableClientId,
        server1VM);

    // Start normal publisher client
    this.publisherClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
        getClientPool(getServerHostName(), server1Port, false),
        regionName));

    // Publish some entries
    final int numberOfEntries = 10;
    publishEntries(0, numberOfEntries);

    // Verify the durable client received the updates
    checkListenerEvents(numberOfEntries, 1, -1, durableClientVM);

    // Stop the durable client
    this.durableClientVM.invoke(() -> CacheServerTestUtil.closeCache(Boolean.TRUE));

    // Verify the durable client still exists on the server
    verifyDurableClientPresent(DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT, durableClientId,
        server1VM);

    // Publish some more entries
    this.publisherClientVM.invoke(new CacheSerializableRunnable("Publish additional updates") {
      @Override
      public void run2() throws CacheException {
        // Get the region
        Region<String, String> region = CacheServerTestUtil.getCache().getRegion(regionName);
        assertNotNull(region);

        // Publish some entries
        for (int i = 0; i < numberOfEntries; i++) {
          String keyAndValue = String.valueOf(i);
          region.put(keyAndValue, keyAndValue + "lkj");
        }
      }
    });

    this.publisherClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Re-start the durable client
    this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClientFromXmlN(
        DurableClientTestBase.class.getResource("durablecq-client-cache.xml"), "client",
        durableClientId, DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT, Boolean.TRUE));

    // Durable client registers durable cq on server'
    registerInterest(durableClientVM, regionName, true, InterestResultPolicy.KEYS_VALUES);

    // Send clientReady message
    sendClientReady(this.durableClientVM);

    // Verify durable client on server
    verifyDurableClientPresent(DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT, durableClientId,
        server1VM);

    // Verify the durable client received the updates held for it on the server
    checkListenerEvents(numberOfEntries, 1, -1, durableClientVM);

    // Stop the durable client
    this.durableClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop the server
    this.server1VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
  }

  /**
   * Test functionality to close the durable client and drain all events from the ha queue from the
   * server
   */
  @Test
  public void testCloseCacheProxy() {
    String greaterThan5Query = "select * from /" + regionName + " p where p.ID > 5";
    String allQuery = "select * from /" + regionName + " p where p.ID > -1";
    String lessThan5Query = "select * from /" + regionName + " p where p.ID < 5";

    // Start a server
    server1Port = this.server1VM
        .invoke(() -> CacheServerTestUtil.createCacheServer(regionName, Boolean.TRUE));

    // Start a durable client that is kept alive on the server when it stops
    // normally
    durableClientId = getName() + "_client";
    startDurableClient(durableClientVM, durableClientId, server1Port, regionName);
    // register durable cqs
    createCq(durableClientVM, "GreaterThan5", greaterThan5Query, true);
    createCq(durableClientVM, "All", allQuery, true);
    createCq(durableClientVM, "LessThan5", lessThan5Query, true);
    // send client ready
    sendClientReady(durableClientVM);

    // Verify durable client on server
    verifyDurableClientPresent(DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT, durableClientId,
        server1VM);

    // Stop the durable client
    this.disconnectDurableClient(true);

    // Start normal publisher client
    startClient(publisherClientVM, server1Port, regionName);

    // Publish some entries
    publishEntries(regionName, 10);

    // verify cq stats are correct
    checkNumDurableCqs(server1VM, durableClientId, 3);
    checkCqStatOnServer(server1VM, durableClientId, "All", 10);
    checkCqStatOnServer(server1VM, durableClientId, "GreaterThan5", 4);
    checkCqStatOnServer(server1VM, durableClientId, "LessThan5", 5);

    // drop client proxy
    this.server1VM.invoke(
        new CacheSerializableRunnable("Close client proxy on server for client" + durableClientId) {
          @Override
          public void run2() throws CacheException {

            final CacheClientNotifier ccnInstance = CacheClientNotifier.getInstance();

            ccnInstance.closeDurableClientProxy(durableClientId);
          }
        });

    // Restart the durable client
    startDurableClient(durableClientVM, durableClientId, server1Port, regionName);

    // check that cqs are no longer registered
    checkNumDurableCqs(server1VM, durableClientId, 0);

    // Reregister durable cqs
    createCq(durableClientVM, "GreaterThan5", "select * from /" + regionName + " p where p.ID > 5",
        true);
    createCq(durableClientVM, "All", "select * from /" + regionName + " p where p.ID > -1", true);
    createCq(durableClientVM, "LessThan5", "select * from /" + regionName + " p where p.ID < 5",
        true);

    // Before sending client ready, lets make sure the stats already reflect 0 queued events
    checkCqStatOnServer(server1VM, durableClientId, "LessThan5", 0);
    checkCqStatOnServer(server1VM, durableClientId, "GreaterThan5", 0);
    checkCqStatOnServer(server1VM, durableClientId, "All", 0);

    // send client ready
    sendClientReady(durableClientVM);

    // verify cq events for all 3 cqs are 0 events
    checkCqListenerEvents(durableClientVM, "GreaterThan5", 0 /* numEventsExpected */,
        /* numEventsToWaitFor */ 5/* secondsToWait */);
    checkCqListenerEvents(durableClientVM, "LessThan5", 0 /* numEventsExpected */,
        /* numEventsToWaitFor */ 5/* secondsToWait */);
    checkCqListenerEvents(durableClientVM, "All", 0 /* numEventsExpected */,
        /* numEventsToWaitFor */ 5/* secondsToWait */);

    // Stop the durable client
    this.durableClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop the publisher client
    this.publisherClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop the server
    this.server1VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
  }

  /**
   * Test that starting a durable client on multiple servers is processed correctly.
   */
  @Test
  public void testSimpleDurableClientMultipleServers() {
    // Start server 1
    server1Port = this.server1VM.invoke(
        () -> CacheServerTestUtil.createCacheServer(regionName, Boolean.TRUE));

    // Start server 2 using the same mcast port as server 1
    final int server2Port = this.server2VM
        .invoke(() -> CacheServerTestUtil.createCacheServer(regionName, Boolean.TRUE));

    // Start a durable client connected to both servers that is kept alive when
    // it stops normally

    durableClientId = getName() + "_client";
    this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
        getClientPool(getServerHostName(), server1Port, server2Port, true),
        regionName,
        getClientDistributedSystemProperties(durableClientId, VERY_LONG_DURABLE_TIMEOUT_SECONDS),
        Boolean.TRUE));

    // Send clientReady message
    sendClientReady(this.durableClientVM);

    // Verify durable client on server 1
    verifyDurableClientPresence(VERY_LONG_DURABLE_TIMEOUT_SECONDS, durableClientId, server1VM, 1);

    // Verify durable client on server 2
    verifyDurableClientPresence(VERY_LONG_DURABLE_TIMEOUT_SECONDS, durableClientId, server2VM, 1);

    // Stop the durable client
    this.durableClientVM.invoke(() -> CacheServerTestUtil.closeCache(Boolean.TRUE));

    // Verify the durable client is still on server 1
    verifyDurableClientPresence(VERY_LONG_DURABLE_TIMEOUT_SECONDS, durableClientId, server1VM, 1);

    // Verify the durable client is still on server 2
    verifyDurableClientPresence(VERY_LONG_DURABLE_TIMEOUT_SECONDS, durableClientId, server2VM, 1);

    // Start up the client again. This time initialize it so that it is not kept
    // alive on the servers when it stops normally.
    this.durableClientVM.invoke(() -> CacheServerTestUtil.createCacheClient(
        getClientPool(getServerHostName(), server1Port, server2Port, true),
        regionName, getClientDistributedSystemProperties(durableClientId), Boolean.TRUE));

    // Send clientReady message
    sendClientReady(this.durableClientVM);

    // Verify durable client on server1
    verifyDurableClientPresence(DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT, durableClientId,
        server1VM, 1);

    // Verify durable client on server2
    verifyDurableClientPresence(DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT, durableClientId,
        server2VM, 1);

    // Stop the durable client
    this.durableClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    this.verifyDurableClientPresence(DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT,
        durableClientId, server1VM, 0);

    this.verifyDurableClientPresence(DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT,
        durableClientId, server2VM, 0);

    // Stop server 1
    this.server1VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop server 2
    this.server2VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
  }

  @Test
  public void testDurableClientReceivedClientSessionInitialValue() {
    // Start server 1
    server1Port = this.server1VM
        .invoke(() -> CacheServerTestUtil.createCacheServer(regionName, Boolean.TRUE));

    // Start server 2
    int server2Port = this.server2VM
        .invoke(() -> CacheServerTestUtil.createCacheServer(regionName, Boolean.TRUE));

    // Start normal publisher client
    this.publisherClientVM.invoke(() -> CacheServerTestUtil
        .createCacheClient(getClientPool(getServerHostName(),
            server1Port, server2Port, false), this.regionName));

    // Create an entry
    publishEntries(0, 1);

    // Start a durable client with the ControlListener
    durableClientId = getName() + "_client";
    startupDurableClient(VERY_LONG_DURABLE_TIMEOUT_SECONDS,
        getClientPool(getServerHostName(), server1Port, server2Port,
            true),
        Boolean.TRUE);

    // Use ClientSession on the server to ` in entry key on behalf of durable client
    boolean server1IsPrimary = false;
    boolean registered = this.server1VM.invoke(() -> DurableClientSimpleDUnitTest
        .registerInterestWithClientSession(durableClientId, this.regionName, String.valueOf(0)));
    if (registered) {
      server1IsPrimary = true;
    } else {
      registered = this.server2VM.invoke(() -> DurableClientSimpleDUnitTest
          .registerInterestWithClientSession(durableClientId, this.regionName, String.valueOf(0)));
    }
    assertThat(registered)
        .describedAs("ClientSession interest registration failed to occur in either server.")
        .isTrue();

    // Verify durable client received create event
    checkListenerEvents(1, 1, TYPE_CREATE, this.durableClientVM);

    // Wait for QRM to be processed on the secondary
    waitForEventsRemovedByQueueRemovalMessage(server1IsPrimary ? this.server2VM : this.server1VM,
        durableClientId, 2);

    // Stop durable client
    disconnectDurableClient(true);

    // restart durable client
    restartDurableClient(VERY_LONG_DURABLE_TIMEOUT_SECONDS,
        getClientPool(getServerHostName(), server1Port, server2Port, true), Boolean.TRUE);

    // Verify durable client does not receive create event
    checkListenerEvents(0, 1, TYPE_CREATE, this.durableClientVM);

    // Stop the durable client
    this.durableClientVM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop server 1
    this.server1VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);

    // Stop server 2
    this.server2VM.invoke((SerializableRunnableIF) CacheServerTestUtil::closeCache);
  }

  private static boolean registerInterestWithClientSession(String durableClientId,
      String regionName,
      Object keyOfInterest) {
    ClientSession session = getBridgeServer().getClientSession(durableClientId);
    boolean registered = false;
    if (session.isPrimary()) {
      session.registerInterest(regionName, keyOfInterest, InterestResultPolicy.KEYS_VALUES, true,
          true);
      registered = true;
    }
    return registered;
  }

  private void waitForEventsRemovedByQueueRemovalMessage(VM secondaryServerVM,
      final String durableClientId,
      final int numEvents) {
    secondaryServerVM.invoke(() -> DurableClientSimpleDUnitTest
        .waitForEventsRemovedByQueueRemovalMessage(durableClientId, numEvents));
  }

  private static void waitForEventsRemovedByQueueRemovalMessage(String durableClientId,
      final int numEvents) {
    CacheClientNotifier ccn = CacheClientNotifier.getInstance();
    CacheClientProxy ccp = ccn.getClientProxy(durableClientId);
    HARegionQueue haRegionQueue = ccp.getHARegionQueue();
    HARegionQueueStats haRegionQueueStats = haRegionQueue.getStatistics();
    Awaitility.await().atMost(10 * HEAVY_TEST_LOAD_DELAY_SUPPORT_MULTIPLIER, TimeUnit.SECONDS)
        .untilAsserted(
            () -> assertEquals(
                "Expected queue removal messages: " + numEvents + " but actual messages: "
                    + haRegionQueueStats.getEventsRemovedByQrm(),
                numEvents, haRegionQueueStats.getEventsRemovedByQrm()));
  }
}


text:
import clr
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager

inputdoc = UnwrapElement(IN[1])
if inputdoc == None:
	doc = DocumentManager.Instance.CurrentDBDocument
elif inputdoc.GetType().ToString() == "Autodesk.Revit.DB.RevitLinkInstance":
	doc = inputdoc.GetLinkDocument()
elif inputdoc.GetType().ToString() == "Autodesk.Revit.DB.Document":
	doc = inputdoc
else: doc = None

elementlist = list()
projinfo = doc.ProjectInformation
elementlist.append(projinfo.OrganizationName)
elementlist.append(projinfo.OrganizationDescription)
elementlist.append(projinfo.BuildingName)
# this property seems to be missing in some files - weird...
try:
	elementlist.append(projinfo.Author)
except:
	elementlist.append(None)
elementlist.append(projinfo.IssueDate)
elementlist.append(projinfo.Status)
elementlist.append(projinfo.ClientName)
elementlist.append(projinfo.Address)
elementlist.append(projinfo.Name)
elementlist.append(projinfo.Number)
OUT = elementlist


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema,
	validators = require('mongoose-validators');

/**
 * Partner Schema
 */
var PartnerSchema = new Schema({
	name: {
		type: String,
		default: '',
		required: 'Please list the company name',
		trim: true
	},

	type: {
		type: String,
		default: '',
		enum: ['NEXUS', 'Agency', 'Solution Provider'],
		required: true,
		trim: true
	},

	logo: {
		type: String,
		description: 'Filename'
	},

	/* content script */
	overview: {
		type: String,
		description: 'Overview of the Parter\'s Product',
	},
	valueAdd: {
		type: String,
		description: 'How does Gigya add value?'

	},
	implementation: {
		type: String,
		description: 'One- or two-paragraph description of implementation/integration details'
	},
	developerPageURL: {
		type: String,
		trim: true,
		validate: [ validators.isURL() ]
	},

	created: {
		type: Date,
		default: Date.now
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	}
});

mongoose.model('Partner', PartnerSchema);


text:
import os
import argparse

import alphatwirl
import alphatwirl.heppyresult as HeppyResult
HeppyResult.componentHasTheseFiles[:] = ['roctree']

##__________________________________________________________________||
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--outDir', default = os.path.join('tbl', 'out'))
parser.add_argument('-n', '--nevents', default = -1, type = int, help = 'maximum number of events to process for each component')
parser.add_argument('--max-events-per-process', default = -1, type = int, help = 'maximum number of events per process')

configurer = alphatwirl.AlphaTwirlConfigurerFromArgs()
configurer.add_arguments(parser)

args = parser.parse_args()

cfg = configurer.configure(args)
alphaTwirl = alphatwirl.AlphaTwirl(config = cfg)

##__________________________________________________________________||
analyzerName = 'roctree'
fileName = 'tree.root'
treeName = 'tree'

##__________________________________________________________________||
tbl_xsec_path = os.path.join(args.outDir, 'tbl_xsec.txt')
tblXsec = heppyresult.TblComponentConfig(
    outPath = tbl_xsec_path,
    columnNames = ('xsec', ),
    keys = ('xSection', ),
)
alphaTwirl.addComponentReader(tblXsec)

tbl_nevt_path = os.path.join(args.outDir, 'tbl_nevt.txt')
tblNevt = heppyresult.TblCounter(
    outPath = tbl_nevt_path,
    columnNames = ('nevt', 'nevt_sumw'),
    analyzerName = 'skimAnalyzerCount',
    fileName = 'SkimReport.txt',
    levels = ('All Events', 'Sum Weights')
)
alphaTwirl.addComponentReader(tblNevt)

##__________________________________________________________________||
from alphatwirl.binning import RoundLog
tblcfg = [
    dict(
        keyAttrNames = ('met_pt', ),
        binnings = (RoundLog(0.1, 10), ),
        keyOutColumnNames = ('met', ),
     )
]

tableConfigCompleter = alphatwirl.configure.TableConfigCompleter(
    defaultSummaryClass = alphatwirl.summary.Count,
    defaultOutDir = args.outDir,
    createOutFileName = alphatwirl.configure.TableFileNameComposer()
)
tblcfg = [tableConfigCompleter.complete(c) for c in tblcfg]

reader_collector_pair = [alphatwirl.configure.build_counter_collector_pair(c) for c in tblcfg]
reader = alphatwirl.loop.ReaderComposite()
collector = alphatwirl.loop.CollectorComposite(alphaTwirl.progressMonitor.createReporter())
for r, c in reader_collector_pair:
    reader.add(r)
    collector.add(c)
eventLoopRunner = alphatwirl.loop.MPEventLoopRunner(alphaTwirl.communicationChannel)
eventBuilder = alphatwirl.heppyresult.EventBuilder(analyzerName, fileName, treeName, args.nevents)
eventReader = alphatwirl.loop.EventsInDatasetReader(eventBuilder, eventLoopRunner, reader, collector, args.max_events_per_process)
alphaTwirl.addComponentReader(eventReader)

alphaTwirl.run()
alphaTwirl.end()

##__________________________________________________________________||
import pandas as pd

##__________________________________________________________________||
d1 = pd.read_table(os.path.join(args.outDir, 'tbl_process.txt'), delim_whitespace = True)
d2 = pd.read_table(os.path.join(args.outDir, 'tbl_xsec.txt'), delim_whitespace = True)

d = pd.merge(d1, d2)
d = d[['phasespace', 'xsec']].drop_duplicates()

f = open(os.path.join(args.outDir, 'tbl_xsec.txt'), 'w')
d.to_string(f, index = False)
f.write("\n")
f.close()

##__________________________________________________________________||


text:
class ChangeCourseTargetGroupToText < ActiveRecord::Migration[5.1]
  def change
    change_column :courses, :target_group, :text
  end
end


text:
define('service/cpStyle', [
], function(
){

    var id = 'cp_style_id',
        alreadyAdded = {};

    document.head.innerHTML += '<style id="'+id+'"></style>';
    var el = document.getElementById(id);

    return function(ngModule){
        ngModule
            .service('cpStyle', function(){
                return function(cpCtrlName, styleStr){
                    if(!cpCtrlName)
                        throw 'cpCtrlName must be defined';
                    if(typeof styleStr === 'undefined' || styleStr === null)
                        throw 'styleStr must be defined';
                    if(alreadyAdded[cpCtrlName])
                        return;
                    el.innerHTML += styleStr + ' ';
                    alreadyAdded[cpCtrlName] = true;
                };
            });
    }
});


text:
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^', include('localedb.urls')),
)


text:
<title>Overview - Untitled</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Untitled">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="prev" href="index.html#Top" title="Top">
<link rel="next" href="BFD-front-end.html#BFD-front-end" title="BFD front end">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: BFD front end,
Previous: Top,
Up: Top

1 Introduction

BFD is a package which allows applications to use the
same routines to operate on object files whatever the object file
format.  A new object file format can be supported simply by
creating a new BFD back end and adding it to the library.

BFD is split into two parts: the front end, and the back ends (one for
each object file format).

The front end of BFD provides the interface to the user. It manages
memory and various canonical data structures. The front end also
decides which back end to use and when to call back end routines.

The back ends provide BFD its view of the real world. Each back
end provides a set of calls which the BFD front end can use to maintain
its canonical form. The back ends also may keep around information for
their own use, for greater efficiency.

History: 			History

How It Works: 		How It Works

What BFD Version 2 Can Do: 	What BFD Version 2 Can Do


text:
@extends('layouts.no_nav')
@section('content')

                @if(file_exists(base_path("/public/assets/images/logo.png")))

                @else

                @endif

{{trans("headers.newPassword",[],$language)}}

                            {{trans("register.resetDescription",[],$language)}}

                        {!! Form::open(['action' => ['AuthenticationController@updateContactWithNewPassword', 'token' => $passwordReset->token], 'id' => 'passwordResetForm', 'method' => 'post']) !!}

                            {{trans("register.email",[],$language)}}
                            {!! Form::email("email",null,['id' => 'email', 'class' => 'form-control', 'placeholder' => trans("register.email",[],$language)]) !!}

                            {{trans("register.password",[],$language)}}
                            {!! Form::password("password",['id' => 'password', 'class' => 'form-control', 'placeholder' => trans("register.password",[],$language)]) !!}

                            {{trans("register.confirmPassword",[],$language)}}
                            {!! Form::password("password_confirmation",['id' => 'password_confirmation', 'class' => 'form-control', 'placeholder' => trans("register.confirmPassword",[],$language)]) !!}

                        <button type="submit" class="btn btn-primary">{{trans("actions.resetPassword",[],$language)}}</button>
                        {!! Form::close() !!}

                    {{trans("register.back",[],$language)}}

@endsection
@section('additionalJS')
    {!! JsValidator::formRequest('App\Http\Requests\PasswordUpdateRequest','#passwordResetForm') !!}
@endsection
@section('additionalCSS')
    <link rel="stylesheet" href="/assets/css/pages/index.css">
@endsection


text:
using Neo4j.NDP.CSharpDriver.Extensions;
using Neo4j.NDP.CSharpDriver.Logging;
using Neo4j.NDP.CSharpDriver.Serialization;
using System;
using System.Collections.Generic;
using System.Net.Sockets;

namespace Neo4j.NDP.CSharpDriver
{
    public class Neo4jService
    {
        private readonly ILogger logger;
        IBitConverter bitConverter = new BigEndianTargetBitConverter();
        // TODO: This should be injected

        public Neo4jService(ILogger logger = null)
        {
            this.logger = logger;
        }

        public IConnection CreateConnection(string host, int portNumber)
        {
            logger.Info("Connecting to {0}:{1}", host, portNumber);
            TcpClient client = null;
            NetworkStream stream = null;
            try
            {
                client = new TcpClient(host, portNumber);
                stream = client.GetStream();
                logger.Info("Connected to {0}:{1}", host, portNumber);

                int agreedVersion = DoHandshake(stream);
                if (agreedVersion == 1)
                {
                    logger.Info("Protocol version {0} agreed", agreedVersion);
                    IConnection connection = new Connection(client, stream, logger);
                    return connection;
                }
                else
                {
                    logger.Warn("Closing connection as no protocol version could be agreed");
                    Cleanup(client, stream);
                    return null;
                }

            }

            catch (SocketException ex)
            {
                logger.Info("Shutting down and closing connection due to the error: {0}", ex.Message);
                Cleanup(client, stream);
                throw;
            }
            catch (Exception ex) // TODO: Find possible connections
            {
                logger.Info("Shutting down and closing connection due to the error: {0}", ex.Message);
                Cleanup(client, stream);
                throw;
            }

        }

        private void Cleanup(TcpClient client, NetworkStream stream)
        {
            if (stream != null)
            {
                stream.Dispose();
            }

            if (client != null)
            {
                ((IDisposable)client).Dispose();
            }
        }

        private int DoHandshake(NetworkStream stream)
        {
            // Send details of the protocol versions supported
            int[] supportedVersion = new int[] { 1, 0, 0, 0 };
            // Are there more than one supported version, and how are this send?
            logger.Info("Supported protocol versions are: " + supportedVersion.ToReadableString());
            byte[] data = PackVersions(supportedVersion);
            logger.Debug("Sending handshake: " + data.ToReadableString());
            stream.Write(data);

            // Handle the handshake response
            data = new byte[4];
            stream.Read(data, 0, 4);
            logger.Debug("Received handshake data: " + data.ToReadableString());
            int agreedVersion = GetAgreedVersion(data);

            return agreedVersion;
        }

        private byte[] PackVersions(IEnumerable<int> versions)
        {
            List<byte> bytes = new List<byte>();
            foreach (int version in versions)
            {
                bytes.AddRange(bitConverter.GetBytes(version));
            }
            return bytes.ToArray();
        }

        private int GetAgreedVersion(byte[] data)
        {
            return bitConverter.ToInt32(data);
        }
    }
}


text:
using System;

namespace WebExtras.JQFlot.Graphs
{
  /// <summary>
  /// line options
  /// </summary>
  [Serializable]
  public class LineGraph : BaseGraph
  {
    /// <summary>
    /// Specifies whether chart should normally start from zero.
    /// </summary>
    public bool? zero;

    /// <summary>
    /// Whether two adjacent points are connected with a straight line or a
    /// step i.e a horizontal line followed by a vertical line
    /// </summary>
    public bool? steps;
  }
}