<commit_before>/**
 * Advanced OpenReports, SugarCRM Reporting.
 * @package Advanced OpenReports for SugarCRM
 * @copyright SalesAgility Ltd http://www.salesagility.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
 * along with this program; if not, see http://www.gnu.org/licenses
 * or write to the Free Software Foundation,Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301  USA
 *
 * @author SalesAgility <info@salesagility.com>
 */

$(document).ready(function () {

  $('#download_pdf_button_old').click(function () {

    var _form = addParametersToForm('DownloadPDF');

    var rGraphs = document.getElementsByClassName('resizableCanvas');
    for (var i = 0; i < rGraphs.length; i++) {
      _form.append('<input type="hidden" id="graphsForPDF" name="graphsForPDF[]" value=' + rGraphs[i].toDataURL() + '>');
    }

    _form.submit();

    $("#formDetailView #graphsForPDF").remove();
  });

  $('#download_csv_button_old').click(function () {

    var _form = addParametersToForm('Export');

    _form.submit();
  });

  $('#updateParametersButton').click(function(){

    var _form = addParametersToForm('DetailView');

    _form.submit();
  });
});

function updateTimeDateFields(fieldInput, ln) {
  // datetime combo fields
  if (typeof fieldInput === 'undefined'
    && $("[name='aor_conditions_value\\[" + ln + "\\]").val()
    && $("[name='aor_conditions_value\\[" + ln + "\\]").hasClass('DateTimeCombo')) {
    var datetime = $("[name='aor_conditions_value\\[" + ln + "\\]']").val();
    var date = datetime.substr(0, 10);
    var formatDate = $.datepicker.formatDate('yy-mm-dd', new Date(date));
    fieldInput = datetime.replace(date, formatDate) + ':00';
  }
  return fieldInput;
}

function updateHiddenReportFields(ln, _form) {
// Fix for issue #1272 - AOR_Report module cannot update Date type parameter.
  if ($('#aor_conditions_value' + ln).length) {
      var conditionsValue = $('#aor_conditions_value' + ln).val();
      var fieldValue = conditionsValue;
      var fieldSign = conditionsValue;
      var fieldNumber = conditionsValue;
      var fieldTime = conditionsValue;

      _form.append('<input type="hidden" name="parameter_date_value['+ ln + '] value="' + fieldValue + '">');
      _form.append('<input type="hidden" name="parameter_date_sign['+ ln + ']" value="' + fieldSign + '">');
      _form.append('<input type="hidden" name="parameter_date_number['+ ln + ']" value="' + fieldNumber + '">');
      _form.append('<input type="hidden" name="parameter_date_time['+ ln + ']" value="' + fieldTime + '">');
  }
}

function localToDbFormat(index, ln, fieldInput) {
// Fix for issue #1082 - change local date format to db date format
  if ($('#aor_conditions_value' + index + '').hasClass('date_input')) { // only change to DB format if its a date
    if ($('#aor_conditions_value' + ln + '').hasClass('date_input')) {
      fieldInput = $.datepicker.formatDate('yy-mm-dd', new Date(fieldInput));
    }
  }
  return fieldInput;
}

function appendHiddenFields(_form, ln, id) {
    _form.append('<input type="hidden" name="parameter_id\[' + ln + '\]" value="' + id + '">');
    var operator = $("#aor_conditions_operator\\[" + ln + "\\]").val();
    _form.append('<input type="hidden" name="parameter_operator\[' + ln + '\]" value="' + operator + '">');
    var fieldType = $('#aor_conditions_value_type\\[' + ln + '\\]').val();
    _form.append('<input type="hidden" name="parameter_type[' + ln + ']" value="' + fieldType + '">');

    // values can be #aor_conditions_value3 or #aor_conditions_value[3]
    var fieldInput = '';
    if ($('#aor_conditions_value' + ln).length > 0) {
        fieldInput = $('#aor_conditions_value' + ln).val();
        fieldInput = updateTimeDateFields(fieldInput, ln);
    } else {
        fieldInput = $('#aor_conditions_value\\[' + ln + '\\]').val();
    }

    _form.append('<input type="hidden" name="parameter_value[' + ln + ']" value="' + fieldInput + '">');
    updateHiddenReportFields(ln, _form);
}

function addParametersToForm(action) {
  var _form = $('#formDetailView');
  _form.find('input[name=action]').val(action);

  $('.aor_conditions_id').each(function(index, elem) {
    $elem = $(elem);
    var ln = $elem.attr('id').substr(17);
    var id = $elem.val();
    appendHiddenFields(_form, ln, id);
  });
    debugger;
  return _form;
}

function openProspectPopup() {

  var popupRequestData = {
    "call_back_function": "setProspectReturn",
    "form_name": "EditView",
    "field_to_name_array": {
      "id": "prospect_id"
    }
  };

  open_popup('ProspectLists', '600', '400', '', true, false, popupRequestData);

}

function setProspectReturn(popup_reply_data) {

  var callback = {
    success: function (result) {
      //report_rel_modules = result.responseText;
      //alert('pass '+result.responseText);
    },
    failure: function (result) {
      //alert('fail '+result.responseText);
    }
  }

  var prospect_id = popup_reply_data.name_to_value_array.prospect_id;
  var record = document.getElementsByName('record')[0].value;

  YAHOO.util.Connect.asyncRequest("GET", "index.php?module=AOR_Reports&action=addToProspectList&record=" + record + "&prospect_id=" + prospect_id, callback);

}

function changeReportPage(record, offset, group_value, table_id) {
  var paginationButtonCaller = $(this);
  var query = "?module=AOR_Reports&action=changeReportPage&record=" + record + "&offset=" + offset + "&group=" + group_value;
  $('.aor_conditions_id').each(function (index, elem) {
    $elem = $(elem);
    var ln = $elem.attr('id').substr(17);
    var id = $elem.val();
    query += "&parameter_id[]=" + id;
    var operator = $("#aor_conditions_operator\\[" + ln + "\\]").val();
    query += "&parameter_operator[]=" + operator;
    var fieldType = $('#aor_conditions_value_type\\[' + ln + '\\]').val();
    query += "&parameter_type[]=" + fieldType;
    var fieldInput = '';
    if ($('#aor_conditions_value' + ln).length > 0) {
        fieldInput = $('#aor_conditions_value' + ln).val();
        fieldInput = updateTimeDateFields(fieldInput, ln);
    } else {
        fieldInput = $('#aor_conditions_value\\[' + ln + '\\]').val();
    }
    query += "&parameter_value[]=" + fieldInput;
  });

  $.get(query).done(
    function (data) {
      $('#report_table_' + table_id).replaceWith(data);
    }
  );
}<commit_msg>Removing debugging statement<commit_after>/**
 * Advanced OpenReports, SugarCRM Reporting.
 * @package Advanced OpenReports for SugarCRM
 * @copyright SalesAgility Ltd http://www.salesagility.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
 * along with this program; if not, see http://www.gnu.org/licenses
 * or write to the Free Software Foundation,Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301  USA
 *
 * @author SalesAgility <info@salesagility.com>
 */

$(document).ready(function () {

  $('#download_pdf_button_old').click(function () {

    var _form = addParametersToForm('DownloadPDF');

    var rGraphs = document.getElementsByClassName('resizableCanvas');
    for (var i = 0; i < rGraphs.length; i++) {
      _form.append('<input type="hidden" id="graphsForPDF" name="graphsForPDF[]" value=' + rGraphs[i].toDataURL() + '>');
    }

    _form.submit();

    $("#formDetailView #graphsForPDF").remove();
  });

  $('#download_csv_button_old').click(function () {

    var _form = addParametersToForm('Export');

    _form.submit();
  });

  $('#updateParametersButton').click(function(){

    var _form = addParametersToForm('DetailView');

    _form.submit();
  });
});

function updateTimeDateFields(fieldInput, ln) {
  // datetime combo fields
  if (typeof fieldInput === 'undefined'
    && $("[name='aor_conditions_value\\[" + ln + "\\]").val()
    && $("[name='aor_conditions_value\\[" + ln + "\\]").hasClass('DateTimeCombo')) {
    var datetime = $("[name='aor_conditions_value\\[" + ln + "\\]']").val();
    var date = datetime.substr(0, 10);
    var formatDate = $.datepicker.formatDate('yy-mm-dd', new Date(date));
    fieldInput = datetime.replace(date, formatDate) + ':00';
  }
  return fieldInput;
}

function updateHiddenReportFields(ln, _form) {
// Fix for issue #1272 - AOR_Report module cannot update Date type parameter.
  if ($('#aor_conditions_value' + ln).length) {
      var conditionsValue = $('#aor_conditions_value' + ln).val();
      var fieldValue = conditionsValue;
      var fieldSign = conditionsValue;
      var fieldNumber = conditionsValue;
      var fieldTime = conditionsValue;

      _form.append('<input type="hidden" name="parameter_date_value['+ ln + '] value="' + fieldValue + '">');
      _form.append('<input type="hidden" name="parameter_date_sign['+ ln + ']" value="' + fieldSign + '">');
      _form.append('<input type="hidden" name="parameter_date_number['+ ln + ']" value="' + fieldNumber + '">');
      _form.append('<input type="hidden" name="parameter_date_time['+ ln + ']" value="' + fieldTime + '">');
  }
}

function localToDbFormat(index, ln, fieldInput) {
// Fix for issue #1082 - change local date format to db date format
  if ($('#aor_conditions_value' + index + '').hasClass('date_input')) { // only change to DB format if its a date
    if ($('#aor_conditions_value' + ln + '').hasClass('date_input')) {
      fieldInput = $.datepicker.formatDate('yy-mm-dd', new Date(fieldInput));
    }
  }
  return fieldInput;
}

function appendHiddenFields(_form, ln, id) {
    _form.append('<input type="hidden" name="parameter_id\[' + ln + '\]" value="' + id + '">');
    var operator = $("#aor_conditions_operator\\[" + ln + "\\]").val();
    _form.append('<input type="hidden" name="parameter_operator\[' + ln + '\]" value="' + operator + '">');
    var fieldType = $('#aor_conditions_value_type\\[' + ln + '\\]').val();
    _form.append('<input type="hidden" name="parameter_type[' + ln + ']" value="' + fieldType + '">');

    // values can be #aor_conditions_value3 or #aor_conditions_value[3]
    var fieldInput = '';
    if ($('#aor_conditions_value' + ln).length > 0) {
        fieldInput = $('#aor_conditions_value' + ln).val();
        fieldInput = updateTimeDateFields(fieldInput, ln);
    } else {
        fieldInput = $('#aor_conditions_value\\[' + ln + '\\]').val();
    }

    _form.append('<input type="hidden" name="parameter_value[' + ln + ']" value="' + fieldInput + '">');
    updateHiddenReportFields(ln, _form);
}

