<commit_before>import { shallowMount, mount, createLocalVue} from '@vue/test-utils'
import SumaClient from '@/components/SumaClient.vue'
import flushPromises from 'flush-promises'
import VueRouter from 'vue-router'

const localVue = createLocalVue()
localVue.use(VueRouter)
const router = new VueRouter()

let consoleSpy;
jest.mock('./__mocks__/axios');

describe('SumaClient.vue', () => {
  test('Testing Suma Client on Load', async () => {
    const wrapper = shallowMount(SumaClient, {localVue, router});
    await flushPromises();
    var data = wrapper.vm.$data;
    expect(data.currentinit).toBe('')
    expect(data.appVersion).toBe("1.1.0")
    expect(data.children).toEqual([])
    expect(data.initresults).toEqual([{"initiativeId":"2","initiativeTitle":"Sample Headcount Initiative"},{"initiativeId":"1","initiativeTitle":"Sample Reference Initiative"},{"initiativeId":"3","initiativeTitle":"test"}])
  })
  test('Update select options', async () => {
    const wrapper = mount(SumaClient, {localVue, router, attachToDocument: true});
    await flushPromises();

    var data = wrapper.vm.$data;

    //Select initiative from dropdown
    const select = wrapper.findAll('#initiativeDropdown > option');
    select.at(1).element.selected = true;
    wrapper.find('#initiativeDropdown').trigger('change');
    await flushPromises();
    await wrapper.vm.$nextTick()
    expect(data.currentinit).toBe("2")

    expect(data.children).toEqual([{"id":4,"title":"West Wing","children":[{"id":5,"title":"Quiet Reading Room"},{"id":6,"title":"IT Teaching Center"}]},{"id":7,"title":"East Wing","children":[{"id":8,"title":"Media Lab"},{"id":9,"title":"Learning Commons"}]},{"id":2,"title":"Ground Floor"},{"id":3,"title":"Lobby"}])
    expect(data.showcounts).toBe(false)

    //select location from items
    const locationselect = wrapper.findAll('.level-1 > li');
    await locationselect.at(0).trigger('click');
    expect(data.currentinit).toBe("2")
    expect(data.children).toEqual([{"id":4,"title":"West Wing","children":[{"id":5,"title":"Quiet Reading Room"},{"id":6,"title":"IT Teaching Center"}]},{"id":7,"title":"East Wing","children":[{"id":8,"title":"Media Lab"},{"id":9,"title":"Learning Commons"}]},{"id":2,"title":"Ground Floor"},{"id":3,"title":"Lobby"}])
    expect(data.location).toBe("")
    expect(data.showcounts).toBe(false)

    //select second location
    const locationselect2 = wrapper.findAll('.level-2 > li');
    await locationselect2.at(0).trigger('click');
    const time = Math.round(Date.now() / 1000);
    var initiativedata = data.counts[data.currentinit];
    expect(data.currentinit).toBe("2")
    expect(data.location).toBe(5)
    expect(data.showcounts).toBe(true)
    expect(data.activities).toEqual({})
    expect(initiativedata['counts'][0]['number']).toEqual(0)
    expect(initiativedata['counts'][0]['location']).toEqual(5)
    expect(initiativedata['counts'].length).toEqual(1)
    expect(initiativedata["startTime"]).toEqual(initiativedata['counts'][0]['timestamp'])
    expect(initiativedata["initiativeID"]).toEqual("2")
    expect(initiativedata['counts']).toEqual([{"activities": [], "location": 5, "number": 0, "timestamp": time}])
    expect(wrapper.find(".countButton").text()).toContain("Count (0)")

    //click on count button
    wrapper.find("form").trigger("submit.prevent")
    await wrapper.vm.$nextTick();
    expect(initiativedata['counts'].length).toEqual(1)
    expect(initiativedata['counts'][0]['number']).toEqual(1)
    expect(initiativedata['counts'][0]['location']).toEqual(5)
    expect(initiativedata['counts'].length).toEqual(1)
    expect(Object.keys(initiativedata)).toEqual(["counts","initiativeID","startTime","endTime"])
    expect(initiativedata["initiativeID"]).toEqual("2")
    expect(wrapper.find(".countButton").text()).toContain("Count (1)")

    //click on count button fourteen times
    for (var i=0; i<14; i++){
      wrapper.find("form").trigger("submit.prevent")
      await wrapper.vm.$nextTick();
    }
    expect(initiativedata['counts'][0]['number']).toEqual(1)
    expect(initiativedata['counts'].length).toEqual(15)
    expect(initiativedata['counts'][0]['location']).toEqual(5)
    expect(Object.keys(initiativedata)).toEqual(["counts","initiativeID","startTime","endTime"])
    expect(initiativedata["initiativeID"]).toEqual("2")
    expect(wrapper.find(".countButton").text()).toContain("Count (15)")

    //choose another location from location tree
    await locationselect2.at(1).trigger('click');
    expect(data.currentinit).toBe("2")
    expect(data.location).toBe(6)
    expect(data.showcounts).toBe(true)
    expect(data.activities).toEqual({})
    expect(initiativedata['counts'][15]['number']).toEqual(0)
    expect(initiativedata['counts'][15]['location']).toEqual(6)
    expect(initiativedata['counts'].length).toEqual(16)
    expect(initiativedata["startTime"]).toEqual(initiativedata['counts'][0]['timestamp'])
    expect(initiativedata["initiativeID"]).toEqual("2")
    expect(wrapper.find(".countButton").text()).toContain("Count (0)")

    //add to counts. Check location count and init count
    wrapper.find("form").trigger("submit.prevent")
    await wrapper.vm.$nextTick();
    expect(initiativedata['counts'].length).toEqual(16)
    expect(Object.keys(initiativedata)).toEqual(["counts","initiativeID","startTime","endTime"])
    expect(initiativedata["initiativeID"]).toEqual("2")
    expect(wrapper.find(".countButton").text()).toContain("Count (1)")

    //click on already clicked initiative (make sure not to add zero count)
    await locationselect2.at(1).trigger('click');
    expect(initiativedata['counts'].length).toEqual(16)

    //switch back to first location clicked
    await locationselect2.at(0).trigger('click');
    expect(initiativedata['counts'].length).toEqual(16)
    expect(Object.keys(initiativedata)).toEqual(["counts","initiativeID","startTime","endTime"])
    expect(initiativedata["initiativeID"]).toEqual("2")
    expect(wrapper.find(".countButton").text()).toContain("Count (15)")
    expect(initiativedata['counts'].length).toEqual(16)

    //change initiative
    select.at(2).element.selected = true;
    wrapper.find('#initiativeDropdown').trigger('change');
    await flushPromises();
    await wrapper.vm.$nextTick();
    expect(data.currentinit).toBe("1")
    expect(data.showcounts).toBe(false)
    expect(data.activities).toEqual({"1": {"allowMulti": true, "id": 1, "options": [{"groupId": 1, "id": 1, "rank": 0, "title": "Reading"}, {"groupId": 1, "id": 2, "rank": 1, "title": "Computing"}, {"groupId": 1, "id": 3, "rank": 2, "title": "Collaborating"}, {"groupId": 1, "id": 4, "rank": 3, "title": "Training/Class"}], "rank": 1, "required": true, "title": "Type"}, "2": {"allowMulti": true, "id": 2, "options": [{"groupId": 2, "id": 5, "rank": 4, "title": "In-Person"}, {"groupId": 2, "id": 6, "rank": 5, "title": "Online"}], "rank": 2, "required": false, "title": "Medium"}})
    expect(wrapper.findAll(".countButton").length).toBe(0)
    expect(data.counts[data.currentinit]).toBe(undefined)
    expect(Object.keys(data.counts)).toEqual(["2"])

    //change initiative with one location
    select.at(3).element.selected = true;
    wrapper.find('#initiativeDropdown').trigger('change');
    await flushPromises();
    await wrapper.vm.$nextTick();
    initiativedata = data.counts[data.currentinit];
    expect(data.showcounts).toBe(true)
    expect(data.currentinit).toBe("3")
    expect(data.activities).toEqual({"4": {"allowMulti": true, "id": 4, "options": [{"groupId": 4, "id": 8, "rank": 0, "title": "New Activity"}, {"groupId": 4, "id": 9, "rank": 1, "title": "test"}, {"groupId": 4, "id": 10, "rank": 2, "title": "test Activity 2"}], "rank": 0, "required": true, "title": "New Activity Group"}})
    expect(wrapper.find(".countButton").text()).toContain("Count (0)")
    expect(Object.keys(data.counts)).toEqual(["2", "3"])
    expect(data.location).toBe(11)
    expect(initiativedata['counts'][0]['number']).toEqual(0)
    expect(initiativedata['counts'][0]['location']).toEqual(11)
    expect(initiativedata['counts'].length).toEqual(1)
    expect(initiativedata["initiativeID"]).toEqual("3")
    expect(initiativedata['counts']).toEqual([{"activities": [], "location":11, "number": 0, "timestamp": time}])
    expect(wrapper.find(".countButton").text()).toContain("Count (0)")
  })
})<commit_msg>fix tests<commit_after>import { shallowMount, mount, createLocalVue} from '@vue/test-utils'
import VModal from 'vue-js-modal'
import SumaClient from '@/components/SumaClient.vue'
import flushPromises from 'flush-promises'
import VueRouter from 'vue-router'

const localVue = createLocalVue()
localVue.use(VueRouter)
localVue.use(VModal)
const router = new VueRouter()

let consoleSpy;
jest.mock('./__mocks__/axios');

