<commit_before>import React from 'react/addons.js';
import CodeEditor from './editors/CodeEditor.js';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon.js';
import TextBox from './editors/TextBox.js';
import Metaform from './MetaForm.js';
import metadataProvider from '../lib/metadataProvider.js';
import Alert from 'react-bootstrap/lib/Alert.js';
import CheckBox from './editors/CheckBox.js';
import Lookup from './editors/Lookup.js';
import DefaultComponentFactory from '../lib/DefaultComponentFactory.js';
import liveSchemaEditorPresetProvider from './LiveSchemaEditorPresetProvider.js';
import _ from 'underscore';

let presetsConfig = liveSchemaEditorPresetProvider.getPresets();
const LiveSchemaEditor = React.createClass({

    getInitialState: function () {
        let initialPreset = 'textbox';
        let presetConfig = _.find(presetsConfig, p => p.value == initialPreset);
        if (!presetConfig) {
            throw Error(`Could not find the given preset`);
        }
        return {
            schema: {},
            entityName: presetConfig.entityName,
            layoutName: presetConfig.layoutName,
            model: {},
            title: presetConfig.title,
            autoUpdateMetaform: true,
            presets: presetsConfig,
            selectedPreset: initialPreset,
            text: presetConfig.code
        };
    },

    onPresetChange: function (event) {
        let preset = event.value;
        let updatedState;
        if (!preset) {
            updatedState = React.addons.update(this.state, {selectedPreset: {$set: preset}});
            this.setState(updatedState);
            return;
        }
        let presetConfig = _.find(presetsConfig, p => p.value == preset);
        if (!presetConfig) {
            throw new Error(`Could not find the given preset`);
        }
        updatedState = _.extend({}, this.state);
        updatedState.selectedPreset = preset;
        updatedState.title = presetConfig.title;
        updatedState.entityName = presetConfig.entityName;
        updatedState.layoutName = presetConfig.layoutName;
        updatedState.text = presetConfig.code;
        this.setState(updatedState, () => {
            this.resetMetaform();
        });
    },

    onCodeChange: function (event) {
        let updatedState = React.addons.update(this.state, {text: {$set: event.value}});
        this.setState(updatedState);
        if (this.state.autoUpdateMetaform) {
            this.resetMetaform();
        }
    },

    onMainEntityNameChanged: function (event) {
        let updatedState = React.addons.update(this.state, {entityName: {$set: event.value}});
        this.setState(updatedState);
    },

    onMainLayoutNameChanged: function (event) {
        let updatedState = React.addons.update(this.state, {layoutName: {$set: event.value}});
        this.setState(updatedState);
    },

    onFormTitleChanged: function (event) {
        let updatedState = React.addons.update(this.state, {title: {$set: event.value}});
        this.setState(updatedState);
    },

    resetMetaform: function () {
        if (this.refs.mf) {
            this.refs.mf.resetState();
        }
    },

    /**
     * Returns the schema object based on the text
     */
    buildMetaform: function () {
        try {
            let schema = eval('(' + this.state.text + ')');

            return <Metaform
                schema={schema}
                ref="mf"
                entityName={this.state.entityName}
                layoutName={this.state.layoutName}
                componentFactory={DefaultComponentFactory}
                model={this.state.model}
                title={this.state.title}
                schema={schema}
                entityName={this.state.entityName}
                layoutName={this.state.layoutName}
                />;
        }
        catch (ex) {
            return <Alert bsStyle='danger' onDismiss={this.handleAlertDismiss}>

Oh snap! The schema is not valid.

Detailed information: {ex.message}

                    Change the schema
                     or
                    <Button onClick={() => this.forceUpdate()}>try again</Button>

            </Alert>
        }
    },

    render: function () {
        let _this = this;
        return

React-metaform demo

                            <Lookup name="presets" displayName="Presets" options={this.state.presets}
                                    onChange={this.onPresetChange} value={this.state.selectedPreset}/>

                            <TextBox displayName="Main entity name" value={this.state.entityName}
                                     onChange={this.onMainEntityNameChanged}/>

                            <TextBox displayName="Main layout name" value={this.state.layoutName}
                                     onChange={this.onMainLayoutNameChanged}/>

                            <TextBox displayName="Form title" value={this.state.title}
                                     onChange={this.onFormTitleChanged}/>

                    <CodeEditor
                        displayName="Schema"
                        onChange={this.onCodeChange}
                        name="liveSchemaEditor"
                        value={this.state.text}
                        />

                        {this.buildMetaform()}

            :

;
    }
});

export default LiveSchemaEditor;
<commit_msg>Making the MetaForm to trigger an error when the entity or the layoutname is not valid<commit_after>import React from 'react/addons.js';
import CodeEditor from './editors/CodeEditor.js';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon.js';
import TextBox from './editors/TextBox.js';
import Metaform from './MetaForm.js';
import metadataProvider from '../lib/metadataProvider.js';
import Alert from 'react-bootstrap/lib/Alert.js';
import CheckBox from './editors/CheckBox.js';
import Lookup from './editors/Lookup.js';
import DefaultComponentFactory from '../lib/DefaultComponentFactory.js';
import liveSchemaEditorPresetProvider from './LiveSchemaEditorPresetProvider.js';
import _ from 'underscore';

let presetsConfig = liveSchemaEditorPresetProvider.getPresets();
const LiveSchemaEditor = React.createClass({

    getInitialState: function () {
        let initialPreset = 'textbox';
        let presetConfig = _.find(presetsConfig, p => p.value == initialPreset);
        if (!presetConfig) {
            throw Error(`Could not find the given preset`);
        }
        return {
            schema: {},
            entityName: presetConfig.entityName,
            layoutName: presetConfig.layoutName,
            model: {},
            title: presetConfig.title,
            autoUpdateMetaform: true,
            presets: presetsConfig,
            selectedPreset: initialPreset,
            text: presetConfig.code
        };
    },

    onPresetChange: function (event) {
        let preset = event.value;
        let updatedState;
        if (!preset) {
            updatedState = React.addons.update(this.state, {selectedPreset: {$set: preset}});
            this.setState(updatedState);
            return;
        }
        let presetConfig = _.find(presetsConfig, p => p.value == preset);
        if (!presetConfig) {
            throw new Error(`Could not find the given preset`);
        }
        updatedState = _.extend({}, this.state);
        updatedState.selectedPreset = preset;
        updatedState.title = presetConfig.title;
        updatedState.entityName = presetConfig.entityName;
        updatedState.layoutName = presetConfig.layoutName;
        updatedState.text = presetConfig.code;
        this.setState(updatedState, () => {
            this.resetMetaform();
        });
    },

    onCodeChange: function (event) {
        let updatedState = React.addons.update(this.state, {text: {$set: event.value}});
        this.setState(updatedState);
        if (this.state.autoUpdateMetaform) {
            this.resetMetaform();
        }
    },

    onMainEntityNameChanged: function (event) {
        let updatedState = React.addons.update(this.state, {entityName: {$set: event.value}});
        this.setState(updatedState);
    },

    onMainLayoutNameChanged: function (event) {
        let updatedState = React.addons.update(this.state, {layoutName: {$set: event.value}});
        this.setState(updatedState);
    },

    onFormTitleChanged: function (event) {
        let updatedState = React.addons.update(this.state, {title: {$set: event.value}});
        this.setState(updatedState);
    },

    resetMetaform: function () {
        if (this.refs.mf) {
            this.refs.mf.resetState();
        }
    },

    /**
     * Returns the schema object based on the text
     */
    buildMetaform: function () {
        try {
            let schema = eval('(' + this.state.text + ')');

            // the only reason why I'm getting this here, is so it's going to trigger an exception
            // when the entityName and/or the layoutName is not valid
            let schemaAndLayout = metadataProvider.getEntityAndLayout(schema, this.state.entityName, this.state.layoutName);

            return <Metaform
                schema={schema}
                ref="mf"
                entityName={this.state.entityName}
                layoutName={this.state.layoutName}
                componentFactory={DefaultComponentFactory}
                model={this.state.model}
                title={this.state.title}
                schema={schema}
                entityName={this.state.entityName}
                layoutName={this.state.layoutName}
                />;
        }
        catch (ex) {
            return <Alert bsStyle='danger' onDismiss={this.handleAlertDismiss}>

Oh snap! The schema is not valid.

Detailed information: {ex.message}

                    Change the schema
                     or
                    <Button onClick={() => this.forceUpdate()}>try again</Button>

            </Alert>
        }
    },

    render: function () {
        let _this = this;
        return

React-metaform demo

                            <Lookup name="presets" displayName="Presets" options={this.state.presets}
                                    onChange={this.onPresetChange} value={this.state.selectedPreset}/>

                            <TextBox displayName="Main entity name" value={this.state.entityName}
                                     onChange={this.onMainEntityNameChanged}/>

                            <TextBox displayName="Main layout name" value={this.state.layoutName}
                                     onChange={this.onMainLayoutNameChanged}/>

                            <TextBox displayName="Form title" value={this.state.title}
                                     onChange={this.onFormTitleChanged}/>

                    <CodeEditor
                        displayName="Schema"
                        onChange={this.onCodeChange}
                        name="liveSchemaEditor"
                        value={this.state.text}
                        />

                        {this.buildMetaform()}

            :

;
    }
});

export default LiveSchemaEditor;
<|endoftext|>


<commit_before>function Post (opts) {
  for (var keys in opts) {
    this[keys] = opts[keys];
  }
}

Post.allPosts = [];

Post.prototype.toHtml = function(){
  var $templateScript = $('#postsTemplate').html();
  var compiledTemplate = Handlebars.compile($templateScript);
  return compiledTemplate(this);
};

Post.loadAll = function(inputData) {
  inputData.sort(function(a,b) {
    return (new Date(b.datePublished)) - (new Date(a.datePublished));
  })
  .forEach(function(ele) {
    Post.allPosts.push(new Post(ele));
    // console.log(ele);
  });
};

Post.fetchAll = function() {
  if (localStorage.postsJSON){
    Posts.loadAll(JSON.parse(postsJSON));
    postsViewer.renderToPage();
  }else{
    $.getJSON('data/posts.json', function(postsJSON){
      Post.loadAll(postsJSON);
      localStorage.setItem('posts', JSON.stringify(postsJSON));
      postsViewer.renderToPage();
    });
  }
};

/* Great work so far! STRETCH GOAL TIME!? Our main goal in this part of the
   lab will be saving the eTag located in Headers, to see if it's been updated:

  Article.fetchAll = function() {
    if (localStorage.hackerIpsum) {
       Let's make a request to get the eTag (hint: what method on which
        object could we use to find the eTag?

    } else {}
  }
*/
<commit_msg>playing around with assignment. storing changes.<commit_after>function Post (opts) {
  for (var keys in opts) {
    this[keys] = opts[keys];
  }
}

Post.allPosts = [];

Post.prototype.toHtml = function(){
  var $templateScript = $('#postsTemplate').html();
  var compiledTemplate = Handlebars.compile($templateScript);
  return compiledTemplate(this);
};

Post.loadAll = function(inputData) {
  inputData.sort(function(a,b) {
    return (new Date(b.datePublished)) - (new Date(a.datePublished));
  })
  .forEach(function(ele) {
    Post.allPosts.push(new Post(ele));
    // console.log(ele);
  });
};

