text:
'use strict'

// external deps
var ObjectId = require("mongodb").ObjectId;

// internal deps
require('mongodb-toolkit');
var DLModels = require('dl-models');
var map = DLModels.map;
var PurchaseOrderExternal = DLModels.purchasing.PurchaseOrderExternal;
var PurchaseOrder = DLModels.purchasing.PurchaseOrder;
var uom = DLModels.master.Uom;
var PurchaseOrderManager = require('./purchase-order-manager');
var PurchaseRequestManager = require('./purchase-request-manager');
var CurrencyManager = require('../master/currency-manager');
var VatManager = require('../master/vat-manager');
var SupplierManager = require('../master/supplier-manager');
var ProductManager = require("../master/product-manager");
var BaseManager = require('module-toolkit').BaseManager;
var generateCode = require('../../utils/code-generator');
var i18n = require('dl-i18n');
var poStatusEnum = DLModels.purchasing.enum.PurchaseOrderStatus;
var prStatusEnum = DLModels.purchasing.enum.PurchaseRequestStatus;

module.exports = class PurchaseOrderExternalManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.purchasing.collection.PurchaseOrderExternal);
        this.year = (new Date()).getFullYear().toString().substring(2, 4);
        this.purchaseOrderManager = new PurchaseOrderManager(db, user);
        this.purchaseRequestManager = new PurchaseRequestManager(db, user);
        this.currencyManager = new CurrencyManager(db, user);
        this.vatManager = new VatManager(db, user);
        this.supplierManager = new SupplierManager(db, user);
        this.productManager = new ProductManager(db, user);
    }

    _getQuery(paging) {
        var _default = {
            _deleted: false
        },
            pagingFilter = paging.filter || {},
            keywordFilter = {},
            query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterPODLNo = {
                'no': {
                    '$regex': regex
                }
            };
            var filterRefPO = {
                'refNo': {
                    '$regex': regex
                }
            };

            var filterPrNo = {
                items: {
                    $elemMatch: {
                        'purchaseRequest.no': {
                            '$regex': regex
                        }
                    }
                }
            };

            var filterPOItem = {
                items: {
                    $elemMatch: {
                        no: {
                            '$regex': regex
                        }
                    }
                }
            };
            var filterSupplierName = {
                'supplier.name': {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterPODLNo, filterPrNo, filterRefPO, filterPOItem, filterSupplierName]
            };
        }
        query = {
            '$and': [_default, paging.filter, keywordFilter]
        }
        return query;
    }

    _beforeInsert(purchaseOrderExternal) {
        purchaseOrderExternal.no = generateCode();
        purchaseOrderExternal.status = poStatusEnum.CREATED;
        return Promise.resolve(purchaseOrderExternal)
    }

    _afterInsert(id) {
        return this.getSingleById(id)
            .then((purchaseOrderExternal) => {
                var jobsUpdatePO = purchaseOrderExternal.items.map((poeItem) => {
                    return this.purchaseOrderManager.getSingleByIdOrDefault(poeItem._id)
                        .then((purchaseOrder) => {
                            purchaseOrder.isPosted = true;
                            purchaseOrder.status = poStatusEnum.PROCESSING;
                            for (var item of poeItem.items) {
                                var poItem = purchaseOrder.items.find((_poItem) => _poItem.product._id.toString() === item.product._id.toString());
                                if (poItem) {
                                    poItem.priceBeforeTax = item.priceBeforeTax;
                                    poItem.dealQuantity = item.dealQuantity;
                                    poItem.dealUom = item.dealUom;
                                    poItem.conversion = item.conversion;
                                }
                            }
                            return this.purchaseOrderManager.updateCollectionPurchaseOrder(purchaseOrder);
                        })
                })
                return Promise.all(jobsUpdatePO)
                    .then((purchaseOrders) => {
                        for (var purchaseOrder of purchaseOrders) {
                            var item = purchaseOrderExternal.items.find(item => item._id.toString() === purchaseOrder._id.toString());
                            var index = purchaseOrderExternal.items.indexOf(item);
                            purchaseOrderExternal.items.splice(index, 1, purchaseOrder);
                        }
                        return this.collection
                            .updateOne({
                                _id: purchaseOrderExternal._id
                            }, {
                                $set: purchaseOrderExternal
                            })
                            .then((result) => Promise.resolve(purchaseOrderExternal._id));
                    });
            });
    }

    _beforeUpdate(purchaseOrderExternal) {
        return this.getSingleById(purchaseOrderExternal._id)
            .then((oldPurchaseOrderExternal) => {
                var oldItems = [];
                var newItems = [];
                var jobs = [];
                for (var oldItem of oldPurchaseOrderExternal.items) {
                    var _item = purchaseOrderExternal.items.find(item => item._id.toString() === oldItem._id.toString());
                    if (!_item) {
                        oldItems.push(oldItem);
                    }
                }

                for (var newItem of purchaseOrderExternal.items) {
                    var _item = oldPurchaseOrderExternal.items.find(item => item._id.toString() === newItem._id.toString());
                    if (!_item) {
                        newItems.push(newItem);
                    }
                }

                if (oldItems.length > 0) {
                    jobs.push(this._deleteOldPO(oldItems));
                }
                if (newItems.length > 0) {
                    jobs.push(this._insertNewPO(newItems));
                }
                if (jobs.length == 0) {
                    jobs.push(Promise.resolve(null));
                }
                return Promise.all(jobs);
            })
            .then((result) => {
                return Promise.resolve(purchaseOrderExternal);
            })
    }

    _deleteOldPO(oldItems) {
        var getPurchaseOrderIds = oldItems.map((purchaseOrder) => this.purchaseOrderManager.getSingleByIdOrDefault(purchaseOrder._id));
        var getPurchaseRequestIds = oldItems.map((purchaseOrder) => this.purchaseRequestManager.getSingleByIdOrDefault(purchaseOrder.purchaseRequest._id));
        return Promise.all(getPurchaseRequestIds)
            .then((purchaseRequests) => {
                var jobsUpdatePR = purchaseRequests.map((purchaseRequest) => {
                    purchaseRequest.status = prStatusEnum.PROCESSING;
                    return this.purchaseRequestManager.updateCollectionPR(purchaseRequest)
                })
                return Promise.all(jobsUpdatePR);
            })
            .then((purchaseRequests) => {
                return Promise.all(getPurchaseOrderIds)
                    .then((purchaseOrders) => {
                        var jobsUpdatePO = purchaseOrders.map((purchaseOrder) => {
                            var _purchaseRequest = purchaseRequests.find((purchaseRequest) => purchaseRequest._id.toString() === purchaseOrder.purchaseRequest._id.toString());
                            if (_purchaseRequest) {
                                purchaseOrder.purchaseRequest = _purchaseRequest;
                            }
                            purchaseOrder.isPosted = false;
                            purchaseOrder.status = poStatusEnum.CREATED;
                            for (var poItem of purchaseOrder.items) {
                                poItem.priceBeforeTax = 0;
                                poItem.dealQuantity = 0;
                                poItem.dealUom = new uom();
                                poItem.conversion = 1;
                            }
                            return this.purchaseOrderManager.updateCollectionPurchaseOrder(purchaseOrder);
                        })
                        return Promise.all(jobsUpdatePO)
                    })
            })
    }

    _insertNewPO(newItems) {
        var getPurchaseOrderIds = newItems.map((purchaseOrder) => this.purchaseOrderManager.getSingleByIdOrDefault(purchaseOrder._id));
        return Promise.all(getPurchaseOrderIds)
            .then((purchaseOrders) => {
                var jobsUpdatePO = purchaseOrders.map((purchaseOrder) => {
                    purchaseOrder.isPosted = true;
                    purchaseOrder.status = poStatusEnum.PROCESSING;
                    var poeItem = newItems.find((po) => po._id.toString() === purchaseOrder._id.toString());
                    if (poeItem) {
                        for (var item of poeItem.items) {
                            var poItem = purchaseOrder.items.find((_poItem) => _poItem.product._id.toString() === item.product._id.toString());
                            if (poItem) {
                                poItem.priceBeforeTax = item.priceBeforeTax;
                                poItem.dealQuantity = item.dealQuantity;
                                poItem.dealUom = item.dealUom;
                                poItem.conversion = item.conversion;
                            }
                        }
                        return this.purchaseOrderManager.updateCollectionPurchaseOrder(purchaseOrder);
                    } else {
                        return Promise.resolve(null);
                    }
                })
                return Promise.all(jobsUpdatePO)
            })
    }

    delete(poExternal) {
        return this._createIndexes()
            .then((createIndexResults) => {
                return this._validate(poExternal)
                    .then((purchaseOrderExternal) => {
                        purchaseOrderExternal._deleted = true;
                        return this.update(purchaseOrderExternal);
                    })
                    .then((poExId) => {
                        var query = {
                            _id: ObjectId.isValid(poExId) ? new ObjectId(poExId) : {}
                        };
                        return this.getSingleByQuery(query);
                    })
                    .then((purchaseOrderExternal) => {
                        var getPurchaseOrderIds = purchaseOrderExternal.items.map((purchaseOrder) => this.purchaseOrderManager.getSingleByIdOrDefault(purchaseOrder._id));
                        var getPurchaseRequestIds = purchaseOrderExternal.items.map((purchaseOrder) => this.purchaseRequestManager.getSingleByIdOrDefault(purchaseOrder.purchaseRequest._id));

                        return Promise.all(getPurchaseRequestIds)
                            .then((purchaseRequests) => {
                                var jobsUpdatePR = purchaseRequests.map((purchaseRequest) => {
                                    purchaseRequest.status = prStatusEnum.PROCESSING;
                                    return this.purchaseRequestManager.updateCollectionPR(purchaseRequest)
                                })
                                return Promise.all(jobsUpdatePR);
                            })
                            .then((purchaseRequests) => {
                                return Promise.all(getPurchaseOrderIds)
                                    .then((purchaseOrders) => {
                                        var jobsUpdatePO = purchaseOrders.map((purchaseOrder) => {
                                            var _purchaseRequest = purchaseRequests.find((purchaseRequest) => purchaseRequest._id.toString() === purchaseOrder.purchaseRequest._id.toString());
                                            if (_purchaseRequest) {
                                                purchaseOrder.purchaseRequest = _purchaseRequest;
                                            }
                                            purchaseOrder.isPosted = false;
                                            purchaseOrder.status = poStatusEnum.CREATED;
                                            for (var poItem of purchaseOrder.items) {
                                                poItem.priceBeforeTax = 0;
                                                poItem.dealQuantity = 0;
                                                poItem.dealUom = new uom();
                                                poItem.conversion = 1;
                                            }
                                            return this.purchaseOrderManager.updateCollectionPurchaseOrder(purchaseOrder)
                                        })
                                        return Promise.all(jobsUpdatePO)
                                    })
                            })
                            .then((purchaseOrders) => {
                                for (var purchaseOrder of purchaseOrders) {
                                    var item = purchaseOrderExternal.items.find(item => item._id.toString() === purchaseOrder._id.toString());
                                    var index = purchaseOrderExternal.items.indexOf(item);
                                    if (index !== -1) {
                                        purchaseOrderExternal.items.splice(index, 1, purchaseOrder);
                                    }
                                }
                                return this.collection
                                    .updateOne({
                                        _id: purchaseOrderExternal._id
                                    }, {
                                        $set: purchaseOrderExternal
                                    })
                                    .then((result) => Promise.resolve(purchaseOrderExternal._id));
                            })
                    })
            });
    }

    _validate(purchaseOrderGroup) {
        var purchaseOrderExternalError = {};
        var valid = purchaseOrderGroup;

        var getOtherPurchaseOrder = this.collection.singleOrDefault({
            "$and": [{
                _id: {
                    '$ne': new ObjectId(valid._id)
                }
            }, {
                    "no": valid.no
                }]
        });
        var getCurrency = valid.currency && ObjectId.isValid(valid.currency._id) ? this.currencyManager.getSingleByIdOrDefault(valid.currency._id) : Promise.resolve(null);
        var getSupplier = valid.supplier && ObjectId.isValid(valid.supplier._id) ? this.supplierManager.getSingleByIdOrDefault(valid.supplier._id) : Promise.resolve(null);
        var getVat = valid.vat && ObjectId.isValid(valid.vat._id) ? this.vatManager.getSingleByIdOrDefault(valid.vat._id) : Promise.resolve(null);

        var getPOInternal = [];
        valid.items = valid.items || [];
        for (var po of valid.items) {
            if (ObjectId.isValid(po._id)) {
                getPOInternal.push(this.purchaseOrderManager.getSingleByIdOrDefault(po._id));
            }
        }

        return Promise.all([getOtherPurchaseOrder, getSupplier, getCurrency, getVat].concat(getPOInternal))
            .then(results => {
                var _otherPurchaseOrder = results[0];
                var _supplier = results[1];
                var _currency = results[2];
                var _vat = results[3];
                var _poInternals = results.slice(4, results.length);

                var _products = _poInternals.map((poInternal) => {
                    return poInternal.items.map((item) => { return item.product })
                });
                _products = [].concat.apply([], _products);

                var _listProducts = _products.filter(function (elem, index, self) {
                    return index == self.indexOf(elem);
                })

                var getProducts = _listProducts.map((product) => {
                    if (ObjectId.isValid(product._id)) {
                        return this.productManager.getSingleByIdOrDefault(product._id)
                    } else {
                        return Promise.resolve(null)
                    }
                });

                return Promise.all(getProducts)
                    .then(listProduct => {
                        if (_otherPurchaseOrder) {
                            purchaseOrderExternalError["no"] = i18n.__("PurchaseOrderExternal.no.isExist:%s is exist", i18n.__("PurchaseOrderExternal.no._:No"));
                        }

                        if (!valid.supplierId || valid.supplierId.toString() === "") {
                            purchaseOrderExternalError["supplierId"] = i18n.__("PurchaseOrderExternal.supplier.name.isRequired:%s is required", i18n.__("PurchaseOrderExternal.supplier.name._:Name")); //"Nama Supplier tidak boleh kosong";
                        }
                        else if (valid.supplier) {
                            if (!valid.supplier._id) {
                                purchaseOrderExternalError["supplierId"] = i18n.__("PurchaseOrderExternal.supplier.name.isRequired:%s is required", i18n.__("PurchaseOrderExternal.supplier.name._:Name")); //"Nama Supplier tidak boleh kosong";
                            }
                        }
                        else if (!_supplier) {
                            purchaseOrderExternalError["supplierId"] = i18n.__("PurchaseOrderExternal.supplier.name.isRequired:%s is required", i18n.__("PurchaseOrderExternal.supplier.name._:Name")); //"Nama Supplier tidak boleh kosong";
                        }

                        if (!valid.expectedDeliveryDate || valid.expectedDeliveryDate === "") {
                            purchaseOrderExternalError["expectedDeliveryDate"] = i18n.__("PurchaseOrderExternal.expectedDeliveryDate.isRequired:%s is required", i18n.__("PurchaseOrderExternal.expectedDeliveryDate._:Expected Delivery Date")); //"Tanggal tersedia tidak boleh kosong";
                        }

                        if (!valid.date || valid.date === "") {
                            purchaseOrderExternalError["date"] = i18n.__("PurchaseOrderExternal.date.isRequired:%s is required", i18n.__("PurchaseOrderExternal.date._:Date")); //"Tanggal tidak boleh kosong";
                        }

                        if (!valid.paymentMethod || valid.paymentMethod === "") {
                            purchaseOrderExternalError["paymentMethod"] = i18n.__("PurchaseOrderExternal.paymentMethod.isRequired:%s is required", i18n.__("PurchaseOrderExternal.paymentMethod._:Payment Method")); //"Metode Pembayaran tidak boleh kosong";
                        }

                        if (!valid.currency) {
                            purchaseOrderExternalError["currency"] = i18n.__("PurchaseOrderExternal.currency.isRequired:%s is required", i18n.__("PurchaseOrderExternal.currency._:Currency")); //"Currency tidak boleh kosong";
                        }
                        else if (valid.currency) {
                            if (!valid.currency._id) {
                                purchaseOrderExternalError["currency"] = i18n.__("PurchaseOrderExternal.currency.isRequired:%s is required", i18n.__("PurchaseOrderExternal.currency._:Currency")); //"Currency tidak boleh kosong";
                            }
                        }
                        else if (!_currency) {
                            purchaseOrderExternalError["currency"] = i18n.__("PurchaseOrderExternal.currency.isRequired:%s is required", i18n.__("PurchaseOrderExternal.currency._:Currency")); //"Currency tidak boleh kosong";
                        }

                        // if (!valid.currencyRate || valid.currencyRate === 0) {
                        //     purchaseOrderExternalError["currencyRate"] = i18n.__("PurchaseOrderExternal.currencyRate.isRequired:%s is required", i18n.__("PurchaseOrderExternal.currencyRate._:Currency Rate")); //"Rate tidak boleh kosong";
                        // }

                        if (!valid.paymentMethod || valid.paymentMethod.toUpperCase() != "CASH") {
                            if (!valid.paymentDueDays || valid.paymentDueDays === "" || valid.paymentDueDays === 0) {
                                purchaseOrderExternalError["paymentDueDays"] = i18n.__("PurchaseOrderExternal.paymentDueDays.isRequired:%s is required", i18n.__("PurchaseOrderExternal.paymentDueDays._:Payment Due Days")); //"Tempo Pembayaran tidak boleh kosong";
                            }
                        }
                        if ((valid.freightCostBy || "").toString() === "") {
                            purchaseOrderExternalError["freightCostBy"] = i18n.__("PurchaseOrderExternal.freightCostBy.isRequired:%s is required", i18n.__("PurchaseOrderExternal.freightCostBy._:FreightCostBy")); //"Tempo Pembayaran tidak boleh kosong";
                        }

                        if (valid.items && valid.items.length > 0) {

                            var purchaseOrderExternalItemErrors = [];
                            var poItemExternalHasError = false;
                            for (var purchaseOrder of valid.items) {
                                var purchaseOrderError = {};
                                var purchaseOrderItemErrors = [];
                                var poItemHasError = false;
                                if (Object.getOwnPropertyNames(purchaseOrder).length == 0) {
                                    purchaseOrderError["no"] = i18n.__("PurchaseOrderExternal.items.no.isRequired:%s is required", i18n.__("PurchaseOrderExternal.items.no._:No")); //"Purchase order internal tidak boleh kosong";
                                    poItemExternalHasError = true;
                                    purchaseOrderExternalItemErrors.push(purchaseOrderError);
                                } else {
                                    for (var po of _poInternals) {
                                        if (po._id.toString() === purchaseOrder._id.toString()) {
                                            if (po.isPosted && !valid._id) {
                                                poItemHasError = true;
                                                purchaseOrderError["no"] = i18n.__("PurchaseOrderExternal.items.isPosted:%s is already used", i18n.__("PurchaseOrderExternal.items._:Purchase Order Internal ")); //"Purchase order internal tidak boleh kosong";
                                            }
                                            else if (!purchaseOrder.no || purchaseOrder.no == "") {
                                                poItemHasError = true;
                                                purchaseOrderError["no"] = i18n.__("PurchaseOrderExternal.items.no.isRequired:%s is required", i18n.__("PurchaseOrderExternal.items.no._:No")); //"Purchase order internal tidak boleh kosong";
                                            }

                                            for (var poItem of purchaseOrder.items || []) {
                                                var poItemError = {};
                                                var dealUomId = new ObjectId(poItem.dealUom._id);
                                                var defaultUomId = new ObjectId(poItem.defaultUom._id);
                                                var product = listProduct.find((_product) => _product._id.toString() === poItem.product._id.toString());

                                                if (!poItem.dealQuantity || poItem.dealQuantity === 0) {
                                                    poItemHasError = true;
                                                    poItemError["dealQuantity"] = i18n.__("PurchaseOrderExternal.items.items.dealQuantity.isRequired:%s is required", i18n.__("PurchaseOrderExternal.items.items.dealQuantity._:Deal Quantity")); //"Jumlah kesepakatan tidak boleh kosong";
                                                }
                                                else if (dealUomId.equals(defaultUomId) && poItem.dealQuantity > poItem.defaultQuantity) {
                                                    poItemHasError = true;
                                                    poItemError["dealQuantity"] = i18n.__("PurchaseOrderExternal.items.items.dealQuantity.isGreater:%s must not be greater than defaultQuantity", i18n.__("PurchaseOrderExternal.items.items.dealQuantity._:Deal Quantity")); //"Jumlah kesepakatan tidak boleh kosong";
                                                }
                                                if (!poItem.dealUom || !poItem.dealUom.unit || poItem.dealUom.unit === "") {
                                                    poItemHasError = true;
                                                    poItemError["dealUom"] = i18n.__("PurchaseOrderExternal.items.items.dealQuantity.isRequired:%s is required", i18n.__("PurchaseOrderExternal.items.items.dealQuantity._:Deal Quantity")); //"Jumlah kesepakatan tidak boleh kosong";
                                                }
                                                if (!poItem.priceBeforeTax || poItem.priceBeforeTax === 0) {
                                                    poItemHasError = true;
                                                    poItemError["priceBeforeTax"] = i18n.__("PurchaseOrderExternal.items.items.priceBeforeTax.isRequired:%s is required", i18n.__("PurchaseOrderExternal.items.items.priceBeforeTax._:Price Per Deal Unit")); //"Harga tidak boleh kosong";
                                                } else if (!ObjectId.isValid(valid._id) && product) {
                                                    if (poItem.priceBeforeTax > product.price) {
                                                        poItemHasError = true;
                                                        poItemError["priceBeforeTax"] = i18n.__("PurchaseOrderExternal.items.items.priceBeforeTax.isGreater:%s must not be greater than default price", i18n.__("PurchaseOrderExternal.items.items.priceBeforeTax._:Price Per Deal Unit")); //"Harga tidak boleh kosong";
                                                    }
                                                }
                                                var price = (poItem.priceBeforeTax.toString()).split(",");
                                                if (price[1] != undefined || price[1] !== "" || price[1] !== " ") {
                                                    {
                                                        poItem.priceBeforeTax = parseFloat(poItem.priceBeforeTax.toString() + ".00");
                                                    }
                                                }
                                                else if (price[1].length() > 2) {
                                                    poItemHasError = true;
                                                    poItemError["priceBeforeTax"] = i18n.__("PurchaseOrderExternal.items.items.priceBeforeTax.isRequired:%s is greater than 2", i18n.__("PurchaseOrderExternal.items.items.priceBeforeTax._:Price Per Deal Unit")); //"Harga tidak boleh kosong";
                                                }
                                                else {
                                                    poItem.priceBeforeTax = poItem.priceBeforeTax;
                                                }
                                                if (!poItem.conversion || poItem.conversion === "") {
                                                    poItemHasError = true;
                                                    poItemError["conversion"] = i18n.__("PurchaseOrderExternal.items.items.conversion.isRequired:%s is required", i18n.__("PurchaseOrderExternal.items.items.conversion._:Conversion")); //"Konversi tidak boleh kosong";
                                                }
                                                purchaseOrderItemErrors.push(poItemError);
                                            }
                                            if (poItemHasError) {
                                                poItemExternalHasError = true;
                                                purchaseOrderError["items"] = purchaseOrderItemErrors;
                                            }

                                            purchaseOrderExternalItemErrors.push(purchaseOrderError);
                                            break;
                                        }
                                    }
                                }
                            }
                            if (poItemExternalHasError) {
                                purchaseOrderExternalError["items"] = purchaseOrderExternalItemErrors;
                            }
                        }
                        else {
                            purchaseOrderExternalError["items"] = i18n.__("PurchaseOrderExternal.items.isRequired:%s is required", i18n.__("PurchaseOrderExternal.items._:Purchase Order Internal")); //"Harus ada minimal 1 po internal";
                        }

                        // 2c. begin: check if data has any error, reject if it has.
                        if (Object.getOwnPropertyNames(purchaseOrderExternalError).length > 0) {
                            var ValidationError = require('module-toolkit').ValidationError;
                            return Promise.reject(new ValidationError('data podl does not pass validation', purchaseOrderExternalError));
                        }

                        valid.supplier = _supplier;
                        valid.supplierId = new ObjectId(valid.supplier._id);
                        valid.currency = _currency;
                        valid.currency._id = new ObjectId(valid.currency._id);
                        valid.vat = _vat;
                        valid.date = new Date(valid.date);
                        valid.expectedDeliveryDate = new Date(valid.expectedDeliveryDate);
                        valid.currencyRate = parseInt(valid.currencyRate);

                        var items = [];

                        for (var _item of valid.items) {
                            for (var _purchaseOrder of _poInternals) {
                                if (_purchaseOrder._id.toString() === _item._id.toString()) {
                                    var _po = new PurchaseOrder();
                                    _po = _purchaseOrder;
                                    for (var _poItem of _item.items) {
                                        for (var _purchaseOrderItem of _po.items) {
                                            if (_purchaseOrderItem.product._id.toString() === _poItem.product._id.toString()) {
                                                _purchaseOrderItem.product = _poItem.product;
                                                _purchaseOrderItem.dealQuantity =  Number(_poItem.dealQuantity);
                                                _purchaseOrderItem.dealUom = _poItem.dealUom;
                                                _purchaseOrderItem.useIncomeTax = _poItem.useIncomeTax;
                                                _purchaseOrderItem.priceBeforeTax =  Number(_poItem.priceBeforeTax);
                                                _purchaseOrderItem.pricePerDealUnit = _poItem.useIncomeTax ? (100 * _poItem.priceBeforeTax) / 110 : _poItem.priceBeforeTax;
                                                _purchaseOrderItem.conversion = _poItem.conversion;
                                                break;
                                            }
                                        }
                                    }
                                    items.push(_po);
                                    break;
                                }
                            }
                        }
                        valid.items = items;
                        if (!valid.stamp) {
                            valid = new PurchaseOrderExternal(valid);
                        }
                        valid.vat = _vat;
                        valid.stamp(this.user.username, 'manager');
                        return Promise.resolve(valid);
                    });
            });
    }

    post(listPurchaseOrderExternal) {
        var getPOExternalById = listPurchaseOrderExternal.map((purchaseOrderExternal) => this.getSingleByIdOrDefault(purchaseOrderExternal._id));
        return Promise.all(getPOExternalById)
            .then((purchaseOrderExternals) => {
                var jobs = purchaseOrderExternals.map((_purchaseOrderExternal) => {
                    return this._validate(_purchaseOrderExternal)
                        .then((purchaseOrderExternal) => {
                            purchaseOrderExternal.isPosted = true;
                            purchaseOrderExternal.status = poStatusEnum.ORDERED;
                            return this.update(purchaseOrderExternal);
                        })
                        .then((poExId) => {
                            return this.getSingleByIdOrDefault(poExId);
                        })
                        .then((purchaseOrderExternal) => {
                            var getPurchaseOrderIds = purchaseOrderExternal.items.map((purchaseOrder) => this.purchaseOrderManager.getSingleByIdOrDefault(purchaseOrder._id));
                            var getPurchaseRequestIds = purchaseOrderExternal.items.map((purchaseOrder) => this.purchaseRequestManager.getSingleByIdOrDefault(purchaseOrder.purchaseRequest._id));

                            return Promise.all(getPurchaseRequestIds)
                                .then((purchaseRequests) => {
                                    var jobsUpdatePR = purchaseRequests.map((purchaseRequest) => {
                                        purchaseRequest.status = prStatusEnum.ORDERED;
                                        return this.purchaseRequestManager.updateCollectionPR(purchaseRequest)
                                    })
                                    return Promise.all(jobsUpdatePR);
                                })
                                .then((purchaseRequests) => {
                                    return Promise.all(getPurchaseOrderIds)
                                        .then((purchaseOrders) => {
                                            var jobsUpdatePO = purchaseOrders.map((purchaseOrder) => {
                                                var _purchaseRequest = purchaseRequests.find((purchaseRequest) => purchaseRequest._id.toString() === purchaseOrder.purchaseRequest._id.toString());
                                                if (_purchaseRequest) {
                                                    purchaseOrder.purchaseRequest = _purchaseRequest;
                                                }
                                                purchaseOrder.purchaseOrderExternalId = new ObjectId(purchaseOrderExternal._id);
                                                purchaseOrder.purchaseOrderExternal = purchaseOrderExternal;
                                                purchaseOrder.purchaseOrderExternal._id = new ObjectId(purchaseOrderExternal._id);
                                                purchaseOrder.supplierId = new ObjectId(purchaseOrderExternal.supplierId);
                                                purchaseOrder.supplier = purchaseOrderExternal.supplier;
                                                purchaseOrder.supplier._id = new ObjectId(purchaseOrderExternal.supplier._id);
                                                purchaseOrder.freightCostBy = purchaseOrderExternal.freightCostBy;
                                                purchaseOrder.currency = purchaseOrderExternal.currency;
                                                purchaseOrder.currencyRate = purchaseOrderExternal.currencyRate;
                                                purchaseOrder.paymentMethod = _purchaseOrderExternal.paymentMethod;
                                                purchaseOrder.paymentDueDays = purchaseOrderExternal.paymentDueDays;
                                                purchaseOrder.vat = purchaseOrderExternal.vat;
                                                purchaseOrder.useVat = purchaseOrderExternal.useVat;
                                                purchaseOrder.vatRate = purchaseOrderExternal.vatRate;
                                                purchaseOrder.useIncomeTax = purchaseOrderExternal.useIncomeTax;
                                                purchaseOrder.isPosted = true;
                                                purchaseOrder.status = poStatusEnum.ORDERED;

                                                for (var poItem of purchaseOrder.items) {
                                                    var _purchaseOrder = purchaseOrderExternal.items.find((_purchaseOrder) => _purchaseOrder._id.toString() === purchaseOrder._id.toString());
                                                    var itemExternal = _purchaseOrder.items.find((_item) => _item.product._id.toString() === poItem.product._id.toString());
                                                    if (itemExternal) {
                                                        poItem.dealQuantity = Number(itemExternal.dealQuantity);
                                                        poItem.dealUom = itemExternal.dealUom;
                                                        poItem.priceBeforeTax = Number(itemExternal.priceBeforeTax);
                                                        poItem.pricePerDealUnit = itemExternal.useIncomeTax ? (100 * itemExternal.priceBeforeTax) / 110 : itemExternal.priceBeforeTax;
                                                        poItem.conversion = Number(itemExternal.conversion);
                                                        poItem.currency = purchaseOrderExternal.currency;
                                                        poItem.currencyRate =  Number(purchaseOrderExternal.currencyRate);
                                                    }
                                                }
                                                return this.purchaseOrderManager.updateCollectionPurchaseOrder(purchaseOrder)
                                            })
                                            return Promise.all(jobsUpdatePO)
                                        })
                                })
                                .then((purchaseOrders) => {
                                    for (var purchaseOrder of purchaseOrders) {
                                        var item = purchaseOrderExternal.items.find(item => item._id.toString() === purchaseOrder._id.toString());
                                        var index = purchaseOrderExternal.items.indexOf(item);
                                        if (index !== -1) {
                                            purchaseOrderExternal.items.splice(index, 1, purchaseOrder);
                                        }
                                    }
                                    return this.collection
                                        .updateOne({
                                            _id: purchaseOrderExternal._id
                                        }, {
                                            $set: purchaseOrderExternal
                                        })
                                        .then((result) => Promise.resolve(purchaseOrderExternal._id));
                                })
                        })
                })
                return Promise.all(jobs)
            })
            .then((purchaseOrderExternalIds) => {
                return Promise.resolve(purchaseOrderExternalIds);
            });
    }

    pdf(id) {
        return new Promise((resolve, reject) => {

            this.getSingleByIdOrDefault(id)
                .then(pox => {
                    var getDefinition = require('../../pdf/definitions/purchase-order-external');
                    var definition = getDefinition(pox);

                    var generatePdf = require('../../pdf/pdf-generator');
                    generatePdf(definition)
                        .then(binary => {
                            resolve(binary);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });

        });
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.purchasing.collection.PurchaseOrderExternal}_date`,
            key: {
                date: -1
            }
        }

        var noIndex = {
            name: `ix_${map.purchasing.collection.PurchaseOrderExternal}_no`,
            key: {
                no: 1
            },
            unique: true
        }

        return this.collection.createIndexes([dateIndex, noIndex]);
    }

    unpost(poExternalId) {
        return this.getSingleByIdOrDefault(poExternalId)
            .then((poExternal) => {
                return this.validateCancelAndUnpost(poExternal)
                    .then((purchaseOrderExternal) => {
                        purchaseOrderExternal.isPosted = false;
                        purchaseOrderExternal.status = poStatusEnum.CREATED;
                        return this.update(purchaseOrderExternal);
                    })
                    .then((poExId) => {
                        return this.getSingleByIdOrDefault(poExId);
                    })
                    .then((purchaseOrderExternal) => {
                        var getPurchaseOrderIds = purchaseOrderExternal.items.map((purchaseOrder) => this.purchaseOrderManager.getSingleByIdOrDefault(purchaseOrder._id));
                        var getPurchaseRequestIds = purchaseOrderExternal.items.map((purchaseOrder) => this.purchaseRequestManager.getSingleByIdOrDefault(purchaseOrder.purchaseRequest._id));

                        return Promise.all(getPurchaseRequestIds)
                            .then((purchaseRequests) => {
                                var jobsUpdatePR = purchaseRequests.map((purchaseRequest) => {
                                    purchaseRequest.status = prStatusEnum.PROCESSING
                                    return this.purchaseRequestManager.updateCollectionPR(purchaseRequest)
                                })
                                return Promise.all(jobsUpdatePR);
                            })
                            .then((purchaseRequests) => {
                                return Promise.all(getPurchaseOrderIds)
                                    .then((purchaseOrders) => {
                                        var jobsUpdatePO = purchaseOrders.map((purchaseOrder) => {
                                            var _purchaseRequest = purchaseRequests.find((purchaseRequest) => purchaseRequest._id.toString() === purchaseOrder.purchaseRequest._id.toString());
                                            if (_purchaseRequest) {
                                                purchaseOrder.purchaseRequest = _purchaseRequest;
                                            }
                                            purchaseOrder.purchaseOrderExternalId = {};
                                            purchaseOrder.purchaseOrderExternal = {};
                                            purchaseOrder.supplierId = {};
                                            purchaseOrder.supplier = {};
                                            purchaseOrder.freightCostBy = '';
                                            purchaseOrder.currency = {};
                                            purchaseOrder.currencyRate = 1;
                                            purchaseOrder.paymentMethod = '';
                                            purchaseOrder.paymentDueDays = 0;
                                            purchaseOrder.vat = {};
                                            purchaseOrder.useVat = false;
                                            purchaseOrder.vatRate = 0;
                                            purchaseOrder.useIncomeTax = false;
                                            purchaseOrder.status = poStatusEnum.PROCESSING;

                                            for (var poItem of purchaseOrder.items) {
                                                poItem.dealQuantity = 0;
                                                poItem.dealUom = {};
                                                poItem.priceBeforeTax = 0;
                                                poItem.pricePerDealUnit = 0;
                                                poItem.conversion = 1;
                                                poItem.currency = {};
                                                poItem.currencyRate = 1;
                                            }
                                            return this.purchaseOrderManager.updateCollectionPurchaseOrder(purchaseOrder)
                                        })
                                        return Promise.all(jobsUpdatePO)
                                    })
                            })
                            .then((purchaseOrders) => {
                                return this.collection
                                    .updateOne({
                                        _id: purchaseOrderExternal._id
                                    }, {
                                        $set: purchaseOrderExternal
                                    })
                                    .then((result) => Promise.resolve(purchaseOrderExternal._id));
                            })
                    })
            });
    }

    validateCancelAndUnpost(purchaseOrderExternal) {
        var purchaseOrderExternalError = {};
        var valid = purchaseOrderExternal;

        return this.getSingleByIdOrDefault(valid._id)
            .then((poe) => {
                if (!poe.isPosted)
                    purchaseOrderExternalError["no"] = i18n.__("PurchaseOrderExternal.isPosted:%s is not yet being posted", i18n.__("PurchaseOrderExternal.isPosted._:Posted"));

                if (valid.items && valid.items.length > 0) {
                    for (var purchaseOrder of valid.items) {
                        var poItemError = {};
                        var purchaseOrderItemErrors = [];
                        var poItemHasError = false;
                        for (var poItem of purchaseOrder.items) {
                            if (poItem.fulfillments && poItem.fulfillments.length > 0) {
                                poItemHasError = true;
                                poItemError["no"] = i18n.__("PurchaseOrderExternal.items.items.no:%s is already have delivery order", i18n.__("PurchaseOrderExternal.items,items.no._:No"));

                                purchaseOrderItemErrors.push(poItemError);
                            }
                        }

                        if (poItemHasError)
                            purchaseOrderExternalError["items"] = purchaseOrderItemErrors;
                    }
                }

                if (Object.getOwnPropertyNames(purchaseOrderExternalError).length > 0) {
                    var ValidationError = require('module-toolkit').ValidationError;
                    return Promise.reject(new ValidationError('data podl does not pass validation', purchaseOrderExternalError));
                }

                if (!valid.stamp) {
                    valid = new PurchaseOrderExternal(valid);
                }
                valid.stamp(this.user.username, 'manager');
                return Promise.resolve(valid);
            });
    }

    cancel(poExternalId) {
        return this.getSingleByIdOrDefault(poExternalId)
            .then((poExternal) => {
                return this.validateCancelAndUnpost(poExternal)
                    .then((purchaseOrderExternal) => {
                        purchaseOrderExternal.status = poStatusEnum.VOID;
                        return this.update(purchaseOrderExternal);
                    })
                    .then((poExId) => {
                        return this.getSingleByIdOrDefault(poExId);
                    })
                    .then((purchaseOrderExternal) => {
                        var getPurchaseOrderIds = purchaseOrderExternal.items.map((purchaseOrder) => this.purchaseOrderManager.getSingleByIdOrDefault(purchaseOrder._id));
                        var getPurchaseRequestIds = purchaseOrderExternal.items.map((purchaseOrder) => this.purchaseRequestManager.getSingleByIdOrDefault(purchaseOrder.purchaseRequest._id));

                        return Promise.all(getPurchaseRequestIds)
                            .then((purchaseRequests) => {
                                var jobsUpdatePR = purchaseRequests.map((purchaseRequest) => {
                                    purchaseRequest.status = prStatusEnum.VOID;
                                    return this.purchaseRequestManager.updateCollectionPR(purchaseRequest)
                                })
                                return Promise.all(jobsUpdatePR);
                            })
                            .then((purchaseRequests) => {
                                return Promise.all(getPurchaseOrderIds)
                                    .then((purchaseOrders) => {
                                        var jobsUpdatePO = purchaseOrders.map((purchaseOrder) => {
                                            var _purchaseRequest = purchaseRequests.find((purchaseRequest) => purchaseRequest._id.toString() === purchaseOrder.purchaseRequest._id.toString());
                                            if (_purchaseRequest) {
                                                purchaseOrder.purchaseRequest = _purchaseRequest;
                                            }
                                            purchaseOrder.status = poStatusEnum.VOID;

                                            return this.purchaseOrderManager.updateCollectionPurchaseOrder(purchaseOrder)
                                        })
                                        return Promise.all(jobsUpdatePO)
                                    })
                            })
                            .then((purchaseOrders) => {
                                for (var purchaseOrder of purchaseOrders) {
                                    var item = purchaseOrderExternal.items.find(item => item._id.toString() === purchaseOrder._id.toString());
                                    var index = purchaseOrderExternal.items.indexOf(item);
                                    if (index !== -1) {
                                        purchaseOrderExternal.items.splice(index, 1, purchaseOrder);
                                    }
                                }
                                return this.collection
                                    .updateOne({
                                        _id: purchaseOrderExternal._id
                                    }, {
                                        $set: purchaseOrderExternal
                                    })
                                    .then((result) => Promise.resolve(purchaseOrderExternal._id));
                            })
                    });

            });
    }

    close(poExternalId) {
        return this.getSingleByIdOrDefault(poExternalId)
            .then((poExternal) => {
                return this.validateClose(poExternal)
                    .then((purchaseOrderExternal) => {
                        purchaseOrderExternal.isClosed = true;
                        return this.update(purchaseOrderExternal);
                    })
                    .then((poExId) => {
                        return this.getSingleByIdOrDefault(poExId);
                    })
                    .then((purchaseOrderExternal) => {
                        var getPurchaseOrderIds = purchaseOrderExternal.items.map((purchaseOrder) => this.purchaseOrderManager.getSingleByIdOrDefault(purchaseOrder._id));

                        return Promise.all(getPurchaseOrderIds)
                            .then((purchaseOrders) => {
                                var jobsUpdatePO = purchaseOrders.map((purchaseOrder) => {
                                    purchaseOrder.items.map((item) => item.isClosed = true);
                                    purchaseOrder.isClosed = true;
                                    return this.purchaseOrderManager.updateCollectionPurchaseOrder(purchaseOrder)
                                })
                                return Promise.all(jobsUpdatePO)
                            })
                            .then((purchaseOrders) => {
                                for (var purchaseOrder of purchaseOrders) {
                                    var item = purchaseOrderExternal.items.find(item => item._id.toString() === purchaseOrder._id.toString());
                                    var index = purchaseOrderExternal.items.indexOf(item);
                                    if (index !== -1) {
                                        purchaseOrderExternal.items.splice(index, 1, purchaseOrder);
                                    }
                                }
                                return this.collection
                                    .updateOne({
                                        _id: purchaseOrderExternal._id
                                    }, {
                                        $set: purchaseOrderExternal
                                    })
                                    .then((result) => Promise.resolve(purchaseOrderExternal._id));
                            })
                    })
            });
    }

    validateClose(purchaseOrderExternal) {
        var purchaseOrderExternalError = {};
        var valid = purchaseOrderExternal;

        return this.getSingleByIdOrDefault(valid._id)
            .then((poe) => {
                if (!poe.isPosted)
                    purchaseOrderExternalError["no"] = i18n.__("PurchaseOrderExternal.isPosted:%s is not yet being posted", i18n.__("PurchaseOrderExternal.isPosted._:Posted"));

                if (Object.getOwnPropertyNames(purchaseOrderExternalError).length > 0) {
                    var ValidationError = require('module-toolkit').ValidationError;
                    return Promise.reject(new ValidationError('data podl does not pass validation', purchaseOrderExternalError));
                }

                if (!valid.stamp) {
                    valid = new PurchaseOrderExternal(valid);
                }
                valid.stamp(this.user.username, 'manager');
                return Promise.resolve(valid);
            });
    }

    getAllData(filter) {
        return this._createIndexes()
            .then((createIndexResults) => {
                return new Promise((resolve, reject) => {
                    var query = Object.assign({});
                    query = Object.assign(query, filter);
                    query = Object.assign(query, {
                        _deleted: false
                    });

                    var _select = ["no",
                        "date",
                        "supplier",
                        "expectedDeliveryDate",
                        "freightCostBy",
                        "paymentMethod",
                        "paymentDueDays",
                        "currency",
                        "useIncomeTax",
                        "useVat",
                        "vat.rate",
                        "remark",
                        "isPosted",
                        "_createdBy",
                        "items.no",
                        "items.purchaseRequest.no",
                        "items.items"];

                    this.collection.where(query).select(_select).execute()
                        .then((results) => {
                            resolve(results.data);
                        })
                        .catch(e => {
                            reject(e);
                        });
                });
            });
    }
};


text:
var express = require('express')
  , stylus = require('stylus')
  , nib = require('nib')
  , util = require('./util')
  , dateFormat = require("date-format-lite")
  , async = require('async')
  , http = require('http')
;

//Set up Express stuff.
var app = express();

function compile(str, path) {
  return stylus(str)
    .set('filename', path)
    .use(nib())
}
app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(express.logger('dev'))
app.use(stylus.middleware(
  { src: __dirname + '/public'
  , compile: compile
  }
))
app.use(express.static(__dirname + '/public'))

var courseUri = 'http://isi.edu/cs548/2014/fall';

var endpoint = '/openrdf-sesame/repositories/cs548?query=';
var query = "CONSTRUCT { ?s ?p ?o } where { ?s ?p ?o }";

var uris = [
           {
            	uriString: 'http://lod.isi.edu/ontology/syllabus/hasInstructor',
            	createObject: function(results, globalData) {
            		globalData.instructors = results;
            	}
            },
            {
            	uriString: 'http://vivoweb.org/ontology/core#hasPrerequisite',
            	createObject: function(results, globalData) {
            		globalData.prerequisites = results;
            	}

            },
            {
            	uriString: 'http://lod.isi.edu/ontology/syllabus/hasProjectEvent',
            	createObject: function(results, globalData,parsedJSON) {
            		util.sortData(results,globalData,parsedJSON,'http://lod.isi.edu/ontology/syllabus/hasEventDate','projectevents');
            	}
            },
            {
            	uriString: 'http://lod.isi.edu/ontology/syllabus/hasHomework',
            	createObject: function(results, globalData,parsedJSON) {
            		util.sortData(results,globalData,parsedJSON,'http://lod.isi.edu/ontology/syllabus/hasEventDate','homeworks');
            	}

            } ,

            {
            	uriString: 'http://lod.isi.edu/ontology/syllabus/hasLecture',
            	createObject: function(results, globalData,parsedJSON) {
            		util.sortData(results,globalData,parsedJSON,'http://lod.isi.edu/ontology/syllabus/hasEventDate','lectures');
            	}
            }
];

//register for GET request
app.get('/', serveRequest);
app.listen(3000);
console.log("Listening on port 3000");

//It serves the request for the index page.
function serveRequest(req,resp){
	var pagedata = new Object();
	var data = '';
	async.series([
	              function(callback){
	              //1. Get all the triples from the endpoint
	          		var encodedquerystring = encodeURIComponent(query);
	          		var options = {
	        		    host: 'localhost',
	        		    port: 8080,
	        		    path: endpoint +encodedquerystring,
	        	        headers: {
	        	            'Content-Type': 'application/x-www-form-urlencoded',
	        	            'Accept': 'application/rdf+json',
	        	        }
	        		  };

	          		var req = http.get(options, function(res) {
	        	    res.on('data', function (chunk) {
	        	      data += chunk;
	        	    });
	        	    res.on('end', function () {
	        	    	//console.log(data);
	        	    	callback(); //the current task is finished, go onto the next task.
	        	    });
	        	  }).on('error', function(e) {
	        	    console.log("Got error: " + e.message);
	        	  });
	              },

	              function(callback) {
	              //2. Construct data to be rendered by jade
	            	  var parsedJSON = JSON.parse(data);
	            	  pagedata.course = parsedJSON[courseUri];
	            	  pagedata.alltriples = parsedJSON;
	            	  uris.forEach(function(entry){
                  		var results = pagedata.course[entry.uriString];
                  		console.log(results);
                  		entry.createObject(results,pagedata,parsedJSON);
                  	});
	            	  callback();
	              }

	], function(){
		//3. render the page.
		resp.render("index",pagedata);
	});
}

redpajama_set_name: RedPajamaGithub


text:
package org.javashlook.util.comparatorfactory;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

import net.sf.cglib.core.ClassEmitter;
import net.sf.cglib.core.ClassNameReader;
import net.sf.cglib.core.CodeEmitter;
import net.sf.cglib.core.EmitUtils;
import net.sf.cglib.core.Local;
import net.sf.cglib.core.ReflectUtils;
import net.sf.cglib.core.Signature;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;

/**
 * Factory for code generation of {@link Comparator}s.
 *
 */
public final class ComparatorFactory<T> {

	private ComparatorFactory(Class<?> type) {
		if (type == null) {
			throw new IllegalArgumentException();
		}
		this.comparatorClass = type;
	}

	/**
	 * Start generation of {@link Comparator} for a class.
	 */
	public static final <T> ComparatorFactory<T> forClass(Class<T> comparatorClass) {
		return new ComparatorFactory<T>(comparatorClass);
	}

	/**
	 * Add a property from target class to a comparison chain, in ascending order.
	 */
	public ComparatorFactory<T> addProperty(String propertyName, Class<?> propertyClass) {
		return addProperty(propertyName, propertyClass, true);
	}

	/**
	 * Add a property from target class to a comparison chain, in specified order.
	 */
	public ComparatorFactory<T> addProperty(String propertyName, Class<?> propertyClass, boolean ascending) {
		pdl.add(new PropertyDescriptor(propertyName, propertyClass, (ascending) ? 1 : -1));
		return this;
	}

	@SuppressWarnings("unchecked")
	public Comparator<T> generate() {
		try {
			pds = pdl.toArray(new PropertyDescriptor[pdl.size()]);
			Class<?> c = createComparatorClass();
			return (Comparator<T>) c.newInstance();
		} catch (Exception e) {
			if (e instanceof RuntimeException) {
				throw (RuntimeException) e;
			}
			throw new RuntimeException("Error generating comparator for: " + comparatorClass, e);
		}
	}

	// Implementation

	private final Class<?> comparatorClass;

	static final class PropertyDescriptor {
		String propertyName;
		Class<?> propertyClass;
		int order;

		public PropertyDescriptor(String propertyName, Class<?> propertyClass, int order) {
			this.propertyName = propertyName;
			this.propertyClass = propertyClass;
			this.order = order;
		}
	}

	private final List<PropertyDescriptor> pdl = new LinkedList<PropertyDescriptor>();

	private PropertyDescriptor[] pds;

	private Type ct;
	private Local b1;
	private Local b2;
	private Local c;

	private ClassWriter cw;
	private ClassEmitter cle;
	private CodeEmitter ce;

	private byte[] byteCode;

	private Class<?> createComparatorClass() throws Exception {
		emitComparatorClass();

		ClassLoader loader = comparatorClass.getClassLoader();
		String className = ClassNameReader.getClassName(new ClassReader(byteCode));
		return ReflectUtils.defineClass(className, byteCode, loader);
	}

	private void emitComparatorClass() throws Exception {
		ct = Type.getType(comparatorClass);

		cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
		cle = new ClassEmitter(cw);

		String fullClassName = getComparatorClassName();

		cle.begin_class(Opcodes.V1_4,
				Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL,
				fullClassName,
				OBJECT_TYPE,
				new Type[] { COMPARATOR_TYPE },
				null);

		// default constructor
		EmitUtils.null_constructor(cle);

		emitCompareToMethod();

		cle.end_class();

		byteCode = cw.toByteArray();
	}

	private String getComparatorClassName() {
		String className = comparatorClass.getName();
		int p = className.lastIndexOf('.');
		String packageName = className.substring(0, p);

		StringBuffer sb = new StringBuffer();
		sb.append(packageName);
		sb.append('.');
		sb.append(comparatorClass.getSimpleName());
		sb.append("Comparator$");
		for (int i = 0, n = pds.length; i < n; i++) {
			sb.append(pds[i].propertyName).append("_");
		}
		return sb.toString();
	}

	private static final Type OBJECT_TYPE = Type.getType(Object.class);
	private static final Type COMPARABLE_TYPE = Type.getType(Comparable.class);
	private static final Type COMPARATOR_TYPE = Type.getType(Comparator.class);
	private static final Type COMPARATOR_HELPER_TYPE = Type.getType(ComparatorHelper.class);

	private static final Signature COMPARE =
			new Signature("compare", Type.INT_TYPE, new Type[] { OBJECT_TYPE, OBJECT_TYPE });

	private static final Signature STATIC_COMPARE =
			new Signature("compare", Type.INT_TYPE, new Type[] { COMPARABLE_TYPE, COMPARABLE_TYPE });

	private void emitCompareToMethod() {
		ce = cle.begin_method(Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL, COMPARE, null);

		emitAssertArguments();

		c = ce.make_local(Type.INT_TYPE);
		emitCompareMethodBody();

		ce.end_method();
	}

	private void emitAssertArguments() {
		// b1
		b1 = ce.make_local(ct);
		ce.load_arg(0);
		ce.checkcast(ct);
		ce.store_local(b1);

		// b2
		b2 = ce.make_local(ct);
		ce.load_arg(1);
		ce.checkcast(ct);
		ce.store_local(b2);
	}

	private Signature getGetterSignature(int i) {
		String name = pds[i].propertyName;
		String s = Character.toUpperCase(name.charAt(0)) + name.substring(1);
		return new Signature("get" + s, Type.getType(pds[i].propertyClass), new Type[] {});
	}

	private void emitCompareMethodBody() {
		for (int i = 0, n = pds.length - 1; i <= n; i++) {
			emitCompareIf(i, n);
		}
	}

	private void emitCompareIf(int i, int n) {
		// b1.get..(), b2.get..()
		Signature gs = getGetterSignature(i);
		ce.load_local(b1);
		ce.invoke_virtual(ct, gs);
		ce.load_local(b2);
		ce.invoke_virtual(ct, gs);

		// int c = ComparatorHelper.compare(...);
		ce.invoke_static(COMPARATOR_HELPER_TYPE, STATIC_COMPARE);
		ce.store_local(c);

		ce.load_local(c);

		if (i == n) {
			if (pds[i].order < 0) {
				ce.push(-1);
				ce.math(Opcodes.IMUL, Type.INT_TYPE);
			}
			ce.return_value();
			return;
		}

		Label lbl = ce.make_label();
		ce.push(0);
		ce.if_icmp(CodeEmitter.EQ, lbl);

		ce.load_local(c);
		if (pds[i].order < 0) {
			ce.push(-1);
			ce.math(Opcodes.IMUL, Type.INT_TYPE);
		}
		ce.return_value();

		ce.mark(lbl);
	}

}


text:
using namespace std;

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        if (n == 0){
			return vector<string>{""};
		}
		vector<string> res;
		for (int m = 0; m < n; m++){
			vector<string> xs = generateParenthesis(m);
			vector<string> rests = generateParenthesis(n - m - 1);
			for (vector<string>::iterator rest = rests.begin(); rest != rests.end(); rest++){
				for (vector<string>::iterator x = xs.begin(); x != xs.end(); x ++){
					res.push_back("(" + (*x) + ")" + (*rest));
				}
			}
		}
		return res;
    }
};

int main(){
	Solution sol;
	vector<string> ans = sol.generateParenthesis(3);
	for (vector<string>::iterator it = ans.begin(); it != ans.end(); it++)
		cout << *it << ", " ;
	cout << endl;
	return 0;
}


text:
require "spec_helper"

describe Manticore::Cookie do
  context "created from a Client request" do
    let(:client) { Manticore::Client.new cookies: true }
    subject {
      response = client.get(local_server("/cookies/1/2"))
      expect(response.final_url.to_s).to eq local_server("/cookies/2/2")
      response.cookies["x"].first
    }

    its(:name) { is_expected.to eq "x" }
    its(:value) { is_expected.to eq "2" }
    its(:path) { is_expected.to eq "/" }
    its(:domain) { is_expected.to eq "localhost" }
  end

  let(:opts) { {} }
  subject {
    Manticore::Cookie.new({name: "foo", value: "bar"}.merge(opts))
  }

  its(:secure?) { is_expected.to be nil }
  its(:persistent?) { is_expected.to be nil }

  context "created as secure" do
    let(:opts) { {secure: true} }
    its(:secure?) { is_expected.to be true }
  end

  context "created as persistent" do
    let(:opts) { {persistent: true} }
    its(:persistent?) { is_expected.to be true }
  end
end


text:
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;

namespace Com.Aspose.Cells.Model {
  public class WorkbookEncryptionRequest {
    public string EncryptionType { get; set; }

    public int? KeyLength { get; set; }

    public string Password { get; set; }

    public override string ToString()  {
      var sb = new StringBuilder();
      sb.Append("class WorkbookEncryptionRequest {\n");
      sb.Append("  EncryptionType: ").Append(EncryptionType).Append("\n");
      sb.Append("  KeyLength: ").Append(KeyLength).Append("\n");
      sb.Append("  Password: ").Append(Password).Append("\n");
      sb.Append("}\n");
      return sb.ToString();
    }
  }
  }


text:
package org.insightech.er.editor.view.action.line;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.swt.widgets.Event;
import org.eclipse.ui.actions.LabelRetargetAction;
import org.insightech.er.ERDiagramActivator;
import org.insightech.er.ImageKey;
import org.insightech.er.ResourceString;
import org.insightech.er.editor.ERDiagramEditor;
import org.insightech.er.editor.controller.command.diagram_contents.element.node.MoveElementCommand;
import org.insightech.er.editor.controller.editpart.element.AbstractModelEditPart;
import org.insightech.er.editor.controller.editpart.element.node.ERTableEditPart;
import org.insightech.er.editor.controller.editpart.element.node.NodeElementEditPart;
import org.insightech.er.editor.controller.editpart.element.node.NoteEditPart;
import org.insightech.er.editor.model.ERDiagram;
import org.insightech.er.editor.model.diagram_contents.element.node.NodeElement;
import org.insightech.er.editor.view.action.AbstractBaseSelectionAction;

public class HorizontalLineAction extends AbstractBaseSelectionAction {

	public static final String ID = HorizontalLineAction.class.getName();

	public HorizontalLineAction(ERDiagramEditor editor) {
		super(ID, ResourceString
				.getResourceString("action.title.horizontal.line"), editor);

		this.setImageDescriptor(ERDiagramActivator
				.getImageDescriptor(ImageKey.HORIZONTAL_LINE));
		// this.setDisabledImageDescriptor(Activator
		// .getImageDescriptor(ImageKey.HORIZONTAL_LINE_DISABLED));
		this.setToolTipText(ResourceString
				.getResourceString("action.title.horizontal.line"));
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected boolean calculateEnabled() {
		Command cmd = this.createCommand();
		if (cmd == null) {
			return false;
		}
		return cmd.canExecute();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void execute(Event event) {
		execute(createCommand());
	}

	private Command createCommand() {
		Command command = null;

		List<NodeElementEditPart> list = new ArrayList<NodeElementEditPart>();

		for (Object object : this.getSelectedObjects()) {
			if (object instanceof ERTableEditPart
					|| object instanceof NoteEditPart) {
				list.add((NodeElementEditPart) object);
			}
		}

		if (list.size() < 3) {
			return null;
		}

		NodeElementEditPart firstEditPart = this.getFirstEditPart(list);
		list.remove(firstEditPart);

		Collections.sort(list, comparator);

		Rectangle firstRectangle = firstEditPart.getFigure().getBounds();
		int start = firstRectangle.x;
		int left = firstRectangle.x + firstRectangle.width;

		Rectangle lastRectangle = list.remove(list.size() - 1).getFigure()
				.getBounds();
		int right = lastRectangle.x;

		if (left > right) {
			command = this.alignToStart(start, list);

		} else {
			command = this.adjustSpace(start, left, right, list);
		}

		return command;
	}

	private Command alignToStart(int start, List<NodeElementEditPart> list) {
		CompoundCommand command = new CompoundCommand();

		ERDiagram diagram = this.getDiagram();

		for (AbstractModelEditPart editPart : list) {
			NodeElement nodeElement = (NodeElement) editPart.getModel();

			MoveElementCommand moveCommand = new MoveElementCommand(diagram,
					editPart.getFigure().getBounds(), start,
					nodeElement.getY(), nodeElement.getWidth(),
					nodeElement.getHeight(), nodeElement);

			command.add(moveCommand);

		}

		return command.unwrap();
	}

	private Command adjustSpace(int start, int left, int right,
			List<NodeElementEditPart> list) {
		CompoundCommand command = new CompoundCommand();

		ERDiagram diagram = this.getDiagram();

		int totalWidth = 0;

		for (AbstractModelEditPart editPart : list) {
			totalWidth += editPart.getFigure().getBounds().width;
		}

		int space = (right - left - totalWidth) / (list.size() + 1);

		int x = left;

		for (AbstractModelEditPart editPart : list) {
			NodeElement nodeElement = (NodeElement) editPart.getModel();

			x += space;

			int nextX = x + editPart.getFigure().getBounds().width;

			if (x < start) {
				x = start;
			}

			MoveElementCommand moveCommand = new MoveElementCommand(diagram,
					editPart.getFigure().getBounds(), x, nodeElement.getY(),
					nodeElement.getWidth(), nodeElement.getHeight(),
					nodeElement);
			command.add(moveCommand);

			x = nextX;
		}

		return command.unwrap();
	}

	private NodeElementEditPart getFirstEditPart(List<NodeElementEditPart> list) {
		NodeElementEditPart firstEditPart = null;

		for (NodeElementEditPart editPart : list) {
			if (firstEditPart == null) {
				firstEditPart = editPart;

			} else {
				if (firstEditPart.getFigure().getBounds().x > editPart
						.getFigure().getBounds().x) {
					firstEditPart = editPart;
				}
			}
		}

		return firstEditPart;
	}

	private static final Comparator<AbstractModelEditPart> comparator = new AbstractModelEditPartHorizontalComparator();

	private static class AbstractModelEditPartHorizontalComparator implements
			Comparator<AbstractModelEditPart> {

		public int compare(AbstractModelEditPart o1, AbstractModelEditPart o2) {
			if (o1 == null) {
				return -1;
			}
			if (o2 == null) {
				return 1;
			}

			Rectangle bounds1 = o1.getFigure().getBounds();
			Rectangle bounds2 = o2.getFigure().getBounds();

			int rightX1 = bounds1.x + bounds1.width;
			int rightX2 = bounds2.x + bounds2.width;

			return rightX1 - rightX2;
		}

	}

	public static class HorizontalLineRetargetAction extends
			LabelRetargetAction {
		public HorizontalLineRetargetAction() {
			super(ID, ResourceString
					.getResourceString("action.title.horizontal.line"));

			this.setImageDescriptor(ERDiagramActivator
					.getImageDescriptor(ImageKey.HORIZONTAL_LINE));
			// this.setDisabledImageDescriptor(Activator
			// .getImageDescriptor(ImageKey.HORIZONTAL_LINE_DISABLED));
			this.setToolTipText(ResourceString
					.getResourceString("action.title.horizontal.line"));
		}

	}

	@Override
	protected List<Command> getCommand(EditPart editPart, Event event) {
		return null;
	}
}


text:
package org.gradle.sample

import org.junit.runner.RunWith
import org.scalatest.FunSpec
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class PersonSpec extends FunSpec:
  describe("create a person") {
    it("should succeed for scala") {
      val person: Named = new Person(List("bob smith"))
      person
    }
  }


text:
{% extends "layout.html" %}

{% block page_title %}
Search for a charge
{% endblock %}

{% block content %}

BETA

Find charges by map

          <form action="map-results" method="GET">

              <fieldset>
                <legend class="visuallyhidden">Enter postcode or charge ID to find a charge</legend>

                  <input class="form-control search-field" id="maintain-map-search" name="maintain-map-search" type="text" value="" autofocus="autofocus">
                  <input class="search-button submit maintain-map-search-button" type="submit" name="maintain-map-search" value="">

              </fieldset>

          </form>

        <form class="form-inline" id="map_controls">
            <select size="5" id="type">
                <option value="Point">Point</option>
                <option value="LineString">LineString</option>
                <option value="Polygon">Polygon</option>
                <option value="Circle">Circle</option>
                <option value="None">None</option>
            </select>
        </form>

You can also search by address, postcode or Unique Property Reference Number (UPRN)

Or you can find a charge by Charge ID

    Find charges

{% endblock %}


text:
class WebusersController < ApplicationController
  before_action :set_webuser, only: [:show, :edit, :update, :destroy]

  # GET /webusers
  # GET /webusers.json
  def index
    @webusers = Webuser.all
  end

  # GET /webusers/1
  # GET /webusers/1.json
  def show
  end

  # GET /webusers/new
  def new
    @webuser = Webuser.new
  end

  # GET /webusers/1/edit
  def edit
  end

  # POST /webusers
  # POST /webusers.json
  def create
    @webuser = Webuser.new(webuser_params)

    respond_to do |format|
      if @webuser.save
        format.html { redirect_to @webuser, notice: 'Webuser was successfully created.' }
        format.json { render action: 'show', status: :created, location: @webuser }
      else
        format.html { render action: 'new' }
        format.json { render json: @webuser.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /webusers/1
  # PATCH/PUT /webusers/1.json
  def update
    respond_to do |format|
      if @webuser.update(webuser_params)
        format.html { redirect_to @webuser, notice: 'Webuser was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @webuser.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /webusers/1
  # DELETE /webusers/1.json
  def destroy
    @webuser.destroy
    respond_to do |format|
      format.html { redirect_to webusers_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_webuser
      @webuser = Webuser.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def webuser_params
      params.require(:webuser).permit(:user_id, :ip)
    end
end


text:
function g = diffy(f, n)
%DIFFY   Differentiate a CHEBFUN3 with respect to its second argument.
%   G = DIFFY(F) returns a CHEBFUN3 representing the derivative of F in its
%   second argument. This is the same as DIFF(F, 1, 2).
%
%   G = DIFFY(F, N) returns a CHEBFUN3 representing the Nth derivative of F
%   in its second argument. This is the same as DIFF(F, N, 2).
%
% See also CHEBFUN3/DIFFX, CHEBFUN3/DIFFZ, and CHEBFUN3/DIFF.

% Copyright 2016 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% Default to first derivative:
if ( nargin == 1 )
    n = 1;
end

% Call diff:
g = diff(f, n, 2);

end


text:
namespace resolve_component_dependencies_test
{
    bool run_app_and_resolve(
        const pal::string_t& hostfxr_path,
        const pal::string_t& app_path,
        const pal::string_t& component_path,
        pal::stringstream_t& test_output);

    bool run_app_and_resolve_multithreaded(
        const pal::string_t& hostfxr_path,
        const pal::string_t& app_path,
        const pal::string_t& component_path_a,
        const pal::string_t& component_path_b,
        pal::stringstream_t& test_output);
}


text:
package org.jaudiotagger.tag.datatype;

import org.jaudiotagger.tag.InvalidDataTypeException;
import org.jaudiotagger.tag.id3.AbstractTagFrameBody;
import org.jaudiotagger.tag.id3.ID3Tags;

/**
 * Represents a number held as a fixed number of digits.
 *
 * The bitorder in ID3v2 is most significant bit first (MSB). The byteorder in multibyte numbers is most significant
 * byte first (e.g. $12345678 would be encoded $12 34 56 78), also known as big endian and network byte order.
 *
 * In ID3Specification would be denoted as $xx xx this denotes exactly two bytes required
 */
public class NumberFixedLength extends AbstractDataType
{
    /**
     * Creates a new ObjectNumberFixedLength datatype.
     *
     * @param identifier
     * @param frameBody
     * @param size       the number of significant places that the number is held to
     * @throws IllegalArgumentException
     */
    public NumberFixedLength(String identifier, AbstractTagFrameBody frameBody, int size)
    {
        super(identifier, frameBody);
        if (size < 0)
        {
            throw new IllegalArgumentException("Length is less than zero: " + size);
        }
        this.size = size;

    }

    public NumberFixedLength(NumberFixedLength copy)
    {
        super(copy);
        this.size = copy.size;
    }

    /**
     * Set Size in Bytes of this Object
     *
     * @param size in bytes that this number will be held as
     */
    public void setSize(int size)
    {
        if (size > 0)
        {
            this.size = size;
        }
    }

    /**
     * Return size
     *
     * @return the size of this number
     */
    public int getSize()
    {
        return size;
    }

    public void setValue(Object value)
    {
        if (!(value instanceof Number))
        {
            throw new IllegalArgumentException("Invalid value type for NumberFixedLength:" + value.getClass());
        }
        super.setValue(value);
    }

    /**
     * @param obj
     * @return true if obj equivalent to this
     */
    public boolean equals(Object obj)
    {
        if (!(obj instanceof NumberFixedLength))
        {
            return false;
        }
        NumberFixedLength object = (NumberFixedLength) obj;
        return this.size == object.size && super.equals(obj);
    }

    /**
     * Read the number from the byte array
     *
     * @param arr
     * @param offset
     * @throws NullPointerException
     * @throws IndexOutOfBoundsException
     */
    public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException
    {
        if (arr == null)
        {
            throw new NullPointerException("Byte array is null");
        }
        if ((offset < 0) || (offset >= arr.length))
        {
            throw new InvalidDataTypeException("Offset to byte array is out of bounds: offset = " + offset + ", array.length = " + arr.length);
        }

        if(offset + size > arr.length)
        {
            throw new InvalidDataTypeException("Offset plus size to byte array is out of bounds: offset = "
                    + offset + ", size = "+size  +" + arr.length "+ arr.length );
        }

        long lvalue = 0;
        for (int i = offset; i < (offset + size); i++)
        {
            lvalue <<= 8;
            lvalue += (arr[i] & 0xff);
        }
        value = lvalue;
        logger.config("Read NumberFixedlength:" + value);
    }

    /**
     * @return String representation of this datatype
     */
    public String toString()
    {
        if (value == null)
        {
            return "";
        }
        else
        {
            return value.toString();
        }
    }

    /**
     * Write data to byte array
     *
     * @return the datatype converted to a byte array
     */
    public byte[] writeByteArray()
    {
        byte[] arr;
        arr = new byte[size];
        if (value != null)
        {
            //Convert value to long
            long temp = ID3Tags.getWholeNumber(value);

            for (int i = size - 1; i >= 0; i--)
            {
                arr[i] = (byte) (temp & 0xFF);
                temp >>= 8;
            }
        }
        return arr;
    }
}


text:
@implementation DSAPITweet

+ (NSString *)className
{
    return kClassName;
}

- (NSURLSessionDataTask *)showWithParameters:(NSDictionary *)parameters
                                       queue:(NSOperationQueue *)queue
                                     success:(void (^)(DSAPITweet *))success
                                     failure:(DSAPIFailureBlock)failure
{
    return [super showWithParameters:parameters
                               queue:queue
                             success:^(DSAPIResource *resource) {
                                 if (success) {
                                     success((DSAPITweet *)resource);
                                 }
                             }
                             failure:failure];
}

- (NSURLSessionDataTask *)postAction:(NSDictionary *)parameters
                               queue:(NSOperationQueue *)queue
                             success:(void (^)(DSAPITweet *))success
                             failure:(DSAPIFailureBlock)failure
{
    NSString *actionsHref = [NSString stringWithFormat:@"%@/%@", self.linkToSelf.href, kActionsKey];

    return [self.client POST:actionsHref
                  parameters:parameters
                       queue:queue
                     success:^(NSHTTPURLResponse *response, id responseObject) {
                         if (success) {
                             success((DSAPITweet *)[responseObject DSAPIResourceWithClient:self.client]);
                         }
                     }
                     failure:^(NSHTTPURLResponse *response, NSError *error) {
                         [self.client postRateLimitingNotificationIfNecessary:response];
                         if (failure) {
                             failure(response, error);
                         }
                     }];
}

@end


text:
#ifndef ScrollbarThemeAura_h
#define ScrollbarThemeAura_h

#include "platform/scroll/ScrollbarThemeNonMacCommon.h"

namespace blink {

class PLATFORM_EXPORT ScrollbarThemeAura : public ScrollbarThemeNonMacCommon {
public:
    int scrollbarThickness(ScrollbarControlSize) override;

protected:
    bool shouldRepaintAllPartsOnInvalidation() const override;
    ScrollbarPart invalidateOnThumbPositionChange(const ScrollbarThemeClient&, float oldPosition, float newPosition) const override;
    void paintTrackPiece(GraphicsContext&, const ScrollbarThemeClient&, const IntRect&, ScrollbarPart) override;
    void paintButton(GraphicsContext&, const ScrollbarThemeClient&, const IntRect&, ScrollbarPart) override;
    void paintThumb(GraphicsContext&, const ScrollbarThemeClient&, const IntRect&) override;
    IntSize buttonSize(const ScrollbarThemeClient&) override;
    int minimumThumbLength(const ScrollbarThemeClient&) override;
};

} // namespace blink

#endif


text:
    <title>ActiveMQ Artemis JMS Symmetric Cluster Example</title>
    <link rel="stylesheet" type="text/css" href="../common/common.css" />
    <link rel="stylesheet" type="text/css" href="../common/prettify.css" />

JMS Symmetric Cluster Example

This examples demonstrates a symmetric cluster set-up with ActiveMQ Artemis.

ActiveMQ Artemis has extremely flexible clustering which allows you to set-up servers in
     many different topologies.

The most common topology that you'll perhaps be familiar with if you are used to application
     server clustering is a symmetric cluster.

With a symmetric cluster, the cluster is homogeneous, i.e. each node is configured the same
     as every other node, and every node is connected to every other node in the cluster.

By connecting node in such a way, we can, from a JMS point of view, give the impression of distributed
     JMS queues and topics.

The configuration used in this example is very similar to the configuration used by ActiveMQ
     when installed as a clustered profile in JBoss Application Server.

To set up ActiveMQ Artemis to form a symmetric cluster we simply need to mark each server as clustered
     and we need to define a cluster-connection in broker.xml.

The cluster-connection tells the nodes what other nodes to make connections to.
     With a cluster-connection each node that we connect to can either be specified
     indivually, or we can use UDP discovery to find out what other nodes are in the cluster.

Using UDP discovery makes configuration simpler since we don't have to know what nodes are
     available at any one time.

Here's the relevant snippet from the server configuration, which tells the server to form a cluster
     with the other nodes:

   <cluster-connection name="my-cluster">
      <address>jms</address>
      <connector-ref>netty-connector</connector-ref>
	   <retry-interval>500</retry-interval>
	   <use-duplicate-detection>true</use-duplicate-detection>
	   <message-load-balancing>STRICT</message-load-balancing>
	   <max-hops>1</max-hops>
	   <discovery-group-ref discovery-group-name="my-discovery-group"/>
   </cluster-connection>

In this example we create a symmetric cluster of six live nodes, and we also pair each live node
     with it's own backup node. (A backup node is not strictly necessary for a symmetric cluster).

In this example will we will demonstrate this by deploying a JMS topic and Queue on all nodes of the cluster
     , sending messages to the queue and topic from different nodes, and verifying messages are received correctly
     by consumers on different nodes.

For more information on configuring ActiveMQ Artemis clustering in general, please see the clustering
     section of the user manual.

Example step-by-step

To run the example, simply type mvn verify -Pexample from this directory

We instantiate a connection factory directly, specifying the UDP address and port for discovering
         the list of servers in the cluster.
         We could use JNDI to look-up a connection factory, but we'd need to know the JNDI server host and port for the
         specific server to do that, and that server might not be available at the time. By creating the
         connection factory directly we avoid having to worry about a JNDI look-up.
         In an app server environment you could use HA-JNDI to lookup from the clustered JNDI servers without
         having to know about a specific one.

   ConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithHA("231.7.7.7", 9876);

Directly instantiate JMS Queue and Topic objects

   Queue queue = new ActiveMQQueue("exampleQueue");

   Topic topic = ActiveMQJMSClient.createActiveMQTopic("exampleTopic");

We create six connections, they should be to different nodes of the cluster in a round-robin fashion
         and start them.

   connection0 = cf.createConnection();

     connection1 = cf.createConnection();

     connection2 = cf.createConnection();

     connection3 = cf.createConnection();

     connection4 = cf.createConnection();

     connection5 = cf.createConnection();

     connection0.start();

     connection1.start();

     connection2.start();

     connection3.start();

     connection4.start();

     connection5.start();

We create a session on each connection.

     Session session0 = connection0.createSession(false, Session.AUTO_ACKNOWLEDGE);

     Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);

     Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

     Session session3 = connection0.createSession(false, Session.AUTO_ACKNOWLEDGE);

     Session session4 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);

     Session session5 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

We create a topic subscriber on each server.

         MessageConsumer subscriber0 = session0.createConsumer(topic);

         MessageConsumer subscriber1 = session1.createConsumer(topic);

         MessageConsumer subscriber2 = session2.createConsumer(topic);

         MessageConsumer subscriber3 = session3.createConsumer(topic);

         MessageConsumer subscriber4 = session4.createConsumer(topic);

         MessageConsumer subscriber5 = session5.createConsumer(topic);

We create a queue consumer on server 0.

   MessageConsumer consumer0 = session0.createConsumer(queue);

We create an anonymous message producer on server 2.

   MessageProducer producer2 = session2.createProducer(null);

We send 500 messages each to the queue and topic.

   final int numMessages = 500;

   for (int i = 0; i < numMessages; i++)
   {
      TextMessage message1 = session2.createTextMessage("Topic message 1");

      producer2.send(topic, message1);

      TextMessage message2 = session2.createTextMessage("Queue message 1");

      producer2.send(queue, message2);
   }

Verify all subscribers and consumer receive the messages.

   for (int i = 0; i < numMessages; i++)
     {
        TextMessage received0 = (TextMessage)subscriber0.receive(5000);

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

        TextMessage received1 = (TextMessage)subscriber1.receive(5000);

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

        TextMessage received2 = (TextMessage)subscriber2.receive(5000);

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

        TextMessage received3 = (TextMessage)subscriber3.receive(5000);

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

        TextMessage received4 = (TextMessage)subscriber4.receive(5000);

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

        TextMessage received5 = (TextMessage)subscriber5.receive(5000);

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

        TextMessage received6 = (TextMessage)consumer0.receive(5000);

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

Be sure to close our resources!

   finally
   {
      if (connection0 != null)
      {
         connection0.close();
      }

      if (connection1 != null)
      {
         connection1.close();
      }

      if (connection2 != null)
      {
         connection2.close();
      }
   }


text:
var gulp = require('gulp'),
  plugins = require('gulp-load-plugins')(),
  pack = require('./package.json'),
  port = 9191;

gulp.task('coffee', function() {
  gulp.src('./src/*.coffee')
    .pipe(plugins.coffee({bare: true}))
    .pipe(gulp.dest('.tmp'))
});

gulp.task('less', function () {
  gulp.src('./src/**/*.less')
    .pipe(plugins.less())
    .pipe(gulp.dest('.tmp'));

});

gulp.task('server', ["coffee","less","watch"], function () {
  plugins.connect.server({
    root: ['bower_components', '.tmp', 'src'],
    port: port,
    livereload: true
  });
  plugins.bower()
         .on('end',function(){
           require('opn')('http://localhost:' + port + '/')
  });
});

gulp.task('watch',function(){
  gulp.watch('./src/*.coffee', ['coffee']);
});

gulp.task('build', function(){
  gulp.src('src/*.coffee')
    .pipe(plugins.coffee())
    .pipe(plugins.uglify())
    .pipe(plugins.header('//author: <%= author %>\n//verion: <%= version %>\n',{author:pack.author,version:pack.version}))
    .pipe(gulp.dest('dist'));
  gulp.src('./src/**/*.less')
    .pipe(plugins.less())
    .pipe(gulp.dest('dist'));
});

gulp.task('default', ['build']);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DansLEnsemble.Messages
{
    class MessageBoxQuestionMessage
    {
        public string Content { get; set; }
        public string Response { get; set; }
        public Action<string> ActionOnResponse { get; set; }
    }
}