<commit_before>var wptmonitor = (function(window, $, wptmonitor){
    "use strict";

    var config = {
        histogramMaxLimit : 60 // in seconds
    };

    var chart;

    $(document).ready(function(){
        $('#histogramButton').on('click', function () {
            if(getSelectedJobsCount() == 0){
                alert('Please select job(s).');
                return;
            }
            var button = $(this);
            button.attr('disabled', 'disabled');
            var selectedJobs = $.makeArray($('#updateForm').find('select#jobs option:selected').map(function(){return this.value;}));

            try{
                drawHistogramForJobs(selectedJobs)
                .always(function(){
                    button.removeAttr('disabled');
                })
                .fail(function(e){
                    alert(e);
                });
            }catch(e){
                alert("Error: " + e);
                button.removeAttr('disabled');
            }
        });

        $('#hideHistograms').click(function(e){
            e.preventDefault();
            $('#histogramsContainer').slideUp(function(){
                $('#histogramOverlay').show();
                $('#histogram').empty();
                chart = null;
            });
        });
    });

    function isHistogramContainerHidden() {
        return $("#histogramsContainer").is(":hidden");
    }

    function showHistogramContainer(){
        var deferred = $.Deferred();
        var container = $("#histogramsContainer");
        if(container.is(":hidden")){
            container.slideDown(1000, function(){
                deferred.resolve();
            });
        } else {
            deferred.resolve();
        }

        return deferred.promise();
    }

    function drawHistogramForJobs(jobId) {
        var deferred = $.Deferred();
        var histogramContainerWasHidden = isHistogramContainerHidden();

        $.when(
            getHistogramDataForJobs(jobId),
            showHistogramContainer().done(function(){
                $('#histogramOverlay').fadeIn(100);
            })
        )
        .done(function(data){
            try{
                drawChart(data);
            }catch(e) {
                deferred.reject(e);
            }
            setTimeout(function(){
                $('#histogramOverlay').fadeOut(600, function(){
                    deferred.resolve();
                });
                if(histogramContainerWasHidden){
                    scrollToGraph();
                }
            }, 10);
        })
        .fail(function(e){
            deferred.reject(e);
        }).always(function(){
            setTimeout(function(){
                $('#histogramOverlay').fadeOut(600, function(){
                    deferred.resolve();
                });
            }, 10);
        });

        return deferred.promise();

    }

    function scrollToGraph() {
        var container = $("#histogramsContainer");
        $('html, body').animate({
            'scrollTop': container.offset().top - $(window).height() + container.height() },
            1000,
            'swing'
        );
    }

    var drawChart = (function(){
        var previousResolution;
        return function(data) {
            var currentResolution = $('select[name="histogramResolution"]').val();
            var graphs = [];

            for(var i in data.fields) {
                if(data.fields.hasOwnProperty(i)){
                    var field = data.fields[i];
                    graphs.push({
                        id         : data.fields[i],
                        title      : data.fieldJobLabelMap[field] + " " + data.fieldMetricMap[field],
                        balloonText: "[[title]]
[[value]] samples for [[category]] seconds",
                        valueField : field,
                        type       : 'smoothedLine',
                        fillAlphas : 0.5
                    });
                }
            }

            var chartScrollbar;

            if(scrollbarToBeDisplayed()) {
                chartScrollbar = {
                    autoGridCount    : true,
                    graph            : data.fields[0],
                    "scrollbarHeight": 20, hideResizeGrips: true
                    // ,updateOnReleaseOnly: true
                };
            }

            if(chart){
                chart.dataProvider = data.dataset;
                chart.graphs = graphs;

                chart.removeChartScrollbar();
                chart.chartScrollbar = chartScrollbar;

                if(previousResolution != currentResolution) {
                    chart.addListener('dataUpdated', function(){
                        chart.zoomOut();
                    });
                }

                chart.validateData();
            }else {
                chart = AmCharts.makeChart("histogram", {
                    type               : "serial",
                    theme              : "none",
                    pathToImages       : "js/amcharts/images/",
                    dataProvider       : data.dataset,
                    zoomOutOnDataUpdate: false,
                    valueAxes: [
                        {
                            title     : 'samples count',
                            titleBold : false,
                            axisAlpha : 0.2,
                            dashLength: 1,
                            position  : "left",
                            minimum   : 0
                            // ,unit: "s"
                        }
                    ],
                    graphs        : graphs,
                    chartScrollbar: chartScrollbar,
                    chartCursor: {
                        cursorPosition           : "mouse",
                        categoryBalloonDateFormat: "MMM DD JJ:NN:SS",
                        cursorAlpha              : 0.5,
                        graphBulletSize          : 2
                    },
                    categoryField: "bucket",
                    categoryAxis: {
                        minorGridEnabled: false,
                        title           : 'time in seconds',
                        titleBold       : false,
                        minimum         : 0,
                        categoryFunction: function (e) {
                            return (e / 1000).toString();
                        }
                    },
                    legend: {
                        fontSize: 9
                    },
                    exportConfig : {}
                });
            }

            previousResolution = currentResolution;
        }
    })();

    function getHistogramDataForJobs(jobId) {
        var deferred = $.Deferred();
        $.when.apply($, $(jobId).map(function(){
                    return getHistogramDataForJob(this);
                }))
                .done(function(){
                    try{
                        var dataConverted = convertHistogramData(arguments);
                        deferred.resolve(dataConverted);
                    }catch(e) {
                        deferred.reject(e);
                        throw e;
                    }
                })
                .always(function(){

                })
                .fail(function(e){
                    deferred.reject(e);
                });
        return deferred.promise();
    }

    /**
     *
     * @param {{bucketWidth, minBucket, maxBucket, jobId, fields: [], datasets: {metric, series: {bucket, count}[], maxBucket, minBucket}[], jobLabel}[]} data
     * @returns {{dataset: {}, fields: Array, fieldJobIdMap: {}, fieldJobLabelMap: {}, fieldMetricMap: {}}}
     */
    function convertHistogramData(data) {

        var dataConverted = {};
        var minBucket = getMinBucket();
        var maxBucket = getMaxBucket();
        var bucketWidth = getBucketWidth();
        var fields = [];
        var fieldJobIdMap = {};
        var fieldJobLabelMap = {};
        var fieldMetricMap = {};
        var i, j, k; //iterators

        if(maxBucket > minBucket) {
            for (i=minBucket-bucketWidth; i <= maxBucket+bucketWidth; i+=bucketWidth) {
              if(i < 0) {
                  continue;
              }
              dataConverted[i] = {bucket: i};
              for(j in data){
                  if(data.hasOwnProperty(j)){
                      for(k in data[j].fields){
                          if(data[j].fields.hasOwnProperty(k)){
                              dataConverted[i][data[j].fields[k] + "-" + data[j].jobId] = 0;
                          }
                      }
                  }
              }
            }
        }

        for(var jobIndex in data) {
            if(data.hasOwnProperty(jobIndex)) {
                for (var metricIndex in data[jobIndex].datasets) {
                    if(data[jobIndex].datasets.hasOwnProperty(metricIndex)){
                        var valueField = data[jobIndex].datasets[metricIndex].metric + "-" + data[jobIndex].jobId;
                        for (i in data[jobIndex].datasets[metricIndex].series) {
                            if(data[jobIndex].datasets[metricIndex].series.hasOwnProperty(i)){
                                dataConverted[data[jobIndex].datasets[metricIndex].series[i].bucket][valueField] = data[jobIndex].datasets[metricIndex].series[i].count;
                            }
                        }
                        fields.push(valueField);
                        fieldJobIdMap[valueField] = data[jobIndex].jobId;
                        fieldJobLabelMap[valueField] = data[jobIndex].jobLabel;
                        fieldMetricMap[valueField] = data[jobIndex].datasets[metricIndex].metric;
                    }
                }
            }
        }

        dataConverted = $.map(dataConverted, function(element){
            return element;
        });

        return {
            dataset         : dataConverted,
            fields          : fields,
            fieldJobIdMap   : fieldJobIdMap,
            fieldJobLabelMap: fieldJobLabelMap,
            fieldMetricMap  : fieldMetricMap
        };

        function getMinBucket() {
            var minBucket = null;
            for(var i in data){
                if(data.hasOwnProperty(i)) {
                    if (minBucket === null || minBucket > data[i].minBucket) {
                        minBucket = data[i].minBucket;
                    }
                }
            }
            return minBucket;
        }

        function getMaxBucket() {
            var maxBucket = null;
            for(var i in data){
                if(data.hasOwnProperty(i)) {
                    if (maxBucket === null || maxBucket < data[i].maxBucket) {
                        maxBucket = data[i].maxBucket;
                    }
                }
            }
            return maxBucket;
        }

        function getBucketWidth() {
            var bucketWidth = null;

            for(var i in data){
                if(data.hasOwnProperty(i)){
                    if(bucketWidth !== null && bucketWidth !== data[i].bucketWidth) {
                        throw "Different bucket widths in datasets";
                    }
                    bucketWidth = data[i].bucketWidth;
                }
            }

            return bucketWidth;
        }

    }

    function getHistogramDataForJob(jobId) {
        var deferred = $.Deferred();

        var params = getFormParams();

        params.job = jobId;

        $.ajax({
           url: 'jash/getHistogramData.json.php',
           data: params
        }).done(function(data){
            if(data.status !== 200) {
                deferred.reject(data.message);
            } else {
                deferred.resolve(data.results);
            }
        }).error(function(jqxhr, errorType, exception){
            var errorMessage = exception || errorType;
            deferred.reject(errorMessage);
        });

        return deferred.promise();
    }

    function getSelectedJobsCount() {
        var val = $('#jobs').val();
        if(val == null) {
            return 0;
        }
        return val.length;
    }

    function getFormParams() {
        return {
            startYear  : $('select[name="startYear"]').val(),
            startMonth : $('select[name="startMonth"]').val(),
            startDay   : $('select[name="startDay"]').val(),
            startHour  : $('select[name="startHour"]').val(),
            endYear    : $('select[name="endYear"]').val(),
            endMonth   : $('select[name="endMonth"]').val(),
            endDay     : $('select[name="endDay"]').val(),
            endHour    : $('select[name="endHour"]').val(),
            timeFrame  : $("#timeFrame").val(),
            field      : $.makeArray($("input[name='fields[]']:checked").map(function(){
                return $(this).val();
            })),
            histMinLimit: $('select[name="histogramMinLimit"]').val(),
            histMaxLimit: $('select[name="histogramMaxLimit"]').val(),
            histogramResolution: $('select[name="histogramResolution"]').val()
        };
    }

    function scrollbarToBeDisplayed() {
        return $('input[name="displayHistogramScrollbar"]').prop('checked');
    }

    wptmonitor.histograms = {
        initialized: true,
        getChart   : function () {
            return chart;
        }
    };

    return wptmonitor;
})(window, jQuery, wptmonitor || {});
<commit_msg>removed unused variable<commit_after>var wptmonitor = (function(window, $, wptmonitor){
    "use strict";

    var chart;

    $(document).ready(function(){
        $('#histogramButton').on('click', function () {
            if(getSelectedJobsCount() == 0){
                alert('Please select job(s).');
                return;
            }
            var button = $(this);
            button.attr('disabled', 'disabled');
            var selectedJobs = $.makeArray($('#updateForm').find('select#jobs option:selected').map(function(){return this.value;}));

            try{
                drawHistogramForJobs(selectedJobs)
                .always(function(){
                    button.removeAttr('disabled');
                })
                .fail(function(e){
                    alert(e);
                });
            }catch(e){
                alert("Error: " + e);
                button.removeAttr('disabled');
            }
        });

        $('#hideHistograms').click(function(e){
            e.preventDefault();
            $('#histogramsContainer').slideUp(function(){
                $('#histogramOverlay').show();
                $('#histogram').empty();
                chart = null;
            });
        });
    });

    function isHistogramContainerHidden() {
        return $("#histogramsContainer").is(":hidden");
    }

    function showHistogramContainer(){
        var deferred = $.Deferred();
        var container = $("#histogramsContainer");
        if(container.is(":hidden")){
            container.slideDown(1000, function(){
                deferred.resolve();
            });
        } else {
            deferred.resolve();
        }

        return deferred.promise();
    }

    function drawHistogramForJobs(jobId) {
        var deferred = $.Deferred();
        var histogramContainerWasHidden = isHistogramContainerHidden();

        $.when(
            getHistogramDataForJobs(jobId),
            showHistogramContainer().done(function(){
                $('#histogramOverlay').fadeIn(100);
            })
        )
        .done(function(data){
            try{
                drawChart(data);
            }catch(e) {
                deferred.reject(e);
            }
            setTimeout(function(){
                $('#histogramOverlay').fadeOut(600, function(){
                    deferred.resolve();
                });
                if(histogramContainerWasHidden){
                    scrollToGraph();
                }
            }, 10);
        })
        .fail(function(e){
            deferred.reject(e);
        }).always(function(){
            setTimeout(function(){
                $('#histogramOverlay').fadeOut(600, function(){
                    deferred.resolve();
                });
            }, 10);
        });

        return deferred.promise();

    }

    function scrollToGraph() {
        var container = $("#histogramsContainer");
        $('html, body').animate({
            'scrollTop': container.offset().top - $(window).height() + container.height() },
            1000,
            'swing'
        );
    }

    var drawChart = (function(){
        var previousResolution;
        return function(data) {
            var currentResolution = $('select[name="histogramResolution"]').val();
            var graphs = [];

            for(var i in data.fields) {
                if(data.fields.hasOwnProperty(i)){
                    var field = data.fields[i];
                    graphs.push({
                        id         : data.fields[i],
                        title      : data.fieldJobLabelMap[field] + " " + data.fieldMetricMap[field],
                        balloonText: "[[title]]
[[value]] samples for [[category]] seconds",
                        valueField : field,
                        type       : 'smoothedLine',
                        fillAlphas : 0.5
                    });
                }
            }

            var chartScrollbar;

            if(scrollbarToBeDisplayed()) {
                chartScrollbar = {
                    autoGridCount    : true,
                    graph            : data.fields[0],
                    "scrollbarHeight": 20, hideResizeGrips: true
                    // ,updateOnReleaseOnly: true
                };
            }

            if(chart){
                chart.dataProvider = data.dataset;
                chart.graphs = graphs;

                chart.removeChartScrollbar();
                chart.chartScrollbar = chartScrollbar;

                if(previousResolution != currentResolution) {
                    chart.addListener('dataUpdated', function(){
                        chart.zoomOut();
                    });
                }

                chart.validateData();
            }else {
                chart = AmCharts.makeChart("histogram", {
                    type               : "serial",
                    theme              : "none",
                    pathToImages       : "js/amcharts/images/",
                    dataProvider       : data.dataset,
                    zoomOutOnDataUpdate: false,
                    valueAxes: [
                        {
                            title     : 'samples count',
                            titleBold : false,
                            axisAlpha : 0.2,
                            dashLength: 1,
                            position  : "left",
                            minimum   : 0
                            // ,unit: "s"
                        }
                    ],
                    graphs        : graphs,
                    chartScrollbar: chartScrollbar,
                    chartCursor: {
                        cursorPosition           : "mouse",
                        categoryBalloonDateFormat: "MMM DD JJ:NN:SS",
                        cursorAlpha              : 0.5,
                        graphBulletSize          : 2
                    },
                    categoryField: "bucket",
                    categoryAxis: {
                        minorGridEnabled: false,
                        title           : 'time in seconds',
                        titleBold       : false,
                        minimum         : 0,
                        categoryFunction: function (e) {
                            return (e / 1000).toString();
                        }
                    },
                    legend: {
                        fontSize: 9
                    },
                    exportConfig : {}
                });
            }

            previousResolution = currentResolution;
        }
    })();

    function getHistogramDataForJobs(jobId) {
        var deferred = $.Deferred();
        $.when.apply($, $(jobId).map(function(){
                    return getHistogramDataForJob(this);
                }))
                .done(function(){
                    try{
                        var dataConverted = convertHistogramData(arguments);
                        deferred.resolve(dataConverted);
                    }catch(e) {
                        deferred.reject(e);
                        throw e;
                    }
                })
                .always(function(){

                })
                .fail(function(e){
                    deferred.reject(e);
                });
        return deferred.promise();
    }

    /**
     *
     * @param {{bucketWidth, minBucket, maxBucket, jobId, fields: [], datasets: {metric, series: {bucket, count}[], maxBucket, minBucket}[], jobLabel}[]} data
     * @returns {{dataset: {}, fields: Array, fieldJobIdMap: {}, fieldJobLabelMap: {}, fieldMetricMap: {}}}
     */
    function convertHistogramData(data) {

        var dataConverted = {};
        var minBucket = getMinBucket();
        var maxBucket = getMaxBucket();
        var bucketWidth = getBucketWidth();
        var fields = [];
        var fieldJobIdMap = {};
        var fieldJobLabelMap = {};
        var fieldMetricMap = {};
        var i, j, k; //iterators

        if(maxBucket > minBucket) {
            for (i=minBucket-bucketWidth; i <= maxBucket+bucketWidth; i+=bucketWidth) {
              if(i < 0) {
                  continue;
              }
              dataConverted[i] = {bucket: i};
              for(j in data){
                  if(data.hasOwnProperty(j)){
                      for(k in data[j].fields){
                          if(data[j].fields.hasOwnProperty(k)){
                              dataConverted[i][data[j].fields[k] + "-" + data[j].jobId] = 0;
                          }
                      }
                  }
              }
            }
        }

        for(var jobIndex in data) {
            if(data.hasOwnProperty(jobIndex)) {
                for (var metricIndex in data[jobIndex].datasets) {
                    if(data[jobIndex].datasets.hasOwnProperty(metricIndex)){
                        var valueField = data[jobIndex].datasets[metricIndex].metric + "-" + data[jobIndex].jobId;
                        for (i in data[jobIndex].datasets[metricIndex].series) {
                            if(data[jobIndex].datasets[metricIndex].series.hasOwnProperty(i)){
                                dataConverted[data[jobIndex].datasets[metricIndex].series[i].bucket][valueField] = data[jobIndex].datasets[metricIndex].series[i].count;
                            }
                        }
                        fields.push(valueField);
                        fieldJobIdMap[valueField] = data[jobIndex].jobId;
                        fieldJobLabelMap[valueField] = data[jobIndex].jobLabel;
                        fieldMetricMap[valueField] = data[jobIndex].datasets[metricIndex].metric;
                    }
                }
            }
        }

        dataConverted = $.map(dataConverted, function(element){
            return element;
        });

        return {
            dataset         : dataConverted,
            fields          : fields,
            fieldJobIdMap   : fieldJobIdMap,
            fieldJobLabelMap: fieldJobLabelMap,
            fieldMetricMap  : fieldMetricMap
        };

        function getMinBucket() {
            var minBucket = null;
            for(var i in data){
                if(data.hasOwnProperty(i)) {
                    if (minBucket === null || minBucket > data[i].minBucket) {
                        minBucket = data[i].minBucket;
                    }
                }
            }
            return minBucket;
        }

        function getMaxBucket() {
            var maxBucket = null;
            for(var i in data){
                if(data.hasOwnProperty(i)) {
                    if (maxBucket === null || maxBucket < data[i].maxBucket) {
                        maxBucket = data[i].maxBucket;
                    }
                }
            }
            return maxBucket;
        }

        function getBucketWidth() {
            var bucketWidth = null;

            for(var i in data){
                if(data.hasOwnProperty(i)){
                    if(bucketWidth !== null && bucketWidth !== data[i].bucketWidth) {
                        throw "Different bucket widths in datasets";
                    }
                    bucketWidth = data[i].bucketWidth;
                }
            }

            return bucketWidth;
        }

    }

    function getHistogramDataForJob(jobId) {
        var deferred = $.Deferred();

        var params = getFormParams();

        params.job = jobId;

        $.ajax({
           url: 'jash/getHistogramData.json.php',
           data: params
        }).done(function(data){
            if(data.status !== 200) {
                deferred.reject(data.message);
            } else {
                deferred.resolve(data.results);
            }
        }).error(function(jqxhr, errorType, exception){
            var errorMessage = exception || errorType;
            deferred.reject(errorMessage);
        });

        return deferred.promise();
    }

    function getSelectedJobsCount() {
        var val = $('#jobs').val();
        if(val == null) {
            return 0;
        }
        return val.length;
    }

    function getFormParams() {
        return {
            startYear  : $('select[name="startYear"]').val(),
            startMonth : $('select[name="startMonth"]').val(),
            startDay   : $('select[name="startDay"]').val(),
            startHour  : $('select[name="startHour"]').val(),
            endYear    : $('select[name="endYear"]').val(),
            endMonth   : $('select[name="endMonth"]').val(),
            endDay     : $('select[name="endDay"]').val(),
            endHour    : $('select[name="endHour"]').val(),
            timeFrame  : $("#timeFrame").val(),
            field      : $.makeArray($("input[name='fields[]']:checked").map(function(){
                return $(this).val();
            })),
            histMinLimit: $('select[name="histogramMinLimit"]').val(),
            histMaxLimit: $('select[name="histogramMaxLimit"]').val(),
            histogramResolution: $('select[name="histogramResolution"]').val()
        };
    }

    function scrollbarToBeDisplayed() {
        return $('input[name="displayHistogramScrollbar"]').prop('checked');
    }

    wptmonitor.histograms = {
        initialized: true,
        getChart   : function () {
            return chart;
        }
    };

    return wptmonitor;
})(window, jQuery, wptmonitor || {});
<|endoftext|>