Post.fetchAll = function() {
  if (localStorage.postsJSON){
    Posts.loadAll(JSON.parse(postsJSON));
    postsViewer.renderToPage();
  }else{
    $.getJSON('data/posts.json', function(postsJSON){
      Post.loadAll(postsJSON);
      localStorage.setItem('posts', JSON.stringify(postsJSON));
      postsViewer.renderToPage();
    });
  }
};

/* Great work so far! STRETCH GOAL TIME!? Our main goal in this part of the
   lab will be saving the eTag located in Headers, to see if it's been updated:

  Article.fetchAll = function() {
    if (localStorage.hackerIpsum) {
       Let's make a request to get the eTag (hint: what method on which object could we use to find the eTag?
       $.getJSON('data')

    } else {}
  }
*/
<|endoftext|>


<commit_before>/**
*
*	Schedule Dialog creation methods.
*
*/

//dateText mm-dd-yy
function startDpSelect(dateText, inst) {
	var time, date;

	time = dateText.split("-");
	date = new Date(time[0], time[1] - 1, time[2]);

	$("#add_show_end_date").datepicker("option", "minDate", date);
    $('input[name^="add_show_rebroadcast_absolute_date"]').datepicker("option", "minDate", date);
    if (inst.input)
        inst.input.trigger('change');
}

function endDpSelect(dateText, inst) {
	var time, date;

	time = dateText.split("-");
	date = new Date(time[0], time[1] - 1, time[2]);

	//$("#add_show_start_date").datepicker( "option", "maxDate", date);
	if (inst.input)
        inst.input.trigger('change');
}

function createDateInput(el, onSelect) {
	var date;

	el.datepicker({
			minDate: new Date(),
			onSelect: onSelect,
			dateFormat: 'yy-mm-dd'
		});
}

function autoSelect(event, ui) {

	$("#add_show_hosts-"+ui.item.value).attr("checked", "checked");
	event.preventDefault();
}

function findHosts(request, callback) {
	var search, url;

	url = "/User/get-hosts";
	search = request.term;

	$.post(url,
		{format: "json", term: search},

		function(json) {
			callback(json.hosts);
		});

}

function beginEditShow(data){
    $("#add-show-form")
        .empty()
        .append(data.newForm);

    removeAddShowButton();
    setAddShowEvents();
    openAddShowForm();
}

function setAddShowEvents() {

    var form = $("#add-show-form");

	form.find("h3").click(function(){
        $(this).next().toggle();
    });

    if(!form.find("#add_show_repeats").attr('checked')) {
        form.find("#schedule-show-when > fieldset:last").hide();
        $("#add_show_rebroadcast_relative").hide();
    }
    else {
        $("#add_show_rebroadcast_absolute").hide();
    }

    if(!form.find("#add_show_record").attr('checked')) {
        form.find("#add_show_rebroadcast").hide();
    }

    if(!form.find("#add_show_rebroadcast").attr('checked')) {
        form.find("#schedule-record-rebroadcast > fieldset:not(:first-child)").hide();
    }

    form.find("#add_show_repeats").click(function(){
        $(this).blur();
        form.find("#schedule-show-when > fieldset:last").toggle();

        //must switch rebroadcast displays
        if(form.find("#add_show_rebroadcast").attr('checked')) {

            if($(this).attr('checked')){
                form.find("#add_show_rebroadcast_absolute").hide();
                form.find("#add_show_rebroadcast_relative").show();
            }
            else {
                form.find("#add_show_rebroadcast_absolute").show();
                form.find("#add_show_rebroadcast_relative").hide();
            }
        }
    });

    form.find("#add_show_record").click(function(){
        $(this).blur();
        form.find("#add_show_rebroadcast").toggle();

        //uncheck rebroadcast checkbox
        form.find("#add_show_rebroadcast").attr('checked', false);

        //hide rebroadcast options
        form.find("#schedule-record-rebroadcast > fieldset:not(:first-child)").hide();
    });

    form.find("#add_show_rebroadcast").click(function(){
        $(this).blur();
        if(form.find("#add_show_record").attr('checked')){
	        if($(this).attr('checked') && !form.find("#add_show_repeats").attr('checked')) {
	            form.find("#add_show_rebroadcast_absolute").show();
	        }
	        else if($(this).attr('checked') && form.find("#add_show_repeats").attr('checked')) {
	            form.find("#add_show_rebroadcast_relative").show();
	        }
	        else {
	            form.find("#schedule-record-rebroadcast > fieldset:not(:first-child)").hide();
	        }
    	}
    });

    form.find("#add_show_repeat_type").change(function(){
        if($(this).val() == 2) {
            form.find("#add_show_day_check-label, #add_show_day_check-element").hide();
        }
        else {
            form.find("#add_show_day_check-label, #add_show_day_check-element").show();
        }
    });

    form.find("#add_show_day_check-label").addClass("block-display");
    form.find("#add_show_day_check-element").addClass("block-display clearfix");
    form.find("#add_show_day_check-element label").addClass("wrapp-label");
    form.find("#add_show_day_check-element br").remove();

    function endDateVisibility(){
        if(form.find("#add_show_no_end").is(':checked')){
            form.find("#add_show_end_date").hide();
        } else {
            form.find("#add_show_end_date").show();
        }
    }
    endDateVisibility();
    form.find("#add_show_no_end").click(endDateVisibility);

	createDateInput(form.find("#add_show_start_date"), startDpSelect);
	createDateInput(form.find("#add_show_end_date_no_repeat"), endDpSelect);
	createDateInput(form.find("#add_show_end_date"), endDpSelect);

    form.find("#add_show_start_time").timepicker({
        amPmText: ['', ''],
        defaultTime: '00:00'
    });
    form.find("#add_show_end_time").timepicker({
        amPmText: ['', '']
    });

    form.find('input[name^="add_show_rebroadcast_date_absolute"]').datepicker({
		minDate: new Date(),
		dateFormat: 'yy-mm-dd'
	});
    form.find('input[name^="add_show_rebroadcast_time"]').timepicker({
        amPmText: ['', ''],
        defaultTime: ''
    });

    form.find(".add_absolute_rebroadcast_day").click(function(){
        var li = $(this).parent().find("ul.formrow-repeat > li:visible:last").next();

        li.show();
        li = li.next();
        if(li.length === 0) {
            $(this).hide();
        }
    });

    form.find('a[id^="remove_rebroadcast"]').click(function(){
        var list = $(this).parent().parent();
        var li_num = $(this).parent().index();
        var num = list.find("li").length;
        var count = num - li_num;

        var curr = $(this).parent();
        var next = curr.next();

        for(var i=0; i<=count; i++) {
            var date = next.find('[name^="add_show_rebroadcast_date"]').val();
            curr.find('[name^="add_show_rebroadcast_date"]').val(date);
            var time = next.find('[name^="add_show_rebroadcast_time"]').val();
            curr.find('[name^="add_show_rebroadcast_time"]').val(time);

            curr = next;
            next = curr.next();
        }

        list.find("li:visible:last")
                .find('[name^="add_show_rebroadcast_date"]')
                    .val('')
                .end()
                .find('[name^="add_show_rebroadcast_time"]')
                    .val('')
                .end()
            .hide();

        list.next().show();
    });

	form.find("#add_show_hosts_autocomplete").autocomplete({
		source: findHosts,
		select: autoSelect,
        delay: 200
	});

	form.find("#schedule-show-style input").ColorPicker({
        onChange: function (hsb, hex, rgb, el) {
		    $(el).val(hex);
	    },
		onSubmit: function(hsb, hex, rgb, el) {
			$(el).val(hex);
			$(el).ColorPickerHide();
		},
		onBeforeShow: function () {
			$(this).ColorPickerSetColor(this.value);
		}
	});

    form.find("#add-show-close")
		.click(function(event){
            event.stopPropagation();
            event.preventDefault();

            $("#schedule_calendar").removeAttr("style")
                .fullCalendar('render');

			$("#add-show-form").hide();
            $.get("/Schedule/get-form", {format:"json"}, function(json){
                $("#add-show-form")
                    .empty()
                    .append(json.form);

                setAddShowEvents();
            });
            makeAddShowButton();
		});

	form.find(".add-show-submit")
		.click(function(event){
            var addShowButton = $(this);
            if (!addShowButton.hasClass("disabled")){
                addShowButton.addClass("disabled");
            }
            else {
                return;
            }

            event.preventDefault();

			var data = $("form").serializeArray();

            var hosts = $('#add_show_hosts-element input').map(function() {
                if($(this).attr("checked")) {
                    return $(this).val();
                }
            }).get();

            var days = $('#add_show_day_check-element input').map(function() {
                if($(this).attr("checked")) {
                    return $(this).val();
                }
            }).get();

            var start_date = $("#add_show_start_date").val();
            var end_date = $("#add_show_end_date").val();

            $.post("/Schedule/add-show", {format: "json", data: data, hosts: hosts, days: days}, function(json){
                addShowButton.removeClass("disabled");
                if(json.form) {
                    $("#add-show-form")
                        .empty()
                        .append(json.form);

                    setAddShowEvents();

                    $("#add_show_end_date").val(end_date);
                    $("#add_show_start_date").val(start_date);
                    showErrorSections();
                }
                else {
                     $("#add-show-form")
                        .empty()
                        .append(json.newForm);

                    setAddShowEvents();
                    scheduleRefetchEvents();
                }
            });
		});

	// when start date/time changes, set end date/time to start date/time+1 hr
	$('#add_show_start_date, #add_show_start_time').change(function(){
		var startDate = $('#add_show_start_date').val().split('-');
		var startTime = $('#add_show_start_time').val().split(':');
        var startDateTime = new Date(startDate[0], parseInt(startDate[1], 10)-1, startDate[2], startTime[0], startTime[1], 0, 0);

		var endDate = $('#add_show_end_date_no_repeat').val().split('-');
		var endTime = $('#add_show_end_time').val().split(':');
        var endDateTime = new Date(endDate[0], parseInt(endDate[1], 10)-1, endDate[2], endTime[0], endTime[1], 0, 0);

		if(startDateTime.getTime() > endDateTime.getTime()){
		    var duration = $('#add_show_duration').val();
	        // parse duration
		    var time = 0;
		    var info = duration.split(' ');
		    var h = parseInt(info[0], 10);
		    time += h * 60 * 60* 1000;
		    if(info.length >1 && $.trim(info[1]) !== ''){
		        var m = parseInt(info[1], 10);
		        time += m * 60 * 1000;
		    }
			endDateTime = new Date(startDateTime.getTime() + time);
		}

		var endDateFormat = endDateTime.getFullYear() + '-' + pad(endDateTime.getMonth()+1,2) + '-' + pad(endDateTime.getDate(),2);
		var endTimeFormat = pad(endDateTime.getHours(),2) + ':' + pad(endDateTime.getMinutes(),2);

		$('#add_show_end_date_no_repeat').val(endDateFormat);
		$('#add_show_end_time').val(endTimeFormat);

		// calculate duration
		calculateDuration(endDateTime, startDateTime);
	});

	// when end date/time changes, check if the changed date is in past of start date/time
	$('#add_show_end_date_no_repeat, #add_show_end_time').change(function(){
		var startDate = $('#add_show_start_date').val().split('-');
        var startTime = $('#add_show_start_time').val().split(':');
		var startDateTime = new Date(startDate[0], parseInt(startDate[1], 10)-1, startDate[2], startTime[0], startTime[1], 0, 0);

		var endDate = $('#add_show_end_date_no_repeat').val().split('-');
		var endTime = $('#add_show_end_time').val().split(':');
        var endDateTime = new Date(endDate[0], parseInt(endDate[1], 10)-1, endDate[2], endTime[0], endTime[1], 0, 0);

		if(startDateTime.getTime() > endDateTime.getTime()){
			$('#add_show_end_date_no_repeat').css('background-color', '#F49C9C');
			$('#add_show_end_time').css('background-color', '#F49C9C');
		}else{
			$('#add_show_end_date_no_repeat').css('background-color', '');
			$('#add_show_end_time').css('background-color', '');
		}

		// calculate duration
		calculateDuration(endDateTime, startDateTime);
	});

	function calculateDuration(endDateTime, startDateTime){
		var duration;
		var durationSeconds = (endDateTime.getTime() - startDateTime.getTime())/1000;
		if(durationSeconds != 0){
			var durationHour = parseInt(durationSeconds/3600, 10);
			var durationMin = parseInt((durationSeconds%3600)/60, 10);
			duration = (durationHour == 0 ? '' : durationHour+'h'+' ')+(durationMin == 0 ? '' : durationMin+'m');
		}else{
			duration = '0m';
		}
		$('#add_show_duration').val(duration);
	}

	function pad(number, length) {
	    var str = '' + number;
	    while (str.length < length) {
	        str = '0' + str;
	    }

	    return str;
	}
}

