<commit_before>function notlarComboBoxOlustur(index) {
    let not_cb_html = '<select id="not' + index + '" class="form-control">' +
        '<option >Seçiniz</option>' +
        '<option value="4.0">AA</option>' +
        '<option value="3.5">BA</option>' +
        '<option value="3.0">BB</option>' +
        '<option value="2.5">CB</option>' +
        '<option value="2.0">CC</option>' +
        '<option value="1.5">DC</option>' +
        '<option value="1.0">DD</option>' +
        '<option value="0.5">FD</option>' +
        '<option value="0.0">FF</option>' +
        '</select>';
    return not_cb_html;
}

function kredilerComboBoxOlustur(index) {
    let kredi_cb_html = '<select id="kredi' + index + '" class="form-control"> ';
    for (i = 0; i < 30; i++) {
        kredi_cb_html += '<option value="' + (i + 1) + '">' + (i + 1) + '</option>';
    }
    kredi_cb_html += '</select>';

    return kredi_cb_html;
}

function dersKredisiniGetir(all_courses, course_code) {
    let course = all_courses.find(function (course) {
        return course.course_code === course_code;
    });
    if (course === undefined) {
        alert("course_ects.json'da bulunamayan ders: " + course_code);
    }

    return course.course_ects[0];
}

function tabloyaDersEkle(course_code, course_name, index) {
    let course_name_html = '<input type="text" class="form-control col-sm-10" id="dersadi' + index + '" value="' + course_name + '">';
    let course_credits_html = kredilerComboBoxOlustur(index);
    let course_grades_html = notlarComboBoxOlustur(index);

    $("#not_tablosu").find('tbody')
        .append($('
')
            .append($('').append(course_code))
            .append($('').append(course_name_html))
            .append($('').append(course_credits_html))
            .append($('').append(course_grades_html))
            .append($('').append('<input color="black" class="silinicekSatir" type="button" value="Sil">'))
        );
}
let VALID_GRADES = ["AA", "BA", "BB", "CB", "CC", "DC", "DD", "FD", "FF"];

function ganoHesaplaYazdir() {
    let not_kredi_dict = {};
    $("tr").each(function () {
        let id = $(this).attr('id');
        let not = $("#not" + id + " option:selected").val();
        let kredi = $("#kredi" + id + " option:selected").val();

        if (not !== "Seçiniz") {
            not = parseFloat(not);
            if (not_kredi_dict[not]) {
                not_kredi_dict[not] = not_kredi_dict[not] + parseInt(kredi);
            } else {
                not_kredi_dict[not] = parseInt(kredi);
            }
        }
    });

    delete not_kredi_dict['NaN'];

    let tamamlananKredi = 0;
    let gano = 0.0;

    for (let not in not_kredi_dict) {
        let kredi = parseInt(not_kredi_dict[not]);
        tamamlananKredi = tamamlananKredi + kredi;
    }

    for (let not in not_kredi_dict) {
        let kredi = parseInt(not_kredi_dict[not]);
        gano = gano + kredi * not;
    }
    gano = gano / tamamlananKredi;
    gano = parseFloat(gano).toFixed(2);

    $("#gano").text(gano);
    $("#akts").text(tamamlananKredi);
}

chrome.storage.sync.get("parsed_courses", function (items) {

    $.getJSON("https://raw.githubusercontent.com/cankatabaci/ChromeEklenti-v1/master/src/course_ects.json", function (json) {
        let all_courses = json;
        let parsed_courses = items.parsed_courses;

        for (index = 0; index < parsed_courses.length; ++index) {

            if (VALID_GRADES.includes(parsed_courses[index].course_grade.toString()) || parsed_courses[index].course_grade.toString() === "A") {

                let course_code = parsed_courses[index].course_code;
                let course_name = parsed_courses[index].course_name;
                tabloyaDersEkle(course_code, course_name, index);

                let course_credit = dersKredisiniGetir(all_courses, course_code);

                $("#not" + index + " option").filter(function () { // selecting grade options based on its text
                    return $(this).text() === parsed_courses[index].course_grade;
                }).prop("selected", true);

                $("#kredi" + index + " option").filter(function () { // selecting credits options based on its text
                    return $(this).text() === course_credit.toString();
                }).prop("selected", true);

                ganoHesaplaYazdir();
            } else {
                console.log(parsed_courses[index].course_grade);
            }
        }

    });
});

function satirdakiDersAdiniGetirme(satirID) {
    let degisken = "dersadi" + satirID;
    return $("#" + degisken).val();
}

$(document).ready(function () {

    $('#not_tablosu').on('click', 'select', function () {
        ganoHesaplaYazdir();
    });

    $('#not_tablosu').on('click', '.silinicekSatir', function () {
        let aktif = $(this);
        let satirID = aktif.closest("tr").attr('id');
        let dersAd = satirdakiDersAdiniGetirme(satirID);
        if (confirm(dersAd + ' Dersini Silmek İstediğinizden Emin Misiniz?')) {
            $(this).parent('td').parent('tr').remove();
            ganoHesaplaYazdir();
        }
    });

    $('#btn').click(function () {
        let kod = "Eklenen";
        let name = "";
        let id = $('#not_tablosu tr:last').attr('id');

        tabloyaDersEkle(kod, name, id + 1);
        alert("Yeni Ders Satırı Eklenmiştir");
        $("html, body").animate({scrollTop: $(document).height() - $(window).height()});//Scrolls to bottom.
    });

    $('#yenile').click(function () {
        location.reload();
    });

});
<commit_msg>Bulunamayan dersler için console.log eklendi<commit_after>function notlarComboBoxOlustur(index) {
    let not_cb_html = '<select id="not' + index + '" class="form-control">' +
        '<option >Seçiniz</option>' +
        '<option value="4.0">AA</option>' +
        '<option value="3.5">BA</option>' +
        '<option value="3.0">BB</option>' +
        '<option value="2.5">CB</option>' +
        '<option value="2.0">CC</option>' +
        '<option value="1.5">DC</option>' +
        '<option value="1.0">DD</option>' +
        '<option value="0.5">FD</option>' +
        '<option value="0.0">FF</option>' +
        '</select>';
    return not_cb_html;
}

function kredilerComboBoxOlustur(index) {
    let kredi_cb_html = '<select id="kredi' + index + '" class="form-control"> ';
    for (i = 0; i < 30; i++) {
        kredi_cb_html += '<option value="' + (i + 1) + '">' + (i + 1) + '</option>';
    }
    kredi_cb_html += '</select>';

    return kredi_cb_html;
}

function dersKredisiniGetir(all_courses, course_code) {
    let course = all_courses.find(function (course) {
        return course.course_code === course_code;
    });
    if (course === undefined) {
        alert("course_ects.json'da bulunamayan ders: " + course_code);
        console.log("Bunulanamayan ders: [" + course_code + "]");
    }

    return course.course_ects[0];
}

function tabloyaDersEkle(course_code, course_name, index) {
    let course_name_html = '<input type="text" class="form-control col-sm-10" id="dersadi' + index + '" value="' + course_name + '">';
    let course_credits_html = kredilerComboBoxOlustur(index);
    let course_grades_html = notlarComboBoxOlustur(index);

    $("#not_tablosu").find('tbody')
        .append($('
')
            .append($('').append(course_code))
            .append($('').append(course_name_html))
            .append($('').append(course_credits_html))
            .append($('').append(course_grades_html))
            .append($('').append('<input color="black" class="silinicekSatir" type="button" value="Sil">'))
        );
}
let VALID_GRADES = ["AA", "BA", "BB", "CB", "CC", "DC", "DD", "FD", "FF"];

function ganoHesaplaYazdir() {
    let not_kredi_dict = {};
    $("tr").each(function () {
        let id = $(this).attr('id');
        let not = $("#not" + id + " option:selected").val();
        let kredi = $("#kredi" + id + " option:selected").val();

        if (not !== "Seçiniz") {
            not = parseFloat(not);
            if (not_kredi_dict[not]) {
                not_kredi_dict[not] = not_kredi_dict[not] + parseInt(kredi);
            } else {
                not_kredi_dict[not] = parseInt(kredi);
            }
        }
    });

    delete not_kredi_dict['NaN'];

    let tamamlananKredi = 0;
    let gano = 0.0;

    for (let not in not_kredi_dict) {
        let kredi = parseInt(not_kredi_dict[not]);
        tamamlananKredi = tamamlananKredi + kredi;
    }

    for (let not in not_kredi_dict) {
        let kredi = parseInt(not_kredi_dict[not]);
        gano = gano + kredi * not;
    }
    gano = gano / tamamlananKredi;
    gano = parseFloat(gano).toFixed(2);

    $("#gano").text(gano);
    $("#akts").text(tamamlananKredi);
}

chrome.storage.sync.get("parsed_courses", function (items) {

    $.getJSON("https://raw.githubusercontent.com/cankatabaci/ChromeEklenti-v1/master/src/course_ects.json", function (json) {
        let all_courses = json;
        let parsed_courses = items.parsed_courses;

        for (index = 0; index < parsed_courses.length; ++index) {

            if (VALID_GRADES.includes(parsed_courses[index].course_grade.toString()) || parsed_courses[index].course_grade.toString() === "A") {

                let course_code = parsed_courses[index].course_code;
                let course_name = parsed_courses[index].course_name;
                tabloyaDersEkle(course_code, course_name, index);

                let course_credit = dersKredisiniGetir(all_courses, course_code);

                $("#not" + index + " option").filter(function () { // selecting grade options based on its text
                    return $(this).text() === parsed_courses[index].course_grade;
                }).prop("selected", true);

                $("#kredi" + index + " option").filter(function () { // selecting credits options based on its text
                    return $(this).text() === course_credit.toString();
                }).prop("selected", true);

                ganoHesaplaYazdir();
            } else {
                console.log(parsed_courses[index].course_grade);
            }
        }

    });
});

function satirdakiDersAdiniGetirme(satirID) {
    let degisken = "dersadi" + satirID;
    return $("#" + degisken).val();
}

$(document).ready(function () {

    $('#not_tablosu').on('click', 'select', function () {
        ganoHesaplaYazdir();
    });

    $('#not_tablosu').on('click', '.silinicekSatir', function () {
        let aktif = $(this);
        let satirID = aktif.closest("tr").attr('id');
        let dersAd = satirdakiDersAdiniGetirme(satirID);
        if (confirm(dersAd + ' Dersini Silmek İstediğinizden Emin Misiniz?')) {
            $(this).parent('td').parent('tr').remove();
            ganoHesaplaYazdir();
        }
    });

    $('#btn').click(function () {
        let kod = "Eklenen";
        let name = "";
        let id = $('#not_tablosu tr:last').attr('id');

        tabloyaDersEkle(kod, name, id + 1);
        alert("Yeni Ders Satırı Eklenmiştir");
        $("html, body").animate({scrollTop: $(document).height() - $(window).height()});//Scrolls to bottom.
    });

    $('#yenile').click(function () {
        location.reload();
    });

});
<|endoftext|>


<commit_before>var should = require('chai').should();
var sinon = require('sinon');
var _ = require('lodash');

var _convert = require('./../../app/convert.js');

var _factory = {};

var _axial = {
  'q': 2,
  'r': -3
};

var _cube = {
  'x': 2,
  'y': 1,
  'z': -3
};

_.set(_factory, 'create.from.axial', sinon.stub().returns(_axial));

_.set(_factory, 'create.from.cube', sinon.stub().returns(_cube));

_convert = _convert(_factory);

describe('convert.from.cube.to.axial()', function () {
  it('should exist', function () {
    _convert.from.cube.to.axial.should.exist;
  });

  it('should return an axial hex object', function () {
    var cube = [2, 1, -3];
    var axial = _convert.from.cube.to.axial(cube);

    axial.should.have.property('q').which.eql(2);
    axial.should.have.property('r').which.eql(-3);
  });

  it('should work with objects', function () {
    var cube = {
      'x': 2,
      'y': 1,
      'z': -3
    }
    var axial = _convert.from.cube.to.axial(cube);

    axial.should.have.property('q').which.eql(2);
    axial.should.have.property('r').which.eql(-3);
  });
});

describe('convert.from.axial.to.cube()', function () {
  it('should exist', function () {
    _convert.from.axial.to.cube.should.exist;
  });

  it('should return a cube hex object', function () {
    var axial = [2, -3];
    var cube = _convert.from.axial.to.cube(axial);

    cube.should.have.property('x').which.eql(2);
    cube.should.have.property('y').which.eql(1);
    cube.should.have.property('z').which.eql(-3);
  });

  it('should work with objects', function () {
    var axial = {
      'q': 2,
      'r': -3
    }
    var cube = _convert.from.axial.to.cube(axial);

    cube.should.have.property('x').which.eql(2);
    cube.should.have.property('y').which.eql(1);
    cube.should.have.property('z').which.eql(-3);
  });
});
<commit_msg>Removed repetition<commit_after>var should = require('chai').should();
var sinon = require('sinon');
var _ = require('lodash');

var _convert = require('./../../app/convert.js');

var _factory = {};

var _axial = {
  'q': 2,
  'r': -3
};

var _cube = {
  'x': 2,
  'y': 1,
  'z': -3
};

_.set(_factory, 'create.from.axial', sinon.stub().returns(_axial));

_.set(_factory, 'create.from.cube', sinon.stub().returns(_cube));

_convert = _convert(_factory);

describe('convert.from.cube.to.axial()', function () {
  it('should exist', function () {
    _convert.from.cube.to.axial.should.exist;
  });

  it('should return an axial hex object', function () {
    var cube = [2, 1, -3];
    var axial = _convert.from.cube.to.axial(cube);

    axial.should.have.property('q').which.eql(2);
    axial.should.have.property('r').which.eql(-3);
  });

  it('should work with objects', function () {
    var axial = _convert.from.cube.to.axial(_cube);

    axial.should.have.property('q').which.eql(2);
    axial.should.have.property('r').which.eql(-3);
  });
});

describe('convert.from.axial.to.cube()', function () {
  it('should exist', function () {
    _convert.from.axial.to.cube.should.exist;
  });

  it('should return a cube hex object', function () {
    var axial = [2, -3];
    var cube = _convert.from.axial.to.cube(axial);

    cube.should.have.property('x').which.eql(2);
    cube.should.have.property('y').which.eql(1);
    cube.should.have.property('z').which.eql(-3);
  });

  it('should work with objects', function () {
    var cube = _convert.from.axial.to.cube(_axial);

    cube.should.have.property('x').which.eql(2);
    cube.should.have.property('y').which.eql(1);
    cube.should.have.property('z').which.eql(-3);
  });
});
<|endoftext|>


<commit_before>import Base from './base';
import ModelMixin from './-model-mixin';

export default class BaseProxyInternal extends ModelMixin(Base) {

  constructor(store, database, owner, opts) {
    super();
    this.store = store;
    this.database = database;
    this.owner = owner;
    this.opts = opts;
    this._filter = null;
    this._loader = null;
    console.log(opts);
  }

  //

  _createFilter() {
    let { owner, document, matches } = this.opts;
    return this.database._createInternalFilter(this.owner, { owner, document, matches });
  }

  filter(create) {
    let filter = this._filter;
    if(!filter && create) {
      filter = this._createFilter();
      this._filter = filter;
    }
    return filter;
  }

  //

  loader(create) {
    let loader = this._loader;
    if(!loader && create) {
      loader = this._createLoader();
      this._loader = loader;
    }
    return loader;
  }

  //

  _didDestroyModel() {
    super._didDestroyModel();

    let filter = this.filter();
    if(filter) {
      filter.destroy();
    }

    let loader = this.loader();
    if(loader) {
      loader.destroy();
    }
  }

  //

  destroy() {
    let model = this.model(false);
    if(model) {
      model.destroy();
    }
  }

}
<commit_msg>remove console.log<commit_after>import Base from './base';
import ModelMixin from './-model-mixin';

export default class BaseProxyInternal extends ModelMixin(Base) {

  constructor(store, database, owner, opts) {
    super();
    this.store = store;
    this.database = database;
    this.owner = owner;
    this.opts = opts;
    this._filter = null;
    this._loader = null;
  }

  //

  _createFilter() {
    let { owner, document, matches } = this.opts;
    return this.database._createInternalFilter(this.owner, { owner, document, matches });
  }

  filter(create) {
    let filter = this._filter;
    if(!filter && create) {
      filter = this._createFilter();
      this._filter = filter;
    }
    return filter;
  }

  //

  loader(create) {
    let loader = this._loader;
    if(!loader && create) {
      loader = this._createLoader();
      this._loader = loader;
    }
    return loader;
  }

  //

  _didDestroyModel() {
    super._didDestroyModel();

    let filter = this.filter();
    if(filter) {
      filter.destroy();
    }

    let loader = this.loader();
    if(loader) {
      loader.destroy();
    }
  }

  //

  destroy() {
    let model = this.model(false);
    if(model) {
      model.destroy();
    }
  }

}
<|endoftext|>


<commit_before>// @flow

const KeycloakAdminClient = require('keycloak-admin').default;
const logger = require('../logger');

/* ::

type ConnectionSettings = {
  baseUrl?: string,
  realmName?: string,
  requestConfig?: Object,
}

type UserSettings = {
  username?: string,
  password?: string,
  grantType?: string,
  clientId?: string,
};

*/

async function waitAndInitKeycloak(
  connectionSettings /* : ConnectionSettings */,
  userSettings /* : UserSettings */,
) {
  let keycloakClient;
  let keycloakReady = false;

  do {
    try {
      keycloakClient = new KeycloakAdminClient(connectionSettings);
      await keycloakClient.auth(userSettings);
      keycloakReady = true;
    } catch (err) {
      logger.debug('Waiting for Keycloak to start...');
      await new Promise(resolve => setTimeout(resolve, 2000));
    }
  } while (!keycloakReady);

  if (!keycloakClient) {
    throw new Error('Keycloak client not initialized!');
  }

  logger.debug('Connected to Keycloak');

  return keycloakClient;
}

module.exports = waitAndInitKeycloak;
<commit_msg>more resilient keycloak init: - wait until the realm lagoon exists - reauth every 55 secs to prevent issue of access token being not valid anymore<commit_after>// @flow

const KeycloakAdminClient = require('keycloak-admin').default;
const logger = require('../logger');

/* ::

type ConnectionSettings = {
  baseUrl?: string,
  realmName?: string,
  requestConfig?: Object,
}

type UserSettings = {
  username?: string,
  password?: string,
  grantType?: string,
  clientId?: string,
};

*/

async function waitAndInitKeycloak(
  connectionSettings /* : ConnectionSettings */,
  userSettings /* : UserSettings */,
) {
  let keycloakClient;
  let keycloakReady = false;

  keycloakClient = new KeycloakAdminClient(connectionSettings);

  do {
    try {
      await keycloakClient.auth(userSettings);
      const realm = await keycloakClient.realms.findOne({realm: 'lagoon'});
      if (!realm) {
        throw new Error('lagoon realm not existing')
      }
      keycloakReady = true;
    } catch (err) {
      logger.debug(`Waiting for Keycloak to start... (error was ${err})`);
      await new Promise(resolve => setTimeout(resolve, 2000));
    }

  } while (!keycloakReady);

  setInterval(async () => await keycloakClient.auth(userSettings), 55*1000);

  if (!keycloakClient) {
    throw new Error('Keycloak client not initialized!');
  }

  logger.debug('Connected to Keycloak');

  return keycloakClient;
}

module.exports = waitAndInitKeycloak;
<|endoftext|>


<commit_before>'use strict';

const WorldstateObject = require('./WorldstateObject.js');
const SyndicateJob = require('./SyndicateJob.js');

/**
 * Represents a syndicate daily mission
 * @extends {WorldstateObject}
 */
class SyndicateMission extends WorldstateObject {
  /**
   * @param   {Object}             data            The syndicate mission data
   * @param   {Object}             deps            The dependencies object
   * @param   {MarkdownSettings}   deps.mdConfig   The markdown settings
   * @param   {Translator}         deps.translator The string translator
   * @param   {TimeDateFunctions}  deps.timeDate   The time and date functions
   */
  constructor(data, { mdConfig, translator, timeDate }) {
    super(data);

    /**
     * The markdown settings
     * @type {MarkdownSettings}
     * @private
     */
    this.mdConfig = mdConfig;
    Object.defineProperty(this, 'mdConfig', { enumerable: false, configurable: false });

    /**
     * The time and date functions
     * @type {TimeDateFunctions}
     * @private
     */
    this.timeDate = timeDate;
    Object.defineProperty(this, 'timeDate', { enumerable: false, configurable: false });

     /**
     * The translation functions
     * @type {Translator}
     * @private
     */
    this.translator = translator;
    Object.defineProperty(this, 'translator', { enumerable: false, configurable: false });

    /**
     * The date and time at which the syndicate mission starts
     * @type {Date}
     */
    this.activation = timeDate.parseDate(data.Activation);

    /**
     * The date and time at which the syndicate mission ends
     * @type {Date}
     */
    this.expiry = timeDate.parseDate(data.Expiry);

    /**
     * The syndicate that is offering the mission
     * @type {string}
     */
    this.syndicate = translator.syndicate(data.Tag);

    /**
     * The nodes on which the missions are taking place
     * @type {Array.<string>}
     */
    this.nodes = data.Nodes.map(n => translator.node(n));

    /**
     * The jobs for this syndicate. Will normally be []
     * @type {Array.<SyndicateJob>}
     */
    this.jobs = (data.Jobs || []).map(j => new SyndicateJob(j, expiry, { translator: this.translator, timeDate: this.timeDate }));

    /**
     * Unique identifier for this mission set built from the end time and syndicate
     * @type {string}
     */
    this.id = `${this.expiry.getTime()}${this.syndicate.replace(/\\s/i, '')}`;

    /**
     * ETA string (at time of object creation)
     * @type {String}
     */
    this.eta = this.getETAString();
  }

  /**
   * Get a string indicating how much time is left before the syndicate mission expries
   * @returns {string}
   */
  getETAString() {
    return this.timeDate.timeDeltaToString(this.timeDate.fromNow(this.expiry));
  }

  /**
   * Returns a string representation of the syndicate mission
   * @returns {string}
   */
  toString() {
    if (this.nodes.length > 0) {
      const missions = this.nodes.map(n => `  \u2022${n.toString()}`).join(this.mdConfig.lineEnd);
      return `[${this.getETAString()}] ${this.syndicate} currently has missions on: ` +
        `${this.mdConfig.lineEnd}${missions}`;
    }

    return `No missions available for ${this.syndicate}`;
  }
}

module.exports = SyndicateMission;
<commit_msg>attempt fix for weird desctructuring<commit_after>'use strict';

const WorldstateObject = require('./WorldstateObject.js');
const SyndicateJob = require('./SyndicateJob.js');

/**
 * Represents a syndicate daily mission
 * @extends {WorldstateObject}
 */
class SyndicateMission extends WorldstateObject {
  /**
   * @param   {Object}             data            The syndicate mission data
   * @param   {Object}             deps            The dependencies object
   * @param   {MarkdownSettings}   deps.mdConfig   The markdown settings
   * @param   {Translator}         deps.translator The string translator
   * @param   {TimeDateFunctions}  deps.timeDate   The time and date functions
   */
  constructor(data, { mdConfig, translator, timeDate }) {
    super(data);

    const deps = { mdConfig, translator, timeDate };

    /**
     * The markdown settings
     * @type {MarkdownSettings}
     * @private
     */
    this.mdConfig = mdConfig;
    Object.defineProperty(this, 'mdConfig', { enumerable: false, configurable: false });

    /**
     * The time and date functions
     * @type {TimeDateFunctions}
     * @private
     */
    this.timeDate = timeDate;
    Object.defineProperty(this, 'timeDate', { enumerable: false, configurable: false });

     /**
     * The translation functions
     * @type {Translator}
     * @private
     */
    this.translator = translator;
    Object.defineProperty(this, 'translator', { enumerable: false, configurable: false });

    /**
     * The date and time at which the syndicate mission starts
     * @type {Date}
     */
    this.activation = timeDate.parseDate(data.Activation);

    /**
     * The date and time at which the syndicate mission ends
     * @type {Date}
     */
    this.expiry = timeDate.parseDate(data.Expiry);

    /**
     * The syndicate that is offering the mission
     * @type {string}
     */
    this.syndicate = translator.syndicate(data.Tag);

    /**
     * The nodes on which the missions are taking place
     * @type {Array.<string>}
     */
    this.nodes = data.Nodes.map(n => translator.node(n));

    /**
     * The jobs for this syndicate. Will normally be []
     * @type {Array.<SyndicateJob>}
     */
    this.jobs = (data.Jobs || []).map(j => new SyndicateJob(j, expiry, deps));

    /**
     * Unique identifier for this mission set built from the end time and syndicate
     * @type {string}
     */
    this.id = `${this.expiry.getTime()}${this.syndicate.replace(/\\s/i, '')}`;

    /**
     * ETA string (at time of object creation)
     * @type {String}
     */
    this.eta = this.getETAString();
  }

  /**
   * Get a string indicating how much time is left before the syndicate mission expries
   * @returns {string}
   */
  getETAString() {
    return this.timeDate.timeDeltaToString(this.timeDate.fromNow(this.expiry));
  }

  /**
   * Returns a string representation of the syndicate mission
   * @returns {string}
   */
  toString() {
    if (this.nodes.length > 0) {
      const missions = this.nodes.map(n => `  \u2022${n.toString()}`).join(this.mdConfig.lineEnd);
      return `[${this.getETAString()}] ${this.syndicate} currently has missions on: ` +
        `${this.mdConfig.lineEnd}${missions}`;
    }

    return `No missions available for ${this.syndicate}`;
  }
}

module.exports = SyndicateMission;
<|endoftext|>


<commit_before>/*用来删除写到xunit report里的install信息*/

var fs = require('fs');
var file = "report.xml";
var report = fs.readFileSync(file);
var content = report.toString().split('\n');
var i = 0;
for(i=0; i<content.length;i++ ){
    var reg = /\binstall.*/g ;
    callback = function($1){
        if($1){
            content.splice(i,1);
            i--;
        }
    };
    content[i].replace(reg,callback);
}
fs.writeFileSync(file, content);<commit_msg>[case]删除xunit report.xml中install输出的信息<commit_after>/*用来删除写到xunit report里的install信息*/

var fs = require('fs');
var file = "report.xml";
var report = fs.readFileSync(file);
var content = report.toString().split('\n');
var i = 0;
for(i=0; i<content.length;i++ ){
    var reg = /\binstall.*/g ;
    callback = function($1){
        if($1){
            content.splice(i,1);
            i--;
        }
    };
    content[i].replace(reg,callback);
}
for(i=0; i<content.length;i++ ){
    content[i] = content[i]+'\n';
}
fs.writeFileSync(file, content);<|endoftext|>


<commit_before>import Stops from './defaults.js';
import * as C from '../../common/Census.js';

const CensusHandler = C.CensusHandlerBase;

function process_key (key) {
  return key
    .replace('Unknown', 'other')
    .toLowerCase()
    .replace(/\s/, '_');
}

const CensusRatioDonut = C.CensusRatioDonutBase.extend({
  Stops: Stops,

  _items: function () {
    return Stops.ethnicities;
  },

  _pprint: function (type) {
    return type;
  },

  _process_key: process_key,

  triggerRaceToggle: () => null
});

var CensusTable = C.CensusTableBase.extend({
  _get_header_rows: function () {
    return Stops.pprint.values();
  },

  _process_key: (key) => key,

  types: [Stops.races, Stops.census_ethnicities]
});

export default {
  CensusHandler,
  CensusRatioDonut,
  CensusTable
};
<commit_msg>Removing "Hispanic" from MD census donut races<commit_after>import Stops from './defaults.js';
import * as C from '../../common/Census.js';

const CensusHandler = C.CensusHandlerBase;

function process_key (key) {
  return key
    .replace('Unknown', 'other')
    .toLowerCase()
    .replace(/\s/, '_');
}

const CensusRatioDonut = C.CensusRatioDonutBase.extend({
  Stops: Stops,

  _items: function () {
    return Stops.races;
  },

  _pprint: function (type) {
    return Stops.pprint.get(type);
  },

  _process_key: process_key,

  triggerRaceToggle: () => null
});

var CensusTable = C.CensusTableBase.extend({
  _get_header_rows: function () {
    return Stops.pprint.values();
  },

  _process_key: (key) => key,

  types: [Stops.races, Stops.census_ethnicities]
});

export default {
  CensusHandler,
  CensusRatioDonut,
  CensusTable
};
<|endoftext|>


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

  angular.module('toastr')
    .directive('progressBar', progressBar);

  progressBar.$inject = ['toastrConfig'];

  function progressBar(toastrConfig) {
    return {
      replace: true,
      require: '^toast',
      templateUrl: function() {
        return toastrConfig.templates.progressbar;
      },
      link: linkFunction
    };

    function linkFunction(scope, element, attrs, toastCtrl) {
      var intervalId, currentTimeOut, hideTime;

      toastCtrl.progressBar = scope;

      scope.start = function(duration) {
        if (intervalId) {
          clearInterval(intervalId);
        }

        currentTimeOut = parseFloat(duration);
        hideTime = new Date().getTime() + currentTimeOut;
        intervalId = setInterval(updateProgress, 10);
      };

      scope.stop = function() {
        if (intervalId) {
          clearInterval(intervalId);
        }
      };

      function updateProgress() {
        console.log('update');
        var percentage = ((hideTime - (new Date().getTime())) / currentTimeOut) * 100;
        element.css('width', percentage + '%');
      }

      scope.$on('$destroy', function() {
        // Failsafe stop
        clearInterval(intervalId);
      });
    }
  }
}());
<commit_msg>Remove nasty console.log<commit_after>(function() {
  'use strict';

  angular.module('toastr')
    .directive('progressBar', progressBar);

  progressBar.$inject = ['toastrConfig'];

  function progressBar(toastrConfig) {
    return {
      replace: true,
      require: '^toast',
      templateUrl: function() {
        return toastrConfig.templates.progressbar;
      },
      link: linkFunction
    };

    function linkFunction(scope, element, attrs, toastCtrl) {
      var intervalId, currentTimeOut, hideTime;

      toastCtrl.progressBar = scope;

      scope.start = function(duration) {
        if (intervalId) {
          clearInterval(intervalId);
        }

        currentTimeOut = parseFloat(duration);
        hideTime = new Date().getTime() + currentTimeOut;
        intervalId = setInterval(updateProgress, 10);
      };

      scope.stop = function() {
        if (intervalId) {
          clearInterval(intervalId);
        }
      };

      function updateProgress() {
        var percentage = ((hideTime - (new Date().getTime())) / currentTimeOut) * 100;
        element.css('width', percentage + '%');
      }

      scope.$on('$destroy', function() {
        // Failsafe stop
        clearInterval(intervalId);
      });
    }
  }
}());
<|endoftext|>