<commit_before>import React, { PropTypes, View, ScrollView, StyleSheet, Text, Linking } from 'react-native';

import moment from 'moment/min/moment-with-locales';
import HTMLView from 'react-native-htmlview';

import DigiHeader from '../../common/DigiHeader';
import EventVenue from './EventVenue';

moment.locale('fr');

export default function Event({ event, navigator }) {
  return (
    <View style={styles.container}>
      <DigiHeader
        title="Évement"
        leftItem={{
          icon: require('../../common/img/back_white.png'),
          onPress: () => navigator.pop(),
        }}
      />
      <ScrollView style={styles.scrollview}>
        <Text style={styles.title}>
          {event.Event.name}
        </Text>
        <Text style={styles.date}>
          {moment(event.Event.start_at).format('dddd D MMMM YYYY')}
        </Text>
        <HTMLView
          value={event.Event.description}
          onLinkPress={url => Linking.openURL(url)}
        />
        <EventVenue
          venue={event.Venue}
        />
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollview: {
    flex: 1,
    padding: 10,
  },
  title: {
    fontSize: 24,
    fontWeight: '500',
  },
  date: {
    fontSize: 18,
    marginBottom: 10,
  },
});

Event.propTypes = {
  event: PropTypes.object.isRequired,
  navigator: PropTypes.object.isRequired,
};
<commit_msg>fix typo<commit_after>import React, { PropTypes, View, ScrollView, StyleSheet, Text, Linking } from 'react-native';

