<commit_before>
var Scope = require("./scope");
var Observers = require("./observers");
var autoCancelPrevious = Observers.autoCancelPrevious;
var once = Observers.once;
var observeRangeChange = Observers.observeRangeChange;
var cancelEach = Observers.cancelEach;
var makeNotObserver = Observers.makeNotObserver;
var makeOrObserver = Observers.makeOrObserver;
var makeAndObserver = Observers.makeAndObserver;
var observeValue = Observers.observeValue;
var observeUndefined = Observers.makeLiteralObserver();
var trueScope = new Scope(true);
var falseScope = new Scope(false);

exports.bindProperty = bindProperty;
var _bindProperty = bindProperty; // to bypass scope shadowing problems below
function bindProperty(object, key, observeValue, source, descriptor, trace) {
    return observeValue(autoCancelPrevious(function replaceBoundPropertyValue(value) {
        if (descriptor.isActive) {
            return;
        }
        try {
            descriptor.isActive = true;
            trace && console.log("SET", trace.targetPath, "TO", value, "ON", object, "BECAUSE", trace.sourcePath, new Error("here").stack);
            if (Array.isArray(object) && key >>> 0 === key) {
                // TODO spec this case
                object.set(key, value);
            } else {
                object[key] = value;
            }
        } finally {
            descriptor.isActive = false;
        }
    }), source);
}

exports.makePropertyBinder = makePropertyBinder;
function makePropertyBinder(observeObject, observeKey) {
    return function bindProperty(observeValue, source, target, descriptor, trace) {
        return observeKey(autoCancelPrevious(function replaceKey(key) {
            if (key == null) return;
            return observeObject(autoCancelPrevious(function replaceObject(object) {
                if (object == null) return;
                if (object.bindProperty) {
                    return object.bindProperty(key, observeValue, source, descriptor, trace);
                } else {
                    return _bindProperty(object, key, observeValue, source, descriptor, trace);
                }
            }), target);
        }), target);
    };
}

exports.bindGet = bindGet;
var _bindGet = bindGet; // to bypass scope shadowing below
function bindGet(collection, key, observeValue, source, descriptor, trace) {
    return observeValue(autoCancelPrevious(function replaceValue(value) {
        if (descriptor.isActive) {
            return;
        }
        try {
            descriptor.isActive = true;
            trace && console.log("SET FOR KEY", key, "TO", value, "ON", collection, "BECAUSE", trace.sourcePath, new Error("here").stack);
            collection.set(key, value);
        } finally {
            descriptor.isActive = false;
        }
    }), source);
}

exports.makeGetBinder = makeGetBinder;
function makeGetBinder(observeCollection, observeKey) {
    return function bindGet(observeValue, source, target, descriptor, trace) {
        return observeCollection(autoCancelPrevious(function replaceCollection(collection) {
            if (!collection) return;
            return observeKey(autoCancelPrevious(function replaceKey(key) {
                if (key == null) return;
                return _bindGet(collection, key, observeValue, source, descriptor, trace);
            }), target);
        }), target);
    };
}

exports.makeHasBinder = makeHasBinder;
function makeHasBinder(observeSet, observeValue) {
    return function bindHas(observeHas, source, target, descriptor, trace) {
        return observeSet(autoCancelPrevious(function replaceHasBindingSet(set) {
            if (!set) return;
            return observeValue(autoCancelPrevious(function replaceHasBindingValue(value) {
                return observeHas(autoCancelPrevious(function changeWhetherSetHas(has) {
                    // wait for the initial value to be updated by the
                    // other-way binding
                    if (has) { // should be in set
                        if (!(set.has || set.contains).call(set, value)) {
                            trace && console.log("ADD", value, "TO", trace.targetPath, "BECAUSE", trace.sourcePath, new Error("here").stack);
                            set.add(value);
                        }
                    } else { // should not be in set
                        while ((set.has || set.contains).call(set, value)) {
                            trace && console.log("REMOVE", value, "FROM", trace.targetPath, "BECAUSE", trace.sourcePath, new Error("here").stack);
                            (set.remove || set['delete']).call(set, value);
                        }
                    }
                }), source);
            }), target);
        }), target);
    };
}

// a == b <-> c
exports.makeEqualityBinder = makeEqualityBinder;
function makeEqualityBinder(bindLeft, observeRight) {
    return function bindEquals(observeEquals, source, target, descriptor, trace) {
        // c
        return observeEquals(autoCancelPrevious(function changeWhetherEquals(equals) {
            if (equals) {
                trace && console.log("BIND", trace.targetPath, "TO", trace.sourcePath, new Error("here").stack);
                // a <-> b
                var cancel = bindLeft(observeRight, source, source, descriptor, trace);
                return function cancelEqualityBinding() {
                    trace && console.log("UNBIND", trace.targetPath, "FROM", trace.sourcePath, new Error("here").stack);
                };
            }
        }), target);
    };
}

// collection.every{condition} <- everyCondition
exports.makeEveryBlockBinder = makeEveryBlockBinder;
function makeEveryBlockBinder(observeCollection, bindCondition, observeValue) {
    return function bindEveryBlock(observeEveryCondition, source, target, descriptor, trace) {
        return observeEveryCondition(autoCancelPrevious(function replaceCondition(condition) {
            if (!condition) return;
            return observeCollection(autoCancelPrevious(function replaceCollection(collection) {
                if (!collection) return;
                var cancelers = [];
                function rangeChange(plus, minus, index) {
                    cancelers.swap(index, minus.length, plus.map(function (value, offset) {
                        var scope = Scope.nest(target, value);
                        return bindCondition(observeValue, scope, scope, descriptor, trace);
                    }));
                }
                var cancelRangeChange = observeRangeChange(collection, rangeChange, target);
                return function cancelEveryBinding() {
                    cancelEach(cancelers);
                    cancelRangeChange();
                };
            }), target);
        }), source);
    };
};

exports.makeAndBinder = makeAndBinder;
function makeAndBinder(bindLeft, bindRight, observeLeft, observeRight, observeLeftBind, observeRightBind) {
    var observeNotRight = makeNotObserver(observeRight);
    var observeLeftAndNotRight = makeAndObserver(observeLeft, observeNotRight);
    return function bindEveryBlock(observeAndCondition, source, target, descriptor, trace) {
        return observeAndCondition(autoCancelPrevious(function replaceAndCondition(condition) {
            if (condition == null) {
            } else if (condition) {
                var cancelLeft = bindLeft(observeLeftBind, trueScope, target, descriptor, trace);
                var cancelRight = bindRight(observeRightBind, trueScope, target, descriptor, trace);
                return function cancelAndBinding() {
                    cancelLeft();
                    cancelRight();
                };
            } else {
                return bindLeft(observeLeftAndNotRight, target, target, descriptor, trace);
            }
        }), source);
    };
}

exports.makeOrBinder = makeOrBinder;
function makeOrBinder(bindLeft, bindRight, observeLeft, observeRight, observeLeftBind, observeRightBind) {
    var observeNotRight = makeNotObserver(observeRight);
    var observeLeftOrNotRight = makeOrObserver(observeLeft, observeNotRight);
    return function bindEveryBlock(observeOrCondition, source, target, descriptor, trace) {
        return observeOrCondition(autoCancelPrevious(function replaceOrCondition(condition) {
            if (condition == null) {
            } else if (!condition) {
                var cancelLeft = bindLeft(observeLeftBind, falseScope, target, descriptor, trace);
                var cancelRight = bindRight(observeRightBind, falseScope, target, descriptor, trace); return function cancelOrBinding() {
                    cancelLeft();
                    cancelRight();
                };
            } else {
                return bindLeft(observeLeftOrNotRight, target, target, descriptor, trace);
            }
        }), source);
    };
}

// (a ? b : c) <- d
exports.makeConditionalBinder = makeConditionalBinder;
function makeConditionalBinder(observeCondition, bindConsequent, bindAlternate) {
    return function bindCondition(observeSource, source, target, descriptor, trace) {
        // a
        return observeCondition(autoCancelPrevious(function replaceCondition(condition) {
            if (condition == null) return;
            if (condition) {
                // b <- d
                return bindConsequent(observeSource, source, target, descriptor, trace);
            } else {
                // c <- d
                return bindAlternate(observeSource, source, target, descriptor, trace);
            }
        }), source);
    };
}

// a.* <- b.*
exports.makeRangeContentBinder = makeRangeContentBinder;
function makeRangeContentBinder(observeTarget, bindTarget) {
    return function bindRangeContent(observeSource, sourceScope, targetScope, descriptor, trace) {
        return observeTarget(autoCancelPrevious(function replaceRangeContentTarget(target) {
            if (!target) {
                return bindTarget(
                    Observers.makeLiteralObserver([]),
                    sourceScope,
                    targetScope,
                    descriptor,
                    trace
                );
            }

            return observeSource(autoCancelPrevious(function replaceRangeContentSource(source) {
                if (source === target) {
                    return;
                }
                if (!source) {
                    target.clear();
                    return;
                }
                if (!source.addRangeChangeListener) {
                    return;
                }

                function rangeContentSourceRangeChange(plus, minus, index) {
                    if (isActive(target))
                        return;
                    if (trace) {
                        console.log("SWAPPING", minus, "FOR", plus, "AT", index, "ON", trace.targetPath, new Error("here").stack);
                    }
                    if (target.swap) {
                        target.swap(index, minus.length, plus);
                    } else if (target.add && (target.remove || target["delete"])) {
                        plus.forEach(target.add, target);
                        minus.forEach(target.remove || target["delete"], target);
                    }
                }

                source.addRangeChangeListener(rangeContentSourceRangeChange);
                rangeContentSourceRangeChange(Array.from(source), Array.from(target), 0);
                return once(function cancelRangeContentBinding() {
                    source.removeRangeChangeListener(rangeContentSourceRangeChange);
                });
            }), sourceScope);
        }), targetScope);
    };
}

exports.makeMapContentBinder = makeMapContentBinder;
function makeMapContentBinder(observeTarget) {
    return function bindMapContent(observeSource, source, target, descriptor, trace) {
        return observeTarget(autoCancelPrevious(function replaceMapContentBindingTarget(target) {
            if (!target) return;
            return observeSource(autoCancelPrevious(function replaceMapContentBindingSource(source) {
                if (!source) {
                    target.clear();
                    return;
                }

                function mapChange(value, key) {
                    if (descriptor.isActive) {
                        return;
                    }
                    try {
                        descriptor.isActive = true;
                        if (value === undefined) {
                            if (trace) {
                                trace && console.log("DELETED", trace.targetPath, "FOR KEY", key, "ON", target, "BECAUSE", trace.sourcePath, new Error("here").stack);
                            }
                            if (Array.isArray(target)) {
                                target.splice(key, 1);
                            } else {
                                target["delete"](key);
                            }
                        } else {
                            if (trace) {
                                trace && console.log("SET", trace.targetPath, "FOR KEY", key, "TO", value, "ON", target, "BECAUSE", trace.sourcePath, new Error("here").stack);
                            }
                            target.set(key, value);
                        }
                    } finally {
                        descriptor.isActive = false;
                    }
                }
                target.clear();
                source.forEach(mapChange);
                return source.addMapChangeListener(mapChange);
            }), source);
        }), target);
    };
}