<commit_before>// Column header date format options
var HEADER_DATE_OPTIONS = { month: "short", day: "2-digit" };
// Column header time format options
var HEADER_TIME_OPTIONS = { hour: "2-digit", minute: "2-digit" };

// Notifier control
var notifier = null;
// Current view date
var viewDate = null;

// Time period: firstHour <= timeFrom <= timeTo <= lastHour
// Beginning of the displayed time period
var timeFrom = null;
// End of the displayed time period
var timeTo = null;
// First possible hour of the time period
var firstHour = null;
// Last possible hour of the time period
var lastHour = null

// jQuery cells that display current data
var curDataCells = null;
// Array of columns those display hourly data, and consist of jQuery cells
var hourDataCols = [];
// Timeout ID of the hourly data updating timer
var updateHourDataTimeoutID = null;

// Set current view date to the initial value
function initViewDate() {
    if (viewHub) {
        if (viewHub.currentViewDate) {
            setViewDate(viewHub.currentViewDate);
        } else {
            viewHub.currentViewDate = today;
            setViewDate(today);
        }
    } else {
        setViewDate(today);
    }
}

// Parse manually entered view date and apply it
function parseViewDate(dateStr) {
    scada.clientAPI.parseDateTime(dateStr, function (success, value) {
        if (Number.isInteger(value)) {
            var parsedDate = new Date(value);
            setViewDate(parsedDate);
            sendViewDateNotification(parsedDate);
            restartUpdatingHourData();
        } else {
            $("#spanDate i").addClass("error");
        }
    });
}