import moment from 'moment/min/moment-with-locales';
import HTMLView from 'react-native-htmlview';

import DigiHeader from '../../common/DigiHeader';
import EventVenue from './EventVenue';

moment.locale('fr');

export default function Event({ event, navigator }) {
  return (
    <View style={styles.container}>
      <DigiHeader
        title="Évènement"
        leftItem={{
          icon: require('../../common/img/back_white.png'),
          onPress: () => navigator.pop(),
        }}
      />
      <ScrollView style={styles.scrollview}>
        <Text style={styles.title}>
          {event.Event.name}
        </Text>
        <Text style={styles.date}>
          {moment(event.Event.start_at).format('dddd D MMMM YYYY')}
        </Text>
        <HTMLView
          value={event.Event.description}
          onLinkPress={url => Linking.openURL(url)}
        />
        <EventVenue
          venue={event.Venue}
        />
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollview: {
    flex: 1,
    padding: 10,
  },
  title: {
    fontSize: 24,
    fontWeight: '500',
  },
  date: {
    fontSize: 18,
    marginBottom: 10,
  },
});

Event.propTypes = {
  event: PropTypes.object.isRequired,
  navigator: PropTypes.object.isRequired,
};
<|endoftext|>


<commit_before>/**
* search trials
*
* @author Isaak Y Tecle <iyt2@cornell.edu>
*
*/