// a.reversed() <-> b
exports.makeReversedBinder = makeReversedBinder;
function makeReversedBinder(observeTarget) {
    return function bindReversed(observeSource, source, target, descriptor, trace) {
        return observeTarget(autoCancelPrevious(function replaceReversedBindingTarget(target) {
            if (!target) return;
            return observeSource(autoCancelPrevious(function replaceReversedBindingSource(source) {
                if (!source) {
                    target.clear();
                    return;
                }

                function rangeChange(plus, minus, index) {
                    if (isActive(target))
                        return;
                    var reflected = target.length - index - minus.length;
                    target.swap(reflected, minus.length, plus.reversed());
                }
                source.addRangeChangeListener(rangeChange);
                rangeChange(source, target, 0);
                return once(function cancelReversedBinding() {
                    source.removeRangeChangeListener(rangeChange);
                });
            }), source);
        }), target);
    };
}

exports.makeDefinedBinder = makeDefinedBinder;
function makeDefinedBinder(bindTarget) {
    return function bindReversed(observeSource, sourceScope, targetScope, descriptor, trace) {
        return observeSource(autoCancelPrevious(function replaceSource(condition) {
            if (!condition) {
                return bindTarget(
                    observeUndefined,
                    sourceScope,
                    targetScope,
                    descriptor,
                    trace
                );
            } else {
                return Function.noop;
            }
        }), targetScope);
    }
}

function isActive(target) {
    return (
        target.getRangeChangeDescriptor &&
        target.getRangeChangeDescriptor().isActive
    );
}

<commit_msg>Short-circuit has(value) binding if value is null<commit_after>
var Scope = require("./scope");
var Observers = require("./observers");
var autoCancelPrevious = Observers.autoCancelPrevious;
var once = Observers.once;
var observeRangeChange = Observers.observeRangeChange;
var cancelEach = Observers.cancelEach;
var makeNotObserver = Observers.makeNotObserver;
var makeOrObserver = Observers.makeOrObserver;
var makeAndObserver = Observers.makeAndObserver;
var observeValue = Observers.observeValue;
var observeUndefined = Observers.makeLiteralObserver();
var trueScope = new Scope(true);
var falseScope = new Scope(false);

exports.bindProperty = bindProperty;
var _bindProperty = bindProperty; // to bypass scope shadowing problems below
function bindProperty(object, key, observeValue, source, descriptor, trace) {
    return observeValue(autoCancelPrevious(function replaceBoundPropertyValue(value) {
        if (descriptor.isActive) {
            return;
        }
        try {
            descriptor.isActive = true;
            trace && console.log("SET", trace.targetPath, "TO", value, "ON", object, "BECAUSE", trace.sourcePath, new Error("here").stack);
            if (Array.isArray(object) && key >>> 0 === key) {
                // TODO spec this case
                object.set(key, value);
            } else {
                object[key] = value;
            }
        } finally {
            descriptor.isActive = false;
        }
    }), source);
}

exports.makePropertyBinder = makePropertyBinder;
function makePropertyBinder(observeObject, observeKey) {
    return function bindProperty(observeValue, source, target, descriptor, trace) {
        return observeKey(autoCancelPrevious(function replaceKey(key) {
            if (key == null) return;
            return observeObject(autoCancelPrevious(function replaceObject(object) {
                if (object == null) return;
                if (object.bindProperty) {
                    return object.bindProperty(key, observeValue, source, descriptor, trace);
                } else {
                    return _bindProperty(object, key, observeValue, source, descriptor, trace);
                }
            }), target);
        }), target);
    };
}

exports.bindGet = bindGet;
var _bindGet = bindGet; // to bypass scope shadowing below
function bindGet(collection, key, observeValue, source, descriptor, trace) {
    return observeValue(autoCancelPrevious(function replaceValue(value) {
        if (descriptor.isActive) {
            return;
        }
        try {
            descriptor.isActive = true;
            trace && console.log("SET FOR KEY", key, "TO", value, "ON", collection, "BECAUSE", trace.sourcePath, new Error("here").stack);
            collection.set(key, value);
        } finally {
            descriptor.isActive = false;
        }
    }), source);
}

exports.makeGetBinder = makeGetBinder;
function makeGetBinder(observeCollection, observeKey) {
    return function bindGet(observeValue, source, target, descriptor, trace) {
        return observeCollection(autoCancelPrevious(function replaceCollection(collection) {
            if (!collection) return;
            return observeKey(autoCancelPrevious(function replaceKey(key) {
                if (key == null) return;
                return _bindGet(collection, key, observeValue, source, descriptor, trace);
            }), target);
        }), target);
    };
}

exports.makeHasBinder = makeHasBinder;
function makeHasBinder(observeSet, observeValue) {
    return function bindHas(observeHas, source, target, descriptor, trace) {
        return observeSet(autoCancelPrevious(function replaceHasBindingSet(set) {
            if (!set) return;
            return observeValue(autoCancelPrevious(function replaceHasBindingValue(value) {
                if (value == null) return;
                return observeHas(autoCancelPrevious(function changeWhetherSetHas(has) {
                    // wait for the initial value to be updated by the
                    // other-way binding
                    if (has) { // should be in set
                        if (!(set.has || set.contains).call(set, value)) {
                            trace && console.log("ADD", value, "TO", trace.targetPath, "BECAUSE", trace.sourcePath, new Error("here").stack);
                            set.add(value);
                        }
                    } else { // should not be in set
                        while ((set.has || set.contains).call(set, value)) {
                            trace && console.log("REMOVE", value, "FROM", trace.targetPath, "BECAUSE", trace.sourcePath, new Error("here").stack);
                            (set.remove || set['delete']).call(set, value);
                        }
                    }
                }), source);
            }), target);
        }), target);
    };
}

// a == b <-> c
exports.makeEqualityBinder = makeEqualityBinder;
function makeEqualityBinder(bindLeft, observeRight) {
    return function bindEquals(observeEquals, source, target, descriptor, trace) {
        // c
        return observeEquals(autoCancelPrevious(function changeWhetherEquals(equals) {
            if (equals) {
                trace && console.log("BIND", trace.targetPath, "TO", trace.sourcePath, new Error("here").stack);
                // a <-> b
                var cancel = bindLeft(observeRight, source, source, descriptor, trace);
                return function cancelEqualityBinding() {
                    trace && console.log("UNBIND", trace.targetPath, "FROM", trace.sourcePath, new Error("here").stack);
                };
            }
        }), target);
    };
}

// collection.every{condition} <- everyCondition
exports.makeEveryBlockBinder = makeEveryBlockBinder;
function makeEveryBlockBinder(observeCollection, bindCondition, observeValue) {
    return function bindEveryBlock(observeEveryCondition, source, target, descriptor, trace) {
        return observeEveryCondition(autoCancelPrevious(function replaceCondition(condition) {
            if (!condition) return;
            return observeCollection(autoCancelPrevious(function replaceCollection(collection) {
                if (!collection) return;
                var cancelers = [];
                function rangeChange(plus, minus, index) {
                    cancelers.swap(index, minus.length, plus.map(function (value, offset) {
                        var scope = Scope.nest(target, value);
                        return bindCondition(observeValue, scope, scope, descriptor, trace);
                    }));
                }
                var cancelRangeChange = observeRangeChange(collection, rangeChange, target);
                return function cancelEveryBinding() {
                    cancelEach(cancelers);
                    cancelRangeChange();
                };
            }), target);
        }), source);
    };
};

exports.makeAndBinder = makeAndBinder;
function makeAndBinder(bindLeft, bindRight, observeLeft, observeRight, observeLeftBind, observeRightBind) {
    var observeNotRight = makeNotObserver(observeRight);
    var observeLeftAndNotRight = makeAndObserver(observeLeft, observeNotRight);
    return function bindEveryBlock(observeAndCondition, source, target, descriptor, trace) {
        return observeAndCondition(autoCancelPrevious(function replaceAndCondition(condition) {
            if (condition == null) {
            } else if (condition) {
                var cancelLeft = bindLeft(observeLeftBind, trueScope, target, descriptor, trace);
                var cancelRight = bindRight(observeRightBind, trueScope, target, descriptor, trace);
                return function cancelAndBinding() {
                    cancelLeft();
                    cancelRight();
                };
            } else {
                return bindLeft(observeLeftAndNotRight, target, target, descriptor, trace);
            }
        }), source);
    };
}

exports.makeOrBinder = makeOrBinder;
function makeOrBinder(bindLeft, bindRight, observeLeft, observeRight, observeLeftBind, observeRightBind) {
    var observeNotRight = makeNotObserver(observeRight);
    var observeLeftOrNotRight = makeOrObserver(observeLeft, observeNotRight);
    return function bindEveryBlock(observeOrCondition, source, target, descriptor, trace) {
        return observeOrCondition(autoCancelPrevious(function replaceOrCondition(condition) {
            if (condition == null) {
            } else if (!condition) {
                var cancelLeft = bindLeft(observeLeftBind, falseScope, target, descriptor, trace);
                var cancelRight = bindRight(observeRightBind, falseScope, target, descriptor, trace); return function cancelOrBinding() {
                    cancelLeft();
                    cancelRight();
                };
            } else {
                return bindLeft(observeLeftOrNotRight, target, target, descriptor, trace);
            }
        }), source);
    };
}

// (a ? b : c) <- d
exports.makeConditionalBinder = makeConditionalBinder;
function makeConditionalBinder(observeCondition, bindConsequent, bindAlternate) {
    return function bindCondition(observeSource, source, target, descriptor, trace) {
        // a
        return observeCondition(autoCancelPrevious(function replaceCondition(condition) {
            if (condition == null) return;
            if (condition) {
                // b <- d
                return bindConsequent(observeSource, source, target, descriptor, trace);
            } else {
                // c <- d
                return bindAlternate(observeSource, source, target, descriptor, trace);
            }
        }), source);
    };
}

// a.* <- b.*
exports.makeRangeContentBinder = makeRangeContentBinder;
function makeRangeContentBinder(observeTarget, bindTarget) {
    return function bindRangeContent(observeSource, sourceScope, targetScope, descriptor, trace) {
        return observeTarget(autoCancelPrevious(function replaceRangeContentTarget(target) {
            if (!target) {
                return bindTarget(
                    Observers.makeLiteralObserver([]),
                    sourceScope,
                    targetScope,
                    descriptor,
                    trace
                );
            }

            return observeSource(autoCancelPrevious(function replaceRangeContentSource(source) {
                if (source === target) {
                    return;
                }
                if (!source) {
                    target.clear();
                    return;
                }
                if (!source.addRangeChangeListener) {
                    return;
                }

                function rangeContentSourceRangeChange(plus, minus, index) {
                    if (isActive(target))
                        return;
                    if (trace) {
                        console.log("SWAPPING", minus, "FOR", plus, "AT", index, "ON", trace.targetPath, new Error("here").stack);
                    }
                    if (target.swap) {
                        target.swap(index, minus.length, plus);
                    } else if (target.add && (target.remove || target["delete"])) {
                        plus.forEach(target.add, target);
                        minus.forEach(target.remove || target["delete"], target);
                    }
                }

                source.addRangeChangeListener(rangeContentSourceRangeChange);
                rangeContentSourceRangeChange(Array.from(source), Array.from(target), 0);
                return once(function cancelRangeContentBinding() {
                    source.removeRangeChangeListener(rangeContentSourceRangeChange);
                });
            }), sourceScope);
        }), targetScope);
    };
}