function addParametersToForm(action) {
  var _form = $('#formDetailView');
  _form.find('input[name=action]').val(action);

  $('.aor_conditions_id').each(function(index, elem) {
    $elem = $(elem);
    var ln = $elem.attr('id').substr(17);
    var id = $elem.val();
    appendHiddenFields(_form, ln, id);
  });
  return _form;
}

function openProspectPopup() {

  var popupRequestData = {
    "call_back_function": "setProspectReturn",
    "form_name": "EditView",
    "field_to_name_array": {
      "id": "prospect_id"
    }
  };

  open_popup('ProspectLists', '600', '400', '', true, false, popupRequestData);

}

function setProspectReturn(popup_reply_data) {

  var callback = {
    success: function (result) {
      //report_rel_modules = result.responseText;
      //alert('pass '+result.responseText);
    },
    failure: function (result) {
      //alert('fail '+result.responseText);
    }
  }

  var prospect_id = popup_reply_data.name_to_value_array.prospect_id;
  var record = document.getElementsByName('record')[0].value;

  YAHOO.util.Connect.asyncRequest("GET", "index.php?module=AOR_Reports&action=addToProspectList&record=" + record + "&prospect_id=" + prospect_id, callback);

}

function changeReportPage(record, offset, group_value, table_id) {
  var paginationButtonCaller = $(this);
  var query = "?module=AOR_Reports&action=changeReportPage&record=" + record + "&offset=" + offset + "&group=" + group_value;
  $('.aor_conditions_id').each(function (index, elem) {
    $elem = $(elem);
    var ln = $elem.attr('id').substr(17);
    var id = $elem.val();
    query += "&parameter_id[]=" + id;
    var operator = $("#aor_conditions_operator\\[" + ln + "\\]").val();
    query += "&parameter_operator[]=" + operator;
    var fieldType = $('#aor_conditions_value_type\\[' + ln + '\\]').val();
    query += "&parameter_type[]=" + fieldType;
    var fieldInput = '';
    if ($('#aor_conditions_value' + ln).length > 0) {
        fieldInput = $('#aor_conditions_value' + ln).val();
        fieldInput = updateTimeDateFields(fieldInput, ln);
    } else {
        fieldInput = $('#aor_conditions_value\\[' + ln + '\\]').val();
    }
    query += "&parameter_value[]=" + fieldInput;
  });

  $.get(query).done(
    function (data) {
      $('#report_table_' + table_id).replaceWith(data);
    }
  );
}<|endoftext|>


<commit_before>/**
 * Connect Request event
 * @module peer/events/connect-request
 */
const uuid = require('uuid');
const NError = require('nerror');

/**
 * Connect Request event class
 */
class ConnectRequest {
    /**
     * Create service
     * @param {App} app                             The application
     * @param {object} config                       Configuration
     * @param {Logger} logger                       Logger service
     * @param {Crypter} crypter                     Crypter service
     * @param {ConnectionsList} connectionsList     ConnectionsList service
     */
    constructor(app, config, logger, crypter, connectionsList) {
        this._app = app;
        this._config = config;
        this._logger = logger;
        this._crypter = crypter;
        this._connectionsList = connectionsList;
    }

    /**
     * Service name is 'modules.peer.events.connectRequest'
     * @type {string}
     */
    static get provides() {
        return 'modules.peer.events.connectRequest';
    }

    /**
     * Dependencies as constructor arguments
     * @type {string[]}
     */
    static get requires() {
        return [ 'app', 'config', 'logger', 'crypter', 'connectionsList' ];
    }

    /**
     * Event handler
     * @param {string} sessionId                Session ID
     * @param {object} message                  The message
     */
    handle(sessionId, message) {
        let session = this.peer.sessions.get(sessionId);
        if (!session)
            return;

        let reply = accepted => {
            let response = this.peer.ConnectResponse.create({
                response: accepted ? this.peer.ConnectResponse.Result.ACCEPTED : this.peer.ConnectResponse.Result.REJECTED,
            });
            let msg = this.peer.OuterMessage.create({
                type: this.peer.OuterMessage.Type.CONNECT_RESPONSE,
                connectResponse: response,
            });
            let buffer = this.peer.OuterMessage.encode(msg).finish();
            this._logger.debug('connect-request', accepted ? 'Sending ACCEPT' : 'Sending REJECT');
            this.peer.send(sessionId, buffer);
        };

        if (session.name && session.name !== message.connectRequest.connectionName)
            return reply(false);

        let connection = this.peer.connections.get(message.connectRequest.connectionName);
        if (!connection)
            return reply(false);

        if (!session.name) {
            session.name = connection.name;
            connection.sessionIds.add(sessionId);
            let cryptSession = this._crypter.sessions.get(sessionId);
            if (cryptSession)
                cryptSession.connection = connection.name;
        }

        this._crypter.verify(
                sessionId,
                connection.tracker,
                message.connectRequest.identity,
                message.connectRequest.publicKey,
                message.connectRequest.signature,
                connection.fixed
            )
            .then(result => {
                session.verified = result.verified;

                if (session.verified) {
                    let cryptSession = this._crypter.sessions.get(sessionId);
                    cryptSession.peerKey = new Uint8Array(Buffer.from(message.connectRequest.publicKey, 'base64'));
                    cryptSession.peerName = result.name;
                    this._connectionsList.updateServerName(connection.tracker, connection.name, cryptSession.peerName);
                    this._logger.info(
                        `Peer ${result.name} of ${message.connectRequest.connectionName} passed identity check (${session.socket.address().address}:${session.socket.address().port})`
                    );
                } else {
                    if (result.name && connection.fixed && connection.peers.indexOf(result.name) === -1) {
                        this._logger.error(
                            `Peer ${result.name} of ${message.connectRequest.connectionName} is not in the fixed list and rejected (${session.socket.address().address}:${session.socket.address().port})`
                        );
                    } else {
                        this._logger.error(
                            `Peer ${result.name ? result.name : 'unknown'} of ${message.connectRequest.connectionName} failed identity check (${session.socket.address().address}:${session.socket.address().port})`
                        );
                    }
                }

                reply(session.verified);

                if (session.verified) {
                    if (session.accepted && !session.established) {
                        session.established = true;
                        this.peer.emit('established', sessionId);
                    } else if (connection.server) {
                        this.peer.sendConnectRequest(sessionId);
                    }
                }
            })
            .catch(error => {
                this._logger.error(new NError(error, `ConnectRequest.handle()`));
            });
    }

    /**
     * Retrieve tracker server
     * @return {Tracker}
     */
    get tracker() {
        if (this._tracker)
            return this._tracker;
        this._tracker = this._app.get('servers').get('tracker');
        return this._tracker;
    }

    /**
     * Retrieve peer server
     * @return {Peer}
     */
    get peer() {
        if (this._peer)
            return this._peer;
        this._peer = this._app.get('servers').get('peer');
        return this._peer;
    }

    /**
     * Retrieve front server
     * @return {Front}
     */
    get front() {
        if (this._front)
            return this._front;
        this._front = this._app.get('servers').get('front');
        return this._front;
    }
}

module.exports = ConnectRequest;<commit_msg>Check if it is a client before updating server name<commit_after>/**
 * Connect Request event
 * @module peer/events/connect-request
 */
const uuid = require('uuid');
const NError = require('nerror');

/**
 * Connect Request event class
 */
class ConnectRequest {
    /**
     * Create service
     * @param {App} app                             The application
     * @param {object} config                       Configuration
     * @param {Logger} logger                       Logger service
     * @param {Crypter} crypter                     Crypter service
     * @param {ConnectionsList} connectionsList     ConnectionsList service
     */
    constructor(app, config, logger, crypter, connectionsList) {
        this._app = app;
        this._config = config;
        this._logger = logger;
        this._crypter = crypter;
        this._connectionsList = connectionsList;
    }

    /**
     * Service name is 'modules.peer.events.connectRequest'
     * @type {string}
     */
    static get provides() {
        return 'modules.peer.events.connectRequest';
    }

    /**
     * Dependencies as constructor arguments
     * @type {string[]}
     */
    static get requires() {
        return [ 'app', 'config', 'logger', 'crypter', 'connectionsList' ];
    }

    /**
     * Event handler
     * @param {string} sessionId                Session ID
     * @param {object} message                  The message
     */
    handle(sessionId, message) {
        let session = this.peer.sessions.get(sessionId);
        if (!session)
            return;

        let reply = accepted => {
            let response = this.peer.ConnectResponse.create({
                response: accepted ? this.peer.ConnectResponse.Result.ACCEPTED : this.peer.ConnectResponse.Result.REJECTED,
            });
            let msg = this.peer.OuterMessage.create({
                type: this.peer.OuterMessage.Type.CONNECT_RESPONSE,
                connectResponse: response,
            });
            let buffer = this.peer.OuterMessage.encode(msg).finish();
            this._logger.debug('connect-request', accepted ? 'Sending ACCEPT' : 'Sending REJECT');
            this.peer.send(sessionId, buffer);
        };

        if (session.name && session.name !== message.connectRequest.connectionName)
            return reply(false);

        let connection = this.peer.connections.get(message.connectRequest.connectionName);
        if (!connection)
            return reply(false);

        if (!session.name) {
            session.name = connection.name;
            connection.sessionIds.add(sessionId);
            let cryptSession = this._crypter.sessions.get(sessionId);
            if (cryptSession)
                cryptSession.connection = connection.name;
        }

        this._crypter.verify(
                sessionId,
                connection.tracker,
                message.connectRequest.identity,
                message.connectRequest.publicKey,
                message.connectRequest.signature,
                connection.fixed
            )
            .then(result => {
                session.verified = result.verified;

                if (session.verified) {
                    let cryptSession = this._crypter.sessions.get(sessionId);
                    cryptSession.peerKey = new Uint8Array(Buffer.from(message.connectRequest.publicKey, 'base64'));
                    cryptSession.peerName = result.name;
                    if (!connection.server)
                        this._connectionsList.updateServerName(connection.tracker, connection.name, cryptSession.peerName);
                    this._logger.info(
                        `Peer ${result.name} of ${message.connectRequest.connectionName} passed identity check (${session.socket.address().address}:${session.socket.address().port})`
                    );
                } else {
                    if (result.name && connection.fixed && connection.peers.indexOf(result.name) === -1) {
                        this._logger.error(
                            `Peer ${result.name} of ${message.connectRequest.connectionName} is not in the fixed list and rejected (${session.socket.address().address}:${session.socket.address().port})`
                        );
                    } else {
                        this._logger.error(
                            `Peer ${result.name ? result.name : 'unknown'} of ${message.connectRequest.connectionName} failed identity check (${session.socket.address().address}:${session.socket.address().port})`
                        );
                    }
                }

                reply(session.verified);

                if (session.verified) {
                    if (session.accepted && !session.established) {
                        session.established = true;
                        this.peer.emit('established', sessionId);
                    } else if (connection.server) {
                        this.peer.sendConnectRequest(sessionId);
                    }
                }
            })
            .catch(error => {
                this._logger.error(new NError(error, `ConnectRequest.handle()`));
            });
    }

