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

/**
 * Filters markers based on category
 */

//All distance variable use the unit - Kilometer

async function getMarkersByCategory() {
    const category = document.getElementById("category");
    const markers = await fetch("/marker").then(response => response.json());
    const markersToDisplay = filterByCategory(markers, category);
    return markersToDisplay;
}

function filterByCategory(markers, markerCategory) {
    const markersToDisplay = [];
    for (let marker in markers) {
        if (markers[marker].category.includes(markerCategory) === true) {
            markersToDisplay.push(markers[marker]);
        }
    }
    return markersToDisplay;
}

async function getMarkersByProximity() {
    const userLongitude = document.getElementById("user-longitude");
    const userLatitude = document.getElementById("user-latitude");
    const markerRadius = document.getElementById("marker-radius");
    const markers = await fetch("/marker").then(response => response.json());

    const markersToDisplay = filterByProximity(markers, markerRadius, userLongitude, userLatitude);
    return markersToDisplay;
}

function filterByProximity(markers, markerRadius, userLongitude, userLatitude) {

    for ( let marker in markers) {
        markers[marker]["distance"] = distanceBetweenTwoCoordinates(markers[marker].longitude, markers[marker].latitude, userLongitude, userLatitude);
    }

    const markersToDisplay = [];

    for (let marker in markers) {
        if (markers[marker].distance < markerRadius) {
            markersToDisplay.push(markers[marker]);
        }
    }

    for (let marker in markers) {
        delete markers[marker].distance;
    }

    return markersToDisplay;
}

function toRadians(degrees) {
    var pi = Math.PI;
    return degrees * (pi/180);
}

function distanceBetweenTwoCoordinates(longitudeA, latitudeA, longitudeB, latitudeB) {
    longitudeA = toRadians(longitudeA);
    latitudeA = toRadians(latitudeA);
    longitudeB = toRadians(longitudeB);
    latitudeB = toRadians(latitudeB);

    longitudeDifference = longitudeB - longitudeA;
    latitudeDifference = latitudeB - latitudeA;

    // using haversine formula
    a = Math.sin(latitudeDifference / 2) ** 2 + Math.cos(latitudeA) * Math.cos(latitudeB) * Math.sin(longitudeDifference / 2) ** 2;
    c = 2 * Math.asin(Math.sqrt(a));

    earthRadius = 6378;
    distance = earthRadius * c;

    return distance;
}

module.exports = {filterByCategory, filterByProximity};
<commit_msg>Simplified filter proximity function<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * Filters markers based on category
 */

//All distance variable use the unit - Kilometer

async function getMarkersByCategory() {
    const category = document.getElementById("category");
    const markers = await fetch("/marker").then(response => response.json());
    const markersToDisplay = filterByCategory(markers, category);
    return markersToDisplay;
}

function filterByCategory(markers, markerCategory) {
    const markersToDisplay = [];
    for (let marker in markers) {
        if (markers[marker].category.includes(markerCategory) === true) {
            markersToDisplay.push(markers[marker]);
        }
    }
    return markersToDisplay;
}

async function getMarkersByProximity() {
    const userLongitude = document.getElementById("user-longitude");
    const userLatitude = document.getElementById("user-latitude");
    const markerRadius = document.getElementById("marker-radius");
    const markers = await fetch("/marker").then(response => response.json());

    const markersToDisplay = filterByProximity(markers, markerRadius, userLongitude, userLatitude);
    return markersToDisplay;
}

function filterByProximity(markers, markerRadius, userLongitude, userLatitude) {

    const markersToDisplay = [];

    for (let marker in markers) {
        if (distanceBetweenTwoCoordinates(markers[marker].longitude, markers[marker].latitude, userLongitude, userLatitude) < markerRadius) {
            markersToDisplay.push(markers[marker]);
        }
    }
    return markersToDisplay;
}

function toRadians(degrees) {
    var pi = Math.PI;
    return degrees * (pi/180);
}

function distanceBetweenTwoCoordinates(longitudeA, latitudeA, longitudeB, latitudeB) {
    longitudeA = toRadians(longitudeA);
    latitudeA = toRadians(latitudeA);
    longitudeB = toRadians(longitudeB);
    latitudeB = toRadians(latitudeB);

    longitudeDifference = longitudeB - longitudeA;
    latitudeDifference = latitudeB - latitudeA;

    // using haversine formula
    a = Math.sin(latitudeDifference / 2) ** 2 + Math.cos(latitudeA) * Math.cos(latitudeB) * Math.sin(longitudeDifference / 2) ** 2;
    c = 2 * Math.asin(Math.sqrt(a));

    earthRadius = 6378;
    distance = earthRadius * c;

    return distance;
}

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


<commit_before>/// <reference path="../libs/_references.js" />
var betMania = betMania || {};

betMania.data = (function () {

    var saveUserData = function(user){
        localStorage.setItem("sessionKey", user.sessionKey);
        localStorage.setItem("nickname", user.nickname);
    }

    var clearUserData = function () {
        localStorage.removeItem("sessionKey");
        localStorage.removeItem("nickname");
    }

    var loadUserData = function(){
        sessionKey = localStorage.getItem("sessionKey");
    }

    var getNickname = function(){
        return localStorage.getItem("nickname");
    }

    var getSessionKey = function () {
        return localStorage.getItem("sessionKey");
    }

    var isUserLogged = function(){
        var sessionkey = localStorage.getItem("sessionKey");
        var nickname = localStorage.getItem("nickname");

        if (!sessionkey || !nickname) {
            return false;
        }
        return true;
    }

    var DataPersister = Class.create({
        init: function (baseUrl) {
            this.baseUrl = baseUrl;
            this.users = new UsersPersister(baseUrl + "/user/");
            this.matches = new MatchesPersister(baseUrl + "/matches/");
        },
        isUserLogged: function(){
            return isUserLogged();
        },
        loadUserData:function(){
            loadUserData();
        },
        getNickname: function(){
            return getNickname();
        }
    });

    var UsersPersister = Class.create({
        init: function(baseUrl){
            this.baseUrl = baseUrl;
        },
        login: function(username, password){
            var user = {
                username: username,
                authCode: CryptoJS.SHA1(username + password).toString()
            }

            return betMania.requester.postJSON(this.baseUrl + "login", user).
                then(function (result) {
                    saveUserData(result);
                });
        },
        register: function (username, password, nickname) {
            var user = {
                username: username,
                nickname: nickname,
                authCode: CryptoJS.SHA1(username + password).toString()
            }

            return betMania.requester.postJSON(this.baseUrl + "register", user).
                then(function (result) {
                    saveUserData(user);
                });
        },
        logout: function () {
            var headers = {
                "X-sessionKey": getSessionKey()
            }

            return betMania.requester.putJSON(this.baseUrl + "logout", {}, headers)
                .then(function () {
                    clearUserData();
                });
        },
        addMoney: function (ammount) {
            var headers = {
                "X-sessionKey": getSessionKey()
            }

            return betMania.requester.putJSON(this.baseUrl + "addmoney/" + ammount, {}, headers);
        },
        getUsers: function () {
            var headers = {
                "X-sessionKey": getSessionKey()
            }

            return betMania.requester.getJSON(this.baseUrl + "getusers/", headers)

        },
        deleteUser: function (userId) {
            var headers = {
                "X-sessionKey": getSessionKey()
            }

            return betMania.requester.deleteJSON(this.baseUrl + "delete/" + userId, headers);
        },
        modify: function (user) {
            var headers = {
                "X-sessionKey": getSessionKey()
            }

            return betMania.requester.putJSON(this.baseUrl + "modify", user, headers);
        }

    });

    var MatchesPersister = Class.create({
        init: function (baseUrl) {
            this.baseUrl = baseUrl;
        },
        getMatches: function (category, status, my, page, take) {
            var headers = {
                "X-sessionKey":""
            };
            var queryStartAdded = false;

            var url = this.baseUrl;
            var checkForQuery = function () {
                if (!queryStartAdded) {
                    url += "?"
                    queryStartAdded = true;
                }
            }

            if (category) {
                url += "?category=" + category + "&";
                queryStartAdded = true;
            }

            if (status) {
                checkForQuery();
                url += "status=" + status + "&";

            }

            if (my) {
                checkForQuery();
                url += "my=" + true + "&";
                headers["X-sessionKey"] = getSessionKey();
            }

            if (page) {
                checkForQuery();
                url += "page=" + page + "&";
            }

            if (take) {
                checkForQuery();
                url += "take=" + take;
            }

            return betMania.requester.getJSON(url, headers)
            .then(function (response, status, my) {
                debugger;
            }, function (err) {
                debugger;
            });
        }
    });

    return new DataPersister("/api");
}());<commit_msg>return result from login and register in the returned promise<commit_after>/// <reference path="../libs/_references.js" />
var betMania = betMania || {};

