text:
package eu.smartenit.sbox.web;

import java.io.Serializable;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import eu.smartenit.sbox.db.dao.BGRouterDAO;
import eu.smartenit.sbox.db.dao.LinkDAO;
import eu.smartenit.sbox.db.dto.BGRouter;
import eu.smartenit.sbox.db.dto.Link;
import eu.smartenit.sbox.db.dto.NetworkAddressIPv4;
import eu.smartenit.sbox.db.dto.Segment;
import eu.smartenit.sbox.db.dto.SimpleLinkID;
import eu.smartenit.sbox.web.util.WebUtils;

/**
 * The LinksBean bean class.
 *
 * It is the controlling class of the links.xhtml page.
 *
 * @author George Petropoulos
 * @version 1.2
 *
 */
@ManagedBean
@ViewScoped
public class LinksBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory
			.getLogger(LinksBean.class);

	private BGRouterDAO bgdao;

	private LinkDAO linkdao;

	@PostConstruct
	public void init() {
		linkdao = new LinkDAO();
		bgdao = new BGRouterDAO();

		link = new Link();
		link.setLinkID(new SimpleLinkID());
		segment = new Segment();

		linksList = linkdao.findAll();
		bgRoutersList = bgdao.findAll();
		bgRoutersArray = WebUtils.listToArray(BGRouter.class, bgRoutersList);
		editable = true;
		insertLink = true;

		logger.debug("Navigating to links page.");
	}

	public boolean editable = true;

	public boolean isEditable() {
		return editable;
	}

	public void setEditable(boolean editable) {
		this.editable = editable;
	}

	/**
	 * Links-page relevant parameters and functions.
	 *
	 */

	public Link link;
	public List<Link> linksList;
	public List<BGRouter> bgRoutersList;
	public BGRouter[] bgRoutersArray;
	public String selectedBGRouter;
	public Segment segment;
	public boolean insertLink = true;

	public Segment getSegment() {
		return segment;
	}

	public void setSegment(Segment segment) {
		this.segment = segment;
	}

	public Link getLink() {
		return link;
	}

	public void setLink(Link link) {
		this.link = link;
	}

	public List<Link> getLinksList() {
		return linksList;
	}

	public void setLinksList(List<Link> linksList) {
		this.linksList = linksList;
	}

	public BGRouter[] getBgRoutersArray() {
		return bgRoutersArray;
	}

	public void setBgRoutersArray(BGRouter[] bgRoutersArray) {
		this.bgRoutersArray = bgRoutersArray;
	}

	public String getSelectedBGRouter() {
		return selectedBGRouter;
	}

	public void setSelectedBGRouter(String selectedBGRouter) {
		this.selectedBGRouter = selectedBGRouter;
	}

	public List<BGRouter> getBgRoutersList() {
		return bgRoutersList;
	}

	public void setBgRoutersList(List<BGRouter> bgRoutersList) {
		this.bgRoutersList = bgRoutersList;
	}

	/**
	 * The method that inserts/updates a Link to the db.
	 *
	 */
	public String updateLink() {
		logger.debug("Updating Link " + link.getLinkID() + ".");
		BGRouter bgRouter = new BGRouter();
		bgRouter.setManagementAddress(new NetworkAddressIPv4(selectedBGRouter,
				0));
		link.setBgRouter(bgRouter);

		link.getCostFunction().setType("Cost-function");
		link.getCostFunction().setInputUnit("bps");
		link.getCostFunction().setOutputUnit("euros");
		if (insertLink) {
			try {
				linkdao.insert(link);
			} catch (Exception e) {
				logger.warn("Error while inserting link to database. "
						+ "Probably primary key already exists.");
			}
		} else {
			try {
				linkdao.update(link);
			} catch (Exception e) {
				logger.warn("Error while updating link to database. "
						+ "Probably primary key already exists.");
			}
		}

		linksList = linkdao.findAll();

		link = new Link();
		link.setLinkID(new SimpleLinkID());
		editable = true;
		segment = new Segment();

		logger.debug("Link " + link + " was successfully updated.");
		return "links";
	}

	/**
	 * The method that edits a Link.
	 *
	 */
	public void editLink(Link l) {
		logger.debug("Editing Link " + l + ".");
		link = l;
		editable = false;
		insertLink = false;
	}

	/**
	 * The method that deletes a Link from the db.
	 *
	 */
	public String deleteLink(Link l) {
		logger.debug("Deleting Link " + l.getLinkID() + ".");
		linkdao.deleteById((SimpleLinkID) l.getLinkID());
		linksList = linkdao.findAll();
		link = new Link();
		link.setLinkID(new SimpleLinkID());
		editable = true;
		logger.debug("Link " + l.getLinkID() + " was successfully deleted.");
		return "links";
	}

	/**
	 * The method that adds a Segment to the list of link's segments.
	 *
	 */
	public void addSegment() {
		logger.debug("Adding segment " + segment + ".");
		link.getCostFunction().getSegments().add(segment);
		segment = new Segment();
	}

	/**
	 * The method that deletes a Segment from the list of link's segments.
	 *
	 */
	public void deleteSegment(Segment s) {
		logger.debug("Deleting segment " + s + ".");
		link.getCostFunction().getSegments().remove(s);
	}

}