    /**
     * Retrieve tracker server
     * @return {Tracker}
     */
    get tracker() {
        if (this._tracker)
            return this._tracker;
        this._tracker = this._app.get('servers').get('tracker');
        return this._tracker;
    }

    /**
     * Retrieve peer server
     * @return {Peer}
     */
    get peer() {
        if (this._peer)
            return this._peer;
        this._peer = this._app.get('servers').get('peer');
        return this._peer;
    }

    /**
     * Retrieve front server
     * @return {Front}
     */
    get front() {
        if (this._front)
            return this._front;
        this._front = this._app.get('servers').get('front');
        return this._front;
    }
}

module.exports = ConnectRequest;<|endoftext|>


<commit_before>#!/usr/bin/env node

//=========== run_command_sync_to_console: run one command and let output immediately flow to console ============
var run_command_sync_to_console = function (cmd) {
    var execSync = require('child_process').execSync;
    execSync(cmd, {stdio:[0,1,2]}, function(error, stdout, stderr) {
        if (error) {
            console.log('======= RUN ERROR =======');
            throw error;
        }
    });
}

//=========== run_command_async_to_console: async run one command and dump output to console when complete ============
var run_command_async_to_console = function (cmd) {
    var exec = require('child_process').exec;
    exec(cmd, function(error, stdout, stderr) {
        if (stdout.length > 0 ) console.log(stdout);
        if (stderr.length > 0 ) console.log(stderr);
    });
}

//=========== run_command_quietly: runs without output unless error ============
var run_command_quietly = function (cmd) {
    var execSync = require('child_process').execSync;
    execSync(cmd, function(error, stdout, stderr) {
        if (error) {
            console.log('======= RUN ERROR =======');
            throw error;
        }
    });
}

// =========== run_command: run one command and get output ============
// Run a command asynchronously and get the output when it finishes in a callback.
// Usage:
// run_command( "ls -l", function(text) { console.log (text) });
var run_command = function (cmd, callBack ) {

    var fullargs = spawnargs(cmd);
    cmd = fullargs[0];
    var args = fullargs.slice(1);

    // TODO this needs work, spawn isn't cooperating yet...

    // DEBUG
    // run_command_sync_to_console(cmd);

    // Ignorant spawn absolutely whines if you don't split out the arguments.
    /*
    var spawnargs = require('spawn-args');
    var args = cmd.split(" ").slice(1);
    var argstring = "";
    for (var i = 0;i < args.length;i++) {
        argstring += args[i] + ' ';
    }
    console.log('argstring: ' + argstring);

    cmd = cmd.split(" ",1);
    */

    // DEBUG:
    // console.log('cmd args: ' + cmd + ' ----- ' + args);

    // STRAIGHT COMMAND PARSING, doesn't work either
    /*
    var args = cmd.split(" ").slice(1);
    for (var i = 0;i < args.length;i++) {
        args[i] = trim(args[i]);
    }
    cmd = cmd.split(" ",1).trim();
    */

    // DEBUG this works!
    // var args = ["status"];
    // cmd = "git";

    // DEBUG this works!
    // cmd = "git";
    // var args = ["commit","-a","-m",'"synctrouble"'];

    // DEBUG:
    // console.log('cmd args: ' + cmd + ' ----- ' + args);

    var spawn = require('child_process').spawn;

    var child = spawn(cmd, args);
    // var child = spawn(cmd, args, {stdio: "inherit"});

    // THIS SHIT BREAKS EVERYTHING SILENTLY
    /*
    if (error) {
        console.log(error.stack);
        console.log('Error code: '+error.code);
        console.log('Signal received: '+error.signal);
    }
    */

    var resp = "";
    child.stdout.on('data', function (buffer) { resp += buffer.toString() });
    child.stderr.on('data', function (buffer) { resp += 'ERROR: ' + buffer.toString() });

    child.stdout.on('end', function() { callBack (resp) });
}

// =========== run_command_sync: run one command and get output ============
// Run a command synchronously and get the output when it finishes.
// Usage:
// var lsout = run_command_sync( "ls", ["-l"]);
var run_command_sync = function (cmd) {

    // Ignorant spawn absolutely whines if you don't split out the arguments.
    var args = cmd.split(" ").slice(1);
    cmd = cmd.split(" ",1);

    var ss = require('child_process').spawnSync;
    var outp = ss(cmd, args, { encoding : 'utf8' });
    return outp.stdout;

    // From here:
    //  http://stackoverflow.com/questions/32393250/nodejs-child-process-spawnsync-or-child-process-spawn-wrapped-in-yieldable-gener
    // More example cde:
    // var ls = cp.spawnSync('ls', ['-l', '/usr'], { encoding : 'utf8' });
    // uncomment the following if you want to see everything returned by the spawnSync command
    // console.log('ls: ' , ls);
    // console.log('stdout here: \n' + ls.stdout);
}

// =========== runsteps: run a specific set of commands in specific directories ============
// Given: steps, an array of {name,folder,cmd} objects, eg:
//
//      var my_steps =
//      [
//          { name: 'update Project'        , folder: '.'       , cmd: 'git pull'       },
//          { name: 'build Project'         , folder: '.'       , cmd: 'make'           },
//      ];
//
// This function runs the requested steps.
// Verbosity can be:
//		"quiet"		no output
//		undefined	normal output - the step name and command output are logged to console
//		"verbose"	more output - step name, folder, command output
// Define async to get asynchronous execution.
var runsteps = function (steps,verbosity,async) {

    var path = require('path');

    for (var i = 0;i < steps.length;i++) {

        try {

        	if (verbosity != "quiet") {
                console.log('step: ' + steps[i].name);
        	}
            if (verbosity == "verbose") {
                console.log('cd: ' + process.cwd());
            }

            process.chdir(path.normalize(steps[i].folder));

            if (async) {
                run_command_async_to_console(steps[i].cmd);
            } else if (verbosity != "quiet") {
        		run_command_sync_to_console(steps[i].cmd);
        	} else {
        		run_command_quietly(steps[i].cmd);
        	}
        }
        catch (err) {
            if (verbosity == "verbose") {
            	console.log(err);
            }
        }
    }
}

var combine_params = function(params) {
    var result = "";
    if (params.length > 0)
    {
        params.forEach(function(val,index,array){
            if (index != 0) { result += " "; }
            result += val;
        });
    }
    return result;
}

module.exports.run_command_sync = run_command_sync;
module.exports.run_command_sync_to_console = run_command_sync_to_console;
module.exports.run_command_async_to_console = run_command_async_to_console;
module.exports.run_command_quietly = run_command_quietly;
module.exports.run_command = run_command;
module.exports.runsteps = runsteps;
module.exports.combine_params = combine_params;
<commit_msg>testing auto commit<commit_after>#!/usr/bin/env node

//=========== run_command_sync_to_console: run one command and let output immediately flow to console ============
var run_command_sync_to_console = function (cmd) {
    var execSync = require('child_process').execSync;
    execSync(cmd, {stdio:[0,1,2]}, function(error, stdout, stderr) {
        if (error) {
            console.log('======= RUN ERROR =======');
            throw error;
        }
    });
}

//=========== run_command_async_to_console: async run one command and dump output to console when complete ============
var run_command_async_to_console = function (cmd) {
    var exec = require('child_process').exec;
    exec(cmd, function(error, stdout, stderr) {
        if (stdout.length > 0 ) console.log(stdout);
        if (stderr.length > 0 ) console.log(stderr);
    });
}

//=========== run_command_quietly: runs without output unless error ============
var run_command_quietly = function (cmd) {
    var execSync = require('child_process').execSync;
    execSync(cmd, function(error, stdout, stderr) {
        if (error) {
            console.log('======= RUN ERROR =======');
            throw error;
        }
    });
}

// =========== run_command: run one command and get output ============
// Run a command asynchronously and get the output when it finishes in a callback.
// Usage:
// run_command( "ls -l", function(text) { console.log (text) });
var run_command = function (cmd, callBack ) {

    var fullargs = spawnargs(cmd);
    cmd = fullargs[0];
    var args = fullargs.slice(1);

    // TODO this needs work, spawn isn't cooperating yet...

    // DEBUG
    // run_command_sync_to_console(cmd);

    // Ignorant spawn absolutely whines if you don't split out the arguments.
    /*
    var spawnargs = require('spawn-args');
    var args = cmd.split(" ").slice(1);
    var argstring = "";
    for (var i = 0;i < args.length;i++) {
        argstring += args[i] + ' ';
    }
    console.log('argstring: ' + argstring);

    cmd = cmd.split(" ",1);
    */

    // DEBUG:
    // console.log('cmd args: ' + cmd + ' ----- ' + args);

    // STRAIGHT COMMAND PARSING, doesn't work either
    /*
    var args = cmd.split(" ").slice(1);
    for (var i = 0;i < args.length;i++) {
        args[i] = trim(args[i]);
    }
    cmd = cmd.split(" ",1).trim();
    */

    // DEBUG this works!
    // var args = ["status"];
    // cmd = "git";

    // DEBUG this works!
    // cmd = "git";
    // var args = ["commit","-a","-m",'"synctrouble"'];

    // DEBUG:
    // console.log('cmd args: ' + cmd + ' ----- ' + args);

    var spawn = require('child_process').spawn;

    var child = spawn(cmd, args);
    // var child = spawn(cmd, args, {stdio: "inherit"});

    // THIS SHIT BREAKS EVERYTHING SILENTLY
    /*
    if (error) {
        console.log(error.stack);
        console.log('Error code: '+error.code);
        console.log('Signal received: '+error.signal);
    }
    */

    var resp = "";
    child.stdout.on('data', function (buffer) { resp += buffer.toString() });
    child.stderr.on('data', function (buffer) { resp += 'ERROR: ' + buffer.toString() });

    child.stdout.on('end', function() { callBack (resp) });
}