betMania.data = (function () {

    var saveUserData = function(user){
        localStorage.setItem("sessionKey", user.sessionKey);
        localStorage.setItem("nickname", user.nickname);
    }

    var clearUserData = function () {
        localStorage.removeItem("sessionKey");
        localStorage.removeItem("nickname");
    }

    var loadUserData = function(){
        sessionKey = localStorage.getItem("sessionKey");
    }

    var getNickname = function(){
        return localStorage.getItem("nickname");
    }

    var getSessionKey = function () {
        return localStorage.getItem("sessionKey");
    }

    var isUserLogged = function(){
        var sessionkey = localStorage.getItem("sessionKey");
        var nickname = localStorage.getItem("nickname");

        if (!sessionkey || !nickname) {
            return false;
        }
        return true;
    }

    var DataPersister = Class.create({
        init: function (baseUrl) {
            this.baseUrl = baseUrl;
            this.users = new UsersPersister(baseUrl + "/user/");
            this.matches = new MatchesPersister(baseUrl + "/matches/");
        },
        isUserLogged: function(){
            return isUserLogged();
        },
        loadUserData:function(){
            loadUserData();
        },
        getNickname: function(){
            return getNickname();
        }
    });

    var UsersPersister = Class.create({
        init: function(baseUrl){
            this.baseUrl = baseUrl;
        },
        login: function(username, password){
            var user = {
                username: username,
                authCode: CryptoJS.SHA1(username + password).toString()
            }

            return betMania.requester.postJSON(this.baseUrl + "login", user).
                then(function (result) {
                    saveUserData(result);
                    return result;
                });
        },
        register: function (username, password, nickname) {
            var user = {
                username: username,
                nickname: nickname,
                authCode: CryptoJS.SHA1(username + password).toString()
            }

            return betMania.requester.postJSON(this.baseUrl + "register", user).
                then(function (result) {
                    saveUserData(result);
                    return result;
                });
        },
        logout: function () {
            var headers = {
                "X-sessionKey": getSessionKey()
            }

            return betMania.requester.putJSON(this.baseUrl + "logout", {}, headers)
                .then(function () {
                    clearUserData();
                });
        },
        addMoney: function (ammount) {
            var headers = {
                "X-sessionKey": getSessionKey()
            }

            return betMania.requester.putJSON(this.baseUrl + "addmoney/" + ammount, {}, headers);
        },
        getUsers: function () {
            var headers = {
                "X-sessionKey": getSessionKey()
            }

            return betMania.requester.getJSON(this.baseUrl + "getusers/", headers)

        },
        deleteUser: function (userId) {
            var headers = {
                "X-sessionKey": getSessionKey()
            }

            return betMania.requester.deleteJSON(this.baseUrl + "delete/" + userId, headers);
        },
        modify: function (user) {
            var headers = {
                "X-sessionKey": getSessionKey()
            }

            return betMania.requester.putJSON(this.baseUrl + "modify", user, headers);
        }

    });

    var MatchesPersister = Class.create({
        init: function (baseUrl) {
            this.baseUrl = baseUrl;
        },
        /* takes options {} with properties category, status, my, page, take
        * {category:"football",my:true}
        */
        getMatches: function (options) {
            var headers = {
                "X-sessionKey":""
            };
            var queryStartAdded = false;

            var url = this.baseUrl;
            var checkForQuery = function () {
                if (!queryStartAdded) {
                    url += "?"
                    queryStartAdded = true;
                }
            }

            if (options.category) {
                url += "?category=" + options.category + "&";
                queryStartAdded = true;
            }

            if (options.status) {
                checkForQuery();
                url += "status=" + options.status + "&";
            }
            else {
                checkForQuery();
                url += "status=all&";
            }

            if (options.my) {
                checkForQuery();
                url += "my=" + true + "&";
                headers["X-sessionKey"] = getSessionKey();
            }

            if (options.page) {
                checkForQuery();
                url += "page=" + options.page + "&";
            }

            if (options.take) {
                checkForQuery();
                url += "take=" + options.take;
            }

            return betMania.requester.getJSON(url, headers)
            .then(function (response, status, my) {
                debugger;
            }, function (err) {
                debugger;
            });
        }
    });

    return new DataPersister("/api");
}());<|endoftext|>


<commit_before>/*!
 * jQuery TimeDurationPicker Plugin v1.0.2
 *
 * https://github.com/digaev/jQuery-timeDurationPicker
 *
 * Copyright (c) 2015 Nikolay Digaev
 * Released under the MIT license
 */

(function($) {
  $.timeDurationPicker = function(options) {
    $.timeDurationPicker.defaults = $.extend({}, $.timeDurationPicker.defaults, options);
  }

  $.timeDurationPicker.defaults = {
    lang: 'en',
    seconds: false,
    minutes: true,
    hours: true,
    days: true,
    months: true,
    years: true
  }
})(jQuery);