// Set current view date
function setViewDate(date) {
    viewDate = date;
    $("#txtDate").val(date.toLocaleDateString(locale, VIEW_DATE_OPTIONS));
    $("#spanDate i").removeClass("error");
    updateHourDataColHdrText();
}

// Send view date changed notification to data windows
function sendViewDateNotification(date) {
    if (viewHub) {
        viewHub.notify(scada.EventTypes.VIEW_DATE_CHANGED, window, date);
    }
}

// Retrieve the time period from the control values
function retrieveTimePeriod() {
    timeFrom = parseInt($("#selTimeFrom").val());
    timeTo = parseInt($("#selTimeTo").val());
    firstHour = $("#divTblWrapper tr:first td.hour:first").data("hour");
    lastHour = $("#divTblWrapper tr:first td.hour:last").data("hour");
}

// Correct the beginning of the time period
function correctTimeFrom() {
    if (timeFrom > timeTo) {
        timeFrom = timeTo;
        $("#selTimeFrom").val(timeFrom);
    }
}

// Correct the end of the time period
function correctTimeTo()
{
    if (timeTo < timeFrom) {
        timeTo = timeFrom;
        $("#selTimeTo").val(timeFrom);
    }
}

// Save the time period in the cookies
function saveTimePeriod() {
    scada.utils.setCookie("Table.TimeFrom", $("#selTimeFrom").val());
    scada.utils.setCookie("Table.TimeTo", $("#selTimeTo").val());
}