exports.makeMapContentBinder = makeMapContentBinder;
function makeMapContentBinder(observeTarget) {
    return function bindMapContent(observeSource, source, target, descriptor, trace) {
        return observeTarget(autoCancelPrevious(function replaceMapContentBindingTarget(target) {
            if (!target) return;
            return observeSource(autoCancelPrevious(function replaceMapContentBindingSource(source) {
                if (!source) {
                    target.clear();
                    return;
                }

                function mapChange(value, key) {
                    if (descriptor.isActive) {
                        return;
                    }
                    try {
                        descriptor.isActive = true;
                        if (value === undefined) {
                            if (trace) {
                                trace && console.log("DELETED", trace.targetPath, "FOR KEY", key, "ON", target, "BECAUSE", trace.sourcePath, new Error("here").stack);
                            }
                            if (Array.isArray(target)) {
                                target.splice(key, 1);
                            } else {
                                target["delete"](key);
                            }
                        } else {
                            if (trace) {
                                trace && console.log("SET", trace.targetPath, "FOR KEY", key, "TO", value, "ON", target, "BECAUSE", trace.sourcePath, new Error("here").stack);
                            }
                            target.set(key, value);
                        }
                    } finally {
                        descriptor.isActive = false;
                    }
                }
                target.clear();
                source.forEach(mapChange);
                return source.addMapChangeListener(mapChange);
            }), source);
        }), target);
    };
}

// a.reversed() <-> b
exports.makeReversedBinder = makeReversedBinder;
function makeReversedBinder(observeTarget) {
    return function bindReversed(observeSource, source, target, descriptor, trace) {
        return observeTarget(autoCancelPrevious(function replaceReversedBindingTarget(target) {
            if (!target) return;
            return observeSource(autoCancelPrevious(function replaceReversedBindingSource(source) {
                if (!source) {
                    target.clear();
                    return;
                }

                function rangeChange(plus, minus, index) {
                    if (isActive(target))
                        return;
                    var reflected = target.length - index - minus.length;
                    target.swap(reflected, minus.length, plus.reversed());
                }
                source.addRangeChangeListener(rangeChange);
                rangeChange(source, target, 0);
                return once(function cancelReversedBinding() {
                    source.removeRangeChangeListener(rangeChange);
                });
            }), source);
        }), target);
    };
}

exports.makeDefinedBinder = makeDefinedBinder;
function makeDefinedBinder(bindTarget) {
    return function bindReversed(observeSource, sourceScope, targetScope, descriptor, trace) {
        return observeSource(autoCancelPrevious(function replaceSource(condition) {
            if (!condition) {
                return bindTarget(
                    observeUndefined,
                    sourceScope,
                    targetScope,
                    descriptor,
                    trace
                );
            } else {
                return Function.noop;
            }
        }), targetScope);
    }
}

function isActive(target) {
    return (
        target.getRangeChangeDescriptor &&
        target.getRangeChangeDescriptor().isActive
    );
}

<|endoftext|>


<commit_before>require( 'wTools' );
require( '../staging/abase/printer/printer/Logger.s' );

var _ = wTools;

var colorNames = _.mapOwnKeys( _.color.ColorMapShell );
var n = 0;
// var list = [];
var c = 0;
var line = '';
for( var i = 0; i < colorNames.length; i++ )
{
  var fg = colorNames[ i ];

  for( var j = colorNames.length - 1; j >= 0; --j )
  {
    var bg = colorNames[ j ];
    n++;
    var text = '  #' + n + '  ';
    // list.push( [ '#' + n + ' ' + fg + ' - ' + bg ] )

    if( n <= 10 )
    text += '  ';
    else if( n <= 100 )
    text += ' ';

    line += _.strColor.bg( _.strColor.fg( text, fg ), bg );
    c++;
    if( c === 8 )
    {
      logger.log( line );
      c = 0;
      line = '';
    }
  }
}

/* List :

Number  foreground - backround

#1 white - light white            #2 white - light green           #3 white - light cyan
#4 white - light blue             #5 white - light magenta         #6 white - light red
#7 white - light yellow           #8 white - light black           #9 white - magenta
#10 white - cyan                  #11 white - blue                 #12 white - yellow
#13 white - red                   #14 white - green                #15 white - black
#16 white - white                 #17 black - light white          #18 black - light green
#19 black - light cyan            #20 black - light blue           #21 black - light magenta
#22 black - light red             #23 black - light yellow         #24 black - light black
#25 black - magenta               #26 black - cyan                 #27 black - blue
#28 black - yellow                #29 black - red                  #30 black - green
#31 black - black                 #32 black - white                #33 green - light white
#34 green - light green           #35 green - light cyan           #36 green - light blue
#37 green - light magenta         #38 green - light red            #39 green - light yellow
#40 green - light black           #41 green - magenta              #42 green - cyan
#43 green - blue                  #44 green - yellow               #45 green - red
#46 green - green                 #47 green - black                #48 green - white
#49 red - light white             #50 red - light green            #51 red - light cyan
#52 red - light blue              #53 red - light magenta          #54 red - light red
#55 red - light yellow            #56 red - light black            #57 red - magenta
#58 red - cyan                    #59 red - blue                   #60 red - yellow
#61 red - red                     #62 red - green                  #63 red - black
#64 red - white                   #65 yellow - light white         #66 yellow - light green
#67 yellow - light cyan           #68 yellow - light blue          #69 yellow - light magenta
#70 yellow - light red            #71 yellow - light yellow        #72 yellow - light black
#73 yellow - magenta              #74 yellow - cyan                #75 yellow - blue
#76 yellow - yellow               #77 yellow - red                 #78 yellow - green
#79 yellow - black                #80 yellow - white               #81 blue - light white
#82 blue - light green            #83 blue - light cyan            #84 blue - light blue
#85 blue - light magenta          #86 blue - light red             #87 blue - light yellow
#88 blue - light black            #89 blue - magenta               #90 blue - cyan
#91 blue - blue                   #92 blue - yellow                #93 blue - red
#94 blue - green                  #95 blue - black                 #96 blue - white
#97 cyan - light white            #98 cyan - light green           #99 cyan - light cyan
#100 cyan - light blue            #101 cyan - light magenta        #102 cyan - light red
#103 cyan - light yellow          #104 cyan - light black          #105 cyan - magenta
#106 cyan - cyan                  #107 cyan - blue                 #108 cyan - yellow
#109 cyan - red                   #110 cyan - green                #111 cyan - black
#112 cyan - white                 #113 magenta - light white       #114 magenta - light green
#115 magenta - light cyan         #116 magenta - light blue        #117 magenta - light magenta
#118 magenta - light red          #119 magenta - light yellow      #120 magenta - light black
#121 magenta - magenta            #122 magenta - cyan              #123 magenta - blue
#124 magenta - yellow             #125 magenta - red               #126 magenta - green
#127 magenta - black              #128 magenta - white             #129 light black - light white
#130 light black - light green    #131 light black - light cyan    #132 light black - light blue
#133 light black - light magenta  #134 light black - light red     #135 light black - light yellow
#136 light black - light black    #137 light black - magenta       #138 light black - cyan
#139 light black - blue           #140 light black - yellow        #141 light black - red
#142 light black - green          #143 light black - black         #144 light black - white
#145 light yellow - light white   #146 light yellow - light green  #147 light yellow - light cyan
#148 light yellow - light blue    #149 light yellow - light magenta#150 light yellow - light red
#151 light yellow - light yellow  #152 light yellow - light black  #153 light yellow - magenta
#154 light yellow - cyan          #155 light yellow - blue         #156 light yellow - yellow
#157 light yellow - red           #158 light yellow - green        #159 light yellow - black
#160 light yellow - white         #161 light red - light white     #162 light red - light green
#163 light red - light cyan       #164 light red - light blue      #165 light red - light magenta
#166 light red - light red        #167 light red - light yellow    #168 light red - light black
#169 light red - magenta          #170 light red - cyan            #171 light red - blue
#172 light red - yellow           #173 light red - red             #174 light red - green
#175 light red - black            #176 light red - white           #177 light magenta - light white
#178 light magenta - light green  #179 light magenta - light cyan  #180 light magenta - light blue
#181 light magenta - light magenta#182 light magenta - light red   #183 light magenta - light yellow
#184 light magenta - light black  #185 light magenta - magenta     #186 light magenta - cyan
#187 light magenta - blue         #188 light magenta - yellow      #189 light magenta - red
#190 light magenta - green        #191 light magenta - black       #192 light magenta - white
#193 light blue - light white     #194 light blue - light green    #195 light blue - light cyan
#196 light blue - light blue      #197 light blue - light magenta  #198 light blue - light red
#199 light blue - light yellow    #200 light blue - light black    #201 light blue - magenta
#202 light blue - cyan            #203 light blue - blue           #204 light blue - yellow
#205 light blue - red             #206 light blue - green          #207 light blue - black
#208 light blue - white           #209 light cyan - light white    #210 light cyan - light green
#211 light cyan - light cyan      #212 light cyan - light blue     #213 light cyan - light magenta
#214 light cyan - light red       #215 light cyan - light yellow   #216 light cyan - light black
#217 light cyan - magenta         #218 light cyan - cyan           #219 light cyan - blue
#220 light cyan - yellow          #221 light cyan - red            #222 light cyan - green
#223 light cyan - black           #224 light cyan - white          #225 light green - light white
#226 light green - light green    #227 light green - light cyan    #228 light green - light blue
#229 light green - light magenta  #230 light green - light red     #231 light green - light yellow
#232 light green - light black    #233 light green - magenta       #234 light green - cyan
#235 light green - blue           #236 light green - yellow        #237 light green - red
#238 light green - green          #239 light green - black         #240 light green - white
#241 light white - light white    #242 light white - light green   #243 light white - light cyan
#244 light white - light blue     #245 light white - light magenta #246 light white - light red
#247 light white - light yellow   #248 light white - light black   #249 light white - magenta
#250 light white - cyan           #251 light white - blue          #252 light white - yellow
#253 light white - red            #254 light white - green         #255 light white - black
#256 light white - white
*/
<commit_msg>adjust colors sample<commit_after>require( 'wTools' );
require( 'wConsequence' );
require( '../staging/abase/printer/printer/Logger.s' );

var _ = wTools;
var colorNames = _.mapOwnKeys( _.color.ColorMapShell );

function shortColor( name )
{
  var parts = _.strSplit( name );
  if( parts[ 0 ] === 'light' )
  name = 'l.' + parts[ 1 ];

  return name;
}

function prepareTableInfo()
{
  function onWrite( data )
  {
    row[ shortColor( fg ) ].push( data.outputForTerminal[ 0 ] )
  }

  var table = [];
  var fg,bg;
  var row  = {};

  var silencedLogger = new wLogger
  ({
    output : null,
    onWrite : onWrite
  })
  for( var i = 0; i < colorNames.length; i++ )
  {
    fg = colorNames[ i ];
    row[ shortColor( fg ) ] = [];
    for( var j = 0; j < colorNames.length; j++ )
    {
      bg = colorNames[ j ];
      var coloredLine = _.strColor.bg( _.strColor.fg( 'xYz', fg ), bg );
      silencedLogger.log( coloredLine );
    }
    table.push( row );
    row = {};
  }

  return table;
}

function drawTable()
{
  var Table = require( 'cli-table2' );
  var info = prepareTableInfo();
  var o =
  {
    head : [ "fg/bg" ],
    colWidths : [ 9 ],
    rowAligns : [ 'left' ],
    colAligns : null,
    style:
    {
       compact : true,
      'padding-left': 0,
      'padding-right': 0
    },
  }

  colorNames.forEach( ( name, i ) => colorNames[ i ] = shortColor( name ) );
  o.head.push.apply( o.head, colorNames );

  o.colWidths.push.apply( o.colWidths, _.arrayFill({ times : colorNames.length / 2 , value : 5 }) )
  o.colWidths.push.apply( o.colWidths, _.arrayFill({ times : colorNames.length / 2 , value : 7 }) )

  o.rowAligns.push.apply( o.rowAligns, _.arrayFill({ times : colorNames.length , value : 'center' }) );
  o.colAligns = o.rowAligns;

  var table = new Table( o );
  table.push.apply( table, info );

  logger.log( table.toString() );
}