function showErrorSections() {

    if($("#schedule-show-what .errors").length > 0) {
        $("#schedule-show-what").show();
    }
    if($("#schedule-show-when .errors").length > 0) {
        $("#schedule-show-when").show();
    }
    if($("#schedule-show-who .errors").length > 0) {
        $("#schedule-show-who").show();
    }
    if($("#schedule-show-style .errors").length > 0) {
        $("#schedule-show-style").show();
    }
    if($("#add_show_rebroadcast_absolute .errors").length > 0) {
        $("#schedule-record-rebroadcast").show();
        $("#add_show_rebroadcast_absolute").show();
    }
    if($("#add_show_rebroadcast_relative .errors").length > 0) {
        $("#schedule-record-rebroadcast").show();
        $("#add_show_rebroadcast_relative").show();
    }
}

$(document).ready(function() {

	//setAddShowEvents();
});

$(window).resize(function(){
	var windowWidth = $(this).width();
    // margin on showform are 16 px on each side
	if(!$("#schedule-add-show").is(':hidden')){
        var calendarWidth = 100-(($("#schedule-add-show").width() + (16 * 4))/windowWidth*100);
        var widthPercent = parseInt(calendarWidth)+"%";
        $("#schedule_calendar").css("width", widthPercent);
        $("#schedule_calendar").fullCalendar('render');
	}
});

$(window).load(function() {

	setAddShowEvents();
});
<commit_msg>CC-2839: End Date and Time show NaN when incorrect start date is entered<commit_after>/**
*
*	Schedule Dialog creation methods.
*
*/

//dateText mm-dd-yy
function startDpSelect(dateText, inst) {
	var time, date;

	time = dateText.split("-");
	date = new Date(time[0], time[1] - 1, time[2]);

	$("#add_show_end_date").datepicker("option", "minDate", date);
    $('input[name^="add_show_rebroadcast_absolute_date"]').datepicker("option", "minDate", date);
    if (inst.input)
        inst.input.trigger('change');
}

function endDpSelect(dateText, inst) {
	var time, date;

	time = dateText.split("-");
	date = new Date(time[0], time[1] - 1, time[2]);

	//$("#add_show_start_date").datepicker( "option", "maxDate", date);
	if (inst.input)
        inst.input.trigger('change');
}

function createDateInput(el, onSelect) {
	var date;

	el.datepicker({
			minDate: new Date(),
			onSelect: onSelect,
			dateFormat: 'yy-mm-dd'
		});
}

function autoSelect(event, ui) {

	$("#add_show_hosts-"+ui.item.value).attr("checked", "checked");
	event.preventDefault();
}

function findHosts(request, callback) {
	var search, url;

	url = "/User/get-hosts";
	search = request.term;

	$.post(url,
		{format: "json", term: search},

		function(json) {
			callback(json.hosts);
		});

}

function beginEditShow(data){
    $("#add-show-form")
        .empty()
        .append(data.newForm);

    removeAddShowButton();
    setAddShowEvents();
    openAddShowForm();
}

function setAddShowEvents() {

    var form = $("#add-show-form");

	form.find("h3").click(function(){
        $(this).next().toggle();
    });

    if(!form.find("#add_show_repeats").attr('checked')) {
        form.find("#schedule-show-when > fieldset:last").hide();
        $("#add_show_rebroadcast_relative").hide();
    }
    else {
        $("#add_show_rebroadcast_absolute").hide();
    }

    if(!form.find("#add_show_record").attr('checked')) {
        form.find("#add_show_rebroadcast").hide();
    }

    if(!form.find("#add_show_rebroadcast").attr('checked')) {
        form.find("#schedule-record-rebroadcast > fieldset:not(:first-child)").hide();
    }

    form.find("#add_show_repeats").click(function(){
        $(this).blur();
        form.find("#schedule-show-when > fieldset:last").toggle();

        //must switch rebroadcast displays
        if(form.find("#add_show_rebroadcast").attr('checked')) {

            if($(this).attr('checked')){
                form.find("#add_show_rebroadcast_absolute").hide();
                form.find("#add_show_rebroadcast_relative").show();
            }
            else {
                form.find("#add_show_rebroadcast_absolute").show();
                form.find("#add_show_rebroadcast_relative").hide();
            }
        }
    });

    form.find("#add_show_record").click(function(){
        $(this).blur();
        form.find("#add_show_rebroadcast").toggle();

        //uncheck rebroadcast checkbox
        form.find("#add_show_rebroadcast").attr('checked', false);

        //hide rebroadcast options
        form.find("#schedule-record-rebroadcast > fieldset:not(:first-child)").hide();
    });

    form.find("#add_show_rebroadcast").click(function(){
        $(this).blur();
        if(form.find("#add_show_record").attr('checked')){
	        if($(this).attr('checked') && !form.find("#add_show_repeats").attr('checked')) {
	            form.find("#add_show_rebroadcast_absolute").show();
	        }
	        else if($(this).attr('checked') && form.find("#add_show_repeats").attr('checked')) {
	            form.find("#add_show_rebroadcast_relative").show();
	        }
	        else {
	            form.find("#schedule-record-rebroadcast > fieldset:not(:first-child)").hide();
	        }
    	}
    });

    form.find("#add_show_repeat_type").change(function(){
        if($(this).val() == 2) {
            form.find("#add_show_day_check-label, #add_show_day_check-element").hide();
        }
        else {
            form.find("#add_show_day_check-label, #add_show_day_check-element").show();
        }
    });

    form.find("#add_show_day_check-label").addClass("block-display");
    form.find("#add_show_day_check-element").addClass("block-display clearfix");
    form.find("#add_show_day_check-element label").addClass("wrapp-label");
    form.find("#add_show_day_check-element br").remove();

    function endDateVisibility(){
        if(form.find("#add_show_no_end").is(':checked')){
            form.find("#add_show_end_date").hide();
        } else {
            form.find("#add_show_end_date").show();
        }
    }
    endDateVisibility();
    form.find("#add_show_no_end").click(endDateVisibility);

	createDateInput(form.find("#add_show_start_date"), startDpSelect);
	createDateInput(form.find("#add_show_end_date_no_repeat"), endDpSelect);
	createDateInput(form.find("#add_show_end_date"), endDpSelect);

    form.find("#add_show_start_time").timepicker({
        amPmText: ['', ''],
        defaultTime: '00:00'
    });
    form.find("#add_show_end_time").timepicker({
        amPmText: ['', '']
    });

    form.find('input[name^="add_show_rebroadcast_date_absolute"]').datepicker({
		minDate: new Date(),
		dateFormat: 'yy-mm-dd'
	});
    form.find('input[name^="add_show_rebroadcast_time"]').timepicker({
        amPmText: ['', ''],
        defaultTime: ''
    });

    form.find(".add_absolute_rebroadcast_day").click(function(){
        var li = $(this).parent().find("ul.formrow-repeat > li:visible:last").next();

        li.show();
        li = li.next();
        if(li.length === 0) {
            $(this).hide();
        }
    });

    form.find('a[id^="remove_rebroadcast"]').click(function(){
        var list = $(this).parent().parent();
        var li_num = $(this).parent().index();
        var num = list.find("li").length;
        var count = num - li_num;

        var curr = $(this).parent();
        var next = curr.next();

        for(var i=0; i<=count; i++) {
            var date = next.find('[name^="add_show_rebroadcast_date"]').val();
            curr.find('[name^="add_show_rebroadcast_date"]').val(date);
            var time = next.find('[name^="add_show_rebroadcast_time"]').val();
            curr.find('[name^="add_show_rebroadcast_time"]').val(time);

            curr = next;
            next = curr.next();
        }

        list.find("li:visible:last")
                .find('[name^="add_show_rebroadcast_date"]')
                    .val('')
                .end()
                .find('[name^="add_show_rebroadcast_time"]')
                    .val('')
                .end()
            .hide();

        list.next().show();
    });

	form.find("#add_show_hosts_autocomplete").autocomplete({
		source: findHosts,
		select: autoSelect,
        delay: 200
	});

	form.find("#schedule-show-style input").ColorPicker({
        onChange: function (hsb, hex, rgb, el) {
		    $(el).val(hex);
	    },
		onSubmit: function(hsb, hex, rgb, el) {
			$(el).val(hex);
			$(el).ColorPickerHide();
		},
		onBeforeShow: function () {
			$(this).ColorPickerSetColor(this.value);
		}
	});

    form.find("#add-show-close")
		.click(function(event){
            event.stopPropagation();
            event.preventDefault();

            $("#schedule_calendar").removeAttr("style")
                .fullCalendar('render');

			$("#add-show-form").hide();
            $.get("/Schedule/get-form", {format:"json"}, function(json){
                $("#add-show-form")
                    .empty()
                    .append(json.form);

                setAddShowEvents();
            });
            makeAddShowButton();
		});

	form.find(".add-show-submit")
		.click(function(event){
            var addShowButton = $(this);
            if (!addShowButton.hasClass("disabled")){
                addShowButton.addClass("disabled");
            }
            else {
                return;
            }

            event.preventDefault();

			var data = $("form").serializeArray();

            var hosts = $('#add_show_hosts-element input').map(function() {
                if($(this).attr("checked")) {
                    return $(this).val();
                }
            }).get();

            var days = $('#add_show_day_check-element input').map(function() {
                if($(this).attr("checked")) {
                    return $(this).val();
                }
            }).get();

            var start_date = $("#add_show_start_date").val();
            var end_date = $("#add_show_end_date").val();

            $.post("/Schedule/add-show", {format: "json", data: data, hosts: hosts, days: days}, function(json){
                addShowButton.removeClass("disabled");
                if(json.form) {
                    $("#add-show-form")
                        .empty()
                        .append(json.form);

                    setAddShowEvents();

                    $("#add_show_end_date").val(end_date);
                    $("#add_show_start_date").val(start_date);
                    showErrorSections();
                }
                else {
                     $("#add-show-form")
                        .empty()
                        .append(json.newForm);

                    setAddShowEvents();
                    scheduleRefetchEvents();
                }
            });
		});

	// when start date/time changes, set end date/time to start date/time+1 hr
	$('#add_show_start_date, #add_show_start_time').change(function(){
		var startDate = $('#add_show_start_date').val().split('-');
		var startTime = $('#add_show_start_time').val().split(':');
        var startDateTime = new Date(startDate[0], parseInt(startDate[1], 10)-1, startDate[2], startTime[0], startTime[1], 0, 0);

		var endDate = $('#add_show_end_date_no_repeat').val().split('-');
		var endTime = $('#add_show_end_time').val().split(':');
        var endDateTime = new Date(endDate[0], parseInt(endDate[1], 10)-1, endDate[2], endTime[0], endTime[1], 0, 0);

		if(startDateTime.getTime() > endDateTime.getTime()){
		    var duration = $('#add_show_duration').val();
	        // parse duration
		    var time = 0;
		    var info = duration.split(' ');
		    var h = parseInt(info[0], 10);
		    time += h * 60 * 60* 1000;
		    if(info.length >1 && $.trim(info[1]) !== ''){
		        var m = parseInt(info[1], 10);
		        time += m * 60 * 1000;
		    }
			endDateTime = new Date(startDateTime.getTime() + time);
		}

		var endDateFormat = endDateTime.getFullYear() + '-' + pad(endDateTime.getMonth()+1,2) + '-' + pad(endDateTime.getDate(),2);
		var endTimeFormat = pad(endDateTime.getHours(),2) + ':' + pad(endDateTime.getMinutes(),2);

		$('#add_show_end_date_no_repeat').val(endDateFormat);
		$('#add_show_end_time').val(endTimeFormat);

		// calculate duration
		calculateDuration(endDateTime, startDateTime);
	});

	// when end date/time changes, check if the changed date is in past of start date/time
	$('#add_show_end_date_no_repeat, #add_show_end_time').change(function(){
		var startDate = $('#add_show_start_date').val().split('-');
        var startTime = $('#add_show_start_time').val().split(':');
		var startDateTime = new Date(startDate[0], parseInt(startDate[1], 10)-1, startDate[2], startTime[0], startTime[1], 0, 0);

		var endDate = $('#add_show_end_date_no_repeat').val().split('-');
		var endTime = $('#add_show_end_time').val().split(':');
        var endDateTime = new Date(endDate[0], parseInt(endDate[1], 10)-1, endDate[2], endTime[0], endTime[1], 0, 0);

		if(startDateTime.getTime() > endDateTime.getTime()){
			$('#add_show_end_date_no_repeat').css('background-color', '#F49C9C');
			$('#add_show_end_time').css('background-color', '#F49C9C');
		}else{
			$('#add_show_end_date_no_repeat').css('background-color', '');
			$('#add_show_end_time').css('background-color', '');
		}

		// calculate duration
		calculateDuration(endDateTime, startDateTime);
	});

	function calculateDuration(endDateTime, startDateTime){
		var duration;
		var durationSeconds = (endDateTime.getTime() - startDateTime.getTime())/1000;
		if(durationSeconds != 0){
			var durationHour = parseInt(durationSeconds/3600, 10);
			var durationMin = parseInt((durationSeconds%3600)/60, 10);
			duration = (durationHour == 0 ? '' : durationHour+'h'+' ')+(durationMin == 0 ? '' : durationMin+'m');
		}else{
			duration = '0m';
		}
		if(isNaN(duration)){
		    duration = '1h';
		}
		$('#add_show_duration').val(duration);
	}

	function pad(number, length) {
	    var str = '' + number;
	    while (str.length < length) {
	        str = '0' + str;
	    }

	    return str;
	}
}