// Select and prepare the current data cells
function initCurDataCells() {
    // select cells
    curDataCells = $("#divTblWrapper td.cur");

    // copy data-cnl attributes from rows to the cells
    curDataCells.each(function () {
        $(this).data("cnl", $(this).closest("tr.item").data("cnl"));
    });
}

// Select and prepare the hourly data columns
function initHourDataCols() {
    // init columns
    hourDataCols.length = lastHour - firstHour + 1;
    for (var i = 0, len = hourDataCols.length; i < len; i++) {
        hourDataCols[i] = [];
    }

    // get and arrange cells
    $("#divTblWrapper tr.item").each(function () {
        var row = $(this);
        var cnlNum = row.data("cnl");
        row.find("td.hour").each(function () {
            var cell = $(this);
            cell.data("cnl", cnlNum);
            var hour = cell.data("hour");
            hourDataCols[hour - firstHour].push(cell);
        });
    });
}

// Update header text of the hourly data columns
function updateHourDataColHdrText() {
    $("#divTblWrapper tr.hdr td.hour").each(function () {
        var cell = $(this);
        var hour = cell.data("hour");
        var colDT = new Date(viewDate.getTime());
        colDT.setHours(hour);

        if (timeFrom >= 0) {
            // display time only
            cell.text(colDT.toLocaleTimeString(locale, HEADER_TIME_OPTIONS));
        } else {
            // display date and time
            cell.text(colDT.toLocaleDateString(locale, HEADER_DATE_OPTIONS) + " " +
                colDT.toLocaleTimeString(locale, HEADER_TIME_OPTIONS));
        }
    });
}

// Update visibility of the table view columns according to the time period
function updateHourDataColVisibility() {
    $("#divTblWrapper tr").each(function () {
        var row = $(this);
        var hourCells = row.find("td.hour");

        // show all the cells of the row
        hourCells.removeClass("hidden");

        // hide cells from the left
        var cellsToHide = timeFrom - firstHour;
        if (cellsToHide > 0) {
            var cells = hourCells.slice(0, cellsToHide);
            cells.addClass("hidden");
            if (row.hasClass("item")) {
                cells.text(""); // clear cell text
            }
        }

        // hide cells from the right
        cellsToHide = lastHour - timeTo;
        if (cellsToHide > 0) {
            cells = hourCells.slice(-cellsToHide);
            cells.addClass("hidden");
            if (row.hasClass("item")) {
                cells.text(""); // clear cell text
            }
        }
    });
}

// Set widths of the item links to fill cells
function setItemLinkWidths() {
    var cellWidth = $("#divTblWrapper td.cap:first").width();
    $("#divTblWrapper td.cap").each(function () {
        var cell = $(this);
        cell.children("a.lbl").outerWidth(cellWidth -
            cell.children("img.icon").outerWidth(true) -
            cell.children("span.cmd").outerWidth(true));
    });
}

// Show hint associated with the icon
function showHint(imgIcon) {
    var iconOffset = imgIcon.offset();
    var hint = imgIcon.siblings("span.hint");
    var hintTop = iconOffset.top + imgIcon.height();
    var hintHeight = hint.outerHeight();

    if (hintTop + hintHeight > $(document).height()) {
        hintTop = iconOffset.top - hintHeight;
        if (hintTop < 0) {
            hintTop = 0;
        }
    }

    hint
    .css({
        "left": iconOffset.left + imgIcon.outerWidth(true),
        "top": hintTop
    })
    .addClass("visible");
}

// Hide hint associated with the icon
function hideHint(imgIcon) {
    imgIcon.siblings("span.hint").removeClass("visible");
}

// Display the given data in the cell
function displayCellData(cell, cnlDataMap) {
    var cnlNum = cell.data("cnl");
    if (cnlNum) {
        var cnlData = cnlDataMap.get(cnlNum);
        if (cnlData) {
            cell.text(cnlData.Text);
            cell.css("color", cnlData.Color);
        } else {
            cell.text("");
            cell.css("color", "");
        }
    }
}

// Request and display current data.
// callback is function (success)
function updateCurData(callback) {
    scada.clientAPI.getCurCnlDataExtByView(viewID, function (success, cnlDataExtArr) {
        if (success) {
            var cnlDataMap = scada.clientAPI.createCnlDataExtMap(cnlDataExtArr);

            curDataCells.each(function () {
                var cell = $(this);
                displayCellData(cell, cnlDataMap);
            });

            callback(true);
        } else {
            callback(false);
        }
    });
}

// Request and display hourly data.
// callback is function (success)
function updateHourData(callback) {
    scada.clientAPI.getHourCnlDataExtByView(viewDate, timeFrom, timeTo, viewID, scada.HourDataModes.INTEGER_HOURS,
        function (success, hourCnlDataExtArr) {
            if (success) {
                var hourDataMap = scada.clientAPI.createHourCnlDataExtMap(hourCnlDataExtArr);

                for (var hour = timeFrom; hour <= timeTo; hour++) {
                    var hourData = hourDataMap.get(hour);
                    var hourCol = hourDataCols[hour - firstHour];

                    if (hourData) {
                        var cnlDataMap = scada.clientAPI.createCnlDataExtMap(hourData.CnlDataExtArr);
                        $.each(hourCol, function () {
                            var cell = $(this);
                            displayCellData(cell, cnlDataMap);
                        });
                    } else {
                        $.each(hourCol, function () {
                            var cell = $(this);
                            cell.text("");
                            cell.css("color", "");
                        });
                    }
                }

                callback(true);
            } else {
                callback(false);
            }
        });
}

// Start cyclic updating of current data
function startUpdatingCurData() {
    updateCurData(function (success) {
        if (!success) {
            notifier.addNotification(phrases.UpdateCurDataError, true, notifier.DEF_NOTIF_LIFETIME);
        }

        setTimeout(startUpdatingCurData, dataRefrRate);
    });
}

// Start cyclic updating of hourly data
function startUpdatingHourData() {
    updateHourData(function (success) {
        if (!success) {
            notifier.addNotification(phrases.UpdateHourDataError, true, notifier.DEF_NOTIF_LIFETIME);
        }

        updateHourDataTimeoutID = setTimeout(startUpdatingHourData, arcRefrRate);
    });
}

// Restart updating of hourly data immediately
function restartUpdatingHourData() {
    clearTimeout(updateHourDataTimeoutID);
    startUpdatingHourData();
}

$(document).ready(function () {
    scada.clientAPI.rootPath = "../../";
    styleIOS();
    updateLayout();
    setItemLinkWidths();
    initViewDate();
    retrieveTimePeriod();
    initCurDataCells();
    initHourDataCols();
    updateHourDataColHdrText();
    notifier = new scada.Notifier("#divNotif");
    notifier.startClearingNotifications();

    // update layout on window and table area resize
    $(window).on("resize " + scada.EventTypes.UPDATE_LAYOUT, function () {
        updateLayout();
    });

    // process the view date changing
    $(window).on(scada.EventTypes.VIEW_DATE_CHANGED, function (event, sender, extraParams) {
        setViewDate(extraParams);
        restartUpdatingHourData();
    });

    // show calendar popup on click the calendar icon
    $("#spanDate i").click(function (event) {
        var dialogs = viewHub ? viewHub.dialogs : null;
        if (dialogs) {
            var txtDate = $("#txtDate");
            dialogs.showCalendar(txtDate, txtDate.val(), function (dialogResult, extraParams) {
                if (dialogResult) {
                    setViewDate(extraParams.date);
                    sendViewDateNotification(extraParams.date);
                    restartUpdatingHourData();
                }
            });
        } else {
            console.warn("Unable to show calendar because dialogs object is undefined");
        }
    });

    // parse manually entered view date
    $("#txtDate").change(function () {
        parseViewDate($(this).val());
    });

    // process the time period changing
    $("#selTimeFrom, #selTimeTo").change(function () {
        retrieveTimePeriod();

        if ($(this).attr("id") == "selTimeFrom") {
            correctTimeTo();
        } else {
            correctTimeFrom();
        }

        saveTimePeriod();
        updateHourDataColHdrText();
        updateHourDataColVisibility();
        restartUpdatingHourData();
    });

    // show and hide hint on hover and click
    $("#divTblWrapper img.icon").hover(
        function () {
            showHint($(this));
        }, function () {
            hideHint($(this));
        }
    );

    $("#divTblWrapper span.hint").click(function () {
        $(this).css("display", "none");
    });

    if (DEBUG_MODE) {
        initDebugTools();
    } else {
        startUpdatingCurData();
        startUpdatingHourData();
    }
});
<commit_msg>PlgTable: format date and time<commit_after>// Column header time format options
var HEADER_TIME_OPTIONS = { hour: "2-digit", minute: "2-digit" };
// Column header date and time format options
var HEADER_DATETIME_OPTIONS = { month: "short", day: "2-digit", hour: "2-digit", minute: "2-digit" };

// Notifier control
var notifier = null;
// Current view date
var viewDate = null;

// Time period: firstHour <= timeFrom <= timeTo <= lastHour
// Beginning of the displayed time period
var timeFrom = null;
// End of the displayed time period
var timeTo = null;
// First possible hour of the time period
var firstHour = null;
// Last possible hour of the time period
var lastHour = null

// jQuery cells that display current data
var curDataCells = null;
// Array of columns those display hourly data, and consist of jQuery cells
var hourDataCols = [];
// Timeout ID of the hourly data updating timer
var updateHourDataTimeoutID = null;

// Set current view date to the initial value
function initViewDate() {
    if (viewHub) {
        if (viewHub.currentViewDate) {
            setViewDate(viewHub.currentViewDate);
        } else {
            viewHub.currentViewDate = today;
            setViewDate(today);
        }
    } else {
        setViewDate(today);
    }
}

// Parse manually entered view date and apply it
function parseViewDate(dateStr) {
    scada.clientAPI.parseDateTime(dateStr, function (success, value) {
        if (Number.isInteger(value)) {
            var parsedDate = new Date(value);
            setViewDate(parsedDate);
            sendViewDateNotification(parsedDate);
            restartUpdatingHourData();
        } else {
            $("#spanDate i").addClass("error");
        }
    });
}

// Set current view date
function setViewDate(date) {
    viewDate = date;
    $("#txtDate").val(date.toLocaleDateString(locale, VIEW_DATE_OPTIONS));
    $("#spanDate i").removeClass("error");
    updateHourDataColHdrText();
}

// Send view date changed notification to data windows
function sendViewDateNotification(date) {
    if (viewHub) {
        viewHub.notify(scada.EventTypes.VIEW_DATE_CHANGED, window, date);
    }
}