_.shell( 'npm i cli-table2' )
.doThen( () => drawTable() );

<|endoftext|>


<commit_before>var Kts = require('kts');

var client = new Kts({
    endpoint: '',
    accessKey: '',
    secretKey: ''
});
var tableName = '';

// list all tables
client.listTables(function onListTable(err, res, info) {
    if (err) {
        console.warn(err);
    } else {
        console.log(res);  // ['tableName1', 'tableName2' ...]
        console.log(info);  // { logId, consumedCapacity}
    }
});

// describe table
client.describeTable(tableName, function onDeleteTable(err, res, info) {
    if (err) {
        console.warn(err);
    } else {
        console.log(res);  // {...tableDescription}
        console.log(info);  // {logId, consumedCapacity}
    }
});

// put row
client.putRow(tableName, {
    key: {
        partitionKey: 'Key1'
        // rowKey: 'rk1',
    },
    columns: {
        'name': 'Jack',
        'age': 32,
        'weight': 56.3,
        'is_vip': false
    }
}, function onPutRow(err, res, info) {
    if (err) {
        console.warn(err);
    } else {
        console.log(res);  // undefined
        console.log(info);  // {logId, consumedCapacity}
    }
});

// get row
client.getRow(tableName, {
    key: {
        partitionKey: 'Key1',
    },
    columns: ['name', 'age'],  // default is null, get all columns
    strongConsistent: true,  // default is false
}, function(err, res, info) {
    if (err) {
        console.warn(err);
    } else {
        console.log(res);  // {key, columns}
        console.log(info);  // {logId, consumedCapacity}
    }
});

// scan
client.scan(tableName, {
    limit: 100,
    strongConsistent: true,
    startKey: {  // default is null, scan from first row
        partitionKey: 'Key1',
    },
    endKey: {  // default is null, scan until latest row
        partitionKey: 'Key9',
    }
}, function(err, res, info) {
    if (err) {
        console.warn(err);
    } else {
        console.log(res);  // [{...row1}, {...{row2}]
        console.log(info);  // {logId, consumedCapacity}
    }
});

// batch write rows
client.batchWriteRow(tableName, [{
    key: {
        partitionKey: 'Key2'
    },
    columns: {
        'name': 'Rose',
        'age': 31,
        'weight': 45.3,
        'is_vip': true
    }
}, {
    key: {
        partitionKey: 'Key3'
    },
    action: 'DELETE',
    columns: ['is_vip']
}, {
    key: {
        partitionKey: 'Key4'
    },
    action: 'DELETE'
}], function(err, res, info) {
    if (err) {
        console.log(err);
    } else {
        console.log(res);  // undefined
        console.log(info);  // {logId, consumedCapacity}
    }
});

// batch read rows
client.batchGetRow(tableName, [{
    partitionKey: 'Key2'
}, {
    partitionKey: 'Key3',
}], function(err, res, info) {
    if (err) {
        console.warn(err);
    } else {
        console.log(res);  // [{...row1}, {...{row2}]
        console.log(info);  // {logId, consumedCapacity}
    }
});

console.log('end');
<commit_msg>update sample<commit_after>var Kts = require('kts');

var client = new Kts({
  endpoint: '',
  accessKey: '',
  secretKey: ''
});
var tableName = '';

// list all tables
client.listTables(function onListTable(err, res, info) {
  if (err) {
    console.warn(err);
  } else {
    console.log(res);  // ['tableName1', 'tableName2' ...]
    console.log(info);  // { logId, consumedCapacity}
  }
});

// describe table
client.describeTable(tableName, function onDeleteTable(err, res, info) {
  if (err) {
    console.warn(err);
  } else {
    console.log(res);  // {...tableDescription}
    console.log(info);  // {logId, consumedCapacity}
  }
});

// put row
client.putRow(tableName, {
  key: {
    partitionKey: 'Key1'
    // rowKey: 'rk1',
  },
  columns: {
    'name': 'Jack',
    'age': 32,
    'weight': 56.3,
    'is_vip': false
  }
}, function onPutRow(err, res, info) {
  if (err) {
    console.warn(err);
  } else {
    console.log(res);  // undefined
    console.log(info);  // {logId, consumedCapacity}
  }
});

// get row
client.getRow(tableName, {
  key: {
    partitionKey: 'Key1',
  },
  columns: ['name', 'age'],  // default is null, get all columns
  strongConsistent: true,  // default is false
}, function (err, res, info) {
  if (err) {
    console.warn(err);
  } else {
    console.log(res);  // {key, columns}
    console.log(info);  // {logId, consumedCapacity}
  }
});

// scan
client.scan(tableName, {
  limit: 100,
  strongConsistent: true,
  startKey: {  // default is null, scan from first row
    partitionKey: 'Key1',
  },
  endKey: {  // default is null, scan until latest row
    partitionKey: 'Key9',
  }
}, function (err, res, info) {
  if (err) {
    console.warn(err);
  } else {
    console.log(res);  // [{...row1}, {...{row2}]
    console.log(info);  // {logId, consumedCapacity}
  }
});

// batch write rows
client.batchWriteRow(tableName, [{
  key: {
    partitionKey: 'Key2'
  },
  columns: {
    'name': 'Rose',
    'age': 31,
    'weight': 45.3,
    'is_vip': true
  }
}, {
  key: {
    partitionKey: 'Key3'
  },
  action: 'DELETE',
  columns: ['is_vip']
}, {
  key: {
    partitionKey: 'Key4'
  },
  action: 'DELETE'
}], function (err, res, info) {
  if (err) {
    console.log(err);
  } else {
    console.log(res);  // undefined
    console.log(info);  // {logId, consumedCapacity}
  }
});

// batch read rows
client.batchGetRow(tableName, [{
  partitionKey: 'Key2'
}, {
  partitionKey: 'Key3',
}], function (err, res, info) {
  if (err) {
    console.warn(err);
  } else {
    console.log(res);  // [{...row1}, {...{row2}]
    console.log(info);  // {logId, consumedCapacity}
  }
});

console.log('end');
<|endoftext|>


<commit_before>var tencentyoutuyun = require('..');
var conf  = tencentyoutuyun.conf;
var youtu = tencentyoutuyun.youtu;

// 设置开发者和应用信息, 请填写你在开放平台
var appid = '';
var secretId = '';
var secretKey = '';
var userid = '';

conf.setAppInfo(appid, secretId, secretKey, userid, 1)

// 人脸检测 测试
youtu.detectface('a.jpg', function(data){
    console.log("detectface:" + JSON.stringify(data));
});

// 人脸比对 测试
//youtu.facecompare('a.jpg', 'a.jpg', function(data){
//    console.log("facecompare:" + JSON.stringify(data));
//});

// 人脸比对 测试
//youtu.fuzzydetect('a.jpg', function(data){
//    console.log("fuzzydetect:" + JSON.stringify(data));
//});

//youtu.fooddetect('a.jpg', function(data){
//    console.log("fooddetect:" + JSON.stringify(data));
//});

youtu.imagetag('a.jpg', function(data){
    console.log("imagetag:" + JSON.stringify(data));
});

// 其他接口 类似
<commit_msg>fix sample bug `detectface = function(imagePath,　isbigface, callback)`<commit_after>var tencentyoutuyun = require('..');
var conf  = tencentyoutuyun.conf;
var youtu = tencentyoutuyun.youtu;

// 设置开发者和应用信息, 请填写你在开放平台
var appid = '';
var secretId = '';
var secretKey = '';
var userid = '';

conf.setAppInfo(appid, secretId, secretKey, userid, 1)

// 人脸检测 测试
youtu.detectface('a.jpg', 0, function(data){
    console.log("detectface:" + JSON.stringify(data));
});

// 人脸比对 测试
//youtu.facecompare('a.jpg', 'a.jpg', function(data){
//    console.log("facecompare:" + JSON.stringify(data));
//});

// 人脸比对 测试
//youtu.fuzzydetect('a.jpg', function(data){
//    console.log("fuzzydetect:" + JSON.stringify(data));
//});

//youtu.fooddetect('a.jpg', function(data){
//    console.log("fooddetect:" + JSON.stringify(data));
//});

youtu.imagetag('a.jpg', function(data){
    console.log("imagetag:" + JSON.stringify(data));
});

// 其他接口 类似
<|endoftext|>


<commit_before>/*
* Build Elasticsearch query for watcherWizard chart
*/

class WatcherWizardConditionBuilder {
  constructor() {
  }

  _mathSmbl(word) {
    if (word === 'above') {
      return '>';
    }
    if (word === 'above eq') {
      return '>=';
    }
    if (word === 'below') {
      return '<';
    }
    if (word === 'below eq') {
      return '<=';
    }
  }

  /*
  * @return {string}
    // if (over.type === 'all docs')
    "payload.hits.total > 0"
    // else
    "for(var r=payload.aggregations.bucketAgg.buckets,t=0;t<r.length;t++)if(r[t].doc_count>0)return!0;return!1"
  */
  count({over = {type: 'all docs'}, threshold = {n: 0, direction: 'above'}} = {}) {
    const compToThis = this._mathSmbl(threshold.direction) + threshold.n;

    if (over.type === 'all docs') {
      return `payload.hits.total ${compToThis}`;
    }
    return `payload.aggregations.bucketAgg.buckets.some(e => e.doc_count${compToThis})`;
  }

  /*
  * @return {string}
  */
  average({over = {type: 'all docs'}, threshold = {n: 0, direction: 'above'}} = {}) {
    return this._metricAggScript({over, threshold});
  }

  /*
  * @return {string}
  */
  sum({over = {type: 'all docs'}, threshold = {n: 0, direction: 'above'}} = {}) {
    return this._metricAggScript({over, threshold});
  }

  /*
  * @return {string}
  */
  min({over = {type: 'all docs'}, threshold = {n: 0, direction: 'above'}} = {}) {
    return this._metricAggScript({over, threshold});
  }

  /*
  * @return {string}
  */
  max({over = {type: 'all docs'}, threshold = {n: 0, direction: 'above'}} = {}) {
    return this._metricAggScript({over, threshold});
  }

  /*
  * @return {string}
    // if (over.type === 'all docs')
    "payload.aggregations.metricAgg.value >0"
    // else
    for(var r=payload.aggregations.bucketAgg.buckets,a=0;a<r.length;a++)if(r[a].metricAgg.value>0)return!0;return!1
  */
  _metricAggScript({over = {type: 'all docs'}, threshold = {n: 0, direction: 'above'}} = {}) {
    const compToThis = this._mathSmbl(threshold.direction) + threshold.n;

    if (over.type === 'all docs') {
      return `payload.aggregations.metricAgg.value ${compToThis}`;
    }
    return `payload.aggregations.bucketAgg.buckets.some(e => e.metricAgg.value${compToThis})`;
  }
}