text:
package fahem.belili.eventmgr.entities;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;

@Entity
@Table(name="events")
public class Event implements Serializable {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private long id;

	@NotEmpty
	@Size(min=3, max=25)
	private String title;

	private String summary;

	// date de l'event
	@NotEmpty
	private Date date;

	// card
	@ManyToMany // participants<-->events
	private Collection<Participant> participants;

	/*
	many event to one participant. un participant peut créer 0,* events & un event est créé par 1seul participant
	*/
	@ManyToOne
	@NotEmpty
	private Participant participant;

	public Event() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Event(long id, String title, String summary, Date date) {
		super();
		this.title = title;
		this.summary = summary;
		this.date = date;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getSummary() {
		return summary;
	}

	public void setSummary(String summary) {
		this.summary = summary;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public Collection<Participant> getParticipants() {
		return participants;
	}

	public void setParticipants(Collection<Participant> participants) {
		this.participants = participants;
	}

	public Participant getParticipant() {
		return participant;
	}

	public void setParticipant(Participant participant) {
		this.participant = participant;
	}

}

redpajama_set_name: RedPajamaGithub


text:
/* *
 *
 *  License: www.highcharts.com/license
 *
 *  !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
 *
 * */
'use strict';
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
import Chart from '../../../Core/Chart/Chart.js';
import RequiredIndicatorMixin from '../../../Mixins/IndicatorRequired.js';
import SeriesRegistry from '../../../Core/Series/SeriesRegistry.js';
var LineSeries = SeriesRegistry.seriesTypes.line;
import U from '../../../Core/Utilities.js';
var addEvent = U.addEvent, error = U.error, extend = U.extend, isArray = U.isArray, merge = U.merge, pick = U.pick, splat = U.splat;
import './SMAComposition.js';
var generateMessage = RequiredIndicatorMixin.generateMessage;
/* *
 *
 *  Class
 *
 * */
/**
 * The SMA series type.
 *
 * @private
 */
var SMAIndicator = /** @class */ (function (_super) {
    __extends(SMAIndicator, _super);
    function SMAIndicator() {
        /* *
         *
         *  Static Properties
         *
         * */
        var _this = _super !== null && _super.apply(this, arguments) || this;
        /* *
         *
         *  Properties
         *
         * */
        _this.data = void 0;
        _this.dataEventsToUnbind = void 0;
        _this.linkedParent = void 0;
        _this.options = void 0;
        _this.points = void 0;
        return _this;
        /* eslint-enable valid-jsdoc */
    }
    /* *
     *
     *  Functions
     *
     * */
    /* eslint-disable valid-jsdoc */
    /**
     * @private
     */
    SMAIndicator.prototype.destroy = function () {
        this.dataEventsToUnbind.forEach(function (unbinder) {
            unbinder();
        });
        _super.prototype.destroy.apply(this, arguments);
    };
    /**
     * @private
     */
    SMAIndicator.prototype.getName = function () {
        var name = this.name, params = [];
        if (!name) {
            (this.nameComponents || []).forEach(function (component, index) {
                params.push(this.options.params[component] +
                    pick(this.nameSuffixes[index], ''));
            }, this);
            name = (this.nameBase || this.type.toUpperCase()) +
                (this.nameComponents ? ' (' + params.join(', ') + ')' : '');
        }
        return name;
    };
    /**
     * @private
     */
    SMAIndicator.prototype.getValues = function (series, params) {
        var period = params.period, xVal = series.xData, yVal = series.yData, yValLen = yVal.length, range = 0, sum = 0, SMA = [], xData = [], yData = [], index = -1, i, SMAPoint;
        if (xVal.length < period) {
            return;
        }
        // Switch index for OHLC / Candlestick / Arearange
        if (isArray(yVal[0])) {
            index = params.index ? params.index : 0;
        }
        // Accumulate first N-points
        while (range < period - 1) {
            sum += index < 0 ? yVal[range] : yVal[range][index];
            range++;
        }
        // Calculate value one-by-one for each period in visible data
        for (i = range; i < yValLen; i++) {
            sum += index < 0 ? yVal[i] : yVal[i][index];
            SMAPoint = [xVal[i], sum / period];
            SMA.push(SMAPoint);
            xData.push(SMAPoint[0]);
            yData.push(SMAPoint[1]);
            sum -= (index < 0 ?
                yVal[i - range] :
                yVal[i - range][index]);
        }
        return {
            values: SMA,
            xData: xData,
            yData: yData
        };
    };
    /**
     * @private
     */
    SMAIndicator.prototype.init = function (chart, options) {
        var indicator = this, requiredIndicators = indicator.requireIndicators();
        // Check whether all required indicators are loaded.
        if (!requiredIndicators.allLoaded) {
            return error(generateMessage(indicator.type, requiredIndicators.needed));
        }
        _super.prototype.init.call(indicator, chart, options);
        // Only after series are linked indicator can be processed.
        var linkedSeriesUnbiner = addEvent(Chart, 'afterLinkSeries', function () {
            var hasEvents = !!indicator.dataEventsToUnbind.length;
            if (indicator.linkedParent) {
                if (!hasEvents) {
                    indicator.dataEventsToUnbind.push(addEvent(indicator.bindTo.series ?
                        indicator.linkedParent :
                        indicator.linkedParent.xAxis, indicator.bindTo.eventName, function () {
                        indicator.recalculateValues();
                    }));
                }
                if (indicator.calculateOn === 'init') {
                    if (!indicator.processedYData) {
                        indicator.recalculateValues();
                    }
                }
                else {
                    if (!hasEvents) {
                        var unbinder_1 = addEvent(indicator.chart, indicator.calculateOn, function () {
                            indicator.recalculateValues();
                            // Call this just once, on init
                            unbinder_1();
                        });
                    }
                }
            }
            else {
                return error('Series ' +
                    indicator.options.linkedTo +
                    ' not found! Check `linkedTo`.', false, chart);
            }
        }, {
            order: 0
        });
        // Make sure we find series which is a base for an indicator
        // chart.linkSeries();
        indicator.dataEventsToUnbind = [];
        indicator.eventsToUnbind.push(linkedSeriesUnbiner);
    };
    /**
     * @private
     * @return {void}
     */
    SMAIndicator.prototype.recalculateValues = function () {
        var indicator = this, oldData = indicator.points || [], oldDataLength = (indicator.xData || []).length, processedData = (indicator.getValues(indicator.linkedParent, indicator.options.params) || {
            values: [],
            xData: [],
            yData: []
        }), croppedDataValues = [], overwriteData = true, oldFirstPointIndex, oldLastPointIndex, croppedData, min, max, i;
        // We need to update points to reflect changes in all,
        // x and y's, values. However, do it only for non-grouped
        // data - grouping does it for us (#8572)
        if (oldDataLength &&
            !indicator.hasGroupedData &&
            indicator.visible &&
            indicator.points) {
            // When data is cropped update only avaliable points (#9493)
            if (indicator.cropped) {
                if (indicator.xAxis) {
                    min = indicator.xAxis.min;
                    max = indicator.xAxis.max;
                }
                croppedData = indicator.cropData(processedData.xData, processedData.yData, min, max);
                for (i = 0; i < croppedData.xData.length; i++) {
                    // (#10774)
                    croppedDataValues.push([
                        croppedData.xData[i]
                    ].concat(splat(croppedData.yData[i])));
                }
                oldFirstPointIndex = processedData.xData.indexOf(indicator.xData[0]);
                oldLastPointIndex = processedData.xData.indexOf(indicator.xData[indicator.xData.length - 1]);
                // Check if indicator points should be shifted (#8572)
                if (oldFirstPointIndex === -1 &&
                    oldLastPointIndex === processedData.xData.length - 2) {
                    if (croppedDataValues[0][0] === oldData[0].x) {
                        croppedDataValues.shift();
                    }
                }
                indicator.updateData(croppedDataValues);
                // Omit addPoint() and removePoint() cases
            }
            else if (processedData.xData.length !== oldDataLength - 1 &&
                processedData.xData.length !== oldDataLength + 1) {
                overwriteData = false;
                indicator.updateData(processedData.values);
            }
        }
        if (overwriteData) {
            indicator.xData = processedData.xData;
            indicator.yData = processedData.yData;
            indicator.options.data = processedData.values;
        }
        // Removal of processedXData property is required because on
        // first translate processedXData array is empty
        if (indicator.bindTo.series === false) {
            delete indicator.processedXData;
            indicator.isDirty = true;
            indicator.redraw();
        }
        indicator.isDirtyData = false;
    };
    /**
     * @private
     */
    SMAIndicator.prototype.processData = function () {
        var series = this, compareToMain = series.options.compareToMain, linkedParent = series.linkedParent;
        _super.prototype.processData.apply(series, arguments);
        if (linkedParent && linkedParent.compareValue && compareToMain) {
            series.compareValue = linkedParent.compareValue;
        }
        return;
    };
    /**
     * @private
     */
    SMAIndicator.prototype.requireIndicators = function () {
        var obj = {
            allLoaded: true
        };
        // Check whether all required indicators are loaded, else return
        // the object with missing indicator's name.
        this.requiredIndicators.forEach(function (indicator) {
            if (SeriesRegistry.seriesTypes[indicator]) {
                SeriesRegistry.seriesTypes[indicator].prototype.requireIndicators();
            }
            else {
                obj.allLoaded = false;
                obj.needed = indicator;
            }
        });
        return obj;
    };
    /**
     * The parameter allows setting line series type and use OHLC indicators.
     * Data in OHLC format is required.
     *
     * @sample {highstock} stock/indicators/use-ohlc-data
     *         Use OHLC data format to plot line chart
     *
     * @type      {boolean}
     * @product   highstock
     * @apioption plotOptions.line.useOhlcData
     */
    /**
     * Simple moving average indicator (SMA). This series requires `linkedTo`
     * option to be set.
     *
     * @sample stock/indicators/sma
     *         Simple moving average indicator
     *
     * @extends      plotOptions.line
     * @since        6.0.0
     * @excluding    allAreas, colorAxis, dragDrop, joinBy, keys,
     *               navigatorOptions, pointInterval, pointIntervalUnit,
     *               pointPlacement, pointRange, pointStart, showInNavigator,
     *               stacking, useOhlcData
     * @product      highstock
     * @requires     stock/indicators/indicators
     * @optionparent plotOptions.sma
     */
    SMAIndicator.defaultOptions = merge(LineSeries.defaultOptions, {
        /**
         * The name of the series as shown in the legend, tooltip etc. If not
         * set, it will be based on a technical indicator type and default
         * params.
         *
         * @type {string}
         */
        name: void 0,
        tooltip: {
            /**
             * Number of decimals in indicator series.
             */
            valueDecimals: 4
        },
        /**
         * The main series ID that indicator will be based on. Required for this
         * indicator.
         *
         * @type {string}
         */
        linkedTo: void 0,
        /**
         * Whether to compare indicator to the main series values
         * or indicator values.
         *
         * @sample {highstock} stock/plotoptions/series-comparetomain/
         *         Difference between comparing SMA values to the main series
         *         and its own values.
         *
         * @type {boolean}
         */
        compareToMain: false,
        /**
         * Paramters used in calculation of regression series' points.
         */
        params: {
            /**
             * The point index which indicator calculations will base. For
             * example using OHLC data, index=2 means the indicator will be
             * calculated using Low values.
             */
            index: 0,
            /**
             * The base period for indicator calculations. This is the number of
             * data points which are taken into account for the indicator
             * calculations.
             */
            period: 14
        }
    });
    return SMAIndicator;
}(LineSeries));
extend(SMAIndicator.prototype, {
    bindTo: {
        series: true,
        eventName: 'updatedData'
    },
    calculateOn: 'init',
    hasDerivedData: true,
    nameComponents: ['period'],
    nameSuffixes: [],
    // Defines on which other indicators is this indicator based on.
    requiredIndicators: [],
    useCommonDataGrouping: true
});
SeriesRegistry.registerSeriesType('sma', SMAIndicator);
/* *
 *
 *  Default Export
 *
 * */
export default SMAIndicator;
/* *
 *
 *  API Options
 *
 * */
/**
 * A `SMA` series. If the [type](#series.sma.type) option is not specified, it
 * is inherited from [chart.type](#chart.type).
 *
 * @extends   series,plotOptions.sma
 * @since     6.0.0
 * @product   highstock
 * @excluding dataParser, dataURL, useOhlcData
 * @requires  stock/indicators/indicators
 * @apioption series.sma
 */
''; // adds doclet above to the transpiled file


text:
package com.capitalone.dashboard.collector;

import com.capitalone.dashboard.model.CollectorItem;
import com.capitalone.dashboard.model.CollectorType;
import com.capitalone.dashboard.model.Environment;
import com.capitalone.dashboard.model.EnvironmentComponent;
import com.capitalone.dashboard.model.EnvironmentStatus;
import com.capitalone.dashboard.model.UDeployApplication;
import com.capitalone.dashboard.model.UDeployCollector;
import com.capitalone.dashboard.model.UDeployEnvResCompData;
import com.capitalone.dashboard.repository.BaseCollectorRepository;
import com.capitalone.dashboard.repository.ComponentRepository;
import com.capitalone.dashboard.repository.EnvironmentComponentRepository;
import com.capitalone.dashboard.repository.EnvironmentStatusRepository;
import com.capitalone.dashboard.repository.UDeployApplicationRepository;
import com.capitalone.dashboard.repository.UDeployCollectorRepository;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Collects {@link EnvironmentComponent} and {@link EnvironmentStatus} data from
 * {@link UDeployApplication}s.
 */
@Component
public class UDeployCollectorTask extends CollectorTask<UDeployCollector> {
    @SuppressWarnings({"unused", "PMD.UnusedPrivateField"})
    private static final Logger LOGGER = LoggerFactory.getLogger(UDeployCollectorTask.class);

    private final UDeployCollectorRepository uDeployCollectorRepository;
    private final UDeployApplicationRepository uDeployApplicationRepository;
    private final UDeployClient uDeployClient;
    private final UDeploySettings uDeploySettings;

    private final EnvironmentComponentRepository envComponentRepository;
    private final EnvironmentStatusRepository environmentStatusRepository;

    private final ComponentRepository dbComponentRepository;

    @Autowired
    public UDeployCollectorTask(TaskScheduler taskScheduler,
                                UDeployCollectorRepository uDeployCollectorRepository,
                                UDeployApplicationRepository uDeployApplicationRepository,
                                EnvironmentComponentRepository envComponentRepository,
                                EnvironmentStatusRepository environmentStatusRepository,
                                UDeploySettings uDeploySettings, UDeployClient uDeployClient,
                                ComponentRepository dbComponentRepository) {
        super(taskScheduler, "UDeploy");
        this.uDeployCollectorRepository = uDeployCollectorRepository;
        this.uDeployApplicationRepository = uDeployApplicationRepository;
        this.uDeploySettings = uDeploySettings;
        this.uDeployClient = uDeployClient;
        this.envComponentRepository = envComponentRepository;
        this.environmentStatusRepository = environmentStatusRepository;
        this.dbComponentRepository = dbComponentRepository;
    }

    @Override
    public UDeployCollector getCollector() {
        return UDeployCollector.prototype(uDeploySettings.getServers());
    }

    @Override
    public BaseCollectorRepository<UDeployCollector> getCollectorRepository() {
        return uDeployCollectorRepository;
    }

    @Override
    public String getCron() {
        return uDeploySettings.getCron();
    }

    @Override
    public void collect(UDeployCollector collector) {
        for (String instanceUrl : collector.getUdeployServers()) {

            logBanner(instanceUrl);

            long start = System.currentTimeMillis();

            clean(collector);

            addNewApplications(uDeployClient.getApplications(instanceUrl),
                    collector);
            updateData(enabledApplications(collector, instanceUrl));

            log("Finished", start);
        }
    }

    /**
     * Clean up unused deployment collector items
     *
     * @param collector the {@link UDeployCollector}
     */
    @SuppressWarnings("PMD.AvoidDeeplyNestedIfStmts")
    private void clean(UDeployCollector collector) {
        deleteUnwantedJobs(collector);
        Set<ObjectId> uniqueIDs = new HashSet<>();
        for (com.capitalone.dashboard.model.Component comp : dbComponentRepository
                .findAll()) {
            if (comp.getCollectorItems() == null || comp.getCollectorItems().isEmpty()) continue;
            List<CollectorItem> itemList = comp.getCollectorItems().get(
                    CollectorType.Deployment);
            if (itemList == null) continue;
            for (CollectorItem ci : itemList) {
                if (ci == null) continue;
                uniqueIDs.add(ci.getId());
            }
        }
        List<UDeployApplication> appList = new ArrayList<>();
        Set<ObjectId> udId = new HashSet< >();
        udId.add(collector.getId());
        for (UDeployApplication app : uDeployApplicationRepository.findByCollectorIdIn(udId)) {
            if (app != null) {
                app.setEnabled(uniqueIDs.contains(app.getId()));
                appList.add(app);
            }
        }
        uDeployApplicationRepository.save(appList);
    }

    private void deleteUnwantedJobs(UDeployCollector collector) {

        List<UDeployApplication> deleteAppList = new ArrayList<>();
        Set<ObjectId> udId = new HashSet<>();
        udId.add(collector.getId());
        for (UDeployApplication app : uDeployApplicationRepository.findByCollectorIdIn(udId)) {
            if (!collector.getUdeployServers().contains(app.getInstanceUrl()) ||
                    (!app.getCollectorId().equals(collector.getId()))) {
                deleteAppList.add(app);
            }
        }

        uDeployApplicationRepository.delete(deleteAppList);

    }

    private List<EnvironmentComponent> getEnvironmentComponent(List<UDeployEnvResCompData> dataList, Environment environment, UDeployApplication application) {
        List<EnvironmentComponent> returnList = new ArrayList<>();
        for (UDeployEnvResCompData data : dataList) {
            EnvironmentComponent component = new EnvironmentComponent();
            component.setComponentName(data.getComponentName());
            component.setCollectorItemId(data.getCollectorItemId());
            component.setComponentVersion(data
                    .getComponentVersion());
            component.setDeployed(data.isDeployed());
            component.setEnvironmentName(data
                    .getEnvironmentName());

            component.setEnvironmentName(environment.getName());
            component.setAsOfDate(data.getAsOfDate());
            String environmentURL = StringUtils.removeEnd(
                    application.getInstanceUrl(), "/")
                    + "/#environment/" + environment.getId();
            component.setEnvironmentUrl(environmentURL);

            returnList.add(component);
        }
        return returnList;
    }

    private List<EnvironmentStatus> getEnvironmentStatus(List<UDeployEnvResCompData> dataList) {
        List<EnvironmentStatus> returnList = new ArrayList<>();
        for (UDeployEnvResCompData data : dataList) {
            EnvironmentStatus status = new EnvironmentStatus();
            status.setCollectorItemId(data.getCollectorItemId());
            status.setComponentID(data.getComponentID());
            status.setComponentName(data.getComponentName());
            status.setEnvironmentName(data.getEnvironmentName());
            status.setOnline(data.isOnline());
            status.setResourceName(data.getResourceName());

            returnList.add(status);
        }
        return returnList;
    }

    /**
     * For each {@link UDeployApplication}, update the current
     * {@link EnvironmentComponent}s and {@link EnvironmentStatus}.
     *
     * @param uDeployApplications list of {@link UDeployApplication}s
     */
    private void updateData(List<UDeployApplication> uDeployApplications) {
        for (UDeployApplication application : uDeployApplications) {
            List<EnvironmentComponent> compList = new ArrayList<>();
            List<EnvironmentStatus> statusList = new ArrayList<>();
            long startApp = System.currentTimeMillis();

            for (Environment environment : uDeployClient
                    .getEnvironments(application)) {

                List<UDeployEnvResCompData> combinedDataList = uDeployClient
                        .getEnvironmentResourceStatusData(application,
                                environment);

                compList.addAll(getEnvironmentComponent(combinedDataList, environment, application));
                statusList.addAll(getEnvironmentStatus(combinedDataList));
            }
            if (!compList.isEmpty()) {
                List<EnvironmentComponent> existingComponents = envComponentRepository
                        .findByCollectorItemId(application.getId());
                envComponentRepository.delete(existingComponents);
                envComponentRepository.save(compList);
            }
            if (!statusList.isEmpty()) {
                List<EnvironmentStatus> existingStatuses = environmentStatusRepository
                        .findByCollectorItemId(application.getId());
                environmentStatusRepository.delete(existingStatuses);
                environmentStatusRepository.save(statusList);
            }

            log(" " + application.getApplicationName(), startApp);
        }
    }

    private List<UDeployApplication> enabledApplications(
            UDeployCollector collector, String instanceUrl) {
        return uDeployApplicationRepository.findEnabledApplications(
                collector.getId(), instanceUrl);
    }

    /**
     * Add any new {@link UDeployApplication}s.
     *
     * @param applications list of {@link UDeployApplication}s
     * @param collector    the {@link UDeployCollector}
     */
    private void addNewApplications(List<UDeployApplication> applications,
                                    UDeployCollector collector) {
        long start = System.currentTimeMillis();
        int count = 0;

        log("All apps", start, applications.size());
        for (UDeployApplication application : applications) {

            if (isNewApplication(collector, application)) {
                application.setCollectorId(collector.getId());
                application.setEnabled(false);
                application.setDescription(application.getApplicationName());
                try {
                    uDeployApplicationRepository.save(application);
                } catch (org.springframework.dao.DuplicateKeyException ce) {
                    log("Duplicates items not allowed", 0);

                }
                count++;
            }

        }
        log("New apps", start, count);
    }

    private boolean isNewApplication(UDeployCollector collector,
                                     UDeployApplication application) {
        return uDeployApplicationRepository.findUDeployApplication(
                collector.getId(), application.getInstanceUrl(),
                application.getApplicationId()) == null;
    }

    @SuppressWarnings("unused")
	private boolean changed(EnvironmentStatus status, EnvironmentStatus existing) {
        return existing.isOnline() != status.isOnline();
    }

    @SuppressWarnings("unused")
	private EnvironmentStatus findExistingStatus(
            final EnvironmentStatus proposed,
            List<EnvironmentStatus> existingStatuses) {

        return Iterables.tryFind(existingStatuses,
                new Predicate<EnvironmentStatus>() {
                    @Override
                    public boolean apply(EnvironmentStatus existing) {
                        return existing.getEnvironmentName().equals(
                                proposed.getEnvironmentName())
                                && existing.getComponentName().equals(
                                proposed.getComponentName())
                                && existing.getResourceName().equals(
                                proposed.getResourceName());
                    }
                }).orNull();
    }

    @SuppressWarnings("unused")
	private boolean changed(EnvironmentComponent component,
                            EnvironmentComponent existing) {
        return existing.isDeployed() != component.isDeployed()
                || existing.getAsOfDate() != component.getAsOfDate() || !existing.getComponentVersion().equalsIgnoreCase(component.getComponentVersion());
    }

    @SuppressWarnings("unused")
	private EnvironmentComponent findExistingComponent(
            final EnvironmentComponent proposed,
            List<EnvironmentComponent> existingComponents) {

        return Iterables.tryFind(existingComponents,
                new Predicate<EnvironmentComponent>() {
                    @Override
                    public boolean apply(EnvironmentComponent existing) {
                        return existing.getEnvironmentName().equals(
                                proposed.getEnvironmentName())
                                && existing.getComponentName().equals(
                                proposed.getComponentName());

                    }
                }).orNull();
    }
}


text:
#import "PFPingServer.h"

@implementation PFPingServer
{
  GCDAsyncSocket *_server;
  NSMutableArray *_clients;
}

- (instancetype)initWithPort:(NSUInteger)port
{
  if (self = [super init]) {
    _clients = [NSMutableArray array];
    _server = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

    NSError *error;
    if (![_server acceptOnPort:port error:&error]) {
      NSLog(@"Failed to listen on port %lu: %@", (unsigned long)port, error);
      return nil;
    }
  }
  return self;
}

- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
  [_clients addObject:newSocket];
  [newSocket readDataWithTimeout:-1 tag:0];
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
  [sock writeData:data withTimeout:-1 tag:0];
  [sock readDataWithTimeout:-1 tag:0];
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
  [_clients removeObject:sock];
}

- (NSInteger)clientsCount
{
  return [_clients count];
}

@end