// Retrieve the time period from the control values
function retrieveTimePeriod() {
    timeFrom = parseInt($("#selTimeFrom").val());
    timeTo = parseInt($("#selTimeTo").val());
    firstHour = $("#divTblWrapper tr:first td.hour:first").data("hour");
    lastHour = $("#divTblWrapper tr:first td.hour:last").data("hour");
}

// Correct the beginning of the time period
function correctTimeFrom() {
    if (timeFrom > timeTo) {
        timeFrom = timeTo;
        $("#selTimeFrom").val(timeFrom);
    }
}

// Correct the end of the time period
function correctTimeTo()
{
    if (timeTo < timeFrom) {
        timeTo = timeFrom;
        $("#selTimeTo").val(timeFrom);
    }
}

// Save the time period in the cookies
function saveTimePeriod() {
    scada.utils.setCookie("Table.TimeFrom", $("#selTimeFrom").val());
    scada.utils.setCookie("Table.TimeTo", $("#selTimeTo").val());
}

// Select and prepare the current data cells
function initCurDataCells() {
    // select cells
    curDataCells = $("#divTblWrapper td.cur");

    // copy data-cnl attributes from rows to the cells
    curDataCells.each(function () {
        $(this).data("cnl", $(this).closest("tr.item").data("cnl"));
    });
}

// Select and prepare the hourly data columns
function initHourDataCols() {
    // init columns
    hourDataCols.length = lastHour - firstHour + 1;
    for (var i = 0, len = hourDataCols.length; i < len; i++) {
        hourDataCols[i] = [];
    }

    // get and arrange cells
    $("#divTblWrapper tr.item").each(function () {
        var row = $(this);
        var cnlNum = row.data("cnl");
        row.find("td.hour").each(function () {
            var cell = $(this);
            cell.data("cnl", cnlNum);
            var hour = cell.data("hour");
            hourDataCols[hour - firstHour].push(cell);
        });
    });
}

// Update header text of the hourly data columns
function updateHourDataColHdrText() {
    $("#divTblWrapper tr.hdr td.hour").each(function () {
        var cell = $(this);
        var hour = cell.data("hour");
        var colDT = new Date(viewDate.getTime());
        colDT.setHours(hour);

        if (timeFrom >= 0) {
            // display time only
            cell.text(colDT.toLocaleTimeString(locale, HEADER_TIME_OPTIONS));
        } else {
            // display date and time
            cell.text(colDT.toLocaleString(locale, HEADER_DATETIME_OPTIONS));
        }
    });
}

// Update visibility of the table view columns according to the time period
function updateHourDataColVisibility() {
    $("#divTblWrapper tr").each(function () {
        var row = $(this);
        var hourCells = row.find("td.hour");

        // show all the cells of the row
        hourCells.removeClass("hidden");

        // hide cells from the left
        var cellsToHide = timeFrom - firstHour;
        if (cellsToHide > 0) {
            var cells = hourCells.slice(0, cellsToHide);
            cells.addClass("hidden");
            if (row.hasClass("item")) {
                cells.text(""); // clear cell text
            }
        }

        // hide cells from the right
        cellsToHide = lastHour - timeTo;
        if (cellsToHide > 0) {
            cells = hourCells.slice(-cellsToHide);
            cells.addClass("hidden");
            if (row.hasClass("item")) {
                cells.text(""); // clear cell text
            }
        }
    });
}

// Set widths of the item links to fill cells
function setItemLinkWidths() {
    var cellWidth = $("#divTblWrapper td.cap:first").width();
    $("#divTblWrapper td.cap").each(function () {
        var cell = $(this);
        cell.children("a.lbl").outerWidth(cellWidth -
            cell.children("img.icon").outerWidth(true) -
            cell.children("span.cmd").outerWidth(true));
    });
}

// Show hint associated with the icon
function showHint(imgIcon) {
    var iconOffset = imgIcon.offset();
    var hint = imgIcon.siblings("span.hint");
    var hintTop = iconOffset.top + imgIcon.height();
    var hintHeight = hint.outerHeight();

    if (hintTop + hintHeight > $(document).height()) {
        hintTop = iconOffset.top - hintHeight;
        if (hintTop < 0) {
            hintTop = 0;
        }
    }

    hint
    .css({
        "left": iconOffset.left + imgIcon.outerWidth(true),
        "top": hintTop
    })
    .addClass("visible");
}

// Hide hint associated with the icon
function hideHint(imgIcon) {
    imgIcon.siblings("span.hint").removeClass("visible");
}

// Display the given data in the cell
function displayCellData(cell, cnlDataMap) {
    var cnlNum = cell.data("cnl");
    if (cnlNum) {
        var cnlData = cnlDataMap.get(cnlNum);
        if (cnlData) {
            cell.text(cnlData.Text);
            cell.css("color", cnlData.Color);
        } else {
            cell.text("");
            cell.css("color", "");
        }
    }
}

// Request and display current data.
// callback is function (success)
function updateCurData(callback) {
    scada.clientAPI.getCurCnlDataExtByView(viewID, function (success, cnlDataExtArr) {
        if (success) {
            var cnlDataMap = scada.clientAPI.createCnlDataExtMap(cnlDataExtArr);

            curDataCells.each(function () {
                var cell = $(this);
                displayCellData(cell, cnlDataMap);
            });

            callback(true);
        } else {
            callback(false);
        }
    });
}

// Request and display hourly data.
// callback is function (success)
function updateHourData(callback) {
    scada.clientAPI.getHourCnlDataExtByView(viewDate, timeFrom, timeTo, viewID, scada.HourDataModes.INTEGER_HOURS,
        function (success, hourCnlDataExtArr) {
            if (success) {
                var hourDataMap = scada.clientAPI.createHourCnlDataExtMap(hourCnlDataExtArr);

                for (var hour = timeFrom; hour <= timeTo; hour++) {
                    var hourData = hourDataMap.get(hour);
                    var hourCol = hourDataCols[hour - firstHour];

                    if (hourData) {
                        var cnlDataMap = scada.clientAPI.createCnlDataExtMap(hourData.CnlDataExtArr);
                        $.each(hourCol, function () {
                            var cell = $(this);
                            displayCellData(cell, cnlDataMap);
                        });
                    } else {
                        $.each(hourCol, function () {
                            var cell = $(this);
                            cell.text("");
                            cell.css("color", "");
                        });
                    }
                }

                callback(true);
            } else {
                callback(false);
            }
        });
}

// Start cyclic updating of current data
function startUpdatingCurData() {
    updateCurData(function (success) {
        if (!success) {
            notifier.addNotification(phrases.UpdateCurDataError, true, notifier.DEF_NOTIF_LIFETIME);
        }

        setTimeout(startUpdatingCurData, dataRefrRate);
    });
}

// Start cyclic updating of hourly data
function startUpdatingHourData() {
    updateHourData(function (success) {
        if (!success) {
            notifier.addNotification(phrases.UpdateHourDataError, true, notifier.DEF_NOTIF_LIFETIME);
        }

        updateHourDataTimeoutID = setTimeout(startUpdatingHourData, arcRefrRate);
    });
}

// Restart updating of hourly data immediately
function restartUpdatingHourData() {
    clearTimeout(updateHourDataTimeoutID);
    startUpdatingHourData();
}

$(document).ready(function () {
    scada.clientAPI.rootPath = "../../";
    styleIOS();
    updateLayout();
    setItemLinkWidths();
    initViewDate();
    retrieveTimePeriod();
    initCurDataCells();
    initHourDataCols();
    updateHourDataColHdrText();
    notifier = new scada.Notifier("#divNotif");
    notifier.startClearingNotifications();

    // update layout on window and table area resize
    $(window).on("resize " + scada.EventTypes.UPDATE_LAYOUT, function () {
        updateLayout();
    });

    // process the view date changing
    $(window).on(scada.EventTypes.VIEW_DATE_CHANGED, function (event, sender, extraParams) {
        setViewDate(extraParams);
        restartUpdatingHourData();
    });

    // show calendar popup on click the calendar icon
    $("#spanDate i").click(function (event) {
        var dialogs = viewHub ? viewHub.dialogs : null;
        if (dialogs) {
            var txtDate = $("#txtDate");
            dialogs.showCalendar(txtDate, txtDate.val(), function (dialogResult, extraParams) {
                if (dialogResult) {
                    setViewDate(extraParams.date);
                    sendViewDateNotification(extraParams.date);
                    restartUpdatingHourData();
                }
            });
        } else {
            console.warn("Unable to show calendar because dialogs object is undefined");
        }
    });

    // parse manually entered view date
    $("#txtDate").change(function () {
        parseViewDate($(this).val());
    });

    // process the time period changing
    $("#selTimeFrom, #selTimeTo").change(function () {
        retrieveTimePeriod();

        if ($(this).attr("id") == "selTimeFrom") {
            correctTimeTo();
        } else {
            correctTimeFrom();
        }

        saveTimePeriod();
        updateHourDataColHdrText();
        updateHourDataColVisibility();
        restartUpdatingHourData();
    });

    // show and hide hint on hover and click
    $("#divTblWrapper img.icon").hover(
        function () {
            showHint($(this));
        }, function () {
            hideHint($(this));
        }
    );

    $("#divTblWrapper span.hint").click(function () {
        $(this).css("display", "none");
    });

    if (DEBUG_MODE) {
        initDebugTools();
    } else {
        startUpdatingCurData();
        startUpdatingHourData();
    }
});
<|endoftext|>


<commit_before>define([

  'Backbone',

  //Model
  'app/models/project',

  //Collection
  'app/collections/projects',

  //View
  'app/views/taskController',
  'app/views/projectsController',
  'app/views/filterController',

  //Templates
  'text!templates/project-page/gamePageTemplate.html',
  'text!templates/project-page/errorTemplate.html'

], function(

  Backbone,

  //Model
  Project,

  //Collection
  Projects,

  //Views
  taskController,
  projectsController,
  filterController,

  //Templates
  gamePageTemplate,
  errorTemplate
){

  var ProjectManager = Backbone.View.extend({

    template: _.template(gamePageTemplate),
    errorTemplate: _.template(errorTemplate),

    model: new Project(),

    initialize: function(){
      this.model.clear({silent: true}).off();
      this.model.bind('change:error', this.error, this);
      this.model.bind('change:name', this.render, this);

      this.model.fetch({data: {id: this.options.projectId}});

      this.projectsList = new projectsController({
        collection: new Projects(),
        router: this.options.router
      });

      this.taskList = new taskController({
        projectId: this.options.projectId
      });

      this.filter = new filterController({
        collection: this.taskList.collection
      });
    },

    error: function(){
      var message = this.model.get('error');
      this.$el.html(this.errorTemplate({message: message}));
    },

    render: function(){
      this.$el.html(this.template({project: {name: this.model.get('name')}}));
      this.taskList.setElement('.js-taskList');
      this.filter.setElement('.fn-filter-task');

      this.taskList.collection.fetch();

      if(!$('.projects-list li')[0]){
        this.projectsList.setElement('.projects-list').start();
      }

    }
  });

  return ProjectManager;

});
<commit_msg>Emit switch project<commit_after>define([

  'Backbone',

  //Model
  'app/models/project',

  //Collection
  'app/collections/projects',

  //View
  'app/views/taskController',
  'app/views/projectsController',
  'app/views/filterController',

  //Templates
  'text!templates/project-page/gamePageTemplate.html',
  'text!templates/project-page/errorTemplate.html'

], function(

  Backbone,

  //Model
  Project,

  //Collection
  Projects,

  //Views
  taskController,
  projectsController,
  filterController,

  //Templates
  gamePageTemplate,
  errorTemplate
){

  var ProjectManager = Backbone.View.extend({

    template: _.template(gamePageTemplate),
    errorTemplate: _.template(errorTemplate),

    model: new Project(),

    initialize: function(){
      this.model.clear({silent: true}).off();
      this.model.bind('change:error', this.error, this);
      this.model.bind('change:name', this.render, this);

      this.model.fetch({data: {id: this.options.projectId}});

      this.projectsList = new projectsController({
        collection: new Projects(),
        router: this.options.router
      });

      this.taskList = new taskController({
        projectId: this.options.projectId
      });

      this.filter = new filterController({
        collection: this.taskList.collection
      });

    },

    error: function(){
      var message = this.model.get('error');
      this.$el.html(this.errorTemplate({message: message}));
    },

    render: function(){
      var project = this.model.get('name');
      var player  = this.options.router.account.get('user');

      socket.emit('add player', player, project);

      this.$el.html(this.template({project: {name: project}}));
      this.taskList.setElement('.js-taskList');
      this.filter.setElement('.fn-filter-task');

      this.taskList.collection.fetch();

      if(!$('.projects-list li')[0]){
        this.projectsList.setElement('.projects-list').start();
      }

    }
  });

  return ProjectManager;

});
<|endoftext|>