// =========== run_command_sync: run one command and get output ============
// Run a command synchronously and get the output when it finishes.
// Usage:
// var lsout = run_command_sync( "ls", ["-l"]);
var run_command_sync = function (cmd) {

    // Ignorant spawn absolutely whines if you don't split out the arguments.
    var args = cmd.split(" ").slice(1);
    cmd = cmd.split(" ",1);

    var ss = require('child_process').spawnSync;
    var outp = ss(cmd, args, { encoding : 'utf8' });
    return outp.stdout;

    // From here:
    //  http://stackoverflow.com/questions/32393250/nodejs-child-process-spawnsync-or-child-process-spawn-wrapped-in-yieldable-gener
    // More example cde:
    // var ls = cp.spawnSync('ls', ['-l', '/usr'], { encoding : 'utf8' });
    // uncomment the following if you want to see everything returned by the spawnSync command
    // console.log('ls: ' , ls);
    // console.log('stdout here: \n' + ls.stdout);
}

// =========== runsteps: run a specific set of commands in specific directories ============
// Given: steps, an array of {name,folder,cmd} objects, eg:
//
//      var my_steps =
//      [
//          { name: 'update Project'        , folder: '.'       , cmd: 'git pull'       },
//          { name: 'build Project'         , folder: '.'       , cmd: 'make'           },
//      ];
//
// This function runs the requested steps.
// Verbosity can be:
//		"quiet"		no output
//		undefined	normal output - the step name and command output are logged to console
//		"verbose"	more output - step name, folder, command output
// Define async to get asynchronous execution.
var runsteps = function (steps,verbosity,async) {

    var path = require('path');

    for (var i = 0;i < steps.length;i++) {

        try {

        	if (verbosity != "quiet") {
                console.log('step: ' + steps[i].name);
        	}
            if (verbosity == "verbose") {
                console.log('cd: ' + process.cwd());
            }

            process.chdir(path.normalize(steps[i].folder));

            if (async) {

                // TODO
                //run_command(steps[i].cmd, function(text) { console.log (text) });

                // Workaround
                run_command_async_to_console(steps[i].cmd);

            } else if (verbosity != "quiet") {
        		run_command_sync_to_console(steps[i].cmd);
        	} else {
        		run_command_quietly(steps[i].cmd);
        	}
        }
        catch (err) {
            if (verbosity == "verbose") {
            	console.log(err);
            }
        }
    }
}

var combine_params = function(params) {
    var result = "";
    if (params.length > 0)
    {
        params.forEach(function(val,index,array){
            if (index != 0) { result += " "; }
            result += val;
        });
    }
    return result;
}

module.exports.run_command_sync = run_command_sync;
module.exports.run_command_sync_to_console = run_command_sync_to_console;
module.exports.run_command_async_to_console = run_command_async_to_console;
module.exports.run_command_quietly = run_command_quietly;
module.exports.run_command = run_command;
module.exports.runsteps = runsteps;
module.exports.combine_params = combine_params;
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

var pkg = require('../package.json')
var cli = require('commander');

var fs      = require('fs');
var path    = require('path');
var request = require('request');
var tar     = require('tar-fs');
var zlib    = require('zlib');

cli
  .version( pkg.version )
  .arguments( '<project-name>' )
  .option('-a, --author <full name>', 'set a project author')
  .option('-m, --matter <url>', 'include a Matter repository from a clone URL')
  .parse( process.argv );

// If no args were passed, exit with help.
if( ! cli.args.length ) {
  cli.help();
}

// Begin
//

var cwd  = process.cwd();
var name = cli.args[0];

var newProjectPath = path.join( cwd, name );

var colliderFile = {
  name: name,
  createdTime: Date.now(),
  author: typeof cli.author !== 'undefined' ? cli.author : "",
  matter: typeof cli.matter !== 'undefined' ? cli.matter : ""
};

var colliderFileData = JSON.stringify( colliderFile );

// Create a new directory at 'newProjectPath'.
fs.mkdir( newProjectPath, function(error) {

  // Set a default error message.
  var errorMsg = `There was a problem creating "${name}" inside "${cwd}".`;

  if(error) {

    // Using the error code, make the default error message more useful.
    switch (error.code) {
      case 'EEXIST':
        errorMsg = `A file or directory named "${name}" already exists in "${cwd}".`;
        break;

      default:
    }

    // Log 'errorMsg' and exit.
    console.log(errorMsg);
    process.exit(1);

  } else {

    writeColliderFile( colliderFileData );
    getCollider();

    // To Do:
    // - Get Matter using `gulp matter` if option was passed
    // - Add "@import 'matter/matter';" to "main.scss"

  }

});

function writeColliderFile(data) {
  var colliderFilePath = path.join( newProjectPath, '.collider' );

  fs.writeFile( colliderFilePath, data, function(error) {
    if(error) throw error;
  });
}

function getCollider() {
  request('http://getcollider.com/latest.tar.gz')
    .pipe( zlib.createGunzip() )
    .pipe( tar.extract( newProjectPath ) );
}
<commit_msg>Update Collider-file path<commit_after>#!/usr/bin/env node

'use strict';

var pkg = require('../package.json')
var cli = require('commander');

var fs      = require('fs');
var path    = require('path');
var request = require('request');
var tar     = require('tar-fs');
var zlib    = require('zlib');

cli
  .version( pkg.version )
  .arguments( '<project-name>' )
  .option('-a, --author <full name>', 'set a project author')
  .option('-m, --matter <url>', 'include a Matter repository from a clone URL')
  .parse( process.argv );

// If no args were passed, exit with help.
if( ! cli.args.length ) {
  cli.help();
}

// Begin
//

var cwd  = process.cwd();
var name = cli.args[0];

var newProjectPath = path.join( cwd, name );

var colliderFile = {
  name: name,
  createdTime: Date.now(),
  author: typeof cli.author !== 'undefined' ? cli.author : "",
  matter: typeof cli.matter !== 'undefined' ? cli.matter : ""
};

var colliderFileData = JSON.stringify( colliderFile );

// Create a new directory at 'newProjectPath'.
fs.mkdir( newProjectPath, function(error) {

  // Set a default error message.
  var errorMsg = `There was a problem creating "${name}" inside "${cwd}".`;

  if(error) {

    // Using the error code, make the default error message more useful.
    switch (error.code) {
      case 'EEXIST':
        errorMsg = `A file or directory named "${name}" already exists in "${cwd}".`;
        break;

      default:
    }

    // Log 'errorMsg' and exit.
    console.log(errorMsg);
    process.exit(1);

  } else {

    writeColliderFile( colliderFileData );
    getCollider();

    // To Do:
    // - Get Matter using `gulp matter` if option was passed
    // - Add "@import 'matter/matter';" to "main.scss"

  }

});

function writeColliderFile(data) {
  var colliderFilePath = path.join( newProjectPath, 'project', '.collider' );

  fs.writeFile( colliderFilePath, data, function(error) {
    if(error) throw error;
  });
}

function getCollider() {
  request('http://getcollider.com/latest.tar.gz')
    .pipe( zlib.createGunzip() )
    .pipe( tar.extract( newProjectPath ) );
}
<|endoftext|>


<commit_before>Ext.namespace('Gemma');

/**
 *
 * Top level container for all sections of expression experiment info Sections are: 1. Details (has editing tools) 2.
 * Experimental design 3. Expression visualisation 4. Diagnostics 5. Quantitation Types ? 6. History (admin only) 7.
 * Admin (running analyses)
 *
 *
 * To open the page at a specific tab, include ?tab=[tabName] suffix in the URL. Tab names are each tab's itemId.
 *
 * @class Gemma.ExpressionExperimentPage
 * @extends Ext.TabPanel
 *
 */