describe('SumaClient.vue', () => {
  test('Testing Suma Client on Load', async () => {
    const wrapper = shallowMount(SumaClient, {localVue, router});
    await flushPromises();
    var data = wrapper.vm.$data;
    expect(data.currentinit).toBe('')
    expect(data.appVersion).toBe("1.1.0")
    expect(data.children).toEqual([])
    expect(data.initresults).toEqual([{"initiativeId":"2","initiativeTitle":"Sample Headcount Initiative"},{"initiativeId":"1","initiativeTitle":"Sample Reference Initiative"},{"initiativeId":"3","initiativeTitle":"test"}])
  })
  test('Update select options', async () => {
    const wrapper = mount(SumaClient, {localVue, router, attachToDocument: true});
    await flushPromises();

    var data = wrapper.vm.$data;

    //Select initiative from dropdown
    const select = wrapper.findAll('#initiativeDropdown > option');
    select.at(1).element.selected = true;
    wrapper.find('#initiativeDropdown').trigger('change');
    await flushPromises();
    await wrapper.vm.$nextTick()
    expect(data.currentinit).toBe("2")

    expect(data.children).toEqual([{"id":4,"title":"West Wing","children":[{"id":5,"title":"Quiet Reading Room"},{"id":6,"title":"IT Teaching Center"}]},{"id":7,"title":"East Wing","children":[{"id":8,"title":"Media Lab"},{"id":9,"title":"Learning Commons"}]},{"id":2,"title":"Ground Floor"},{"id":3,"title":"Lobby"}])
    expect(data.showcounts).toBe(false)

    //select location from items
    const locationselect = wrapper.findAll('.level-1 > li');
    await locationselect.at(0).trigger('click');
    expect(data.currentinit).toBe("2")
    expect(data.children).toEqual([{"id":4,"title":"West Wing","children":[{"id":5,"title":"Quiet Reading Room"},{"id":6,"title":"IT Teaching Center"}]},{"id":7,"title":"East Wing","children":[{"id":8,"title":"Media Lab"},{"id":9,"title":"Learning Commons"}]},{"id":2,"title":"Ground Floor"},{"id":3,"title":"Lobby"}])
    expect(data.location).toBe("")
    expect(data.showcounts).toBe(false)

    //select second location
    const locationselect2 = wrapper.findAll('.level-2 > li');
    await locationselect2.at(0).trigger('click');
    const time = Math.round(Date.now() / 1000);
    var initiativedata = data.counts[data.currentinit];
    expect(data.currentinit).toBe("2")
    expect(data.location).toBe(5)
    expect(data.showcounts).toBe(true)
    expect(data.activities).toEqual({})
    expect(initiativedata['counts'][0]['number']).toEqual(0)
    expect(initiativedata['counts'][0]['location']).toEqual(5)
    expect(initiativedata['counts'].length).toEqual(1)
    expect(initiativedata["startTime"]).toEqual(initiativedata['counts'][0]['timestamp'])
    expect(initiativedata["initiativeID"]).toEqual("2")
    expect(initiativedata['counts']).toEqual([{"activities": [], "location": 5, "number": 0, "timestamp": time}])
    expect(wrapper.find(".countButton").text()).toContain("Count (0)")

    //click on count button
    wrapper.find("form").trigger("submit.prevent")
    await wrapper.vm.$nextTick();
    expect(initiativedata['counts'].length).toEqual(1)
    expect(initiativedata['counts'][0]['number']).toEqual(1)
    expect(initiativedata['counts'][0]['location']).toEqual(5)
    expect(initiativedata['counts'].length).toEqual(1)
    expect(Object.keys(initiativedata)).toEqual(["counts","initiativeID","startTime","endTime"])
    expect(initiativedata["initiativeID"]).toEqual("2")
    expect(wrapper.find(".countButton").text()).toContain("Count (1)")

    //click on count button fourteen times
    for (var i=0; i<14; i++){
      wrapper.find("form").trigger("submit.prevent")
      await wrapper.vm.$nextTick();
    }
    expect(initiativedata['counts'][0]['number']).toEqual(1)
    expect(initiativedata['counts'].length).toEqual(15)
    expect(initiativedata['counts'][0]['location']).toEqual(5)
    expect(Object.keys(initiativedata)).toEqual(["counts","initiativeID","startTime","endTime"])
    expect(initiativedata["initiativeID"]).toEqual("2")
    expect(wrapper.find(".countButton").text()).toContain("Count (15)")

    //choose another location from location tree
    await locationselect2.at(1).trigger('click');
    expect(data.currentinit).toBe("2")
    expect(data.location).toBe(6)
    expect(data.showcounts).toBe(true)
    expect(data.activities).toEqual({})
    expect(initiativedata['counts'][15]['number']).toEqual(0)
    expect(initiativedata['counts'][15]['location']).toEqual(6)
    expect(initiativedata['counts'].length).toEqual(16)
    expect(initiativedata["startTime"]).toEqual(initiativedata['counts'][0]['timestamp'])
    expect(initiativedata["initiativeID"]).toEqual("2")
    expect(wrapper.find(".countButton").text()).toContain("Count (0)")

    //add to counts. Check location count and init count
    wrapper.find("form").trigger("submit.prevent")
    await wrapper.vm.$nextTick();
    expect(initiativedata['counts'].length).toEqual(16)
    expect(Object.keys(initiativedata)).toEqual(["counts","initiativeID","startTime","endTime"])
    expect(initiativedata["initiativeID"]).toEqual("2")
    expect(wrapper.find(".countButton").text()).toContain("Count (1)")

    //click on already clicked initiative (make sure not to add zero count)
    await locationselect2.at(1).trigger('click');
    expect(initiativedata['counts'].length).toEqual(16)

    //switch back to first location clicked
    await locationselect2.at(0).trigger('click');
    expect(initiativedata['counts'].length).toEqual(16)
    expect(Object.keys(initiativedata)).toEqual(["counts","initiativeID","startTime","endTime"])
    expect(initiativedata["initiativeID"]).toEqual("2")
    expect(wrapper.find(".countButton").text()).toContain("Count (15)")
    expect(initiativedata['counts'].length).toEqual(16)

    //change initiative
    select.at(2).element.selected = true;
    wrapper.find('#initiativeDropdown').trigger('change');
    await flushPromises();
    await wrapper.vm.$nextTick();
    expect(data.currentinit).toBe("1")
    expect(data.showcounts).toBe(false)
    expect(data.activities).toEqual({"1": {"allowMulti": true, "id": 1, "options": [{"groupId": 1, "id": 1, "rank": 0, "title": "Reading"}, {"groupId": 1, "id": 2, "rank": 1, "title": "Computing"}, {"groupId": 1, "id": 3, "rank": 2, "title": "Collaborating"}, {"groupId": 1, "id": 4, "rank": 3, "title": "Training/Class"}], "rank": 1, "required": true, "title": "Type"}, "2": {"allowMulti": true, "id": 2, "options": [{"groupId": 2, "id": 5, "rank": 4, "title": "In-Person"}, {"groupId": 2, "id": 6, "rank": 5, "title": "Online"}], "rank": 2, "required": false, "title": "Medium"}})
    expect(wrapper.findAll(".countButton").length).toBe(0)
    expect(data.counts[data.currentinit]).toBe(undefined)
    expect(Object.keys(data.counts)).toEqual(["2"])

    //change initiative with one location
    select.at(3).element.selected = true;
    wrapper.find('#initiativeDropdown').trigger('change');
    await flushPromises();
    await wrapper.vm.$nextTick();
    initiativedata = data.counts[data.currentinit];
    expect(data.showcounts).toBe(true)
    expect(data.currentinit).toBe("3")
    expect(data.activities).toEqual({"4": {"allowMulti": true, "id": 4, "options": [{"groupId": 4, "id": 8, "rank": 0, "title": "New Activity"}, {"groupId": 4, "id": 9, "rank": 1, "title": "test"}, {"groupId": 4, "id": 10, "rank": 2, "title": "test Activity 2"}], "rank": 0, "required": true, "title": "New Activity Group"}})
    expect(wrapper.find(".countButton").text()).toContain("Count (0)")
    expect(Object.keys(data.counts)).toEqual(["2", "3"])
    expect(data.location).toBe(11)
    expect(initiativedata['counts'][0]['number']).toEqual(0)
    expect(initiativedata['counts'][0]['location']).toEqual(11)
    expect(initiativedata['counts'].length).toEqual(1)
    expect(initiativedata["initiativeID"]).toEqual("3")
    expect(initiativedata['counts']).toEqual([{"activities": [], "location":11, "number": 0, "timestamp": time}])
    expect(wrapper.find(".countButton").text()).toContain("Count (0)")
  })
})<|endoftext|>


<commit_before>var waitingDialog = waitingDialog || (function ($) {
        'use strict';
        return {
            show: function (message, options) {
                // Assigning defaults
                if (typeof options === 'undefined') {
                    options = {};
                }
                if (typeof message === 'undefined') {
                    message = 'Loading';
                }
                var settings = $.extend({
                    dialogSize: 'm',
                    progressType: '',
                    onHide: null // This callback runs after the dialog was hidden
                }, options);

                var dialog = $("#dialog");

                dialog.find('.modal-dialog').attr('class', 'modal-dialog').addClass('modal-' + settings.dialogSize);
                dialog.find('.progress-bar').attr('class', 'progress-bar');
                if (settings.progressType) {
                    dialog.find('.progress-bar').addClass('progress-bar-' + settings.progressType);
                }
                dialog.find('h3').text(message);

                if (typeof settings.onHide === 'function') {
                    dialog.off('hidden.bs.modal').on('hidden.bs.modal', function (e) {
                        settings.onHide.call($dialog);
                    });
                }
                dialog.modal();
            },
            hide: function () {
                $("#dialog").modal('hide');
            }
        };
    })(jQuery);