<commit_before>import Feature from 'ol/Feature';
import {fromExtent as polygonFromExtent} from 'ol/geom/Polygon';

export default [
  '$rootScope',
  'hs.compositions.service_parser',
  'config',
  '$q',
  '$http',
  'hs.map.service',
  'hs.utils.service',
  function ($rootScope, compositionParser, config, $q, $http, hsMap, utils) {
    const me = this;
    angular.extend(me, {
      getCompositionsQueryUrl(endpoint, params, bbox) {
        const query = params.query;
        const bboxDelimiter =
          endpoint.url.indexOf('cswClientRun.php') > 0 ? ',' : ' ';
        const serviceName = angular.isDefined(endpoint.serviceName)
          ? 'serviceName=&' + endpoint.serviceName
          : '';
        bbox = params.filterExtent
          ? encodeURIComponent(" and BBOX='" + bbox.join(bboxDelimiter) + "'")
          : '';
        const textFilter =
          query && angular.isDefined(query.title) && query.title != ''
            ? encodeURIComponent(
                " AND title like '*" +
                  query.title +
                  "*' OR abstract like '*" +
                  query.title +
                  "*'"
              )
            : '';
        const selected = [];
        let keywordFilter = '';
        let tmp = endpoint.url;
        angular.forEach(params.keywords, (value, key) => {
          if (value) {
            selected.push("subject='" + key + "'");
          }
        });
        if (selected.length > 0) {
          keywordFilter = encodeURIComponent(
            ' AND (' + selected.join(' OR ') + ')'
          );
        }

        tmp +=
          '?format=json&' +
          serviceName +
          'query=type%3Dapplication' +
          bbox +
          textFilter +
          keywordFilter +
          '&lang=eng&sortBy=' +
          params.sortBy +
          '&detail=summary&start=' +
          params.start +
          '&limit=' +
          params.limit;
        tmp = utils.proxify(tmp);
        return tmp;
      },

      loadList(endpoint, params, bbox, extentLayer) {
        endpoint.compositionsPaging.loaded = false;
        if (angular.isUndefined(params.sortBy)) {
          params.sortBy = 'bbox';
        }
        if (angular.isUndefined(params.start)) {
          params.start = endpoint.compositionsPaging.start;
        }
        if (angular.isUndefined(params.limit) || isNaN(params.limit)) {
          params.limit = endpoint.compositionsPaging.limit;
        }
        return new Promise((resolve, reject) => {
          if (angular.isDefined(me.canceler)) {
            me.canceler.resolve();
            delete me.canceler;
          }
          me.canceler = $q.defer();
          $http
            .get(me.getCompositionsQueryUrl(endpoint, params, bbox), {
              timeout: me.canceler.promise,
            })
            .then(
              (response) => {
                endpoint.compositionsPaging.loaded = true;
                response = response.data;
                endpoint.compositions = response.records;
                if (response.records && response.records.length > 0) {
                  endpoint.compositionsPaging.compositionsCount =
                    response.matched;
                } else {
                  endpoint.compositionsPaging.compositionsCount = 0;
                }
                //TODO: Needs refactoring
                endpoint.compositionsPaging.next = response.next;
                const mapExtent = hsMap.getMapExtent();
                angular.forEach(endpoint.compositions, (record) => {
                  const attributes = {
                    record: record,
                    hs_notqueryable: true,
                    highlighted: false,
                    title: record.title || record.name,
                  };
                  record.editable = false;
                  record.endpoint = endpoint;
                  if (angular.isUndefined(record.thumbnail)) {
                    record.thumbnail =
                      endpoint.url + '?request=loadthumb&id=' + record.id;
                  }
                  const extent = compositionParser.parseExtent(record.bbox);
                  //Check if height or Width covers the whole screen
                  if (
                    !(
                      (extent[0] < mapExtent[0] && extent[2] > mapExtent[2]) ||
                      (extent[1] < mapExtent[1] && extent[3] > mapExtent[3])
                    )
                  ) {
                    attributes.geometry = polygonFromExtent(extent);
                    attributes.is_hs_composition_extent = true;
                    const newFeature = new Feature(attributes);
                    record.feature = newFeature;
                    extentLayer.getSource().addFeatures([newFeature]);
                  } else {
                    //Composition not in extent
                  }
                });
                $rootScope.$broadcast('CompositionsLoaded');
                resolve();
              },
              (err) => {}
            );
        });
      },

      resetCompositionCounter(endpoint) {
        endpoint.compositionsPaging.start = 0;
        endpoint.compositionsPaging.next = endpoint.compositionsPaging.limit;
      },
    });
    return me;
  },
];
<commit_msg>Dont sort micka record by bbox and add 1 flag to bbox filter<commit_after>import Feature from 'ol/Feature';
import {fromExtent as polygonFromExtent} from 'ol/geom/Polygon';

export default [
  '$rootScope',
  'hs.compositions.service_parser',
  'config',
  '$q',
  '$http',
  'hs.map.service',
  'hs.utils.service',
  function ($rootScope, compositionParser, config, $q, $http, hsMap, utils) {
    const me = this;
    angular.extend(me, {
      getCompositionsQueryUrl(endpoint, params, bbox) {
        const query = params.query;
        const bboxDelimiter =
          endpoint.url.indexOf('cswClientRun.php') > 0 ? ',' : ' ';
        const serviceName = angular.isDefined(endpoint.serviceName)
          ? 'serviceName=&' + endpoint.serviceName
          : '';
        bbox = params.filterExtent
          ? encodeURIComponent(" and BBOX='" + bbox.join(bboxDelimiter) + " 1'")
          : '';
        const textFilter =
          query && angular.isDefined(query.title) && query.title != ''
            ? encodeURIComponent(
                " AND title like '*" +
                  query.title +
                  "*' OR abstract like '*" +
                  query.title +
                  "*'"
              )
            : '';
        const selected = [];
        let keywordFilter = '';
        let tmp = endpoint.url;
        angular.forEach(params.keywords, (value, key) => {
          if (value) {
            selected.push("subject='" + key + "'");
          }
        });
        if (selected.length > 0) {
          keywordFilter = encodeURIComponent(
            ' AND (' + selected.join(' OR ') + ')'
          );
        }

        tmp +=
          '?format=json&' +
          serviceName +
          'query=type%3Dapplication' +
          bbox +
          textFilter +
          keywordFilter +
          '&lang=eng&sortBy=' +
          params.sortBy +
          '&detail=summary&start=' +
          params.start +
          '&limit=' +
          params.limit;
        tmp = utils.proxify(tmp);
        return tmp;
      },

      loadList(endpoint, params, bbox, extentLayer) {
        endpoint.compositionsPaging.loaded = false;
        if (angular.isUndefined(params.sortBy)) {
          params.sortBy = 'title';
        }
        if (angular.isUndefined(params.start)) {
          params.start = endpoint.compositionsPaging.start;
        }
        if (angular.isUndefined(params.limit) || isNaN(params.limit)) {
          params.limit = endpoint.compositionsPaging.limit;
        }
        return new Promise((resolve, reject) => {
          if (angular.isDefined(me.canceler)) {
            me.canceler.resolve();
            delete me.canceler;
          }
          me.canceler = $q.defer();
          $http
            .get(me.getCompositionsQueryUrl(endpoint, params, bbox), {
              timeout: me.canceler.promise,
            })
            .then(
              (response) => {
                endpoint.compositionsPaging.loaded = true;
                response = response.data;
                endpoint.compositions = response.records;
                if (response.records && response.records.length > 0) {
                  endpoint.compositionsPaging.compositionsCount =
                    response.matched;
                } else {
                  endpoint.compositionsPaging.compositionsCount = 0;
                }
                //TODO: Needs refactoring
                endpoint.compositionsPaging.next = response.next;
                const mapExtent = hsMap.getMapExtent();
                angular.forEach(endpoint.compositions, (record) => {
                  const attributes = {
                    record: record,
                    hs_notqueryable: true,
                    highlighted: false,
                    title: record.title || record.name,
                  };
                  record.editable = false;
                  record.endpoint = endpoint;
                  if (angular.isUndefined(record.thumbnail)) {
                    record.thumbnail =
                      endpoint.url + '?request=loadthumb&id=' + record.id;
                  }
                  const extent = compositionParser.parseExtent(record.bbox);
                  //Check if height or Width covers the whole screen
                  if (
                    !(
                      (extent[0] < mapExtent[0] && extent[2] > mapExtent[2]) ||
                      (extent[1] < mapExtent[1] && extent[3] > mapExtent[3])
                    )
                  ) {
                    attributes.geometry = polygonFromExtent(extent);
                    attributes.is_hs_composition_extent = true;
                    const newFeature = new Feature(attributes);
                    record.feature = newFeature;
                    extentLayer.getSource().addFeatures([newFeature]);
                  } else {
                    //Composition not in extent
                  }
                });
                $rootScope.$broadcast('CompositionsLoaded');
                resolve();
              },
              (err) => {}
            );
        });
      },

      resetCompositionCounter(endpoint) {
        endpoint.compositionsPaging.start = 0;
        endpoint.compositionsPaging.next = endpoint.compositionsPaging.limit;
      },
    });
    return me;
  },
];
<|endoftext|>


<commit_before>var nbjscolor = {};

nbjscolor.nbjsColors = [
  '#ff5a5f', // rausch
  '#7b0051', // hackb
  '#007A87', // kazan
  '#00d1c1', // babu
  '#8ce071', // lima
  '#ffb400', // beach
  // '#b4a76c', // barol
  '#6A5ACD',
  '#ff8083',
  '#cc0086',
  '#00a1b3',
  '#00ffeb',
  '#bbedab',
  '#ffd266',
  // '#cbc29a',
  '#8B2323',
  '#ff3339',
  '#ff1ab1',
  '#005c66',
  '#00b3a5',
  '#55d12e',
  '#b22222',
  '#009ACD'
  // '#b37e00',
  // '#988b4e',
];