function showErrorSections() {

    if($("#schedule-show-what .errors").length > 0) {
        $("#schedule-show-what").show();
    }
    if($("#schedule-show-when .errors").length > 0) {
        $("#schedule-show-when").show();
    }
    if($("#schedule-show-who .errors").length > 0) {
        $("#schedule-show-who").show();
    }
    if($("#schedule-show-style .errors").length > 0) {
        $("#schedule-show-style").show();
    }
    if($("#add_show_rebroadcast_absolute .errors").length > 0) {
        $("#schedule-record-rebroadcast").show();
        $("#add_show_rebroadcast_absolute").show();
    }
    if($("#add_show_rebroadcast_relative .errors").length > 0) {
        $("#schedule-record-rebroadcast").show();
        $("#add_show_rebroadcast_relative").show();
    }
}

$(document).ready(function() {

	//setAddShowEvents();
});

$(window).resize(function(){
	var windowWidth = $(this).width();
    // margin on showform are 16 px on each side
	if(!$("#schedule-add-show").is(':hidden')){
        var calendarWidth = 100-(($("#schedule-add-show").width() + (16 * 4))/windowWidth*100);
        var widthPercent = parseInt(calendarWidth)+"%";
        $("#schedule_calendar").css("width", widthPercent);
        $("#schedule_calendar").fullCalendar('render');
	}
});

$(window).load(function() {

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


<commit_before>import _defn from './internal/_defn'
import _slice from './internal/_slice'

/**
 * @name dropUntil
 * @signature (a -> Boolean) -> [a] -> [a]
 * @category Collection
 * @since v0.14.0
 * @description
 * Runs a predicate function sequentially through a list, dropping
 * all elements until the predicate returns `true`. Once the predicate
 * returns `true`, the remainder of the list is returned.
 * @see dropWhile
 *
 * @example
 * const isEven = x => x % 2 === 0
 *
 * dropUntil(isEven, [1, 3, 6, 8, 10]) // => [6, 8, 10]
 * dropUntil(isEven, [1, 3, 6, 5, 7])  // => [6, 5, 7]
 */
export default _defn(function dropUntil (fn, xs) {
  var i = 0

  while (i < xs.length && !fn(xs[i])) i += 1
  return _slice.call(xs, i)
})
<commit_msg>refactor(dropUntil): implement as dropWhile<commit_after>import _defn from './internal/_defn'
import _complement from './internal/_complement'
import dropWhile from './dropWhile'

/**
 * @name dropUntil
 * @signature (a -> Boolean) -> [a] -> [a]
 * @category Collection
 * @since v0.14.0
 * @description
 * Runs a predicate function sequentially through a list, dropping
 * all elements until the predicate returns `true`. Once the predicate
 * returns `true`, the remainder of the list is returned.
 * @see dropWhile
 *
 * @example
 * const isEven = x => x % 2 === 0
 *
 * dropUntil(isEven, [1, 3, 6, 8, 10]) // => [6, 8, 10]
 * dropUntil(isEven, [1, 3, 6, 5, 7])  // => [6, 5, 7]
 */
export default _defn(function dropUntil (fn, xs) {
  return dropWhile(_complement(fn), xs)
})
<|endoftext|>


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

    let depth = Number.parseInt(
      window.location.search.substring(1),
      10
    );

    if(Number.isNaN(depth)
      || depth < 0){
        depth = 0;
    }

    let display = [];

    Object.getOwnPropertyNames(window).forEach(
      function(property){
          display.push(
            '
'
            + property
            + '<textarea readonly>'
            + window[property]
            + '</textarea>'
          );
          fetchInfo(
            window[property],
            property,
            0
          );
      }
    );

    function fetchInfo(object, name, depthcounter){
        if(depthcounter >= depth
          || object === window){
            return;
        }

        for(let property in object){
            if(Reflect.has(object, property)){
                display.push(
                  '
'
                  + name
                  + '.'
                  + property
                  + '<textarea readonly>'
                  + object[property]
                  + '</textarea>'
                );
                fetchInfo(
                  object[property],
                  name + '.' + property,
                  depthcounter + 1
                );
            }
        }
    }

    document.getElementById('depth').value = 'Depth: ' + depth;
    document.getElementById('depth').onclick = function(){
        let newdepth = window.prompt(
          'Enter new depth:',
          depth
        );

        if(newdepth === null
          || newdepth.length === 0
          || isNaN(newdepth)){
            return;
        }

        window.location.replace('?' + newdepth);
    };
    document.getElementById('result').innerHTML = display.sort().join('');
}());
<commit_msg>replaced some let with const, reverted reflect<commit_after>(function(){
    'use strict';

    let depth = Number.parseInt(
      window.location.search.substring(1),
      10
    );

    if(Number.isNaN(depth)
      || depth < 0){
        depth = 0;
    }

    const display = [];

    Object.getOwnPropertyNames(window).forEach(
      function(property){
          display.push(
            '
'
            + property
            + '<textarea readonly>'
            + window[property]
            + '</textarea>'
          );
          fetchInfo(
            window[property],
            property,
            0
          );
      }
    );

    function fetchInfo(object, name, depthcounter){
        if(depthcounter >= depth
          || object === window){
            return;
        }

        for(const property in object){
            if(object.hasOwnProperty(property)){
                display.push(
                  '
'
                  + name
                  + '.'
                  + property
                  + '<textarea readonly>'
                  + object[property]
                  + '</textarea>'
                );
                fetchInfo(
                  object[property],
                  name + '.' + property,
                  depthcounter + 1
                );
            }
        }
    }

    document.getElementById('depth').value = 'Depth: ' + depth;
    document.getElementById('depth').onclick = function(){
        const newdepth = window.prompt(
          'Enter new depth:',
          depth
        );

        if(newdepth === null
          || newdepth.length === 0
          || isNaN(newdepth)){
            return;
        }

        window.location.replace('?' + newdepth);
    };
    document.getElementById('result').innerHTML = display.sort().join('');
}());
<|endoftext|>


<commit_before>'use strict';

/**
 * Account is a user with a collection or rights
 * registrations on site create accounts
 */