Gemma.ExpressionExperimentPage = Ext.extend(Ext.TabPanel, {

            height : 600,
            defaults : {
                autoScroll : true,
                width : 850
            },
            initialTab : 'details',
            deferredRender : true,
            listeners : {
                'tabchange' : function(tabPanel, newTab) {
                    newTab.fireEvent('tabChanged');
                },
                'beforetabchange' : function(tabPanel, newTab, currTab) {
                    // if false is returned, tab isn't changed
                    if (currTab) {
                        return currTab.fireEvent('leavingTab');
                    }
                    return true;
                }
            },
            checkURLforInitialTab : function() {
                this.loadSpecificTab = (document.URL.indexOf("?") > -1 && (document.URL.indexOf("tab=") > -1));
                if (this.loadSpecificTab) {
                    var param = Ext.urlDecode(document.URL.substr(document.URL.indexOf("?") + 1));
                    if (param.tab) {
                        if (this.getComponent(param.tab) != undefined) {
                            this.initialTab = param.tab;
                        }
                    }
                }
            },
            initComponent : function() {

                var eeId = this.eeId;

                var isAdmin = Ext.get("hasAdmin").getValue() == 'true';

                Gemma.ExpressionExperimentPage.superclass.initComponent.call(this);
                this.on('render', function() {
                            if (!this.loadMask) {
                                this.loadMask = new Ext.LoadMask(this.getEl(), {
                                            msg : Gemma.StatusText.Loading.generic,
                                            msgCls : 'absolute-position-loading-mask ext-el-mask-msg x-mask-loading'
                                        });
                            }
                            this.loadMask.show();
                        });

                ExpressionExperimentController.loadExpressionExperimentDetails(eeId, function(experimentDetails) {
                            this.initFromExperimentValueObject(experimentDetails, isAdmin);

                            this.checkURLforInitialTab();
                            this.setActiveTab(this.initialTab);

                        }.createDelegate(this));

                Gemma.Application.currentUser.on("logIn", function(userName, isAdmin) {
                            var appScope = this;
                            ExpressionExperimentController.canCurrentUserEditExperiment(experimentDetails.id, {
                                        callback : function(editable) {
                                            // console.log(this);
                                            appScope.adjustForIsAdmin(isAdmin, editable);
                                        },
                                        scope : appScope
                                    });

                        }, this);

                Gemma.Application.currentUser.on("logOut", function() {

                            this.adjustForIsAdmin(false, false);

                        }, this);
            },
            initFromExperimentValueObject : function(experimentDetails, isAdmin) {

                this.experimentDetails = experimentDetails;
                this.editable = experimentDetails.canCurrentUserEditExperiment;
                this.ownedByCurrentUser = experimentDetails.doesCurrentUserOwnExperiment;

                if (this.loadMask) {
                    this.loadMask.hide();
                }

                // DETAILS TAB
                this.add(this.makeDetailsTab(experimentDetails));

                // EXPERIMENT DESIGN TAB

                this.add(this.makeDesignTab(experimentDetails));

                // VISUALISATION TAB
                this.add(this.makeVisualisationTab(experimentDetails, isAdmin));

                // DIAGNOSTICS TAB
                this.add(this.makeDiagnosticsTab(experimentDetails, isAdmin));

                // QUANTITATION TYPES TAB
                this.add(new Gemma.ExpressionExperimentQuantitationTypeGrid({
                            title : 'Quantitation Types',
                            itemId : 'quantitation',
                            eeid : experimentDetails.id
                        }));

                this.adjustForIsAdmin(isAdmin, this.editable);

            },
            makeDetailsTab : function(experimentDetails) {
                return new Gemma.ExpressionExperimentDetails({
                            title : 'Details',
                            itemId : 'details',
                            id : 'ee-details-panel',
                            experimentDetails : experimentDetails,
                            editable : this.editable,
                            owned : this.ownedByCurrentUser,
                            admin : this.admin,
                            listeners : {
                                'experimentDetailsReloadRequired' : function() {
                                    var myMask = new Ext.LoadMask(Ext.getBody(), {
                                                msg : "Refreshing..."
                                            });
                                    myMask.show();
                                    window.location.reload(false); // could do something fancier like reloading just
                                                                    // the component
                                },
                                scope : this
                            }
                        });
            },
            makeDesignTab : function(experimentDetails) {
                var batchInfo = '';
                if (experimentDetails.hasBatchInformation) {
                    batchInfo = 'This experimental design also '
                            + 'has information on batches, not shown.' + '
'
                            + ' ' + experimentDetails.batchConfound
                            + ' ' + ' '
                            + experimentDetails.batchEffect + ' ';
                }

                return {
                    title : 'Experimental Design',
                    tbar : [{
                        text : 'Show Details',
                        itemId : 'design',
                        tooltip : 'Go to the design details',
                        icon : '/Gemma/images/magnifier.png',
                        handler : function() {
                            window.open("/Gemma/experimentalDesign/showExperimentalDesign.html?eeid="
                                    + experimentDetails.id);
                        }
                    }],
                    html : batchInfo + '
Loading...
',
                    layout : 'absolute',
                    // items -> bar chart and table?
                    listeners : {
                        render : function() {
                            DesignMatrix.init({
                                        id : experimentDetails.id
                                    });
                        }
                    }
                };
            },
            makeVisualisationTab : function(experimentDetails, isAdmin) {
                var eeId = this.eeId;
                var title = "Data for a 'random' sampling of probes";
                var downloadLink = '';
                var geneList = [];
                downloadLink = String.format("/Gemma/dedv/downloadDEDV.html?ee={0}", eeId);
                var viz = new Gemma.VisualizationWithThumbsPanel({
                            thumbnails : false,
                            downloadLink : downloadLink,
                            params : [[eeId], geneList]
                        });
                viz.on('render', function() {
                            viz.loadFromParam({
                                        params : [[eeId], geneList]
                                    });
                        });
                var geneTBar = new Gemma.VisualizationWidgetGeneSelectionToolbar({
                            eeId : eeId,
                            visPanel : viz,
                            taxonId : experimentDetails.parentTaxonId,
                            showRefresh : (isAdmin || this.editable)
                        });
                geneTBar.on('refreshVisualisation', function() {
                            viz.loadFromParam({
                                        params : [[eeId], geneList]
                                    });
                        });
                return {
                    items : viz,
                    itemId : 'visualize',
                    layout : 'fit',
                    padding : 0,
                    title : 'Visualize Expression',
                    tbar : geneTBar
                };
            },
            makeDiagnosticsTab : function(experimentDetails, isAdmin) {

                var refreshDiagnosticsLink = '';
                if (this.editable || isAdmin) {
                    refreshDiagnosticsLink = 'Refresh
';
                }
                this.refreshDiagnosticsBtn = new Ext.Button({
                            icon : '/Gemma/images/icons/arrow_refresh_small.png',
                            text : 'Refresh',
                            handler : function() {
                                window.location = "refreshCorrMatrix.html?id=" + experimentDetails.id;
                            },
                            hidden : (this.editable || isAdmin)
                        });
                return {
                    title : 'Diagnostics',
                    itemId : 'diagnostics',
                    items : [this.refreshDiagnosticsBtn, {
                                html : experimentDetails.QChtml,
                                border : false
                            }]
                };
            },
            adjustForIsAdmin : function(isAdmin, isEditable) {
                // hide/show 'refresh' link to diagnostics tab
                this.refreshDiagnosticsBtn.setVisible(isAdmin || isEditable);

                /* HISTORY TAB */
                if ((isAdmin || isEditable) && !this.historyTab) {
                    this.historyTab = new Gemma.AuditTrailGrid({
                                title : 'History',
                                itemId : 'history',
                                bodyBorder : false,
                                collapsible : false,
                                viewConfig : {
                                    forceFit : true
                                },
                                auditable : {
                                    id : this.experimentDetails.id,
                                    classDelegatingFor : "ubic.gemma.model.expression.experiment.ExpressionExperimentImpl"
                                },
                                loadOnlyOnRender : true
                            });
                    this.add(this.historyTab);
                } else if (this.historyTab) {
                    this.historyTab.setVisible((isAdmin || isEditable));
                }

                /* ADMIN TOOLS TAB */
                if ((isAdmin || isEditable) && !this.toolTab) {
                    this.toolTab = new Gemma.ExpressionExperimentTools({
                                experimentDetails : this.experimentDetails,
                                title : 'Admin',
                                itemId : 'admin',
                                editable : isEditable,
                                listeners : {
                                    'reloadNeeded' : function() {
                                        var myMask = new Ext.LoadMask(Ext.getBody(), {
                                                    msg : "Refreshing..."
                                                });
                                        myMask.show();
                                        var reloadToAdminTab = document.URL;
                                        reloadToAdminTab = reloadToAdminTab.replace(/&*tab=\w*/, '');
                                        reloadToAdminTab += '&tab=admin';
                                        window.location.href = reloadToAdminTab;

                                    }
                                }
                            });
                    this.add(this.toolTab);
                } else if (this.toolTab) {
                    this.toolTab.setVisible((isAdmin || isEditable));
                }
            }
        });

/**
 * Used to make the correlation heatmap clickable. See ExperimentQCTag.java
 *
 * @param {Object} bigImageUrl
 */
var popupImage = function(url, width, height) {
    url = url + "&nocache=" + Math.floor(Math.random() * 1000);
    var b = new Ext.Window({
                modal : true,
                stateful : false,
                resizable : true,
                autoScroll : true,
                height : height, // or false.
                width : width || 200,
                padding : 10,
                html : ''
            });
    b.show();
};
<commit_msg>bug 3436, admin functions on experiment details page no longer appear.  Result of recent renaming of properties in value object<commit_after>Ext.namespace('Gemma');

/**
 *
 * Top level container for all sections of expression experiment info Sections are: 1. Details (has editing tools) 2.
 * Experimental design 3. Expression visualisation 4. Diagnostics 5. Quantitation Types ? 6. History (admin only) 7.
 * Admin (running analyses)
 *
 *
 * To open the page at a specific tab, include ?tab=[tabName] suffix in the URL. Tab names are each tab's itemId.
 *
 * @class Gemma.ExpressionExperimentPage
 * @extends Ext.TabPanel
 *
 */