nbjscolor.categoryGenerator1 = function () {
  // Color factory
  randomSeed = Math.floor(Math.random() * 21);
  const seen = {};
  return function (s) {
    if (!s) {
      return;
    }
    let stringifyS = String(s);
    // next line is for superset series that should have the same color
    stringifyS = stringifyS.replace('---', '');
    if (seen[stringifyS] === undefined) {
      seen[stringifyS] = randomSeed + Object.keys(seen).length;
    }
    /* eslint consistent-return: 0 */
    return nbjscolor.nbjsColors[seen[stringifyS] % nbjscolor.nbjsColors.length];
  };
};
<commit_msg>Adjust color generator<commit_after>var nbjscolor = {};

nbjscolor.nbjsColors = [
  '#ff5a5f', // rausch
  '#7b0051', // hackb
  '#007A87', // kazan
  '#00d1c1', // babu
  '#8ce071', // lima
  '#ffb400', // beach
  // '#b4a76c', // barol
  '#6A5ACD',
  '#ff8083',
  '#cc0086',
  '#00a1b3',
  '#00ffeb',
  // '#bbedab',
  '#ffd266',
  // '#cbc29a',
  '#8B2323',
  '#ff3339',
  '#ff1ab1',
  '#005c66',
  '#00b3a5',
  '#55d12e',
  '#b22222',
  '#009ACD',
  '#445D6E',
  '#CC3399',
  // '#b37e00',
  // '#988b4e',
];

nbjscolor.categoryGenerator1 = function () {
  // Color factory
  randomSeed = Math.floor(Math.random() * 21);
  const seen = {};
  return function (s) {
    if (!s) {
      return;
    }
    let stringifyS = String(s);
    // next line is for superset series that should have the same color
    stringifyS = stringifyS.replace('---', '');
    if (seen[stringifyS] === undefined) {
      seen[stringifyS] = randomSeed + Object.keys(seen).length;
    }
    /* eslint consistent-return: 0 */
    return nbjscolor.nbjsColors[seen[stringifyS] % nbjscolor.nbjsColors.length];
  };
};
<|endoftext|>


<commit_before>// Player: A player in this game. Every AI controls one player.

const Class = require("classe");
const log = require(`${__basedir}/gameplay/log`);
const GameObject = require("./gameObject");

//<<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.

// any additional requires you want can be required here safely between Creer re-runs

//<<-- /Creer-Merge: requires -->>

// @class Player: A player in this game. Every AI controls one player.
let Player = Class(GameObject, {
    /**
     * Initializes Players.
     *
     * @param {Object} data - a simple mapping passed in to the constructor with whatever you sent with it. GameSettings are in here by key/value as well.
     */
    init: function(data) {
        GameObject.init.apply(this, arguments);

        /**
         * The overlord cat Unit owned by this Player.
         *
         * @type {Unit}
         */
        this.cat = this.cat || null;

        /**
         * What type of client this is, e.g. 'Python', 'JavaScript', or some other language. For potential data mining purposes.
         *
         * @type {string}
         */
        this.clientType = this.clientType || "";

        /**
         * The amount of food owned by this player.
         *
         * @type {number}
         */
        this.food = this.food || 0;

        /**
         * If the player lost the game or not.
         *
         * @type {boolean}
         */
        this.lost = this.lost || false;

        /**
         * The name of the player.
         *
         * @type {string}
         */
        this.name = this.name || "";

        /**
         * This player's opponent in the game.
         *
         * @type {Player}
         */
        this.opponent = this.opponent || null;

        /**
         * The reason why the player lost the game.
         *
         * @type {string}
         */
        this.reasonLost = this.reasonLost || "";

        /**
         * The reason why the player won the game.
         *
         * @type {string}
         */
        this.reasonWon = this.reasonWon || "";

        /**
         * Every Structure owned by this Player.
         *
         * @type {Array.<Structure>}
         */
        this.structures = this.structures || [];

        /**
         * The amount of time (in ns) remaining for this AI to send commands.
         *
         * @type {number}
         */
        this.timeRemaining = this.timeRemaining || 0;

        /**
         * Every Unit owned by this Player.
         *
         * @type {Array.<Unit>}
         */
        this.units = this.units || [];

        /**
         * The total upkeep of every Unit owned by this Player. If there isn't enough food for every Unit, all Units become starved and do not consume food.
         *
         * @type {number}
         */
        this.upkeep = this.upkeep || 0;

        /**
         * If the player won the game or not.
         *
         * @type {boolean}
         */
        this.won = this.won || false;

        //<<-- Creer-Merge: init -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.

        // put any initialization logic here. the base variables should be set from 'data' above
        this.cat = data.cat || null;
        this.clientType = data.clientType || null;
        this.food = data.food || null;
        this.name = data.name || null;
        this.opponent = data.opponent || null;
        this.timeRemaining = data.timeRemaining || -1;

        //<<-- /Creer-Merge: init -->>
    },

    gameObjectName: "Player",

    //<<-- Creer-Merge: added-functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.

    // You can add additional functions here. These functions will not be directly callable by client AIs

    //<<-- /Creer-Merge: added-functions -->>

});

module.exports = Player;
<commit_msg>Removed some extra code, ran linter<commit_after>// Player: A player in this game. Every AI controls one player.

const Class = require("classe");
const log = require(`${__basedir}/gameplay/log`);
const GameObject = require("./gameObject");

//<<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.

// any additional requires you want can be required here safely between Creer re-runs

//<<-- /Creer-Merge: requires -->>

// @class Player: A player in this game. Every AI controls one player.
let Player = Class(GameObject, {
    /**
     * Initializes Players.
     *
     * @param {Object} data - a simple mapping passed in to the constructor with whatever you sent with it. GameSettings are in here by key/value as well.
     */
    init: function(data) {
        GameObject.init.apply(this, arguments);

        /**
         * The overlord cat Unit owned by this Player.
         *
         * @type {Unit}
         */
        this.cat = this.cat || null;

        /**
         * What type of client this is, e.g. 'Python', 'JavaScript', or some other language. For potential data mining purposes.
         *
         * @type {string}
         */
        this.clientType = this.clientType || "";

        /**
         * The amount of food owned by this player.
         *
         * @type {number}
         */
        this.food = this.food || 0;

        /**
         * If the player lost the game or not.
         *
         * @type {boolean}
         */
        this.lost = this.lost || false;

        /**
         * The name of the player.
         *
         * @type {string}
         */
        this.name = this.name || "";

        /**
         * This player's opponent in the game.
         *
         * @type {Player}
         */
        this.opponent = this.opponent || null;

        /**
         * The reason why the player lost the game.
         *
         * @type {string}
         */
        this.reasonLost = this.reasonLost || "";

        /**
         * The reason why the player won the game.
         *
         * @type {string}
         */
        this.reasonWon = this.reasonWon || "";

        /**
         * Every Structure owned by this Player.
         *
         * @type {Array.<Structure>}
         */
        this.structures = this.structures || [];

        /**
         * The amount of time (in ns) remaining for this AI to send commands.
         *
         * @type {number}
         */
        this.timeRemaining = this.timeRemaining || 0;

        /**
         * Every Unit owned by this Player.
         *
         * @type {Array.<Unit>}
         */
        this.units = this.units || [];

        /**
         * The total upkeep of every Unit owned by this Player. If there isn't enough food for every Unit, all Units become starved and do not consume food.
         *
         * @type {number}
         */
        this.upkeep = this.upkeep || 0;

        /**
         * If the player won the game or not.
         *
         * @type {boolean}
         */
        this.won = this.won || false;

        //<<-- Creer-Merge: init -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
        this.cat = data.cat || null;
        this.food = data.food || null;
        //<<-- /Creer-Merge: init -->>
    },

    gameObjectName: "Player",

    //<<-- Creer-Merge: added-functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.

    // You can add additional functions here. These functions will not be directly callable by client AIs

    //<<-- /Creer-Merge: added-functions -->>

});

module.exports = Player;
<|endoftext|>


