<commit_before>// ==UserScript==
// @name		      pcp - pr0gramm color picker
// @author		      N0ui
// @namespace	      pcp
// @include		      http://*pr0gramm.com*
// @include		      https://*pr0gramm.com*
// @version		      1.0
// @updateURL	      https://raw.githubusercontent.com/N0ui/pr0gramm-color-picker/master/pcp.user.js
// @downloadURL	      https://raw.githubusercontent.com/N0ui/pr0gramm-color-picker/master/pcp.user.js
// @copyright	      2015+, N0ui
// @description	      alles bleibt hier nicht so wie es ist! (Für den der will)
// @icon		      http://pr0gramm.com/media/pr0gramm-favicon.png
// @run-at            document-end
// ==/UserScript==
(function () {
    'use strict';
    var PCC = {
        // used colors
        colorNames: [{
            key: 'html',
            html: '
Hauptfarben
'
        }, {
            desc: 'Hauptfarbe',
            key: 'main-color',
            value: '#ee4d2e'
        }, {
            desc: 'Hintergrund',
            key: 'bg-color',
            value: '#161618'
        }, {
            desc: 'Standard Schriftfarbe',
            key: 'main-font-color',
            value: '#f2f5f4'
        }, {
            desc: 'Standard Schriftfarbe 2 (grau)',
            key: 'second-main-font-color',
            value: '#888888'
        }, {
            desc: 'Linkfarbe',
            key: 'link-color',
            value: '#75c0c7'
        }, {
            desc: 'Linkfarbe Hover',
            key: 'link-color-hover',
            value: '#F5F7F6'
        }, {
            key: 'html',
            html: '

Buttons
'
        }, {
            desc: 'Buttontext',
            key: 'btn-color',
            value: '#f2f5f4'
        }, {
            desc: 'Abbrechen Button Hintergrund',
            key: 'cancelBtn-bg-color',
            value: '#212425'
        }, {
            desc: 'Abbrechen Button Text',
            key: 'cancelBtn-color',
            value: '#888888'
        }, {
            desc: 'Button Hover Hintergrund',
            key: 'btn-hover-bg-color',
            value: '#F5F7F6'
        }, {
            desc: 'Button Hover Text',
            key: 'btn-hover-color',
            value: '#555555'
        }, {
            key: 'html',
            html: '

Video & Tags
'
        }, {
            desc: 'Tag Hintergrund',
            key: 'tag-bg-color',
            value: '#2A2E31'
        }, {
            desc: 'Tag Text',
            key: 'tag-color',
            value: '#F5F7F6'
        }, {
            desc: 'Video Prozessbalken',
            key: 'video-bg-color',
            value: '#75c0c7'
        }, {
            key: 'html',
            html: '

Sonstiges
'
        }, {
            desc: 'Warnung',
            key: 'warn-color',
            value: '#fc8833'
        }],
        // calculate brightness (http://www.sitepoint.com/javascript-generate-lighter-darker-color/)
        colorLuminance: function (hex, lum) {
            // validate hex string
            hex = String(hex).replace(/[^0-9a-f]/gi, '');
            if (hex.length < 6) {
                hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
            }
            lum = lum || 0;

            // convert to decimal and change luminosity
            var rgb = "#",
                c, i;
            for (i = 0; i < 3; i++) {
                c = parseInt(hex.substr(i * 2, 2), 16);
                c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
                rgb += ("00" + c).substr(c.length);
            }

            return rgb;
        },
        // style
        cssStyle: function () {
            var $styleEl = $('#pcp-style'),
                cssStr = 'html, body, h3, .tab-bar a, .head-link, a#inboxLink, #inboxLink.empty, #search-submit-inline, .user, .user-score {color: ' + localStorage["main-font-color"] + ';}';
            cssStr += 'input.box-from-label:checked + label:before {background-color: ' + localStorage["main-font-color"] + ';}input.box-from-label + label:before {border: 1px solid ' + localStorage["main-font-color"] + ';}';
            cssStr += '#filter-save,.confirm-button, input[type=button], input[type=submit],.filter-setting.active .filter-check, .loader > div, div.stream-next:hover span.stream-next-icon, div.stream-prev:hover span.stream-prev-icon, .user-follow, .user-unfollow {';
            cssStr += 'background-color: ' + localStorage["main-color"] + ';}';
            cssStr += '.filter-setting.active .filter-check, #upload-droparea {';
            cssStr += 'border: 1px solid ' + localStorage["main-color"] + ';}';
            cssStr += 'div.overlay-tabs span.overlay-link:hover, div.overlay-tabs span.active,#upload-droparea.active, #key-indicator, a.item-fullsize-link:hover, .vote-up:hover, .voted-down .vote-up:hover, .voted-up .vote-up:hover, .voted-up .vote-up, a.bookmarklet, #search-submit-inline:hover, #settings-logout-link,.action,.filter-setting.active .filter-name,.head-link:hover,.tab-bar a:hover, .tab-bar a.active,a.head-tab.active, a.head-tab:hover,#inboxLink, #inboxLink.empty:hover,.head-link:hover, div.tagsinput span.tag a, .vote-fav.faved, .vote-fav:hover {';
            cssStr += 'color: ' + localStorage["main-color"] + ';}';
            cssStr += 'a, .link, a.user:hover, a.tag-link:hover, span.tag.voted-down a.tag-link:hover {';
            cssStr += 'color: ' + localStorage["link-color"] + ';}';
            cssStr += 'a:hover, .link:hover, .action:hover {';
            cssStr += 'color: ' + localStorage["link-color-hover"] + ';}';
            cssStr += '.confirm-button, input[type=button], input[type=submit], .user-follow, .user-unfollow {';
            cssStr += 'color: ' + localStorage["btn-color"] + ';}';
            cssStr += '.warn{';
            cssStr += 'color: ' + localStorage["warn-color"] + ';}';
            cssStr += '.confirm-button:hover, input[type=button]:hover, input[type=button]:focus, input[type=submit]:hover, input[type=submit]:focus {background-color: #F5F7F6;}';
            cssStr += 'input[type=button].cancel, input[type=button]:disabled, input[type=submit]:disabled, input[type=submit].cancel {';
            cssStr += 'background-color: ' + localStorage["cancelBtn-bg-color"] + ';color: ' + localStorage["cancelBtn-color"] + ';}';
            cssStr += '.confirm-button:hover, input[type=button]:hover, input[type=button]:focus, input[type=submit]:hover, input[type=submit]:focus, .user-follow:hover, .user-unfollow:hover {';
            cssStr += 'background-color: ' + localStorage["btn-hover-bg-color"] + '; color:  ' + localStorage["btn-hover-color"] + ';}';
            cssStr += 'span.tag {background-color: ' + localStorage["tag-bg-color"] + ' !important;}';
            cssStr += 'a.tag-link {color: ' + localStorage["tag-color"] + ';}';
            cssStr += 'div.video-position {background-color: ' + localStorage["video-bg-color"] + ';}';

            cssStr += '.tab-bar span, .user-stats, div.comment-foot {color: ' + localStorage["second-main-font-color"] + ';}';
            cssStr += 'a.head-tab {color: ' + this.colorLuminance(localStorage["second-main-font-color"], 0.2) + ';}';

            cssStr += 'html, body, #footer-links, div.item-container {background-color: ' + localStorage["bg-color"] + ';}';
            cssStr += '#head-content, input, textarea {background-color: ' + this.colorLuminance(localStorage["bg-color"], -0.5) + ';}';
            cssStr += 'div.comment-foot, div.comment-box div.comment-box {border-color: ' + this.colorLuminance(localStorage["bg-color"], -0.3) + ';}';
            cssStr += 'input.q {background-color: ' + this.colorLuminance(localStorage["bg-color"], -0.3) + ';}';

            cssStr += '.pcp-input-outer {display:blofck;margin: 0 0 10px 0;}.pcp-label {width: 40%; display:inline-block !important;}.pcp-color{padding: 0;width: 50px;display: inline-block;}#pcp-reset {border: 1px solid #fff;display: inline-block;padding: 8px 20px;cursor:pointer;}';

            if ($styleEl.length < 1) {
                $('body').append('');
            }
            $styleEl.html(cssStr);
        },
        // html form
        settingsHtml: function () {
            var settingsHtmlStr = '';
            settingsHtmlStr += '
';
            settingsHtmlStr += '
pr0gramm Farben

Stell einfach deine Farben ein
';
            $.each(this.colorNames, function (i, v) {
                if (v.key !== 'html') {
                    settingsHtmlStr += '
' + v.desc + '';
                    settingsHtmlStr += '<input type="color" class="pcp-color" id="pcp-' + v.key + '">
';
                } else {
                    settingsHtmlStr += v.html;
                }
            });
            settingsHtmlStr += '

Farben zurücksetzen
';
            return settingsHtmlStr;
        },
        // reset all colors
        reset: function () {
            $.each(this.colorNames, function (i, v) {
                if (v.key !== 'html') {
                    localStorage.removeItem(v.key);
                }
            });

            this.init();
        },
        // update colors
        update: function () {
            $.each(this.colorNames, function (i, v) {
                if (v.key !== 'html') {
                    localStorage[v.key] = $('#pcp-' + v.key).val();
                }
            });

            $('#pcp-style').html(this.cssStyle());
        },
        // init
        init: function () {
            var $styleEl = $('#pcp-style');

            // set default colors
            if (typeof localStorage["main-color"] === 'undefined' || localStorage["main-color"] === '') {
                $.each(this.colorNames, function (i, v) {
                    if (v.key !== 'html') {
                        localStorage[v.key] = v.value;
                    }
                });
            }

            // check if form exists
            if ($('#settings-pcp').length < 1) {
                $('#settings-site-form').prepend(PCC.settingsHtml());
            }

            // append style
            if ($styleEl.length < 1) {
                $('head').append('');
            }
            $styleEl.html(this.cssStyle());

            $.each(this.colorNames, function (i, v) {
                if (v.key !== 'html') {
                    $('#pcp-' + v.key).val(localStorage[v.key]);
                }
            });
        }
    };

    // check if document is ready
    $(function () {

        // reset colors
        $(document).on('click', '#pcp-reset', function () {
            PCC.reset();
        });

        // update colors
        $(document).on('change', '.pcp-color', function () {
            PCC.update();
        });

        // only to show settings
        p.View.Base.prototype.render = function () {
            if (!this.visible) {
                return;
            }
            if (!this.$container) {
                this.$container = $(this.compiledTemplate(this.data));
            } else {
                this.$container.html(this.compiledTemplate(this.data));
            }
            var anchors = this.$container.find('a[href^="#"]');
            if (p._hasPushState) {
                anchors.each(function () {
                    this.href = '/' + $(this).attr('href').substr(
                        1);
                });
            }
            anchors.fastclick(this.handleHashLink.bind(this));
            this.needsRendering = false;

            PCC.init();
        };
    });
})();<commit_msg>Bugfix<commit_after>// ==UserScript==
// @name		      pcp - pr0gramm color picker
// @author		      N0ui
// @namespace	      pcp
// @include		      http://*pr0gramm.com*
// @include		      https://*pr0gramm.com*
// @version		      1.0
// @updateURL	      https://raw.githubusercontent.com/N0ui/pr0gramm-color-picker/master/pcp.user.js
// @downloadURL	      https://raw.githubusercontent.com/N0ui/pr0gramm-color-picker/master/pcp.user.js
// @copyright	      2015+, N0ui
// @description	      alles bleibt hier nicht so wie es ist! (Für den der will)
// @icon		      http://pr0gramm.com/media/pr0gramm-favicon.png
// @run-at            document-end
// ==/UserScript==
(function () {
    'use strict';
    var PCC = {
        // used colors
        colorNames: [{
            key: 'html',
            html: '
Hauptfarben
'
        }, {
            desc: 'Hauptfarbe',
            key: 'main-color',
            value: '#ee4d2e'
        }, {
            desc: 'Hintergrund',
            key: 'bg-color',
            value: '#161618'
        }, {
            desc: 'Standard Schriftfarbe',
            key: 'main-font-color',
            value: '#f2f5f4'
        }, {
            desc: 'Standard Schriftfarbe 2 (grau)',
            key: 'second-main-font-color',
            value: '#888888'
        }, {
            desc: 'Linkfarbe',
            key: 'link-color',
            value: '#75c0c7'
        }, {
            desc: 'Linkfarbe Hover',
            key: 'link-color-hover',
            value: '#F5F7F6'
        }, {
            key: 'html',
            html: '

Buttons
'
        }, {
            desc: 'Buttontext',
            key: 'btn-color',
            value: '#f2f5f4'
        }, {
            desc: 'Abbrechen Button Hintergrund',
            key: 'cancelBtn-bg-color',
            value: '#212425'
        }, {
            desc: 'Abbrechen Button Text',
            key: 'cancelBtn-color',
            value: '#888888'
        }, {
            desc: 'Button Hover Hintergrund',
            key: 'btn-hover-bg-color',
            value: '#F5F7F6'
        }, {
            desc: 'Button Hover Text',
            key: 'btn-hover-color',
            value: '#555555'
        }, {
            key: 'html',
            html: '

Video & Tags
'
        }, {
            desc: 'Tag Hintergrund',
            key: 'tag-bg-color',
            value: '#2A2E31'
        }, {
            desc: 'Tag Text',
            key: 'tag-color',
            value: '#F5F7F6'
        }, {
            desc: 'Video Prozessbalken',
            key: 'video-bg-color',
            value: '#75c0c7'
        }, {
            key: 'html',
            html: '

Sonstiges
'
        }, {
            desc: 'Warnung',
            key: 'warn-color',
            value: '#fc8833'
        }],
        // calculate brightness (http://www.sitepoint.com/javascript-generate-lighter-darker-color/)
        colorLuminance: function (hex, lum) {
            // validate hex string
            hex = String(hex).replace(/[^0-9a-f]/gi, '');
            if (hex.length < 6) {
                hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
            }
            lum = lum || 0;

            // convert to decimal and change luminosity
            var rgb = "#",
                c, i;
            for (i = 0; i < 3; i++) {
                c = parseInt(hex.substr(i * 2, 2), 16);
                c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
                rgb += ("00" + c).substr(c.length);
            }

            return rgb;
        },
        convertHex: function(hex, opacity){
            var hex = hex.replace('#','');
            var r = parseInt(hex.substring(0,2), 16);
            var g = parseInt(hex.substring(2,4), 16);
            var b = parseInt(hex.substring(4,6), 16);

            return 'rgba('+r+','+g+','+b+','+opacity/100+')';
        },
        // style
        cssStyle: function () {
            var $styleEl = $('#pcp-style'),
                cssStr = 'html, body, h3, .tab-bar a, .head-link, a#inboxLink, #inboxLink.empty, #search-submit-inline, .user, .user-score {color: ' + localStorage["main-font-color"] + ';}';
            cssStr += 'input.box-from-label:checked + label:before {background-color: ' + localStorage["main-font-color"] + ';}input.box-from-label + label:before {border: 1px solid ' + localStorage["main-font-color"] + ';}';
            cssStr += '#filter-save,.confirm-button, input[type=button], input[type=submit],.filter-setting.active .filter-check, .loader > div, div.stream-next:hover span.stream-next-icon, div.stream-prev:hover span.stream-prev-icon, .user-follow, .user-unfollow {';
            cssStr += 'background-color: ' + localStorage["main-color"] + ';}';
            cssStr += '.filter-setting.active .filter-check, #upload-droparea {';
            cssStr += 'border: 1px solid ' + localStorage["main-color"] + ';}';
            cssStr += 'div.overlay-tabs span.overlay-link:hover, div.overlay-tabs span.active,#upload-droparea.active, #key-indicator, a.item-fullsize-link:hover, .vote-up:hover, .voted-down .vote-up:hover, .voted-up .vote-up:hover, .voted-up .vote-up, a.bookmarklet, #search-submit-inline:hover, #settings-logout-link,.action,.filter-setting.active .filter-name,.head-link:hover,.tab-bar a:hover, .tab-bar a.active,a.head-tab.active, a.head-tab:hover,#inboxLink, #inboxLink.empty:hover,.head-link:hover, div.tagsinput span.tag a, .vote-fav.faved, .vote-fav:hover {';
            cssStr += 'color: ' + localStorage["main-color"] + ';}';
            cssStr += 'a, .link, a.user:hover, a.tag-link:hover, span.tag.voted-down a.tag-link:hover {';
            cssStr += 'color: ' + localStorage["link-color"] + ';}';
            cssStr += 'a:hover, .link:hover, .action:hover {';
            cssStr += 'color: ' + localStorage["link-color-hover"] + ';}';
            cssStr += '.confirm-button, input[type=button], input[type=submit], .user-follow, .user-unfollow {';
            cssStr += 'color: ' + localStorage["btn-color"] + ';}';
            cssStr += '.warn{';
            cssStr += 'color: ' + localStorage["warn-color"] + ';}';
            cssStr += '.confirm-button:hover, input[type=button]:hover, input[type=button]:focus, input[type=submit]:hover, input[type=submit]:focus {background-color: #F5F7F6;}';
            cssStr += 'input[type=button].cancel, input[type=button]:disabled, input[type=submit]:disabled, input[type=submit].cancel {';
            cssStr += 'background-color: ' + localStorage["cancelBtn-bg-color"] + ';color: ' + localStorage["cancelBtn-color"] + ';}';
            cssStr += '.confirm-button:hover, input[type=button]:hover, input[type=button]:focus, input[type=submit]:hover, input[type=submit]:focus, .user-follow:hover, .user-unfollow:hover {';
            cssStr += 'background-color: ' + localStorage["btn-hover-bg-color"] + '; color:  ' + localStorage["btn-hover-color"] + ';}';
            cssStr += 'span.tag {background-color: ' + localStorage["tag-bg-color"] + ' !important;}';
            cssStr += 'a.tag-link {color: ' + localStorage["tag-color"] + ';}';
            cssStr += 'div.video-position {background-color: ' + localStorage["video-bg-color"] + ';}';

            cssStr += '.tab-bar span, .user-stats, div.comment-foot {color: ' + localStorage["second-main-font-color"] + ';}';
            cssStr += 'a.head-tab {color: ' + this.colorLuminance(localStorage["second-main-font-color"], 0.2) + ';}';

            cssStr += 'html, body, #footer-links, div.item-container {background-color: ' + localStorage["bg-color"] + ';}';
            cssStr += '#head-content {background-color: ' + this.convertHex(this.colorLuminance(localStorage["bg-color"], -0.6), 80) + ';}';
            cssStr += 'input, textarea {background-color: ' + this.colorLuminance(localStorage["bg-color"], 0.3) + ';}';
            cssStr += 'input:focus, textarea:focus {background-color: ' + this.colorLuminance(localStorage["bg-color"], 0.4) + ';}';
            cssStr += 'div.comment-foot, div.comment-box div.comment-box {border-color: ' + this.colorLuminance(localStorage["bg-color"], -0.3) + ';}';
            cssStr += 'input.q {background-color: ' + this.convertHex(this.colorLuminance(localStorage["bg-color"], 0.4), 80) + ';}';

            cssStr += '.pcp-input-outer {display:blofck;margin: 0 0 10px 0;}.pcp-label {width: 40%; display:inline-block !important;}.pcp-color{padding: 0;width: 50px;display: inline-block;}#pcp-reset {border: 1px solid #fff;display: inline-block;padding: 8px 20px;cursor:pointer;}';

            if ($styleEl.length < 1) {
                $('body').append('');
            }
            $styleEl.html(cssStr);
        },
        // html form
        settingsHtml: function () {
            var settingsHtmlStr = '';
            settingsHtmlStr += '
';
            settingsHtmlStr += '
pr0gramm Farben

Stell einfach deine Farben ein
';
            $.each(this.colorNames, function (i, v) {
                if (v.key !== 'html') {
                    settingsHtmlStr += '
' + v.desc + '';
                    settingsHtmlStr += '<input type="color" class="pcp-color" id="pcp-' + v.key + '">
';
                } else {
                    settingsHtmlStr += v.html;
                }
            });
            settingsHtmlStr += '

Farben zurücksetzen
';
            return settingsHtmlStr;
        },
        // reset all colors
        reset: function () {
            $.each(this.colorNames, function (i, v) {
                if (v.key !== 'html') {
                    localStorage.removeItem(v.key);
                }
            });

            this.init();
        },
        // update colors
        update: function () {
            $.each(this.colorNames, function (i, v) {
                if (v.key !== 'html') {
                    localStorage[v.key] = $('#pcp-' + v.key).val();
                }
            });

            $('#pcp-style').html(this.cssStyle());
        },
        // init
        init: function () {
            var $styleEl = $('#pcp-style');

            // set default colors
            if (typeof localStorage["main-color"] === 'undefined' || localStorage["main-color"] === '') {
                $.each(this.colorNames, function (i, v) {
                    if (v.key !== 'html') {
                        localStorage[v.key] = v.value;
                    }
                });
            }

            // check if form exists
            if ($('#settings-pcp').length < 1) {
                $('#settings-site-form').prepend(PCC.settingsHtml());
            }

            // append style
            if ($styleEl.length < 1) {
                $('head').append('');
            }
            $styleEl.html(this.cssStyle());

            $.each(this.colorNames, function (i, v) {
                if (v.key !== 'html') {
                    $('#pcp-' + v.key).val(localStorage[v.key]);
                }
            });
        }
    };

    // check if document is ready
    $(function () {

        // reset colors
        $(document).on('click', '#pcp-reset', function () {
            PCC.reset();
        });

        // update colors
        $(document).on('change', '.pcp-color', function () {
            PCC.update();
        });

        // only to show settings
        p.View.Base.prototype.render = function () {
            if (!this.visible) {
                return;
            }
            if (!this.$container) {
                this.$container = $(this.compiledTemplate(this.data));
            } else {
                this.$container.html(this.compiledTemplate(this.data));
            }
            var anchors = this.$container.find('a[href^="#"]');
            if (p._hasPushState) {
                anchors.each(function () {
                    this.href = '/' + $(this).attr('href').substr(
                        1);
                });
            }
            anchors.fastclick(this.handleHashLink.bind(this));
            this.needsRendering = false;

            PCC.init();
        };
    });
})();<|endoftext|>