Gemma.ExpressionExperimentPage = Ext.extend(Ext.TabPanel, {

            height : 600,
            defaults : {
                autoScroll : true,
                width : 850
            },
            initialTab : 'details',
            deferredRender : true,
            listeners : {
                'tabchange' : function(tabPanel, newTab) {
                    newTab.fireEvent('tabChanged');
                },
                'beforetabchange' : function(tabPanel, newTab, currTab) {
                    // if false is returned, tab isn't changed
                    if (currTab) {
                        return currTab.fireEvent('leavingTab');
                    }
                    return true;
                }
            },
            checkURLforInitialTab : function() {
                this.loadSpecificTab = (document.URL.indexOf("?") > -1 && (document.URL.indexOf("tab=") > -1));
                if (this.loadSpecificTab) {
                    var param = Ext.urlDecode(document.URL.substr(document.URL.indexOf("?") + 1));
                    if (param.tab) {
                        if (this.getComponent(param.tab) != undefined) {
                            this.initialTab = param.tab;
                        }
                    }
                }
            },
            initComponent : function() {

                var eeId = this.eeId;

                var isAdmin = Ext.get("hasAdmin").getValue() == 'true';

                Gemma.ExpressionExperimentPage.superclass.initComponent.call(this);
                this.on('render', function() {
                            if (!this.loadMask) {
                                this.loadMask = new Ext.LoadMask(this.getEl(), {
                                            msg : Gemma.StatusText.Loading.generic,
                                            msgCls : 'absolute-position-loading-mask ext-el-mask-msg x-mask-loading'
                                        });
                            }
                            this.loadMask.show();
                        });

                ExpressionExperimentController.loadExpressionExperimentDetails(eeId, function(experimentDetails) {
                            this.initFromExperimentValueObject(experimentDetails, isAdmin);

                            this.checkURLforInitialTab();
                            this.setActiveTab(this.initialTab);

                        }.createDelegate(this));

                Gemma.Application.currentUser.on("logIn", function(userName, isAdmin) {
                            var appScope = this;
                            ExpressionExperimentController.canCurrentUserEditExperiment(experimentDetails.id, {
                                        callback : function(editable) {
                                            // console.log(this);
                                            appScope.adjustForIsAdmin(isAdmin, editable);
                                        },
                                        scope : appScope
                                    });

                        }, this);

                Gemma.Application.currentUser.on("logOut", function() {

                            this.adjustForIsAdmin(false, false);

                        }, this);
            },
            initFromExperimentValueObject : function(experimentDetails, isAdmin) {

                this.experimentDetails = experimentDetails;
                this.editable = experimentDetails.currentUserHasWritePermission || isAdmin;
                this.ownedByCurrentUser = experimentDetails.currentUserIsOwner;

                if (this.loadMask) {
                    this.loadMask.hide();
                }

                // DETAILS TAB
                this.add(this.makeDetailsTab(experimentDetails));

                // EXPERIMENT DESIGN TAB

                this.add(this.makeDesignTab(experimentDetails));

                // VISUALISATION TAB
                this.add(this.makeVisualisationTab(experimentDetails, isAdmin));

                // DIAGNOSTICS TAB
                this.add(this.makeDiagnosticsTab(experimentDetails, isAdmin));

                // QUANTITATION TYPES TAB
                this.add(new Gemma.ExpressionExperimentQuantitationTypeGrid({
                            title : 'Quantitation Types',
                            itemId : 'quantitation',
                            eeid : experimentDetails.id
                        }));

                this.adjustForIsAdmin(isAdmin, this.editable);

            },
            makeDetailsTab : function(experimentDetails) {
                return new Gemma.ExpressionExperimentDetails({
                            title : 'Details',
                            itemId : 'details',
                            id : 'ee-details-panel',
                            experimentDetails : experimentDetails,
                            editable : this.editable,
                            owned : this.ownedByCurrentUser,
                            admin : this.admin,
                            listeners : {
                                'experimentDetailsReloadRequired' : function() {
                                    var myMask = new Ext.LoadMask(Ext.getBody(), {
                                                msg : "Refreshing..."
                                            });
                                    myMask.show();
                                    window.location.reload(false); // could do something fancier like reloading just
                                                                    // the component
                                },
                                scope : this
                            }
                        });
            },
            makeDesignTab : function(experimentDetails) {
                var batchInfo = '';
                if (experimentDetails.hasBatchInformation) {
                    batchInfo = 'This experimental design also '
                            + 'has information on batches, not shown.' + '
'
                            + ' ' + experimentDetails.batchConfound
                            + ' ' + ' '
                            + experimentDetails.batchEffect + ' ';
                }

                return {
                    title : 'Experimental Design',
                    tbar : [{
                        text : 'Show Details',
                        itemId : 'design',
                        tooltip : 'Go to the design details',
                        icon : '/Gemma/images/magnifier.png',
                        handler : function() {
                            window.open("/Gemma/experimentalDesign/showExperimentalDesign.html?eeid="
                                    + experimentDetails.id);
                        }
                    }],
                    html : batchInfo + '
Loading...
',
                    layout : 'absolute',
                    // items -> bar chart and table?
                    listeners : {
                        render : function() {
                            DesignMatrix.init({
                                        id : experimentDetails.id
                                    });
                        }
                    }
                };
            },
            makeVisualisationTab : function(experimentDetails, isAdmin) {
                var eeId = this.eeId;
                var title = "Data for a 'random' sampling of probes";
                var downloadLink = '';
                var geneList = [];
                downloadLink = String.format("/Gemma/dedv/downloadDEDV.html?ee={0}", eeId);
                var viz = new Gemma.VisualizationWithThumbsPanel({
                            thumbnails : false,
                            downloadLink : downloadLink,
                            params : [[eeId], geneList]
                        });
                viz.on('render', function() {
                            viz.loadFromParam({
                                        params : [[eeId], geneList]
                                    });
                        });
                var geneTBar = new Gemma.VisualizationWidgetGeneSelectionToolbar({
                            eeId : eeId,
                            visPanel : viz,
                            taxonId : experimentDetails.parentTaxonId,
                            showRefresh : (isAdmin || this.editable)
                        });
                geneTBar.on('refreshVisualisation', function() {
                            viz.loadFromParam({
                                        params : [[eeId], geneList]
                                    });
                        });
                return {
                    items : viz,
                    itemId : 'visualize',
                    layout : 'fit',
                    padding : 0,
                    title : 'Visualize Expression',
                    tbar : geneTBar
                };
            },
            makeDiagnosticsTab : function(experimentDetails, isAdmin) {

                var refreshDiagnosticsLink = '';
                if (this.editable || isAdmin) {
                    refreshDiagnosticsLink = 'Refresh
';
                }
                this.refreshDiagnosticsBtn = new Ext.Button({
                            icon : '/Gemma/images/icons/arrow_refresh_small.png',
                            text : 'Refresh',
                            handler : function() {
                                window.location = "refreshCorrMatrix.html?id=" + experimentDetails.id;
                            },
                            hidden : (this.editable || isAdmin)
                        });
                return {
                    title : 'Diagnostics',
                    itemId : 'diagnostics',
                    items : [this.refreshDiagnosticsBtn, {
                                html : experimentDetails.QChtml,
                                border : false
                            }]
                };
            },
            adjustForIsAdmin : function(isAdmin, isEditable) {
                // hide/show 'refresh' link to diagnostics tab
                this.refreshDiagnosticsBtn.setVisible(isAdmin || isEditable);

                /* HISTORY TAB */
                if ((isAdmin || isEditable) && !this.historyTab) {
                    this.historyTab = new Gemma.AuditTrailGrid({
                                title : 'History',
                                itemId : 'history',
                                bodyBorder : false,
                                collapsible : false,
                                viewConfig : {
                                    forceFit : true
                                },
                                auditable : {
                                    id : this.experimentDetails.id,
                                    classDelegatingFor : "ubic.gemma.model.expression.experiment.ExpressionExperimentImpl"
                                },
                                loadOnlyOnRender : true
                            });
                    this.add(this.historyTab);
                } else if (this.historyTab) {
                    this.historyTab.setVisible((isAdmin || isEditable));
                }

                /* ADMIN TOOLS TAB */
                if ((isAdmin || isEditable) && !this.toolTab) {
                    this.toolTab = new Gemma.ExpressionExperimentTools({
                                experimentDetails : this.experimentDetails,
                                title : 'Admin',
                                itemId : 'admin',
                                editable : isEditable,
                                listeners : {
                                    'reloadNeeded' : function() {
                                        var myMask = new Ext.LoadMask(Ext.getBody(), {
                                                    msg : "Refreshing..."
                                                });
                                        myMask.show();
                                        var reloadToAdminTab = document.URL;
                                        reloadToAdminTab = reloadToAdminTab.replace(/&*tab=\w*/, '');
                                        reloadToAdminTab += '&tab=admin';
                                        window.location.href = reloadToAdminTab;

                                    }
                                }
                            });
                    this.add(this.toolTab);
                } else if (this.toolTab) {
                    this.toolTab.setVisible((isAdmin || isEditable));
                }
            }
        });

/**
 * Used to make the correlation heatmap clickable. See ExperimentQCTag.java
 *
 * @param {Object} bigImageUrl
 */
var popupImage = function(url, width, height) {
    url = url + "&nocache=" + Math.floor(Math.random() * 1000);
    var b = new Ext.Window({
                modal : true,
                stateful : false,
                resizable : true,
                autoScroll : true,
                height : height, // or false.
                width : width || 200,
                padding : 10,
                html : ''
            });
    b.show();
};
<|endoftext|>


<commit_before>function draw(){
    if(key_left){
        rotation -= speed / 10 + 1;
    }
    if(key_right){
        rotation += speed / 10 + 1;
    }

    if(key_speedminus && speed > 0){
        speed -= 1;
    }
    if(key_speedplus){
        speed += 1;
    }

    var no_blink_fix = 1;
    do_split = 0;

    // move wall split location
    i = 3;
    do{
        wall_splits[i * 2] += wall_splits[i * 2] >= 0 ? speed : -speed;
        wall_splits[i * 2 + 1] += wall_splits[i * 2 + 1] >= 0 ? speed : -speed;

        // check if wall split reached edge of screen
        if(wall_splits[i * 2] < -x || wall_splits[i * 2] > x){
            // this temporary variable prevents blinking bug
            no_blink_fix = 0;

            // reset wall splits
            wall_splits[i * 2] = [
                -2,
                -2,
                 2,
                -2,
                -2,
                 2,
                 2,
                 2
            ][i * 2];
            wall_splits[i * 2 + 1] = [
                -2,
                -2,
                 2,
                -2,
                -2,
                 2,
                 2,
                 2
            ][i * 2 + 1];

            do_split = 1;
        }
    }while(i--);

    if(settings[5]){// clear?
        buffer.clearRect(
            0,
            0,
            width,
            height
        );
    }

    buffer.translate(
        x,
        y
    );
    buffer.rotate(rotation * (Math.PI / 180));

    // draw walls
    draw_walls(no_blink_fix);

    if(do_split){
        colors[1] = colors[0];
        colors[0] = [
            '#' + random_hex() + random_hex() + random_hex(),
            '#' + random_hex() + random_hex() + random_hex(),
            '#' + random_hex() + random_hex() + random_hex(),
            '#' + random_hex() + random_hex() + random_hex()
        ];
    }

    // undo rotate/translate
    buffer.rotate(-rotation * (Math.PI / 180));
    buffer.translate(
        -x,
        -y
    );

    // draw current speed
    buffer.font = '23pt sans-serif';
    buffer.textAlign = 'left';
    buffer.textBaseline = 'top';
    buffer.fillStyle = '#fff';
    buffer.fillText(
        speed + ' m/s',
        5,
        5
    );

    if(settings[5]){// clear?
        canvas.clearRect(
            0,
            0,
            width,
            height
        );
    }
    canvas.drawImage(
        get('buffer'),
        0,
        0
    );
}

function draw_walls(no_blink_fix){
    if(no_blink_fix){
        i = 3;
        do{
            buffer.beginPath();
            buffer.moveTo(
                0,
                0
            );
            buffer.lineTo(
                wall_splits[[0,0,2,4][i]],
                wall_splits[[1,1,3,5][i]]
            );
            buffer.lineTo(
                wall_splits[[2,4,6,6][i]],
                wall_splits[[3,5,7,7][i]]
            );
            buffer.closePath();
            buffer.fillStyle = colors[0][i];
            buffer.fill();
        }while(i--);
    }

    buffer.beginPath();
    buffer.moveTo(
        -x,
        -x
    );
    buffer.lineTo(
        wall_splits[0],
        wall_splits[1]
    );
    buffer.lineTo(
        wall_splits[2],
        wall_splits[3]
    );
    buffer.lineTo(
        x,
        -x
    );
    buffer.closePath();
    buffer.fillStyle = colors[no_blink_fix][0];
    buffer.fill();

    buffer.beginPath();
    buffer.moveTo(
        -x,
        -x
    );
    buffer.lineTo(
        wall_splits[0],
        wall_splits[1]
    );
    buffer.lineTo(
        wall_splits[4],
        wall_splits[5]
    );
    buffer.lineTo(
        -x,
        x
    );
    buffer.closePath();
    buffer.fillStyle = colors[no_blink_fix][1];
    buffer.fill();

    buffer.beginPath();
    buffer.moveTo(
        x,
        -x
    );
    buffer.lineTo(
        wall_splits[2],
        wall_splits[3]
    );
    buffer.lineTo(
        wall_splits[6],
        wall_splits[7]
    );
    buffer.lineTo(
        x,
        x
    );
    buffer.closePath();
    buffer.fillStyle = colors[no_blink_fix][2];
    buffer.fill();

    buffer.beginPath();
    buffer.moveTo(
        -x,
        x
    );
    buffer.lineTo(
        wall_splits[4],
        wall_splits[5]
    );
    buffer.lineTo(
        wall_splits[6],
        wall_splits[7]
    );
    buffer.lineTo(
        x,
        x
    );
    buffer.closePath();
    buffer.fillStyle = colors[no_blink_fix][3];
    buffer.fill();

    if(!no_blink_fix){
        i = 3;
        do{
            buffer.beginPath();
            buffer.moveTo(
                0,
                0
            );
            buffer.lineTo(
                wall_splits[[0,0,2,4][i]],
                wall_splits[[1,1,3,5][i]]
            );
            buffer.lineTo(
                wall_splits[[2,4,6,6][i]],
                wall_splits[[3,5,7,7][i]]
            );
            buffer.closePath();
            buffer.fillStyle = colors[1][i];
            buffer.fill();
        }while(i--);
    }
}