<commit_before>// @license Copyright (C) 2015 Neovici AB - Apache 2 License
(function () {
	'use strict';
	Polymer({
		/**
		 * Fired when `hidden`, `disabled`,'heading' or `badge` tab properties change.
		 *
		 * @event tab-property-changed
		 * @param {String} detail.property The property name
		 * @param {String|Number|Object|*} detail.value The property value
		 * @param {HTMLElement} detail.item The item that changed.
		 */

		is: 'cosmoz-tab',
		properties: {
			/**
			 * If true, the item will be hidden.
			 */
			hidden: {
				type: Boolean,
				value: false,
				notify: true,
				reflectToAttribute: true,
			},

			/**
			 *  If true, the item will be disabled.
			 */
			disabled: {
				type: Boolean,
				value: false,
				notify: true,
				reflectToAttribute: true,
			},

			/**
			 * Only items that match this CSS selector are selectable.
			 */
			selectable: {
				type: String,
				value: 'cosmoz-tab-card'
			},

			/**
			 * True if the item contains cards.
			 */
			hasCards: {
				type: Boolean,
				reflectToAttribute: true,
				readOnly: true,
				notify: true,
				value: false,
				computed: '_computeHasCards(items)'
			}
		},

		behaviors: [
			Cosmoz.TabbedBehavior,
			Cosmoz.TabbableBehavior
		],

		observers: [
			'_notifyProperty("hidden", hidden)',
			'_notifyProperty("disabled", disabled)',
			'_notifyProperty("heading", heading)',
			'_notifyProperty("badge", badge)'
		],

		/**
		 * Computes `hasCards` depending on `items`.
		 *
		 * @param  {Array} items Array of selectable items
		 * @returns {Boolean} True if items is not empty
		 */
		_computeHasCards: function (items = this.items) {
			return items && items.length > 0;
		},

		/**
		 * Computes opened property of the included `iron-collapse`.
		 *
		 * @param  {Boolean} accordion   The accordion property
		 * @param  {Boolean} hasCards   The hasCards property
		 * @param  {Boolean} isSelected The isSelected property
		 * @returns {Boolean} True if `hasCards` or `isSelected`
		 */
		_computeOpened: function (accordion, hasCards = this.hasCards, isSelected = this.isSelected) {
			return !accordion || hasCards || isSelected;
		},

		/**
		 * Observes changes to a property and fires a bubbling
		 * `tab-property-changed` event.
		 *
		 * @fires tab-property-changed
		 * @param {String} property The name of the changed property
		 * @param {String|Number|Object|*} value The value of the changed property.
		 * @return {void}

		 */
		_notifyProperty: function (property, value) {
			this.fire('tab-property-changed', {
				property: property,
				value: value,
				item: this
			});
		},

		resizerShouldBeNotified(resizable) {
			return resizable.parentNode !== this.$.header;
		}

	});
}());
<commit_msg>Quick hack to fix a display issue when cosmoz-tab is used in cosmoz-data-nav and the content of the tab is scrolled.<commit_after>// @license Copyright (C) 2015 Neovici AB - Apache 2 License
(function () {
	'use strict';
	Polymer({
		/**
		 * Fired when `hidden`, `disabled`,'heading' or `badge` tab properties change.
		 *
		 * @event tab-property-changed
		 * @param {String} detail.property The property name
		 * @param {String|Number|Object|*} detail.value The property value
		 * @param {HTMLElement} detail.item The item that changed.
		 */

		is: 'cosmoz-tab',
		properties: {
			/**
			 * If true, the item will be hidden.
			 */
			hidden: {
				type: Boolean,
				value: false,
				notify: true,
				reflectToAttribute: true,
			},

			/**
			 *  If true, the item will be disabled.
			 */
			disabled: {
				type: Boolean,
				value: false,
				notify: true,
				reflectToAttribute: true,
			},

			/**
			 * Only items that match this CSS selector are selectable.
			 */
			selectable: {
				type: String,
				value: 'cosmoz-tab-card'
			},

			/**
			 * True if the item contains cards.
			 */
			hasCards: {
				type: Boolean,
				reflectToAttribute: true,
				readOnly: true,
				notify: true,
				value: false,
				computed: '_computeHasCards(items)'
			}
		},

		behaviors: [
			Cosmoz.TabbedBehavior,
			Cosmoz.TabbableBehavior
		],

		observers: [
			'_notifyProperty("hidden", hidden)',
			'_notifyProperty("disabled", disabled)',
			'_notifyProperty("heading", heading)',
			'_notifyProperty("badge", badge)'
		],

		listeners: {
			'iron-resize': '_onResize'
		},

		_onResize: function () {
			// HACK(pasleq): Can't explain why, but under Chrome 62, we've experienced disappearing content
			// the tab content is scolled. This hack seems to fix this issue.
			var scrollTop = this.$.content.scrollTop;
			this.$.content.scrollTop = 0;
			this.$.content.scrollTop = scrollTop;
		},

		/**
		 * Computes `hasCards` depending on `items`.
		 *
		 * @param  {Array} items Array of selectable items
		 * @returns {Boolean} True if items is not empty
		 */
		_computeHasCards: function (items = this.items) {
			return items && items.length > 0;
		},

		/**
		 * Computes opened property of the included `iron-collapse`.
		 *
		 * @param  {Boolean} accordion   The accordion property
		 * @param  {Boolean} hasCards   The hasCards property
		 * @param  {Boolean} isSelected The isSelected property
		 * @returns {Boolean} True if `hasCards` or `isSelected`
		 */
		_computeOpened: function (accordion, hasCards = this.hasCards, isSelected = this.isSelected) {
			return !accordion || hasCards || isSelected;
		},

		/**
		 * Observes changes to a property and fires a bubbling
		 * `tab-property-changed` event.
		 *
		 * @fires tab-property-changed
		 * @param {String} property The name of the changed property
		 * @param {String|Number|Object|*} value The value of the changed property.
		 * @return {void}

		 */
		_notifyProperty: function (property, value) {
			this.fire('tab-property-changed', {
				property: property,
				value: value,
				item: this
			});
		},

		resizerShouldBeNotified(resizable) {
			return resizable.parentNode !== this.$.header;
		}

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


<commit_before>angular.module('WatchTimer')
  .directive('resizeTextToFill', function ($document, $timeout) {
    return {
      link: function (scope, element, attrs, controller, transcludeFn) {

        var font_size_increment = 20;
        var max_height = $document.height() - font_size_increment;
        var max_width  = $document.width()  - font_size_increment;

        var set_size = function (fontSize) {
          element.css({
            fontSize: fontSize + "px",
            lineHeight: fontSize + "px" // digits don't need more than this
          });
        };

        $timeout(function () {
          var fontSize = 10;
          var safety_counter = 0;
          var safety_counter_max = 100;

          while (element.height() <= max_height && element.width() <= max_width && safety_counter < safety_counter_max ) {
            safety_counter++;
            fontSize += font_size_increment;
            set_size(fontSize);
          }

          // go back down one size so we know it fits
          fontSize -= font_size_increment;
          set_size(fontSize);

          console.log({safety_counter: safety_counter, fontSize: fontSize});
        });

      }
    };
  })<commit_msg>Respond to srceen change events<commit_after>angular.module('WatchTimer')
  .directive('resizeTextToFill', function ($document, $timeout) {
    return {
      link: function (scope, element, attrs, controller, transcludeFn) {

        var initial_font_size = 10;
        var font_size_increment = 20;

        var safety_counter_max = 100;

        function set_size (font_size) {
          element.css({
            fontSize:   font_size + "px",
            lineHeight: font_size + "px" // digits don't need more than this
          });
        }

        function resize_to_fit () {
          var font_size = initial_font_size;
          var max_height = $document.height() - font_size_increment;
          var max_width  = $document.width()  - font_size_increment;
          var safety_counter = 0;

          set_size(font_size);

          while (
            element.height() <= max_height
            && element.width() <= max_width
            && safety_counter < safety_counter_max
          ) {
            safety_counter++;
            font_size += font_size_increment;
            set_size(font_size);
          }

          // go back down one size so we know it fits
          font_size -= font_size_increment;
          set_size(font_size);
        }

        $timeout(function () {
          resize_to_fit();
        });

        // 'resize' as the chrome dev toolkit does not trigger an
        // 'orientationchange' event when switching between oriantations.
        $(window).on("resize", resize_to_fit);

      }
    };
  })<|endoftext|>


<commit_before>
var env = require('env');
var config;

try {
  config = require('config');
}
catch (e) {
  config = require('config.sample');
}

var win = Ti.UI.createWindow({});

var list = Ti.UI.createScrollView({
  width: Ti.UI.SIZE,
  height: Ti.UI.SIZE,
  layout: 'vertical'
});

var bar = Ti.UI.createProgressBar({
  top: 0,
  right: 0,
  left: 0,
  min: 0,
  max: 1,
  value: 0
});

bar.hide();

win.add(list);
win.add(bar);

var ACTIONS = [
  {
    title: 'Errors Test',
    handle: require('tests/errors')
  },
  {
    title: 'Callback Test',
    handle: require('tests/once')
  },
  {
    title: 'Timeout Test',
    handle: require('tests/timeout')
  },
  {
    title: 'Failure Test',
    handle: require('tests/failure')
  },
  {
    title: 'Stress Test',
    handle: require('tests/stress')
  },
  {
    all: true,
    title: '» All «',
    handle: launchAll
  }
];

var BUTTONS = ACTIONS.map(function (action) {

  action.button = Ti.UI.createButton({
    title: action.title
  });

  action.running = false;

  action.button.addEventListener('click', function () {
    if (action.button.disabled) {
      return;
    }

    var buttons;

    if (action.all) {
      buttons = BUTTONS;
    }
    else {
      buttons = [ action.button ];
    }

    action.running = true;
    buttons.forEach(disableButton);
    action.handle(config, function (err) {
      action.running = false;
      buttons.forEach(enableButton);
      informUser(action.title, err);
    });
  });

  list.add(action.button);

  return action.button;
});

if (config.AUTO_LAUNCH || env.TRAVIS === 'true') {
  launchAll(config, function (err) {
    notifyBuildSystem(err);
  });
}

function notifyBuildSystem(err) {
  if (err) {
    Ti.API.error("NOTOK");
    Ti.API.error(err);
  }
  else {
    Ti.API.info("ALLOK");
  }
}

function informUser(message, err) {
  if (err) {
    alert(message + ": NOT OK\n" + err);
    throw err;
  }
  else {
    alert(message + ": Done");
  }
}

function launchAll(config, callback) {
  bar.show();
  bar.value = 0;
  launch(0, function () {
    bar.value = 1;
    bar.hide();
    return callback.apply(this, arguments);
  });
}

function launch(i, callback) {
  bar.value = (1 / (ACTIONS.length - 1)) * i;
  var action = ACTIONS[i];
  if (action && !action.all) action.handle(config, function (err) {
    if (action.running) callback(new Error("Already running"));
    else if (err) callback(err);
    else setTimeout(function () {
      launch(i + 1, callback)
    }, 0);
  });
  else callback();
}

function enableButton(button) {
  button.enabled = true;
  button.disabled = false;
}

function disableButton(button) {
  button.enabled = false;
  button.disabled = true;
}

win.open();
<commit_msg>Log the error BEFORE the marker<commit_after>
var env = require('env');
var config;

try {
  config = require('config');
}
catch (e) {
  config = require('config.sample');
}

var win = Ti.UI.createWindow({});

var list = Ti.UI.createScrollView({
  width: Ti.UI.SIZE,
  height: Ti.UI.SIZE,
  layout: 'vertical'
});

var bar = Ti.UI.createProgressBar({
  top: 0,
  right: 0,
  left: 0,
  min: 0,
  max: 1,
  value: 0
});

bar.hide();

win.add(list);
win.add(bar);

var ACTIONS = [
  {
    title: 'Errors Test',
    handle: require('tests/errors')
  },
  {
    title: 'Callback Test',
    handle: require('tests/once')
  },
  {
    title: 'Timeout Test',
    handle: require('tests/timeout')
  },
  {
    title: 'Failure Test',
    handle: require('tests/failure')
  },
  {
    title: 'Stress Test',
    handle: require('tests/stress')
  },
  {
    all: true,
    title: '» All «',
    handle: launchAll
  }
];

var BUTTONS = ACTIONS.map(function (action) {

  action.button = Ti.UI.createButton({
    title: action.title
  });

  action.running = false;

  action.button.addEventListener('click', function () {
    if (action.button.disabled) {
      return;
    }

    var buttons;

    if (action.all) {
      buttons = BUTTONS;
    }
    else {
      buttons = [ action.button ];
    }

    action.running = true;
    buttons.forEach(disableButton);
    action.handle(config, function (err) {
      action.running = false;
      buttons.forEach(enableButton);
      informUser(action.title, err);
    });
  });

  list.add(action.button);

  return action.button;
});

if (config.AUTO_LAUNCH || env.TRAVIS === 'true') {
  launchAll(config, function (err) {
    notifyBuildSystem(err);
  });
}

function notifyBuildSystem(err) {
  if (err) {
    Ti.API.error(err);
    Ti.API.error("NOTOK");
  }
  else {
    Ti.API.info("ALLOK");
  }
}

function informUser(message, err) {
  if (err) {
    alert(message + ": NOT OK\n" + err);
    throw err;
  }
  else {
    alert(message + ": Done");
  }
}

function launchAll(config, callback) {
  bar.show();
  bar.value = 0;
  launch(0, function () {
    bar.value = 1;
    bar.hide();
    return callback.apply(this, arguments);
  });
}

function launch(i, callback) {
  bar.value = (1 / (ACTIONS.length - 1)) * i;
  var action = ACTIONS[i];
  if (action && !action.all) action.handle(config, function (err) {
    if (action.running) callback(new Error("Already running"));
    else if (err) callback(err);
    else setTimeout(function () {
      launch(i + 1, callback)
    }, 0);
  });
  else callback();
}

function enableButton(button) {
  button.enabled = true;
  button.disabled = false;
}

function disableButton(button) {
  button.enabled = false;
  button.disabled = true;
}

win.open();
<|endoftext|>