(function($) {
  var instances = [];

  $(document).focusin(function(e) {
    for (var i = 0, c = instances.length; i < c; ++i) {
      var inst = instances[i];
      for (var j = 0, l = inst.element.length; j < l; ++j) {
        if (inst.element[j] == e.target) {
          var offset = $(e.target).offset();
          offset.top += $(e.target).outerHeight();
          inst._content.div.css(offset).fadeIn();
        }
      }
    }
  }).focusout(function(e) {
    // FIXME
    setTimeout(function() {
      var el = document.activeElement;
      if ($(el).parents('.time-duration-picker-content').length == 0) {
        for (var i = 0, c = instances.length; i < c; ++i) {
          var hide = true;
          var inst = instances[i];
          for (var j = 0, l = inst.element.length; j < l; ++j) {
            if (inst.element[j] == el) {
              hide = false;
              break;
            }
          }
          if (hide) {
            inst._content.div.fadeOut();
          }
        }
      }
    }, 10);
  });

  var YEAR = 12 * 30 * 24 * 60 * 60;
  var MONTH = 30 * 24 * 60 * 60;
  var DAY = 24 * 60 * 60;
  var HOUR = 60 * 60;
  var MINUTE = 60;

  $.widget('custom.timeDurationPicker', {
    options: {
    },
    _langs: {
      en: {
        seconds: 'Seconds',
        minutes: 'Minutes',
        hours: 'Hours',
        days: 'Days',
        months: 'Months',
        years: 'Years',
        human_years: 'years',
        human_months: 'months',
        human_days: 'days',
        human_hours: 'hours',
        human_minutes: 'minutes',
        human_seconds: 'seconds',
        and: 'and',
        button_ok: 'Done'
      },
      ru: {
        seconds: 'Секунды',
        minutes: 'Минуты',
        hours: 'Часы',
        days: 'Дни',
        months: 'Месяцы',
        years: 'Годы',
        human_years: 'лет',
        human_months: 'месяцев',
        human_days: 'дней',
        human_hours: 'часов',
        human_minutes: 'минут',
        human_seconds: 'секунд',
        and: 'и',
        button_ok: 'Выбрать'
      },
      ru_short: {
        seconds: 'Секунды',
        minutes: 'Минуты',
        hours: 'Часы',
        days: 'Дни',
        months: 'Месяцы',
        years: 'Годы',
        human_years: 'г.',
        human_months: 'мес.',
        human_days: 'д.',
        human_hours: 'час.',
        human_minutes: 'мин.',
        human_seconds: 'сек.',
        and: 'и',
        button_ok: 'Выбрать'
      }
    },
    _create: function() {
        var self = this;

        this.options = $.extend({}, $.timeDurationPicker.defaults, this.options);

        this._content = {};
        this._content.div = $('
');
        this._content.div.addClass('ui-widget ui-widget-content ui-helper-clearfix ui-corner-all');
        this._content.div.addClass('time-duration-picker-content');
        this._content.div.css({
            display: 'none',
            position: 'fixed',
            "z-index": 401
        });
        this._content.div.appendTo(document.body);

        this._content.table = $('

').appendTo(this._content.div);
        this._content.tableBody = $('tbody', this._content.table);

        this._content.button = $('<input type="button" />').val(this._tr('button_ok'));
        this._content.button.addClass('ui-button ui-widget ui-state-default ui-corner-all');
        this._content.button.css({
          display: 'block',
          margin: '0.5em auto',
          padding: '0.5em 1em'
        });
        this._content.button.hover(function() {
          $(this).addClass('ui-state-hover');
        }, function() {
          $(this).removeClass('ui-state-hover');
        });
        this._content.button.on('click', function(e) {
          self._content.div.fadeOut();
          if (self.options.onselect) {
            self.options.onselect(self.element, self.getDuration(), self.getHumanDuration());
          }
        });
        this._content.button.appendTo(this._content.div);

        this._initUnits();

        instances.push(this);
    },
    _initUnits: function() {
        var i;
        if (this.options.seconds) {
          this._content.seconds = this._createSelectWithOptions(0, 59);
          this._appendRow(this._tr('seconds'), this._content.seconds);
        }
        if (this.options.minutes) {
          this._content.minutes = this._createSelectWithOptions(0, 59);
          this._appendRow(this._tr('minutes'), this._content.minutes);
        }
        if (this.options.hours) {
          this._content.hours = this._createSelectWithOptions(0, 23);
          this._appendRow(this._tr('hours'), this._content.hours);
        }
        if (this.options.days) {
          this._content.days = this._createSelectWithOptions(0, 29);
          this._appendRow(this._tr('days'), this._content.days);
        }
        if (this.options.months) {
          this._content.months = this._createSelectWithOptions(0, 11);
          this._appendRow(this._tr('months'), this._content.months);
        }
        if (this.options.years) {
          this._content.years = this._createSelectWithOptions(0, 10);
          this._appendRow(this._tr('years'), this._content.years);
        }
        if (this.options.defaultValue) {
          this.setDuration(this.options.defaultValue);
        }
    },
    _createSelectWithOptions: function(min, max) {
        var select = $('<select />')
          .addClass('ui-widget ui-state-default ui-corner-all')

        select.hover(function() {
          $(this).addClass('ui-state-hover');
        }, function() {
          $(this).removeClass('ui-state-hover');
        });

        this._createOptionsForSelect(select, min, max);
        return select;
    },
    _createOptionsForSelect: function(select, min, max) {
      for (var i = min; i <= max; ++i) {
        select.append($('<option />').val(i).text(i < 10 ? ('0' + i) : i));
      }
    },
    _appendRow: function(text, el) {
      var row = $('
').appendTo(this._content.tableBody);
      $('').css({
        width: '50%',
        padding: '.5em 1em',
        "text-align": 'right',
        "vertical-align": 'middle'
      }).append($('')
        .text(text))
        .appendTo(row);
      $('').css({
        width: '50%',
        padding: '.5em 1em',
        "text-align": 'right',
        "vertical-align": 'middle'
      }).append(el)
        .appendTo(row);
    },
    _tr: function(key) {
      return this._langs[this.options.lang][key];
    },
    getSeconds: function() {
      return parseInt(this._content.seconds.val());
    },
    getMinutes: function() {
      return parseInt(this._content.minutes.val());
    },
    getHours: function() {
      return parseInt(this._content.hours.val());
    },
    getDays: function() {
      return parseInt(this._content.days.val());
    },
    getMonths: function() {
      return parseInt(this._content.months.val());
    },
    getYears: function() {
      return parseInt(this._content.years.val());
    },
    setDuration: function(value) {
      value = parseInt(value);
      if (isNaN(value)) {
        return false;
      }

      var i;
      if (this.options.years) {
        i = Math.floor(value / YEAR);
        value -= i * YEAR;
        this._content.years.val(i);
      }
      if (this.options.months) {
        i = Math.floor(value / MONTH);
        if (i >= 12) {
          i = 0;
        }
        value -= i * MONTH;
        this._content.months.val(i);
      }
      if (this.options.days) {
        i = Math.floor(value / DAY);
        if (i >= 30) {
          i = 0;
        }
        value -= i * DAY;
        this._content.days.val(i);
      }
      if (this.options.hours) {
        i = Math.floor(value / HOUR);
        if (i >= 24) {
          i = 0;
        }
        value -= i * HOUR;
        this._content.hours.val(i);
      }
      if (this.options.minutes) {
        i = Math.floor(value / MINUTE);
        if (i >= 60) {
          i = 0;
        }
        value -= i * MINUTE;
        this._content.minutes.val(i);
      }
      if (this.options.seconds) {
        i = Math.floor(value);
        if (i >= 60) {
          i = 0;
        }
        this._content.seconds.val(i);
      }
      return value;
    },
    getDuration: function() {
      var seconds = 0;
      if (this.options.seconds) {
        seconds += this.getSeconds();
      }
      if (this.options.minutes) {
        seconds += this.getMinutes() * MINUTE;
      }
      if (this.options.hours) {
        seconds += this.getHours() * HOUR;
      }
      if (this.options.days) {
        seconds += this.getDays() * DAY;
      }
      if (this.options.months) {
        seconds += this.getMonths() * MONTH;
      }
      if (this.options.years) {
        seconds += this.getYears() * YEAR;
      }
      return seconds;
    },
    getHumanDuration: function() {
      var units = [];
      var duration = '';

      if (this.options.years && this.getYears() > 0) {
        units.push({value: this.getYears(), name: this._tr('human_years')});
      }
      if (this.options.months && this.getMonths() > 0) {
        units.push({value: this.getMonths(), name: this._tr('human_months')});
      }
      if (this.options.days && this.getDays() > 0) {
        units.push({value: this.getDays(), name: this._tr('human_days')});
      }
      if (this.options.hours && this.getHours() > 0) {
        units.push({value: this.getHours(), name: this._tr('human_hours')});
      }
      if (this.options.minutes && this.getMinutes() > 0) {
        units.push({value: this.getMinutes(), name: this._tr('human_minutes')});
      }
      if (this.options.seconds && this.getSeconds() > 0) {
        units.push({value: this.getSeconds(), name: this._tr('human_seconds')});
      }

      for (var i = 0, l = units.length; i < l; ++i) {
        var unit = units[i];
        var separator = i == l - 1 ? '' : (i == l - 2 ? ' ' + this._tr('and') + ' ' : ', ');

        duration += unit.value + ' ' + unit.name + separator;
      }
      return duration;
    }
  });
})(jQuery);
<commit_msg>Bump version<commit_after>/*!
 * jQuery TimeDurationPicker Plugin v1.0.3
 *
 * https://github.com/digaev/jQuery-timeDurationPicker
 *
 * Copyright (c) 2015 Nikolay Digaev
 * Released under the MIT license
 */

(function($) {
  $.timeDurationPicker = function(options) {
    $.timeDurationPicker.defaults = $.extend({}, $.timeDurationPicker.defaults, options);
  }

  $.timeDurationPicker.defaults = {
    lang: 'en',
    seconds: false,
    minutes: true,
    hours: true,
    days: true,
    months: true,
    years: true
  }
})(jQuery);

(function($) {
  var instances = [];

  $(document).focusin(function(e) {
    for (var i = 0, c = instances.length; i < c; ++i) {
      var inst = instances[i];
      for (var j = 0, l = inst.element.length; j < l; ++j) {
        if (inst.element[j] == e.target) {
          var offset = $(e.target).offset();
          offset.top += $(e.target).outerHeight();
          inst._content.div.css(offset).fadeIn();
        }
      }
    }
  }).focusout(function(e) {
    // FIXME
    setTimeout(function() {
      var el = document.activeElement;
      if ($(el).parents('.time-duration-picker-content').length == 0) {
        for (var i = 0, c = instances.length; i < c; ++i) {
          var hide = true;
          var inst = instances[i];
          for (var j = 0, l = inst.element.length; j < l; ++j) {
            if (inst.element[j] == el) {
              hide = false;
              break;
            }
          }
          if (hide) {
            inst._content.div.fadeOut();
          }
        }
      }
    }, 10);
  });

  var YEAR = 12 * 30 * 24 * 60 * 60;
  var MONTH = 30 * 24 * 60 * 60;
  var DAY = 24 * 60 * 60;
  var HOUR = 60 * 60;
  var MINUTE = 60;

  $.widget('custom.timeDurationPicker', {
    options: {
    },
    _langs: {
      en: {
        seconds: 'Seconds',
        minutes: 'Minutes',
        hours: 'Hours',
        days: 'Days',
        months: 'Months',
        years: 'Years',
        human_years: 'years',
        human_months: 'months',
        human_days: 'days',
        human_hours: 'hours',
        human_minutes: 'minutes',
        human_seconds: 'seconds',
        and: 'and',
        button_ok: 'Done'
      },
      ru: {
        seconds: 'Секунды',
        minutes: 'Минуты',
        hours: 'Часы',
        days: 'Дни',
        months: 'Месяцы',
        years: 'Годы',
        human_years: 'лет',
        human_months: 'месяцев',
        human_days: 'дней',
        human_hours: 'часов',
        human_minutes: 'минут',
        human_seconds: 'секунд',
        and: 'и',
        button_ok: 'Выбрать'
      },
      ru_short: {
        seconds: 'Секунды',
        minutes: 'Минуты',
        hours: 'Часы',
        days: 'Дни',
        months: 'Месяцы',
        years: 'Годы',
        human_years: 'г.',
        human_months: 'мес.',
        human_days: 'д.',
        human_hours: 'час.',
        human_minutes: 'мин.',
        human_seconds: 'сек.',
        and: 'и',
        button_ok: 'Выбрать'
      }
    },
    _create: function() {
        var self = this;

        this.options = $.extend({}, $.timeDurationPicker.defaults, this.options);

        this._content = {};
        this._content.div = $('
');
        this._content.div.addClass('ui-widget ui-widget-content ui-helper-clearfix ui-corner-all');
        this._content.div.addClass('time-duration-picker-content');
        this._content.div.css({
            display: 'none',
            position: 'fixed',
            "z-index": 401
        });
        this._content.div.appendTo(document.body);

        this._content.table = $('

').appendTo(this._content.div);
        this._content.tableBody = $('tbody', this._content.table);

        this._content.button = $('<input type="button" />').val(this._tr('button_ok'));
        this._content.button.addClass('ui-button ui-widget ui-state-default ui-corner-all');
        this._content.button.css({
          display: 'block',
          margin: '0.5em auto',
          padding: '0.5em 1em'
        });
        this._content.button.hover(function() {
          $(this).addClass('ui-state-hover');
        }, function() {
          $(this).removeClass('ui-state-hover');
        });
        this._content.button.on('click', function(e) {
          self._content.div.fadeOut();
          if (self.options.onselect) {
            self.options.onselect(self.element, self.getDuration(), self.getHumanDuration());
          }
        });
        this._content.button.appendTo(this._content.div);

        this._initUnits();

        instances.push(this);
    },
    _initUnits: function() {
        var i;
        if (this.options.seconds) {
          this._content.seconds = this._createSelectWithOptions(0, 59);
          this._appendRow(this._tr('seconds'), this._content.seconds);
        }
        if (this.options.minutes) {
          this._content.minutes = this._createSelectWithOptions(0, 59);
          this._appendRow(this._tr('minutes'), this._content.minutes);
        }
        if (this.options.hours) {
          this._content.hours = this._createSelectWithOptions(0, 23);
          this._appendRow(this._tr('hours'), this._content.hours);
        }
        if (this.options.days) {
          this._content.days = this._createSelectWithOptions(0, 29);
          this._appendRow(this._tr('days'), this._content.days);
        }
        if (this.options.months) {
          this._content.months = this._createSelectWithOptions(0, 11);
          this._appendRow(this._tr('months'), this._content.months);
        }
        if (this.options.years) {
          this._content.years = this._createSelectWithOptions(0, 10);
          this._appendRow(this._tr('years'), this._content.years);
        }
        if (this.options.defaultValue) {
          this.setDuration(this.options.defaultValue);
        }
    },
    _createSelectWithOptions: function(min, max) {
        var select = $('<select />')
          .addClass('ui-widget ui-state-default ui-corner-all')

        select.hover(function() {
          $(this).addClass('ui-state-hover');
        }, function() {
          $(this).removeClass('ui-state-hover');
        });

        this._createOptionsForSelect(select, min, max);
        return select;
    },
    _createOptionsForSelect: function(select, min, max) {
      for (var i = min; i <= max; ++i) {
        select.append($('<option />').val(i).text(i < 10 ? ('0' + i) : i));
      }
    },
    _appendRow: function(text, el) {
      var row = $('
').appendTo(this._content.tableBody);
      $('').css({
        width: '50%',
        padding: '.5em 1em',
        "text-align": 'right',
        "vertical-align": 'middle'
      }).append($('')
        .text(text))
        .appendTo(row);
      $('').css({
        width: '50%',
        padding: '.5em 1em',
        "text-align": 'right',
        "vertical-align": 'middle'
      }).append(el)
        .appendTo(row);
    },
    _tr: function(key) {
      return this._langs[this.options.lang][key];
    },
    getSeconds: function() {
      return parseInt(this._content.seconds.val());
    },
    getMinutes: function() {
      return parseInt(this._content.minutes.val());
    },
    getHours: function() {
      return parseInt(this._content.hours.val());
    },
    getDays: function() {
      return parseInt(this._content.days.val());
    },
    getMonths: function() {
      return parseInt(this._content.months.val());
    },
    getYears: function() {
      return parseInt(this._content.years.val());
    },
    setDuration: function(value) {
      value = parseInt(value);
      if (isNaN(value)) {
        return false;
      }

      var i;
      if (this.options.years) {
        i = Math.floor(value / YEAR);
        value -= i * YEAR;
        this._content.years.val(i);
      }
      if (this.options.months) {
        i = Math.floor(value / MONTH);
        if (i >= 12) {
          i = 0;
        }
        value -= i * MONTH;
        this._content.months.val(i);
      }
      if (this.options.days) {
        i = Math.floor(value / DAY);
        if (i >= 30) {
          i = 0;
        }
        value -= i * DAY;
        this._content.days.val(i);
      }
      if (this.options.hours) {
        i = Math.floor(value / HOUR);
        if (i >= 24) {
          i = 0;
        }
        value -= i * HOUR;
        this._content.hours.val(i);
      }
      if (this.options.minutes) {
        i = Math.floor(value / MINUTE);
        if (i >= 60) {
          i = 0;
        }
        value -= i * MINUTE;
        this._content.minutes.val(i);
      }
      if (this.options.seconds) {
        i = Math.floor(value);
        if (i >= 60) {
          i = 0;
        }
        this._content.seconds.val(i);
      }
      return value;
    },
    getDuration: function() {
      var seconds = 0;
      if (this.options.seconds) {
        seconds += this.getSeconds();
      }
      if (this.options.minutes) {
        seconds += this.getMinutes() * MINUTE;
      }
      if (this.options.hours) {
        seconds += this.getHours() * HOUR;
      }
      if (this.options.days) {
        seconds += this.getDays() * DAY;
      }
      if (this.options.months) {
        seconds += this.getMonths() * MONTH;
      }
      if (this.options.years) {
        seconds += this.getYears() * YEAR;
      }
      return seconds;
    },
    getHumanDuration: function() {
      var units = [];
      var duration = '';

      if (this.options.years && this.getYears() > 0) {
        units.push({value: this.getYears(), name: this._tr('human_years')});
      }
      if (this.options.months && this.getMonths() > 0) {
        units.push({value: this.getMonths(), name: this._tr('human_months')});
      }
      if (this.options.days && this.getDays() > 0) {
        units.push({value: this.getDays(), name: this._tr('human_days')});
      }
      if (this.options.hours && this.getHours() > 0) {
        units.push({value: this.getHours(), name: this._tr('human_hours')});
      }
      if (this.options.minutes && this.getMinutes() > 0) {
        units.push({value: this.getMinutes(), name: this._tr('human_minutes')});
      }
      if (this.options.seconds && this.getSeconds() > 0) {
        units.push({value: this.getSeconds(), name: this._tr('human_seconds')});
      }

      for (var i = 0, l = units.length; i < l; ++i) {
        var unit = units[i];
        var separator = i == l - 1 ? '' : (i == l - 2 ? ' ' + this._tr('and') + ' ' : ', ');

        duration += unit.value + ' ' + unit.name + separator;
      }
      return duration;
    }
  });
})(jQuery);
<|endoftext|>


<commit_before>// The football.csv file contains the results from the English Premier League.

// The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of goals scored
// for and against each team in that season (so Arsenal scored 79 goals against opponents, and
// had 36 goals scored against them).

// Write a program to read the file, then print the name of the team with the smallest difference
// in ‘for’ and ‘against’ goals.
// Arsenal,38,26,9,3,79,36,87
var fs = require('fs');

var smallDiff = function(){
	file = "football.csv";
	var smallestDifference = 0;
	var team = "";

	fs.readFile(file, "utf-8", function(err, data){
		if (err) {
			console.log(err);
			return;
		}

		var temp = data.toString();
		var line = temp.split('\n');

		for (var i = 1; i < line.length; i++){
			var value = line[i].split(',');
			var diff = value[5] - value[6];

			if ( i === 1) smallestDifference = diff;

			if (diff < smallestDifference) {
				smallestDifference = diff;
				team = value[0];
			}
		}
		console.log(team);
	});
	//return team;
	return;
}

//console.log(smallDiff());
smallDiff();<commit_msg>footbal done<commit_after>// The football.csv file contains the results from the English Premier League.

// The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of goals scored
// for and against each team in that season (so Arsenal scored 79 goals against opponents, and
// had 36 goals scored against them).

// Write a program to read the file, then print the name of the team with the smallest difference
// in ‘for’ and ‘against’ goals.

var fs = require('fs');

var smallDiff = function(){
	file = "football.csv";
	var smallestDifference = 0;
	var team = "";

	fs.readFile(file, "utf-8", function(err, data){
		if (err) {
			console.log(err);
			return;
		}

		var temp = data.toString();
		var line = temp.split('\n');

		for (var i = 1; i < line.length; i++){
			var value = line[i].split(',');
			var diff = value[5] - value[6];

			if ( i === 1) smallestDifference = diff;

			if (diff < smallestDifference) {
				smallestDifference = diff;
				team = value[0];
			}
		}
		console.log(team);
	});
	//return team;
	return;
}

//console.log(smallDiff());
smallDiff();<|endoftext|>


<commit_before>function ScatterChartController(data) {

	this.chart = null;
	this.context = null;

	this.topicID = data.topicID;

	this.latestPointTime = 0;

}

ScatterChartController.prototype = {

	draw: function() {

		var topic = topics[this.topicID];

		var $canvas = $('<canvas>').addClass('').attr('id', 'canvas_' + topic.id);

		$('#placeForCharts').append(
			$('<li>').append(
				$('<fieldset>').addClass('chartContainer').append(
					$('<legend>').css('text-align', 'center').text(topic.description),
					$('<table>').addClass('summary').append(
						$('<tr>').append(
							$('<td>').addClass('firstColumn'),
							$('<td>').addClass('secondColumn').attr('colspan', '2'), //.addClass('valueCell valueTitle').attr('id', 'minmax_'+t).text('Past '+topics[t].periodName()),
							$('<td>')
						),
						$('<tr>').append(
							$('<td>').addClass('valueCell').append(
								$('<div>').addClass('valueTitle').text('Current'),
								$('<div>').css('font-size', '150%').attr('id', 'current_' + topic.id)
							),
							$('<td>').addClass('valueCell').append(
								$('<div>').addClass('valueTitle').text('Min'),
								$('<div>').css('font-size', '100%').css('padding-top', '5px').attr('id', 'min24_' + topic.id)
							),
							$('<td>').addClass('valueCell').append(
								$('<div>').addClass('valueTitle').text('Max'),
								$('<div>').css('font-size', '100%').css('padding-top', '5px').attr('id', 'max24_' + topic.id)
							),
							$('<td>')
						)
					),
					$('<div>').addClass('chart').append($canvas),
					$('<div>').addClass('lastUpdated').attr('id', 'lastUpdated_' + topic.id)
				)
			)
		);

		this.context = document.getElementById("canvas_" + topic.id).getContext("2d");

		this.chart = new Chart(this.context).Scatter([
			{
				label: topic.description,
				strokeColor: topic.colour,
				pointColor: topic.colour,
				pointStrokeColor: '#fff',
				data: [{x: 0, y: 0}]
			}
		], {
			bezierCurve: false,
			datasetStroke: true,
			pointDot: false,
			showTooltips: true,
			scaleShowHorizontalLines: true,
			scaleShowLabels: true,
			scaleType: "date",
			scaleLabel: "<%=Math.round(value, " + topic.decimalPoints + "%>" + topic.units,
			//scaleLabel: "<%=value%>" + topic.units,
			useUtc: false,
			scaleDateFormat: "mmm d",
			scaleTimeFormat: "HH:MM",
			scaleDateTimeFormat: "mmm d, yyyy, HH:MM",
			animation: false,
			responsive: true,
			maintainAspectRatio: false,
			pointHitDetectionRadius: 1
		});
	},

	update: function() {
		//add more data from the topic

		var newTemps = topics[this.topicID].dataForScatterChart(this.latestPointTime);
		for (var n in newTemps) {
			this.chart.datasets[0].addPoint(newTemps[n].x, newTemps[n].y);
			this.latestPointTime = Math.max(this.latestPointTime, moment(newTemps[n][0]).unix())
		}

		if (this.chart.datasets[0].points.length > 1 && this.chart.datasets[0].points[0].arg == 0) {
			this.chart.datasets[0].removePoint(0);
		}

		this.chart.update();

		$('#current_' + this.topicID).empty().text(topics[this.topicID].latestPoint.value + topics[this.topicID].units);
		$('#lastUpdated_' + this.topicID).empty().text('Updated ' + topics[this.topicID].latestPoint.time.fromNow());

		var minMax = topics[this.topicID].minMax();
		$('#min24_' + this.topicID).empty().append(
			minMax.minValue + topics[this.topicID].units
		);
		$('#max24_' + this.topicID).empty().append(
			minMax.maxValue + topics[this.topicID].units
		);

	},

	redrawChart: function() {

		this.chart.datasets[0].points = [];

		var u = moment().unix() - period;

		for (var p in topics[this.topicID].points) {
			if (p < u) {
				continue;
			}

			this.chart.datasets[0].addPoint(topics[this.topicID].points[p].time.toDate(), topics[this.topicID].points[p].value)
		}

		this.chart.update();
	}

};<commit_msg>Make rounding work!<commit_after>function ScatterChartController(data) {

	this.chart = null;
	this.context = null;

	this.topicID = data.topicID;

	this.latestPointTime = 0;

}

ScatterChartController.prototype = {

	draw: function() {

		var topic = topics[this.topicID];

		var $canvas = $('<canvas>').addClass('').attr('id', 'canvas_' + topic.id);

		$('#placeForCharts').append(
			$('<li>').append(
				$('<fieldset>').addClass('chartContainer').append(
					$('<legend>').css('text-align', 'center').text(topic.description),
					$('<table>').addClass('summary').append(
						$('<tr>').append(
							$('<td>').addClass('firstColumn'),
							$('<td>').addClass('secondColumn').attr('colspan', '2'), //.addClass('valueCell valueTitle').attr('id', 'minmax_'+t).text('Past '+topics[t].periodName()),
							$('<td>')
						),
						$('<tr>').append(
							$('<td>').addClass('valueCell').append(
								$('<div>').addClass('valueTitle').text('Current'),
								$('<div>').css('font-size', '150%').attr('id', 'current_' + topic.id)
							),
							$('<td>').addClass('valueCell').append(
								$('<div>').addClass('valueTitle').text('Min'),
								$('<div>').css('font-size', '100%').css('padding-top', '5px').attr('id', 'min24_' + topic.id)
							),
							$('<td>').addClass('valueCell').append(
								$('<div>').addClass('valueTitle').text('Max'),
								$('<div>').css('font-size', '100%').css('padding-top', '5px').attr('id', 'max24_' + topic.id)
							),
							$('<td>')
						)
					),
					$('<div>').addClass('chart').append($canvas),
					$('<div>').addClass('lastUpdated').attr('id', 'lastUpdated_' + topic.id)
				)
			)
		);

		this.context = document.getElementById("canvas_" + topic.id).getContext("2d");

		this.chart = new Chart(this.context).Scatter([
			{
				label: topic.description,
				strokeColor: topic.colour,
				pointColor: topic.colour,
				pointStrokeColor: '#fff',
				data: [{x: 0, y: 0}]
			}
		], {
			bezierCurve: false,
			datasetStroke: true,
			pointDot: false,
			showTooltips: true,
			scaleShowHorizontalLines: true,
			scaleShowLabels: true,
			scaleType: "date",
			scaleLabel: "<%=Math.round(value, " + topic.decimalPoints + ")%>" + topic.units,
			//scaleLabel: "<%=value%>" + topic.units,
			useUtc: false,
			scaleDateFormat: "mmm d",
			scaleTimeFormat: "HH:MM",
			scaleDateTimeFormat: "mmm d, yyyy, HH:MM",
			animation: false,
			responsive: true,
			maintainAspectRatio: false,
			pointHitDetectionRadius: 1
		});
	},

	update: function() {
		//add more data from the topic

		var newTemps = topics[this.topicID].dataForScatterChart(this.latestPointTime);
		for (var n in newTemps) {
			this.chart.datasets[0].addPoint(newTemps[n].x, newTemps[n].y);
			this.latestPointTime = Math.max(this.latestPointTime, moment(newTemps[n][0]).unix())
		}

		if (this.chart.datasets[0].points.length > 1 && this.chart.datasets[0].points[0].arg == 0) {
			this.chart.datasets[0].removePoint(0);
		}

		this.chart.update();

		$('#current_' + this.topicID).empty().text(topics[this.topicID].latestPoint.value + topics[this.topicID].units);
		$('#lastUpdated_' + this.topicID).empty().text('Updated ' + topics[this.topicID].latestPoint.time.fromNow());

		var minMax = topics[this.topicID].minMax();
		$('#min24_' + this.topicID).empty().append(
			minMax.minValue + topics[this.topicID].units
		);
		$('#max24_' + this.topicID).empty().append(
			minMax.maxValue + topics[this.topicID].units
		);

	},

	redrawChart: function() {

		this.chart.datasets[0].points = [];

		var u = moment().unix() - period;

		for (var p in topics[this.topicID].points) {
			if (p < u) {
				continue;
			}

			this.chart.datasets[0].addPoint(topics[this.topicID].points[p].time.toDate(), topics[this.topicID].points[p].value)
		}

		this.chart.update();
	}

};<|endoftext|>


<commit_before>// Copyright 2020, University of Colorado Boulder

/**
 * A lightweight version of Property (that satisfies some of the interface), meant for high-performance applications
 * where validation, phet-io support and other things are not needed. This includes additional logic for conditionally
 * forwarding to/from another Property.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

import axon from './axon.js';
import Property from './Property.js';
import TinyProperty from './TinyProperty.js';

class TinyForwardingProperty extends TinyProperty {

  /**
   * @param {*} value - The initial value of the property
   * @param {boolean} [targetPropertyInstrumented=false]
   */
  constructor( value, targetPropertyInstrumented = false ) {
    super( value );

    /*******************************************************************************************/
    // @public (read-only NodeTests) {Property.<*>|null|undefined} targetProperty - Set in setTargetProperty()
    /*******************************************************************************************/

    /*******************************************************************************************/
    // @protected {function|undefined} forwardingListener - Set lazily in setTargetProperty
    /*******************************************************************************************/

    /*******************************************************************************************/
    // @public (NodeTests) {Property|undefined} ownedPhetioProperty - TinyProperty is not instrumented for PhET-iO, so when a Node is
    // instrumented, by default, an instrumented `Property` can be forwarded to. This field stores the default
    // instrumented Property when targetPropertyInstrumented is true.
    /*******************************************************************************************/

    /*******************************************************************************************/
    // @private {boolean|undefined} targetPropertyInstrumented -  when true, automatically set up a PhET-iO instrumented
    // forwarded Property for this TinyProperty, see this.initializePhetioObject() for usage.
    /*******************************************************************************************/
    if ( targetPropertyInstrumented ) {
      this.targetPropertyInstrumented = targetPropertyInstrumented;
    }

    if ( assert ) {

      // @private - guard against double initialization
      this.phetioInitialized = false;
    }
  }

  /**
   * Sets (or unsets if `null` is provided) the Property that we use for forwarding changes.
   * @public
   *
   * @param {Node} node - The container of TinyForwardingProperty which supports updateLinkedElementForProperty()
   * @param {string} tandemName
   * @param {TinyProperty.<*>|Property.<*>|null} newTarget - null to "unset" forwarding.
   * @returns {Node} - the passed in Node, for chaining.
   */
  setTargetProperty( node, tandemName, newTarget ) {

    // no-op if we are already forwarding to that property OR if we still aren't forwarding
    if ( this.targetProperty === newTarget ) {
      return node; // for chaining
    }

    const currentForwardingPropertyInstrumented = this.targetProperty &&
                                                  this.targetProperty.isPhetioInstrumented();
    assert && currentForwardingPropertyInstrumented && assert( newTarget && newTarget.isPhetioInstrumented(),
      'Cannot set swap out a PhET-iO instrumented targetProperty for an uninstrumented one' );

    // We need this information eagerly for later on in the function
    const previousTarget = this.targetProperty;

    // If we had the "default instrumented" Property, we'll remove that and then link our new Property. Guard on the fact
    // that ownedPhetioProperty is added via this exact method, see this.initializePhetio() for details
    // Do this before adding a PhET-iO LinkedElement because ownedPhetioProperty has the same phetioID as the LinkedElement
    if ( this.ownedPhetioProperty && newTarget !== this.ownedPhetioProperty ) {
      this.disposeOwnedPhetioProperty();
    }

    node.updateLinkedElementForProperty( tandemName, previousTarget, newTarget );

    // Lazily set this value, it will be added as a listener to any targetProperty we have.
    this.forwardingListener = this.forwardingListener || ( ( value, oldValue ) => {
      this.notifyListeners( oldValue );
    } );

    const oldValue = this.get();

    if ( this.targetProperty ) {
      this.targetProperty.unlink( this.forwardingListener );
    }

    this.targetProperty = newTarget;

    if ( this.targetProperty ) {
      this.targetProperty.lazyLink( this.forwardingListener );
    }
    else {
      // If we're switching away from a targetProperty, prefer no notification (so set our value to the last value)
      this._value = oldValue;
    }

    const newValue = this.get();

    // Changing forwarding target COULD change the value, so send notifications if this is the case.
    if ( !this.areValuesEqual( oldValue, newValue ) ) {
      this.notifyListeners( oldValue );
    }

    return node; // for chaining
  }

  /**
   * Gets the value.
   * @public
   * @override
   *
   * You can also use the es5 getter (property.value) but this means is provided for inner loops
   * or internal code that must be fast.
   * @returns {*}
   */
  get() {
    if ( this.targetProperty ) {
      return this.targetProperty.value;
    }
    else {
      return super.get();
    }
  }

  /**
   * Sets the value and notifies listeners, unless deferred or disposed. You can also use the es5 getter
   * (property.value) but this means is provided for inner loops or internal code that must be fast. If the value
   * hasn't changed, this is a no-op.
   * @public
   * @override
   *
   * @param {*} value
   * @returns {TinyForwardingProperty} this instance, for chaining.
   */
  set( value ) {
    if ( this.targetProperty ) {
      this.targetProperty.set( value );
    }
    else {
      super.set( value );
    }
    return this;
  }

  /**
   * Directly notifies listeners of changes. This needs to be an override to make sure that the value of the targetProperty
   * is used if it exists.
   * @public
   * @override
   *
   * @param {*} oldValue
   */
  notifyListeners( oldValue ) {

    // NOTE: This is overridden to use this.get(), since we need to hook up forwarding.
    this.emit( this.get(), oldValue, this );
  }

  /**
   * Adds listener and calls it immediately. If listener is already registered, this is a no-op. The initial
   * notification provides the current value for newValue and null for oldValue.
   * @public
   * @override - So we can call the slightly more expensive getter, instead of the direct access
   *
   * @param {function} listener a function of the form listener(newValue,oldValue)
   */
  link( listener ) {
    this.addListener( listener );

    listener( this.get(), null, this ); // null should be used when an object is expected but unavailable
  }

  /**
   * Use this to automatically create a forwarded, PhET-iO instrumented Property owned by this TinyForwardingProperty.
   *
   * @public
   * @param {boolean} targetPropertyInstrumented
   * @param {Node} node
   * @returns {Node} - for chaining
   */
  setTargetPropertyInstrumented( targetPropertyInstrumented, node ) {
    assert && assert( typeof targetPropertyInstrumented === 'boolean' );

    // See Node.initializePhetioObject for more details on this assertion
    assert && assert( !node.isPhetioInstrumented(), 'this option only works if it is passed in before this Node is instrumented' );

    this.targetPropertyInstrumented = targetPropertyInstrumented;

    return node;
  }

  /**
   * @param {Node} node - the parent container that supports updateLinkedElementForProperty()
   * @param {string} tandemName
   * @param {function():Property} createProperty - creates an "owned" Property
   * @public
   */
  initializePhetio( node, tandemName, createProperty ) {
    assert && assert( typeof tandemName === 'string' );
    assert && assert( typeof createProperty === 'function' );
    assert && assert( !this.phetioInitialized, 'already initialized' );
    assert && assert( !this.ownedPhetioProperty, 'Already created the ownedPhetioProperty' );

    if ( !this.targetProperty && this.targetPropertyInstrumented ) {

      this.ownedPhetioProperty = createProperty();
      assert && assert( this.ownedPhetioProperty instanceof Property, 'The owned property should be an AXON/Property' );
      assert && assert( this.ownedPhetioProperty.isPhetioInstrumented(), 'The owned property should be PhET-iO instrumented' );

      this.setTargetProperty( node, tandemName, this.ownedPhetioProperty );
    }
    else if ( this.targetProperty && this.targetProperty.isPhetioInstrumented() ) {

      // If the Property was already set, now that it is instrumented, add a LinkedElement for it.
      node.updateLinkedElementForProperty( tandemName, null, this.targetProperty );
    }

    if ( assert ) {
      this.phetioInitialized = true;
    }
  }

  /**
   * This currently also involves deleting the field.
   * @private
   */
  disposeOwnedPhetioProperty() {
    if ( this.ownedPhetioProperty ) {
      this.ownedPhetioProperty.dispose();
      delete this.ownedPhetioProperty; // back to original value
    }
  }

  /**
   * @public
   * @override
   */
  dispose() {
    this.targetProperty && this.targetProperty.unlink( this.forwardingListener );
    this.targetProperty = null;
    this.disposeOwnedPhetioProperty();
    super.dispose();
  }
}

axon.register( 'TinyForwardingProperty', TinyForwardingProperty );
export default TinyForwardingProperty;<commit_msg>don't null out targetProperty on disposal, https://github.com/phetsims/scenery/issues/1097<commit_after>// Copyright 2020, University of Colorado Boulder

/**
 * A lightweight version of Property (that satisfies some of the interface), meant for high-performance applications
 * where validation, phet-io support and other things are not needed. This includes additional logic for conditionally
 * forwarding to/from another Property.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

import axon from './axon.js';
import Property from './Property.js';
import TinyProperty from './TinyProperty.js';

class TinyForwardingProperty extends TinyProperty {

  /**
   * @param {*} value - The initial value of the property
   * @param {boolean} [targetPropertyInstrumented=false]
   */
  constructor( value, targetPropertyInstrumented = false ) {
    super( value );

    /*******************************************************************************************/
    // @public (read-only NodeTests) {Property.<*>|null|undefined} targetProperty - Set in setTargetProperty()
    /*******************************************************************************************/

    /*******************************************************************************************/
    // @protected {function|undefined} forwardingListener - Set lazily in setTargetProperty
    /*******************************************************************************************/

    /*******************************************************************************************/
    // @public (NodeTests) {Property|undefined} ownedPhetioProperty - TinyProperty is not instrumented for PhET-iO, so when a Node is
    // instrumented, by default, an instrumented `Property` can be forwarded to. This field stores the default
    // instrumented Property when targetPropertyInstrumented is true.
    /*******************************************************************************************/

    /*******************************************************************************************/
    // @private {boolean|undefined} targetPropertyInstrumented -  when true, automatically set up a PhET-iO instrumented
    // forwarded Property for this TinyProperty, see this.initializePhetioObject() for usage.
    /*******************************************************************************************/
    if ( targetPropertyInstrumented ) {
      this.targetPropertyInstrumented = targetPropertyInstrumented;
    }

    if ( assert ) {

      // @private - guard against double initialization
      this.phetioInitialized = false;
    }
  }

  /**
   * Sets (or unsets if `null` is provided) the Property that we use for forwarding changes.
   * @public
   *
   * @param {Node} node - The container of TinyForwardingProperty which supports updateLinkedElementForProperty()
   * @param {string} tandemName
   * @param {TinyProperty.<*>|Property.<*>|null} newTarget - null to "unset" forwarding.
   * @returns {Node} - the passed in Node, for chaining.
   */
  setTargetProperty( node, tandemName, newTarget ) {

    // no-op if we are already forwarding to that property OR if we still aren't forwarding
    if ( this.targetProperty === newTarget ) {
      return node; // for chaining
    }

    const currentForwardingPropertyInstrumented = this.targetProperty &&
                                                  this.targetProperty.isPhetioInstrumented();
    assert && currentForwardingPropertyInstrumented && assert( newTarget && newTarget.isPhetioInstrumented(),
      'Cannot set swap out a PhET-iO instrumented targetProperty for an uninstrumented one' );

    // We need this information eagerly for later on in the function
    const previousTarget = this.targetProperty;

    // If we had the "default instrumented" Property, we'll remove that and then link our new Property. Guard on the fact
    // that ownedPhetioProperty is added via this exact method, see this.initializePhetio() for details
    // Do this before adding a PhET-iO LinkedElement because ownedPhetioProperty has the same phetioID as the LinkedElement
    if ( this.ownedPhetioProperty && newTarget !== this.ownedPhetioProperty ) {
      this.disposeOwnedPhetioProperty();
    }

    node.updateLinkedElementForProperty( tandemName, previousTarget, newTarget );

    // Lazily set this value, it will be added as a listener to any targetProperty we have.
    this.forwardingListener = this.forwardingListener || ( ( value, oldValue ) => {
      this.notifyListeners( oldValue );
    } );

    const oldValue = this.get();

    if ( this.targetProperty ) {
      this.targetProperty.unlink( this.forwardingListener );
    }

    this.targetProperty = newTarget;

    if ( this.targetProperty ) {
      this.targetProperty.lazyLink( this.forwardingListener );
    }
    else {
      // If we're switching away from a targetProperty, prefer no notification (so set our value to the last value)
      this._value = oldValue;
    }

    const newValue = this.get();

    // Changing forwarding target COULD change the value, so send notifications if this is the case.
    if ( !this.areValuesEqual( oldValue, newValue ) ) {
      this.notifyListeners( oldValue );
    }

    return node; // for chaining
  }

  /**
   * Gets the value.
   * @public
   * @override
   *
   * You can also use the es5 getter (property.value) but this means is provided for inner loops
   * or internal code that must be fast.
   * @returns {*}
   */
  get() {
    if ( this.targetProperty ) {
      return this.targetProperty.value;
    }
    else {
      return super.get();
    }
  }

  /**
   * Sets the value and notifies listeners, unless deferred or disposed. You can also use the es5 getter
   * (property.value) but this means is provided for inner loops or internal code that must be fast. If the value
   * hasn't changed, this is a no-op.
   * @public
   * @override
   *
   * @param {*} value
   * @returns {TinyForwardingProperty} this instance, for chaining.
   */
  set( value ) {
    if ( this.targetProperty ) {
      this.targetProperty.set( value );
    }
    else {
      super.set( value );
    }
    return this;
  }

  /**
   * Directly notifies listeners of changes. This needs to be an override to make sure that the value of the targetProperty
   * is used if it exists.
   * @public
   * @override
   *
   * @param {*} oldValue
   */
  notifyListeners( oldValue ) {

    // NOTE: This is overridden to use this.get(), since we need to hook up forwarding.
    this.emit( this.get(), oldValue, this );
  }

  /**
   * Adds listener and calls it immediately. If listener is already registered, this is a no-op. The initial
   * notification provides the current value for newValue and null for oldValue.
   * @public
   * @override - So we can call the slightly more expensive getter, instead of the direct access
   *
   * @param {function} listener a function of the form listener(newValue,oldValue)
   */
  link( listener ) {
    this.addListener( listener );

    listener( this.get(), null, this ); // null should be used when an object is expected but unavailable
  }

  /**
   * Use this to automatically create a forwarded, PhET-iO instrumented Property owned by this TinyForwardingProperty.
   *
   * @public
   * @param {boolean} targetPropertyInstrumented
   * @param {Node} node
   * @returns {Node} - for chaining
   */
  setTargetPropertyInstrumented( targetPropertyInstrumented, node ) {
    assert && assert( typeof targetPropertyInstrumented === 'boolean' );

    // See Node.initializePhetioObject for more details on this assertion
    assert && assert( !node.isPhetioInstrumented(), 'this option only works if it is passed in before this Node is instrumented' );

    this.targetPropertyInstrumented = targetPropertyInstrumented;

    return node;
  }

  /**
   * @param {Node} node - the parent container that supports updateLinkedElementForProperty()
   * @param {string} tandemName
   * @param {function():Property} createProperty - creates an "owned" Property
   * @public
   */
  initializePhetio( node, tandemName, createProperty ) {
    assert && assert( typeof tandemName === 'string' );
    assert && assert( typeof createProperty === 'function' );
    assert && assert( !this.phetioInitialized, 'already initialized' );
    assert && assert( !this.ownedPhetioProperty, 'Already created the ownedPhetioProperty' );

    if ( !this.targetProperty && this.targetPropertyInstrumented ) {

      this.ownedPhetioProperty = createProperty();
      assert && assert( this.ownedPhetioProperty instanceof Property, 'The owned property should be an AXON/Property' );
      assert && assert( this.ownedPhetioProperty.isPhetioInstrumented(), 'The owned property should be PhET-iO instrumented' );

      this.setTargetProperty( node, tandemName, this.ownedPhetioProperty );
    }
    else if ( this.targetProperty && this.targetProperty.isPhetioInstrumented() ) {

      // If the Property was already set, now that it is instrumented, add a LinkedElement for it.
      node.updateLinkedElementForProperty( tandemName, null, this.targetProperty );
    }

    if ( assert ) {
      this.phetioInitialized = true;
    }
  }

  /**
   * This currently also involves deleting the field.
   * @private
   */
  disposeOwnedPhetioProperty() {
    if ( this.ownedPhetioProperty ) {
      this.ownedPhetioProperty.dispose();
      delete this.ownedPhetioProperty; // back to original value
    }
  }

  /**
   * @public
   * @override
   */
  dispose() {
    this.targetProperty && this.targetProperty.unlink( this.forwardingListener );
    this.disposeOwnedPhetioProperty();
    super.dispose();
  }
}

axon.register( 'TinyForwardingProperty', TinyForwardingProperty );
export default TinyForwardingProperty;<|endoftext|>


<commit_before>import {element} from 'deku';

const _getMsg = chrome.i18n.getMessage;

function afterRender({props}, el) {
  const itemInfo = props.menuTarget;

  const isHidden = !itemInfo;

  if (!isHidden) {
    setMenuPos(el, props.mousePos);
  }
}

function closeMenu() {
  globals.setRootState({
    menuTarget: null
  });
}

function getChildrenHiddenStatus(itemInfo) {
  let childrenHiddenStatus = [];

  switch (globals.getBookmarkType(itemInfo)) {
    case 'folder':
    case 'bookmark':
      if (globals.isRootFolder(itemInfo)) {
        childrenHiddenStatus = [false, true, true, true, true];
      // } else if (!IS_SEARCHING) {
      //   childrenHiddenStatus = [false, false, false, false, false];
      } else {
        childrenHiddenStatus = [false, false, false, true, true];
      }
      break;

    case 'no-bookmark':
      childrenHiddenStatus = [true, true, false, false, true];
  }

  return childrenHiddenStatus;
}

function getMenuItemNum(menuItem) {
  const menuItemList = document.getElementsByClassName('menu-item');

  return Array.prototype.indexOf.call(menuItemList, menuItem);
}

function menuClickEvent(event, {props}) {
  const target = event.target;

  const menuItemNum = getMenuItemNum(target);

  switch (menuItemNum) {
    case 0: // Open bookmark(s) in background tab or this window
    case 1: // in new window
    case 2: // in incognito window
      break;

    case 3: // Edit... or Rename...
    case 9: // Add folder...
      globals.setRootState({
        editTarget: props.menuTarget,
        menuTarget: null
      });
      return true;

    case 4: // Delete
      break;

    case 5: // Cut
    case 6: // Copy
    case 7: // Paste
      break;

    case 8: // Add current page
      break;

    case 10: // Add separator
      break;

    case 11: // Sort by name
  }

  closeMenu();
}

function render({props, state}) {
  const itemInfo = props.menuTarget;

  const isHidden = !itemInfo;

  let menuItems;

  if (itemInfo) {
    const childrenHiddenStatus = getChildrenHiddenStatus(itemInfo);
    const menuPattern = [
      [],
      [],
      ['cut', 'copy', 'paste'],
      ['addPage', 'addFolder', 'addSeparator'],
      ['sortByName']
    ];

    if (globals.isFolder(itemInfo)) {
      menuPattern[0] = ['openAll', 'openAllInN', 'openAllInI'];
      menuPattern[1] = ['rename', 'del'];
    } else {
      menuPattern[0] = ['openInB', 'openInN', 'openInI'];
      menuPattern[1] = ['edit', 'del'];
    }

    menuItems = menuPattern.map((menuAreaKeys, menuAreaIndex) => {
      const isMenuAreaHidden = childrenHiddenStatus[menuAreaIndex];
      const menuAreaItems = menuAreaKeys.map((menuItemKey) => {
        return (

            {_getMsg(menuItemKey)}

        );
      });

      return
{menuAreaItems}
;
    });
  }

  return
{menuItems}
;
}

function setMenuPos(el, mousePos) {
  const body = document.body;
  const menuHeight = el.offsetHeight;
  const menuWidth = el.offsetWidth;

  const bodyHeight = body.scrollHeight;
  const bodyWidth = body.offsetWidth;

  if (menuHeight > bodyHeight) {
    body.style.height = menuHeight + 'px';
  }

  if (menuWidth > bodyWidth) {
    body.style.width = menuWidth + 'px';
  }

  const bottomPos = bodyHeight - menuHeight - mousePos.y;
  const rightPos = bodyWidth - menuWidth - mousePos.x;

  el.style.bottom = Math.max(bottomPos, 0) + 'px';
  el.style.right = Math.max(rightPos, 0) + 'px';
}

export default {afterRender, render};
<commit_msg>Separate the logic of edit and add folder<commit_after>import {element} from 'deku';

const _getMsg = chrome.i18n.getMessage;

function afterRender({props}, el) {
  const itemInfo = props.menuTarget;

  const isHidden = !itemInfo;

  if (!isHidden) {
    setMenuPos(el, props.mousePos);
  }
}

function closeMenu() {
  globals.setRootState({
    menuTarget: null
  });
}

function getChildrenHiddenStatus(itemInfo) {
  let childrenHiddenStatus = [];

  switch (globals.getBookmarkType(itemInfo)) {
    case 'folder':
    case 'bookmark':
      if (globals.isRootFolder(itemInfo)) {
        childrenHiddenStatus = [false, true, true, true, true];
      // } else if (!IS_SEARCHING) {
      //   childrenHiddenStatus = [false, false, false, false, false];
      } else {
        childrenHiddenStatus = [false, false, false, true, true];
      }
      break;

    case 'no-bookmark':
      childrenHiddenStatus = [true, true, false, false, true];
  }

  return childrenHiddenStatus;
}

function getMenuItemNum(menuItem) {
  const menuItemList = document.getElementsByClassName('menu-item');

  return Array.prototype.indexOf.call(menuItemList, menuItem);
}

function menuClickEvent(event, {props}) {
  const target = event.target;

  const menuItemNum = getMenuItemNum(target);

  switch (menuItemNum) {
    case 0: // Open bookmark(s) in background tab or this window
    case 1: // in new window
    case 2: // in incognito window
      break;

    case 3: // Edit... or Rename...
      globals.setRootState({
        editTarget: props.menuTarget,
        menuTarget: null
      });
      return true;

    case 4: // Delete
      break;

    case 5: // Cut
    case 6: // Copy
    case 7: // Paste
      break;

    case 9: // Add folder...
      return true;

    case 8: // Add current page
      break;

    case 10: // Add separator
      break;

    case 11: // Sort by name
  }

  closeMenu();
}

function render({props, state}) {
  const itemInfo = props.menuTarget;

  const isHidden = !itemInfo;

  let menuItems;

  if (itemInfo) {
    const childrenHiddenStatus = getChildrenHiddenStatus(itemInfo);
    const menuPattern = [
      [],
      [],
      ['cut', 'copy', 'paste'],
      ['addPage', 'addFolder', 'addSeparator'],
      ['sortByName']
    ];

    if (globals.isFolder(itemInfo)) {
      menuPattern[0] = ['openAll', 'openAllInN', 'openAllInI'];
      menuPattern[1] = ['rename', 'del'];
    } else {
      menuPattern[0] = ['openInB', 'openInN', 'openInI'];
      menuPattern[1] = ['edit', 'del'];
    }

    menuItems = menuPattern.map((menuAreaKeys, menuAreaIndex) => {
      const isMenuAreaHidden = childrenHiddenStatus[menuAreaIndex];
      const menuAreaItems = menuAreaKeys.map((menuItemKey) => {
        return (

            {_getMsg(menuItemKey)}

        );
      });

      return
{menuAreaItems}
;
    });
  }

  return
{menuItems}
;
}

function setMenuPos(el, mousePos) {
  const body = document.body;
  const menuHeight = el.offsetHeight;
  const menuWidth = el.offsetWidth;

  const bodyHeight = body.scrollHeight;
  const bodyWidth = body.offsetWidth;

  if (menuHeight > bodyHeight) {
    body.style.height = menuHeight + 'px';
  }

  if (menuWidth > bodyWidth) {
    body.style.width = menuWidth + 'px';
  }

  const bottomPos = bodyHeight - menuHeight - mousePos.y;
  const rightPos = bodyWidth - menuWidth - mousePos.x;

  el.style.bottom = Math.max(bottomPos, 0) + 'px';
  el.style.right = Math.max(rightPos, 0) + 'px';
}

export default {afterRender, render};
<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectDescription = ko.observable("Description");

    gvm.firstNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("firstNameTableTitle");}, gvm);
    gvm.lastNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("lastNameTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.scoreTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("scoreTableTitle")});
    gvm.filesTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("filesTableTitle")});

    gvm.searchStudent = ko.observable("");

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
            gvm.projectDescription(data[0].description);
        });
    };

    gvm.getStudentListBis = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students', function(data) {
            data.forEach(function(element){
                viewModel.addTableData(element.id, element.firstname, element.lastname, element.mail, element.assessCount);
            });
        });
    };

    gvm.getStudentList = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students/', function(data) {
            $.each(data, function(i, item) {

                $.getJSON('/api/project/' + gvm.projectid  + '/student/' + item.id + '/assessed', function(data)
                {
                    viewModel.users.removeAll();
                    data.forEach(function(element)
                    {
                        viewModel.users.push(element.firstname + " " + element.lastname);
                    });

                    viewModel.addTableData(item.id, item.firstname, item.lastname, item.mail, viewModel.users().length);
                });
            });
        });
    };

    gvm.users = ko.observableArray([]);

    gvm.assassedUsers = ko.observableArray([]);

    gvm.tabledata = ko.observableArray([]);

    gvm.tempTableData = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, firstname, lastname, email, countAssessed) {
        // Push data
        var data = countAssessed;
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tScoreTableBtn: gvm.scoreTableTitle, tFilesTableBtn: gvm.filesTableTitle, tpid: gvm.projectId, email: email, tcountAssessed: data};
        gvm.tabledata.push(tblOject);
    };

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    };

    /*gvm.getAllData = function() {
        $.getJSON('/api/project/getAllData/' + $("#projectHeader").data('value'), function(data) {
            console.log(data);
        });
    }*/
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getStudentListBis();
    //viewModel.getStudentList();

    $("#searchField").bind("keypress", {}, keypressInBox);

}