exports = module.exports = function(params) {

    var mongoose = params.mongoose;

    var accountSchema = new mongoose.Schema({
        user: {
          id: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
          name: { type: String, default: '' }
        },
        isVerified: { type: String, default: '' },				// email verification on change
        verificationToken: { type: String, default: '' },		// email verification on change

        status: {
          id: { type: String, ref: 'Status' },
          name: { type: String, default: '' },
          userCreated: {
            id: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
            name: { type: String, default: '' },
            time: { type: Date, default: Date.now }
          }
        },
        statusLog: [mongoose.modelSchemas.StatusLog],

        // start date for seniority vacation rights
        seniority: Date,

        userCreated: {											// the user who create this account
          id: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
          name: { type: String, default: '' }
        },

        notify: {
            approvals: { type: Boolean, default: false },
            allocations: { type: Boolean, default: false }
        }
    });

    accountSchema.index({ user: 1 });
    accountSchema.index({ 'status.id': 1 });
    accountSchema.set('autoIndex', params.autoIndex);

    /**
     * Find rights collections
     * @returns {Query} A mongoose query on the account collection schema
     */
    accountSchema.methods.getAccountCollectionQuery = function() {
        return this.model('AccountCollection')
            .find()
            .where('account').equals(this._id);
    };

    /**
     * Get the right collection for a specific date
     * @return {Promise} resolve to a rightCollection document or null
     */
    accountSchema.methods.getCollection = function(moment) {
        var Q = require('q');
        var deferred = Q.defer();

        moment.setHours(0,0,0,0);

        this.getAccountCollectionQuery()
            .where('from').lte(moment)
            .where('to').gte(moment)
            .populate('rightCollection')
            .exec(function(err, arr) {

                if (err) {
                    deferred.reject(err);
                    return;
                }

                if (!arr || 0 === arr.length) {
                    deferred.resolve(null);
                    return;
                }

                deferred.resolve(arr[0].rightCollection);
            });

        return deferred.promise;
    };

    /**
     * Get the ongoing right collection
     * @return {Promise} resolve to a rightCollection document or null
     */
    accountSchema.methods.getCurrentCollection = function() {
        var today = new Date();
        return this.getCollection(today);
    };

    /**
     *
     * Get the list of rights beneficiaries associated to an account
     * @param {Date} moment  optional date parameter
     *
     * @return {Promise} resolve to an array of beneficiary documents
     */
    accountSchema.methods.getRightBeneficiaries = function(moment) {

        var deferred = require('q').defer();

        if (null === moment) {
            moment = new Date();
        }

        this.getCollection(moment).then(function(rightCollection) {
            this.model('Beneficiary')
            .where('document').in([rightCollection._id, this.user._id])
            .populate('right')
            .exec(function(err, beneficiaries) {
                if (err) {
                    deferred.reject(err);
                }

                deferred.resolve(beneficiaries);
            });
        });

        return deferred.promise;
    };

    /**
     *
     * @param {Date} moment  optional date parameter
     * @return {Promise} resolve to an array of rights
     */
    accountSchema.methods.getRights = function(moment) {

        var deferred = require('q').defer();

        this.getRightBeneficiaries(moment).then(function(beneficiaries) {

            var rights = [];

            for(var i=0; i< beneficiaries.length; i++) {
                rights.push(beneficiaries[i].right);
            }

            deferred.resolve(rights);
        }).catch(deferred.reject);

        return deferred.promise;
    };

    params.db.model('Account', accountSchema);
};
<commit_msg>Fix the current collection method on user account<commit_after>'use strict';

/**
 * Account is a user with a collection or rights
 * registrations on site create accounts
 */
exports = module.exports = function(params) {

    var mongoose = params.mongoose;

    var accountSchema = new mongoose.Schema({
        user: {
          id: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
          name: { type: String, default: '' }
        },
        isVerified: { type: String, default: '' },				// email verification on change
        verificationToken: { type: String, default: '' },		// email verification on change

        status: {
          id: { type: String, ref: 'Status' },
          name: { type: String, default: '' },
          userCreated: {
            id: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
            name: { type: String, default: '' },
            time: { type: Date, default: Date.now }
          }
        },
        statusLog: [mongoose.modelSchemas.StatusLog],

        // start date for seniority vacation rights
        seniority: Date,

        userCreated: {											// the user who create this account
          id: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
          name: { type: String, default: '' }
        },

        notify: {
            approvals: { type: Boolean, default: false },
            allocations: { type: Boolean, default: false }
        }
    });

    accountSchema.index({ user: 1 });
    accountSchema.index({ 'status.id': 1 });
    accountSchema.set('autoIndex', params.autoIndex);

    /**
     * Find rights collections
     * @returns {Query} A mongoose query on the account collection schema
     */
    accountSchema.methods.getAccountCollectionQuery = function() {
        return this.model('AccountCollection')
            .find()
            .where('account').equals(this._id);
    };

    /**
     * Get the right collection for a specific date
     * @return {Promise} resolve to a rightCollection document or null
     */
    accountSchema.methods.getCollection = function(moment) {
        var Q = require('q');
        var deferred = Q.defer();
        var account = this;

        moment.setHours(0,0,0,0);

        account.getAccountCollectionQuery()
            .where('from').lte(moment)
            .where('to').gte(moment)
            .populate('rightCollection')
            .exec(function(err, arr) {

                if (err) {
                    deferred.reject(err);
                    return;
                }

                if (!arr || 0 === arr.length) {

                    account.getAccountCollectionQuery()
                        .where('from').lte(moment)
                        .where('to').equals(null)
                        .populate('rightCollection')
                        .exec(function(err, arr) {

                        if (err) {
                            deferred.reject(err);
                            return;
                        }

                        if (!arr || 0 === arr.length) {
                            deferred.resolve(null);
                            return;
                        }

                        deferred.resolve(arr[0].rightCollection);
                    });

                    return;
                }

                deferred.resolve(arr[0].rightCollection);
            });

        return deferred.promise;
    };

    /**
     * Get the ongoing right collection
     * @return {Promise} resolve to a rightCollection document or null
     */
    accountSchema.methods.getCurrentCollection = function() {
        var today = new Date();
        return this.getCollection(today);
    };

    /**
     *
     * Get the list of rights beneficiaries associated to an account
     * @param {Date} moment  optional date parameter
     *
     * @return {Promise} resolve to an array of beneficiary documents
     */
    accountSchema.methods.getRightBeneficiaries = function(moment) {

        var deferred = require('q').defer();

        if (null === moment) {
            moment = new Date();
        }

        this.getCollection(moment).then(function(rightCollection) {
            this.model('Beneficiary')
            .where('document').in([rightCollection._id, this.user._id])
            .populate('right')
            .exec(function(err, beneficiaries) {
                if (err) {
                    deferred.reject(err);
                }

                deferred.resolve(beneficiaries);
            });
        });

        return deferred.promise;
    };

    /**
     *
     * @param {Date} moment  optional date parameter
     * @return {Promise} resolve to an array of rights
     */
    accountSchema.methods.getRights = function(moment) {

        var deferred = require('q').defer();

        this.getRightBeneficiaries(moment).then(function(beneficiaries) {

            var rights = [];

            for(var i=0; i< beneficiaries.length; i++) {
                rights.push(beneficiaries[i].right);
            }

            deferred.resolve(rights);
        }).catch(deferred.reject);

        return deferred.promise;
    };

    params.db.model('Account', accountSchema);
};
<|endoftext|>


<commit_before>import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';

import ProductsList from './ProductsList'