jQuery(document).ready(function(){

    jQuery.ajax({
        type: 'POST',
        dataType: "json",
        url: '/solgs/search/trials/',
        success: function(res) {
            var trialsList = listTrials(res.trials);
            var pagination = res.pagination;
            jQuery("#homepage_trials_list").html(trialsList + pagination).show();
        },
        error: function() {
            alert('error fetching first 10 trials');
        }

    });

    jQuery("#homepage_trials_list").on('click', "div.paginate_nav a", function(e) {
        var page = jQuery(this).attr('href');

        if (page) {
            jQuery.ajax({
                type: 'POST',
                dataType: "json",
                url: page,
                success: function(res) {
                    var trialsList = listTrials(res.trials);
                    var pagination = res.pagination;
                    jQuery("#homepage_trials_list").empty();
                    jQuery("#homepage_trials_list").html(trialsList + pagination).show();

                },

                error: function() {
                    alert('error fetching trials next pages.');
                }
            });
        }

        return false;
    });

});

function listTrials (trials)  {

    var table = '
';
    table    += '
';
    table += '	Trial	Description	Location	Year	';
    table += '
';

    for (var i=0; i<10; i++) {

        if (trials[i]) {
            table += '
';
            table += '' + trials[i][0] + '	'
                + '' + trials[i][1] + '	'
                + '' + trials[i][2] + '	'
                + '' + trials[i][3] + '	'
                + '' + trials[i][4] + '	';
            table += '
';
        }
    }

    table += '
';

    return table;

}

<commit_msg>request trials search when document ready..<commit_after>/**
* search trials
*
* @author Isaak Y Tecle <iyt2@cornell.edu>
*
*/

jQuery(document).ready(function(){
    searchTrials();
});

function searchTrials() {

    jQuery.ajax({
        type: 'POST',
        dataType: "json",
        url: '/solgs/search/trials/',
        success: function(res) {
            var trialsList = listTrials(res.trials);
            var pagination = res.pagination;
            jQuery("#homepage_trials_list").html(trialsList + pagination).show();
        },
        error: function() {
            alert('error fetching first 10 trials');
        }
    });

    jQuery("#homepage_trials_list").on('click', "div.paginate_nav a", function(e) {
        var page = jQuery(this).attr('href');

        if (page) {
            jQuery.ajax({
                type: 'POST',
                dataType: "json",
                url: page,
                success: function(res) {
                    var trialsList = listTrials(res.trials);
                    var pagination = res.pagination;
                    jQuery("#homepage_trials_list").empty();
                    jQuery("#homepage_trials_list").html(trialsList + pagination).show();

                },

                error: function() {
                    alert('error fetching trials next pages.');
                }
            });
        }

        return false;
    });

}

function listTrials (trials)  {

    var table = '
';
    table    += '
';
    table += '	Trial	Description	Location	Year	';
    table += '
';

    for (var i=0; i<10; i++) {

        if (trials[i]) {
            table += '
';
            table += '' + trials[i][0] + '	'
                + '' + trials[i][1] + '	'
                + '' + trials[i][2] + '	'
                + '' + trials[i][3] + '	'
                + '' + trials[i][4] + '	';
            table += '
';
        }
    }

    table += '
';

    return table;

}

<|endoftext|>


<commit_before>define(["js/ui/View", "require"], function(View, require) {

    return View.inherit("js.ui.ComponentLoader", {

        defaults: {
            type: null,
            error: null,
            load: true,

            instance: null,
            loading: false,
            componentClass: "component-loader {class()}"
        },

        "class": function() {
            return [
                this.$.loading ? "loading" : "",
                this.$.error ? "error" : ""
            ].join(" ")

        }.onChange("loading", "error"),

        _renderLoad: function(load) {
            if (load) {
                this._load();
            }
        },

        clear: function() {

            var instance = this.$.instance;
            if (instance) {
                this.removeChild(instance);
            }

            this.set({
                instance: null,
                loading: false,
                error: null
            });
        },

        _load: function(type, callback) {

            var self = this;

            if (arguments[0] instanceof Function) {
                callback = type;
                type = null;
            }

            type = type || this.$.type;

            if (!type) {
                callback && callback("No type specified");
                return;
            }

            if (this.$.loading) {
                return;
            }

            this.set("loading", true);

            require([this.$stage.$applicationContext.getFqClassName(type)], function(Factory) {

                var attributes = {};
                for (var key in self.$) {
                    //noinspection JSUnfilteredForInLoop
                    if (!self.factory.prototype.defaults.hasOwnProperty(key)) {
                        //noinspection JSUnfilteredForInLoop
                        if (self.$bindingAttributes.hasOwnProperty(key)) {
                            // pass the binding attribute
                            //noinspection JSUnfilteredForInLoop
                            attributes[key] = self.$bindingAttributes[key].value;
                        } else {
                            // direct value
                            //noinspection JSUnfilteredForInLoop
                            attributes[key] = self.$[key];
                        }

                    }
                }

                var instance = self.createComponent(Factory, attributes);
                self.addChild(instance);
                self.set({
                    instance: instance,
                    loading: false
                });

                callback && callback(null, instance);

            }, function(e) {
                self.set({
                    error: e,
                    loading: false
                });

                callback && callback(e);
            });

        }

    });

});<commit_msg>fixed setting of eventDefinitions<commit_after>define(["js/ui/View", "require"], function(View, require) {

    return View.inherit("js.ui.ComponentLoader", {

        defaults: {
            type: null,
            error: null,
            load: true,

            instance: null,
            loading: false,
            componentClass: "component-loader {class()}"
        },

        "class": function() {
            return [
                this.$.loading ? "loading" : "",
                this.$.error ? "error" : ""
            ].join(" ")

        }.onChange("loading", "error"),

        _renderLoad: function(load) {
            if (load) {
                this._load();
            }
        },

        clear: function() {

            var instance = this.$.instance;
            if (instance) {
                this.removeChild(instance);
            }

            this.set({
                instance: null,
                loading: false,
                error: null
            });
        },

        _load: function(type, callback) {

            var self = this;

            if (arguments[0] instanceof Function) {
                callback = type;
                type = null;
            }

            type = type || this.$.type;

            if (!type) {
                callback && callback("No type specified");
                return;
            }

            if (this.$.loading) {
                return;
            }

            this.set("loading", true);

            require([this.$stage.$applicationContext.getFqClassName(type)], function(Factory) {

                var attributes = {};
                for (var key in self.$) {
                    //noinspection JSUnfilteredForInLoop
                    if (!self.factory.prototype.defaults.hasOwnProperty(key)) {
                        //noinspection JSUnfilteredForInLoop
                        if (self.$bindingAttributes.hasOwnProperty(key)) {
                            // pass the binding attribute
                            //noinspection JSUnfilteredForInLoop
                            attributes[key] = self.$bindingAttributes[key].value;
                        } else {
                            // direct value
                            //noinspection JSUnfilteredForInLoop
                            attributes[key] = self.$[key];
                        }

                    }
                }

                var instance = self.createComponent(Factory, attributes);
                // use event definitions
                instance.$eventDefinitions = self.$eventDefinitions;

                self.addChild(instance);
                self.set({
                    instance: instance,
                    loading: false
                });

                callback && callback(null, instance);

            }, function(e) {
                self.set({
                    error: e,
                    loading: false
                });

                callback && callback(e);
            });

        }

    });

});<|endoftext|>


<commit_before>import $ from 'jquery';
import Sortable from 'sortablejs';
import '../../utils/jquery-utils';

export default class CollectionsField {
    constructor() {
        this.lists = $();

        $('[data-type="collection"]').each((index, list) => this.addList(list));
        $('body').on('mutation._grav', this._onAddedNodes.bind(this));

    }