function keypressInBox(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) { //Enter keycode
        $("#searchField").blur();
        getStudentByName();

    }
};

function createPDF(id,name,lastname,email, projectheader, projectdescription)
{
    /*$.getJSON('/api/finalscore/' + viewModel.projectId + '/' + id, function (data) {
        makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        //console.log(data);
    });*/

    $.ajax({
        url: '/api/finalscore/' + viewModel.projectId + '/' + id,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        },
        error: function()
        {
            alert("Please make sure points are given!");
        }
    });
}

function getStudentByName(){

    if(viewModel.tempTableData().length == 0) {
        viewModel.tempTableData(viewModel.tabledata.slice(0));
    }

    viewModel.tabledata([]);

    viewModel.tempTableData().forEach(function(item, element){
        var fullname = item.tfirstname + " " + item.tlastname;
        var fullnameReverse = item.tlastname + " " + item.tfirstname;

        if (item.tfirstname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || item.tlastname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullnameReverse.toLowerCase().contains(viewModel.searchStudent().toLowerCase())){
            viewModel.tabledata.push(item);
        }
    });
}

function showFullList()
{
    viewModel.searchStudent = ko.observable("");
    getStudentByName();
}

function getData(id)
{
    $.getJSON('/api/project/' + viewModel.projectId  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });
    });

    return viewModel.users();
}