function get(i){
    return document.getElementById(i);
}

function random_hex(){
    return '0123456789abcdef'.charAt(Math.floor(Math.random() * 16));
}

function resize(){
    if(mode > 0){
        width = window.innerWidth;
        get('buffer').width = width;
        get('canvas').width = width;

        height = window.innerHeight;
        get('buffer').height = height;
        get('canvas').height = height;

        x = width / 2;
        y = height / 2;
    }
}

function save(){
    i = 1;
    do{
        j = [
            'audio-volume',
            'ms-per-frame'
        ][i];

        if(get(j).value == [1, 30][i] || isNaN(get(j).value) || get(j).value < [0, 1][i]){
            ls.removeItem('tubes-' + i);
            settings[i] = [
                1,
                30
            ][i];
            get(j).value = settings[i];

        }else{
            settings[i] = parseFloat(get(j).value);
            ls.setItem(
                'tubes-' + i,
                settings[i]
            );
        }
    }while(i--);

    i = 2;
    do{
        if(get(['movement-keys', 'key-slowdown', 'key-speedup'][i]).value == ['AD', 'S', 'W'][i]){
            ls.removeItem('tubes-' + (i + 2));
            settings[i + 2] = [
                'AD',
                'S',
                'W'
            ][i];

        }else{
            settings[i + 2] = get(['movement-keys', 'key-slowdown', 'key-speedup'][i]).value;
            ls.setItem(
                'tubes-' + (i + 2),
                settings[i + 2]
            );
        }
    }while(i--);

    settings[5] = get('clear').checked;
    if(settings[5]){
        ls.removeItem('tubes-5');

    }else{
        ls.setItem(
            'tubes-5',
            0
        );
    }
}

function setmode(newmode){
    clearInterval(interval);

    mode = newmode;

    // new game mode
    if(mode > 0){
        save();

        key_left = 0;
        key_right = 0;
        key_speedminus = 0;
        key_speedplus = 0;
        speed = 10;
        rotation = 0;

        get('page').innerHTML = '<canvas id=canvas></canvas>';

        buffer = get('buffer').getContext('2d');
        canvas = get('canvas').getContext('2d');

        resize();

        wall_splits = [
            -2,
            -2,
             2,
            -2,
            -2,
             2,
             2,
             2
        ];

        // set initial tube colors
        colors = [
            ['#f0f', '#06f', '#ff0', '#f60'],// initial
            ['#0f0', '#f00', '#00f', '#0ff']// first swap
        ];

        interval = setInterval('draw()', settings[1]);// milliseconds per frame

    // main menu mode
    }else{
        buffer = 0;
        canvas = 0;

        get('page').innerHTML = '

Tubes

SEIZURE WARNING!
FLASHING COLORS!

Make Mama Sick

<input disabled style=border:0 value=ESC>Main Menu
<input id=movement-keys maxlength=2 value='
            + settings[2] + '>Move ←→
<input id=key-slowdown maxlength=1 value='
            + settings[3] + '>Speed--
<input id=key-speedup maxlength=1 value='
            + settings[4] + '>Speed++

<input id=audio-volume max=1 min=0 step=.01 type=range value='
            + settings[0] + '>Audio
<input '
            + (settings[5] ? 'checked ' : '') + 'id=clear type=checkbox>Clear
<input id=ms-per-frame value='
            + settings[1] + '>ms/Frame
Reset Settings

';
    }
}

var buffer = 0;
var canvas = 0;
var colors = [];
var do_split = 0;
var height = 0;
var i = 0;
var interval = 0;
var j = 0;
var key_left = 0;
var key_right = 0;
var key_speedminus = 0;
var key_speedplus = 0;
var ls = window.localStorage;
var mode = 0;
var mx = 0;
var my = 0;
var px = 0;
var py = 0;
var rotation = 0;
var settings = [
    ls.getItem('tubes-0') === null ?    1 : parseFloat(ls.getItem('tubes-0')),// audio volume
    ls.getItem('tubes-1') === null ?   30 : parseInt(ls.getItem('tubes-1')),// milliseconds per frame
    ls.getItem('tubes-2') === null ? 'AD' : ls.getItem('tubes-2'),// movement keys
    ls.getItem('tubes-3') === null ?  'S' : ls.getItem('tubes-3'),// slowdown key
    ls.getItem('tubes-4') === null ?  'W' : ls.getItem('tubes-4'),// speedup key
    ls.getItem('tubes-5') === null// clear?
];
var speed = 0;
var wall_splits = [];
var width = 0;
var x = 0;
var y = 0;

setmode(0);

window.onkeydown = function(e){
    if(mode > 0){
        i = window.event ? event : e;
        i = i.charCode ? i.charCode : i.keyCode;

        if(String.fromCharCode(i) === settings[2][0]){
            key_left = 1;

        }else if(String.fromCharCode(i) === settings[2][1]){
            key_right = 1;

        }else if(String.fromCharCode(i) === settings[3]){
            key_speedminus = 1;

        }else if(String.fromCharCode(i) === settings[4]){
            key_speedplus = 1;

        }else if(i === 27){// ESC
            setmode(0);
        }
    }
};

window.onkeyup = function(e){
    i = window.event ? event : e;
    i = i.charCode ? i.charCode : i.keyCode;

    if(String.fromCharCode(i) === settings[2][0]){
        key_left = 0;

    }else if(String.fromCharCode(i) === settings[2][1]){
        key_right = 0;

    }else if(String.fromCharCode(i) === settings[3]){
        key_speedminus = 0;

    }else if(String.fromCharCode(i) === settings[4]){
        key_speedplus = 0;
    }
};

window.onresize = resize;
<commit_msg>cleaned up settings reset code, removed get() function<commit_after>function draw(){
    if(key_left){
        rotation -= speed / 10 + 1;
    }
    if(key_right){
        rotation += speed / 10 + 1;
    }

    if(key_speedminus && speed > 0){
        speed -= 1;
    }
    if(key_speedplus){
        speed += 1;
    }

    var no_blink_fix = 1;
    do_split = 0;

    // move wall split location
    i = 3;
    do{
        wall_splits[i * 2] += wall_splits[i * 2] >= 0 ? speed : -speed;
        wall_splits[i * 2 + 1] += wall_splits[i * 2 + 1] >= 0 ? speed : -speed;

        // check if wall split reached edge of screen
        if(wall_splits[i * 2] < -x || wall_splits[i * 2] > x){
            // this temporary variable prevents blinking bug
            no_blink_fix = 0;

            // reset wall splits
            wall_splits[i * 2] = [
                -2,
                -2,
                 2,
                -2,
                -2,
                 2,
                 2,
                 2
            ][i * 2];
            wall_splits[i * 2 + 1] = [
                -2,
                -2,
                 2,
                -2,
                -2,
                 2,
                 2,
                 2
            ][i * 2 + 1];

            do_split = 1;
        }
    }while(i--);

    if(settings[5]){// clear?
        buffer.clearRect(
            0,
            0,
            width,
            height
        );
    }

    buffer.translate(
        x,
        y
    );
    buffer.rotate(rotation * (Math.PI / 180));

    // draw walls
    draw_walls(no_blink_fix);

    if(do_split){
        colors[1] = colors[0];
        colors[0] = [
            '#' + random_hex() + random_hex() + random_hex(),
            '#' + random_hex() + random_hex() + random_hex(),
            '#' + random_hex() + random_hex() + random_hex(),
            '#' + random_hex() + random_hex() + random_hex()
        ];
    }

    // undo rotate/translate
    buffer.rotate(-rotation * (Math.PI / 180));
    buffer.translate(
        -x,
        -y
    );

    // draw current speed
    buffer.font = '23pt sans-serif';
    buffer.textAlign = 'left';
    buffer.textBaseline = 'top';
    buffer.fillStyle = '#fff';
    buffer.fillText(
        speed + ' m/s',
        5,
        5
    );

    if(settings[5]){// clear?
        canvas.clearRect(
            0,
            0,
            width,
            height
        );
    }
    canvas.drawImage(
        document.getElementById('buffer'),
        0,
        0
    );
}

function draw_walls(no_blink_fix){
    if(no_blink_fix){
        i = 3;
        do{
            buffer.beginPath();
            buffer.moveTo(
                0,
                0
            );
            buffer.lineTo(
                wall_splits[[0,0,2,4][i]],
                wall_splits[[1,1,3,5][i]]
            );
            buffer.lineTo(
                wall_splits[[2,4,6,6][i]],
                wall_splits[[3,5,7,7][i]]
            );
            buffer.closePath();
            buffer.fillStyle = colors[0][i];
            buffer.fill();
        }while(i--);
    }

    buffer.beginPath();
    buffer.moveTo(
        -x,
        -x
    );
    buffer.lineTo(
        wall_splits[0],
        wall_splits[1]
    );
    buffer.lineTo(
        wall_splits[2],
        wall_splits[3]
    );
    buffer.lineTo(
        x,
        -x
    );
    buffer.closePath();
    buffer.fillStyle = colors[no_blink_fix][0];
    buffer.fill();

    buffer.beginPath();
    buffer.moveTo(
        -x,
        -x
    );
    buffer.lineTo(
        wall_splits[0],
        wall_splits[1]
    );
    buffer.lineTo(
        wall_splits[4],
        wall_splits[5]
    );
    buffer.lineTo(
        -x,
        x
    );
    buffer.closePath();
    buffer.fillStyle = colors[no_blink_fix][1];
    buffer.fill();

    buffer.beginPath();
    buffer.moveTo(
        x,
        -x
    );
    buffer.lineTo(
        wall_splits[2],
        wall_splits[3]
    );
    buffer.lineTo(
        wall_splits[6],
        wall_splits[7]
    );
    buffer.lineTo(
        x,
        x
    );
    buffer.closePath();
    buffer.fillStyle = colors[no_blink_fix][2];
    buffer.fill();

    buffer.beginPath();
    buffer.moveTo(
        -x,
        x
    );
    buffer.lineTo(
        wall_splits[4],
        wall_splits[5]
    );
    buffer.lineTo(
        wall_splits[6],
        wall_splits[7]
    );
    buffer.lineTo(
        x,
        x
    );
    buffer.closePath();
    buffer.fillStyle = colors[no_blink_fix][3];
    buffer.fill();

    if(!no_blink_fix){
        i = 3;
        do{
            buffer.beginPath();
            buffer.moveTo(
                0,
                0
            );
            buffer.lineTo(
                wall_splits[[0,0,2,4][i]],
                wall_splits[[1,1,3,5][i]]
            );
            buffer.lineTo(
                wall_splits[[2,4,6,6][i]],
                wall_splits[[3,5,7,7][i]]
            );
            buffer.closePath();
            buffer.fillStyle = colors[1][i];
            buffer.fill();
        }while(i--);
    }
}