<commit_before>/**
 * JavaScript implementation of the core concept 'object'
 * version: 0.1.0
 * (c) Liangcun Jiang
 * latest change: Feb 17, 2017.
 */
define(["dojo/_base/declare",
    "dojo/Deferred",
    "esri/tasks/query",
    "esri/layers/FeatureLayer",
    "esri/tasks/BufferParameters",
    "esri/tasks/RelationParameters",
    "esri/tasks/GeometryService"
], function (declare, Deferred, Query, FeatureLayer, BufferParameters, RelationParameters, GeometryService) {
    return declare(null, {
        /**
         *CcObject constructor: Constructs an object instance from either a Map Service or Feature Service
         *@param url: URL to the ArcGIS Server REST resource that represents an feature service.
         */
        constructor: function (url) {
            if (url === null || url === "" || url === undefined) {
                alert("Please enter a valid URL for the field data");
                return;
            }
            var featureLayer = new FeatureLayer(url);
            this.layer = featureLayer; //return featureLayer instead?
        },

        /**
         *CcObject function: gets CcObject's bounds in form of a bounding box(xmin, ymin, xmax, ymax)
         *Return type: Deferred
         *Uses the callback function to receive the object's extent.
         */
        bounds: function () {
            var query = new Query();
            query.where = "1=1"; // Query for all records
            query.outFields = ["*"];
            query.returnGeometry = true;
            var process = this.layer.queryExtent(query);
            return process.then(function (extent) {
                return extent;
            });
        },

        /**
         *CcObject function: gets CcObject's geometry
         *Return type: Deferred
         *Uses the callback function to receive the object's geometry (an array of Geometry).
         */
        getGeometry: function () {
            var query = new Query();
            query.where = "1=1"; // Query for all records
            query.outFields = ["*"];
            query.returnGeometry = true;
            var process = this.layer.queryFeatures(query);
            //function _getGeometry(featureSet){
            //    var geometry = [];
            //    for (var i = 0; i < featureSet.features.length; i++  ) {
            //        geometry.push(featureSet.features[i].geometry);
            //    }
            //    var deferred = new Deferred();
            //    deferred.resolve(geometry);
            //    return deferred.promise;
            //}
            return process.then(function (featureSet) {
                var geometryArray = [];
                for (var i = 0; i < featureSet.features.length; i++) {
                    geometryArray.push(featureSet.features[i].geometry);
                }
                return geometryArray;
            });
        },

        /**
         *CcObject function: Creates buffer polygons at a specified distance around the given object.
         *@param distance: the distance the input object are buffered.
         *@param unitType: the unit for calculating each buffer distance.(case insensitive: kilometer = Kilometer)
         *                 Units can be singular or plural forms: e.g. Foot = feet
         *Return type: Deferred
         *Uses the callback function to receive an array of Geometry that contains the buffer polygons.
         */
        buffer: function (distance, unitType) {
            //This service provided by ESRI is for development and testing purposes only.
            //var gsUrl = "https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer";
            var gsUrl = "https://ags-raid.geog.ucsb.edu:6443/arcgis/rest/services/Utilities/Geometry/GeometryServer";
            var gs = new GeometryService(gsUrl);

            //Defines valid unit types here
            var bufferUnits = {
                "METER": GeometryService.UNIT_METER,
                "METERS": GeometryService.UNIT_METER,
                "KILOMETER": GeometryService.UNIT_KILOMETER,
                "KILOMETERS": GeometryService.UNIT_KILOMETER,
                "FOOT": GeometryService.UNIT_FOOT, //International foot (0.3048 meters)
                "FEET": GeometryService.UNIT_FOOT,
                "MILE": GeometryService.UNIT_STATUTE_MILE, //Miles (5,280 feet, 1,760 yards, or exactly 1,609.344 meters)
                "MILES": GeometryService.UNIT_STATUTE_MILE,
                "NAUTICAL_MILE": GeometryService.UNIT_NAUTICAL_MILE, //Nautical Miles (1,852 meters)
                "NAUTICAL_MILES": GeometryService.UNIT_NAUTICAL_MILE,
                "DEGREE": GeometryService.UNIT_DEGREE,
                "DEGREES": GeometryService.UNIT_DEGREE
            };

            //setup the buffer parameters
            var params = new BufferParameters();
            params.distances = [distance];
            params.unit = bufferUnits[unitType.toUpperCase()];
            //If true, all geometries buffered at a given distance are unioned into
            //a single (possibly multipart) polygon, and the unioned geometry is placed in the output array.
            params.unionResults = true;

            //Get the object geometries and do the buffer
            return this.geometry().then(function (geometries) {
                //The Geometry Service allows a maxBufferCount of 12500.
                // The maxBufferCount property establishes the maximum number of features that can be buffered
                if (geometries.length <= 12500) {
                    params.geometries = geometries;
                    //do the buffer
                    console.log("Doing the buffer...");
                    //buffer function returns a "<Polygon[]> geometries" Array[1]
                    return gs.buffer(params);
                } else {
                    //if the number of features exceeds the maxBufferCount, then executes buffer operation in two parts.
                    //Needs to extend this code snippet if the number of features > 250000.
                    params.geometries = geometries.slice(0, 12500)
                    //do the buffer
                    console.log("Buffering part 1...");
                    return gs.buffer(params).then(function (bufferedGeometries1) {
                        console.log("Buffering part 2...");
                        params.geometries = geometries.slice(12500);
                        var gs2 = new GeometryService("https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
                        return gs2.buffer(params).then(function (bufferedGeometries2) {
                            //console.log([bufferedGeometries1, bufferedGeometries2]);
                            //console.log(bufferedGeometries1.concat(bufferedGeometries2));
                            var gs3 = new GeometryService(gsUrl);
                            //constructs the set-theoretic union of the two buffered geometries
                            console.log("Unifying two parts...");
                            //union function returns a "<Geometry> geometry" Object, then converts it to an Array[1]
                            return gs3.union(bufferedGeometries1.concat(bufferedGeometries2)).then(function (geoUnion) {
                                return [geoUnion];
                            });
                        });
                    });
                }
            });
        },

        /**
         *CcObject function: returns true if self and obj are in a relationship of type relType.
         *@param obj:
         *@param relType: The spatial relationship to be tested between the two CcObject.
         *Return type: Deferred
         *Uses the callback function to receive the result.
         */
        relation: function (obj, relType) {
            var gsUrl = "https://ags-raid.geog.ucsb.edu:6443/arcgis/rest/services/Utilities/Geometry/GeometryServer";
            var gs = new GeometryService(gsUrl);
            var relationParams = new RelationParameters();
            relationParams.geometries1 = null;
            relationParams.geometries2 = null;
            relationParams.relation = RelationParameters.SPATIAL_REL_WITHIN;
            return gs.relation(relationParams).then(function (relatedResults) {
                return relatedResults ? true : false;
            });
        },

        property: function (prop) {

        }
    });
});<commit_msg>Add JavaScript Implementation by Liangcun Jiang<commit_after>/**
 * JavaScript implementation of the core concept 'object'
 * version: 0.1.0
 * (c) Liangcun Jiang
 * latest change: Feb 17, 2017.
 */
define(["dojo/_base/declare",
    "dojo/Deferred",
    "esri/tasks/query",
    "esri/layers/FeatureLayer",
    "esri/tasks/BufferParameters",
    "esri/tasks/RelationParameters",
    "esri/tasks/GeometryService"
], function (declare, Deferred, Query, FeatureLayer, BufferParameters, RelationParameters, GeometryService) {
    return declare(null, {
        /**
         * CcObject constructor: Constructs an object instance from either a Map Service or Feature Service
         * @param url: URL to the ArcGIS Server REST resource that represents an feature service.
         */
        constructor: function (url) {
            if (url === null || url === "" || url === undefined) {
                alert("Please enter a valid URL for the field data");
                return;
            }
            var featureLayer = new FeatureLayer(url);
            this.layer = featureLayer; //return featureLayer instead?
        },

        /**
         * CcObject function: gets CcObject's bounds in form of a bounding box(xmin, ymin, xmax, ymax)
         * Return type: Deferred
         * Uses the callback function to receive the object's extent.
         */
        bounds: function () {
            var query = new Query();
            query.where = "1=1"; // Query for all records
            query.outFields = ["*"];
            query.returnGeometry = true;
            var process = this.layer.queryExtent(query);
            return process.then(function (extent) {
                return extent;
            });
        },

        /**
         * CcObject function: gets CcObject's geometry
         * Return type: Deferred
         * Uses the callback function to receive the object's geometry (an array of Geometry).
         */
        getGeometry: function () {
            var query = new Query();
            query.where = "1=1"; // Query for all records
            query.outFields = ["*"];
            query.returnGeometry = true;
            var process = this.layer.queryFeatures(query);
            //function _getGeometry(featureSet){
            //    var geometry = [];
            //    for (var i = 0; i < featureSet.features.length; i++  ) {
            //        geometry.push(featureSet.features[i].geometry);
            //    }
            //    var deferred = new Deferred();
            //    deferred.resolve(geometry);
            //    return deferred.promise;
            //}
            return process.then(function (featureSet) {
                var geometryArray = [];
                for (var i = 0; i < featureSet.features.length; i++) {
                    geometryArray.push(featureSet.features[i].geometry);
                }
                return geometryArray;
            });
        },

        /**
         * CcObject function: Creates buffer polygons at a specified distance around the given object.
         * @param distance: the distance the input object are buffered.
         * @param unitType: the unit for calculating each buffer distance.(case insensitive: kilometer = Kilometer)
         *                 Units can be singular or plural forms: e.g. Foot = feet
         * Return type: Deferred
         * Uses the callback function to receive an array of Geometry that contains the buffer polygons.
         */
        buffer: function (distance, unitType) {
            //This service provided by ESRI is for development and testing purposes only.
            //var gsUrl = "https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer";
            var gsUrl = "https://ags-raid.geog.ucsb.edu:6443/arcgis/rest/services/Utilities/Geometry/GeometryServer";
            var gs = new GeometryService(gsUrl);

            //Defines valid unit types here
            var bufferUnits = {
                "METER": GeometryService.UNIT_METER,
                "METERS": GeometryService.UNIT_METER,
                "KILOMETER": GeometryService.UNIT_KILOMETER,
                "KILOMETERS": GeometryService.UNIT_KILOMETER,
                "FOOT": GeometryService.UNIT_FOOT, //International foot (0.3048 meters)
                "FEET": GeometryService.UNIT_FOOT,
                "MILE": GeometryService.UNIT_STATUTE_MILE, //Miles (5,280 feet, 1,760 yards, or exactly 1,609.344 meters)
                "MILES": GeometryService.UNIT_STATUTE_MILE,
                "NAUTICAL_MILE": GeometryService.UNIT_NAUTICAL_MILE, //Nautical Miles (1,852 meters)
                "NAUTICAL_MILES": GeometryService.UNIT_NAUTICAL_MILE,
                "DEGREE": GeometryService.UNIT_DEGREE,
                "DEGREES": GeometryService.UNIT_DEGREE
            };

            //setup the buffer parameters
            var params = new BufferParameters();
            params.distances = [distance];
            params.unit = bufferUnits[unitType.toUpperCase()];
            //If true, all geometries buffered at a given distance are unioned into
            //a single (possibly multipart) polygon, and the unioned geometry is placed in the output array.
            params.unionResults = true;

            //Get the object geometries and do the buffer
            return this.geometry().then(function (geometries) {
                //The Geometry Service allows a maxBufferCount of 12500.
                // The maxBufferCount property establishes the maximum number of features that can be buffered
                if (geometries.length <= 12500) {
                    params.geometries = geometries;
                    //do the buffer
                    console.log("Doing the buffer...");
                    //buffer function returns a "<Polygon[]> geometries" Array[1]
                    return gs.buffer(params);
                } else {
                    //if the number of features exceeds the maxBufferCount, then executes buffer operation in two parts.
                    //Needs to extend this code snippet if the number of features > 250000.
                    params.geometries = geometries.slice(0, 12500)
                    //do the buffer
                    console.log("Buffering part 1...");
                    return gs.buffer(params).then(function (bufferedGeometries1) {
                        console.log("Buffering part 2...");
                        params.geometries = geometries.slice(12500);
                        var gs2 = new GeometryService("https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
                        return gs2.buffer(params).then(function (bufferedGeometries2) {
                            //console.log([bufferedGeometries1, bufferedGeometries2]);
                            //console.log(bufferedGeometries1.concat(bufferedGeometries2));
                            var gs3 = new GeometryService(gsUrl);
                            //constructs the set-theoretic union of the two buffered geometries
                            console.log("Unifying two parts...");
                            //union function returns a "<Geometry> geometry" Object, then converts it to an Array[1]
                            return gs3.union(bufferedGeometries1.concat(bufferedGeometries2)).then(function (geoUnion) {
                                return [geoUnion];
                            });
                        });
                    });
                }
            });
        },

        /**
         * CcObject function: returns true if self and obj are in a relationship of type relType.
         * @param obj:
         * @param relType: The spatial relationship to be tested between the two CcObject.
         * Return type: Deferred
         * Uses the callback function to receive the result.
         */
        relation: function (obj, relType) {
            var gsUrl = "https://ags-raid.geog.ucsb.edu:6443/arcgis/rest/services/Utilities/Geometry/GeometryServer";
            var gs = new GeometryService(gsUrl);
            var relationParams = new RelationParameters();
            relationParams.geometries1 = null;
            relationParams.geometries2 = null;
            relationParams.relation = RelationParameters.SPATIAL_REL_WITHIN;
            return gs.relation(relationParams).then(function (relatedResults) {
                return relatedResults ? true : false;
            });
        },

        /**
         * CcObject function: returns value of property in obj
         * @param prop: the property name
         * Return type: Deferred
         * Uses the callback function to receive the result.
         */
        property: function (prop) {

        }
    });
});<|endoftext|>


<commit_before>'use strict';

const { GraphQLInt, GraphQLString } = require('graphql');

// Pagination arguments
const paginationActionTypes = ['find', 'update', 'delete'];
const fullPaginationActionTypes = ['find'];
const getPaginationArgument = function ({ action, defaultPageSize, maxPageSize }) {
  // Only with operations that return an array and do not provide array of data, i.e. only with findMany, deleteMany and
  // updateMany
  if (!(paginationActionTypes.includes(action.type) && action.multiple)) { return; }

  const paginationArgs = {
    page_size: {
      type: GraphQLInt,
      description: `Sets pagination size.
  Using 0 disables pagination.
  Maximum: ${maxPageSize}`,
      defaultValue: defaultPageSize,
    }
  };

  // Only with safe operations that return an array, i.e. only with findMany
  if (!(fullPaginationActionTypes.includes(action.type) && action.multiple)) { return paginationArgs; }

  return Object.assign(paginationArgs, {
    after: {
      type: GraphQLString,
      description: `Retrieves next pagination batch, using the previous response's last model's 'token'.
Using '' means 'from the beginning'`,
      defaultValue: '',
    },

    before: {
      type: GraphQLString,
      description: `Retrieves previous pagination batch, using the previous response's first model's 'token'.
Using '' means 'from the end'`,
    },

    page: {
      type: GraphQLInt,
      description: `Page number, for pagination.
Starts at 1.
Cannot be used with 'before' or 'after'`,
    },
  });
};

module.exports = {
  getPaginationArgument,
};
<commit_msg>Fix line width<commit_after>'use strict';

const { GraphQLInt, GraphQLString } = require('graphql');

// Pagination arguments
const paginationActionTypes = ['find', 'update', 'delete'];
const fullPaginationActionTypes = ['find'];
const getPaginationArgument = function ({
  action,
  defaultPageSize,
  maxPageSize,
}) {
  // Only with actions that return an array and do not provide array of data,
  // i.e. only with findMany, deleteMany and
  // updateMany
  if (!(paginationActionTypes.includes(action.type) && action.multiple)) {
    return;
  }

  const paginationArgs = {
    page_size: {
      type: GraphQLInt,
      description: `Sets pagination size.
  Using 0 disables pagination.
  Maximum: ${maxPageSize}`,
      defaultValue: defaultPageSize,
    }
  };

  // Only with safe operations that return an array, i.e. only with findMany
  if (!(fullPaginationActionTypes.includes(action.type) && action.multiple)) {
    return paginationArgs;
  }

  return Object.assign(paginationArgs, {
    after: {
      type: GraphQLString,
      description: `Retrieves next pagination batch, using the previous response's last model's 'token'.
Using '' means 'from the beginning'`,
      defaultValue: '',
    },

    before: {
      type: GraphQLString,
      description: `Retrieves previous pagination batch, using the previous response's first model's 'token'.
Using '' means 'from the end'`,
    },

    page: {
      type: GraphQLInt,
      description: `Page number, for pagination.
Starts at 1.
Cannot be used with 'before' or 'after'`,
    },
  });
};

module.exports = {
  getPaginationArgument,
};
<|endoftext|>


<commit_before>/**
 * (description)
 *
 * @author yourname
 */

export default class ListController {
    constructor($q, storeSvc, $scope, $http, NgTableParams, $state, templateSvc, storeManageSvc, Api) {
        "ngInject";
        this.$state = $state;
        this.storeSvc = storeSvc;
        this.q = $q;
        this.NgTableParams = NgTableParams;
        this.d = {};
        this.templateSvc = templateSvc;
        this.storeManageSvc = storeManageSvc;
        this.api = Api;
        this.init();
        this.filter = {
            limit: 10,
            offset: 0
        };
    }

    // 格式化后的数据
    getSearchFormData() {
        let filter = this.filter;
        return filter;
    }

    init() {
        var self = this;
        var _this = this;
        var filter = this.filter;

        this.tableParams = new this.NgTableParams({
            page: 1,
            count: 10
        }, {
            getData: function (params) {
                self.loading = true;
                let formData = self.getSearchFormData(filter);

                formData.page = params.url().page;
                formData.offset = (params.url().page-1) * params.url().count;

                self.loadPromise = self.storeManageSvc.getStoreList(formData);
                return self.loadPromise
                    .then(result => {
                        self.loading = false;
                        if (result.datas) {
                            _this.d = {
                                totalCount: result.totalCount
                            };
                            params.total(result.totalCount);
                            return result.datas;
                        }
                    });
            }
        })
    }

    // 二维码
    showQrcode(storeId) {
        let self = this;
        this.api.get('/storemanage/store/code', {storeId: storeId})
            .then(result => {
                console.log(result);
                this.qrCodeUrl = result.qrCodeImgUrl;
            });
        this.singleStoreId = storeId;

        this.isQrcodeShow = true;
    }

    hideQrcode() {
        this.isQrcodeShow = false;
    }

    // 二维码打印
    printQrcode() {
        $(".ng-isolate-scope").hide();
        var imgHtml = '';
        $("body").append(imgHtml);

        if ((window.print())==true) {
            $("#printImg").remove();
            $(".ng-isolate-scope").show();
        }else {
            $("#printImg").remove();
            $(".ng-isolate-scope").show();
        }
    }

    goClaimList(){
        this.$state.go('storeMclaimlist');
    }

    search() {
        this.storeSvc.getStoreInfoList();
    }

    detail(id) {
        this.$state.go('storeMdetail', {id: id});
    }

    edit(id) {
        this.$state.go('storeMedit', {id: id});
    }

    getstaffpageadd() {
        this.staffnewSvc.getstaffpage()
    }

    goStaff(storeid) {
        this.$state.go('stafflist', {storeid: storeid});
    }

    // 批量导出二维码
    batchDownQrcode() {
        var limit = $("#page .active span").html();
        var page = $("#page ul li.active a span").html();
        var offset = (page-1)*limit;

        // this.batchDownQrcodeUrl = "/storemanage/store/codeBatchDown?offset=" +offset+ "&limit=" +limit;
        this.batchDownQrcodeUrl = "http://demo1015.sit.ffan.com/storemanage/store/codeBatchDown?offset=" +offset+ "&limit=" +limit;
    }

    // 导出Excel
    exportExcel() {
        var limit = $("#page .active span").html();
        var page;

        if ($("#page ul li.active a span")==null) {
            page = 1;
        }else {
            page = $("#page ul li.active a span").html();
        }

        var offset = (page-1)*limit;

        // this.exportExcelUrl = "/storemanage/store/excel?offset=" +offset+ "&limit=" +limit;
        this.exportExcelUrl = "http://demo1015.sit.ffan.com/storemanage/store/excel?offset=" +offset+ "&limit=" +limit;
    }
}<commit_msg>update: list<commit_after>/**
 * (description)
 *
 * @author yourname
 */

export default class ListController {
    constructor($q, storeSvc, $scope, $http, NgTableParams, $state, templateSvc, storeManageSvc, Api) {
        "ngInject";
        this.$state = $state;
        this.storeSvc = storeSvc;
        this.q = $q;
        this.NgTableParams = NgTableParams;
        this.d = {};
        this.templateSvc = templateSvc;
        this.storeManageSvc = storeManageSvc;
        this.api = Api;
        this.init();
        this.filter = {
            limit: 10,
            offset: 0
        };
    }

    // 格式化后的数据
    getSearchFormData() {
        let filter = this.filter;
        return filter;
    }

    init() {
        var self = this;
        var _this = this;
        var filter = this.filter;

        this.tableParams = new this.NgTableParams({
            page: 1,
            count: 10
        }, {
            getData: function (params) {
                self.loading = true;
                let formData = self.getSearchFormData(filter);

                formData.page = params.url().page;
                formData.offset = (params.url().page-1) * params.url().count;

                self.loadPromise = self.storeManageSvc.getStoreList(formData);
                return self.loadPromise
                    .then(result => {
                        self.loading = false;
                        if (result.datas) {
                            _this.d = {
                                totalCount: result.totalCount
                            };
                            params.total(result.totalCount);
                            return result.datas;
                        }
                    });
            }
        })
    }

    // 二维码
    showQrcode(storeId) {
        let self = this;
        this.api.get('/storemanage/store/code', {storeId: storeId})
            .then(result => {
                console.log(result);
                this.qrCodeUrl = result.qrCodeImgUrl;
            });
        this.singleStoreId = storeId;

        this.isQrcodeShow = true;
    }

    hideQrcode() {
        this.isQrcodeShow = false;
    }

    // 二维码打印
    printQrcode() {
        $(".ng-isolate-scope").hide();
        var imgHtml = '';
        $("body").append(imgHtml);

        if ((window.print())==true) {
            $("#printImg").remove();
            $(".ng-isolate-scope").show();
        }else {
            $("#printImg").remove();
            $(".ng-isolate-scope").show();
        }
    }

    goClaimList(){
        this.$state.go('storeMclaimlist');
    }

    search() {
        this.storeSvc.getStoreInfoList();
    }

    detail(id) {
        this.$state.go('storeMdetail', {id: id});
    }

    edit(id) {
        this.$state.go('storeMedit', {id: id});
    }

    getstaffpageadd() {
        this.staffnewSvc.getstaffpage()
    }

    goStaff(storeid) {
        this.$state.go('stafflist', {storeid: storeid});
    }

    // 导出 参数
    getDownloadParams() {
        var limit = $("#page .active span").html();
        var page = $("#page ul li.active a span").html();

        if (page == undefined) {
            page = 1;
        }

        limit = parseInt(limit);
        page = parseInt(page);
        var offset = (page-1)*limit;

        var params = {
            limit: limit,
            offset: offset
        }

        return params;
    }

    // 批量导出二维码
    batchDownQrcode() {
        var params = this.getDownloadParams();
        this.batchDownQrcodeUrl = "/storemanage/store/codeBatchDown?offset=" +params.offset+ "&limit=" +params.limit;
    }

    // 导出Excel
    exportExcel() {
        var params = this.getDownloadParams();
        this.exportExcelUrl = "/storemanage/store/excel?offset=" +params.offset+ "&limit=" +params.limit;
    }
}<|endoftext|>


<commit_before>(function() {
  'use strict';

  var formElm = document.getElementById('signup-form'),
  dialogElm = document.getElementById('signup-dialog'),
  optionsErrorElm = dialogElm.getElementsByClassName('options')[0].querySelector('p:last-child'),
  characterMessageElm = formElm.getElementsByClassName('password-req')[0],
  message;

  function customErrorMessage(elm, message) {
    if(message) {
      elm.innerHTML = message;
    }
  }

  function showOptionsError(elm, message){
    if(!document.body.classList.contains('error-state')) {
      document.body.classList.add('error-state');
    }
    if( !elm.classList.contains('error-show') ) {
      elm.classList.add('error-show');
      elm.innerHTML = message;
    }
  }

  var signupForm = new Oform({
    selector: '#signup-form',
    customValidation: {
      password1: function(elm) {
        var validationPassed = w.optly.mrkt.utils.checkComplexPassword(elm.value);
        var errorElm = formElm.getElementsByClassName('password1-related')[0];

        if(!validationPassed) {
          if(elm.value.length === 0) {
            message = 'This field is required';
          } else {
            message = 'Password is Invalid';
          }
          characterMessageElm.classList.add('error-show');
        } else if (validationPassed && characterMessageElm.classList.contains('error-show')) {
          characterMessageElm.className = characterMessageElm.classList.remove('error-show');
        }

        customErrorMessage(errorElm, message);

        return validationPassed;
      },
      password2: function(elm) {
        var password1 = formElm.querySelector('[name="password1"]');
        var errorElm = formElm.getElementsByClassName('password2-related')[0];

        if(elm.value.length === 0) {
          message = 'This field is required';
        } else if (elm.value !== password1.value) {
          message = 'Please enter the same value again';
        }

        customErrorMessage(errorElm, message);

        return elm.value === password1.value && w.optly.mrkt.utils.checkComplexPassword(password1.value);
      }
    },
    middleware: function(xhrObj, data) {
      var urlParams = w.optly.mrkt.utils.deparam( window.location.search );

      if (urlParams.signup_platform) {
        data += '&platform=' + urlParams.signup_platform;
      }

      return data;
    }
  });

  signupForm.on('before', function() {
    //set the hidden input value
    formElm.querySelector('[name="hidden"]').value = 'touched';
    return true;
  });

  signupForm.on('validationerror', function(elm){

    w.optly.mrkt.Oform.validationError(elm);

  });

  signupForm.on('load', function(e){
    var resp = JSON.parse(e.target.responseText);

    if(e.target.status !== 200) {
      showOptionsError(optionsErrorElm, resp.error);
      return;
    }

    var source = w.optly.mrkt.source;
    w.analytics.identify(resp.email,{
      email: resp.email,
      name: resp.first_name + ' ' + resp.last_name,
      phone: resp.phone,
      token: resp.csrf_token,
      utm_Campaign__c: source.utm.campaign,
      utm_Content__c: source.utm.content,
      utm_Medium__c: source.utm.medium,
      utm_Source__c: source.utm.source,
      utm_Keyword__c: source.utm.keyword,
      otm_Campaign__c: source.otm.campaign,
      otm_Content__c: source.otm.content,
      otm_Medium__c: source.otm.medium,
      GCLID__c: source.gclid,
      otm_Source__c: source.otm.source,
      otm_Keyword__c: source.otm.keyword,
      Signup_Platform__c: source.signupPlatform
    }, {
      integrations: {
        Marketo: true
      }
    });
    w.analytics.track('account created', {
      category: 'account',
      label: w.location.pathname
    }, {
      Marketo: true
    });

    window.optly.mrkt.modal.close('signup');
    window.optly_q = new window.optly.mrkt.optly_QFactory(resp);
    window.optly_q.push([window.optly.mrkt.showUtilityNav, 'acctData']);

  });

  signupForm.on('done', w.optly.mrkt.Oform.done);

}());

<commit_msg>remove anonymous function from validation error handler and remover url parsing for platform<commit_after>(function() {
  'use strict';

  var formElm = document.getElementById('signup-form'),
  dialogElm = document.getElementById('signup-dialog'),
  optionsErrorElm = dialogElm.getElementsByClassName('options')[0].querySelector('p:last-child'),
  characterMessageElm = formElm.getElementsByClassName('password-req')[0],
  message;

  function customErrorMessage(elm, message) {
    if(message) {
      elm.innerHTML = message;
    }
  }

  function showOptionsError(elm, message){
    if(!document.body.classList.contains('error-state')) {
      document.body.classList.add('error-state');
    }
    if( !elm.classList.contains('error-show') ) {
      elm.classList.add('error-show');
      elm.innerHTML = message;
    }
  }

  var signupForm = new Oform({
    selector: '#signup-form',
    customValidation: {
      password1: function(elm) {
        var validationPassed = w.optly.mrkt.utils.checkComplexPassword(elm.value);
        var errorElm = formElm.getElementsByClassName('password1-related')[0];

        if(!validationPassed) {
          if(elm.value.length === 0) {
            message = 'This field is required';
          } else {
            message = 'Password is Invalid';
          }
          characterMessageElm.classList.add('error-show');
        } else if (validationPassed && characterMessageElm.classList.contains('error-show')) {
          characterMessageElm.className = characterMessageElm.classList.remove('error-show');
        }

        customErrorMessage(errorElm, message);

        return validationPassed;
      },
      password2: function(elm) {
        var password1 = formElm.querySelector('[name="password1"]');
        var errorElm = formElm.getElementsByClassName('password2-related')[0];

        if(elm.value.length === 0) {
          message = 'This field is required';
        } else if (elm.value !== password1.value) {
          message = 'Please enter the same value again';
        }

        customErrorMessage(errorElm, message);

        return elm.value === password1.value && w.optly.mrkt.utils.checkComplexPassword(password1.value);
      }
    }
  });

  signupForm.on('before', function() {
    //set the hidden input value
    formElm.querySelector('[name="hidden"]').value = 'touched';
    return true;
  });

  signupForm.on('validationerror', w.optly.mrkt.Oform.validationError);

  signupForm.on('load', function(e){
    var resp = JSON.parse(e.target.responseText);

    if(e.target.status !== 200) {
      showOptionsError(optionsErrorElm, resp.error);
      return;
    }

    var source = w.optly.mrkt.source;
    w.analytics.identify(resp.email,{
      email: resp.email,
      name: resp.first_name + ' ' + resp.last_name,
      phone: resp.phone,
      token: resp.csrf_token,
      utm_Campaign__c: source.utm.campaign,
      utm_Content__c: source.utm.content,
      utm_Medium__c: source.utm.medium,
      utm_Source__c: source.utm.source,
      utm_Keyword__c: source.utm.keyword,
      otm_Campaign__c: source.otm.campaign,
      otm_Content__c: source.otm.content,
      otm_Medium__c: source.otm.medium,
      GCLID__c: source.gclid,
      otm_Source__c: source.otm.source,
      otm_Keyword__c: source.otm.keyword,
      Signup_Platform__c: source.signupPlatform
    }, {
      integrations: {
        Marketo: true
      }
    });
    w.analytics.track('account created', {
      category: 'account',
      label: w.location.pathname
    }, {
      Marketo: true
    });

    window.optly.mrkt.modal.close('signup');
    window.optly_q = new window.optly.mrkt.optly_QFactory(resp);
    window.optly_q.push([window.optly.mrkt.showUtilityNav, 'acctData']);

  });

  signupForm.on('done', w.optly.mrkt.Oform.done);

}());

<|endoftext|>


<commit_before>hqDefine("domain/js/add_form_repeater", function() {
    $(function() {
        var handleSuccess = function(resp) {
            /*
             * Handles a successful attempt to test the link. Note, just gets run when HQ returns
             * successful not if the link being tested returns successful
             */
            var jsonResp = JSON.parse(resp),
                message;
            $testResult.removeClass("hide text-danger text-success");
            $testLinkButton.enableButton();

            if (jsonResp.status) {
                message = jsonResp.status + ": " + jsonResp.response;
            } else {
                message = jsonResp.response;
            }

            if (jsonResp.success) {
                $testResult.addClass("text-success");
                $testResult.text(gettext('Success! Response is: ') + message);
            } else {
                $testResult.addClass("text-danger");
                $testResult.text(gettext('Failed! Response is: ') + message);
            }
        };

        var handleFailure = function(resp) {
            /*
             * Handles an HQ failure to test the URL
             */
            $testLinkButton.enableButton();
            $testResult
                .removeClass("hide text-success")
                .addClass("text-danger");
            $testResult.text(gettext('HQ was unable to make the request: ') + resp.statusText);
        };

        var $testLinkButton = $('#test-forward-link'),
            $testResult = $('#test-forward-result');

        $testLinkButton.click(function () {
            var data = {
                url: $('#id_url').val(),
                format: $('#id_format').val(),
                repeater_type: hqImport("hqwebapp/js/initial_page_data").get("repeater_type"),
                auth_type: $('#id_auth_type').val(),
                username: $('#id_username').val(),
                password: $('#id_password').val(),
            };
            $testLinkButton.disableButton();

            $.post({
                url: hqImport("hqwebapp/js/initial_page_data").reverse("test_repeater"),
                data: data,
                success: handleSuccess,
                error: handleFailure,
            });
        });
        $('#id_url').change(function () {
            if ($(this).val()) {
                $testLinkButton.removeClass('disabled');
            } else {
                $testLinkButton.addClass('disabled');
            }
        });
    });
});
<commit_msg>minimal diff<commit_after>hqDefine("domain/js/add_form_repeater", function() {
    $(function() {
        var $testLinkButton = $('#test-forward-link'),
            $testResult = $('#test-forward-result');

        var handleSuccess = function(resp) {
            /*
             * Handles a successful attempt to test the link. Note, just gets run when HQ returns
             * successful not if the link being tested returns successful
             */
            var jsonResp = JSON.parse(resp),
                message;
            $testResult.removeClass("hide text-danger text-success");
            $testLinkButton.enableButton();

            if (jsonResp.status) {
                message = jsonResp.status + ": " + jsonResp.response;
            } else {
                message = jsonResp.response;
            }

            if (jsonResp.success) {
                $testResult.addClass("text-success");
                $testResult.text(gettext('Success! Response is: ') + message);
            } else {
                $testResult.addClass("text-danger");
                $testResult.text(gettext('Failed! Response is: ') + message);
            }
        };

        var handleFailure = function(resp) {
            /*
             * Handles an HQ failure to test the URL
             */
            $testLinkButton.enableButton();
            $testResult
                .removeClass("hide text-success")
                .addClass("text-danger");
            $testResult.text(gettext('HQ was unable to make the request: ') + resp.statusText);
        };

        $testLinkButton.click(function () {
            var data = {
                url: $('#id_url').val(),
                format: $('#id_format').val(),
                repeater_type: hqImport("hqwebapp/js/initial_page_data").get("repeater_type"),
                auth_type: $('#id_auth_type').val(),
                username: $('#id_username').val(),
                password: $('#id_password').val(),
            };
            $testLinkButton.disableButton();

            $.post({
                url: hqImport("hqwebapp/js/initial_page_data").reverse("test_repeater"),
                data: data,
                success: handleSuccess,
                error: handleFailure,
            });
        });
        $('#id_url').change(function () {
            if ($(this).val()) {
                $testLinkButton.removeClass('disabled');
            } else {
                $testLinkButton.addClass('disabled');
            }
        });
    });
});
<|endoftext|>


<commit_before>/*
	This functionality has been duplicated using the initial implementation from https://github.com/nglasl/silverstripe-apiwesome
	@author Nathan Glasl <nathan@silverstripe.com.au>
 */

;(function($) {
	$(function() {

		// Determine whether the test URL button display and functionality should be enabled.

		function enable(input) {

			var URL = input ? input.val() : $('div.link-mapping-test.admin input.url').val();
			var button = $('div.link-mapping-test.admin span.test');
			if(URL.length > 0) {
				button.fadeTo(250, 1, function() {
					button.removeClass('disabled');
				});
			}
			else {
				button.fadeTo(250, 0.4, function() {
					button.addClass('disabled');
				});
			}
		};

		// Retrieve the link mapping chain for a given URL.

		function retrieveLinkMappingChain(map) {

			$.getJSON('admin/link-mappings/LinkMapping/getLinkMappingChain',
				{
					map: map
				},
				function(JSON) {

					var output = '';
					if(JSON) {

						// Iterate over each link mapping and collate any important data.

						$.each(JSON, function(index, object) {
							output += "
";
								if(object['ResponseCode'] !== 404) {
									output += '
' + object['Counter'] + '
';
									output += '
Link Type ' + object['LinkType'] + '
';
									output += '
Mapped Link ' + object['MappedLink'] + '
';
									output += '
Redirect Link ' + object['RedirectLink'] + '
';
									output += '
Response Code ' + object['ResponseCode'] + '
';
									output += '
Priority ' + object['Priority'] + '
';
								}
								else {
									output += '
Maximum
';
									output += '
Response Code ' + object['ResponseCode'] + '
';
								}
							output += '
';
						});
					}
					else {
						output += "
";
							output += '
No Matches
';
						output += '
';
					}

					// Display these to the user.

					$('div.link-mapping-test.admin div.results').html(output);
				});
		}

		// Bind the mouse events dynamically.

		$.entwine('ss', function($) {

			// Trigger an interface update on key press.

			$('div.link-mapping-test.admin input.url').entwine({
				onchange: function() {

					enable($(this));
				}
			});

			// Trigger an interface update and handle any preview request.

			$('div.link-mapping-test.admin span.test').entwine({
				onmouseenter: function() {

					enable();
				},
				onclick: function() {

					if(!$(this).hasClass('disabled')) {

						// Retrieve the link mapping chain using the current test URL and display this to the user.

						retrieveLinkMappingChain($('div.link-mapping-test.admin input.url').val());
					}
				}
			});
		});

	});
})(jQuery);
<commit_msg>Minor updates regarding naming convention.<commit_after>/*
	This functionality has been duplicated using the initial implementation from https://github.com/nglasl/silverstripe-apiwesome
	@author Nathan Glasl <nathan@silverstripe.com.au>
 */

;(function($) {
	$(function() {

		// Determine whether the test URL button display and functionality should be enabled.

		function enable(input) {

			var URL = input ? input.val() : $('div.link-mapping-test.admin input.url').val();
			var button = $('div.link-mapping-test.admin span.test');
			if(URL.length > 0) {
				button.fadeTo(250, 1, function() {
					button.removeClass('disabled');
				});
			}
			else {
				button.fadeTo(250, 0.4, function() {
					button.addClass('disabled');
				});
			}
		};

		// Retrieve the link mapping chain for a given URL.

		function retrieveLinkMappingChain(map) {

			$.getJSON('admin/misdirection/LinkMapping/getLinkMappingChain',
				{
					map: map
				},
				function(JSON) {

					var output = '';
					if(JSON) {

						// Iterate over each link mapping and collate any important data.

						$.each(JSON, function(index, object) {
							output += "
";
								if(object['ResponseCode'] !== 404) {
									output += '
' + object['Counter'] + '
';
									output += '
Link Type ' + object['LinkType'] + '
';
									output += '
Mapped Link ' + object['MappedLink'] + '
';
									output += '
Redirect Link ' + object['RedirectLink'] + '
';
									output += '
Response Code ' + object['ResponseCode'] + '
';
									output += '
Priority ' + object['Priority'] + '
';
								}
								else {
									output += '
Maximum
';
									output += '
Response Code ' + object['ResponseCode'] + '
';
								}
							output += '
';
						});
					}
					else {
						output += "
";
							output += '
No Matches
';
						output += '
';
					}

					// Display these to the user.

					$('div.link-mapping-test.admin div.results').html(output);
				});
		}

		// Bind the mouse events dynamically.

		$.entwine('ss', function($) {

			// Trigger an interface update on key press.

			$('div.link-mapping-test.admin input.url').entwine({
				onchange: function() {

					enable($(this));
				}
			});

			// Trigger an interface update and handle any preview request.

			$('div.link-mapping-test.admin span.test').entwine({
				onmouseenter: function() {

					enable();
				},
				onclick: function() {

					if(!$(this).hasClass('disabled')) {

						// Retrieve the link mapping chain using the current test URL and display this to the user.

						retrieveLinkMappingChain($('div.link-mapping-test.admin input.url').val());
					}
				}
			});
		});

	});
})(jQuery);
<|endoftext|>


<commit_before>var tz = require('timezone');
var calcMealCOB = require('oref0/lib/determine-basal/cob-autosens');
var basal = require('oref0/lib/profile/basal');
var get_iob = require('oref0/lib/iob');
var isf = require('../profile/isf');

function diaCarbs(opts) {
    var treatments = opts.treatments;
    treatments.sort(function (a, b) {
        //console.error(a);
        var aDate = new Date(tz(a.timestamp));
        var bDate = new Date(tz(b.timestamp));
        return bDate.getTime() - aDate.getTime();
    });
    var profile_data = opts.profile;
    if (typeof(opts.glucose) !== 'undefined') {
        //var glucose_data = opts.glucose;
        var glucose_data = opts.glucose.map(function prepGlucose (obj) {
            //Support the NS sgv field to avoid having to convert in a custom way
            obj.glucose = obj.glucose || obj.sgv;
            return obj;
        });
    }
    if (typeof(opts.prepped_glucose) !== 'undefined') {
        var prepped_glucose_data = opts.prepped_glucose;
    }
    var boluses = 0;
    var carbDelay = 20 * 60 * 1000;
    var maxCarbs = 0;
    //console.error(treatments);
    if (!treatments) return {};

    //console.error(glucose_data);
    var iob_inputs = {
        profile: profile_data
    ,   history: opts.pumphistory
    };
    var COB_inputs = {
        glucose_data: glucose_data
    ,   iob_inputs: iob_inputs
    ,   basalprofile: opts.basalprofile
    };
    var mealCOB = 0;
    var csf_glucose_data = [];
    var isf_glucose_data = [];
    var basal_glucose_data = [];

    var bucketed_data = [];
    bucketed_data[0] = glucose_data[0];
    j=0;
    for (var i=1; i < glucose_data.length; ++i) {
        var bgTime;
        var lastbgTime;
        if (glucose_data[i].display_time) {
            bgTime = new Date(glucose_data[i].display_time.replace('T', ' '));
        } else if (glucose_data[i].dateString) {
            bgTime = new Date(glucose_data[i].dateString);
        } else { console.error("Could not determine BG time"); }
        if (glucose_data[i-1].display_time) {
            lastbgTime = new Date(glucose_data[i-1].display_time.replace('T', ' '));
        } else if (glucose_data[i-1].dateString) {
            lastbgTime = new Date(glucose_data[i-1].dateString);
        } else { console.error("Could not determine last BG time"); }
        if (glucose_data[i].glucose < 39 || glucose_data[i-1].glucose < 39) {
            continue;
        }
        var elapsed_minutes = (bgTime - lastbgTime)/(60*1000);
        if(Math.abs(elapsed_minutes) > 2) {
            j++;
            bucketed_data[j]=glucose_data[i];
            bucketed_data[j].date = bgTime.getTime();
        } else {
            bucketed_data[j].glucose = (bucketed_data[j].glucose + glucose_data[i].glucose)/2;
        }
    }
    //console.error(bucketed_data);
    //console.error(bucketed_data[bucketed_data.length-1]);
    // go through the treatments and remove any that are older than the oldest glucose value
    //console.error(treatments);
    for (var i=treatments.length-1; i>0; --i) {
        var treatment = treatments[i];
        var treatmentDate = new Date(tz(treatment.timestamp));
        var treatmentTime = treatmentDate.getTime();
        var glucose_datum = bucketed_data[bucketed_data.length-1];
        //console.error(glucose_datum);
        var bgDate = new Date(glucose_datum.date);
        var bgTime = bgDate.getTime();
        if ( treatmentTime < bgTime ) {
            treatments.splice(i,1);
        }
    }
    console.error(treatments);
    absorbing = 0;
    mealCOB = 0;
    mealCarbs = 0;
    var type="";
    for (var i=bucketed_data.length-5; i > 0; --i) {
        var glucose_datum = bucketed_data[i];
        //console.error(glucose_datum);
        var bgDate = new Date(glucose_datum.date);
        var bgTime = bgDate.getTime();
        // As we're processing each data point, go through the treatment.carbs and see if any of them are older than
        // the current BG data point.  If so, add those carbs to COB.
        var treatment = treatments[treatments.length-1];
        var treatmentDate = new Date(tz(treatment.timestamp));
        var treatmentTime = treatmentDate.getTime();
        //console.error(treatmentDate);
        if ( treatmentTime < bgTime ) {
            if (treatment.carbs >= 1) {
                mealCOB += parseFloat(treatment.carbs);
                mealCarbs += parseFloat(treatment.carbs);
            }
            treatments.pop();
        }

        var bg;
        var avgDelta;
        var delta;
        // TODO: re-implement interpolation to avoid issues here with gaps
        // calculate avgDelta as last 4 datapoints to better catch more rises after COB hits zero
        if (typeof(bucketed_data[i].glucose) != 'undefined') {
            //console.error(bucketed_data[i]);
            bg = bucketed_data[i].glucose;
            if ( bg < 40 || bucketed_data[i+4].glucose < 40) {
                process.stderr.write("!");
                continue;
            }
            avgDelta = (bg - bucketed_data[i+4].glucose)/4;
            delta = (bg - bucketed_data[i+1].glucose);
        } else { console.error("Could not find glucose data"); }

        avgDelta = avgDelta.toFixed(2);
        glucose_datum.avgDelta = avgDelta;

        var sens = isf.isfLookup(iob_inputs.profile.isfProfile,bgDate);
        iob_inputs.clock=bgDate.toISOString();
        currentBasal = basal.basalLookup(opts.basalprofile, bgDate);
        iob_inputs.profile.current_basal = currentBasal;
        basalBgi = Math.round(( currentBasal * sens / 60 * 5 )*100)/100; // U/hr * mg/dL/U * 1 hr / 60 minutes * 5 = mg/dL/5m
        //console.log(JSON.stringify(iob_inputs.profile));
        var iob = get_iob(iob_inputs)[0];
        //console.error(JSON.stringify(iob));

        var bgi = Math.round(( -iob.activity * sens * 5 )*100)/100;
        glucose_datum.bgi = bgi;
        deviation = avgDelta-bgi;
        deviation = deviation.toFixed(2);
        glucose_datum.deviation = deviation;

        // Then, calculate carb absorption for that 5m interval using the deviation.
        if ( mealCOB > 0 ) {
            var profile = profile_data;
            ci = Math.max(deviation, profile.min_5m_carbimpact);
            absorbed = ci * profile.carb_ratio / sens;
            mealCOB = Math.max(0, mealCOB-absorbed);
        }
        // Store the COB, and use it as the starting point for the next data point.

        // If mealCOB is zero but all deviations since hitting COB=0 are positive, assign those data points to csf_glucose_data
        // Once deviations go negative for at least one data point after COB=0, we can use the rest of the data to tune ISF or basals
        if (mealCOB > 0 || absorbing || mealCarbs > 0) {
            if (deviation > 0) {
                absorbing = 1;
            } else {
                absorbing = 0;
            }
            if ( ! absorbing && ! mealCOB ) {
                mealCarbs = 0;
            }
            // check previous "type" value, and if it wasn't csf, set a mealAbsorption start flag
            //console.error(type);
            if ( type != "csf" ) {
                glucose_datum.mealAbsorption = "start";
                console.error(glucose_datum.mealAbsorption);
            }
            type="csf";
            csf_glucose_data.push(glucose_datum);
        } else {
            // check previous "type" value, and if it was csf, set a mealAbsorption end flag
            if ( type === "csf" ) {
                csf_glucose_data[csf_glucose_data.length-1].mealAbsorption = "end";
                console.error(csf_glucose_data[csf_glucose_data.length-1].mealAbsorption);
            }

            // Go through the remaining time periods and divide them into periods where scheduled basal insulin activity dominates. This would be determined by calculating the BG impact of scheduled basal insulin (for example 1U/hr * 48 mg/dL/U ISF = 48 mg/dL/hr = 5 mg/dL/5m), and comparing that to BGI from bolus and net basal insulin activity.
            // When BGI is positive (insulin activity is negative), we want to use that data to tune basals
            // When BGI is smaller than about 1/4 of basalBGI, we want to use that data to tune basals
            // When BGI is negative and more than about 1/4 of basalBGI, we can use that data to tune ISF,
            // unless avgDelta is positive: then that's some sort of unexplained rise we don't want to use for ISF or basals
            if (basalBgi > -4 * bgi) {
                type="basal";
                basal_glucose_data.push(glucose_datum);
            } else {
                if (avgDelta > 0 ) {
                    type="unknown"
                } else {
                    type="isf";
                    isf_glucose_data.push(glucose_datum);
                }
            }
        }
        console.error(absorbing.toString(),"mealCOB:",mealCOB.toFixed(1),"mealCarbs:",mealCarbs,"basalBgi:",basalBgi.toFixed(1),"bgi:",bgi.toFixed(1),"at",bgDate,"dev:",deviation,"avgDelta:",avgDelta,type);
    }

    return {
        csf_glucose_data: csf_glucose_data,
        isf_glucose_data: isf_glucose_data,
        basal_glucose_data: basal_glucose_data
    };
}

exports = module.exports = diaCarbs;

<commit_msg>add mealCarbs to glucose_data<commit_after>var tz = require('timezone');
var calcMealCOB = require('oref0/lib/determine-basal/cob-autosens');
var basal = require('oref0/lib/profile/basal');
var get_iob = require('oref0/lib/iob');
var isf = require('../profile/isf');

function diaCarbs(opts) {
    var treatments = opts.treatments;
    treatments.sort(function (a, b) {
        //console.error(a);
        var aDate = new Date(tz(a.timestamp));
        var bDate = new Date(tz(b.timestamp));
        return bDate.getTime() - aDate.getTime();
    });
    var profile_data = opts.profile;
    if (typeof(opts.glucose) !== 'undefined') {
        //var glucose_data = opts.glucose;
        var glucose_data = opts.glucose.map(function prepGlucose (obj) {
            //Support the NS sgv field to avoid having to convert in a custom way
            obj.glucose = obj.glucose || obj.sgv;
            return obj;
        });
    }
    if (typeof(opts.prepped_glucose) !== 'undefined') {
        var prepped_glucose_data = opts.prepped_glucose;
    }
    var boluses = 0;
    var carbDelay = 20 * 60 * 1000;
    var maxCarbs = 0;
    //console.error(treatments);
    if (!treatments) return {};

    //console.error(glucose_data);
    var iob_inputs = {
        profile: profile_data
    ,   history: opts.pumphistory
    };
    var COB_inputs = {
        glucose_data: glucose_data
    ,   iob_inputs: iob_inputs
    ,   basalprofile: opts.basalprofile
    };
    var mealCOB = 0;
    var csf_glucose_data = [];
    var isf_glucose_data = [];
    var basal_glucose_data = [];

    var bucketed_data = [];
    bucketed_data[0] = glucose_data[0];
    j=0;
    for (var i=1; i < glucose_data.length; ++i) {
        var bgTime;
        var lastbgTime;
        if (glucose_data[i].display_time) {
            bgTime = new Date(glucose_data[i].display_time.replace('T', ' '));
        } else if (glucose_data[i].dateString) {
            bgTime = new Date(glucose_data[i].dateString);
        } else { console.error("Could not determine BG time"); }
        if (glucose_data[i-1].display_time) {
            lastbgTime = new Date(glucose_data[i-1].display_time.replace('T', ' '));
        } else if (glucose_data[i-1].dateString) {
            lastbgTime = new Date(glucose_data[i-1].dateString);
        } else { console.error("Could not determine last BG time"); }
        if (glucose_data[i].glucose < 39 || glucose_data[i-1].glucose < 39) {
            continue;
        }
        var elapsed_minutes = (bgTime - lastbgTime)/(60*1000);
        if(Math.abs(elapsed_minutes) > 2) {
            j++;
            bucketed_data[j]=glucose_data[i];
            bucketed_data[j].date = bgTime.getTime();
        } else {
            bucketed_data[j].glucose = (bucketed_data[j].glucose + glucose_data[i].glucose)/2;
        }
    }
    //console.error(bucketed_data);
    //console.error(bucketed_data[bucketed_data.length-1]);
    // go through the treatments and remove any that are older than the oldest glucose value
    //console.error(treatments);
    for (var i=treatments.length-1; i>0; --i) {
        var treatment = treatments[i];
        var treatmentDate = new Date(tz(treatment.timestamp));
        var treatmentTime = treatmentDate.getTime();
        var glucose_datum = bucketed_data[bucketed_data.length-1];
        //console.error(glucose_datum);
        var bgDate = new Date(glucose_datum.date);
        var bgTime = bgDate.getTime();
        if ( treatmentTime < bgTime ) {
            treatments.splice(i,1);
        }
    }
    //console.error(treatments);
    absorbing = 0;
    mealCOB = 0;
    mealCarbs = 0;
    var type="";
    for (var i=bucketed_data.length-5; i > 0; --i) {
        var glucose_datum = bucketed_data[i];
        //console.error(glucose_datum);
        var bgDate = new Date(glucose_datum.date);
        var bgTime = bgDate.getTime();
        // As we're processing each data point, go through the treatment.carbs and see if any of them are older than
        // the current BG data point.  If so, add those carbs to COB.
        var treatment = treatments[treatments.length-1];
        var treatmentDate = new Date(tz(treatment.timestamp));
        var treatmentTime = treatmentDate.getTime();
        //console.error(treatmentDate);
        if ( treatmentTime < bgTime ) {
            if (treatment.carbs >= 1) {
                mealCOB += parseFloat(treatment.carbs);
                mealCarbs += parseFloat(treatment.carbs);
            }
            treatments.pop();
        }

        var bg;
        var avgDelta;
        var delta;
        // TODO: re-implement interpolation to avoid issues here with gaps
        // calculate avgDelta as last 4 datapoints to better catch more rises after COB hits zero
        if (typeof(bucketed_data[i].glucose) != 'undefined') {
            //console.error(bucketed_data[i]);
            bg = bucketed_data[i].glucose;
            if ( bg < 40 || bucketed_data[i+4].glucose < 40) {
                process.stderr.write("!");
                continue;
            }
            avgDelta = (bg - bucketed_data[i+4].glucose)/4;
            delta = (bg - bucketed_data[i+1].glucose);
        } else { console.error("Could not find glucose data"); }

        avgDelta = avgDelta.toFixed(2);
        glucose_datum.avgDelta = avgDelta;

        var sens = isf.isfLookup(iob_inputs.profile.isfProfile,bgDate);
        iob_inputs.clock=bgDate.toISOString();
        currentBasal = basal.basalLookup(opts.basalprofile, bgDate);
        iob_inputs.profile.current_basal = currentBasal;
        basalBgi = Math.round(( currentBasal * sens / 60 * 5 )*100)/100; // U/hr * mg/dL/U * 1 hr / 60 minutes * 5 = mg/dL/5m
        //console.log(JSON.stringify(iob_inputs.profile));
        var iob = get_iob(iob_inputs)[0];
        //console.error(JSON.stringify(iob));

        var bgi = Math.round(( -iob.activity * sens * 5 )*100)/100;
        glucose_datum.bgi = bgi;
        deviation = avgDelta-bgi;
        deviation = deviation.toFixed(2);
        glucose_datum.deviation = deviation;

        // Then, calculate carb absorption for that 5m interval using the deviation.
        if ( mealCOB > 0 ) {
            var profile = profile_data;
            ci = Math.max(deviation, profile.min_5m_carbimpact);
            absorbed = ci * profile.carb_ratio / sens;
            mealCOB = Math.max(0, mealCOB-absorbed);
        }
        // Store the COB, and use it as the starting point for the next data point.

        // If mealCOB is zero but all deviations since hitting COB=0 are positive, assign those data points to csf_glucose_data
        // Once deviations go negative for at least one data point after COB=0, we can use the rest of the data to tune ISF or basals
        if (mealCOB > 0 || absorbing || mealCarbs > 0) {
            if (deviation > 0) {
                absorbing = 1;
            } else {
                absorbing = 0;
            }
            if ( ! absorbing && ! mealCOB ) {
                mealCarbs = 0;
            }
            // check previous "type" value, and if it wasn't csf, set a mealAbsorption start flag
            //console.error(type);
            if ( type != "csf" ) {
                glucose_datum.mealAbsorption = "start";
                console.error(glucose_datum.mealAbsorption);
            }
            type="csf";
            glucose_datum.mealCarbs = mealCarbs;
            //if (i == 0) { glucose_datum.mealAbsorption = "end"; }
            csf_glucose_data.push(glucose_datum);
        } else {
            // check previous "type" value, and if it was csf, set a mealAbsorption end flag
            if ( type === "csf" ) {
                csf_glucose_data[csf_glucose_data.length-1].mealAbsorption = "end";
                console.error(csf_glucose_data[csf_glucose_data.length-1].mealAbsorption);
            }

            // Go through the remaining time periods and divide them into periods where scheduled basal insulin activity dominates. This would be determined by calculating the BG impact of scheduled basal insulin (for example 1U/hr * 48 mg/dL/U ISF = 48 mg/dL/hr = 5 mg/dL/5m), and comparing that to BGI from bolus and net basal insulin activity.
            // When BGI is positive (insulin activity is negative), we want to use that data to tune basals
            // When BGI is smaller than about 1/4 of basalBGI, we want to use that data to tune basals
            // When BGI is negative and more than about 1/4 of basalBGI, we can use that data to tune ISF,
            // unless avgDelta is positive: then that's some sort of unexplained rise we don't want to use for ISF or basals
            if (basalBgi > -4 * bgi) {
                type="basal";
                basal_glucose_data.push(glucose_datum);
            } else {
                if (avgDelta > 0 ) {
                    type="unknown"
                } else {
                    type="isf";
                    isf_glucose_data.push(glucose_datum);
                }
            }
        }
        console.error(absorbing.toString(),"mealCOB:",mealCOB.toFixed(1),"mealCarbs:",mealCarbs,"basalBgi:",basalBgi.toFixed(1),"bgi:",bgi.toFixed(1),"at",bgDate,"dev:",deviation,"avgDelta:",avgDelta,type);
    }

    return {
        csf_glucose_data: csf_glucose_data,
        isf_glucose_data: isf_glucose_data,
        basal_glucose_data: basal_glucose_data
    };
}

exports = module.exports = diaCarbs;

<|endoftext|>


<commit_before>({
  name: "main",

  deps: [
    "common/controllers/services",
    "fco/controllers/overview",
    "hmrc/controllers/overview",
    "licensing/controllers/authorities",
    "licensing/controllers/licences",
    "licensing/controllers/overview",
    "licensing/controllers/per_authority",
    "licensing/controllers/per_licence",
    "licensing/controllers/preprocessors/module_touch_actions",
    "licensing/controllers/preprocessors/partial_experience_warning",
    "lpa/controllers/overview"
  ],

  out: "production.js",

  preserveLicenseComments: false,

  baseUrl: ".",

  paths: {
    jquery: 'jqueryloader',
    jqueryxdr: 'vendor/jquery.xdr',
    jquerymousewheel: 'vendor/jquery.mousewheel',
    lodash: 'vendor/lodash',
    backbone: 'vendor/backbone',
    css: 'vendor/require-css',
    modernizr: 'vendor/modernizr',
    moment: 'vendor/moment',
    tpl: 'vendor/tpl',
    d3: 'vendor/d3.v3'
  },

  shim: {
    backbone: {
      deps: ['lodash', 'jqueryxdr', 'jquerymousewheel'],
      exports: 'Backbone'
    },
    modernizr: {
      exports: 'Modernizr'
    },
    moment: {
      exports: 'Moment'
    },
    d3: {
      exports: 'd3'
    }
  },

  excludeShallow: [ 'd3' ]
})<commit_msg>fix build dependencies<commit_after>({
  name: "main",

  deps: [
    "common/controllers/services",
    "fco/controllers/overview",
    "hmrc/controllers/overview",
    "licensing/controllers/authorities",
    "licensing/controllers/licences",
    "licensing/controllers/overview",
    "licensing/controllers/per_authority",
    "licensing/controllers/per_licence",
    "common/controllers/preprocessors/module_touch_actions",
    "common/controllers/preprocessors/partial_experience_warning",
    "lpa/controllers/overview"
  ],

  out: "production.js",

  preserveLicenseComments: false,

  baseUrl: ".",

  paths: {
    jquery: 'jqueryloader',
    jqueryxdr: 'vendor/jquery.xdr',
    jquerymousewheel: 'vendor/jquery.mousewheel',
    lodash: 'vendor/lodash',
    backbone: 'vendor/backbone',
    css: 'vendor/require-css',
    modernizr: 'vendor/modernizr',
    moment: 'vendor/moment',
    tpl: 'vendor/tpl',
    d3: 'vendor/d3.v3'
  },

  shim: {
    backbone: {
      deps: ['lodash', 'jqueryxdr', 'jquerymousewheel'],
      exports: 'Backbone'
    },
    modernizr: {
      exports: 'Modernizr'
    },
    moment: {
      exports: 'Moment'
    },
    d3: {
      exports: 'd3'
    }
  },

  excludeShallow: [ 'd3' ]
})<|endoftext|>