export default WatcherWizardConditionBuilder;
<commit_msg>Fix watcher condition scripts. (#695)<commit_after>/*
* Build Elasticsearch query for watcherWizard chart
*/

class WatcherWizardConditionBuilder {
  constructor() {
  }

  _mathSmbl(word) {
    if (word === 'above') {
      return '>';
    }
    if (word === 'above eq') {
      return '>=';
    }
    if (word === 'below') {
      return '<';
    }
    if (word === 'below eq') {
      return '<=';
    }
  }

  /*
  * @return {string}
    // if (over.type === 'all docs')
    "payload.aggregations.dateAgg.buckets.some(b => b.doc_count>1)"
    // else
    "payload.aggregations.bucketAgg.buckets.some(b => b.dateAgg.buckets.some(b => b.doc_count>1))"
  */
  count({over = {type: 'all docs'}, threshold = {n: 0, direction: 'above'}, filterMethod = 'some'} = {}) {
    const compToThis = this._mathSmbl(threshold.direction) + threshold.n;

    if (over.type === 'all docs') {
      return `payload.aggregations.dateAgg.buckets.${filterMethod}(b => b.doc_count${compToThis})`;
    }
    return `payload.aggregations.bucketAgg.buckets.${filterMethod}(b => b.dateAgg.buckets.${filterMethod}(b => b.doc_count${compToThis}))`;
  }

  /*
  * @return {string}
  */
  average({over, threshold, filterMethod}) {
    return this._metricAgg({over, threshold, filterMethod});
  }

  /*
  * @return {string}
  */
  sum({over, threshold, filterMethod}) {
    return this._metricAgg({over, threshold, filterMethod});
  }

  /*
  * @return {string}
  */
  min({over, threshold, filterMethod}) {
    return this._metricAgg({over, threshold, filterMethod});
  }

  /*
  * @return {string}
  */
  max({over, threshold, filterMethod}) {
    return this._metricAgg({over, threshold, filterMethod});
  }

  /*
  * @return {string}
    // if (over.type === 'all docs')
    "payload.aggregations.dateAgg.buckets.some(b => b.metricAgg.value>1)"
    // else
    "payload.aggregations.bucketAgg.buckets.some(b => b.dateAgg.buckets.some(b => b.metricAgg.value>1))"
  */
  _metricAgg({over = {type: 'all docs'}, threshold = {n: 0, direction: 'above'}, filterMethod = 'some'} = {}) {
    const compToThis = this._mathSmbl(threshold.direction) + threshold.n;

    if (over.type === 'all docs') {
      return `payload.aggregations.dateAgg.buckets.${filterMethod}(b => b.metricAgg.value${compToThis})`;
    }
    return `payload.aggregations.bucketAgg.buckets.${filterMethod}` +
      `(b => b.dateAgg.buckets.${filterMethod}(b => b.metricAgg.value${compToThis}))`;
  }
}

export default WatcherWizardConditionBuilder;
<|endoftext|>


<commit_before>/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * TERMS OF REPRODUCTION USE
 *
 * 1. Provide a link back to the original repository (this repository), as
 * 		in, https://github.com/ConnerGDavis/Plugbot, that is well-visible
 * 		wherever the source is being reproduced.  For example, should you
 * 		display it on a website, you should provide a link above/below that
 *		which the users use, titled something such as "ORIGINAL AUTHOR".
 *
 * 2. Retain these three comments:  the GNU GPL license statement, this comment,
 * 		and that below it, that details the author and purpose.
 *
 * Thanks for playing fair!  You'll fare better than WOLVES, that's for sure.
 */

/**
 * NOTE:  This is all procedural as hell because prototypes and any
 * 			OOP techniques in Javascript are stupid and confusing.
 *
 * @author Conner Davis ([VIP] ♫Łŏġïç®) & Harrison Schneidman ([VIDJ] EXƎ)
 * @version 0.2.0a
 */

// Triggers
var autowoot = true;
var autoqueue = false;
var hideVideo = false;
var userList = true;

// DJ Battles
var points = 0;
var highScore = 0;

// API listeners
function initAPIListeners()
{
	API.addEventListener(API.DJ_ADVANCE, djAdvanced);
	API.addEventListener(API.VOTE_UPDATE, function(obj) {
		if (userList)
			populateUserlist();
	});
	API.addEventListener(API.USER_JOIN, function(user) {
		if (userList)
			populateUserlist();
		if (isBoris())
			API.sendChat("Welcome to " + $("#current-room-value").text() + ", " + user.username + "!");
	});
	API.addEventListener(API.USER_LEAVE, function(user) {
		if (userList)
			populateUserlist();
	})
}

// Display UI
function displayUI()
{
	$('#plugbot-ui').remove();
	$('#playback').css('z-index', '8'); // hack to make the buttons usable

	$('#playback').append('

');
		$("#plugbot-ui").animate({"height": "64px"}, {duration: "slow" });
		$('#plugbot-ui').append(
			'' +
			'' +
			'' +
			''
		);

	$('body').append('

');
}

// Some on-click listeners for the UI buttons
function initUIListeners()
{
	$("#plugbot-btn-userlist").on("click", function() {
		userList = !userList;
		$(this).attr("src", userList ? 'http://i.imgur.com/IGcMP.png' : 'http://i.imgur.com/pAFJS.png');
		$("#plugbot-userlist").css("visibility", userList ? ("visible") : ("hidden"));
		if (!userList) {
			$("#plugbot-userlist").empty();
		}
		console.log('Userlist is now ' + (userList ? 'enabled' : 'disabled'));
	});
	$("#plugbot-btn-woot").on("click", function() {
		autowoot = !autowoot;
		$(this).attr("src", autowoot ? 'http://i.imgur.com/fWb8n.png' : 'http://i.imgur.com/uyUtA.png');
		if (autowoot)
			$("#button-vote-positive").click();
		console.log('Auto-woot is now ' + (autowoot ? 'enabled' : 'disabled'));
	});

	$("#plugbot-btn-hidevideo").on("click", function() {
		hideVideo = !hideVideo;
		$(this).attr("src", hideVideo ? 'http://i.imgur.com/lwpfH.png' : 'http://i.imgur.com/jbJDe.png');
		$("#yt-frame").animate({"height": (hideVideo ? "0px" : "271px")}, {duration: "fast"});
	});

	$("#plugbot-btn-queue").on("click", function() {
		autoqueue = !autoqueue;
		$(this).attr("src", autoqueue ? 'http://i.imgur.com/IxK27.png' : 'http://i.imgur.com/W5ncS.png');
		$("#button-dj-waitlist-" + (autoqueue ? "join" : "leave")).click();
		console.log('Auto-queue is now ' + (autoqueue ? 'enabled' : 'disabled'));
	});
}

function djAdvanced(obj)
{
	if (autowoot)
		$("#button-vote-positive").click();

	if ($("#button-dj-waitlist-join").css("display") === "block" && autoqueue)
		$("#button-dj-waitlist-join").click();

	$("#yt-frame").css("height", "271px");
	$('#plugbot-btn-hidevideo').attr('src', 'http://i.imgur.com/jbJDe.png');
	hideVideo = false;

	points = 0;
	highScore = 0;

	if (userList)
		populateUserlist();
}

function populateUserlist()
{
	points = 0;
	var userNames = new Array();

	for (var i = 0; i < API.getUsers().length; i++)
	{
		userNames[i] = API.getUsers()[i];
	}

	$('#plugbot-userlist').empty();

	for (var i = 0; i < userNames.length; i++)
	{
		var user = userNames[i];
		refreshList(user.username, user.vote)
	}

	if (points > highScore)
		highScore = points;

	//$('#plugbot-userlist').append('
High Score: ' + highScore + '
');
	$('body').append('

');
}

function refreshList(username, vote)
{
	var colour;
	var currentDj = false;
	var moderator = false;
	var img;

	for (var i = 0; i < API.getModerators().length; i++) {
		if (API.getModerators()[i].username == username) {
			moderator = true;
		}
	}

	switch (vote)
	{
		case 1:
			colour = "3FFF00";
			points++;
			if (moderator)
				img = "http://i.imgur.com/T5G4f.png";
			break;
		case 0:
			colour = "FFFFFF";
			if (moderator)
				img = "http://i.imgur.com/sRsU0.png";
			break;
		case -1:
			colour = "ED1C24";
			if (moderator)
				img = "http://i.imgur.com/JPA1Q.png";
			break;
	}

	if (API.getDJs()[0].username == username) {
		currentDj = true;
		colour = "42A5DC";
		if (moderator)
			img = "http://i.imgur.com/CsK3d.png";
	}

	$('#plugbot-userlist').append(
		(moderator ? '' : '')
		+ '
'
		+ username + '
'
	);
}

function isSebastian() { return API.getSelf().username == "Sebastian[BOT]"; }
function isBoris() { return API.getSelf().username == "BorisYeltsin[BOT]"; }

// On init

$('head').prepend('<link href="http://wlsandd.net78.net/plugbot/plugbot.css" rel="stylesheet" type="text/css" />');

$("#button-vote-positive").click();

$("#plugbot-userlist").empty();
initAPIListeners();
populateUserlist();
displayUI();
initUIListeners();

if (isBoris())
{
	window.setInterval(function() {
		API.sendChat("Please remember to view our rules at http://goo.gl/YoFDH");
	}, (1000 * 60 * 30));
}
<commit_msg>Patched undecided mod broken image, thanks for letting me know NoizeRebel<commit_after>/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * TERMS OF REPRODUCTION USE
 *
 * 1. Provide a link back to the original repository (this repository), as
 * 		in, https://github.com/ConnerGDavis/Plugbot, that is well-visible
 * 		wherever the source is being reproduced.  For example, should you
 * 		display it on a website, you should provide a link above/below that
 *		which the users use, titled something such as "ORIGINAL AUTHOR".
 *
 * 2. Retain these three comments:  the GNU GPL license statement, this comment,
 * 		and that below it, that details the author and purpose.
 *
 * Thanks for playing fair!  You'll fare better than WOLVES, that's for sure.
 */

/**
 * NOTE:  This is all procedural as hell because prototypes and any
 * 			OOP techniques in Javascript are stupid and confusing.
 *
 * @author Conner Davis ([VIP] ♫Łŏġïç®) & Harrison Schneidman ([VIDJ] EXƎ)
 * @version 0.2.0a
 */

// Triggers
var autowoot = true;
var autoqueue = false;
var hideVideo = false;
var userList = true;

// DJ Battles
var points = 0;
var highScore = 0;

// API listeners
function initAPIListeners()
{
	API.addEventListener(API.DJ_ADVANCE, djAdvanced);
	API.addEventListener(API.VOTE_UPDATE, function(obj) {
		if (userList)
			populateUserlist();
	});
	API.addEventListener(API.USER_JOIN, function(user) {
		if (userList)
			populateUserlist();
		if (isBoris())
			API.sendChat("Welcome to " + $("#current-room-value").text() + ", " + user.username + "!");
	});
	API.addEventListener(API.USER_LEAVE, function(user) {
		if (userList)
			populateUserlist();
	})
}

// Display UI
function displayUI()
{
	$('#plugbot-ui').remove();
	$('#playback').css('z-index', '8'); // hack to make the buttons usable

	$('#playback').append('

');
		$("#plugbot-ui").animate({"height": "64px"}, {duration: "slow" });
		$('#plugbot-ui').append(
			'' +
			'' +
			'' +
			''
		);

	$('body').append('

');
}

// Some on-click listeners for the UI buttons
function initUIListeners()
{
	$("#plugbot-btn-userlist").on("click", function() {
		userList = !userList;
		$(this).attr("src", userList ? 'http://i.imgur.com/IGcMP.png' : 'http://i.imgur.com/pAFJS.png');
		$("#plugbot-userlist").css("visibility", userList ? ("visible") : ("hidden"));
		if (!userList) {
			$("#plugbot-userlist").empty();
		}
		console.log('Userlist is now ' + (userList ? 'enabled' : 'disabled'));
	});
	$("#plugbot-btn-woot").on("click", function() {
		autowoot = !autowoot;
		$(this).attr("src", autowoot ? 'http://i.imgur.com/fWb8n.png' : 'http://i.imgur.com/uyUtA.png');
		if (autowoot)
			$("#button-vote-positive").click();
		console.log('Auto-woot is now ' + (autowoot ? 'enabled' : 'disabled'));
	});

	$("#plugbot-btn-hidevideo").on("click", function() {
		hideVideo = !hideVideo;
		$(this).attr("src", hideVideo ? 'http://i.imgur.com/lwpfH.png' : 'http://i.imgur.com/jbJDe.png');
		$("#yt-frame").animate({"height": (hideVideo ? "0px" : "271px")}, {duration: "fast"});
	});

	$("#plugbot-btn-queue").on("click", function() {
		autoqueue = !autoqueue;
		$(this).attr("src", autoqueue ? 'http://i.imgur.com/IxK27.png' : 'http://i.imgur.com/W5ncS.png');
		$("#button-dj-waitlist-" + (autoqueue ? "join" : "leave")).click();
		console.log('Auto-queue is now ' + (autoqueue ? 'enabled' : 'disabled'));
	});
}

function djAdvanced(obj)
{
	if (autowoot)
		$("#button-vote-positive").click();

	if ($("#button-dj-waitlist-join").css("display") === "block" && autoqueue)
		$("#button-dj-waitlist-join").click();

	$("#yt-frame").css("height", "271px");
	$('#plugbot-btn-hidevideo').attr('src', 'http://i.imgur.com/jbJDe.png');
	hideVideo = false;

	points = 0;
	highScore = 0;

	if (userList)
		populateUserlist();
}

function populateUserlist()
{
	points = 0;
	var userNames = new Array();

	for (var i = 0; i < API.getUsers().length; i++)
	{
		userNames[i] = API.getUsers()[i];
	}

	$('#plugbot-userlist').empty();

	for (var i = 0; i < userNames.length; i++)
	{
		var user = userNames[i];
		refreshList(user.username, user.vote)
	}

	if (points > highScore)
		highScore = points;

	//$('#plugbot-userlist').append('
High Score: ' + highScore + '
');
	$('body').append('

');
}

function refreshList(username, vote)
{
	var colour;
	var currentDj = false;
	var moderator = false;
	var img;

	for (var i = 0; i < API.getModerators().length; i++) {
		if (API.getModerators()[i].username == username) {
			moderator = true;
		}
	}

	switch (vote)
	{
		case 1:
			colour = "3FFF00";
			points++;
			if (moderator)
				img = "http://i.imgur.com/T5G4f.png";
			break;
		case 0:
			colour = "FFFFFF";
			if (moderator)
				img = "http://i.imgur.com/sRsU0.png";
			break;
		case -1:
			colour = "ED1C24";
			if (moderator)
				img = "http://i.imgur.com/JPA1Q.png";
			break;
	}

	if (API.getDJs()[0].username == username) {
		currentDj = true;
		colour = "42A5DC";
		if (moderator)
			img = "http://i.imgur.com/CsK3d.png";
	}

	if (img == undefined && moderator)
		img = "http://i.imgur.com/sRsU0.png";

	$('#plugbot-userlist').append(
		(moderator ? '' : '')
		+ '
'
		+ username + '
'
	);
}

function isSebastian() { return API.getSelf().username == "Sebastian[BOT]"; }
function isBoris() { return API.getSelf().username == "BorisYeltsin[BOT]"; }

// On init

$('head').prepend('<link href="http://wlsandd.net78.net/plugbot/plugbot.css" rel="stylesheet" type="text/css" />');

$("#button-vote-positive").click();

$("#plugbot-userlist").empty();
initAPIListeners();
populateUserlist();
displayUI();
initUIListeners();

if (isBoris())
{
	window.setInterval(function() {
		API.sendChat("Please remember to view our rules at http://goo.gl/YoFDH");
	}, (1000 * 60 * 30));
}
<|endoftext|>


<commit_before>'use strict';
const path = require('path');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const CleanWebpackPlugin = require('clean-webpack-plugin');

const DEFAULT_OPTIONS = {
  outputPath: 'public',
  clean: {
    path: [],
    options: {
      root: process.cwd()
    }
  },
  uglify: {
    compress: {
      warnings: false
    },
    comments: false,
    sourceMap: true
  }
};
module.exports = function (options = {}) {
  const env = process.env.NODE_ENV || 'development';
  options = webpackMerge({}, DEFAULT_OPTIONS, options);
  const config = {
    devtool: '#source-map',
    output: {
      path: path.join(process.cwd(), options.outputPath),
      publicPath: '/',
      filename: "assets/js/[name].js",
      jsonpFunction: 'fr',
      library: '[name]_library'
    },
    resolve: {
      extensions: ['.js', '.jsx', '.ts', '.tsx', '.sass', '.scss', '.ejs', '.html'],
      modules: [
        path.join(process.cwd(), 'src'),
        path.join(process.cwd(), 'node_modules')
      ]
    },
    stats: 'minimal',
    watchOptions: {
      ignored: /node_modules/
    },
    performance: {
      hints: false
    },
    plugins: [
      new webpack.NoEmitOnErrorsPlugin(),
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify(env)
        }
      }),
      new webpack.LoaderOptionsPlugin({
        options: {
          context: process.cwd(),
          output: {
            path: path.join(process.cwd(),options.outputPath)
          }
        }
      })
    ]
  };

  if (env === 'production') { // for production
    options.clean.path.push(options.outputPath);
    config.plugins.push(
      new CleanWebpackPlugin(options.clean.path, options.clean.options),
      new webpack.optimize.AggressiveMergingPlugin(),
      new webpack.optimize.UglifyJsPlugin(options.uglify)
    );
  } else {  // for development
    try {
      let manifest = require.resolve(path.join(process.cwd(), 'vendor-manifest.json'));
      config.plugins.push(new webpack.DllReferencePlugin({
        context: process.cwd(),
        manifest: path.join(process.cwd(), 'vendor-manifest.json')
      }));
    } catch (e) {
      console.log('Not found vendor-manifest.json');
    }
  }
  return config;
};<commit_msg>ProgressPluginを入れてstatsを調整<commit_after>'use strict';
const path = require('path');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ProgressPlugin = require('webpack/lib/ProgressPlugin');
const DEFAULT_OPTIONS = {
  outputPath: 'public',
  clean: {
    path: [],
    options: {
      root: process.cwd()
    }
  },
  uglify: {
    compress: {
      warnings: false
    },
    comments: false,
    sourceMap: true
  }
};
module.exports = function (options = {}) {
  const env = process.env.NODE_ENV || 'development';
  options = webpackMerge({}, DEFAULT_OPTIONS, options);
  const config = {
    devtool: '#source-map',
    output: {
      path: path.join(process.cwd(), options.outputPath),
      publicPath: '/',
      filename: "assets/js/[name].js",
      jsonpFunction: 'fr',
      library: '[name]_library'
    },
    resolve: {
      extensions: ['.js', '.jsx', '.ts', '.tsx', '.sass', '.scss', '.ejs', '.html'],
      modules: [
        path.join(process.cwd(), 'src'),
        path.join(process.cwd(), 'node_modules')
      ]
    },
    stats: {
      assets: false,
      modules: false,
      children: false,
    },
    watchOptions: {
      ignored: /node_modules/
    },
    performance: {
      hints: false
    },
    plugins: [
      new webpack.NoEmitOnErrorsPlugin(),
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify(env)
        }
      }),
      new ProgressPlugin({profile:options.verbose, colors: true }),
      new webpack.LoaderOptionsPlugin({
        options: {
          context: process.cwd(),
          output: {
            path: path.join(process.cwd(),options.outputPath)
          }
        }
      })
    ]
  };

  if (env === 'production') { // for production
    options.clean.path.push(options.outputPath);
    config.plugins.push(
      new CleanWebpackPlugin(options.clean.path, options.clean.options),
      new webpack.optimize.AggressiveMergingPlugin(),
      new webpack.optimize.UglifyJsPlugin(options.uglify)
    );
  } else {  // for development
    try {
      let manifest = require.resolve(path.join(process.cwd(), 'vendor-manifest.json'));
      config.plugins.push(new webpack.DllReferencePlugin({
        context: process.cwd(),
        manifest: path.join(process.cwd(), 'vendor-manifest.json')
      }));
    } catch (e) {
      console.log('Not found vendor-manifest.json');
    }
  }
  return config;
};<|endoftext|>


<commit_before>/**
 * Copyright 2016 - 2021 SigScale Global Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';
import '@polymer/iron-ajax/iron-ajax.js';
import '@polymer/paper-dialog/paper-dialog.js';
import '@polymer/app-layout/app-toolbar/app-toolbar.js';
import '@polymer/paper-progress/paper-progress.js';
import '@polymer/paper-dropdown-menu/paper-dropdown-menu.js';
import '@polymer/paper-input/paper-input.js';
import '@polymer/paper-button/paper-button.js';
import '@polymer/paper-listbox/paper-listbox.js';
import '@polymer/paper-item/paper-item.js'
import '@polymer/paper-tooltip/paper-tooltip.js';
import './style-element.js';

class offerAdd extends PolymerElement {
	static get template() {
		return html`

			<paper-dialog
					class="dialog"
					id="addBucketModal"
					modal>
				<app-toolbar>

Add Bucket

				</app-toolbar>
				<paper-progress
						indeterminate
						id="progressId"
						class="slow red"
						disabled="{{!loading}}">
				</paper-progress>

					<paper-input
							value="{{productId}}"
							label="Product">
					</paper-input>
					<paper-tooltip>
						Identifier of the Product associated with this bucket.
					</paper-tooltip>

					<paper-input
							type="datetime-local"
							value="{{bucketStart}}"
							label="Start Date">
					</paper-input>
					<paper-tooltip>
						Start of balance bucket validity period.
					</paper-tooltip>

					<paper-input
							value="{{bucketEnd}}"
							label="End Date">
					</paper-input>
					<paper-tooltip>
						End of balance bucket validity period.
					</paper-tooltip>

					<paper-dropdown-menu
							value="{{bucketUnit}}"
							no-animations="true"
							label="Units">
						<paper-listbox
								id="addBucket"
								slot="dropdown-content">
							<paper-item>
								Bytes
							</paper-item>
							<paper-item>
								Cents
							</paper-item>
							<paper-item>
								Seconds
							</paper-item>
						</paper-listbox>
					</paper-dropdown-menu>
					<paper-tooltip>
						Type of units contained in this bucket.
					</paper-tooltip>

					<paper-input
							type="text"
							allowed-pattern="[0-9kmg]"
							pattern="^[0-9]+[kmg]?$"
							label="Amount"
							value="{{bucketAmount}}"
							auto-validate>
					</paper-input>
					<paper-tooltip>
						Total amount of units contained in this bucket.
					</paper-tooltip>

					<paper-button
							raised
							class="submit-button"
							on-tap="_bucketAddSubmit">
						Add
					</paper-button>
					<paper-button dialog-dismiss
							class="cancel-button"
							on-tap="_cancel">
						Cancel
					</paper-button>

			</paper-dialog>
			<paper-dialog
					class="dialog"
					id="deleteBucketModal"
					modal>
				<app-toolbar>

Delete Bucket

				</app-toolbar>

					<paper-input
							value="{{deleteBucketId}}"
							label="Bucket Id"
							required
							disabled>
					</paper-input>
					<paper-tooltip>
						Identifier of bucket to be deleted.
					</paper-tooltip>

					<paper-button raised
							on-tap="_deleteBucket"
							class="delete-button">
						Delete
					</paper-button>
					<paper-button dialog-dismiss
							class="cancel-button"
							onclick="deleteBucketModal.close()">
						Cancel
					</paper-button>

			</paper-dialog>
			<iron-ajax
					id="deleteBucketAjax"
					url="/balanceManagement/v1/bucket/"
					method="delete"
					on-response="_deleteBucketResponse"
					on-error="_deleteBucketError">
			</iron-ajax>
			<iron-ajax
					id="addBucketAjax"
					method = "post"
					content-type="application/json"
					on-loading-changed="_onLoadingChanged"
					on-response="_addBucketResponse"
					on-error="_addBucketError">
			</iron-ajax>
		`;
	}

	static get properties() {
		return {
			loading: {
				type: Boolean,
				value: false
			},
			productId: {
				type: String
			},
			bucketStart: {
				type: String
			},
			bucketEnd: {
				type: String
			},
			bucketAmount: {
				type: String
			},
			bucketUnit: {
				type: String
			},
			deleteBucketId: {
				type: String
			}
		}
	}

	ready() {
		super.ready()
	}

	_deleteBucket(event) {
		this.$.deleteBucketAjax.url = "/balanceManagement/v1/bucket/" + this.deleteBucketId;
		this.$.deleteBucketAjax.generateRequest();
	}

	_deleteBucketError(event) {
		this.$.deleteBucketModal.close();
		var toast = document.body.querySelector('sig-app').shadowRoot.getElementById('restError');
		toast.text = "Error";
		toast.open();
	}

	_deleteBucketResponse(event) {
		this.$.deleteBucketModal.close();
		this.deleteBucketId = null;
		document.body.querySelector('sig-app').shadowRoot.querySelector('sig-bucket-list').shadowRoot.getElementById('balanceBucketGrid').clearCache();
	}

	_bucketAddSubmit(event) {
		if(this.productId && this.bucketUnit && this.bucketAmount) {
			var bucket = {name: "channel"};
			bucket.product = {id: this.productId,
					href: "/productInventoryManagement/v2/product/" + this.productId};
			if(this.bucketStart || this.bucketEnd) {
				bucket.validFor = new Object;
				if(this.bucketStart) {
					bucket.validFor.startDateTime = this.bucketStart;
				}
				if(this.bucketEnd) {
					bucket.validFor.endDateTime = this.bucketEnd;
				}
			}
			if(this.bucketUnit == "Bytes") {
				bucket.amount = {units: "octets", amount: this.bucketAmount};
			}
			else if(this.bucketUnit == "Cents") {
				bucket.amount = {units: "cents", amount: this.bucketAmount};
			}
			else if(this.bucketUnit == "Seconds") {
				bucket.amount = {units: "seconds", amount: this.bucketAmount};
			}
			var ajax = this.$.addBucketAjax;
			ajax.body = bucket;
			ajax.url="/balanceManagement/v1/product/" + this.productId + "/balanceTopup";
			ajax.generateRequest();
			this.$.addBucket.selected = null;
		}
	}

	_cancel() {
		this.productId = null;
		this.bucketStart = null;
		this.bucketEnd = null;
		this.bucketUnit = null;
		this.bucketAmount = null;
	}

	_addBucketResponse(event) {
		this.$.addBucketModal.close();
		this.productId = null;
		this.bucketStart = null;
		this.bucketEnd = null;
		this.bucketUnit = null;
		this.bucketAmount = null;
		document.body.querySelector('sig-app').shadowRoot.getElementById('bucketList').shadowRoot.getElementById('balanceBucketGrid').clearCache();
	}

	_addBucketError(event) {
		var toast = document.body.querySelector('sig-app').shadowRoot.getElementById('restError');
		toast.text = "Error";
		toast.open();
	}

	_onLoadingChanged(event) {
		if (this.$.addBucketAjax.loading) {
			this.$.progressId.disabled = false;
		} else {
			this.$.progressId.disabled = true;
		}
	}
}

window.customElements.define('sig-bucket-add', offerAdd);
<commit_msg>fix endDate format in gui<commit_after>/**
 * Copyright 2016 - 2021 SigScale Global Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';
import '@polymer/iron-ajax/iron-ajax.js';
import '@polymer/paper-dialog/paper-dialog.js';
import '@polymer/app-layout/app-toolbar/app-toolbar.js';
import '@polymer/paper-progress/paper-progress.js';
import '@polymer/paper-dropdown-menu/paper-dropdown-menu.js';
import '@polymer/paper-input/paper-input.js';
import '@polymer/paper-button/paper-button.js';
import '@polymer/paper-listbox/paper-listbox.js';
import '@polymer/paper-item/paper-item.js'
import '@polymer/paper-tooltip/paper-tooltip.js';
import './style-element.js';

class offerAdd extends PolymerElement {
	static get template() {
		return html`

			<paper-dialog
					class="dialog"
					id="addBucketModal"
					modal>
				<app-toolbar>

Add Bucket

				</app-toolbar>
				<paper-progress
						indeterminate
						id="progressId"
						class="slow red"
						disabled="{{!loading}}">
				</paper-progress>

					<paper-input
							value="{{productId}}"
							label="Product">
					</paper-input>
					<paper-tooltip>
						Identifier of the Product associated with this bucket.
					</paper-tooltip>

					<paper-input
							type="datetime-local"
							value="{{bucketStart}}"
							label="Start Date">
					</paper-input>
					<paper-tooltip>
						Start of balance bucket validity period.
					</paper-tooltip>

					<paper-input
							type="datetime-local"
							value="{{bucketEnd}}"
							label="End Date">
					</paper-input>
					<paper-tooltip>
						End of balance bucket validity period.
					</paper-tooltip>

					<paper-dropdown-menu
							value="{{bucketUnit}}"
							no-animations="true"
							label="Units">
						<paper-listbox
								id="addBucket"
								slot="dropdown-content">
							<paper-item>
								Bytes
							</paper-item>
							<paper-item>
								Cents
							</paper-item>
							<paper-item>
								Seconds
							</paper-item>
						</paper-listbox>
					</paper-dropdown-menu>
					<paper-tooltip>
						Type of units contained in this bucket.
					</paper-tooltip>

					<paper-input
							type="text"
							allowed-pattern="[0-9kmg]"
							pattern="^[0-9]+[kmg]?$"
							label="Amount"
							value="{{bucketAmount}}"
							auto-validate>
					</paper-input>
					<paper-tooltip>
						Total amount of units contained in this bucket.
					</paper-tooltip>

					<paper-button
							raised
							class="submit-button"
							on-tap="_bucketAddSubmit">
						Add
					</paper-button>
					<paper-button dialog-dismiss
							class="cancel-button"
							on-tap="_cancel">
						Cancel
					</paper-button>

			</paper-dialog>
			<paper-dialog
					class="dialog"
					id="deleteBucketModal"
					modal>
				<app-toolbar>

Delete Bucket

				</app-toolbar>

					<paper-input
							value="{{deleteBucketId}}"
							label="Bucket Id"
							required
							disabled>
					</paper-input>
					<paper-tooltip>
						Identifier of bucket to be deleted.
					</paper-tooltip>

					<paper-button raised
							on-tap="_deleteBucket"
							class="delete-button">
						Delete
					</paper-button>
					<paper-button dialog-dismiss
							class="cancel-button"
							onclick="deleteBucketModal.close()">
						Cancel
					</paper-button>

			</paper-dialog>
			<iron-ajax
					id="deleteBucketAjax"
					url="/balanceManagement/v1/bucket/"
					method="delete"
					on-response="_deleteBucketResponse"
					on-error="_deleteBucketError">
			</iron-ajax>
			<iron-ajax
					id="addBucketAjax"
					method = "post"
					content-type="application/json"
					on-loading-changed="_onLoadingChanged"
					on-response="_addBucketResponse"
					on-error="_addBucketError">
			</iron-ajax>
		`;
	}

	static get properties() {
		return {
			loading: {
				type: Boolean,
				value: false
			},
			productId: {
				type: String
			},
			bucketStart: {
				type: String
			},
			bucketEnd: {
				type: String
			},
			bucketAmount: {
				type: String
			},
			bucketUnit: {
				type: String
			},
			deleteBucketId: {
				type: String
			}
		}
	}

	ready() {
		super.ready()
	}

	_deleteBucket(event) {
		this.$.deleteBucketAjax.url = "/balanceManagement/v1/bucket/" + this.deleteBucketId;
		this.$.deleteBucketAjax.generateRequest();
	}

	_deleteBucketError(event) {
		this.$.deleteBucketModal.close();
		var toast = document.body.querySelector('sig-app').shadowRoot.getElementById('restError');
		toast.text = "Error";
		toast.open();
	}

	_deleteBucketResponse(event) {
		this.$.deleteBucketModal.close();
		this.deleteBucketId = null;
		document.body.querySelector('sig-app').shadowRoot.querySelector('sig-bucket-list').shadowRoot.getElementById('balanceBucketGrid').clearCache();
	}

	_bucketAddSubmit(event) {
		if(this.productId && this.bucketUnit && this.bucketAmount) {
			var bucket = {name: "channel"};
			bucket.product = {id: this.productId,
					href: "/productInventoryManagement/v2/product/" + this.productId};
			if(this.bucketStart || this.bucketEnd) {
				bucket.validFor = new Object;
				if(this.bucketStart) {
					bucket.validFor.startDateTime = this.bucketStart;
				}
				if(this.bucketEnd) {
					bucket.validFor.endDateTime = this.bucketEnd;
				}
			}
			if(this.bucketUnit == "Bytes") {
				bucket.amount = {units: "octets", amount: this.bucketAmount};
			}
			else if(this.bucketUnit == "Cents") {
				bucket.amount = {units: "cents", amount: this.bucketAmount};
			}
			else if(this.bucketUnit == "Seconds") {
				bucket.amount = {units: "seconds", amount: this.bucketAmount};
			}
			var ajax = this.$.addBucketAjax;
			ajax.body = bucket;
			ajax.url="/balanceManagement/v1/product/" + this.productId + "/balanceTopup";
			ajax.generateRequest();
			this.$.addBucket.selected = null;
		}
	}

	_cancel() {
		this.productId = null;
		this.bucketStart = null;
		this.bucketEnd = null;
		this.bucketUnit = null;
		this.bucketAmount = null;
	}

	_addBucketResponse(event) {
		this.$.addBucketModal.close();
		this.productId = null;
		this.bucketStart = null;
		this.bucketEnd = null;
		this.bucketUnit = null;
		this.bucketAmount = null;
		document.body.querySelector('sig-app').shadowRoot.getElementById('bucketList').shadowRoot.getElementById('balanceBucketGrid').clearCache();
	}

	_addBucketError(event) {
		var toast = document.body.querySelector('sig-app').shadowRoot.getElementById('restError');
		toast.text = "Error";
		toast.open();
	}

	_onLoadingChanged(event) {
		if (this.$.addBucketAjax.loading) {
			this.$.progressId.disabled = false;
		} else {
			this.$.progressId.disabled = true;
		}
	}
}

window.customElements.define('sig-bucket-add', offerAdd);
<|endoftext|>


<commit_before>/* Copyright(c) 2018 Philip Mulcahy. */
/* jshint strict: true, esversion: 6 */

const date_tests = (() => {
    "use strict";

    const de_test = () => {
         return (
             date.normalizeDateString('29 Dezember 2017') == '2017-12-29' &&
             date.normalizeDateString('29. Dezember 2017') == '2017-12-29'
         );
    };

    const es_test = () => {
        return (
            date.normalizeDateString('16 de noviembre de 2018') == '2018-11-16' &&
            date.normalizeDateString('23 de agosto de 2016') == '2016-08-23'
        );
   };

    const fr_test = () => {
         return (
             date.normalizeDateString('29 mai 2018') == '2018-05-29' &&
             date.normalizeDateString('29. mai 2018') == '2018-05-29'
         );
    };

    const it_test = () => {
         return (
             date.normalizeDateString('22. luglio 2016') == '2016-07-22'
         );
    };

    const uk_test = () => {
         return (
             date.normalizeDateString('15 July 2018') == '2018-07-15' &&
             date.normalizeDateString('4 March 2018') == '2018-03-04'
         );
    };

    const us_test = () => {
         return (
             date.normalizeDateString('October 14, 2016') == '2016-10-14'
         );
    };

    return {
        de_test: de_test,
        es_test: es_test,
        fr_test: fr_test,
        it_test: it_test,
        uk_test: uk_test,
        us_test: us_test
    };
})()

tests.register('date', date_tests);
<commit_msg>removed a trailing space<commit_after>/* Copyright(c) 2018 Philip Mulcahy. */
/* jshint strict: true, esversion: 6 */

const date_tests = (() => {
    "use strict";

    const de_test = () => {
         return (
             date.normalizeDateString('29 Dezember 2017') == '2017-12-29' &&
             date.normalizeDateString('29. Dezember 2017') == '2017-12-29'
         );
    };

    const es_test = () => {
        return (
            date.normalizeDateString('16 de noviembre de 2018') == '2018-11-16' &&
            date.normalizeDateString('23 de agosto de 2016') == '2016-08-23'
        );
   };

    const fr_test = () => {
         return (
             date.normalizeDateString('29 mai 2018') == '2018-05-29' &&
             date.normalizeDateString('29. mai 2018') == '2018-05-29'
         );
    };

    const it_test = () => {
         return (
             date.normalizeDateString('22. luglio 2016') == '2016-07-22'
         );
    };

    const uk_test = () => {
         return (
             date.normalizeDateString('15 July 2018') == '2018-07-15' &&
             date.normalizeDateString('4 March 2018') == '2018-03-04'
         );
    };

    const us_test = () => {
         return (
             date.normalizeDateString('October 14, 2016') == '2016-10-14'
         );
    };

    return {
        de_test: de_test,
        es_test: es_test,
        fr_test: fr_test,
        it_test: it_test,
        uk_test: uk_test,
        us_test: us_test
    };
})()

tests.register('date', date_tests);
<|endoftext|>


<commit_before>var dummyEl = document.getElementById('dummy')

test('Mithril accessible as window.m', function() {
	expect(1);
	ok(window.m);
});

test('issue99', function() {
	expect(3);
	var view1 = m('div', {}, [
		m('a', {href: '#/product/' + 12345}, 'link1')
	]);

	var view2 = m('div', {}, [
	  m('img', {src: 'http://www.ru', align:'right', width:400}),
	  m('h1', {}, 'Product1'),
	  m('h2', {}, 'brand')
	]);

	m.render(dummyEl, view1);
	equal(dummyEl.innerHTML, '
link1
');

	m.render(dummyEl, view2);
	equal(dummyEl.innerHTML, '

Product1

brand

');

	m.render(dummyEl, view1);
	equal(dummyEl.innerHTML, '
link1
');

});
<commit_msg>Added assert messages<commit_after>var dummyEl = document.getElementById('dummy')

test('Mithril accessible as window.m', function() {
	expect(1);
	ok(window.m);
});

test('issue99 regression', function() {
	// https://github.com/lhorie/mithril.js/issues/99
	expect(3);
	var view1 = m('div', {}, [
		m('a', {href: '#/product/' + 12345}, 'link1')
	]);

	var view2 = m('div', {}, [
	  m('img', {src: 'http://www.ru', align:'right', width:400}),
	  m('h1', {}, 'Product1'),
	  m('h2', {}, 'brand')
	]);

	m.render(dummyEl, view1);
	equal(dummyEl.innerHTML, '
link1
', 'view1 rendered correctly');

	m.render(dummyEl, view2);
	equal(dummyEl.innerHTML, '

Product1

brand

', 'view2 rendered correctly');

	m.render(dummyEl, view1);
	equal(dummyEl.innerHTML, '
link1
', 'view1 should be restored correctly');

});
<|endoftext|>


<commit_before>import update from 'react-addons-update';
import { generateCacheTTL } from 'redux-cache';
import _ from 'lodash';

import * as actionTypes from '../constants/actionTypes';
import initialState from './initialState';

const data = (state = {}, action) => {
  let combined;

  switch (action.type) {
    case actionTypes.DATA_WORKER_ADD_DATA_REQUEST:
      const {
        fetchedUntil = state.fetchedUntil,
      } = action.payload;

      return update(state, {
        fetchedUntil: { $set: fetchedUntil ? fetchedUntil : 'start' },
        cacheUntil: { $set: generateCacheTTL(36e5) },
        metaData: { $merge: { size: _.get(state, 'metaData.size', 0) + action.payload.fetchedCount } },
      });

    case actionTypes.DATA_WORKER_ADD_DATA_SUCCESS:
      return update(state, {
        data: {
          aggregationsByDate: { $set: state.data.aggregationsByDate },
          combined: { $push: action.payload.result.data || [] },
          current: { $set: state.data.current },
          next: { $set: state.data.next },
          prev: { $set: state.data.prev },
        },
        metaData: { $merge: action.payload.result.metaData || {} },
      });

    case actionTypes.DATA_WORKER_UPDATE_DATUM_SUCCESS:
      const datum = action.payload.result.datum;
      const existingDatumIndex = _.findIndex(state.data.combined, { id: datum.id });

      return update(state, {
        data: {
          aggregationsByDate: { $set: state.data.aggregationsByDate },
          combined: { $splice: [[existingDatumIndex, 1, datum]] },
          current: { $set: state.data.current },
          next: { $set: state.data.next },
          prev: { $set: state.data.prev },
        },
        metaData: { $merge: action.payload.result.metaData || {} },
      });

    case actionTypes.DATA_WORKER_REMOVE_DATA_SUCCESS:
    case actionTypes.LOGOUT_REQUEST:
    case actionTypes.FETCH_PATIENT_DATA_FAILURE:
      return update(state, { $set: {
        ...initialState.data,
        cacheUntil: _.get(action.payload, 'preserveCache') ? state.cacheUntil : null,
        metaData: _.get(action.payload, 'preserveCache') ? { patientId: _.get(state, 'metaData.patientId') } : {},
      } });

    case actionTypes.DATA_WORKER_QUERY_DATA_SUCCESS:
      const current = _.get(action.payload, 'result.data.current', {});
      const next = _.get(action.payload, 'result.data.next', {});
      const prev = _.get(action.payload, 'result.data.prev', {});

      // We only want to replace the combined data when data types are queried.
      // This is to allow us to retain the combined data when, for instance, only querying for stats
      const typesQueried = action.payload.result.query.types;
      combined = typesQueried ? [] : state.data.combined;

      if (typesQueried) {
        console.time('Process Combined Data');
        const currentData = current.data || {};
        const nextData = next.data || {};
        const prevData = prev.data || {};

        _.each([prevData, currentData, nextData], (dataSet = {}) => {
          _.forOwn(dataSet, datums => {
            combined.push.apply(combined, datums);
          });
        });

        combined = _.uniqBy(combined, 'id');
        console.timeEnd('Process Combined Data');
      }

      return update(state, {
        data: {
          aggregationsByDate: { $set: current.aggregationsByDate || state.data.aggregationsByDate },
          combined: { $set: combined },
          current: { $set: current },
          next: { $set: next },
          prev: { $set: prev },
        },
        timePrefs: { $merge: action.payload.result.timePrefs || {} },
        bgPrefs: { $merge: action.payload.result.bgPrefs || {} },
        metaData: { $merge: action.payload.result.metaData || {} },
        query: { $set: action.payload.result.query || {} }
      });

    default:
      return state;
  }
};

export default data;
<commit_msg>preserve fetchedUntil when caching data<commit_after>import update from 'react-addons-update';
import { generateCacheTTL } from 'redux-cache';
import _ from 'lodash';

import * as actionTypes from '../constants/actionTypes';
import initialState from './initialState';

const data = (state = {}, action) => {
  let combined;

  switch (action.type) {
    case actionTypes.DATA_WORKER_ADD_DATA_REQUEST:
      const {
        fetchedUntil = state.fetchedUntil,
      } = action.payload;

      return update(state, {
        fetchedUntil: { $set: fetchedUntil ? fetchedUntil : 'start' },
        cacheUntil: { $set: generateCacheTTL(36e5) },
        metaData: { $merge: { size: _.get(state, 'metaData.size', 0) + action.payload.fetchedCount } },
      });

    case actionTypes.DATA_WORKER_ADD_DATA_SUCCESS:
      return update(state, {
        data: {
          aggregationsByDate: { $set: state.data.aggregationsByDate },
          combined: { $push: action.payload.result.data || [] },
          current: { $set: state.data.current },
          next: { $set: state.data.next },
          prev: { $set: state.data.prev },
        },
        metaData: { $merge: action.payload.result.metaData || {} },
      });

    case actionTypes.DATA_WORKER_UPDATE_DATUM_SUCCESS:
      const datum = action.payload.result.datum;
      const existingDatumIndex = _.findIndex(state.data.combined, { id: datum.id });

      return update(state, {
        data: {
          aggregationsByDate: { $set: state.data.aggregationsByDate },
          combined: { $splice: [[existingDatumIndex, 1, datum]] },
          current: { $set: state.data.current },
          next: { $set: state.data.next },
          prev: { $set: state.data.prev },
        },
        metaData: { $merge: action.payload.result.metaData || {} },
      });

    case actionTypes.DATA_WORKER_REMOVE_DATA_SUCCESS:
    case actionTypes.LOGOUT_REQUEST:
    case actionTypes.FETCH_PATIENT_DATA_FAILURE:
      return update(state, { $set: {
        ...initialState.data,
        cacheUntil: _.get(action.payload, 'preserveCache') ? state.cacheUntil : null,
        fetchedUntil: _.get(action.payload, 'preserveCache') ? state.fetchedUntil : null,
        metaData: _.get(action.payload, 'preserveCache') ? { patientId: _.get(state, 'metaData.patientId') } : {},
      } });

    case actionTypes.DATA_WORKER_QUERY_DATA_SUCCESS:
      const current = _.get(action.payload, 'result.data.current', {});
      const next = _.get(action.payload, 'result.data.next', {});
      const prev = _.get(action.payload, 'result.data.prev', {});

      // We only want to replace the combined data when data types are queried.
      // This is to allow us to retain the combined data when, for instance, only querying for stats
      const typesQueried = action.payload.result.query.types;
      combined = typesQueried ? [] : state.data.combined;

      if (typesQueried) {
        console.time('Process Combined Data');
        const currentData = current.data || {};
        const nextData = next.data || {};
        const prevData = prev.data || {};

        _.each([prevData, currentData, nextData], (dataSet = {}) => {
          _.forOwn(dataSet, datums => {
            combined.push.apply(combined, datums);
          });
        });

        combined = _.uniqBy(combined, 'id');
        console.timeEnd('Process Combined Data');
      }

      return update(state, {
        data: {
          aggregationsByDate: { $set: current.aggregationsByDate || state.data.aggregationsByDate },
          combined: { $set: combined },
          current: { $set: current },
          next: { $set: next },
          prev: { $set: prev },
        },
        timePrefs: { $merge: action.payload.result.timePrefs || {} },
        bgPrefs: { $merge: action.payload.result.bgPrefs || {} },
        metaData: { $merge: action.payload.result.metaData || {} },
        query: { $set: action.payload.result.query || {} }
      });

    default:
      return state;
  }
};

export default data;
<|endoftext|>