    addList(list) {
        list = $(list);
        this.lists = this.lists.add(list);

        list.on('click', '> .collection-actions [data-action="add"]', (event) => this.addItem(event));
        list.on('click', '> ul > li > .item-actions [data-action="delete"]', (event) => this.removeItem(event));

        list.find('[data-collection-holder]').each((index, container) => {
            container = $(container);
            if (container.data('collection-sort')) { return; }

            container.data('collection-sort', new Sortable(container.get(0), {
                forceFallback: true,
                animation: 150,
                onUpdate: () => this.reindex(container)
            }));
        });
    }

    addItem(event) {
        let button = $(event.currentTarget);
        let list = button.closest('[data-type="collection"]');
        let template = $(list.find('> [data-collection-template="new"]').data('collection-template-html'));

        list.find('> [data-collection-holder]').append(template);
        this.reindex(list);
        // button.data('key-index', keyIndex + 1);

        // process markdown editors
        /* var field = template.find('[name]').filter('textarea');
        if (field.length && field.data('grav-mdeditor') && typeof MDEditors !== 'undefined') {
            MDEditors.add(field);
        }*/
    }

    removeItem(event) {
        let button = $(event.currentTarget);
        let item = button.closest('[data-collection-item]');
        let list = button.closest('[data-type="collection"]');

        item.remove();
        this.reindex(list);
    }

    reindex(list) {
        list = $(list).closest('[data-type="collection"]');

        let items = list.find('> ul > [data-collection-item]');

        items.each((index, item) => {
            item = $(item);
            item.attr('data-collection-key', index);

            ['name', 'data-grav-field-name', 'id', 'for'].forEach((prop) => {
                item.find('[' + prop + ']').each(function() {
                    let element = $(this);
                    let indexes = [];
                    element.parents('[data-collection-key]').map((idx, parent) => indexes.push($(parent).attr('data-collection-key')));
                    indexes.reverse();

                    let replaced = element.attr(prop).replace(/\[(\d+|\*)\]/g, (/* str, p1, offset */) => {
                        return `[${indexes.shift()}]`;
                    });

                    element.attr(prop, replaced);
                });
            });

        });
    }

    _onAddedNodes(event, target/* , record, instance */) {
        let collections = $(target).find('[data-type="collection"]');
        if (!collections.length) { return; }

        collections.each((index, collection) => {
            collection = $(collection);
            if (!~this.lists.index(collection)) {
                this.addList(collection);
            }
        });
    }
}

export let Instance = new CollectionsField();
<commit_msg>Exclude CodeMirror from SortableJS<commit_after>import $ from 'jquery';
import Sortable from 'sortablejs';
import '../../utils/jquery-utils';

export default class CollectionsField {
    constructor() {
        this.lists = $();

        $('[data-type="collection"]').each((index, list) => this.addList(list));
        $('body').on('mutation._grav', this._onAddedNodes.bind(this));

    }

    addList(list) {
        list = $(list);
        this.lists = this.lists.add(list);

        list.on('click', '> .collection-actions [data-action="add"]', (event) => this.addItem(event));
        list.on('click', '> ul > li > .item-actions [data-action="delete"]', (event) => this.removeItem(event));

        list.find('[data-collection-holder]').each((index, container) => {
            container = $(container);
            if (container.data('collection-sort')) { return; }

            container.data('collection-sort', new Sortable(container.get(0), {
                forceFallback: true,
                animation: 150,
                filter: '.CodeMirror',
                onUpdate: () => this.reindex(container)
            }));
        });
    }

    addItem(event) {
        let button = $(event.currentTarget);
        let list = button.closest('[data-type="collection"]');
        let template = $(list.find('> [data-collection-template="new"]').data('collection-template-html'));

        list.find('> [data-collection-holder]').append(template);
        this.reindex(list);
        // button.data('key-index', keyIndex + 1);

        // process markdown editors
        /* var field = template.find('[name]').filter('textarea');
        if (field.length && field.data('grav-mdeditor') && typeof MDEditors !== 'undefined') {
            MDEditors.add(field);
        }*/
    }

    removeItem(event) {
        let button = $(event.currentTarget);
        let item = button.closest('[data-collection-item]');
        let list = button.closest('[data-type="collection"]');

        item.remove();
        this.reindex(list);
    }

    reindex(list) {
        list = $(list).closest('[data-type="collection"]');

        let items = list.find('> ul > [data-collection-item]');

        items.each((index, item) => {
            item = $(item);
            item.attr('data-collection-key', index);

            ['name', 'data-grav-field-name', 'id', 'for'].forEach((prop) => {
                item.find('[' + prop + ']').each(function() {
                    let element = $(this);
                    let indexes = [];
                    element.parents('[data-collection-key]').map((idx, parent) => indexes.push($(parent).attr('data-collection-key')));
                    indexes.reverse();

                    let replaced = element.attr(prop).replace(/\[(\d+|\*)\]/g, (/* str, p1, offset */) => {
                        return `[${indexes.shift()}]`;
                    });

                    element.attr(prop, replaced);
                });
            });

        });
    }

    _onAddedNodes(event, target/* , record, instance */) {
        let collections = $(target).find('[data-type="collection"]');
        if (!collections.length) { return; }

        collections.each((index, collection) => {
            collection = $(collection);
            if (!~this.lists.index(collection)) {
                this.addList(collection);
            }
        });
    }
}

export let Instance = new CollectionsField();
<|endoftext|>


<commit_before>/** July 2012. Josh de Leeuw

	This plugin gives the user the ability to execute an arbitrary function
	during an experiment. It can be used to save data in the middle of an
	experiment, for example.

	Params:
		"type" is "call_function"
		"func" is the function that will be called
		"args" is an array of arguments to pass to the function. (optional)

	Data:
		The return value of the function will be stored in the data.
**/

(function( $ ) {
	jsPsych.call_function = (function(){

		var plugin = {};

		plugin.create = function(params) {
			var trials = new Array(1);
			trials[0] = {
				"type": "call_function",
				"func": params["func"],
				"args": params["args"] || []
			}
			return trials;
		}

		plugin.trial = function($this, block, trial, part)
		{
			block.data[block.trial_idx] = trial.func.apply({}, trial.args);

			block.next();
		}

		return plugin;
	})();
})(jQuery);<commit_msg>fixed bug in call-function<commit_after>/** July 2012. Josh de Leeuw

	This plugin gives the user the ability to execute an arbitrary function
	during an experiment. It can be used to save data in the middle of an
	experiment, for example.

	Params:
		"type" is "call_function"
		"func" is the function that will be called
		"args" is an array of arguments to pass to the function. (optional)

	Data:
		The return value of the function will be stored in the data.
**/