var dataLoader = (function ($) {
    var raderLoaded = false;
    var scoreLoaded = false;
    var startDate = '';
    return {
        load: function (endpoint_id, evaluation_id, start_date) {
            raderLoaded = false;
            scoreLoaded = false;
            waitingDialog.show('Loading Endpoint Information...');
            dataLoader.showInfo(endpoint_id, evaluation_id);
            startDate = start_date;
        },

        done: function() {
            if (raderLoaded && scoreLoaded) {
                waitingDialog.hide();
                $('#jump-button').on("click", function () {
                    var input_date = $("#calendar").val();
                    var param = (input_date == '') ? '' : '?date=' + input_date;
                    $.getJSON("/api/endpoints/" + endpoint_id + "/created_at" + param, function (json) {
                        var evaluation_id = json['evaluation_id'];
                        if (evaluation_id == '') {
                            $('#get_evaluation_id').modal();
                        } else {
                            location.href = "/endpoints/" + endpoint_id + "/" + evaluation_id + param
                        }
                    });
                });
                $('#calendar').datepicker({
                    autoclose: true,
                    startDate: "#" + startDate,
                    endDate: new Date(),
                    format: 'dd-M-yyyy',
                    todayHighlight: true,
                });
            }
        },

        showInfo: function(endpoint_id, evaluation_id) {
            $.ajax({
                type: "GET",
                url: "/endpoints/" + endpoint_id + "/" + evaluation_id + "/info",
                success: function (element) {
                    var html = $.parseHTML(element);
                    $("#endpoint_info").html(html);
                    dataLoader.showRadar(endpoint_id, evaluation_id);
                    dataLoader.showScoreHistory(endpoint_id, evaluation_id);
                }
            });
        },

        showRadar: function (endpoint_id, evaluation_id) {
            $.getJSON("/endpoints/" + endpoint_id + "/" + evaluation_id + "/radar", function (json) {
                var data = json['data'];
                var avg = json['avg'];
                var context = $("#radar");
                var labels = ["availability", "freshness", "operation", "usefulness", "validity", "performance"];
                new Chart(context, {
                    type: 'radar',
                    data: {
                        labels: labels,
                        datasets: [
                            {
                                label: "Target",
                                backgroundColor: "rgba(151,187,205,0.2)",
                                borderColor: "rgba(151,187,205,1)",
                                pointBorderColor: "rgba(151,187,205,1)",
                                pointBackgroundColor: "#fff",
                                data: data
                            },
                            {
                                label: "Average",
                                backgroundColor: "rgba(220,220,220,0.5)",
                                borderColor: "rgba(220,220,220,1)",
                                pointBorderColor: "rgba(220,220,220,1)",
                                pointBackgroundColor: "#fff",
                                data: avg
                            }
                        ]
                    },
                    options: {
                        responsive: true
                    }
                });
                dataLoader.setScoresOnLabels(labels, data);
                raderLoaded = true;
                dataLoader.done();
            });
        },

        setScoresOnLabels: function (labels, data) {
            var status;
            for (var i = 0; i < 6; ++i) {
                $('#' + labels[i] + '_score').text('(' + data[i] + ')');
                if (data[i] < 20) {
                    status = 'poor';
                } else if (data[i] < 40) {
                    status = 'below_average'
                } else if (data[i] < 60) {
                    status = 'average'
                } else if (data[i] < 80) {
                    status = 'good'
                } else {
                    status = 'excellent';
                }
                $('.' + labels[i]).addClass(status)
            }
        },

        appendOptions: function (datasets) {
            datasets['datasets'].forEach(function (element) {
                var label = element['label'];

                if (label) {
                    element['lineTension'] = 0;
                    // set all 'pointBackgroundColor' to white
                    element['pointBackgroundColor'] = 'rgba(255, 255, 255, 1)';
                    // set the area under the line not to fill
                    element['fill'] = false;
                }

                switch (label.toLowerCase()) {
                    case 'availability':
                        element['backgroundColor'] = 'rgba(220, 220, 220, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(220, 220, 220, 1)';
                        break;
                    case 'freshness':
                        element['backgroundColor'] = 'rgba(54, 162, 235, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(54, 162, 235, 1)';
                        break;
                    case 'operation':
                        element['backgroundColor'] = 'rgba(255, 99, 132, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(255, 99, 132, 1)';
                        break;
                    case 'usefulness':
                        element['backgroundColor'] = 'rgba(255, 206, 86, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(255, 206, 86, 1)';
                        break;
                    case 'validity':
                        element['backgroundColor'] = 'rgba(75, 192, 192, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(75, 192, 192, 1)';
                        break;
                    case 'performance':
                        element['backgroundColor'] = 'rgba(21, 7, 119, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(21, 7, 119, 1)';
                        break;
                    case 'rank':
                        element['backgroundColor'] = 'rgba(151, 187, 205, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(151, 187, 205, 1)';
                        break;
                    default:
                        break;
                }
            });
        },

        showScoreHistory: function (endpoint_id, evaluation_id) {
            $.getJSON("/endpoints/" + endpoint_id + "/" + evaluation_id + "/score_history", function (json) {
                var context = $("#score_history");
                dataLoader.appendOptions(json);
                var labels = json['labels'];
                json['labels'] = labels.map(formatDate);
                var options = make_scale_options()
                options['datasetFill'] = false
                var lineChart = new Chart(context, {
                    type: 'line',
                    data: json,
                    options: options
                });
                dataLoader.addGraphClickEvent(context, lineChart, labels, endpoint_id);
                scoreLoaded = true;
                dataLoader.done();
            });
        },

        addGraphClickEvent: function (context, lineChart, labels, endpoint_id) {
            $(context).on("click", function (evt) {
                var activePoints = lineChart.getElementsAtEvent(evt);
                if (activePoints.length == 0) {
                    return
                }
                var index = activePoints[0]['_index'];
                var datestring = labels[index];
                var clickedDate = new Date(datestring);
                $.getJSON("/api/endpoints/" + endpoint_id + "/created_at?date=" + datestring, function (json) {
                    var evaluation_id = json['evaluation_id']
                    if (evaluation_id == '') {
                        $('#get_evaluation_id').modal();
                    } else {
                        location.href = location.protocol + "//" + location.host + '/endpoints/' + endpoint_id + '/' + evaluation_id + "?date=" + datestring
                    }
                });
            });
        },
    }
})(jQuery);

$(function() {
    var endpoint_id = $("#endpoint_id").text().trim();
    var evaluation_id = $("#evaluation_id").text().trim();
    var start_date = $("#start_date").text().trim();
    dataLoader.load(endpoint_id, evaluation_id, start_date);
});

<commit_msg>Fix the problem that calendar does not work well on endpoint details page.<commit_after>var waitingDialog = waitingDialog || (function ($) {
        'use strict';
        return {
            show: function (message, options) {
                // Assigning defaults
                if (typeof options === 'undefined') {
                    options = {};
                }
                if (typeof message === 'undefined') {
                    message = 'Loading';
                }
                var settings = $.extend({
                    dialogSize: 'm',
                    progressType: '',
                    onHide: null // This callback runs after the dialog was hidden
                }, options);

                var dialog = $("#dialog");

                dialog.find('.modal-dialog').attr('class', 'modal-dialog').addClass('modal-' + settings.dialogSize);
                dialog.find('.progress-bar').attr('class', 'progress-bar');
                if (settings.progressType) {
                    dialog.find('.progress-bar').addClass('progress-bar-' + settings.progressType);
                }
                dialog.find('h3').text(message);

                if (typeof settings.onHide === 'function') {
                    dialog.off('hidden.bs.modal').on('hidden.bs.modal', function (e) {
                        settings.onHide.call($dialog);
                    });
                }
                dialog.modal();
            },
            hide: function () {
                $("#dialog").modal('hide');
            }
        };
    })(jQuery);

var dataLoader = (function ($) {
    var endpointId = null;
    var raderLoaded = false;
    var scoreLoaded = false;
    var startDate = '';
    return {
        load: function (endpoint_id, evaluation_id, start_date) {
            endpointId = endpoint_id;
            raderLoaded = false;
            scoreLoaded = false;
            waitingDialog.show('Loading Endpoint Information...');
            dataLoader.showInfo(endpointId, evaluation_id);
            startDate = start_date;
        },

        done: function() {
            if (raderLoaded && scoreLoaded) {
                waitingDialog.hide();
                $('#jump-button').on("click", function () {
                    var input_date = $("#calendar").val();
                    var param = (input_date == '') ? '' : '?date=' + input_date;
                    $.getJSON("/api/endpoints/" + endpointId + "/created_at" + param, function (json) {
                        var evaluation_id = json['evaluation_id'];
                        if (evaluation_id == '') {
                            $('#get_evaluation_id').modal();
                        } else {
                            location.href = "/endpoints/" + endpointId + "/" + evaluation_id + param
                        }
                    });
                });
                $('#calendar').datepicker({
                    autoclose: true,
                    startDate: "#" + startDate,
                    endDate: new Date(),
                    format: 'dd-M-yyyy',
                    todayHighlight: true,
                });
            }
        },

        showInfo: function(endpoint_id, evaluation_id) {
            $.ajax({
                type: "GET",
                url: "/endpoints/" + endpoint_id + "/" + evaluation_id + "/info",
                success: function (element) {
                    var html = $.parseHTML(element);
                    $("#endpoint_info").html(html);
                    dataLoader.showRadar(endpoint_id, evaluation_id);
                    dataLoader.showScoreHistory(endpoint_id, evaluation_id);
                }
            });
        },

        showRadar: function (endpoint_id, evaluation_id) {
            $.getJSON("/endpoints/" + endpoint_id + "/" + evaluation_id + "/radar", function (json) {
                var data = json['data'];
                var avg = json['avg'];
                var context = $("#radar");
                var labels = ["availability", "freshness", "operation", "usefulness", "validity", "performance"];
                new Chart(context, {
                    type: 'radar',
                    data: {
                        labels: labels,
                        datasets: [
                            {
                                label: "Target",
                                backgroundColor: "rgba(151,187,205,0.2)",
                                borderColor: "rgba(151,187,205,1)",
                                pointBorderColor: "rgba(151,187,205,1)",
                                pointBackgroundColor: "#fff",
                                data: data
                            },
                            {
                                label: "Average",
                                backgroundColor: "rgba(220,220,220,0.5)",
                                borderColor: "rgba(220,220,220,1)",
                                pointBorderColor: "rgba(220,220,220,1)",
                                pointBackgroundColor: "#fff",
                                data: avg
                            }
                        ]
                    },
                    options: {
                        responsive: true
                    }
                });
                dataLoader.setScoresOnLabels(labels, data);
                raderLoaded = true;
                dataLoader.done();
            });
        },

        setScoresOnLabels: function (labels, data) {
            var status;
            for (var i = 0; i < 6; ++i) {
                $('#' + labels[i] + '_score').text('(' + data[i] + ')');
                if (data[i] < 20) {
                    status = 'poor';
                } else if (data[i] < 40) {
                    status = 'below_average'
                } else if (data[i] < 60) {
                    status = 'average'
                } else if (data[i] < 80) {
                    status = 'good'
                } else {
                    status = 'excellent';
                }
                $('.' + labels[i]).addClass(status)
            }
        },

        appendOptions: function (datasets) {
            datasets['datasets'].forEach(function (element) {
                var label = element['label'];

                if (label) {
                    element['lineTension'] = 0;
                    // set all 'pointBackgroundColor' to white
                    element['pointBackgroundColor'] = 'rgba(255, 255, 255, 1)';
                    // set the area under the line not to fill
                    element['fill'] = false;
                }

                switch (label.toLowerCase()) {
                    case 'availability':
                        element['backgroundColor'] = 'rgba(220, 220, 220, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(220, 220, 220, 1)';
                        break;
                    case 'freshness':
                        element['backgroundColor'] = 'rgba(54, 162, 235, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(54, 162, 235, 1)';
                        break;
                    case 'operation':
                        element['backgroundColor'] = 'rgba(255, 99, 132, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(255, 99, 132, 1)';
                        break;
                    case 'usefulness':
                        element['backgroundColor'] = 'rgba(255, 206, 86, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(255, 206, 86, 1)';
                        break;
                    case 'validity':
                        element['backgroundColor'] = 'rgba(75, 192, 192, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(75, 192, 192, 1)';
                        break;
                    case 'performance':
                        element['backgroundColor'] = 'rgba(21, 7, 119, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(21, 7, 119, 1)';
                        break;
                    case 'rank':
                        element['backgroundColor'] = 'rgba(151, 187, 205, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(151, 187, 205, 1)';
                        break;
                    default:
                        break;
                }
            });
        },

        showScoreHistory: function (endpoint_id, evaluation_id) {
            $.getJSON("/endpoints/" + endpoint_id + "/" + evaluation_id + "/score_history", function (json) {
                var context = $("#score_history");
                dataLoader.appendOptions(json);
                var labels = json['labels'];
                json['labels'] = labels.map(formatDate);
                var options = make_scale_options()
                options['datasetFill'] = false
                var lineChart = new Chart(context, {
                    type: 'line',
                    data: json,
                    options: options
                });
                dataLoader.addGraphClickEvent(context, lineChart, labels, endpoint_id);
                scoreLoaded = true;
                dataLoader.done();
            });
        },

        addGraphClickEvent: function (context, lineChart, labels, endpoint_id) {
            $(context).on("click", function (evt) {
                var activePoints = lineChart.getElementsAtEvent(evt);
                if (activePoints.length == 0) {
                    return
                }
                var index = activePoints[0]['_index'];
                var datestring = labels[index];
                var clickedDate = new Date(datestring);
                $.getJSON("/api/endpoints/" + endpoint_id + "/created_at?date=" + datestring, function (json) {
                    var evaluation_id = json['evaluation_id']
                    if (evaluation_id == '') {
                        $('#get_evaluation_id').modal();
                    } else {
                        location.href = location.protocol + "//" + location.host + '/endpoints/' + endpoint_id + '/' + evaluation_id + "?date=" + datestring
                    }
                });
            });
        },
    }
})(jQuery);