function random_hex(){
    return '0123456789abcdef'.charAt(Math.floor(Math.random() * 16));
}

function reset(){
    if(confirm('Reset settings?')){
        document.getElementById('audio-volume').value = 1;
        document.getElementById('clear').checked = 1;
        document.getElementById('key-slowdown').value = 'S';
        document.getElementById('key-speedup').value = 'W';
        document.getElementById('movement-keys').value = 'AD';
        document.getElementById('ms-per-frame').value = 30;
        save();
    }
}

function resize(){
    if(mode > 0){
        width = window.innerWidth;
        document.getElementById('buffer').width = width;
        document.getElementById('canvas').width = width;

        height = window.innerHeight;
        document.getElementById('buffer').height = height;
        document.getElementById('canvas').height = height;

        x = width / 2;
        y = height / 2;
    }
}

function save(){
    i = 1;
    do{
        j = [
            'audio-volume',
            'ms-per-frame'
        ][i];

        if(document.getElementById(j).value == [1, 30][i] || isNaN(document.getElementById(j).value) || document.getElementById(j).value < [0, 1][i]){
            ls.removeItem('tubes-' + i);
            settings[i] = [
                1,
                30
            ][i];
            document.getElementById(j).value = settings[i];

        }else{
            settings[i] = parseFloat(document.getElementById(j).value);
            ls.setItem(
                'tubes-' + i,
                settings[i]
            );
        }
    }while(i--);

    i = 2;
    do{
        if(document.getElementById(['movement-keys', 'key-slowdown', 'key-speedup'][i]).value == ['AD', 'S', 'W'][i]){
            ls.removeItem('tubes-' + (i + 2));
            settings[i + 2] = [
                'AD',
                'S',
                'W'
            ][i];

        }else{
            settings[i + 2] = document.getElementById(['movement-keys', 'key-slowdown', 'key-speedup'][i]).value;
            ls.setItem(
                'tubes-' + (i + 2),
                settings[i + 2]
            );
        }
    }while(i--);

    settings[5] = document.getElementById('clear').checked;
    if(settings[5]){
        ls.removeItem('tubes-5');

    }else{
        ls.setItem(
            'tubes-5',
            0
        );
    }
}

function setmode(newmode){
    clearInterval(interval);

    mode = newmode;

    // new game mode
    if(mode > 0){
        save();

        key_left = 0;
        key_right = 0;
        key_speedminus = 0;
        key_speedplus = 0;
        speed = 10;
        rotation = 0;

        document.getElementById('page').innerHTML = '<canvas id=canvas></canvas>';

        buffer = document.getElementById('buffer').getContext('2d');
        canvas = document.getElementById('canvas').getContext('2d');

        resize();

        wall_splits = [
            -2,
            -2,
             2,
            -2,
            -2,
             2,
             2,
             2
        ];

        // set initial tube colors
        colors = [
            ['#f0f', '#06f', '#ff0', '#f60'],// initial
            ['#0f0', '#f00', '#00f', '#0ff']// first swap
        ];

        interval = setInterval('draw()', settings[1]);// milliseconds per frame

    // main menu mode
    }else{
        buffer = 0;
        canvas = 0;

        document.getElementById('page').innerHTML = '

Tubes

SEIZURE WARNING!
FLASHING COLORS!

Make Mama Sick

<input disabled style=border:0 value=ESC>Main Menu
<input id=movement-keys maxlength=2 value='
            + settings[2] + '>Move ←→
<input id=key-slowdown maxlength=1 value='
            + settings[3] + '>Speed--
<input id=key-speedup maxlength=1 value='
            + settings[4] + '>Speed++

<input id=audio-volume max=1 min=0 step=.01 type=range value='
            + settings[0] + '>Audio
<input '
            + (settings[5] ? 'checked ' : '') + 'id=clear type=checkbox>Clear
<input id=ms-per-frame value='
            + settings[1] + '>ms/Frame
Reset Settings

';
    }
}

var buffer = 0;
var canvas = 0;
var colors = [];
var do_split = 0;
var height = 0;
var i = 0;
var interval = 0;
var j = 0;
var key_left = 0;
var key_right = 0;
var key_speedminus = 0;
var key_speedplus = 0;
var ls = window.localStorage;
var mode = 0;
var mx = 0;
var my = 0;
var px = 0;
var py = 0;
var rotation = 0;
var settings = [
    ls.getItem('tubes-0') === null ?    1 : parseFloat(ls.getItem('tubes-0')),// audio volume
    ls.getItem('tubes-1') === null ?   30 : parseInt(ls.getItem('tubes-1')),// milliseconds per frame
    ls.getItem('tubes-2') === null ? 'AD' : ls.getItem('tubes-2'),// movement keys
    ls.getItem('tubes-3') === null ?  'S' : ls.getItem('tubes-3'),// slowdown key
    ls.getItem('tubes-4') === null ?  'W' : ls.getItem('tubes-4'),// speedup key
    ls.getItem('tubes-5') === null// clear?
];
var speed = 0;
var wall_splits = [];
var width = 0;
var x = 0;
var y = 0;

setmode(0);

window.onkeydown = function(e){
    if(mode > 0){
        i = window.event ? event : e;
        i = i.charCode ? i.charCode : i.keyCode;

        if(String.fromCharCode(i) === settings[2][0]){
            key_left = 1;

        }else if(String.fromCharCode(i) === settings[2][1]){
            key_right = 1;

        }else if(String.fromCharCode(i) === settings[3]){
            key_speedminus = 1;

        }else if(String.fromCharCode(i) === settings[4]){
            key_speedplus = 1;

        }else if(i === 27){// ESC
            setmode(0);
        }
    }
};

window.onkeyup = function(e){
    i = window.event ? event : e;
    i = i.charCode ? i.charCode : i.keyCode;

    if(String.fromCharCode(i) === settings[2][0]){
        key_left = 0;

    }else if(String.fromCharCode(i) === settings[2][1]){
        key_right = 0;

    }else if(String.fromCharCode(i) === settings[3]){
        key_speedminus = 0;

    }else if(String.fromCharCode(i) === settings[4]){
        key_speedplus = 0;
    }
};

window.onresize = resize;
<|endoftext|>


<commit_before>$(function(){
  $('.content-header .right-btns a').removeClass('btn').removeClass('btn-primary').removeClass('btn-danger').removeClass('btn-default');
});<commit_msg>remove unused code<commit_after>$(function(){
});
<|endoftext|>


<commit_before>var feature_flags = (function () {

var exports = {};

// Helpers
var internal_24_hour_people= _.contains([],
    page_params.email);

var zulip_mit_emails = [];
var is_zulip_mit_user = _.contains(zulip_mit_emails, page_params.email);

var iceland = page_params.domain === 'customer8.invalid';

var customer4_realms = [
  'customer4.invalid',
  'users.customer4.invalid'
];
var is_customer4 = _.contains(customer4_realms, page_params.domain);

// Manually-flipped debugging flags
exports.log_send_times = false;

// Permanent realm-specific stuff:

exports.twenty_four_hour_time = internal_24_hour_people || iceland;

exports.dropbox_integration = page_params.staging || _.contains(['dropbox.com'], page_params.domain);

exports.mandatory_topics = _.contains([
    'customer7.invalid'
    ],
    page_params.domain
);

exports.left_side_userlist = page_params.staging ||
  _.contains(['customer7.invalid'], page_params.domain);

// Still very beta:
exports.fade_users_when_composing = page_params.staging || is_customer4;
exports.use_socket = page_params.staging;

// Still burning in...
exports.mark_read_at_bottom = true;
exports.summarize_read_while_narrowed = true;
exports.propagate_topic_edits = true;

// Ready for deprecation.
exports.collapsible = false;

exports.single_message_narrowing = page_params.staging || ('customer12.invalid' === page_params.domain);
return exports;

}());
<commit_msg>Temporarily disable sockjs in local dev instances<commit_after>var feature_flags = (function () {

var exports = {};

// Helpers
var internal_24_hour_people= _.contains([],
    page_params.email);

var zulip_mit_emails = [];
var is_zulip_mit_user = _.contains(zulip_mit_emails, page_params.email);

var iceland = page_params.domain === 'customer8.invalid';

var customer4_realms = [
  'customer4.invalid',
  'users.customer4.invalid'
];
var is_customer4 = _.contains(customer4_realms, page_params.domain);

// Manually-flipped debugging flags
exports.log_send_times = false;

// Permanent realm-specific stuff:

exports.twenty_four_hour_time = internal_24_hour_people || iceland;

exports.dropbox_integration = page_params.staging || _.contains(['dropbox.com'], page_params.domain);

exports.mandatory_topics = _.contains([
    'customer7.invalid'
    ],
    page_params.domain
);

exports.left_side_userlist = page_params.staging ||
  _.contains(['customer7.invalid'], page_params.domain);

// Still very beta:
exports.fade_users_when_composing = page_params.staging || is_customer4;
exports.use_socket = page_params.staging && ! page_params.debug_mode;

// Still burning in...
exports.mark_read_at_bottom = true;
exports.summarize_read_while_narrowed = true;
exports.propagate_topic_edits = true;

// Ready for deprecation.
exports.collapsible = false;

exports.single_message_narrowing = page_params.staging || ('customer12.invalid' === page_params.domain);
return exports;

}());
<|endoftext|>


<commit_before><commit_msg>added t=rt parameter for realtime<commit_after><|endoftext|>