function getNrOfAssessing(){
    $.getJSON('/api/project/nrOfAssessing/' + viewModel.projectId , function(data)
    {
        data.forEach(function(item)
        {
            console.log(item.nrOfAssessing);
            if (viewModel.tcountAssessed === item.nrOfAssessing){
                alert("test");
            }

            return item.nrOfAssessing;
        });
    });
}

function getDataCount(projectid, id)
{
    $.getJSON('/api/project/' + projectid  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });

        return viewModel.users().length;
    });
}<commit_msg>nr of assessing color balls<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectDescription = ko.observable("Description");

    gvm.firstNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("firstNameTableTitle");}, gvm);
    gvm.lastNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("lastNameTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.scoreTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("scoreTableTitle")});
    gvm.filesTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("filesTableTitle")});

    gvm.searchStudent = ko.observable("");

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
            gvm.projectDescription(data[0].description);
        });
    };

    gvm.getStudentListBis = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students', function(data) {
            data.forEach(function(element){
                viewModel.addTableData(element.id, element.firstname, element.lastname, element.mail, element.assessCount);
            });
        });
    };

    gvm.getStudentList = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students/', function(data) {
            $.each(data, function(i, item) {

                $.getJSON('/api/project/' + gvm.projectid  + '/student/' + item.id + '/assessed', function(data)
                {
                    viewModel.users.removeAll();
                    data.forEach(function(element)
                    {
                        viewModel.users.push(element.firstname + " " + element.lastname);
                    });

                    viewModel.addTableData(item.id, item.firstname, item.lastname, item.mail, viewModel.users().length);
                });
            });
        });
    };

    gvm.users = ko.observableArray([]);

    gvm.assassedUsers = ko.observableArray([]);

    gvm.tabledata = ko.observableArray([]);

    gvm.tempTableData = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, firstname, lastname, email, countAssessed) {
        // Push data
        var data = countAssessed;
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tScoreTableBtn: gvm.scoreTableTitle, tFilesTableBtn: gvm.filesTableTitle, tpid: gvm.projectId, email: email, tcountAssessed: data};
        gvm.tabledata.push(tblOject);
    };

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    };

    /*gvm.getAllData = function() {
        $.getJSON('/api/project/getAllData/' + $("#projectHeader").data('value'), function(data) {
            console.log(data);
        });
    }*/
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getStudentListBis();
    //viewModel.getStudentList();

    $("#searchField").bind("keypress", {}, keypressInBox);

}