describe('component', () => {

    it('can render a ProductList component', () => {

        const wrapper = mount(<ProductsList title='TestTitle' />);
        expect(wrapper.html()).to.equal('

TestTitle

')

    });

});
<commit_msg>test productlist component with childs<commit_after>import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';

import ProductsList from './ProductsList'

describe('component', () => {

    it('can render a ProductList component', () => {

        const wrapper = mount(<ProductsList title='TestTitle' />);
        expect(wrapper.html()).to.equal('

TestTitle

')

    });

    it('can render a ProductList component with children', () => {

        const wrapper = mount(<ProductsList title='TestTitle' children='childs' />);
        expect(wrapper.html()).to.equal('

TestTitle

childs

')

    });

});
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const Grid = require('gridfs-stream');

// write to mongodb
exports.writeFile = function (mongoose, originalFilePath, filename, prefix = '', done) {
  Grid.mongo = mongoose.mongo;

  let gfs = Grid(mongoose.connection.db);

  // streaming to gridfs
  //filename to store in mongodb
  let writestream = gfs.createWriteStream({
    filename: prefix.length ? prefix + '.' + filename : filename
  });
  fs.createReadStream(originalFilePath).pipe(writestream);

  writestream.on('close', function (file) {
    // do something with `file`
    done(null, file);
  });

};

//read from mongodb
exports.readFile = function (mongoose, filename, prefix = '', done) {
  Grid.mongo = mongoose.mongo;

  let gfs = Grid(mongoose.connection.db);

  let fileOptions = {
    filename: prefix.length ? prefix + '.' + filename : filename
  };

  gfs.exist(fileOptions, function (err, found) {
    if (found) {
      let readstream = gfs.createReadStream(fileOptions);
      return done(null, readstream);
    } else if (err) {
      return done(err);
    } else {
      let error = new Error('File not found');
      error.code = 'ENOENT';
      return done(error);
    }
  });

};

// copy a file in mongodb
exports.copyFile = function (mongoose, sourcefilename, prefix = '', destfilename, done) {
  Grid.mongo = mongoose.mongo;

  let gfs = Grid(mongoose.connection.db);

  let fileOptions = {
    filename: prefix.length ? prefix + '.' + sourcefilename : sourcefilename
  };

  gfs.exist(fileOptions, function (err, found) {
    if (found) {
      let readstream = gfs.createReadStream(fileOptions);
      let fs_write_stream = fs.createWriteStream(prefix.length ? prefix + '.' + destfilename : destfilename);
      readstream.pipe(fs_write_stream);
      fs_write_stream.on('close', function () {
        done (null);
      });
    } else if (err) {
      return done(err);
    } else {
      let error = new Error('File not found');
      error.code = 'ENOENT';
      return done(error);
    }
  });

};
<commit_msg>copyFile will take a destprefix paramter<commit_after>'use strict';

const fs = require('fs');
const Grid = require('gridfs-stream');

// write to mongodb
exports.writeFile = function (mongoose, originalFilePath, filename, prefix = '', done) {
  Grid.mongo = mongoose.mongo;

  let gfs = Grid(mongoose.connection.db);

  // streaming to gridfs
  //filename to store in mongodb
  let writestream = gfs.createWriteStream({
    filename: prefix.length ? prefix + '.' + filename : filename
  });
  fs.createReadStream(originalFilePath).pipe(writestream);

  writestream.on('close', function (file) {
    // do something with `file`
    done(null, file);
  });

};

//read from mongodb
exports.readFile = function (mongoose, filename, prefix = '', done) {
  Grid.mongo = mongoose.mongo;

  let gfs = Grid(mongoose.connection.db);

  let fileOptions = {
    filename: prefix.length ? prefix + '.' + filename : filename
  };

  gfs.exist(fileOptions, function (err, found) {
    if (found) {
      let readstream = gfs.createReadStream(fileOptions);
      return done(null, readstream);
    } else if (err) {
      return done(err);
    } else {
      let error = new Error('File not found');
      error.code = 'ENOENT';
      return done(error);
    }
  });

};

// copy a file in mongodb
exports.copyFile = function (mongoose, sourcefilename, sourceprefix = '', destfilename, destprefix='', done) {
  Grid.mongo = mongoose.mongo;

  let gfs = Grid(mongoose.connection.db);

  let fileOptions = {
    filename: prefix.length ? prefix + '.' + sourcefilename : sourcefilename
  };

  gfs.exist(fileOptions, function (err, found) {
    if (found) {
      let readstream = gfs.createReadStream(fileOptions);
      let fs_write_stream = fs.createWriteStream(prefix.length ? prefix + '.' + destfilename : destfilename);
      readstream.pipe(fs_write_stream);
      fs_write_stream.on('close', function () {
        done (null);
      });
    } else if (err) {
      return done(err);
    } else {
      let error = new Error('File not found');
      error.code = 'ENOENT';
      return done(error);
    }
  });

};
<|endoftext|>


<commit_before>// If you want to access any of these options in React, don’t forget to update CLIENT_CONFIG_OPTIONS array
// in loaders/styleguide-loader.js

const EXTENSIONS = 'js,jsx,ts,tsx';
const DEFAULT_COMPONENTS_PATTERN = `src/@(components|Components)/**/*.{${EXTENSIONS}}`;

const path = require('path');
const startCase = require('lodash/startCase');
const kleur = require('kleur');
const reactDocgen = require('react-docgen');
const createDisplayNameHandler = require('react-docgen-displayname-handler')
	.createDisplayNameHandler;
const annotationResolver = require('react-docgen-annotation-resolver').default;
const logger = require('glogg')('rsg');
const findUserWebpackConfig = require('../utils/findUserWebpackConfig');
const getUserPackageJson = require('../utils/getUserPackageJson');
const fileExistsCaseInsensitive = require('../utils/findFileCaseInsensitive');
const StyleguidistError = require('../utils/error');
const consts = require('../consts');

module.exports = {
	assetsDir: {
		type: 'existing directory path',
		example: 'assets',
	},
	compilerConfig: {
		type: 'object',
		default: {
			objectAssign: 'Object.assign',
		},
	},
	// `components` is a shortcut for { sections: [{ components }] },
	// see `sections` below
	components: {
		type: ['string', 'function', 'array'],
		example: 'components/**/[A-Z]*.js',
	},
	configDir: {
		process: (value, config, rootDir) => rootDir,
	},
	context: {
		type: 'object',
		default: {},
		example: {
			map: 'lodash/map',
		},
	},
	contextDependencies: {
		type: 'array',
	},
	configureServer: {
		type: 'function',
	},
	dangerouslyUpdateWebpackConfig: {
		type: 'function',
	},
	defaultExample: {
		type: ['boolean', 'existing file path'],
		default: false,
		process: val =>
			val === true ? path.resolve(__dirname, '../templates/DefaultExample.md') : val,
	},
	exampleMode: {
		type: 'string',
		process: (value, config) => {
			return config.showCode === undefined ? value : config.showCode ? 'expand' : 'collapse';
		},
		default: 'collapse',
	},
	getComponentPathLine: {
		type: 'function',
		default: componentPath => componentPath,
	},
	getExampleFilename: {
		type: 'function',
		default: componentPath => {
			const files = [
				path.join(path.dirname(componentPath), 'Readme.md'),
				componentPath.replace(path.extname(componentPath), '.md'),
			];

			for (const file of files) {
				const existingFile = fileExistsCaseInsensitive(file);
				if (existingFile) {
					return existingFile;
				}
			}

			return false;
		},
	},
	handlers: {
		type: 'function',
		default: componentPath =>
			reactDocgen.defaultHandlers.concat(createDisplayNameHandler(componentPath)),
	},
	ignore: {
		type: 'array',
		default: [
			'**/__tests__/**',
			`**/*.test.{${EXTENSIONS}}`,
			`**/*.spec.{${EXTENSIONS}}`,
			'**/*.d.ts',
		],
	},
	editorConfig: {
		process: value => {
			if (value) {
				throw new StyleguidistError(
					`${chalk.bold(
						'editorConfig'
					)} config option was removed. Use “theme” option to change syntax highlighting.`
				);
			}
		},
	},
	logger: {
		type: 'object',
	},
	mountPointId: {
		type: 'string',
		default: 'rsg-root',
	},
	pagePerSection: {
		type: 'boolean',
		default: false,
	},
	previewDelay: {
		type: 'number',
		default: 500,
	},
	printBuildInstructions: {
		type: 'function',
	},
	printServerInstructions: {
		type: 'function',
	},
	propsParser: {
		type: 'function',
	},
	require: {
		type: 'array',
		default: [],
		example: ['babel-polyfill', 'path/to/styles.css'],
	},
	resolver: {
		type: 'function',
		default: (ast, recast) => {
			const findAllExportedComponentDefinitions =
				reactDocgen.resolver.findAllExportedComponentDefinitions;
			const annotatedComponents = annotationResolver(ast, recast);
			const exportedComponents = findAllExportedComponentDefinitions(ast, recast);
			return annotatedComponents.concat(exportedComponents);
		},
	},
	ribbon: {
		type: 'object',
		example: {
			url: 'http://example.com/',
			text: 'Fork me on GitHub',
		},
	},
	sections: {
		type: 'array',
		default: [],
		process: (val, config) => {
			if (!val) {
				// If root `components` isn't empty, make it a first section
				// If `components` and `sections` weren’t specified, use default pattern
				const components = config.components || DEFAULT_COMPONENTS_PATTERN;
				return [
					{
						components,
					},
				];
			}
			return val;
		},
		example: [
			{
				name: 'Documentation',
				content: 'Readme.md',
			},
			{
				name: 'Components',
				components: './lib/components/**/[A-Z]*.js',
			},
		],
	},
	serverHost: {
		type: 'string',
		default: '0.0.0.0',
	},
	serverPort: {
		type: 'number',
		default: 6060,
	},
	showCode: {
		type: 'boolean',
		default: false,
		deprecated: 'Use exampleMode option instead',
	},
	showUsage: {
		type: 'boolean',
		default: false,
		deprecated: 'Use usageMode option instead',
	},
	showSidebar: {
		type: 'boolean',
		default: true,
	},
	skipComponentsWithoutExample: {
		type: 'boolean',
		default: false,
	},
	sortProps: {
		type: 'function',
	},
	styleguideComponents: {
		type: 'object',
	},
	styleguideDir: {
		type: 'directory path',
		default: 'styleguide',
	},
	styles: {
		type: 'object',
		default: {},
		example: {
			Logo: {
				logo: {
					fontStyle: 'italic',
				},
			},
		},
	},
	template: {
		type: ['object', 'function'],
		default: {},
		process: val => {
			if (typeof val === 'string') {
				throw new StyleguidistError(
					`${kleur.bold(
						'template'
					)} config option format has been changed, you need to update your config.`,
					'template'
				);
			}
			return val;
		},
	},
	theme: {
		type: 'object',
		default: {},
		example: {
			link: 'firebrick',
			linkHover: 'salmon',
		},
	},
	title: {
		type: 'string',
		process: val => {
			if (val) {
				return val;
			}
			const name = getUserPackageJson().name || '';
			return `${startCase(name)} Style Guide`;
		},
		example: 'My Style Guide',
	},
	updateDocs: {
		type: 'function',
	},
	updateExample: {
		type: 'function',
		default: props => {
			if (props.lang === 'example') {
				props.lang = 'js';
				logger.warn(
					'"example" code block language is deprecated. Use "js", "jsx" or "javascript" instead:\n' +
						consts.DOCS_DOCUMENTING
				);
			}
			return props;
		},
	},
	updateWebpackConfig: {
		type: 'function',
		removed: `Use "webpackConfig" option instead:\n${consts.DOCS_WEBPACK}`,
	},
	usageMode: {
		type: 'string',
		process: (value, config) => {
			return config.showUsage === undefined ? value : config.showUsage ? 'expand' : 'collapse';
		},
		default: 'collapse',
	},
	verbose: {
		type: 'boolean',
		default: false,
	},
	version: {
		type: 'string',
	},
	webpackConfig: {
		type: ['object', 'function'],
		process: val => {
			if (val) {
				return val;
			}

			const file = findUserWebpackConfig();
			if (file) {
				logger.info(`Loading webpack config from:\n${file}`);
				// eslint-disable-next-line import/no-dynamic-require
				return require(file);
			}

			logger.warn(
				'No webpack config found. ' +
					'You may need to specify "webpackConfig" option in your style guide config:\n' +
					consts.DOCS_WEBPACK
			);

			return undefined;
		},
		example: {
			module: {
				rules: [
					{
						test: /\.jsx?$/,
						exclude: /node_modules/,
						loader: 'babel-loader',
					},
				],
			},
		},
	},
};
<commit_msg>Fix: Chalk → Kleur after merge<commit_after>// If you want to access any of these options in React, don’t forget to update CLIENT_CONFIG_OPTIONS array
// in loaders/styleguide-loader.js

const EXTENSIONS = 'js,jsx,ts,tsx';
const DEFAULT_COMPONENTS_PATTERN = `src/@(components|Components)/**/*.{${EXTENSIONS}}`;

const path = require('path');
const startCase = require('lodash/startCase');
const kleur = require('kleur');
const reactDocgen = require('react-docgen');
const createDisplayNameHandler = require('react-docgen-displayname-handler')
	.createDisplayNameHandler;
const annotationResolver = require('react-docgen-annotation-resolver').default;
const logger = require('glogg')('rsg');
const findUserWebpackConfig = require('../utils/findUserWebpackConfig');
const getUserPackageJson = require('../utils/getUserPackageJson');
const fileExistsCaseInsensitive = require('../utils/findFileCaseInsensitive');
const StyleguidistError = require('../utils/error');
const consts = require('../consts');

module.exports = {
	assetsDir: {
		type: 'existing directory path',
		example: 'assets',
	},
	compilerConfig: {
		type: 'object',
		default: {
			objectAssign: 'Object.assign',
		},
	},
	// `components` is a shortcut for { sections: [{ components }] },
	// see `sections` below
	components: {
		type: ['string', 'function', 'array'],
		example: 'components/**/[A-Z]*.js',
	},
	configDir: {
		process: (value, config, rootDir) => rootDir,
	},
	context: {
		type: 'object',
		default: {},
		example: {
			map: 'lodash/map',
		},
	},
	contextDependencies: {
		type: 'array',
	},
	configureServer: {
		type: 'function',
	},
	dangerouslyUpdateWebpackConfig: {
		type: 'function',
	},
	defaultExample: {
		type: ['boolean', 'existing file path'],
		default: false,
		process: val =>
			val === true ? path.resolve(__dirname, '../templates/DefaultExample.md') : val,
	},
	exampleMode: {
		type: 'string',
		process: (value, config) => {
			return config.showCode === undefined ? value : config.showCode ? 'expand' : 'collapse';
		},
		default: 'collapse',
	},
	getComponentPathLine: {
		type: 'function',
		default: componentPath => componentPath,
	},
	getExampleFilename: {
		type: 'function',
		default: componentPath => {
			const files = [
				path.join(path.dirname(componentPath), 'Readme.md'),
				componentPath.replace(path.extname(componentPath), '.md'),
			];

			for (const file of files) {
				const existingFile = fileExistsCaseInsensitive(file);
				if (existingFile) {
					return existingFile;
				}
			}

			return false;
		},
	},
	handlers: {
		type: 'function',
		default: componentPath =>
			reactDocgen.defaultHandlers.concat(createDisplayNameHandler(componentPath)),
	},
	ignore: {
		type: 'array',
		default: [
			'**/__tests__/**',
			`**/*.test.{${EXTENSIONS}}`,
			`**/*.spec.{${EXTENSIONS}}`,
			'**/*.d.ts',
		],
	},
	editorConfig: {
		process: value => {
			if (value) {
				throw new StyleguidistError(
					`${kleur.bold(
						'editorConfig'
					)} config option was removed. Use “theme” option to change syntax highlighting.`
				);
			}
		},
	},
	logger: {
		type: 'object',
	},
	mountPointId: {
		type: 'string',
		default: 'rsg-root',
	},
	pagePerSection: {
		type: 'boolean',
		default: false,
	},
	previewDelay: {
		type: 'number',
		default: 500,
	},
	printBuildInstructions: {
		type: 'function',
	},
	printServerInstructions: {
		type: 'function',
	},
	propsParser: {
		type: 'function',
	},
	require: {
		type: 'array',
		default: [],
		example: ['babel-polyfill', 'path/to/styles.css'],
	},
	resolver: {
		type: 'function',
		default: (ast, recast) => {
			const findAllExportedComponentDefinitions =
				reactDocgen.resolver.findAllExportedComponentDefinitions;
			const annotatedComponents = annotationResolver(ast, recast);
			const exportedComponents = findAllExportedComponentDefinitions(ast, recast);
			return annotatedComponents.concat(exportedComponents);
		},
	},
	ribbon: {
		type: 'object',
		example: {
			url: 'http://example.com/',
			text: 'Fork me on GitHub',
		},
	},
	sections: {
		type: 'array',
		default: [],
		process: (val, config) => {
			if (!val) {
				// If root `components` isn't empty, make it a first section
				// If `components` and `sections` weren’t specified, use default pattern
				const components = config.components || DEFAULT_COMPONENTS_PATTERN;
				return [
					{
						components,
					},
				];
			}
			return val;
		},
		example: [
			{
				name: 'Documentation',
				content: 'Readme.md',
			},
			{
				name: 'Components',
				components: './lib/components/**/[A-Z]*.js',
			},
		],
	},
	serverHost: {
		type: 'string',
		default: '0.0.0.0',
	},
	serverPort: {
		type: 'number',
		default: 6060,
	},
	showCode: {
		type: 'boolean',
		default: false,
		deprecated: 'Use exampleMode option instead',
	},
	showUsage: {
		type: 'boolean',
		default: false,
		deprecated: 'Use usageMode option instead',
	},
	showSidebar: {
		type: 'boolean',
		default: true,
	},
	skipComponentsWithoutExample: {
		type: 'boolean',
		default: false,
	},
	sortProps: {
		type: 'function',
	},
	styleguideComponents: {
		type: 'object',
	},
	styleguideDir: {
		type: 'directory path',
		default: 'styleguide',
	},
	styles: {
		type: 'object',
		default: {},
		example: {
			Logo: {
				logo: {
					fontStyle: 'italic',
				},
			},
		},
	},
	template: {
		type: ['object', 'function'],
		default: {},
		process: val => {
			if (typeof val === 'string') {
				throw new StyleguidistError(
					`${kleur.bold(
						'template'
					)} config option format has been changed, you need to update your config.`,
					'template'
				);
			}
			return val;
		},
	},
	theme: {
		type: 'object',
		default: {},
		example: {
			link: 'firebrick',
			linkHover: 'salmon',
		},
	},
	title: {
		type: 'string',
		process: val => {
			if (val) {
				return val;
			}
			const name = getUserPackageJson().name || '';
			return `${startCase(name)} Style Guide`;
		},
		example: 'My Style Guide',
	},
	updateDocs: {
		type: 'function',
	},
	updateExample: {
		type: 'function',
		default: props => {
			if (props.lang === 'example') {
				props.lang = 'js';
				logger.warn(
					'"example" code block language is deprecated. Use "js", "jsx" or "javascript" instead:\n' +
						consts.DOCS_DOCUMENTING
				);
			}
			return props;
		},
	},
	updateWebpackConfig: {
		type: 'function',
		removed: `Use "webpackConfig" option instead:\n${consts.DOCS_WEBPACK}`,
	},
	usageMode: {
		type: 'string',
		process: (value, config) => {
			return config.showUsage === undefined ? value : config.showUsage ? 'expand' : 'collapse';
		},
		default: 'collapse',
	},
	verbose: {
		type: 'boolean',
		default: false,
	},
	version: {
		type: 'string',
	},
	webpackConfig: {
		type: ['object', 'function'],
		process: val => {
			if (val) {
				return val;
			}

			const file = findUserWebpackConfig();
			if (file) {
				logger.info(`Loading webpack config from:\n${file}`);
				// eslint-disable-next-line import/no-dynamic-require
				return require(file);
			}

			logger.warn(
				'No webpack config found. ' +
					'You may need to specify "webpackConfig" option in your style guide config:\n' +
					consts.DOCS_WEBPACK
			);

			return undefined;
		},
		example: {
			module: {
				rules: [
					{
						test: /\.jsx?$/,
						exclude: /node_modules/,
						loader: 'babel-loader',
					},
				],
			},
		},
	},
};
<|endoftext|>


<commit_before> $(document).ready(function() {
   $('.dropdown-toggle').dropdown()
 });
 var map;
 var baseHeatUrl = "http://kurama:6080/arcgis/rest/services/Hackathon/HackData/FeatureServer/0";
 var routesFeatureUrl = "http://kurama:6080/arcgis/rest/services/Hackathon/HackData/FeatureServer/1";
 var allTimes = [];
 var dailyAverage = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
 var dailyAverageComputed = false;

 require(["esri/map",
     "esri/layers/FeatureLayer",
     "esri/tasks/QueryTask",
     "esri/tasks/query",
     "esri/InfoTemplate",
     "esri/symbols/SimpleMarkerSymbol",
     "esri/symbols/SimpleLineSymbol",
     "esri/symbols/SimpleFillSymbol",
     "esri/renderers/HeatmapRenderer",
     "esri/renderers/SimpleRenderer",
     "esri/geometry/Circle",
     "esri/graphic",
     "esri/dijit/Search",
     "dojox/charting/Chart2D",
     "dojox/charting/themes/MiamiNice",
     "dojox/charting/action2d/Highlight", "dojox/charting/action2d/MoveSlice", "dojox/charting/action2d/Tooltip",
     "dojo/_base/Color",
     "dojo/dom",
     "dojo/dom-class",
     "dojo/on",
     "dijit/form/DateTextBox",
     "dojo/domReady!"
   ],

   function(Map, FeatureLayer, QueryTask, Query, InfoTemplate,
     SimpleMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, HeatmapRenderer, SimpleRenderer,
     Circle, Graphic,
     Search, Chart2D, dojoxTheme, Highlight, MoveSlice, Tooltip, Color, dom, domClass, on, DateTextBox) {

     map = new Map("map", {
       basemap: "streets-night-vector", //For full list of pre-defined basemaps, navigate to http://arcg.is/1JVo6Wd
       center: [-73.8291346, 40.88389], // longitude, latitude THE REAL ONES ARE: -73.8291346, 40.88389 //not real: -122.086, 40.01803741
       zoom: 15
     });

     var circleSymb = new SimpleFillSymbol(
       SimpleFillSymbol.STYLE_NULL,
       new SimpleLineSymbol(
         SimpleLineSymbol.STYLE_SHORTDASHDOTDOT,
         new Color([105, 105, 105]),
         2
       ), new Color([255, 255, 0, 0.25])
     );

     var lineSymb = new SimpleLineSymbol(
            SimpleLineSymbol.STYLE_SOLID,
            new Color([247, 34, 101, 0.9]),
            1
          );

     var search = new Search({
       map: map
     }, "search");
     search.startup();

     var infoTemplate = new InfoTemplate("Attributes",
       "device_id: ${device_id}
Time: ${timestamp_}");

     var heatmapFeatureLayerOptions = {
       mode: FeatureLayer.MODE_SNAPSHOT,
       outFields: ["device_id", "timestamp_"],
       infoTemplate: infoTemplate
     };

     //the point featurelayer
     var heatmapFeatureLayer = new FeatureLayer(baseHeatUrl, heatmapFeatureLayerOptions);

     //the polyline FeatureLayer
     var routeLayer = new FeatureLayer(routesFeatureUrl, {
       mode: FeatureLayer.MODE_ONDEMAND,
       outFields: ["END_TIME", "Day_", "DeviceID"]
     });

     var heatmapRenderer = new HeatmapRenderer();
     heatmapFeatureLayer.setRenderer(heatmapRenderer);
     map.addLayer(heatmapFeatureLayer);

     routeLayer.setRenderer(new SimpleRenderer(lineSymb));
     map.addLayer(routeLayer);

     map.on("click", clickHandler);

     function clickHandler(evt) {
       console.log("Hi");

       circle = new Circle({
         center: evt.mapPoint,
         geodesic: true,
         radius: 0.01,
         radiusUnit: "esriMiles"
       });

       map.graphics.clear();
       var circleGraphic = new Graphic(circle, circleSymb);
       map.graphics.add(circleGraphic);

       var query = new Query();
       query.geometry = circle;
       query.orderByFields = ["END_TIME DESC"];
       routeLayer.queryFeatures(query, function(featureset) {
         var allFeats = featureset.features;

         allTimes = [];

         for (var i = 0; i < allFeats.length; i++) {
           var nowDate = new Date(allFeats[i].attributes.END_TIME*1000);
           allTimes.push(nowDate);
         }
         initHistograms();
       });
     }

     function initHistograms(){
        showChart();
     }
     function showChart(){
         if($("#histogrampanel").css("display") =="none"){
            $("#histogrampanel").css("display","block");
        }
        else{
             $("#chart").empty();
        }

        $("#closePanelBtn").click(function(){
            $("#chart").empty();
            if($("#histogrampanel").css("display") =="block"){
                $("#histogrampanel").css("display","none");
            }
        })

        var chart = new Chart2D($("#chart")[0]);
          domClass.add(chart, "chart");

          // Apply a color theme to the chart.
          chart.setTheme(dojoxTheme);
          // Add the only/default plot
          chart.addPlot("default", {
              type: "Columns",
              markers: true,
              gap: 5
          });

         chart.resize(630,160);

          // Define the data
          var chartData = [10000,9200,11811,12000,7662,13887,14200];

          new Highlight(chart, "default");
          new Tooltip(chart, "default");
          new MoveSlice(chart, "default");

          // Add axes
          chart.addAxis("x",{
                  labels: [
                     {value: 0, text: ""},
			         {value: 1, text: "Mon"},
			         {value: 2, text: "Tue"},
			         {value: 3, text: "Wed"},
			         {value: 4, text: "Thu"},
			         {value: 5, text: "Fri"},
                     {value: 6, text: "Sat"},
                     {value: 7, text: "Sun"}
                  ]
          });
          chart.addAxis("y", { vertical: true, fixLower: "major", fixUpper: "major" });

          // Add the series of data
          chart.addSeries("Monthly Sales",chartData);

          // Render the chart!
          chart.render();

     }

     function calcDailyAverage(){
       if(!dailyAverageComputed){
         var dailySum = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]];
         var uniqueDays = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];

         dailyAverageComputed = true;

         for(var i=0; i<allTimes.length; i++){
           hour = allTimes[i].getHours();
           dailySum[hour].push(allTimes[i]);
         }
         for(var i=0; i<24; i++){
           for(var j=1; j<dailySum[i].length; j++){ //loop through to get all unique days
             if(dailySum[i][j].getDate() != dailySum[i][j-1].getDate()){
               uniqueDays[i]++;
             }
           }
           dailyAverage[i] = dailySum[i].length/uniqueDays[i];
         }
       }//finished computing daily average for all days at hourly interval
     }

   });
<commit_msg>displaying chart<commit_after> $(document).ready(function() {
   $('.dropdown-toggle').dropdown()
 });
 var map;
 var baseHeatUrl = "http://kurama:6080/arcgis/rest/services/Hackathon/HackData/FeatureServer/0";
 var routesFeatureUrl = "http://kurama:6080/arcgis/rest/services/Hackathon/HackData/FeatureServer/1";
 var allTimes = [];
 var dailyAverage = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
 var dailyAverageComputed = false;

 require(["esri/map",
     "esri/layers/FeatureLayer",
     "esri/tasks/QueryTask",
     "esri/tasks/query",
     "esri/InfoTemplate",
     "esri/symbols/SimpleMarkerSymbol",
     "esri/symbols/SimpleLineSymbol",
     "esri/symbols/SimpleFillSymbol",
     "esri/renderers/HeatmapRenderer",
     "esri/renderers/SimpleRenderer",
     "esri/geometry/Circle",
     "esri/graphic",
     "esri/dijit/Search",
     "dojox/charting/Chart2D",
     "dojox/charting/themes/MiamiNice",
     "dojox/charting/action2d/Highlight", "dojox/charting/action2d/MoveSlice", "dojox/charting/action2d/Tooltip",
     "dojo/_base/Color",
     "dojo/dom",
     "dojo/dom-class",
     "dojo/on",
     "dijit/form/DateTextBox",
     "dojo/domReady!"
   ],

   function(Map, FeatureLayer, QueryTask, Query, InfoTemplate,
     SimpleMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, HeatmapRenderer, SimpleRenderer,
     Circle, Graphic,
     Search, Chart2D, dojoxTheme, Highlight, MoveSlice, Tooltip, Color, dom, domClass, on, DateTextBox) {

     map = new Map("map", {
       basemap: "streets-night-vector", //For full list of pre-defined basemaps, navigate to http://arcg.is/1JVo6Wd
       center: [-73.7761702, 41.0308234], // longitude, latitude THE REAL ONES ARE: -73.8291346, 40.88389 //not real: -122.086, 40.01803741
       zoom: 15
     });

     var circleSymb = new SimpleFillSymbol(
       SimpleFillSymbol.STYLE_NULL,
       new SimpleLineSymbol(
         SimpleLineSymbol.STYLE_SHORTDASHDOTDOT,
         new Color([105, 105, 105]),
         2
       ), new Color([255, 255, 0, 0.25])
     );

     var lineSymb = new SimpleLineSymbol(
            SimpleLineSymbol.STYLE_SOLID,
            new Color([247, 34, 101, 0.9]),
            1
          );

     var search = new Search({
       map: map
     }, "search");
     search.startup();

     var infoTemplate = new InfoTemplate("Attributes",
       "device_id: ${device_id}
Time: ${timestamp_}");

     var heatmapFeatureLayerOptions = {
       mode: FeatureLayer.MODE_SNAPSHOT,
       outFields: ["device_id", "timestamp_"],
       infoTemplate: infoTemplate
     };

     //the point featurelayer
     var heatmapFeatureLayer = new FeatureLayer(baseHeatUrl, heatmapFeatureLayerOptions);

     //the polyline FeatureLayer
     var routeLayer = new FeatureLayer(routesFeatureUrl, {
       mode: FeatureLayer.MODE_ONDEMAND,
       outFields: ["END_TIME", "Day_", "DeviceID"]
     });

     var heatmapRenderer = new HeatmapRenderer();
     heatmapFeatureLayer.setRenderer(heatmapRenderer);
     map.addLayer(heatmapFeatureLayer);

     routeLayer.setRenderer(new SimpleRenderer(lineSymb));
     map.addLayer(routeLayer);

     map.on("click", clickHandler);

     function clickHandler(evt) {
       console.log("Hi");

       circle = new Circle({
         center: evt.mapPoint,
         geodesic: true,
         radius: 0.01,
         radiusUnit: "esriMiles"
       });

       map.graphics.clear();
       var circleGraphic = new Graphic(circle, circleSymb);
       map.graphics.add(circleGraphic);

       var query = new Query();
       query.geometry = circle;
       query.orderByFields = ["END_TIME DESC"];
       routeLayer.queryFeatures(query, function(featureset) {
         var allFeats = featureset.features;

         allTimes = [];

         for (var i = 0; i < allFeats.length; i++) {
           var nowDate = new Date(allFeats[i].attributes.END_TIME*1000);
           allTimes.push(nowDate);
         }
         initHistograms();
       });
     }

     function initHistograms(){
       calcDailyAverage();
       showChart();
     }
     function showChart(){
         if($("#histogrampanel").css("display") =="none"){
            $("#histogrampanel").css("display","block");
        }
        else{
             $("#chart").empty();
        }

        $("#closePanelBtn").click(function(){
            $("#chart").empty();
            if($("#histogrampanel").css("display") =="block"){
                $("#histogrampanel").css("display","none");
            }
        })

        var chart = new Chart2D($("#chart")[0]);
          domClass.add(chart, "chart");

          // Apply a color theme to the chart.
          chart.setTheme(dojoxTheme);
          // Add the only/default plot
          chart.addPlot("default", {
              type: "Columns",
              markers: true,
              gap: 5
          });

         chart.resize(630,160);

          // Define the data
          // var chartData = [10000,9200,11811,12000,7662,13887,14200];
          var chartData = dailyAverage;

          new Highlight(chart, "default");
          new Tooltip(chart, "default");
          new MoveSlice(chart, "default");

          // // Add axes
          // chart.addAxis("x",{
          //         labels: [
          //            {value: 0, text: ""},
			    //      {value: 1, text: "Mon"},
			    //      {value: 2, text: "Tue"},
			    //      {value: 3, text: "Wed"},
			    //      {value: 4, text: "Thu"},
			    //      {value: 5, text: "Fri"},
          //            {value: 6, text: "Sat"},
          //            {value: 7, text: "Sun"}
          //         ]
          // });
          chart.addAxis("x", {fixLower: "major", fixUpper: "major"})
          chart.addAxis("y", { vertical: true, fixLower: "major", fixUpper: "major" });

          // Add the series of data
          chart.addSeries("Monthly Sales",chartData);

          // Render the chart!
          chart.render();

     }

     function calcDailyAverage(){
      //  if(!dailyAverageComputed){
         var dailySum = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]];
         var uniqueDays = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];

         dailyAverageComputed = true;
         console.log(allTimes.length);

         for(var i=0; i<allTimes.length; i++){
           hour = allTimes[i].getHours();
           uniqueDays[hour] = 1;
           dailySum[hour].push(allTimes[i]);
         }
         for(var i=0; i<24; i++){
           for(var j=1; j<dailySum[i].length; j++){ //loop through to get all unique days
             if(dailySum[i][j].getDate() != dailySum[i][j-1].getDate()){
               uniqueDays[i]++;
             }
           }
           if(uniqueDays[i]!=0){
             dailyAverage[i] = dailySum[i].length/uniqueDays[i];
           }else{
             dailyAverage[i] = 0;
           }
         }
      //  }//finished computing daily average for all days at hourly interval
     }

   });