(function( $ ) {
	jsPsych.call_function = (function(){

		var plugin = {};

		plugin.create = function(params) {
			var trials = new Array(1);
			trials[0] = {
				"type": "call_function",
				"func": params["func"],
				"args": params["args"] || []
			}
			return trials;
		}

		plugin.trial = function($this, block, trial, part)
		{
			block.data[block.trial_idx] = trial.func.apply({}, [trial.args]);

			block.next();
		}

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


<commit_before>'use strict';
var _ = require('lodash');
var Promise = require('bluebird');
var security = require('../core/utils/security');
var models = require('../models');
var moment = require('moment');
var AppError = require('./app-error')

var middleware = module.exports

var checkAuthToken = function (authToken) {
  var objToken = security.parseToken(authToken);
  return models.Users.findOne({
    where: {identical: objToken.identical}
  })
  .then((users) => {
    if (_.isEmpty(users)) {
      throw new AppError.Unauthorized();
    }
    return models.UserTokens.findOne({
      where: {tokens: authToken, uid: users.id, expires_at: { gt: moment().format('YYYY-MM-DD HH:mm:ss') }}
    })
    .then((tokenInfo) => {
      if (_.isEmpty(tokenInfo)){
        throw new AppError.Unauthorized()
      }
      return users;
    })
  }).then((users) => {
    return users;
  })
}

var checkAccessToken = function (accessToken) {
  return new Promise((resolve, reject) => {
    if (_.isEmpty(accessToken)) {
      throw new AppError.Unauthorized();
    }
    var config = require('../core/config');
    var tokenSecret = _.get(config, 'jwt.tokenSecret');
    var jwt = require('jsonwebtoken');
    var authData = jwt.verify(accessToken, tokenSecret);
    var uid = _.get(authData, 'uid', null);
    var hash = _.get(authData, 'hash', null);
    if (parseInt(uid) > 0) {
      return models.Users.findOne({
        where: {id: uid}
      })
      .then((users) => {
        if (_.isEmpty(users)) {
          throw new AppError.Unauthorized();
        }
        if (!_.eq(hash, security.md5(users.get('ack_code')))){
          throw new AppError.Unauthorized();
        }
        resolve(users);
      })
      .catch((e) => {
        reject(e);
      });
    } else {
      reject(new AppError.Unauthorized());
    }
  });
}

middleware.checkToken = function(req, res, next) {
  var authArr = _.split(req.get('Authorization'), ' ');
  var authType = 1;
  var authToken = null;
  if (_.eq(authArr[0], 'Bearer')) {
    authType = 1;
    authToken = authArr[1]; //Bearer
  } else if(_.eq(authArr[0], 'Basic')) {
    authType = 2;
    var b = new Buffer(authArr[1], 'base64');
    var user = _.split(b.toString(), ':');
    authToken = _.get(user, '1');
  } else {
    authType = 2;
    authToken = _.trim(_.trimStart(_.get(req, 'query.access_token', null)));
  }
  if (authType == 1) {
    checkAuthToken(authToken)
    .then((users) => {
      req.users = users;
      next();
      return users;
    })
    .catch((e) => {
      if (e instanceof AppError.AppError) {
        res.status(e.status || 404).send(e.message);
      } else {
        next(e);
      }
    });
  } else if (authType == 2) {
    checkAccessToken(authToken)
    .then((users) => {
      req.users = users;
      next();
      return users;
    })
    .catch((e) => {
      if (e instanceof AppError.AppError) {
        res.status(e.status || 404).send(e.message);
      } else {
        next(e);
      }
    });
  } else {
    res.send(new AppError.Unauthorized(`Auth type not supported.`));
  }
};
<commit_msg>fix jwt<commit_after>'use strict';
var _ = require('lodash');
var Promise = require('bluebird');
var security = require('../core/utils/security');
var models = require('../models');
var moment = require('moment');
var AppError = require('./app-error')

var middleware = module.exports

var checkAuthToken = function (authToken) {
  var objToken = security.parseToken(authToken);
  return models.Users.findOne({
    where: {identical: objToken.identical}
  })
  .then((users) => {
    if (_.isEmpty(users)) {
      throw new AppError.Unauthorized();
    }
    return models.UserTokens.findOne({
      where: {tokens: authToken, uid: users.id, expires_at: { gt: moment().format('YYYY-MM-DD HH:mm:ss') }}
    })
    .then((tokenInfo) => {
      if (_.isEmpty(tokenInfo)){
        throw new AppError.Unauthorized()
      }
      return users;
    })
  }).then((users) => {
    return users;
  })
}

var checkAccessToken = function (accessToken) {
  return new Promise((resolve, reject) => {
    if (_.isEmpty(accessToken)) {
      throw new AppError.Unauthorized();
    }
    var config = require('../core/config');
    var tokenSecret = _.get(config, 'jwt.tokenSecret');
    var jwt = require('jsonwebtoken');
    try {
      var authData = jwt.verify(accessToken, tokenSecret);
    } catch (e) {
      reject(new AppError.Unauthorized());
    }
    var uid = _.get(authData, 'uid', null);
    var hash = _.get(authData, 'hash', null);
    if (parseInt(uid) > 0) {
      return models.Users.findOne({
        where: {id: uid}
      })
      .then((users) => {
        if (_.isEmpty(users)) {
          throw new AppError.Unauthorized();
        }
        if (!_.eq(hash, security.md5(users.get('ack_code')))){
          throw new AppError.Unauthorized();
        }
        resolve(users);
      })
      .catch((e) => {
        reject(e);
      });
    } else {
      reject(new AppError.Unauthorized());
    }
  });
}

middleware.checkToken = function(req, res, next) {
  var authArr = _.split(req.get('Authorization'), ' ');
  var authType = 1;
  var authToken = null;
  if (_.eq(authArr[0], 'Bearer')) {
    authType = 1;
    authToken = authArr[1]; //Bearer
  } else if(_.eq(authArr[0], 'Basic')) {
    authType = 2;
    var b = new Buffer(authArr[1], 'base64');
    var user = _.split(b.toString(), ':');
    authToken = _.get(user, '1');
  } else {
    authType = 2;
    authToken = _.trim(_.trimStart(_.get(req, 'query.access_token', null)));
  }
  if (authType == 1) {
    checkAuthToken(authToken)
    .then((users) => {
      req.users = users;
      next();
      return users;
    })
    .catch((e) => {
      if (e instanceof AppError.AppError) {
        res.status(e.status || 404).send(e.message);
      } else {
        next(e);
      }
    });
  } else if (authType == 2) {
    checkAccessToken(authToken)
    .then((users) => {
      req.users = users;
      next();
      return users;
    })
    .catch((e) => {
      if (e instanceof AppError.AppError) {
        res.status(e.status || 404).send(e.message);
      } else {
        next(e);
      }
    });
  } else {
    res.send(new AppError.Unauthorized(`Auth type not supported.`));
  }
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Oculus Info Inc.
 * http://www.oculusinfo.com/
 *
 * Released under the MIT License.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
/* global activityLogger */
define(function (require) {
    "use strict";

    return {

        generateUuid: function() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random()*16|0, v = (c === 'x') ? r : (r&0x3|0x8);
                return v.toString(16);
            });
        },

        enableTooltip: function( $elem, message, openFunc, closeFunc ) {

            return true;

            /*
            var tooltipOpened = false,
                pendingCallback;

            $elem.attr('title', '');
            $elem.tooltip({
                content: message,
                track: true,
                show: { delay: 800 },
                open: function() {
                    // wait until tooltip actually opens before calling
                    pendingCallback = setTimeout( function() {
                        tooltipOpened = true;
                        if (openFunc) {
                            openFunc();
                        }
                    }, 800);
                },
                close: function() {
                    // cancel any pending callback
                    clearTimeout( pendingCallback );
                    if ( tooltipOpened ) {
                        // only call if the tooltip actually opened
                        if (closeFunc) {
                            closeFunc();
                        }
                    }
                    // clear flags on close
                    tooltipOpened = false;
                }
            });
            */
        },

        enableScrollBars: function( $elem, $parent ) {

            if ( $elem.length === 0 ) {
                return;
            }

            // add scroll panel to element
            $elem.jScrollPane({ verticalGutter: 0, horizontalGutter: 0, verticalDragMinHeight: 32, horizontalDragMinWidth: 32 });
            // if parent is resizeable, set callback to change scrollbar size
            if ( $parent && $parent.is('.ui-resizable') ) {
                $parent.on("resize", function() {
                    // update scroll panel on parent resize
                    $elem.data('jsp').reinitialise();
                });
            }
        },

        disableTooltip: function( $elem ) {
            $elem.tooltip('disable');
        },

        /**
         * Allows the given DOM element or jQuery object events to propagate through
         * and interact with underlying elements
         */
        enableEventPropagation: function( elem, events ) {

            var domElement = ( elem instanceof jQuery ) ? elem[0] : elem,
                i;

            function propagateEvent( event ) {
                var newEvent = new event.constructor( event.type, event ),
                    $elem,
                    before,
                    below;

                $elem = $( event.currentTarget );
                before = $elem.css( 'pointer-events' );
                $elem.css( 'pointer-events', 'none' );
                below = document.elementFromPoint( event.clientX, event.clientY );
                if ( below ) {
                    below.dispatchEvent( newEvent );
                }
                $elem.css( 'pointer-events', before );
            }

            $( domElement ).addClass( 'propagate' );

            if ( !events ) {
                domElement.onmousedown = propagateEvent;
                domElement.onmouseup = propagateEvent;
                domElement.onmousemove = propagateEvent;
                domElement.onwheel = propagateEvent;
                domElement.onscroll = propagateEvent;
                domElement.onclick = propagateEvent;
                domElement.ondblclick = propagateEvent;
            } else {
                events = ($.isArray) ? events : [events];
                for (i=0; i<events.length; i++) {
                    domElement[events[i]] = propagateEvent;
                }
            }
        },

        disableEventPropagation: function( elem, events ) {

            var domElement = (elem instanceof jQuery) ? elem[0] : elem,
                i;
            if ( !events ) {
                domElement.onmousedown = null;
                domElement.onmouseup = null;
                domElement.onmousemove = null;
                domElement.onwheel = null;
                domElement.onscroll = null;
                domElement.onclick = null;
                domElement.ondblclick = null;
            } else {
                events = ($.isArray) ? events : [events];
                for (i=0; i<events.length; i++) {
                    domElement[events[i]] = null;
                }
            }

        },

        /**
         * Registers a click handler that only fires if the click didn't
         * involve a map drag. Since the map is moving under the mouse cursor
         * the browser will still register a click despite mouse movement. This
         * guards against that.
         */
        dragSensitiveClick : function( node, handler, threshold ) {
            var dragStart = {x: null, y: null};

            threshold = threshold || 10;

            node.on('mousedown', function(evt) {
                dragStart.x = evt.pageX;
                dragStart.y = evt.pageY;
            });

            node.on('click', function(evt) {
                if (Math.abs(dragStart.x-evt.pageX) < threshold &&
                    Math.abs(dragStart.y-evt.pageY) < threshold ) {
                    handler.call(this, evt);
                }
            });
        },

        hexToRgb: function(hex) {
            var bigint;

            // remove #
            hex = hex.replace(/#/, '');

            // if only 3 hex values are provided, expand into 6 digit hex code
            if ( hex.length === 3 ) {
                hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
            }

            bigint = parseInt(hex, 16);
            return {
                r: (bigint >> 16) & 255,
                g: (bigint >> 8) & 255,
                b: bigint & 255
            };
        },

        rgbToHex: function( rgb ) {
            var r = rgb.r,
                g = rgb.g,
                b = rgb.b;
            function componentToHex(c) {
                var hex = c.toString(16);
                return (hex.length === 1) ? "0" + hex : hex;
            }
            return "#" + componentToHex( Math.floor(r)) +
                         componentToHex( Math.floor(g)) +
                         componentToHex( Math.floor(b));
        },

        hexBrightness: function( hex, factor ) {
            var rgb = this.hexToRgb( hex );
            return this.rgbToHex( { r: Math.min( Math.max( 0, rgb.r * factor ), 255 ),
                                    g: Math.min( Math.max( 0, rgb.g * factor ), 255 ),
                                    b: Math.min( Math.max( 0, rgb.b * factor ), 255 ) } );
        },

        hexGreyscale: function( hex ) {
            var rgb = this.hexToRgb( hex ),
                avg = ( rgb.r * 0.21 + rgb.g * 0.72 + rgb.b * 0.07 );
            return this.rgbToHex({
                r: avg,
                g: avg,
                b: avg
            });
        },

        hexBlend: function( hex1, hex2 ) {
            var rgb1 = this.hexToRgb( hex1 ),
                rgb2 = this.hexToRgb( hex2 );

            return this.rgbToHex({
                r : ( rgb1.r + rgb2.r ) / 2,
                g : ( rgb1.g + rgb2.g ) / 2,
                b : ( rgb1.b + rgb2.b ) / 2
            });

        },

        hexPercentageBlend: function( colors, percentages ) {
            var rgbs = [], i,
                rgb = {
                    r : 0,
                    g : 0,
                    b : 0
                };
            // convert hex to rgb
            for ( i=0; i<colors.length; i++ ) {
                rgbs.push( this.hexToRgb( colors[i] ) );
            }
            // apply weights
            for ( i=0; i<percentages.length; i++ ) {
                rgb.r += rgbs[i].r * percentages[i];
                rgb.g += rgbs[i].g * percentages[i];
                rgb.b += rgbs[i].b * percentages[i];
            }
            return this.rgbToHex( rgb );
        },

         parseMalformedJson: function( jsonString ) {
            // replace ( and ) with [ and ]
            var squared = jsonString.replace( /\(/g, '[' ).replace( /\)/g, ']'),
                // ensure all attributes are quoted in ""
                quoted = squared.replace(/([a-zA-Z0-9]+)(:)/g,'"$1"$2');
            return JSON.parse( quoted );
        },

        getURLParameter: function (key) {
            var url = window.location.search.substring(1),
                urlVars = url.split('&'),
                i, varKey,
                result = 0;
            for (i=0; i<urlVars.length; ++i) {
                varKey = urlVars[i].split('=');
                if (key === varKey[0]) {
                    result = varKey[1];
                    break;
                }
            }
            return result;
        }

    };
});
<commit_msg>Remvoed check for resizability in Util.enableScrollBars as it did not work as intending.<commit_after>/*
 * Copyright (c) 2014 Oculus Info Inc.
 * http://www.oculusinfo.com/
 *
 * Released under the MIT License.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
/* global activityLogger */
define(function (require) {
    "use strict";

    return {

        generateUuid: function() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random()*16|0, v = (c === 'x') ? r : (r&0x3|0x8);
                return v.toString(16);
            });
        },

        enableTooltip: function( $elem, message, openFunc, closeFunc ) {

            return true;

            /*
            var tooltipOpened = false,
                pendingCallback;

            $elem.attr('title', '');
            $elem.tooltip({
                content: message,
                track: true,
                show: { delay: 800 },
                open: function() {
                    // wait until tooltip actually opens before calling
                    pendingCallback = setTimeout( function() {
                        tooltipOpened = true;
                        if (openFunc) {
                            openFunc();
                        }
                    }, 800);
                },
                close: function() {
                    // cancel any pending callback
                    clearTimeout( pendingCallback );
                    if ( tooltipOpened ) {
                        // only call if the tooltip actually opened
                        if (closeFunc) {
                            closeFunc();
                        }
                    }
                    // clear flags on close
                    tooltipOpened = false;
                }
            });
            */
        },

        enableScrollBars: function( $elem, $parent ) {

            if ( $elem.length === 0 ) {
                return;
            }

            // add scroll panel to element
            $elem.jScrollPane({ verticalGutter: 0, horizontalGutter: 0, verticalDragMinHeight: 32, horizontalDragMinWidth: 32 });
            // if parent is resizeable, set callback to change scrollbar size
            if ( $parent ) {
                $parent.on("resize", function() {
                    // update scroll panel on parent resize
                    $elem.data('jsp').reinitialise();
                });
            }
        },

        disableTooltip: function( $elem ) {
            $elem.tooltip('disable');
        },

        /**
         * Allows the given DOM element or jQuery object events to propagate through
         * and interact with underlying elements
         */
        enableEventPropagation: function( elem, events ) {

            var domElement = ( elem instanceof jQuery ) ? elem[0] : elem,
                i;

            function propagateEvent( event ) {
                var newEvent = new event.constructor( event.type, event ),
                    $elem,
                    before,
                    below;

                $elem = $( event.currentTarget );
                before = $elem.css( 'pointer-events' );
                $elem.css( 'pointer-events', 'none' );
                below = document.elementFromPoint( event.clientX, event.clientY );
                if ( below ) {
                    below.dispatchEvent( newEvent );
                }
                $elem.css( 'pointer-events', before );
            }

            $( domElement ).addClass( 'propagate' );

            if ( !events ) {
                domElement.onmousedown = propagateEvent;
                domElement.onmouseup = propagateEvent;
                domElement.onmousemove = propagateEvent;
                domElement.onwheel = propagateEvent;
                domElement.onscroll = propagateEvent;
                domElement.onclick = propagateEvent;
                domElement.ondblclick = propagateEvent;
            } else {
                events = ($.isArray) ? events : [events];
                for (i=0; i<events.length; i++) {
                    domElement[events[i]] = propagateEvent;
                }
            }
        },

        disableEventPropagation: function( elem, events ) {

            var domElement = (elem instanceof jQuery) ? elem[0] : elem,
                i;
            if ( !events ) {
                domElement.onmousedown = null;
                domElement.onmouseup = null;
                domElement.onmousemove = null;
                domElement.onwheel = null;
                domElement.onscroll = null;
                domElement.onclick = null;
                domElement.ondblclick = null;
            } else {
                events = ($.isArray) ? events : [events];
                for (i=0; i<events.length; i++) {
                    domElement[events[i]] = null;
                }
            }

        },

        /**
         * Registers a click handler that only fires if the click didn't
         * involve a map drag. Since the map is moving under the mouse cursor
         * the browser will still register a click despite mouse movement. This
         * guards against that.
         */
        dragSensitiveClick : function( node, handler, threshold ) {
            var dragStart = {x: null, y: null};

            threshold = threshold || 10;

            node.on('mousedown', function(evt) {
                dragStart.x = evt.pageX;
                dragStart.y = evt.pageY;
            });

            node.on('click', function(evt) {
                if (Math.abs(dragStart.x-evt.pageX) < threshold &&
                    Math.abs(dragStart.y-evt.pageY) < threshold ) {
                    handler.call(this, evt);
                }
            });
        },

        hexToRgb: function(hex) {
            var bigint;

            // remove #
            hex = hex.replace(/#/, '');

            // if only 3 hex values are provided, expand into 6 digit hex code
            if ( hex.length === 3 ) {
                hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
            }

            bigint = parseInt(hex, 16);
            return {
                r: (bigint >> 16) & 255,
                g: (bigint >> 8) & 255,
                b: bigint & 255
            };
        },

        rgbToHex: function( rgb ) {
            var r = rgb.r,
                g = rgb.g,
                b = rgb.b;
            function componentToHex(c) {
                var hex = c.toString(16);
                return (hex.length === 1) ? "0" + hex : hex;
            }
            return "#" + componentToHex( Math.floor(r)) +
                         componentToHex( Math.floor(g)) +
                         componentToHex( Math.floor(b));
        },

        hexBrightness: function( hex, factor ) {
            var rgb = this.hexToRgb( hex );
            return this.rgbToHex( { r: Math.min( Math.max( 0, rgb.r * factor ), 255 ),
                                    g: Math.min( Math.max( 0, rgb.g * factor ), 255 ),
                                    b: Math.min( Math.max( 0, rgb.b * factor ), 255 ) } );
        },

        hexGreyscale: function( hex ) {
            var rgb = this.hexToRgb( hex ),
                avg = ( rgb.r * 0.21 + rgb.g * 0.72 + rgb.b * 0.07 );
            return this.rgbToHex({
                r: avg,
                g: avg,
                b: avg
            });
        },

        hexBlend: function( hex1, hex2 ) {
            var rgb1 = this.hexToRgb( hex1 ),
                rgb2 = this.hexToRgb( hex2 );

            return this.rgbToHex({
                r : ( rgb1.r + rgb2.r ) / 2,
                g : ( rgb1.g + rgb2.g ) / 2,
                b : ( rgb1.b + rgb2.b ) / 2
            });

        },

        hexPercentageBlend: function( colors, percentages ) {
            var rgbs = [], i,
                rgb = {
                    r : 0,
                    g : 0,
                    b : 0
                };
            // convert hex to rgb
            for ( i=0; i<colors.length; i++ ) {
                rgbs.push( this.hexToRgb( colors[i] ) );
            }
            // apply weights
            for ( i=0; i<percentages.length; i++ ) {
                rgb.r += rgbs[i].r * percentages[i];
                rgb.g += rgbs[i].g * percentages[i];
                rgb.b += rgbs[i].b * percentages[i];
            }
            return this.rgbToHex( rgb );
        },

         parseMalformedJson: function( jsonString ) {
            // replace ( and ) with [ and ]
            var squared = jsonString.replace( /\(/g, '[' ).replace( /\)/g, ']'),
                // ensure all attributes are quoted in ""
                quoted = squared.replace(/([a-zA-Z0-9]+)(:)/g,'"$1"$2');
            return JSON.parse( quoted );
        },

        getURLParameter: function (key) {
            var url = window.location.search.substring(1),
                urlVars = url.split('&'),
                i, varKey,
                result = 0;
            for (i=0; i<urlVars.length; ++i) {
                varKey = urlVars[i].split('=');
                if (key === varKey[0]) {
                    result = varKey[1];
                    break;
                }
            }
            return result;
        }

    };
});
<|endoftext|>


<commit_before>import test from 'ava';
import NoticeZ from '../dist/NoticeZ.min.js'
import browserEnv from 'browser-env';

test.beforeEach(t => {
  browserEnv(['window', 'document']);
});

test('Display at bottom right by default', t => {
	let noti = NoticeZ('default noti', 'hi');
  let noti_in_browser = document.querySelector('.NoticeZ.bottom.right');
	t.is(noti, noti_in_browser);
});

test('Display at bottom right', t => {
	let noti = NoticeZ('hello', 'hi', {
    position: 'bottom right'
  });
  let noti_in_browser = document.querySelector('.NoticeZ.bottom.right');

	t.is(noti, noti_in_browser);
});

test('Display at bottom left', t => {
	let noti = NoticeZ('hello', 'hi', {
    position: 'bottom left'
  });
  let noti_in_browser = document.querySelector('.NoticeZ.bottom.left');

	t.is(noti, noti_in_browser);
});

test('Display at top right', t => {
	let noti = NoticeZ('hello', 'hi', {
    position: 'top right'
  });
  let noti_in_browser = document.querySelector('.NoticeZ.top.right');

	t.is(noti, noti_in_browser);
});

test('Display at top left', t => {
	let noti = NoticeZ('hello', 'hi', {
    position: 'top left'
  });
  let noti_in_browser = document.querySelector('.NoticeZ.top.left');

	t.is(noti, noti_in_browser);
});

<<<<<<< HEAD
=======

>>>>>>> c6777b3b7d363eda654da7dd67d2079e76a88294
test.cb('Disappeared in 2 millisecond', t => {
	let noti = NoticeZ('hello', 'hi', {
    position: 'top left',
    time: 2
  });

  setTimeout(() => {
    let noti_in_browser = document.querySelector('.NoticeZ.top.left');
    let is_noti_in_browser = noti_in_browser !== null;
    t.false(is_noti_in_browser);
    t.end();
  }, 3);
});
<commit_msg>resolved conflict with develop in test<commit_after>import test from 'ava';
import NoticeZ from '../dist/NoticeZ.min.js'
import browserEnv from 'browser-env';

test.beforeEach(t => {
  browserEnv(['window', 'document']);
});

test('Display at bottom right by default', t => {
	let noti = NoticeZ('default noti', 'hi');
  let noti_in_browser = document.querySelector('.NoticeZ.bottom.right');
	t.is(noti, noti_in_browser);
});

test('Display at bottom right', t => {
	let noti = NoticeZ('hello', 'hi', {
    position: 'bottom right'
  });
  let noti_in_browser = document.querySelector('.NoticeZ.bottom.right');

	t.is(noti, noti_in_browser);
});

test('Display at bottom left', t => {
	let noti = NoticeZ('hello', 'hi', {
    position: 'bottom left'
  });
  let noti_in_browser = document.querySelector('.NoticeZ.bottom.left');

	t.is(noti, noti_in_browser);
});

test('Display at top right', t => {
	let noti = NoticeZ('hello', 'hi', {
    position: 'top right'
  });
  let noti_in_browser = document.querySelector('.NoticeZ.top.right');

	t.is(noti, noti_in_browser);
});

test('Display at top left', t => {
	let noti = NoticeZ('hello', 'hi', {
    position: 'top left'
  });
  let noti_in_browser = document.querySelector('.NoticeZ.top.left');

	t.is(noti, noti_in_browser);
});

test.cb('Disappeared in 2 millisecond', t => {
	let noti = NoticeZ('hello', 'hi', {
    position: 'top left',
    time: 2
  });

  setTimeout(() => {
    let noti_in_browser = document.querySelector('.NoticeZ.top.left');
    let is_noti_in_browser = noti_in_browser !== null;
    t.false(is_noti_in_browser);
    t.end();
  }, 3);
});
<|endoftext|>