function keypressInBox(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) { //Enter keycode
        $("#searchField").blur();
        getStudentByName();

    }
};

function createPDF(id,name,lastname,email, projectheader, projectdescription)
{
    /*$.getJSON('/api/finalscore/' + viewModel.projectId + '/' + id, function (data) {
        makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        //console.log(data);
    });*/

    $.ajax({
        url: '/api/finalscore/' + viewModel.projectId + '/' + id,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        },
        error: function()
        {
            alert("Please make sure points are given!");
        }
    });
}

function getStudentByName(){

    if(viewModel.tempTableData().length == 0) {
        viewModel.tempTableData(viewModel.tabledata.slice(0));
    }

    viewModel.tabledata([]);

    viewModel.tempTableData().forEach(function(item, element){
        var fullname = item.tfirstname + " " + item.tlastname;
        var fullnameReverse = item.tlastname + " " + item.tfirstname;

        if (item.tfirstname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || item.tlastname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullnameReverse.toLowerCase().contains(viewModel.searchStudent().toLowerCase())){
            viewModel.tabledata.push(item);
        }
    });
}

function showFullList()
{
    viewModel.searchStudent = ko.observable("");
    getStudentByName();
}

function getData(id)
{
    $.getJSON('/api/project/' + viewModel.projectId  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });
    });

    return viewModel.users();
}