$(function() {
    var endpoint_id = $("#endpoint_id").text().trim();
    var evaluation_id = $("#evaluation_id").text().trim();
    var start_date = $("#start_date").text().trim();
    dataLoader.load(endpoint_id, evaluation_id, start_date);
});

<|endoftext|>


<commit_before>var waitingDialog = waitingDialog || (function ($) {
        'use strict';

        var $dialog = $(
            '
' +
            '
' +
            '
' +
            '

' +
            '
' +
            '

' +
            '
' +
            '

');
        return {
            show: function (message, options) {
                // Assigning defaults
                if (typeof options === 'undefined') {
                    options = {};
                }
                if (typeof message === 'undefined') {
                    message = 'Loading';
                }
                var settings = $.extend({
                    dialogSize: 'm',
                    progressType: '',
                    onHide: null // This callback runs after the dialog was hidden
                }, options);

                $dialog.find('.modal-dialog').attr('class', 'modal-dialog').addClass('modal-' + settings.dialogSize);
                $dialog.find('.progress-bar').attr('class', 'progress-bar');
                if (settings.progressType) {
                    $dialog.find('.progress-bar').addClass('progress-bar-' + settings.progressType);
                }
                $dialog.find('h3').text(message);

                if (typeof settings.onHide === 'function') {
                    $dialog.off('hidden.bs.modal').on('hidden.bs.modal', function (e) {
                        settings.onHide.call($dialog);
                    });
                }

                $dialog.modal();
            },
            hide: function () {
                $dialog.modal('hide');
            }
        };
    })(jQuery);

var dataLoader = (function ($) {
    var raderLoaded = false;
    var scoreLoaded = false;

    return {
        load: function (endpoint_id, evaluation_id) {
            raderLoaded = false;
            scoreLoaded = false;
            waitingDialog.show('Loading Endpoint Information...');
            dataLoader.showInfo(endpoint_id, evaluation_id);
        },

        done: function() {
            if (raderLoaded && scoreLoaded) {
                waitingDialog.hide();
            }
        },

        showInfo: function(endpoint_id, evaluation_id) {
            $.ajax({
                type: "GET",
                url: "/endpoints/" + endpoint_id + "/" + evaluation_id + "/info",
                success: function (element) {
                    var html = $.parseHTML(element);
                    $("#endpoint_info").html(html);
                    dataLoader.showRadar(endpoint_id, evaluation_id);
                    dataLoader.showScoreHistory(endpoint_id, evaluation_id);
                }
            });
        },

        showRadar: function (endpoint_id, evaluation_id) {
            $.getJSON("/endpoints/" + endpoint_id + "/" + evaluation_id + "/radar", function (json) {
                var data = json['data'];
                var avg = json['avg'];
                var context = $("#radar");
                var labels = ["availability", "freshness", "operation", "usefulness", "validity", "performance"];
                new Chart(context, {
                    type: 'radar',
                    data: {
                        labels: labels,
                        datasets: [
                            {
                                label: "Target",
                                backgroundColor: "rgba(151,187,205,0.2)",
                                borderColor: "rgba(151,187,205,1)",
                                pointBorderColor: "rgba(151,187,205,1)",
                                pointBackgroundColor: "#fff",
                                data: data
                            },
                            {
                                label: "Average",
                                backgroundColor: "rgba(220,220,220,0.5)",
                                borderColor: "rgba(220,220,220,1)",
                                pointBorderColor: "rgba(220,220,220,1)",
                                pointBackgroundColor: "#fff",
                                data: avg
                            }
                        ]
                    },
                    options: {
                        responsive: true
                    }
                });
                dataLoader.setScoresOnLabels(labels, data);
                raderLoaded = true;
                dataLoader.done();
            });
        },

        setScoresOnLabels: function (labels, data) {
            var status;
            for (var i = 0; i < 6; ++i) {
                $('#' + labels[i] + '_score').text('(' + data[i] + ')');
                if (data[i] < 20) {
                    status = 'poor';
                } else if (data[i] < 40) {
                    status = 'below_average'
                } else if (data[i] < 60) {
                    status = 'average'
                } else if (data[i] < 80) {
                    status = 'good'
                } else {
                    status = 'excellent';
                }
                $('.' + labels[i]).addClass(status)
            }
        },

        appendOptions: function (datasets) {
            datasets['datasets'].forEach(function (element) {
                var label = element['label'];

                if (label) {
                    element['lineTension'] = 0;
                    // set all 'pointBackgroundColor' to white
                    element['pointBackgroundColor'] = 'rgba(255, 255, 255, 1)';
                    // set the area under the line not to fill
                    element['fill'] = false;
                }

                switch (label.toLowerCase()) {
                    case 'availability':
                        element['backgroundColor'] = 'rgba(220, 220, 220, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(220, 220, 220, 1)';
                        break;
                    case 'freshness':
                        element['backgroundColor'] = 'rgba(54, 162, 235, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(54, 162, 235, 1)';
                        break;
                    case 'operation':
                        element['backgroundColor'] = 'rgba(255, 99, 132, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(255, 99, 132, 1)';
                        break;
                    case 'usefulness':
                        element['backgroundColor'] = 'rgba(255, 206, 86, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(255, 206, 86, 1)';
                        break;
                    case 'validity':
                        element['backgroundColor'] = 'rgba(75, 192, 192, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(75, 192, 192, 1)';
                        break;
                    case 'performance':
                        element['backgroundColor'] = 'rgba(21, 7, 119, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(21, 7, 119, 1)';
                        break;
                    case 'rank':
                        element['backgroundColor'] = 'rgba(151, 187, 205, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(151, 187, 205, 1)';
                        break;
                    default:
                        break;
                }
            });
        },

        showScoreHistory: function (endpoint_id, evaluation_id) {
            $.getJSON("/endpoints/" + endpoint_id + "/" + evaluation_id + "/score_history", function (json) {
                var context = $("#score_history");
                dataLoader.appendOptions(json);
                var labels = json['labels'];
                json['labels'] = labels.map(formatDate);
                var options = make_scale_options()
                options['datasetFill'] = false
                var lineChart = new Chart(context, {
                    type: 'line',
                    data: json,
                    options: options
                });
                dataLoader.addGraphClickEvent(context, lineChart, labels, endpoint_id);
                scoreLoaded = true;
                dataLoader.done();
            });
        },

        addGraphClickEvent: function (context, lineChart, labels, endpoint_id) {
            $(context).on("click", function (evt) {
                var activePoints = lineChart.getElementsAtEvent(evt);
                if (activePoints.length == 0) {
                    return
                }
                var index = activePoints[0]['_index'];
                var datestring = labels[index];
                var clickedDate = new Date(datestring);
                $.getJSON("/api/endpoints/" + endpoint_id + "/created_at?date=" + datestring, function (json) {
                    var evaluation_id = json['evaluation_id']
                    if (evaluation_id == '') {
                        $('#get_evaluation_id').modal();
                    } else {
                        location.href = location.protocol + "//" + location.host + '/endpoints/' + endpoint_id + '/' + evaluation_id + "?date=" + datestring
                    }
                });
            });
        },
    }
})(jQuery);

$(function () {
    var endpoint_id = $('#endpoint_id').text().trim();
    var evaluation_id = $('#evaluation_id').text().trim();

    dataLoader.load(endpoint_id, evaluation_id);

    $('#jump-button').on("click", function () {
        var input_date = $("#calendar").val();
        var param = (input_date == '') ? '' : '?date=' + input_date;
        $.getJSON("/api/endpoints/" + endpoint_id + "/created_at" + param, function (json) {
            var evaluation_id = json['evaluation_id'];
            if (evaluation_id == '') {
                $('#get_evaluation_id').modal();
            } else {
                location.href = "/endpoints/" + endpoint_id + "/" + evaluation_id + param
            }
        });
    });
});
<commit_msg>Update show.js<commit_after>var waitingDialog = waitingDialog || (function ($) {
        'use strict';

        var $dialog = $(
            '
' +
            '
' +
            '
' +
            '

' +
            '
' +
            '

' +
            '
' +
            '

');
        return {
            show: function (message, options) {
                // Assigning defaults
                if (typeof options === 'undefined') {
                    options = {};
                }
                if (typeof message === 'undefined') {
                    message = 'Loading';
                }
                var settings = $.extend({
                    dialogSize: 'm',
                    progressType: '',
                    onHide: null // This callback runs after the dialog was hidden
                }, options);

                $dialog.find('.modal-dialog').attr('class', 'modal-dialog').addClass('modal-' + settings.dialogSize);
                $dialog.find('.progress-bar').attr('class', 'progress-bar');
                if (settings.progressType) {
                    $dialog.find('.progress-bar').addClass('progress-bar-' + settings.progressType);
                }
                $dialog.find('h3').text(message);

                if (typeof settings.onHide === 'function') {
                    $dialog.off('hidden.bs.modal').on('hidden.bs.modal', function (e) {
                        settings.onHide.call($dialog);
                    });
                }

                $dialog.modal();
            },
            hide: function () {
                $dialog.modal('hide');
            }
        };
    })(jQuery);

var dataLoader = (function ($) {
    var raderLoaded = false;
    var scoreLoaded = false;

    return {
        load: function (endpoint_id, evaluation_id) {
            raderLoaded = false;
            scoreLoaded = false;
            waitingDialog.show('Loading Endpoint Information...');
            dataLoader.showInfo(endpoint_id, evaluation_id);
        },

        done: function() {
            if (raderLoaded && scoreLoaded) {
                waitingDialog.hide();

                $('#jump-button').on("click", function () {
                    var input_date = $("#calendar").val();
                    var param = (input_date == '') ? '' : '?date=' + input_date;
                    $.getJSON("/api/endpoints/" + endpoint_id + "/created_at" + param, function (json) {
                        var evaluation_id = json['evaluation_id'];
                        if (evaluation_id == '') {
                            $('#get_evaluation_id').modal();
                        } else {
                            location.href = "/endpoints/" + endpoint_id + "/" + evaluation_id + param
                        }
                    });
                });
            }
        },

        showInfo: function(endpoint_id, evaluation_id) {
            $.ajax({
                type: "GET",
                url: "/endpoints/" + endpoint_id + "/" + evaluation_id + "/info",
                success: function (element) {
                    var html = $.parseHTML(element);
                    $("#endpoint_info").html(html);
                    dataLoader.showRadar(endpoint_id, evaluation_id);
                    dataLoader.showScoreHistory(endpoint_id, evaluation_id);
                }
            });
        },

        showRadar: function (endpoint_id, evaluation_id) {
            $.getJSON("/endpoints/" + endpoint_id + "/" + evaluation_id + "/radar", function (json) {
                var data = json['data'];
                var avg = json['avg'];
                var context = $("#radar");
                var labels = ["availability", "freshness", "operation", "usefulness", "validity", "performance"];
                new Chart(context, {
                    type: 'radar',
                    data: {
                        labels: labels,
                        datasets: [
                            {
                                label: "Target",
                                backgroundColor: "rgba(151,187,205,0.2)",
                                borderColor: "rgba(151,187,205,1)",
                                pointBorderColor: "rgba(151,187,205,1)",
                                pointBackgroundColor: "#fff",
                                data: data
                            },
                            {
                                label: "Average",
                                backgroundColor: "rgba(220,220,220,0.5)",
                                borderColor: "rgba(220,220,220,1)",
                                pointBorderColor: "rgba(220,220,220,1)",
                                pointBackgroundColor: "#fff",
                                data: avg
                            }
                        ]
                    },
                    options: {
                        responsive: true
                    }
                });
                dataLoader.setScoresOnLabels(labels, data);
                raderLoaded = true;
                dataLoader.done();
            });
        },

        setScoresOnLabels: function (labels, data) {
            var status;
            for (var i = 0; i < 6; ++i) {
                $('#' + labels[i] + '_score').text('(' + data[i] + ')');
                if (data[i] < 20) {
                    status = 'poor';
                } else if (data[i] < 40) {
                    status = 'below_average'
                } else if (data[i] < 60) {
                    status = 'average'
                } else if (data[i] < 80) {
                    status = 'good'
                } else {
                    status = 'excellent';
                }
                $('.' + labels[i]).addClass(status)
            }
        },

        appendOptions: function (datasets) {
            datasets['datasets'].forEach(function (element) {
                var label = element['label'];

                if (label) {
                    element['lineTension'] = 0;
                    // set all 'pointBackgroundColor' to white
                    element['pointBackgroundColor'] = 'rgba(255, 255, 255, 1)';
                    // set the area under the line not to fill
                    element['fill'] = false;
                }

                switch (label.toLowerCase()) {
                    case 'availability':
                        element['backgroundColor'] = 'rgba(220, 220, 220, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(220, 220, 220, 1)';
                        break;
                    case 'freshness':
                        element['backgroundColor'] = 'rgba(54, 162, 235, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(54, 162, 235, 1)';
                        break;
                    case 'operation':
                        element['backgroundColor'] = 'rgba(255, 99, 132, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(255, 99, 132, 1)';
                        break;
                    case 'usefulness':
                        element['backgroundColor'] = 'rgba(255, 206, 86, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(255, 206, 86, 1)';
                        break;
                    case 'validity':
                        element['backgroundColor'] = 'rgba(75, 192, 192, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(75, 192, 192, 1)';
                        break;
                    case 'performance':
                        element['backgroundColor'] = 'rgba(21, 7, 119, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(21, 7, 119, 1)';
                        break;
                    case 'rank':
                        element['backgroundColor'] = 'rgba(151, 187, 205, 0.2)';
                        element['borderColor'] = element['pointBorderColor'] = 'rgba(151, 187, 205, 1)';
                        break;
                    default:
                        break;
                }
            });
        },

        showScoreHistory: function (endpoint_id, evaluation_id) {
            $.getJSON("/endpoints/" + endpoint_id + "/" + evaluation_id + "/score_history", function (json) {
                var context = $("#score_history");
                dataLoader.appendOptions(json);
                var labels = json['labels'];
                json['labels'] = labels.map(formatDate);
                var options = make_scale_options()
                options['datasetFill'] = false
                var lineChart = new Chart(context, {
                    type: 'line',
                    data: json,
                    options: options
                });
                dataLoader.addGraphClickEvent(context, lineChart, labels, endpoint_id);
                scoreLoaded = true;
                dataLoader.done();
            });
        },

        addGraphClickEvent: function (context, lineChart, labels, endpoint_id) {
            $(context).on("click", function (evt) {
                var activePoints = lineChart.getElementsAtEvent(evt);
                if (activePoints.length == 0) {
                    return
                }
                var index = activePoints[0]['_index'];
                var datestring = labels[index];
                var clickedDate = new Date(datestring);
                $.getJSON("/api/endpoints/" + endpoint_id + "/created_at?date=" + datestring, function (json) {
                    var evaluation_id = json['evaluation_id']
                    if (evaluation_id == '') {
                        $('#get_evaluation_id').modal();
                    } else {
                        location.href = location.protocol + "//" + location.host + '/endpoints/' + endpoint_id + '/' + evaluation_id + "?date=" + datestring
                    }
                });
            });
        },
    }
})(jQuery);

$(function () {
    var endpoint_id = $('#endpoint_id').text().trim();
    var evaluation_id = $('#evaluation_id').text().trim();

    dataLoader.load(endpoint_id, evaluation_id);
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

const emberCliUpdate = require('../src');
const args = require('../src/args');

const argv = require('yargs')
  .options(args)
  .version()
  .help()
  .argv;

const from = argv['from'];
const to = argv['to'];
const ignoreConflicts = argv['ignore-conflicts'];

emberCliUpdate({
  from,
  to,
  ignoreConflicts
}).catch(console.error);
<commit_msg>yargs enabled these by default<commit_after>#!/usr/bin/env node
'use strict';

const emberCliUpdate = require('../src');
const args = require('../src/args');

const argv = require('yargs')
  .options(args)
  .argv;

const from = argv['from'];
const to = argv['to'];
const ignoreConflicts = argv['ignore-conflicts'];

emberCliUpdate({
  from,
  to,
  ignoreConflicts
}).catch(console.error);
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule TextInputState
 * @flow
 *
 * This class is responsible for coordinating the "focused"
 * state for TextInputs. All calls relating to the keyboard
 * should be funneled through here
 */
'use strict';

var RCTUIManager = require('NativeModules').UIManager;

var TextInputState = {
   /**
   * Internal state
   */
  _currentlyFocusedID: (null: ?number),

  /**
   * Returns the ID of the currently focused text field, if one exists
   * If no text field is focused it returns null
   */
  currentlyFocusedField: function(): ?number {
    return this._currentlyFocusedID;
  },

  /**
   * @param {number} TextInputID id of the text field to focus
   * Focuses the specified text field
   * noop if the text field was already focused
   */
  focusTextInput: function(textFieldID: ?number) {
    if (this._currentlyFocusedID !== textFieldID && textFieldID !== null) {
      this._currentlyFocusedID = textFieldID;
      RCTUIManager.focus(textFieldID);
    }
  },

  /**
   * @param {number} textFieldID id of the text field to focus
   * Unfocuses the specified text field
   * noop if it wasn't focused
   */
  blurTextInput: function(textFieldID: ?number) {
    if (this._currentlyFocusedID === textFieldID && textFieldID !== null) {
      this._currentlyFocusedID = null;
      RCTUIManager.blur(textFieldID);
    }
  }
};

module.exports = TextInputState;
<commit_msg>[ReactNative] Fix TextInput Focus issue<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule TextInputState
 * @flow
 *
 * This class is responsible for coordinating the "focused"
 * state for TextInputs. All calls relating to the keyboard
 * should be funneled through here
 */
'use strict';

var Platform = require('Platform');
var RCTUIManager = require('NativeModules').UIManager;

var TextInputState = {
   /**
   * Internal state
   */
  _currentlyFocusedID: (null: ?number),

  /**
   * Returns the ID of the currently focused text field, if one exists
   * If no text field is focused it returns null
   */
  currentlyFocusedField: function(): ?number {
    return this._currentlyFocusedID;
  },

  /**
   * @param {number} TextInputID id of the text field to focus
   * Focuses the specified text field
   * noop if the text field was already focused
   */
  focusTextInput: function(textFieldID: ?number) {
    if (this._currentlyFocusedID !== textFieldID && textFieldID !== null) {
      this._currentlyFocusedID = textFieldID;
      if (Platform.OS === 'ios') {
        RCTUIManager.focus(textFieldID);
      } else if (Platform.OS === 'android') {
        RCTUIManager.dispatchViewManagerCommand(
          textFieldID,
          RCTUIManager.AndroidTextInput.Commands.focusTextInput,
          null
        );
      }
    }
  },

  /**
   * @param {number} textFieldID id of the text field to focus
   * Unfocuses the specified text field
   * noop if it wasn't focused
   */
  blurTextInput: function(textFieldID: ?number) {
    if (this._currentlyFocusedID === textFieldID && textFieldID !== null) {
      this._currentlyFocusedID = null;
      if (Platform.OS === 'ios') {
        RCTUIManager.blur(textFieldID);
      } else if (Platform.OS === 'android') {
        RCTUIManager.dispatchViewManagerCommand(
          textFieldID,
          RCTUIManager.AndroidTextInput.Commands.blurTextInput,
          null
        );
      }
    }
  }
};

module.exports = TextInputState;
<|endoftext|>


<commit_before>//
// Simple example of using sqlish with NodeJS
//
var sqlish = require("../sqlish"),
	Sql = new sqlish.Sql({dialect: sqlish.MySQL, use_UTC: false}),
	message = {
		id: 0,
		name: "fred",
		email: "fred@gmail.com",
		messages: 'He Said, "Hello World"',
		sent: new Date("09/01/2012 14:15:00")
	};

// Output:
// INSERT INTO messages (name, email, msg, sent) VALUES (
//	"fred", "fred@example.com", "He siad, \"Hello World\"",
//	"2012-09-01 14:15:00")
console.log(Sql.insert("test", message).toString());

// Output:
// SELECT id, name, email, msg, sent FROM messages
//	WHERE email LIKE "%@example.com"
console.log(Sql.select(Object.keys(message))
		.from("messages")
		.where('email LIKE "%@example.com"').toString());

// Output:
// REPLACE INTO messages (id, name, email, msg, sent) VALUES (
//	10123, "George", "george@example.com", "He siad, \"Hello World\"",
//	"2012-07-01")
message.id = 10123;
message.name = "George";
message.email = "george@example.com";
message.sent = new Date("07/01/2012");
console.log(Sql.replace("test", message).toString());
<commit_msg>fixed like clause in example.<commit_after>//
// Simple example of using sqlish with NodeJS
//
var sqlish = require("../sqlish"),
	Sql = new sqlish.Sql({dialect: sqlish.MySQL, use_UTC: false}),
	message = {
		id: 0,
		name: "fred",
		email: "fred@gmail.com",
		messages: 'He Said, "Hello World"',
		sent: new Date("09/01/2012 14:15:00")
	};

// Output:
// INSERT INTO messages (name, email, msg, sent) VALUES (
//	"fred", "fred@example.com", "He siad, \"Hello World\"",
//	"2012-09-01 14:15:00")
console.log(Sql.insert("test", message).toString());

// Output:
// SELECT id, name, email, msg, sent FROM messages
//	WHERE email LIKE "%@example.com"
console.log(Sql.select(Object.keys(message))
		.from("messages"
		.where({email: {$like: "%@example.com"}}).toString());

// Output:
// REPLACE INTO messages (id, name, email, msg, sent) VALUES (
//	10123, "George", "george@example.com", "He siad, \"Hello World\"",
//	"2012-07-01")
message.id = 10123;
message.name = "George";
message.email = "george@example.com";
message.sent = new Date("07/01/2012");
console.log(Sql.replace("test", message).toString());
<|endoftext|>


<commit_before>describe('Preprocessor', function () {
  var
    H = envision,
    Preprocessor = H.Preprocessor;

  it('defines preprocessor', function () {
    expect(H.Preprocessor).toBeDefined();
  });

  it('creates a preprocessor', function () {
    expect(new H.Preprocessor()).toBeDefined();
  });

  it('gets private data from options', function () {
    var
      data = [[],[]],
      options = { data : data },
      preprocessor = new H.Preprocessor(options);

    expect(preprocessor.getData()).toBe(data);
  });

  it('sets new private data', function () {

    var
      data = [[],[]],
      options = { data : [[], []] },
      preprocessor = new H.Preprocessor(options);

    expect(preprocessor.getData()).not.toBe(data);
    preprocessor.setData(data);
    expect(preprocessor.getData()).toBe(data);
  });

  it('calculates length', function () {
    var
      preprocessor = new Preprocessor({data : [[], []]});
    expect(preprocessor.length()).toBe(0);
    preprocessor.setData([[0], [1]]);
    expect(preprocessor.length()).toBe(1);
  });

  describe('Validation', function () {

    var
      preprocessor;

    beforeEach(function () {
      preprocessor = new H.Preprocessor();
    });
    afterEach(function () {
      preprocessor = null;
    });

    it('expects array data', function () {
      expect(function () { preprocessor.setData({}); })
        .toThrow(new Error("Array expected."));
    });

    it('expects at least two dimensions', function () {
      var
        e = new Error('Data must contain at least two dimensions.');
      expect(function () { preprocessor.setData([]); }).toThrow(e);
      expect(function () { preprocessor.setData([[]]); }).toThrow(e);
    });

    it('expects each dimension to be an array', function () {
      expect(function () { preprocessor.setData([[], {}]); })
        .toThrow(new Error('Data dimensions must be arrays.'));
    });

    it('expects each dimension to have the same number of points', function () {
      expect(function () { preprocessor.setData([[], [1]]); })
        .toThrow(new Error('Data dimensions must contain the same number of points.'));
    });

    it('validates options data', function () {
      var
        options = { data : {} };
      expect(function () { new H.Preprocessor(options); })
        .toThrow(new Error("Array expected."));
    });
  });

  describe('Bounds', function () {

    var
      preprocessor;

    beforeEach(function () {
      var
        x = [],
        y = [],
        i;

      for (i = 0; i < 10; i++) {
        x.push(i);
        y.push(10 - 1 - i);
      }

      preprocessor = new Preprocessor({ data : [x, y] });
    });

    afterEach(function () {
      preprocessor = null;
    });

    it('bounds data', function () {
      preprocessor.bound(4, 6);
      expect(preprocessor.length()).toBe(3);
      expect(preprocessor.getData()).toEqual([
        [4, 5, 6],
        [5, 4, 3]
      ]);
    });

    it('makes empty data for bounds out of range', function () {
      preprocessor.bound(10, 12);
      expect(preprocessor.length()).toBe(0);
      expect(preprocessor.getData()).toEqual([[],[]]);
    });

    it('bounds from the beginning', function () {
      preprocessor.bound(0, 2);
      expect(preprocessor.length()).toBe(3);
      expect(preprocessor.getData()).toEqual([
        [0, 1, 2],
        [9, 8, 7]
      ]);
    });

    it('includes points outside the range if match not exact', function () {
      preprocessor.bound(3.5, 6.5);
      expect(preprocessor.length()).toBe(5);
      expect(preprocessor.getData()).toEqual([
        [3, 4, 5, 6, 7],
        [6, 5, 4, 3, 2]
      ]);
    });
  });

  describe('Subsample', function () {

    var
      length = 10,
      data, preprocessor;

    beforeEach(function () {
      var
        x = [],
        y = [],
        i;

      for (i = 0; i < length; i++) {
        x.push(i);
        y.push(10 - 1 - i);
      }

      data = [x, y];
      preprocessor = new Preprocessor({ data : data });
    });

    afterEach(function () {
      preprocessor = null;
    });

    it('subsamples data', function () {
      preprocessor.subsample(5);
      expect(preprocessor.length()).toBe(5);
      expect(preprocessor.getData()).toEqual([
        [0, 2, 4, 6, 9],
        [9, 7, 5, 3, 0]
      ]);
    });

    it('always includes endpoints', function () {
      var
        i, newData, newLength;
      for (i = 0; i < 10; i++) {

        preprocessor.setData(data);
        preprocessor.subsample(i);

        newData = preprocessor.getData();
        newLength = preprocessor.length();

        expect(newLength).toBeGreaterThan(1);
        expect(newData[0][0]).toBe(data[0][0]);
        expect(newData[1][0]).toBe(data[1][0]);
        expect(newData[0][newLength - 1]).toBe(data[0][length - 1]);
        expect(newData[1][newLength - 1]).toBe(data[1][length - 1]);
      }
    });

    it('length equals resolution when resolution 2 or greather', function () {
      var
        i;

      for (i = 2; i < length ; i++) {
        preprocessor.setData(data);
        preprocessor.subsample(i);
        expect(preprocessor.length()).toBe(i);
      }
    });

    it('does not subsample data not longer than resolution', function () {
      preprocessor.subsample(length);
      expect(preprocessor.length()).toBe(length);
      expect(preprocessor.getData()).toBe(data);
    });
  });

  describe('MinMaxSubsample', function () {
    var
      length = 100,
      data, preprocessor;

    beforeEach(function () {
      var
        x = [],
        y = [],
        i;

      for (i = 0; i < length; i++) {
        x.push(i);
        y.push(Math.sin(i/10));
      }

      data = [x, y];
      preprocessor = new Preprocessor({ data : data });
    });

    afterEach(function () {
      preprocessor = null;
    });

    it('subsamples data', function () {

      preprocessor.subsampleMinMax(10);

      var
        data = preprocessor.getData(),
        x = data[0],
        y = data[1];

      expect(Math.min.apply(Math, data[1])).toEqual(Math.min.apply(Math, y));
      expect(Math.max.apply(Math, data[1])).toEqual(Math.max.apply(Math, y));
    });
  });

  describe('Chaining', function  () {

    var
      preprocessor;

    beforeEach(function () {
      preprocessor = new Preprocessor({
        data : [[],[]]
      });
    });

    it('chains setData', function () {
      expect(preprocessor.setData([[],[]])).toBe(preprocessor);
    });

    it('chains bound', function () {
      expect(preprocessor.bound(0, 1)).toBe(preprocessor);
    });

    it('chains subsample', function () {
      expect(preprocessor.subsample(10)).toBe(preprocessor);
    });

    it('chains subsampleMinMax', function () {
      expect(preprocessor.subsampleMinMax(0, 1)).toBe(preprocessor);
    });
  });
});
<commit_msg>Added spec for reset.<commit_after>describe('Preprocessor', function () {
  var
    H = envision,
    Preprocessor = H.Preprocessor;

  it('defines preprocessor', function () {
    expect(H.Preprocessor).toBeDefined();
  });

  it('creates a preprocessor', function () {
    expect(new H.Preprocessor()).toBeDefined();
  });

  it('gets private data from options', function () {
    var
      data = [[],[]],
      options = { data : data },
      preprocessor = new H.Preprocessor(options);

    expect(preprocessor.getData()).toBe(data);
  });

  it('sets new private data', function () {

    var
      data = [[],[]],
      options = { data : [[], []] },
      preprocessor = new H.Preprocessor(options);

    expect(preprocessor.getData()).not.toBe(data);
    preprocessor.setData(data);
    expect(preprocessor.getData()).toBe(data);
  });

  it('calculates length', function () {
    var
      preprocessor = new Preprocessor({data : [[], []]});
    expect(preprocessor.length()).toBe(0);
    preprocessor.setData([[0], [1]]);
    expect(preprocessor.length()).toBe(1);
  });

  describe('Validation', function () {

    var
      preprocessor;

    beforeEach(function () {
      preprocessor = new H.Preprocessor();
    });
    afterEach(function () {
      preprocessor = null;
    });

    it('expects array data', function () {
      expect(function () { preprocessor.setData({}); })
        .toThrow(new Error("Array expected."));
    });

    it('expects at least two dimensions', function () {
      var
        e = new Error('Data must contain at least two dimensions.');
      expect(function () { preprocessor.setData([]); }).toThrow(e);
      expect(function () { preprocessor.setData([[]]); }).toThrow(e);
    });

    it('expects each dimension to be an array', function () {
      expect(function () { preprocessor.setData([[], {}]); })
        .toThrow(new Error('Data dimensions must be arrays.'));
    });

    it('expects each dimension to have the same number of points', function () {
      expect(function () { preprocessor.setData([[], [1]]); })
        .toThrow(new Error('Data dimensions must contain the same number of points.'));
    });

    it('validates options data', function () {
      var
        options = { data : {} };
      expect(function () { new H.Preprocessor(options); })
        .toThrow(new Error("Array expected."));
    });
  });

  describe('Bounds', function () {

    var
      preprocessor;

    beforeEach(function () {
      var
        x = [],
        y = [],
        i;

      for (i = 0; i < 10; i++) {
        x.push(i);
        y.push(10 - 1 - i);
      }

      preprocessor = new Preprocessor({ data : [x, y] });
    });

    afterEach(function () {
      preprocessor = null;
    });

    it('bounds data', function () {
      preprocessor.bound(4, 6);
      expect(preprocessor.length()).toBe(3);
      expect(preprocessor.getData()).toEqual([
        [4, 5, 6],
        [5, 4, 3]
      ]);
    });

    it('resets data', function () {

      var
        data = preprocessor.getData(),
        bounded = preprocessor.bound(4, 6).getData();

      preprocessor.reset();

      expect(bounded).not.toBe(data);
      expect(preprocessor.getData()).toBe(data);
    });

    it('makes empty data for bounds out of range', function () {
      preprocessor.bound(10, 12);
      expect(preprocessor.length()).toBe(0);
      expect(preprocessor.getData()).toEqual([[],[]]);
    });

    it('bounds from the beginning', function () {
      preprocessor.bound(0, 2);
      expect(preprocessor.length()).toBe(3);
      expect(preprocessor.getData()).toEqual([
        [0, 1, 2],
        [9, 8, 7]
      ]);
    });

    it('includes points outside the range if match not exact', function () {
      preprocessor.bound(3.5, 6.5);
      expect(preprocessor.length()).toBe(5);
      expect(preprocessor.getData()).toEqual([
        [3, 4, 5, 6, 7],
        [6, 5, 4, 3, 2]
      ]);
    });
  });

  describe('Subsample', function () {

    var
      length = 10,
      data, preprocessor;

    beforeEach(function () {
      var
        x = [],
        y = [],
        i;

      for (i = 0; i < length; i++) {
        x.push(i);
        y.push(10 - 1 - i);
      }

      data = [x, y];
      preprocessor = new Preprocessor({ data : data });
    });

    afterEach(function () {
      preprocessor = null;
    });

    it('subsamples data', function () {
      preprocessor.subsample(5);
      expect(preprocessor.length()).toBe(5);
      expect(preprocessor.getData()).toEqual([
        [0, 2, 4, 6, 9],
        [9, 7, 5, 3, 0]
      ]);
    });

    it('always includes endpoints', function () {
      var
        i, newData, newLength;
      for (i = 0; i < 10; i++) {

        preprocessor.setData(data);
        preprocessor.subsample(i);

        newData = preprocessor.getData();
        newLength = preprocessor.length();

        expect(newLength).toBeGreaterThan(1);
        expect(newData[0][0]).toBe(data[0][0]);
        expect(newData[1][0]).toBe(data[1][0]);
        expect(newData[0][newLength - 1]).toBe(data[0][length - 1]);
        expect(newData[1][newLength - 1]).toBe(data[1][length - 1]);
      }
    });

    it('length equals resolution when resolution 2 or greather', function () {
      var
        i;

      for (i = 2; i < length ; i++) {
        preprocessor.setData(data);
        preprocessor.subsample(i);
        expect(preprocessor.length()).toBe(i);
      }
    });

    it('does not subsample data not longer than resolution', function () {
      preprocessor.subsample(length);
      expect(preprocessor.length()).toBe(length);
      expect(preprocessor.getData()).toBe(data);
    });
  });

  describe('MinMaxSubsample', function () {
    var
      length = 100,
      data, preprocessor;

    beforeEach(function () {
      var
        x = [],
        y = [],
        i;

      for (i = 0; i < length; i++) {
        x.push(i);
        y.push(Math.sin(i/10));
      }

      data = [x, y];
      preprocessor = new Preprocessor({ data : data });
    });

    afterEach(function () {
      preprocessor = null;
    });

    it('subsamples data', function () {

      preprocessor.subsampleMinMax(10);

      var
        data = preprocessor.getData(),
        x = data[0],
        y = data[1];

      expect(Math.min.apply(Math, data[1])).toEqual(Math.min.apply(Math, y));
      expect(Math.max.apply(Math, data[1])).toEqual(Math.max.apply(Math, y));
    });
  });

  describe('Chaining', function  () {

    var
      preprocessor;

    beforeEach(function () {
      preprocessor = new Preprocessor({
        data : [[],[]]
      });
    });

    it('chains setData', function () {
      expect(preprocessor.setData([[],[]])).toBe(preprocessor);
    });

    it('chains reset', function () {
      expect(preprocessor.reset()).toBe(preprocessor);
    });

    it('chains bound', function () {
      expect(preprocessor.bound(0, 1)).toBe(preprocessor);
    });

    it('chains subsample', function () {
      expect(preprocessor.subsample(10)).toBe(preprocessor);
    });

    it('chains subsampleMinMax', function () {
      expect(preprocessor.subsampleMinMax(0, 1)).toBe(preprocessor);
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

// modules dependencies
var mongoat = require('../../index');

var _this;

// test insert method
describe('Insert', function () {
  // connect to db before all tests
  beforeAll(function (done) {
    _this = this;

    mongoat.MongoClient.connect('mongodb://localhost:27017/mongoatTest')
    .then(function (db) {
      db.dropDatabase();
      _this.testDb = db;
      _this.testCol = db.collection('Person.insert');
      _this.testCol.datetime(true);

      done();
    });
  });

  // close db after all tests
  afterAll(function (done) {
    _this.testCol.find()
    .toArray()
    .then(function (mongoArray) {
      expect(mongoArray.length).toBe(2);

      for (var i = 0; i < mongoArray.length; ++i) {
        expect(mongoArray[i].firstName).toBe('Yacine');
        expect(mongoArray[i].lastName).toBe('KHATAl');
        expect(mongoArray[i].age).toBe(25);
        expect(mongoArray[i].createdAt).toBeDefined();
        if (i > 0) {
          expect(mongoArray[i].email).toBe('khatal.yacine@gmail.com');
          expect(mongoArray[i].company).toBe('Dial Once');
        }
      }

      _this.testDb.dropDatabase();
      _this.testDb.close();
      done();
    });
  });

  // test insert without hooks
  it('should insert new document to Person collection',
  function (done) {
    _this.testCol.insert({
      firstName: 'Yacine',
      lastName: 'KHATAl',
      age: 25
    }).then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(typeof mongObject.result).toBe('object');
      expect(mongObject.result.ok).toBe(1);
      expect(mongObject.result.n).toBe(1);
      done();
    });
  });

  // test with multiple before and after insert hooks
  it('should insert new document to Person collection and handle before and after insert hooks',
  function (done) {
    // add before insert hooks
    _this.testCol.before('insert', function (object) {
      expect(object.firstName).toBe('Yacine');
      expect(object.lastName).toBe('KHATAl');
      expect(object.age).toBe(25);
      object.email = 'khatal.yacine@gmail.com';
      return object;
    });

    _this.testCol.before('insert', function (object) {
      expect(object.firstName).toBe('Yacine');
      expect(object.lastName).toBe('KHATAl');
      expect(object.age).toBe(25);
      expect(object.email).toBe('khatal.yacine@gmail.com');
      object.company = 'Dial Once';
      return object;
    });

    // add after insert hooks
    _this.testCol.after('insert', function (object) {
      expect(object.firstName).toBe('Yacine');
      expect(object.lastName).toBe('KHATAl');
      expect(object.age).toBe(25);
      expect(object.email).toBe('khatal.yacine@gmail.com');
      expect(object.company).toBe('Dial Once');
      return object;
    });

    _this.testCol.after('insert', function (object) {
      expect(object.firstName).toBe('Yacine');
      expect(object.lastName).toBe('KHATAl');
      expect(object.age).toBe(25);
      expect(object.email).toBe('khatal.yacine@gmail.com');
      expect(object.company).toBe('Dial Once');
      return object;
    });

    _this.testCol.insert({
      firstName: 'Yacine',
      lastName: 'KHATAl',
      age: 25
    }).then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(typeof mongObject.result).toBe('object');
      expect(mongObject.result.ok).toBe(1);
      expect(mongObject.result.n).toBe(1);

      done();
    });
  });
});
<commit_msg>Update should message<commit_after>'use strict';

// modules dependencies
var mongoat = require('../../index');

var _this;

// test insert method
describe('Insert', function () {
  // connect to db before all tests
  beforeAll(function (done) {
    _this = this;

    mongoat.MongoClient.connect('mongodb://localhost:27017/mongoatTest')
    .then(function (db) {
      db.dropDatabase();
      _this.testDb = db;
      _this.testCol = db.collection('Person.insert');
      _this.testCol.datetime(true);

      done();
    });
  });

  // close db after all tests
  afterAll(function (done) {
    _this.testCol.find()
    .toArray()
    .then(function (mongoArray) {
      expect(mongoArray.length).toBe(2);

      for (var i = 0; i < mongoArray.length; ++i) {
        expect(mongoArray[i].firstName).toBe('Yacine');
        expect(mongoArray[i].lastName).toBe('KHATAl');
        expect(mongoArray[i].age).toBe(25);
        expect(mongoArray[i].createdAt).toBeDefined();
        if (i > 0) {
          expect(mongoArray[i].email).toBe('khatal.yacine@gmail.com');
          expect(mongoArray[i].company).toBe('Dial Once');
        }
      }

      _this.testDb.dropDatabase();
      _this.testDb.close();
      done();
    });
  });

  // test insert without hooks
  it('should insert new document to collection',
  function (done) {
    _this.testCol.insert({
      firstName: 'Yacine',
      lastName: 'KHATAl',
      age: 25
    }).then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(typeof mongObject.result).toBe('object');
      expect(mongObject.result.ok).toBe(1);
      expect(mongObject.result.n).toBe(1);
      done();
    });
  });

  // test with multiple before and after insert hooks
  it('should insert new document to collection and handle before and after insert hooks',
  function (done) {
    // add before insert hooks
    _this.testCol.before('insert', function (object) {
      expect(object.firstName).toBe('Yacine');
      expect(object.lastName).toBe('KHATAl');
      expect(object.age).toBe(25);
      object.email = 'khatal.yacine@gmail.com';
      return object;
    });

    _this.testCol.before('insert', function (object) {
      expect(object.firstName).toBe('Yacine');
      expect(object.lastName).toBe('KHATAl');
      expect(object.age).toBe(25);
      expect(object.email).toBe('khatal.yacine@gmail.com');
      object.company = 'Dial Once';
      return object;
    });

    // add after insert hooks
    _this.testCol.after('insert', function (object) {
      expect(object.firstName).toBe('Yacine');
      expect(object.lastName).toBe('KHATAl');
      expect(object.age).toBe(25);
      expect(object.email).toBe('khatal.yacine@gmail.com');
      expect(object.company).toBe('Dial Once');
      return object;
    });

    _this.testCol.after('insert', function (object) {
      expect(object.firstName).toBe('Yacine');
      expect(object.lastName).toBe('KHATAl');
      expect(object.age).toBe(25);
      expect(object.email).toBe('khatal.yacine@gmail.com');
      expect(object.company).toBe('Dial Once');
      return object;
    });

    _this.testCol.insert({
      firstName: 'Yacine',
      lastName: 'KHATAl',
      age: 25
    }).then(function (mongObject) {
      expect(typeof mongObject).toBe('object');
      expect(typeof mongObject.result).toBe('object');
      expect(mongObject.result.ok).toBe(1);
      expect(mongObject.result.n).toBe(1);

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


<commit_before>$jin.klass({ '$jin.file.type.viewTree': [ '$jin.file.type.tree' ] })

$jin.method({ '$jin.file.type.viewTree.ext': function( ){
	this['$jin.file.type.tree.ext']
	return '.view.tree'
}})

$jin.atom1.prop({ '$jin.file.type.viewTree..dependList': {
	resolves: [ '$jin.file.base..dependList' ],
	pull: function( ){
		var depends = {
			//'jin2/prop' : 0,
		}

		String( this.content() )
		.replace
		(   /[@$]([a-z][a-z0-9]+(?:_[a-z0-9]+)+)/ig
		,   function( str, path ){
				depends[ path.replace( /[_]/g, '/' ) ] = 0
			}
		)

		return depends
	}
}})

$jin.atom1.prop.list({ '$jin.file.type.viewTree..jsFiles': {
	resolves: [ '$jin.file.base..jsFiles' ],
	pull: function( prev ){
		var target = this.parent().buildFile( this.name(), {}, 'ts' )
		var tree = $jin_tree2.fromString( String( this.content() ) , this.relate() )

		var content = ''
		tree.childs.forEach( function( def ) {
			if( !/^\$\w+$/.test( def.type ) ) return
			var parent = def.childs[0].childs[0]

			var members = {}
			var fields = {}
			var attrs = {}
			var events = {}
			parent.childs.forEach( function( param ) { addProp( param , '' ) } )
            function addProp( param , prefix ) {
				if( !param.type || /^-/.test( param.type ) ) return

				switch( param.type[0] ) {
					default :
						var firstVal = param.childs[0]
						if( firstVal ) {
							switch( firstVal.type[0] ) {
								case ':' :
                                    switch( firstVal.childs[0].type[0] ) {
                                        case '$' : // factory
                                            var overs = firstVal.childs[0].childs.map( function( over ) {
                                                if( !/^\w+$/.test( over.type ) ) return ''
                                                switch( over.childs[0].type ) {
                                                    case '<' :
                                                        addProp( over.childs[0].childs[0] , prefix + param.type + '_' )
                                                        return '\t\tview.' + over.type + ' = () => this.' + over.childs[0].childs[0].type + '()\n'
                                                    case ':' :
                                                        return '\t\tview.' + over.type + ' = () => new $'+'jin2_atom( () => ( ' + JSON.stringify( over.childs[0].childs[0] ) + ' ) )\n'
                                                    default :
        												throw new Error( 'view.tree syntax error: ' + over + over.uri )
                                                }
                                            } )
                                            members[ param.type ] = '\t@ $'+'jin2_grab ' + param.type +'() {\n\t\tvar view = new ' + firstVal.childs[0].type + '\n' + overs.join('') + '\t\treturn view\n\t}\n'
                                            return
                                        default :
                                            members[ param.type ] = '\t@ $'+'jin2_grab ' + param.type +'() { return new $'+'jin2_atom( () => (' + JSON.stringify( firstVal.childs[0] ) + ') ) }\n'
                                            return
                                    }
                                case '<': // binding
                                    if( param.childs.length === 1 ) {
                                        addProp( param.childs[0].childs[0] , prefix + param.type + '_' )
                                        members[ param.type ] = '\t' + param.type +'() { return this.' + param.childs[0].childs[0].type + '() }\n'
                                        return
                                    }
								default :
									var items = []
                                    param.childs.forEach( function( item ) {
										switch( item.type ) {
											case '<' :
												addProp( item.childs[0] , prefix + param.type + '_' )
												items.push( 'this.' + item.childs[0].type + '().get()' )
                                                return
											case '' :
												items.push( JSON.stringify( item.value ) )
                                                return
											case '-' :
												return
											default :
												throw new Error( 'view.tree syntax error: ' + item + item.uri )
										}
									} )
									members[ param.type ] = '\t@ $'+'jin2_grab ' + param.type +'() { return new $'+'jin2_atom( () => [ ' + items.join(' , ') + ' ] ) }\n'
									return
							}
						} else {
							//members[ param.type ] = members[ param.type ] || null
						}
				}
			}

			var paths = Object.keys( fields )
			if( paths.length ) members[ 'field' ] = '\tfield(){ return {\n' + paths.map( function( path ) {
				return '\t\t' + JSON.stringify( path ) + ': ' + fields[ path ] + ',\n'
			} ).join('') + '\t} }\n'

			var attrNames = Object.keys( attrs )
			if( attrNames.length ) members[ 'attr' ] = '\tattr() { return {\n' + attrNames.map( function( name ) {
				return '\t\t' + JSON.stringify( name ) + ': ' + attrs[ name ] + ',\n'
			} ).join('') + '\t} }\n'

			var eventNames = Object.keys( events )
			if( eventNames.length ) members[ 'event' ] = '\tevent() { return {\n' + eventNames.map( function( name ) {
				return '\t\t' + JSON.stringify( name ) + ': ' + events[ name ] + ',\n'
			} ).join('') + '\t} }\n'

			var body = Object.keys( members ).map( function( name ) {
				return members[ name ] || '\t' + name +'() {\n\t\treturn { get : () => null , set : next => null }\n\t}\n'
			}).join( '' )

			var classes = 'module $'+'mol { @$'+'mol_replace export class ' + def.type + ' extends ' + parent.type + ' {\n' + body + '} }\n'

			content += classes + '\n'
		})

		target.content( content )

		if( prev ) $jin.log( target.relate() )

		return [ target ]
	}
}})
<commit_msg>no global deps<commit_after>$jin.klass({ '$jin.file.type.viewTree': [ '$jin.file.type.tree' ] })

$jin.method({ '$jin.file.type.viewTree.ext': function( ){
	this['$jin.file.type.tree.ext']
	return '.view.tree'
}})

$jin.atom1.prop({ '$jin.file.type.viewTree..dependList': {
	resolves: [ '$jin.file.base..dependList' ],
	pull: function( ){
		var depends = {
			//'jin2/prop' : 0,
		}

		String( this.content() )
		.replace
		(   /[@$]([a-z][a-z0-9]+(?:_[a-z0-9]+)+)/ig
		,   function( str, path ){
				depends[ path.replace( /[_]/g, '/' ) ] = 0
			}
		)

		return depends
	}
}})

$jin.atom1.prop.list({ '$jin.file.type.viewTree..jsFiles': {
	resolves: [ '$jin.file.base..jsFiles' ],
	pull: function( prev ){
		var target = this.parent().buildFile( this.name(), {}, 'ts' )
		var tree = $jin_tree2.fromString( String( this.content() ) , this.relate() )

		var content = ''
		tree.childs.forEach( function( def ) {
			if( !/^\$\w+$/.test( def.type ) ) return
			var parent = def.childs[0].childs[0]

			var members = {}
			parent.childs.forEach( function( param ) { addProp( param , '' ) } )
            function addProp( param , prefix ) {
				if( !param.type || /^-/.test( param.type ) ) return

				switch( param.type[0] ) {
					default :
						var firstVal = param.childs[0]
						if( firstVal ) {
							switch( firstVal.type[0] ) {
								case ':' :
                                    switch( firstVal.childs[0].type[0] ) {
                                        case '$' : // factory
                                            var overs = firstVal.childs[0].childs.map( function( over ) {
                                                if( !/^\w+$/.test( over.type ) ) return ''
                                                switch( over.childs[0].type ) {
                                                    case '<' :
                                                        addProp( over.childs[0].childs[0] , prefix + param.type + '_' )
                                                        return '\t\tview.' + over.type + ' = () => this.' + over.childs[0].childs[0].type + '()\n'
                                                    case ':' :
                                                        return '\t\tview.' + over.type + ' = () => this.prop( () => ( ' + JSON.stringify( over.childs[0].childs[0] ) + ' ) )\n'
                                                    default :
        												throw new Error( 'view.tree syntax error: ' + over + over.uri )
                                                }
                                            } )
                                            members[ param.type ] = '\t@ $'+'jin2_grab ' + param.type +'() {\n\t\tvar view = new ' + firstVal.childs[0].type + '\n' + overs.join('') + '\t\treturn view\n\t}\n'
                                            return
                                        default :
                                            members[ param.type ] = '\t@ $'+'jin2_grab ' + param.type +'() { return this.prop( () => (' + JSON.stringify( firstVal.childs[0] ) + ') ) }\n'
                                            return
                                    }
                                case '<': // binding
                                    if( param.childs.length === 1 ) {
                                        addProp( param.childs[0].childs[0] , prefix + param.type + '_' )
                                        members[ param.type ] = '\t' + param.type +'() { return this.' + param.childs[0].childs[0].type + '() }\n'
                                        return
                                    }
								default :
									var items = []
                                    param.childs.forEach( function( item ) {
										switch( item.type ) {
											case '<' :
												addProp( item.childs[0] , prefix + param.type + '_' )
												items.push( 'this.' + item.childs[0].type + '().get()' )
                                                return
											case '' :
												items.push( JSON.stringify( item.value ) )
                                                return
											case '-' :
												return
											default :
												throw new Error( 'view.tree syntax error: ' + item + item.uri )
										}
									} )
									members[ param.type ] = '\t@ $'+'jin2_grab ' + param.type +'() { return this.prop( () => [ ' + items.join(' , ') + ' ] ) }\n'
									return
							}
						} else {
							//members[ param.type ] = members[ param.type ] || null
						}
				}
			}

			var body = Object.keys( members ).map( function( name ) {
				return members[ name ] || '\t' + name +'() { return this.prop( null ) }\n\t}\n'
			}).join( '' )

			var classes = 'module $'+'mol { @$'+'mol_replace export class ' + def.type + ' extends ' + parent.type + ' {\n' + body + '} }\n'

			content += classes + '\n'
		})

		target.content( content )

		if( prev ) $jin.log( target.relate() )

		return [ target ]
	}
}})
<|endoftext|>