<|endoftext|>


<commit_before><commit_msg>Updated the static site<commit_after><|endoftext|>


<commit_before>/**
 * AngularJS Tutorial 1
 * @author Nick Kaye <nick.c.kaye@gmail.com>
 */

/**
 * Main AngularJS Web Application
 */
var app = angular.module('tutorialWebApp', [
  'ngRoute','uiSwitch'
]);

/**
 * Configure the Routes
 */

app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    // Home
    .when("/", {templateUrl: "partials/home.html", controller: "PageCtrl"})
    // Pages
    .when("/signin", {templateUrl: "partials/user/signin.html", controller: "LoginCtrl"})
    .when("/signup", {templateUrl: "partials/user/signup.html", controller: "RegisterCtrl"})
    .when("/signupRequest", {templateUrl: "partials/user/signuprequest.html", controller: "AccountManagerCtrl"})
    .when("/accountsmanager", {templateUrl: "partials/user/accountsmanager.html", controller: "AccountManagerCtrl"})
    .when("/researcher", {templateUrl: "partials/user/researcher.html", controller: "ResearcherCtrl"})
    .when("/administrator", {templateUrl: "partials/user/administrator.html", controller: "AdministratorCtrl"})
    .when("/profile", {templateUrl: "partials/user/userprofile.html", controller: "ProfileCtrl"})
    .when("/about", {templateUrl: "partials/about.html", controller: "PageCtrl"})
    .when("/research", {templateUrl: "partials/faq.html", controller: "PageCtrl"})
    .when("/distribution", {templateUrl: "partials/distribution.html", controller: "MapCtrl"})
    .when("/sightings", {templateUrl: "partials/sightings.html", controller: "PageCtrl"})
    .when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
    // Blog
    .when("/blog", {templateUrl: "partials/blog.html", controller: "BlogCtrl"})
    .when("/blog/post", {templateUrl: "partials/blog_item.html", controller: "BlogCtrl"})
    // else 404
    .otherwise("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"});
}]);
<commit_msg>research controller added.<commit_after>/**
 * AngularJS Tutorial 1
 * @author Nick Kaye <nick.c.kaye@gmail.com>
 */