function getNrOfAssessing(){
    $.getJSON('/api/project/nrOfAssessing/' + viewModel.projectId , function(data)
    {
        data.forEach(function(item)
        {
            console.log(item.nrOfAssessing);
            if (viewModel.tcountAssessed() == item.nrOfAssessing){
                alert("test");
            }

            return item.nrOfAssessing;
        });
    });
}

function getDataCount(projectid, id)
{
    $.getJSON('/api/project/' + projectid  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });

        return viewModel.users().length;
    });
}<|endoftext|>


<commit_before>'use strict';

define(['backend/port', 'darkwallet'], function(Port, DarkWallet) {

/**
 * Service to manage updating all badges.
 */
function BadgeService(core) {
    var self = this;
    this.name = 'badge';
    this.core = core;

    chrome.browserAction.setBadgeBackgroundColor({color:[0,0,0,255]});
    // Port to listen for open tabs so we can do something when
    // the tab closes
    Port.listen('badge', function() {
        }, function(port) {
            // Connected
        }, function(port) {
            // Disconnected
            var identity = DarkWallet.getIdentity();
            if (identity && identity.tasks.removeTasks(null, 'state', 'finished')) {
                self.setItems();
            }
    });
};

/**
 * Set item number from the given identity (or current identity)
 */
BadgeService.prototype.setItems = function(identity) {
    var identity = identity || this.core.getCurrentIdentity();

    // Only count send and receive tasks for now
    var openTasks = identity.tasks.getTasks('send');
    openTasks = openTasks.concat(identity.tasks.getTasks('receive'));

    // Filter to see if there are any unfinished ones
    var unfinished = openTasks.filter(function(task) {return task.state != 'finished'});

    // Set the colour
    if (!unfinished.length) {
        chrome.browserAction.setBadgeBackgroundColor({color:[0,200,0,255]});
    } else {
        chrome.browserAction.setBadgeBackgroundColor({color:[0,0,0,255]});
    }
    // Set the number of tasks
    if (openTasks.length) {
        chrome.browserAction.setBadgeText({text: ""+openTasks.length});
    } else {
        chrome.browserAction.setBadgeText({text: ""});
    }
};

return BadgeService;
});
<commit_msg>Make exiting from badge clear up cancelled tasks too.<commit_after>'use strict';