/**
 * Main AngularJS Web Application
 */
var app = angular.module('tutorialWebApp', [
  'ngRoute','uiSwitch'
]);

/**
 * Configure the Routes
 */

app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    // Home
    .when("/", {templateUrl: "partials/home.html", controller: "PageCtrl"})
    // Pages
    .when("/signin", {templateUrl: "partials/user/signin.html", controller: "LoginCtrl"})
    .when("/signup", {templateUrl: "partials/user/signup.html", controller: "RegisterCtrl"})
    .when("/signupRequest", {templateUrl: "partials/user/signuprequest.html", controller: "AccountManagerCtrl"})
    .when("/accountsmanager", {templateUrl: "partials/user/accountsmanager.html", controller: "AccountManagerCtrl"})
    .when("/researcher", {templateUrl: "partials/user/researcher.html", controller: "ResearcherCtrl"})
    .when("/administrator", {templateUrl: "partials/user/administrator.html", controller: "AdministratorCtrl"})
    .when("/profile", {templateUrl: "partials/user/userprofile.html", controller: "ProfileCtrl"})
    .when("/about", {templateUrl: "partials/about.html", controller: "PageCtrl"})
    .when("/research", {templateUrl: "partials/research/researchHome.html", controller: "ResearchHomeCtrl"})
    .when("/distribution", {templateUrl: "partials/distribution.html", controller: "MapCtrl"})
    .when("/sightings", {templateUrl: "partials/sightings.html", controller: "PageCtrl"})
    .when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
    // Blog
    .when("/blog", {templateUrl: "partials/blog.html", controller: "BlogCtrl"})
    .when("/blog/post", {templateUrl: "partials/blog_item.html", controller: "BlogCtrl"})
    // else 404
    .otherwise("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"});
}]);
<|endoftext|>


<commit_before>import React from 'react';
import RangeSlider from '../rangeSlider';

export default React.createClass({
  getInitialState() {
    return {freq: 300};
  },
  handleFreqChange(event) {
    let value = event.target.value;
    this.setState({freq: value});
    this.onFreqChange(value);
  },
  onFreqChange(value) {
    this.state.freq = value;
    this.props.onFreqChanged(value);
  },
  render() {
    return (

        <button className='btn btn__action' onClick={this.props.onPlay}>Play</button>
        <button className='btn btn__action' onClick={this.props.onStop}>Stop</button>
        <RangeSlider onValueChanged={this.onFreqChange} min={0} max={20000} step={100}/>

    );
  }
});

<commit_msg>fix class name<commit_after>import React from 'react';
import RangeSlider from '../rangeSlider';

export default React.createClass({
  getInitialState() {
    return {freq: 300};
  },
  handleFreqChange(event) {
    let value = event.target.value;
    this.setState({freq: value});
    this.onFreqChange(value);
  },
  onFreqChange(value) {
    this.state.freq = value;
    this.props.onFreqChanged(value);
  },
  render() {
    return (

        <button className='btn btn--action' onClick={this.props.onPlay}>Play</button>
        <button className='btn btn--action' onClick={this.props.onStop}>Stop</button>
        <RangeSlider onValueChanged={this.onFreqChange} min={0} max={20000} step={100}/>

    );
  }
});

<|endoftext|>