define(['backend/port', 'darkwallet'], function(Port, DarkWallet) {

/**
 * Service to manage updating all badges.
 */
function BadgeService(core) {
    var self = this;
    this.name = 'badge';
    this.core = core;

    chrome.browserAction.setBadgeBackgroundColor({color:[0,0,0,255]});
    // Port to listen for open tabs so we can do something when
    // the tab closes
    Port.listen('badge', function() {
        }, function(port) {
            // Connected
        }, function(port) {
            // Disconnected
            var identity = DarkWallet.getIdentity();
            if (identity) {
                var anyFinished = identity.tasks.removeTasks(null, 'state', 'finished');
                var anyCancelled = identity.tasks.removeTasks(null, 'state', 'cancelled');
                if (anyFinished || anyCancelled) {
                    self.setItems();
                }
            }
    });
};

/**
 * Set item number from the given identity (or current identity)
 */
BadgeService.prototype.setItems = function(identity) {
    var identity = identity || this.core.getCurrentIdentity();

    // Only count send and receive tasks for now
    var openTasks = identity.tasks.getTasks('send');
    openTasks = openTasks.concat(identity.tasks.getTasks('receive'));

    // Filter to see if there are any unfinished ones
    var unfinished = openTasks.filter(function(task) {return task.state != 'finished'});

    // Set the colour
    if (!unfinished.length) {
        chrome.browserAction.setBadgeBackgroundColor({color:[0,200,0,255]});
    } else {
        chrome.browserAction.setBadgeBackgroundColor({color:[0,0,0,255]});
    }
    // Set the number of tasks
    if (openTasks.length) {
        chrome.browserAction.setBadgeText({text: ""+openTasks.length});
    } else {
        chrome.browserAction.setBadgeText({text: ""});
    }
};

return BadgeService;
});
<|endoftext|>


<commit_before>jsio('from common.javascript import Class, bind');
jsio('from net.protocols.rtjp import RTJPProtocol');
jsio('import net, logging');
jsio('import common.itemFactory');

var logger = logging.getLogger('common.UbiquityClient');
logger.setLevel(0);

exports = Class(RTJPProtocol, function(supr) {
	this.init = function(playerFactory) {
		supr(this, 'init');
		this._isConnected = false;
		this._subscribedItems = {};
		this._labelCallbacks = {};
	}

	this.connect = function(transport, url, onConnectedCallback) {
		logger.log('Connecting...')
		this.url = url || this.url;
		this.transport = transport || this.transport || 'csp';
		this._onConnectedCallback = onConnectedCallback;
		if(!this._isConnected) {
			net.connect(this, this.transport, {url: this.url});
		}
	}

	this.sendFrame = function(name, args) {
		logger.log('sendFrame', name, JSON.stringify(args));
		supr(this, 'sendFrame', arguments);
	}

	this.isConnected = function() { return this._isConnected; }

	this.subscribeToItem = function(item) {
		if (this._subscribedItems[item.getId()]) { return; }
		this._subscribedItems[item.getId()] = true;
		var args = { id: item.getId() };
		this.sendFrame('ITEM_SUBSCRIBE', args);
	}

	this.getItemsForLabel = function(label, callback) {
		this._labelCallbacks[label] = callback;
		this.sendFrame('LABEL_GET_ITEMS', { label: label });
	}

	/* Private */
	this.connectionMade = function() {
		this._isConnected = true;
	}

	this.connectionLost = function() {
		this._isConnected = false;
	}

	/* Browser event handling */
	this.onItemPropertySet = function(itemId, propertyName, propertyValue) {
		this.sendFrame('ITEM_PROPERTY_SET', { id: itemId, name: propertyName, value: propertyValue });
	}

	/* Server event handling */
	this.frameReceived = function(id, name, args) {
		logger.log('frameReceived', id, name, JSON.stringify(args));

		switch(name) {
			case 'WELCOME':
				logger.log('Connected!')
				this._onConnectedCallback(args.labels);
				break;
			case 'ITEM_SNAPSHOT':
				setTimeout(function(){ common.itemFactory.loadItemSnapshot(args); });
				break;
			case 'ITEM_PROPERTY_UPDATED':
				var item = common.itemFactory.getItem(args.id);
				setTimeout(function(){ item.updateProperty(args.name, args.value); });
				break;
			case 'LABEL_ITEMS':
				var callback = this._labelCallbacks[args.label];
				delete this._labelCallbacks[args.label];
				var items = [];
				for (var i=0, itemId; itemId = args.itemIds[i]; i++) {
					var item = common.itemFactory.getItem(itemId);
					item.subscribe('PropertySet', bind(this, 'onItemPropertySet', item.getId()));
					this.subscribeToItem(item);
					items.push(item);
				}
				setTimeout(function(){ callback(args.label, items); });
				break;
		}
	}
});
<commit_msg>isConnected is not being used<commit_after>jsio('from common.javascript import Class, bind');
jsio('from net.protocols.rtjp import RTJPProtocol');
jsio('import net, logging');
jsio('import common.itemFactory');

var logger = logging.getLogger('common.UbiquityClient');
logger.setLevel(0);

exports = Class(RTJPProtocol, function(supr) {
	this.init = function(playerFactory) {
		supr(this, 'init');
		this._isConnected = false;
		this._subscribedItems = {};
		this._labelCallbacks = {};
	}

	this.connect = function(transport, url, onConnectedCallback) {
		logger.log('Connecting...')
		this.url = url || this.url;
		this.transport = transport || this.transport || 'csp';
		this._onConnectedCallback = onConnectedCallback;
		if(!this._isConnected) {
			net.connect(this, this.transport, {url: this.url});
		}
	}

	this.sendFrame = function(name, args) {
		logger.log('sendFrame', name, JSON.stringify(args));
		supr(this, 'sendFrame', arguments);
	}

	this.subscribeToItem = function(item) {
		if (this._subscribedItems[item.getId()]) { return; }
		this._subscribedItems[item.getId()] = true;
		var args = { id: item.getId() };
		this.sendFrame('ITEM_SUBSCRIBE', args);
	}

	this.getItemsForLabel = function(label, callback) {
		this._labelCallbacks[label] = callback;
		this.sendFrame('LABEL_GET_ITEMS', { label: label });
	}

	/* Private */
	this.connectionMade = function() {
		this._isConnected = true;
	}

	this.connectionLost = function() {
		this._isConnected = false;
	}

	/* Browser event handling */
	this.onItemPropertySet = function(itemId, propertyName, propertyValue) {
		this.sendFrame('ITEM_PROPERTY_SET', { id: itemId, name: propertyName, value: propertyValue });
	}

	/* Server event handling */
	this.frameReceived = function(id, name, args) {
		logger.log('frameReceived', id, name, JSON.stringify(args));

		switch(name) {
			case 'WELCOME':
				logger.log('Connected!')
				this._onConnectedCallback(args.labels);
				break;
			case 'ITEM_SNAPSHOT':
				setTimeout(function(){ common.itemFactory.loadItemSnapshot(args); });
				break;
			case 'ITEM_PROPERTY_UPDATED':
				var item = common.itemFactory.getItem(args.id);
				setTimeout(function(){ item.updateProperty(args.name, args.value); });
				break;
			case 'LABEL_ITEMS':
				var callback = this._labelCallbacks[args.label];
				delete this._labelCallbacks[args.label];
				var items = [];
				for (var i=0, itemId; itemId = args.itemIds[i]; i++) {
					var item = common.itemFactory.getItem(itemId);
					item.subscribe('PropertySet', bind(this, 'onItemPropertySet', item.getId()));
					this.subscribeToItem(item);
					items.push(item);
				}
				setTimeout(function(){ callback(args.label, items); });
				break;
		}
	}
});
<|endoftext|>