<commit_before>if (!customValidators) {

    console.log("Cannot define validator validateCnsaTreatment()", new Date());

} else {
    customValidators.validateCnsaCervicalTreatment = function(viewValue, form, model) {

        var fieldId = form.fieldId;
        var element_ids;

        if (!(model.toggle_anterior_approach || model.toggle_posterior_approach)) {
          return {
            // top form level validation
            custom: true,
            valid: false,
            error: {
              code: 'no_aa_pa'
            }
          }
        }

        if (model.toggle_anterior_approach) {
          // all validation for anterior approach nested under here

          if (!(model.toggle_aa_discectomy || model.toggle_aa_corpectomy)) {
            return {
              custom: true,
              valid: false,
              error: {
                code: 'aa_no_disc_corp',
                element_ids: ['field-toggle_anterior_approach-' + fieldId]
              },
              rootScopeBroadCast: true
            }
          }

          if (model.toggle_aa_discectomy) {
            if (!(
              model.toggle_aa_discectomy_c2c3 ||
              model.toggle_aa_discectomy_c3c4 ||
              model.toggle_aa_discectomy_c4c5 ||
              model.toggle_aa_discectomy_c5c6 ||
              model.toggle_aa_discectomy_c6c7 ||
              model.toggle_aa_discectomy_c7t1
            )) {
              return {
                custom: true,
                valid: false,
                error: {
                  code: 'aa_disc_levels',
                  element_ids: ['field-toggle_aa_discectomy-' + fieldId]
                },
                rootScopeBroadCast: true
              }
            }

            var discectomyLevels = [
              'c2c3',
              'c3c4',
              'c4c5',
              'c5c6',
              'c6c7',
              'c7t1'
            ];

            var missingElementIds = [];

            for (var i = 0; i < discectomyLevels.length; i++) {
              const level = discectomyLevels[i];

              if (model['toggle_aa_discectomy_' + level]) {
                if (model['aa_discectomy_' + level + '_procedure'] === null) {
                  missingElementIds.push('field-aa_discectomy_' + level + '_procedure-' + fieldId);
                } else if (model['aa_discectomy_' + level + '_procedure'] == 1) {
                  // ACDF procedure was selected
                  if (model['aa_acdf_' + level + '_material'] === null) {
                    missingElementIds.push('field-aa_acdf_' + level + '_material-' + fieldId);
                  }
                  if (model['aa_acdf_' + level + '_type'] === null) {
                    missingElementIds.push('field-aa_acdf_' + level + '_type-' + fieldId);
                  }
                  if (model['aa_acdf_' + level + '_companyName'] === null || model['aa_acdf_' + level + '_companyName'] == '') {
                    missingElementIds.push('field-aa_acdf_' + level + '_companyName-' + fieldId);
                  }
                }
              }
            }

            if (missingElementIds.length > 0) {
              return {
                custom: true,
                valid: false,
                error: {
                  code: 0,
                  element_ids: missingElementIds
                },
                rootScopeBroadCast: true
              }
            }
          }

          if (model.toggle_aa_corpectomy) {
            if (!(
              model.toggle_aa_corpectomy_c2 ||
              model.toggle_aa_corpectomy_c3 ||
              model.toggle_aa_corpectomy_c4 ||
              model.toggle_aa_corpectomy_c5 ||
              model.toggle_aa_corpectomy_c6 ||
              model.toggle_aa_corpectomy_c7 ||
              model.toggle_aa_corpectomy_t1
            )) {
              return {
                custom: true,
                valid: false,
                error: {
                  code: 'aa_corp_levels',
                  element_ids: ['field-toggle_aa_corpectomy-' + fieldId]
                },
                rootScopeBroadCast: true
              }
            }

            var corpectomyLevels = [
              'c2',
              'c3',
              'c4',
              'c5',
              'c6',
              'c7',
              't1'
            ];

            var missingElementIds = [];

            for (var i = 0; i < corpectomyLevels.length; i++) {
              const level = corpectomyLevels[i];

              if (model['toggle_aa_corpectomy_' + level]) {
                if (model['aa_corpectomy_' + level + '_material'] === null) {
                  missingElementIds.push('field-aa_corpectomy_' + level + '_material-' + fieldId);
                }
                if (model['aa_corpectomy_' + level + '_type'] === null) {
                  missingElementIds.push('field-aa_corpectomy_' + level + '_type-' + fieldId);
                }
                if (model['aa_corpectomy_' + level + '_companyName'] === null || model['aa_corpectomy_' + level + '_companyName'] == '') {
                  missingElementIds.push('field-aa_corpectomy_' + level + '_companyName-' + fieldId);
                }
              }
            }

            if (missingElementIds.length > 0) {
              return {
                custom: true,
                valid: false,
                error: {
                  code: 0,
                  element_ids: missingElementIds
                },
                rootScopeBroadCast: true
              }
            }
          }
        }

        if (model.toggle_posterior_approach) {
          // all logic for posterior approach nested under here

          if (model.toggle_neural_decomp === null) {
            return {
              custom: true,
              valid: false,
              error: {
                code: 'nd',
                element_ids: ['field-toggle_neural_decomp-' + fieldId]
              },
              rootScopeBroadCast: true
            }
          }

          if (model.toggle_neural_decomp == 1) {
            // neural decompression was marked 'Yes'
            var missingNDElementIds = [];

            if (model.nd_open === null) {
              missingNDElementIds.push('field-nd_open-' + fieldId);
            }
            if (model.nd_procedure === null) {
              missingNDElementIds.push('field-nd_procedure-' + fieldId);
            }

            if (missingNDElementIds.length > 0) {
              return {
                custom: true,
                valid: false,
                error: {
                  code: 0,
                  element_ids: missingNDElementIds
                },
                rootScopeBroadCast: true
              }
            }

            if (!(
              model.toggle_nd_occip ||
              model.toggle_nd_c1 ||
              model.toggle_nd_c2 ||
              model.toggle_nd_c3 ||
              model.toggle_nd_c4 ||
              model.toggle_nd_c5 ||
              model.toggle_nd_c6 ||
              model.toggle_nd_c7 ||
              model.toggle_nd_c8 ||
              model.toggle_nd_t1 ||
              model.toggle_nd_t2 ||
              model.toggle_nd_t3
            )) {
              return {
                custom: true,
                valid: false,
                error: {
                  code: 'nd_levels',
                  element_ids: [ 'field-toggle_neural_decomp-' + fieldId ]
                },
                rootScopeBroadCast: true
              };
            }

            var neuralDecompLevels = [
              'occip',
              'c1',
              'c2',
              'c3',
              'c4',
              'c5',
              'c6',
              'c7',
              'c8',
              't1',
              't2',
              't3'
            ];

            var missingNDSideElementIds = [];

            for (var i = 0; i < neuralDecompLevels.length; i++) {
              const level = neuralDecompLevels[i];

              if (model['toggle_nd_' + level]) {
                if (model['nd_' + level + '_side'] === null) {
                  missingNDSideElementIds.push('field-nd_' + level + '_side-' + fieldId);
                }
              }
            }

            if (missingNDSideElementIds.length > 0) {
              return {
                custom: true,
                valid: false,
                error: {
                  code: 0,
                  element_ids: missingNDSideElementIds
                },
                rootScopeBroadCast: true
              }
            }
          } else if (model.toggle_neural_decomp == 0) {
            // neural decompression was marked 'No'
            if (!model.toggle_arthrodesis) {
              return {
                custom: true,
                valid: false,
                error: {
                  code: 'post_app_no_nd_no_pa',
                  element_ids: ['field-toggle_arthrodesis-' + fieldId]
                },
                rootScopeBroadCast: true
              }
            }

            if (!(
              model.toggle_pa_occipc1 ||
              model.toggle_pa_c1c2 ||
              model.toggle_pa_c2c3 ||
              model.toggle_pa_c3c4 ||
              model.toggle_pa_c4c5 ||
              model.toggle_pa_c5c6 ||
              model.toggle_pa_c6c7 ||
              model.toggle_pa_c7t1 ||
              model.toggle_pa_t1t2 ||
              model.toggle_pa_t2t3 ||
              model.toggle_pa_t3t4
            )) {
              return {
                custom: true,
                valid: false,
                error: {
                    code: 'pa',
                    element_ids: [ 'field-toggle_arthrodesis-' + fieldId ]
                },
                rootScopeBroadCast: true
              };
            }

            var missingPAElementIds = [];

            if (model.pa_fixation_co_name === null || model.pa_fixation_co_name == '') {
              missingPAElementIds.push('field-pa_fixation_co_name-' + fieldId);
            }

            if (missingPAElementIds.length > 0) {
              return {
                custom: true,
                valid: false,
                error: {
                  code: 0,
                  element_ids: missingPAElementIds
                },
                rootScopeBroadCast: true
              }
            }
          }
        }

        return {
            valid: true
        };
    };
}
<commit_msg>update cervical treatment validation<commit_after>if (!customValidators) {
  console.log("Cannot define validator validateCnsaTreatment()", new Date());
} else {
  customValidators.validateCnsaCervicalTreatment = function(viewValue, form, model) {
    var fieldId = form.fieldId;
    var element_ids;

    if (!(model.toggle_anterior_approach || model.toggle_posterior_approach)) {
      return {
        // top form level validation
        custom: true,
        valid: false,
        error: {
          code: 'no_aa_pa'
        }
      }
    }

    if (model.toggle_anterior_approach) {
      // all validation for anterior approach nested under here

      if (!(model.toggle_aa_discectomy || model.toggle_aa_corpectomy)) {
        return {
          custom: true,
          valid: false,
          error: {
            code: 'aa_no_disc_corp',
            element_ids: ['field-toggle_anterior_approach-' + fieldId]
          },
          rootScopeBroadCast: true
        }
      }

      if (model.toggle_aa_discectomy) {
        if (!(
          model.toggle_aa_discectomy_c2c3 ||
          model.toggle_aa_discectomy_c3c4 ||
          model.toggle_aa_discectomy_c4c5 ||
          model.toggle_aa_discectomy_c5c6 ||
          model.toggle_aa_discectomy_c6c7 ||
          model.toggle_aa_discectomy_c7t1
        )) {
          return {
            custom: true,
            valid: false,
            error: {
              code: 'aa_disc_levels',
              element_ids: ['field-toggle_aa_discectomy-' + fieldId]
            },
            rootScopeBroadCast: true
          }
        }

        if (model['aa_discectomy_procedure'] === null) {
          return {
            custom: true,
            valid: false,
            error: {
              code: 0,
              element_ids: ['field-aa_discectomy_procedure-' + fieldId]
            },
            rootScopeBroadCast: true
          }
        }

        var missingElementIds = [];

        if ((model['aa_discectomy_' + level + '_procedure'] == 1) {
          // ACDF procedure was selected
          if (model['aa_acdf_material'] === null) {
            missingElementIds.push('field-aa_acdf_material-' + fieldId);
          }
          if (model['aa_acdf_type'] === null) {
            missingElementIds.push('field-aa_acdf_type-' + fieldId);
          }
          if (model['aa_acdf_companyName'] === null || model['aa_acdf_companyName'] == '') {
            missingElementIds.push('field-aa_acdf_companyName-' + fieldId);
          }
        }

        if (missingElementIds.length > 0) {
          return {
            custom: true,
            valid: false,
            error: {
              code: 0,
              element_ids: missingElementIds
            },
            rootScopeBroadCast: true
          }
        }
      }

      if (model.toggle_aa_corpectomy) {
        if (!(
          model.toggle_aa_corpectomy_c2 ||
          model.toggle_aa_corpectomy_c3 ||
          model.toggle_aa_corpectomy_c4 ||
          model.toggle_aa_corpectomy_c5 ||
          model.toggle_aa_corpectomy_c6 ||
          model.toggle_aa_corpectomy_c7 ||
          model.toggle_aa_corpectomy_t1
        )) {
          return {
            custom: true,
            valid: false,
            error: {
              code: 'aa_corp_levels',
              element_ids: ['field-toggle_aa_corpectomy-' + fieldId]
            },
            rootScopeBroadCast: true
          }
        }

        var corpectomyLevels = [
          'c2',
          'c3',
          'c4',
          'c5',
          'c6',
          'c7',
          't1'
        ];

        var missingElementIds = [];

        for (var i = 0; i < corpectomyLevels.length; i++) {
          const level = corpectomyLevels[i];

          if (model['toggle_aa_corpectomy_' + level]) {
            if (model['aa_corpectomy_' + level + '_material'] === null) {
              missingElementIds.push('field-aa_corpectomy_' + level + '_material-' + fieldId);
            }
            if (model['aa_corpectomy_' + level + '_type'] === null) {
              missingElementIds.push('field-aa_corpectomy_' + level + '_type-' + fieldId);
            }
            if (model['aa_corpectomy_' + level + '_companyName'] === null || model['aa_corpectomy_' + level + '_companyName'] == '') {
              missingElementIds.push('field-aa_corpectomy_' + level + '_companyName-' + fieldId);
            }
          }
        }

        if (missingElementIds.length > 0) {
          return {
            custom: true,
            valid: false,
            error: {
              code: 0,
              element_ids: missingElementIds
            },
            rootScopeBroadCast: true
          }
        }
      }
    }

    if (model.toggle_posterior_approach) {
      // all logic for posterior approach nested under here

      if (model.toggle_neural_decomp === null) {
        return {
          custom: true,
          valid: false,
          error: {
            code: 'nd',
            element_ids: ['field-toggle_neural_decomp-' + fieldId]
          },
          rootScopeBroadCast: true
        }
      }

      if (model.toggle_neural_decomp == 1) {
        // neural decompression was marked 'Yes'
        var missingNDElementIds = [];

        if (model.nd_open === null) {
          missingNDElementIds.push('field-nd_open-' + fieldId);
        }
        if (model.nd_procedure === null) {
          missingNDElementIds.push('field-nd_procedure-' + fieldId);
        }

        if (missingNDElementIds.length > 0) {
          return {
            custom: true,
            valid: false,
            error: {
              code: 0,
              element_ids: missingNDElementIds
            },
            rootScopeBroadCast: true
          }
        }

        if (!(
          model.toggle_nd_occip ||
          model.toggle_nd_c1 ||
          model.toggle_nd_c2 ||
          model.toggle_nd_c3 ||
          model.toggle_nd_c4 ||
          model.toggle_nd_c5 ||
          model.toggle_nd_c6 ||
          model.toggle_nd_c7 ||
          model.toggle_nd_c8 ||
          model.toggle_nd_t1 ||
          model.toggle_nd_t2 ||
          model.toggle_nd_t3
        )) {
          return {
            custom: true,
            valid: false,
            error: {
              code: 'nd_levels',
              element_ids: [ 'field-toggle_neural_decomp-' + fieldId ]
            },
            rootScopeBroadCast: true
          };
        }

        var neuralDecompLevels = [
          'occip',
          'c1',
          'c2',
          'c3',
          'c4',
          'c5',
          'c6',
          'c7',
          'c8',
          't1',
          't2',
          't3'
        ];

        var missingNDSideElementIds = [];

        for (var i = 0; i < neuralDecompLevels.length; i++) {
          const level = neuralDecompLevels[i];

          if (model['toggle_nd_' + level]) {
            if (model['nd_' + level + '_side'] === null) {
              missingNDSideElementIds.push('field-nd_' + level + '_side-' + fieldId);
            }
          }
        }

        if (missingNDSideElementIds.length > 0) {
          return {
            custom: true,
            valid: false,
            error: {
              code: 0,
              element_ids: missingNDSideElementIds
            },
            rootScopeBroadCast: true
          }
        }
      } else if (model.toggle_neural_decomp == 0) {
        // neural decompression was marked 'No'
        if (!model.toggle_arthrodesis) {
          return {
            custom: true,
            valid: false,
            error: {
              code: 'post_app_no_nd_no_pa',
              element_ids: ['field-toggle_arthrodesis-' + fieldId]
            },
            rootScopeBroadCast: true
          }
        }

        if (!(
          model.toggle_pa_occipc1 ||
          model.toggle_pa_c1c2 ||
          model.toggle_pa_c2c3 ||
          model.toggle_pa_c3c4 ||
          model.toggle_pa_c4c5 ||
          model.toggle_pa_c5c6 ||
          model.toggle_pa_c6c7 ||
          model.toggle_pa_c7t1 ||
          model.toggle_pa_t1t2 ||
          model.toggle_pa_t2t3 ||
          model.toggle_pa_t3t4
        )) {
          return {
            custom: true,
            valid: false,
            error: {
                code: 'pa',
                element_ids: [ 'field-toggle_arthrodesis-' + fieldId ]
            },
            rootScopeBroadCast: true
          };
        }

        var missingPAElementIds = [];

        if (model.pa_fixation_co_name === null || model.pa_fixation_co_name == '') {
          missingPAElementIds.push('field-pa_fixation_co_name-' + fieldId);
        }

        if (missingPAElementIds.length > 0) {
          return {
            custom: true,
            valid: false,
            error: {
              code: 0,
              element_ids: missingPAElementIds
            },
            rootScopeBroadCast: true
          }
        }
      }
    }

    return {
      valid: true
    };
  };
}
<|endoftext|>


<commit_before><commit_msg>Moved paramToQuery to a common Spider function.<commit_after><|endoftext|>


<commit_before>'use strict';

// TODO: Restructure module to return object

var dgram = require('dgram');
var osc = require('osc-min');
var EventEmitter = require('events').EventEmitter;

var oscSender, oscReceiver;

exports.outgoingPort = 7000;
exports.incomingPort = 7001;
exports.outgoingHost = 'localhost';

// Incoming message handler
function incomingMessageHandler(msg, rinfo) {
  var oscFromBuffer = osc.fromBuffer(msg, false);

  // Emit incoming message event with data
  exports.eventEmitter.emit('oscMessageReceived', oscFromBuffer);
}

// Create listener socket
function createOSCReceiver(callback) {
  setTimeout(function() {

    // Create socket and bind to port
    oscReceiver = dgram.createSocket('udp4');
    oscReceiver.bind(exports.incomingPort, function() {

      // Attach incoming message handler callback
      oscReceiver.on('message', incomingMessageHandler);

      if (typeof callback === 'function') {
        callback();
      }
    });
  }, 0);
}

// Main initialization
exports.init = function(callback) {
  setTimeout(function createSocket() {

    // Open outgoing socket
    oscSender = dgram.createSocket('udp4');

    // Open incoming socket
    createOSCReceiver(callback);

  }, 0);
};

// Consumers of this module can listen here for OSC-related events
exports.eventEmitter = new EventEmitter();

// Send an OSC message that meets osc-min's message definition over the outgoing socket
exports.sendJSONMessage = function(data, callback) {

  function sendMessage() {
    var buffer = osc.toBuffer(data);

    oscSender.send(buffer, 0, buffer.length, exports.outgoingPort, exports.outgoingHost, callback);
  }

  // If outgoing port is not yet open, open it
  if (!oscSender) {
    this.init(sendMessage);
  } else {
    sendMessage();
  }
};

// Expose OSC message send on the API
exports.sendMessage = function(req, res) {
  var message = {
    oscType: 'message',
    address: '/eim/control',
    args: {
      type: 'string',
      value: req.params.message
    }
  };

  exports.sendJSONMessage({
    oscType: 'message',
    address: '/eim/control',
    args: {
      type: 'string',
      value: req.params.message
    }
  }, function() {
    res.json(200, { sentMessage: message });
  });
};<commit_msg>Log incoming debug/info messages from Max<commit_after>'use strict';

// TODO: Restructure module to return object
// TODO: Max errors should be handled also in Angular in order to display error

var dgram = require('dgram');
var osc = require('osc-min');
var EventEmitter = require('events').EventEmitter;

var oscSender, oscReceiver;

exports.outgoingPort = 7000;
exports.incomingPort = 7001;
exports.outgoingHost = 'localhost';

// Incoming message handler
function incomingMessageHandler(msg, rinfo) {
  var oscFromBuffer = osc.fromBuffer(msg, false);

  // Check if this is a log message coming from Max
  console.log(oscFromBuffer);
  if (oscFromBuffer.address === '/eim/status/log') {

    buildLogMessageFromMessage(oscFromBuffer.args);

  } else {

    // Emit incoming message event with data
    exports.eventEmitter.emit('oscMessageReceived', oscFromBuffer);
  }
}

function buildLogMessageFromMessage(msg) {

  if (msg.constructor.name !== 'Array') {
    return console.error('Malformed OSC error message received: ' + msg);
  }

  console.log(msg[0]);

  var level = msg[0].value.toUpperCase();

  var logMessageParts = msg.splice(1);

  var logMessage = "";

  for (var i = 0; i < logMessageParts.length; i++) {
    logMessage += logMessageParts[i].value;
    if (i !== logMessageParts.length - 1) {
      logMessage += " ";
    }
  }

  if (level === 'INFO') {
    console.info('MaxMSP: ' + logMessage);
  } else if (level === 'ERROR') {
    console.error('MaxMSP: ' + logMessage);
  }
}

// Create listener socket
function createOSCReceiver(callback) {
  setTimeout(function() {

    // Create socket and bind to port
    oscReceiver = dgram.createSocket('udp4');
    oscReceiver.bind(exports.incomingPort, function() {

      // Attach incoming message handler callback
      oscReceiver.on('message', incomingMessageHandler);

      if (typeof callback === 'function') {
        callback();
      }
    });
  }, 0);
}

// Main initialization
exports.init = function(callback) {
  setTimeout(function createSocket() {

    // Open outgoing socket
    oscSender = dgram.createSocket('udp4');

    // Open incoming socket
    createOSCReceiver(callback);

  }, 0);
};

// Consumers of this module can listen here for OSC-related events
exports.eventEmitter = new EventEmitter();

// Send an OSC message that meets osc-min's message definition over the outgoing socket
exports.sendJSONMessage = function(data, callback) {

  function sendMessage() {
    var buffer = osc.toBuffer(data);

    oscSender.send(buffer, 0, buffer.length, exports.outgoingPort, exports.outgoingHost, callback);
  }

  // If outgoing port is not yet open, open it
  if (!oscSender) {
    this.init(sendMessage);
  } else {
    sendMessage();
  }
};

// Expose OSC message send on the API
exports.sendMessage = function(req, res) {
  var message = {
    oscType: 'message',
    address: '/eim/control',
    args: {
      type: 'string',
      value: req.params.message
    }
  };

  exports.sendJSONMessage({
    oscType: 'message',
    address: '/eim/control',
    args: {
      type: 'string',
      value: req.params.message
    }
  }, function() {
    res.json(200, { sentMessage: message });
  });
};<|endoftext|>


<commit_before>#! /usr/bin/env node
const shell = require('shelljs');
const chalk = require('chalk');
const checkGit = require('./helpers/check_git');

if (!checkGit()) {
  shell.exit(1);
}
// SET SILENT TRUE SO THAT DEFAULT OUTPUT IS NOT PRINTED ON CONSOLE
shell.config.silent = true;

// get command line argument for commit message
const args = process.argv.slice(2);
const finalCommitMessage = args.join(' ') || 'Auto commit';
const getBranchName = branchName => `${chalk.bold.underline('Branch name\t')}: ${chalk.bold.underline(branchName)}`;

const getSpaceDelimitedValue = (string, initIndex) => string.substr(initIndex || 0, string.indexOf(' ') - (initIndex || 0));

const getFileChangedMessage = commitDetails => `${chalk.yellow('Files Changed\t: ', getSpaceDelimitedValue(commitDetails[0]))}`;

const getInsertMessage = commitMessage => `${chalk.green('Insertions\t: ', getSpaceDelimitedValue(commitMessage))}`;

const getDeleteMessage = commitMessage => `${chalk.redBright('Deletions\t: ', getSpaceDelimitedValue(commitMessage))}`;

/**
 * Generate message for created, deleted and renamed files
 * param {Array} [commitDetails] array of commit messages from index 2 to end.
 * @returns {String} created, deleted and renamed files message formatted string.
 */
const getFilesMessage = (commitDetails) => {
  let filesMessage = '';
  let filesAdded = '';
  let filesRenamed = '';
  let filesRemoved = '';
  commitDetails.forEach((message) => {
    if (message.indexOf('create') !== -1) {
      // get file name
      // exa. delete mode 100644 mmm.js
      const splittedMessage = message.split(' ').slice(3).join(' ');
      filesAdded += `\n${chalk.green(' -', splittedMessage)}`;
    } else if (message.indexOf('delete') !== -1) {
      const splittedMessage = message.split(' ').slice(3).join(' ');
      filesRemoved += `\n${chalk.red(' -', splittedMessage)}`;
    } else if (message.indexOf('rename') !== -1) {
      // exam. rename ddd.js => ddd_isdas.js (100%)\n
      const arrowIndex = message.indexOf('=>');
      const percentIndex = message.indexOf('(100%)');
      const firstFileName = message.substr(7, arrowIndex - 7);
      const secondFileName = message.substr(arrowIndex + 3, percentIndex - arrowIndex - 3);
      filesRenamed += `\n${chalk.yellow(' -', firstFileName, '=>', secondFileName)}`;
    }
  });
  if (filesAdded) {
    filesMessage += `\n${chalk.greenBright('Files Added:')}${filesAdded}`;
  }
  if (filesRemoved) {
    filesMessage += `\n${chalk.redBright('Files Removed:')}${filesRemoved}`;
  }
  if (filesRenamed) {
    filesMessage += `\n${chalk.yellowBright('Files Renamed:')}${filesRenamed}`;
  }
  return `\n${filesMessage}`;
};

/**
 * Generate message for number of insertion and deletions
 * param {Array} [commitDetails] array of commit messages.
 * @returns {String} insertion and deletion message formatted string.
 */
const getChangesMessage = (commitDetails) => {
  let output = '';
  const changeDetails = commitDetails.slice(1, 3);
  changeDetails.forEach((change) => {
    if (change.indexOf('insertion') !== -1) {
      output += `\n${getInsertMessage(change)}`;
    } else if (change.indexOf('deletion') !== -1) {
      output += `\n${getDeleteMessage(change)}`;
    }
  });
  return output;
};

// If no arguments
if (!args.length) {
  console.log(chalk.redBright('No commit message provided. Using default message \'Auto commit\'));
}

// exa. [ft/commit d525baa] color changed\n 1 file changed, 1 insertion(+)\n
const result = shell.exec(`git add -A . && git commit -a -m '${finalCommitMessage || 'Auto commit'}'`);
let output = '';
if (!result.stderr && !result.code) {
  // get the branch name
  const branchName = getSpaceDelimitedValue(result, 1);
  // attach branch name to output
  output = `${output}${getBranchName(branchName)}\n`;
  // commitDetails includes additions, deletions, file added, file removed, renamed etc.
  // starts from \n and have space before every line
  const commitDetails = result.substr(result.indexOf('\n ') + 2).split(/, |\n /);
  const commitDetailLength = commitDetails.length;
  output = `${output}${getFileChangedMessage(commitDetails)}${getChangesMessage(commitDetails, commitDetailLength)}${getFilesMessage(commitDetails.slice(2))}`;
  console.log(output);
  shell.exit(1);
} else {
  // nothing to commit
  if (result.indexOf('nothing to commit')) {
    output = `${output}${getBranchName(result.substr(10, result.indexOf('\n') - 10))}\n`;
    output = `${output}${chalk.redBright('Nothing to commit')}`;
    console.log(output);
    shell.exit(1);
  }
  console.log(chalk.redBright(result.stderr));
}
<commit_msg>auto commit messaged logged<commit_after>#! /usr/bin/env node
const shell = require('shelljs');
const chalk = require('chalk');
const checkGit = require('./helpers/check_git');

if (!checkGit()) {
  shell.exit(1);
}
// SET SILENT TRUE SO THAT DEFAULT OUTPUT IS NOT PRINTED ON CONSOLE
shell.config.silent = true;

// get command line argument for commit message
const args = process.argv.slice(2);
const finalCommitMessage = args.join(' ') || 'Auto commit';
const getBranchName = branchName => `${chalk.bold.underline('Branch name\t')}: ${chalk.bold.underline(branchName)}`;

const getSpaceDelimitedValue = (string, initIndex) => string.substr(initIndex || 0, string.indexOf(' ') - (initIndex || 0));

const getFileChangedMessage = commitDetails => `${chalk.yellow('Files Changed\t: ', getSpaceDelimitedValue(commitDetails[0]))}`;

const getInsertMessage = commitMessage => `${chalk.green('Insertions\t: ', getSpaceDelimitedValue(commitMessage))}`;

const getDeleteMessage = commitMessage => `${chalk.redBright('Deletions\t: ', getSpaceDelimitedValue(commitMessage))}`;

/**
 * Generate message for created, deleted and renamed files
 * param {Array} [commitDetails] array of commit messages from index 2 to end.
 * @returns {String} created, deleted and renamed files message formatted string.
 */
const getFilesMessage = (commitDetails) => {
  let filesMessage = '';
  let filesAdded = '';
  let filesRenamed = '';
  let filesRemoved = '';
  commitDetails.forEach((message) => {
    if (message.indexOf('create') !== -1) {
      // get file name
      // exa. delete mode 100644 mmm.js
      const splittedMessage = message.split(' ').slice(3).join(' ');
      filesAdded += `\n${chalk.green(' -', splittedMessage)}`;
    } else if (message.indexOf('delete') !== -1) {
      const splittedMessage = message.split(' ').slice(3).join(' ');
      filesRemoved += `\n${chalk.red(' -', splittedMessage)}`;
    } else if (message.indexOf('rename') !== -1) {
      // exam. rename ddd.js => ddd_isdas.js (100%)\n
      const arrowIndex = message.indexOf('=>');
      const percentIndex = message.indexOf('(100%)');
      const firstFileName = message.substr(7, arrowIndex - 7);
      const secondFileName = message.substr(arrowIndex + 3, percentIndex - arrowIndex - 3);
      filesRenamed += `\n${chalk.yellow(' -', firstFileName, '=>', secondFileName)}`;
    }
  });
  if (filesAdded) {
    filesMessage += `\n${chalk.greenBright('Files Added:')}${filesAdded}`;
  }
  if (filesRemoved) {
    filesMessage += `\n${chalk.redBright('Files Removed:')}${filesRemoved}`;
  }
  if (filesRenamed) {
    filesMessage += `\n${chalk.yellowBright('Files Renamed:')}${filesRenamed}`;
  }
  return `\n${filesMessage}`;
};

/**
 * Generate message for number of insertion and deletions
 * param {Array} [commitDetails] array of commit messages.
 * @returns {String} insertion and deletion message formatted string.
 */
const getChangesMessage = (commitDetails) => {
  let output = '';
  const changeDetails = commitDetails.slice(1, 3);
  changeDetails.forEach((change) => {
    if (change.indexOf('insertion') !== -1) {
      output += `\n${getInsertMessage(change)}`;
    } else if (change.indexOf('deletion') !== -1) {
      output += `\n${getDeleteMessage(change)}`;
    }
  });
  return output;
};

// If no arguments
if (!args.length) {
  console.log(chalk.redBright('No commit message provided. Using default message \'Auto commit\''));
}

// exa. [ft/commit d525baa] color changed\n 1 file changed, 1 insertion(+)\n
const result = shell.exec(`git add -A . && git commit -a -m '${finalCommitMessage || 'Auto commit'}'`);
let output = '';
if (!result.stderr && !result.code) {
  // get the branch name
  const branchName = getSpaceDelimitedValue(result, 1);
  // attach branch name to output
  output = `${output}${getBranchName(branchName)}\n`;
  // commitDetails includes additions, deletions, file added, file removed, renamed etc.
  // starts from \n and have space before every line
  const commitDetails = result.substr(result.indexOf('\n ') + 2).split(/, |\n /);
  const commitDetailLength = commitDetails.length;
  output = `${output}${getFileChangedMessage(commitDetails)}${getChangesMessage(commitDetails, commitDetailLength)}${getFilesMessage(commitDetails.slice(2))}`;
  console.log(output);
  shell.exit(1);
} else {
  // nothing to commit
  if (result.indexOf('nothing to commit')) {
    output = `${output}${getBranchName(result.substr(10, result.indexOf('\n') - 10))}\n`;
    output = `${output}${chalk.redBright('Nothing to commit')}`;
    console.log(output);
    shell.exit(1);
  }
  console.log(chalk.redBright(result.stderr));
}
<|endoftext|>


<commit_before>var MainTestLayer = cc.Layer.extend({
    menuItemList : null,
    GAP : 180,
    ctor:function () {
        var winSize, title, i, btn, label, scene;

        this._super();

        winSize = cc.director.getWinSize();

        title = new cc.Sprite("res/cocostyle.png");
        title.scale = 0.7;
        title.x = 150;
        title.y = winSize.height - 50;
        this.addChild(title);

        this.menuItemList = [{title:'csButton',scene:'csButton',desc:'a simple and beautiful button.'},
            {title:'csToast',scene:'csToast',desc:'a quick little message.'},
            {title:'csAlert',scene:'csAlert',desc:'a simple alert window.'},
            {title:'csTypingLabel',scene:'csTypingLabel',desc:'a label with typing effect.'},
            {title:'csTypingLBExt',scene:'csTypingLabelExt',desc:'a label with typing effect and font style.'},
            {title:'csLabelTTFExt',scene:'csLabelTTFExt',desc:'a label with font style(bold, italic and etc).'},
            {title:'csPixelCol',scene:'csPixelCollision',desc:'pixel collision detection.'},
            {title:'csCrypto',scene:'csCrypto',desc:'MD5, SHA1, SHA256, AES and etc.'},
            {title:'csVideo',scene:'csVideo',desc:'a video player as cocos2d sprite.'},
            {title:'csIframe',scene:'csIframe',desc:'a iFrame as cocos2d sprite.'},
            {title:'csAntiAlising',scene:'csCanvasAntiAlising',desc:'anti alising on canvas.'},
            {title:'csValidator',scene:'csValidator',desc:'validate email, url, credit card number and etc.'},
            {title:'csMoment',scene:'csMoment',desc:'parse, validate, manipulate, and display dates.'},
            {title:'csVExpressions',scene:'csVerbalExpressions',desc:'helps to construct difficult regular expressions.'}
        ];

        var scrollView = new ccui.ScrollView();
        scrollView.setDirection(ccui.ScrollView.DIR_VERTICAL);
        scrollView.setTouchEnabled(true);
        scrollView.setContentSize(cc.size(winSize.width, winSize.height));
        scrollView.setInnerContainerSize(cc.size(scrollView.width, this.menuItemList.length * this.GAP));
        this.addChild(scrollView);

        for(i = 0;i < this.menuItemList.length;i++) {
            btn = new csButton(this.menuItemList[i].title, csButton.style.emptycircle, csButton.size.large, csButton.color.orange, function(sender) {
                var scene;

                switch(sender.parent.scene) {
                    case 'csButton':
                        scene = new csButtonTestScene();
                        break;
                    case 'csToast':
                        scene = new csToastTestScene();
                        break;
                    case 'csAlert':
                        scene = new csAlertTestScene();
                        break;
                    case 'csTypingLabel':
                        scene = new csTypingLabelTestScene();
                        break;
                    case 'csTypingLabelExt':
                        scene = new csTypingLabelExtTestScene();
                        break;
                    case 'csLabelTTFExt':
                        scene = new csLabelTTFExtTestScene();
                        break;
                    case 'csPixelCollision':
                        scene = new csPixelCollisionTestScene();
                        break;
                    case 'csCrypto':
                        scene = new csCryptoTestScene();
                        break;
                    case 'csVideo':
                        scene = new csVideoTestScene();
                        break;
                    case 'csIframe':
                        scene = new csIframeTestScene();
                        break;
                    case 'csCanvasAntiAlising':
                        scene = new csCanvasAntiAlisingTestScene();
                        break;
                    case 'csValidator':
                        scene = new csValidatorTestScene();
                        break;
                    case 'csMoment':
                        scene = new csMomentTestScene();
                        break;
                    case 'csVerbalExpressions':
                        scene = new csVerbalExpressionsTestScene();
                        break;
                }

                cc.director.runScene(scene);
            }, btn);

            btn.scene = this.menuItemList[i].scene;
            btn._labelItem.label.fontSize = 12;
            btn._labelItem.width = btn._labelItem.label.width;
            btn._labelItem.height = btn._labelItem.label.height;
            btn.x = winSize.width /  2.5;
            btn.y = (this.menuItemList.length * this.GAP - (this.GAP / 1.2)) - (i * this.GAP);
            scrollView.addChild(btn);

            label = new cc.LabelTTF(this.menuItemList[i].desc, "Arial", 15);
            label.x = winSize.width / 2.1;
            label.y = (this.menuItemList.length * this.GAP - (this.GAP / 1.2)) - (i * this.GAP);
            label.anchorX = 0;
            scrollView.addChild(label);
        }

        return true;
    }
});

var MainTestScene = cc.Scene.extend({
    onEnter:function () {
        this._super();
        var layer = new MainTestLayer();
        this.addChild(layer);
    }
});

<commit_msg>Update MainTestScene.js<commit_after>var MainTestLayer = cc.Layer.extend({
    menuItemList : null,
    GAP : 180,
    ctor:function () {
        var winSize, title, i, btn, label, scene;

        this._super();

        winSize = cc.director.getWinSize();

        title = new cc.Sprite("res/cocostyle.png");
        title.scale = 0.7;
        title.x = 150;
        title.y = winSize.height - 50;
        this.addChild(title);

        this.menuItemList = [{title:'csButton',scene:'csButton',desc:'a simple and beautiful button.'},
            {title:'csToast',scene:'csToast',desc:'a quick little message.'},
            {title:'csAlert',scene:'csAlert',desc:'a simple alert window.'},
            {title:'csTypingLabel',scene:'csTypingLabel',desc:'a label with typing effect.'},
            {title:'csPixelCol',scene:'csPixelCollision',desc:'pixel collision detection.'},
            {title:'csCrypto',scene:'csCrypto',desc:'MD5, SHA1, SHA256, AES and etc.'},
            {title:'csAntiAlising',scene:'csCanvasAntiAlising',desc:'anti alising on canvas.'},
            {title:'csValidator',scene:'csValidator',desc:'validate email, url, credit card number and etc.'},
            {title:'csMoment',scene:'csMoment',desc:'parse, validate, manipulate, and display dates.'},
            {title:'csVExpressions',scene:'csVerbalExpressions',desc:'helps to construct difficult regular expressions.'}
        ];

        var scrollView = new ccui.ScrollView();
        scrollView.setDirection(ccui.ScrollView.DIR_VERTICAL);
        scrollView.setTouchEnabled(true);
        scrollView.setContentSize(cc.size(winSize.width, winSize.height));
        scrollView.setInnerContainerSize(cc.size(scrollView.width, this.menuItemList.length * this.GAP));
        this.addChild(scrollView);

        for(i = 0;i < this.menuItemList.length;i++) {
            btn = new csButton(this.menuItemList[i].title, csButton.style.emptycircle, csButton.size.large, csButton.color.orange, function(sender) {
                var scene;

                switch(sender.parent.scene) {
                    case 'csButton':
                        scene = new csButtonTestScene();
                        break;
                    case 'csToast':
                        scene = new csToastTestScene();
                        break;
                    case 'csAlert':
                        scene = new csAlertTestScene();
                        break;
                    case 'csTypingLabel':
                        scene = new csTypingLabelTestScene();
                        break;
                    case 'csPixelCollision':
                        scene = new csPixelCollisionTestScene();
                        break;
                    case 'csCrypto':
                        scene = new csCryptoTestScene();
                        break;
                    case 'csCanvasAntiAlising':
                        scene = new csCanvasAntiAlisingTestScene();
                        break;
                    case 'csValidator':
                        scene = new csValidatorTestScene();
                        break;
                    case 'csMoment':
                        scene = new csMomentTestScene();
                        break;
                    case 'csVerbalExpressions':
                        scene = new csVerbalExpressionsTestScene();
                        break;
                }

                cc.director.runScene(scene);
            }, btn);

            btn.scene = this.menuItemList[i].scene;
            btn._labelItem.label.fontSize = 12;
            btn._labelItem.width = btn._labelItem.label.width;
            btn._labelItem.height = btn._labelItem.label.height;
            btn.x = winSize.width /  2.5;
            btn.y = (this.menuItemList.length * this.GAP - (this.GAP / 1.2)) - (i * this.GAP);
            scrollView.addChild(btn);

            label = new cc.LabelTTF(this.menuItemList[i].desc, "Arial", 15);
            label.x = winSize.width / 2.1;
            label.y = (this.menuItemList.length * this.GAP - (this.GAP / 1.2)) - (i * this.GAP);
            label.anchorX = 0;
            scrollView.addChild(label);
        }

        return true;
    }
});

var MainTestScene = cc.Scene.extend({
    onEnter:function () {
        this._super();
        var layer = new MainTestLayer();
        this.addChild(layer);
    }
});

<|endoftext|>


<commit_before>const fs = require('fs-extra');
const parseString = require('xml2js').parseString;

const baseDir = 'translation/source';
const destDir = 'translation/dest';
const dbs = ['site', 'arena', 'emails', 'learn', 'activity', 'coordinates'];

function printTransError(r, orig, tran, prefix, e, filename) {
  if (r.test(orig) && !r.test(tran)) {
    console.log(`${prefix}${e['$'].name} contains <${orig.match(r)[0]}> in the source but not in ${filename}`);
  }
}

function checkAgainstRegexes(orig, tran, prefix, e, filename) {
  const warnings = [/lichess/i, /lichess\.org/i, /O-O/, /O-O-O/];
  const errors = [/%s/, /%\d\$s/];
  warnings.forEach(r => printTransError(r, orig, tran, `WARNING: ${prefix}`, e, filename));
  errors.forEach(r => printTransError(r, orig, tran, `ERROR: ${prefix}`, e, filename));
}

function checkPlaceholders(str, prefix, e, file) {
  const filename = file == 'src' ? '' : ` (${file})`;
  if (/%\d\$s/.test(str)) {
    placeholderNums = str.match(/%\d\$s/g).map(x => parseInt(x[1])).sort();
    for (i = 1; i <= placeholderNums.length; i++) {
      if (placeholderNums[i-1] !== i) {
        console.log(`ERROR: Bad placeholder in ${prefix}${e['$'].name}${filename}: ${str}`);
      }
    }
  }
}

function compareDestToSource(src, name) {
  fs.readdir(`${destDir}/${name}`, { encoding: 'utf8' }).then(filenames => {
    Promise.all(filenames.map((filename, index, resolve, reject) =>  {
      fs.readFile(`${destDir}/${name}/${filename}`, { encoding: 'utf8' }).then(txt => {
        return new Promise((resolve, reject) => parseString(txt, (_, xml) => {
          const strings = (xml.resources.string || []);
          const prefix = name === 'site' ? '' : `${name}:`
          strings.forEach(e => {
            orig = src[e['$'].name];
            tran = e['_'];
            checkAgainstRegexes(orig, tran, prefix, e, filename);
            checkPlaceholders(tran, prefix, e, filename);
          });
          const plurals = (xml.resources.plurals || []);
          plurals.forEach(e => {
            orig = src[e['$'].name];
            tran = e.item[0]['_'];
            checkAgainstRegexes(orig, tran, prefix, e, filename);
            checkPlaceholders(tran, prefix, e, filename);
          });
        }));
      });
    }));
  })
}

function VerifyTranslations(name) {
  return fs.readFile(`${baseDir}/${name}.xml`, { encoding: 'utf8' }).then(txt => {
    return new Promise((resolve, reject) => parseString(txt, (_, xml) => {
      const prefix = name === 'site' ? '' : `${name}:`
      const strings = (xml.resources.string || []);
      let source_strings = {};
      strings.forEach(e => {
        source_strings[e['$'].name] = e['_'];
        checkPlaceholders(e['_'], prefix, e, 'src');
      });
      const plurals = (xml.resources.plurals || []);
      plurals.forEach(e => {
        source_strings[e['$'].name] = e.item[0]['_'];
        checkPlaceholders(e.item[0]['_'], prefix, e, 'src');
      });
      resolve(source_strings);
    })).then(src => {
      compareDestToSource(src, name)
    });
  });
}

Promise.all(dbs.map(VerifyTranslations));
<commit_msg>tweak trans-sanity-check.js output - for #4696<commit_after>const fs = require('fs-extra');
const parseString = require('xml2js').parseString;

const baseDir = 'translation/source';
const destDir = 'translation/dest';
const dbs = ['site', 'arena', 'emails', 'learn', 'activity', 'coordinates'];

function printError(level, file, error) {
    console.log(`${level.toUpperCase()} ${file} ${error}`);
}

function printTransError(level, r, orig, tran, db, e, filename) {
  if (r.test(orig) && !r.test(tran))
    printError(level, `${db}/${filename}`, `${e['$'].name} lacks <${orig.match(r)[0]}>: ${e['_']}`);
}

function checkAgainstRegexes(orig, tran, db, e, filename) {
  const warnings = [/lichess/i, /lichess\.org/i, /O-O/, /O-O-O/];
  const errors = [/%s/, /%\d\$s/];
  warnings.forEach(r => printTransError('warning', r, orig, tran, db, e, filename));
  errors.forEach(r => printTransError('error', r, orig, tran, db, e, filename));
}

function checkPlaceholders(str, db, e, filename) {
  if (/%\d\$s/.test(str)) {
    placeholderNums = str.match(/%\d\$s/g).map(x => parseInt(x[1])).sort();
    for (i = 1; i <= placeholderNums.length; i++) {
      if (placeholderNums[i-1] !== i) {
        printError('error', `${db}/${filename}`, `${e['$'].name} bad placeholder: ${str}`);
      }
    }
  }
}

function compareDestToSource(src, db) {
  fs.readdir(`${destDir}/${db}`, { encoding: 'utf8' }).then(filenames => {
    Promise.all(filenames.map((filename, index, resolve, reject) =>  {
      fs.readFile(`${destDir}/${db}/${filename}`, { encoding: 'utf8' }).then(txt => {
        return new Promise((resolve, reject) => parseString(txt, (_, xml) => {
          const strings = (xml.resources.string || []);
          strings.forEach(e => {
            orig = src[e['$'].name];
            tran = e['_'];
            checkAgainstRegexes(orig, tran, db, e, filename);
            checkPlaceholders(tran, db, e, filename);
          });
          const plurals = (xml.resources.plurals || []);
          plurals.forEach(e => {
            orig = src[e['$'].name];
            tran = e.item[0]['_'];
            checkAgainstRegexes(orig, tran, db, e, filename);
            checkPlaceholders(tran, db, e, filename);
          });
        }));
      });
    }));
  })
}

function VerifyTranslations(db) {
  return fs.readFile(`${baseDir}/${db}.xml`, { encoding: 'utf8' }).then(txt => {
    return new Promise((resolve, reject) => parseString(txt, (_, xml) => {
      const prefix = db === 'site' ? '' : `${db}:`
      const strings = (xml.resources.string || []);
      let source_strings = {};
      strings.forEach(e => {
        source_strings[e['$'].name] = e['_'];
        checkPlaceholders(e['_'], db, e, 'src');
      });
      const plurals = (xml.resources.plurals || []);
      plurals.forEach(e => {
        source_strings[e['$'].name] = e.item[0]['_'];
        checkPlaceholders(e.item[0]['_'], db, e, 'src');
      });
      resolve(source_strings);
    })).then(src => {
      compareDestToSource(src, db)
    });
  });
}

Promise.all(dbs.map(VerifyTranslations));
<|endoftext|>


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

    const TEAR_IN_SELECTOR = '.favourites';
    angular.module('stockflux.tearout')
        .directive('tearable', ['geometryService', 'hoverService', 'currentWindowService', 'configService', '$rootScope',
            (geometryService, hoverService, currentWindowService, configService, $rootScope) => {
                return {
                    restrict: 'C',
                    link: (scope, element, attrs) => {
                        // Finding the tear element is tightly coupled to the HTML layout.
                        var dragElement = element[0],
                            tearElement = dragElement.parentNode.parentNode,
                            tileWidth = tearElement.clientWidth || 230,
                            tileHeight = tearElement.clientHeight || 100,
                            store;

                        var windowService = window.windowService;
                        var tearoutWindow = windowService.createTearoutWindow(window.name);

                        var myDropTarget = tearElement.parentNode,
                            parent = myDropTarget.parentNode,
                            myHoverArea = parent.getElementsByClassName('hover-area')[0],
                            offset = { x: 0, y: 0 },
                            currentlyDragging = false,
                            dragService;

                        hoverService.add(myHoverArea, scope.stock.code);

                        function insideFavouritesPane() {
                            // Check if you are over a drop target by seeing if the tearout rectangle intersects the drop target
                            return geometryService.elementIntersect(
                                tearoutWindow, window, document.getElementsByClassName('favourites')[0]);
                        }

                        function setOffset(x, y) {
                            offset.x = x;
                            offset.y = y;
                        }

                        function moveTearoutWindow(x, y) {
                            var tileTopPadding = 5,
                                tileRightPadding = 5,
                                tearElementWidth = 16;

                            tearoutWindow.moveTo(
                                x - tileWidth + (tearElementWidth - offset.x + tileRightPadding),
                                y - (tileTopPadding + offset.y));
                        }

                        function displayTearoutWindow() {
                            tearoutWindow.show();
                            tearoutWindow.setAsForeground();
                        }

                        function appendToOpenfinWindow(injection, openfinWindow) {
                            openfinWindow.contentWindow.document.body.appendChild(injection);
                        }

                        function returnFromTearout() {
                            myDropTarget.appendChild(tearElement);
                            tearoutWindow.hide();
                        }

                        function clearIncomingTearoutWindow() {
                            var document = tearoutWindow.getNativeWindow().document;
                            document.body = document.createElement('body');
                        }

                        function handleMouseDown(e) {
                            if (e.button !== 0) {
                                // Only process left clicks
                                return false;
                            }

                            if (dragElement.classList.contains('single')) {
                                // There is only one favourite card so don't allow tearing out
                                return false;
                            }

                            $rootScope.$broadcast('tearoutStart');
                            dragService = windowService.registerDrag(tearoutWindow, currentWindowService.getCurrentWindow());

                            currentlyDragging = true;
                            setOffset(e.offsetX, e.offsetY);
                            moveTearoutWindow(e.screenX, e.screenY);
                            clearIncomingTearoutWindow();
                            appendToOpenfinWindow(tearElement, tearoutWindow);
                            displayTearoutWindow();
                        }

                        function handleMouseMove(e) {
                            if (currentlyDragging) {
                                moveTearoutWindow(e.screenX, e.screenY);
                            }
                        }

                        function handleMouseUp(e) {
                            if (e.button !== 0) {
                                // Only process left clicks
                                return false;
                            }
                            $rootScope.$broadcast('tearoutEnd');

                            if (currentlyDragging) {
                                currentlyDragging = false;
                                if (dragService.overThisInstance(TEAR_IN_SELECTOR)) {
                                    returnFromTearout();
                                } else {
                                    if (!store) {
                                        store = window.storeService.open(window.name);
                                    }

                                    dragService.overAnotherInstance(TEAR_IN_SELECTOR, (overAnotherInstance) => {
                                        if (overAnotherInstance) {
                                            dragService.moveToOtherInstance(scope.stock);
                                            dragService.destroy();
                                            store.remove(scope.stock);
                                        } else {
                                            // Create new window instance
                                            var compact = store.isCompact();
                                            var indicators = store.indicators();

                                            windowService.createMainWindow(null, compact, (newWindow, showFunction) => {
                                                newWindow.resizeTo(window.outerWidth, window.outerHeight, 'top-left');
                                                var newCardOffset = configService.getTopCardOffset(compact);
                                                newWindow.moveTo(e.screenX - newCardOffset[0], e.screenY - newCardOffset[1], showFunction);
                                                var newStore = window.storeService.open(newWindow.name);
                                                newStore.indicators(indicators);
                                                newStore.add(scope.stock);
                                                store.remove(scope.stock);
                                                newStore.toggleCompact(compact);
                                            });
                                        }

                                        // Remove drop-target from original instance
                                        parent.removeChild(myHoverArea);
                                        parent.removeChild(myDropTarget);
                                        dispose();

                                        // Destroy myself.
                                        tearoutWindow.close();
                                    });
                                }
                            }
                        }

                        function reorderFavourites() {
                            var hoverTargets = hoverService.get();

                            for (var i = 0, max = hoverTargets.length; i < max; i++) {
                                var overDropTarget = geometryService.elementIntersect(
                                    tearoutWindow, window, hoverTargets[i].hoverArea);

                                if (overDropTarget) {
                                    if (!store) {
                                        store = window.storeService.open(window.name);
                                    }

                                    store.reorder(scope.stock.code, hoverTargets[i].code);
                                    break;
                                }
                            }
                        }

                        function boundsChangingEvent() {
                            if (dragService.overThisInstance(TEAR_IN_SELECTOR)) {
                                reorderFavourites();
                            } else {
                                // Check intersections to set the tear in indicator states.
                                dragService.updateIntersections(TEAR_IN_SELECTOR);
                            }
                        }

                        tearoutWindow.addEventListener('bounds-changing', boundsChangingEvent);

                        dragElement.addEventListener('mousedown', handleMouseDown);
                        document.addEventListener('mousemove', handleMouseMove, true);
                        document.addEventListener('mouseup', handleMouseUp, true);

                        function dispose() {
                            hoverService.remove(scope.stock.code);
                            tearoutWindow.removeEventListener('bounds-changing', boundsChangingEvent);
                            dragElement.removeEventListener('mousedown', handleMouseDown);
                            document.removeEventListener('mousemove', handleMouseMove);
                            document.removeEventListener('mouseup', handleMouseUp);
                        }

                        scope.$on('$destroy', () => {
                            dispose();
                        });
                    }
                };
            }]);
}(window));
<commit_msg>Fix blurred tearouts breaking the application; closes #538<commit_after>(function(window) {
    'use strict';

    const TEAR_IN_SELECTOR = '.favourites';
    angular.module('stockflux.tearout')
        .directive('tearable', ['geometryService', 'hoverService', 'currentWindowService', 'configService', '$rootScope',
            (geometryService, hoverService, currentWindowService, configService, $rootScope) => {
                return {
                    restrict: 'C',
                    link: (scope, element, attrs) => {
                        // Finding the tear element is tightly coupled to the HTML layout.
                        var dragElement = element[0],
                            tearElement = dragElement.parentNode.parentNode,
                            tileWidth = tearElement.clientWidth || 230,
                            tileHeight = tearElement.clientHeight || 100,
                            store;

                        var windowService = window.windowService;
                        var tearoutWindow = windowService.createTearoutWindow(window.name);

                        var myDropTarget = tearElement.parentNode,
                            parent = myDropTarget.parentNode,
                            myHoverArea = parent.getElementsByClassName('hover-area')[0],
                            offset = { x: 0, y: 0 },
                            currentlyDragging = false,
                            dragService;

                        hoverService.add(myHoverArea, scope.stock.code);

                        function insideFavouritesPane() {
                            // Check if you are over a drop target by seeing if the tearout rectangle intersects the drop target
                            return geometryService.elementIntersect(
                                tearoutWindow, window, document.getElementsByClassName('favourites')[0]);
                        }

                        function setOffset(x, y) {
                            offset.x = x;
                            offset.y = y;
                        }

                        function moveTearoutWindow(x, y) {
                            var tileTopPadding = 5,
                                tileRightPadding = 5,
                                tearElementWidth = 16;

                            tearoutWindow.moveTo(
                                x - tileWidth + (tearElementWidth - offset.x + tileRightPadding),
                                y - (tileTopPadding + offset.y));
                        }

                        function displayTearoutWindow() {
                            tearoutWindow.show();
                            tearoutWindow.setAsForeground();
                        }

                        function appendToOpenfinWindow(injection, openfinWindow) {
                            openfinWindow.contentWindow.document.body.appendChild(injection);
                        }

                        function returnFromTearout() {
                            myDropTarget.appendChild(tearElement);
                            tearoutWindow.hide();
                        }

                        function clearIncomingTearoutWindow() {
                            var document = tearoutWindow.getNativeWindow().document;
                            document.body = document.createElement('body');
                        }

                        function handleMouseDown(e) {
                            if (e.button !== 0) {
                                // Only process left clicks
                                return false;
                            }

                            if (dragElement.classList.contains('single')) {
                                // There is only one favourite card so don't allow tearing out
                                return false;
                            }

                            $rootScope.$broadcast('tearoutStart');
                            dragService = windowService.registerDrag(tearoutWindow, currentWindowService.getCurrentWindow());

                            currentlyDragging = true;
                            setOffset(e.offsetX, e.offsetY);
                            moveTearoutWindow(e.screenX, e.screenY);
                            clearIncomingTearoutWindow();
                            appendToOpenfinWindow(tearElement, tearoutWindow);
                            displayTearoutWindow();

                            tearoutWindow.addEventListener('blurred', onBlur);
                        }

                        function handleMouseMove(e) {
                            if (currentlyDragging) {
                                moveTearoutWindow(e.screenX, e.screenY);
                            }
                        }

                        function handleMouseUp(e) {
                            if (e.button !== 0) {
                                // Only process left clicks
                                return false;
                            }
                            $rootScope.$broadcast('tearoutEnd');
                            tearoutWindow.removeEventListener('blurred', onBlur);

                            if (currentlyDragging) {
                                currentlyDragging = false;
                                if (dragService.overThisInstance(TEAR_IN_SELECTOR)) {
                                    returnFromTearout();
                                } else {
                                    if (!store) {
                                        store = window.storeService.open(window.name);
                                    }

                                    dragService.overAnotherInstance(TEAR_IN_SELECTOR, (overAnotherInstance) => {
                                        if (overAnotherInstance) {
                                            dragService.moveToOtherInstance(scope.stock);
                                            dragService.destroy();
                                            store.remove(scope.stock);
                                        } else {
                                            // Create new window instance
                                            var compact = store.isCompact();
                                            var indicators = store.indicators();

                                            windowService.createMainWindow(null, compact, (newWindow, showFunction) => {
                                                newWindow.resizeTo(window.outerWidth, window.outerHeight, 'top-left');
                                                var newCardOffset = configService.getTopCardOffset(compact);
                                                newWindow.moveTo(e.screenX - newCardOffset[0], e.screenY - newCardOffset[1], showFunction);
                                                var newStore = window.storeService.open(newWindow.name);
                                                newStore.indicators(indicators);
                                                newStore.add(scope.stock);
                                                store.remove(scope.stock);
                                                newStore.toggleCompact(compact);
                                            });
                                        }

                                        // Remove drop-target from original instance
                                        parent.removeChild(myHoverArea);
                                        parent.removeChild(myDropTarget);
                                        dispose();

                                        // Destroy myself.
                                        tearoutWindow.close();
                                    });
                                }
                            }
                        }

                        function reorderFavourites() {
                            var hoverTargets = hoverService.get();

                            for (var i = 0, max = hoverTargets.length; i < max; i++) {
                                var overDropTarget = geometryService.elementIntersect(
                                    tearoutWindow, window, hoverTargets[i].hoverArea);

                                if (overDropTarget) {
                                    if (!store) {
                                        store = window.storeService.open(window.name);
                                    }

                                    store.reorder(scope.stock.code, hoverTargets[i].code);
                                    break;
                                }
                            }
                        }

                        function boundsChangingEvent() {
                            if (dragService.overThisInstance(TEAR_IN_SELECTOR)) {
                                reorderFavourites();
                            } else {
                                // Check intersections to set the tear in indicator states.
                                dragService.updateIntersections(TEAR_IN_SELECTOR);
                            }
                        }

                        function onBlur() {
                            if (currentlyDragging) {
                                $rootScope.$broadcast('tearoutEnd');
                                returnFromTearout();
                                currentlyDragging = false;
                                dragService.destroy();
                                tearoutWindow.removeEventListener('blurred', onBlur);
                            }
                        }

                        tearoutWindow.addEventListener('bounds-changing', boundsChangingEvent);

                        dragElement.addEventListener('mousedown', handleMouseDown);
                        document.addEventListener('mousemove', handleMouseMove, true);
                        document.addEventListener('mouseup', handleMouseUp, true);

                        function dispose() {
                            hoverService.remove(scope.stock.code);
                            tearoutWindow.removeEventListener('bounds-changing', boundsChangingEvent);
                            tearoutWindow.removeEventListener('blurred', onBlur);
                            dragElement.removeEventListener('mousedown', handleMouseDown);
                            document.removeEventListener('mousemove', handleMouseMove);
                            document.removeEventListener('mouseup', handleMouseUp);
                        }

                        scope.$on('$destroy', () => {
                            dispose();
                        });
                    }
                };
            }]);
}(window));
<|endoftext|>


<commit_before>/**
 * (c) 2016 Tieto Finland Oy
 * Licensed under the MIT license.
 */
'use strict';

/**
 * @ngdoc function
 * @name dashboard.controller:OverviewCtrl
 * @description
 * # OverviewCtrl
 * Controller of the dashboard
 */
angular.module('dashboard')
    .controller('overviewCtrl', ['$scope', '$log', 'ENV', 'SigningOpenApi', '$state', '$rootScope', 'CONST', '$stateParams', 'MTGD', 'StorageSrv', '$http', 'Utils', 'DialogUtils', 'AhjoMeetingSrv', function ($scope, $log, ENV, SigningOpenApi, $state, $rootScope, CONST, $stateParams, MTGD, StorageSrv, $http, Utils, DialogUtils, AhjoMeetingSrv) {
        $log.debug("overviewCtrl: CONTROLLER, mode: ", $stateParams.state);
        var self = this;
        self.loading = 0;
        self.signReqsHeader = 'Avoimet allekirjoituspyynnöt';
        self.signErr = null;
        self.blockMode = CONST.BLOCKMODE.DEFAULT;
        self.vbl = MTGD.VISIBLE;
        self.bms = CONST.BLOCKMODE;
        self.testEnvUserId = StorageSrv.getKey(CONST.KEY.TESTENV_USERID);

        var visibleMtgs = StorageSrv.getKey(CONST.KEY.VISIBLE_MTGS);
        switch (visibleMtgs) {
            case MTGD.VISIBLE.OPEN:
                self.vblMtgs = MTGD.VISIBLE.OPEN;
                break;
            case MTGD.VISIBLE.CLOSED:
                self.vblMtgs = MTGD.VISIBLE.CLOSED;
                break;
            default:
                self.vblMtgs = MTGD.VISIBLE.OPEN;
                break;
        }

        var signingRes = StorageSrv.getKey(CONST.KEY.SIGNING_RES);
        self.closedSignReqs = signingRes ? signingRes : false;

        $rootScope.menu = CONST.MENU.CLOSED;
        var mode = $stateParams.state;
        var storedMode = localStorage.overviewState;

        if (mode === CONST.HOMEMODE.ALL) {
            if (storedMode === '1') {
                mode = CONST.HOMEMODE.MEETINGS;
            }
            else if (storedMode === '2') {
                mode = CONST.HOMEMODE.ESIGN;
            }
        }

        switch (mode) {
            case CONST.HOMEMODE.MEETINGS:
                self.hasMeetings = true;
                break;
            case CONST.HOMEMODE.ESIGN:
                self.hasEsign = true;
                break;
            default:
                self.hasMeetings = true;
                self.hasEsign = true;
                break;
        }

        localStorage.overviewState = mode;

        function goToMeeting(meetingItem, meetingRole, personGuid) {
            $log.debug("overviewCtrl.goToMeeting");
            if (meetingItem && meetingRole && personGuid) {
                StorageSrv.setKey(CONST.KEY.MEETING_ITEM, meetingItem);
                StorageSrv.setKey(CONST.KEY.MEETING_ROLE, meetingRole);
                StorageSrv.setKey(CONST.KEY.MEETING_PERSONGUID, personGuid);
                $state.go(CONST.APPSTATE.MEETING, { 'menu': CONST.MENU.FULL });
            } else {
                $log.error("overviewCtrl.goToMeeting: bad args \n meeting=" + JSON.stringify(meetingItem) + "\n  role=" + JSON.stringify(meetingRole) + "\n person=" + JSON.stringify(personGuid));
                $rootScope.failedInfo('STR_LOGIN_FAILED');
            }
        }

        self.loginMeeting = function loginMeetingFn(meetingItem, meetingRole, personGuid) {
            $log.debug("overviewCtrl.loginMeeting: \n - meeting:\n" + JSON.stringify(meetingItem) + "\n - role: " + JSON.stringify(meetingRole) + "\n - personGuid: " + personGuid);
            var dlg = DialogUtils.showProgress('STR_MTG_LOGIN_PROGRESS');
            AhjoMeetingSrv.meetingLogin(meetingItem.meetingGuid, meetingRole.RoleID, personGuid).then(function (resp) {
                $log.debug("overviewCtrl.loginMeeting: result \n" + JSON.stringify(resp));
                if (!Utils.processAhjoError(resp)) {
                    goToMeeting(meetingItem, meetingRole, personGuid);
                }
            }, function (error) {
                Utils.processAhjoError(error);
            }).finally(function () {
                DialogUtils.close(dlg);
            });
        };

        self.showInfo = function () {
            $log.debug("overviewCtrl: showInfo");
        };

        self.upperClicked = function () {
            self.blockMode = (self.blockMode === CONST.BLOCKMODE.PRIMARY || self.blockMode === CONST.BLOCKMODE.SECONDARY) ? CONST.BLOCKMODE.DEFAULT : CONST.BLOCKMODE.PRIMARY;
        };

        self.lowerClicked = function () {
            self.blockMode = (self.blockMode === CONST.BLOCKMODE.SECONDARY || self.blockMode === CONST.BLOCKMODE.PRIMARY) ? CONST.BLOCKMODE.DEFAULT : CONST.BLOCKMODE.SECONDARY;
        };

        self.setMtgsVisible = function (mtgs) {
            self.vblMtgs = mtgs;
            StorageSrv.setKey(CONST.KEY.VISIBLE_MTGS, mtgs);
        };

        self.setClosedSignReqs = function (value) {
            self.closedSignReqs = value;
            StorageSrv.setKey(CONST.KEY.SIGNING_RES, value);
        };

        function logoutRest() {
            $log.debug("overviewCtrl.logoutRest");
            self.logoutProm = $http({
                method: 'GET',
                withCredentials: true,
                url: ENV.AHJOAPI_USERLOGOUTREST
            }).then(function successCallback(/*response*/) {
                $log.debug("overviewCtrl.logoutRest: done");
                $state.go(CONST.APPSTATE.LOGIN);
            }, function errorCallback(error) {
                $log.error(error);
            }).finally(function () {
            });
        }

        self.logout = function () {
            $log.debug("overviewCtrl.logout");
            if (!self.logoutProm) {
                logoutRest();
            }
            else {
                $log.error("overviewCtrl.logout: ignored");
            }
        };

        $scope.$on('$destroy', function () {
            $log.debug("overviewCtrl: DESTROY");
        });
    }]);
<commit_msg>Mtg: meetingLougoutRest error handling<commit_after>/**
 * (c) 2016 Tieto Finland Oy
 * Licensed under the MIT license.
 */
'use strict';

/**
 * @ngdoc function
 * @name dashboard.controller:OverviewCtrl
 * @description
 * # OverviewCtrl
 * Controller of the dashboard
 */
angular.module('dashboard')
    .controller('overviewCtrl', ['$scope', '$log', 'ENV', 'SigningOpenApi', '$state', '$rootScope', 'CONST', '$stateParams', 'MTGD', 'StorageSrv', '$http', 'Utils', 'DialogUtils', 'AhjoMeetingSrv', function ($scope, $log, ENV, SigningOpenApi, $state, $rootScope, CONST, $stateParams, MTGD, StorageSrv, $http, Utils, DialogUtils, AhjoMeetingSrv) {
        $log.debug("overviewCtrl: CONTROLLER, mode: ", $stateParams.state);
        var self = this;
        self.loading = 0;
        self.signReqsHeader = 'Avoimet allekirjoituspyynnöt';
        self.signErr = null;
        self.blockMode = CONST.BLOCKMODE.DEFAULT;
        self.vbl = MTGD.VISIBLE;
        self.bms = CONST.BLOCKMODE;
        self.testEnvUserId = StorageSrv.getKey(CONST.KEY.TESTENV_USERID);

        var visibleMtgs = StorageSrv.getKey(CONST.KEY.VISIBLE_MTGS);
        switch (visibleMtgs) {
            case MTGD.VISIBLE.OPEN:
                self.vblMtgs = MTGD.VISIBLE.OPEN;
                break;
            case MTGD.VISIBLE.CLOSED:
                self.vblMtgs = MTGD.VISIBLE.CLOSED;
                break;
            default:
                self.vblMtgs = MTGD.VISIBLE.OPEN;
                break;
        }

        var signingRes = StorageSrv.getKey(CONST.KEY.SIGNING_RES);
        self.closedSignReqs = signingRes ? signingRes : false;

        $rootScope.menu = CONST.MENU.CLOSED;
        var mode = $stateParams.state;
        var storedMode = localStorage.overviewState;

        if (mode === CONST.HOMEMODE.ALL) {
            if (storedMode === '1') {
                mode = CONST.HOMEMODE.MEETINGS;
            }
            else if (storedMode === '2') {
                mode = CONST.HOMEMODE.ESIGN;
            }
        }

        switch (mode) {
            case CONST.HOMEMODE.MEETINGS:
                self.hasMeetings = true;
                break;
            case CONST.HOMEMODE.ESIGN:
                self.hasEsign = true;
                break;
            default:
                self.hasMeetings = true;
                self.hasEsign = true;
                break;
        }

        localStorage.overviewState = mode;

        function goToMeeting(meetingItem, meetingRole, personGuid) {
            $log.debug("overviewCtrl.goToMeeting");
            if (meetingItem && meetingRole && personGuid) {
                StorageSrv.setKey(CONST.KEY.MEETING_ITEM, meetingItem);
                StorageSrv.setKey(CONST.KEY.MEETING_ROLE, meetingRole);
                StorageSrv.setKey(CONST.KEY.MEETING_PERSONGUID, personGuid);
                $state.go(CONST.APPSTATE.MEETING, { 'menu': CONST.MENU.FULL });
            } else {
                $log.error("overviewCtrl.goToMeeting: bad args \n meeting=" + JSON.stringify(meetingItem) + "\n  role=" + JSON.stringify(meetingRole) + "\n person=" + JSON.stringify(personGuid));
                $rootScope.failedInfo('STR_LOGIN_FAILED');
            }
        }

        function logoutRest() {
            $log.debug("overviewCtrl.logoutRest");
            self.logoutProm = $http({
                method: 'GET',
                withCredentials: true,
                url: ENV.AHJOAPI_USERLOGOUTREST
            }).then(function successCallback(resp) {
                $log.debug("overviewCtrl.logoutRest: done");
                Utils.processAhjoError(resp); // Print any errors but transition state in any case.
            }, function errorCallback(error) {
                $log.error("overviewCtrl.logoutRest");
                Utils.processAhjoError(error);
            }).finally(function () {
                $state.go(CONST.APPSTATE.LOGIN);
            });
        }

        self.loginMeeting = function loginMeetingFn(meetingItem, meetingRole, personGuid) {
            $log.debug("overviewCtrl.loginMeeting: \n - meeting:\n" + JSON.stringify(meetingItem) + "\n - role: " + JSON.stringify(meetingRole) + "\n - personGuid: " + personGuid);
            var dlg = DialogUtils.showProgress('STR_MTG_LOGIN_PROGRESS');
            AhjoMeetingSrv.meetingLogin(meetingItem.meetingGuid, meetingRole.RoleID, personGuid).then(function (resp) {
                $log.debug("overviewCtrl.loginMeeting: result \n" + JSON.stringify(resp));
                if (!Utils.processAhjoError(resp)) {
                    goToMeeting(meetingItem, meetingRole, personGuid);
                }
            }, function (error) {
                Utils.processAhjoError(error);
            }).finally(function () {
                DialogUtils.close(dlg);
            });
        };

        self.showInfo = function () {
            $log.debug("overviewCtrl: showInfo");
        };

        self.upperClicked = function () {
            self.blockMode = (self.blockMode === CONST.BLOCKMODE.PRIMARY || self.blockMode === CONST.BLOCKMODE.SECONDARY) ? CONST.BLOCKMODE.DEFAULT : CONST.BLOCKMODE.PRIMARY;
        };

        self.lowerClicked = function () {
            self.blockMode = (self.blockMode === CONST.BLOCKMODE.SECONDARY || self.blockMode === CONST.BLOCKMODE.PRIMARY) ? CONST.BLOCKMODE.DEFAULT : CONST.BLOCKMODE.SECONDARY;
        };

        self.setMtgsVisible = function (mtgs) {
            self.vblMtgs = mtgs;
            StorageSrv.setKey(CONST.KEY.VISIBLE_MTGS, mtgs);
        };

        self.setClosedSignReqs = function (value) {
            self.closedSignReqs = value;
            StorageSrv.setKey(CONST.KEY.SIGNING_RES, value);
        };

        self.logout = function () {
            $log.debug("overviewCtrl.logout");
            if (!self.logoutProm) {
                logoutRest();
            }
            else {
                $log.error("overviewCtrl.logout: ignored");
            }
        };

        $scope.$on('$destroy', function () {
            $log.debug("overviewCtrl: DESTROY");
        });
    }]);
<|endoftext|>


<commit_before>'use strict';

angular.module('emulvcApp')
	.directive('drawcrosshairs', function() {
		return {
			restrict: 'A',
			link: function postLink(scope, element) {
				var canvas = element[0];

				// on mouse move
				element.bind('mousemove', function(event) {
					drawCrossHairs(scope.vs, canvas, scope.config, scope.dhs, event);
				});
				// on mouse leave
				element.bind('mouseleave', function() {
					var ctx = canvas.getContext('2d');
					ctx.clearRect(0, 0, canvas.width, canvas.height);
				});

				function drawCrossHairs(viewState, canvas, config, dhs, mouseEvt) {
					var ctx = canvas.getContext('2d');
					ctx.clearRect(0, 0, canvas.width, canvas.height);
					ctx.strokeStyle = config.vals.colors.crossHairsColor;
					ctx.fillStyle = config.vals.colors.crossHairsColor;

					// see if Chrome ->dashed line
					if (navigator.vendor === 'Google Inc.') {
						ctx.setLineDash([2]);
					}

					// draw lines
					var mouseX = dhs.getX(mouseEvt);
					var mouseY = dhs.getY(mouseEvt);

					ctx.beginPath();
					ctx.moveTo(0, mouseY);
					ctx.lineTo(5, mouseY + 5);
					ctx.moveTo(0, mouseY);
					ctx.lineTo(canvas.width, mouseY);
					ctx.lineTo(canvas.width - 5, mouseY + 5);
					ctx.moveTo(mouseX, 0);
					ctx.lineTo(mouseX, canvas.height);
					ctx.stroke();
					// draw frequency / sample / time
					ctx.font = (config.vals.font.fontPxSize + 'px' + ' ' + config.vals.font.fontType);

					var mouseFreq = viewState.round(viewState.spectroSettings.rangeTo - mouseY / canvas.height * viewState.spectroSettings.rangeTo, 2);

					var tW = ctx.measureText(mouseFreq + ' Hz').width;

					ctx.fillText(mouseFreq + ' Hz', 5, mouseY + config.vals.font.fontPxSize);
					ctx.fillText(mouseFreq + ' Hz', canvas.width - 5 - tW, mouseY + config.vals.font.fontPxSize);

					ctx.fillText(Math.round(viewState.curViewPort.sS + mouseX / canvas.width * (viewState.curViewPort.eS - viewState.curViewPort.sS)), mouseX + 5, config.vals.font.fontPxSize);
					ctx.fillText(viewState.round(viewState.getViewPortStartTime() + mouseX / canvas.width * (viewState.getViewPortEndTime() - viewState.getViewPortStartTime()), 6), mouseX + 5, config.vals.font.fontPxSize * 2);
					// see if Chrome ->dashed line
					if (navigator.vendor === 'Google Inc.') {
						ctx.setLineDash([0]);
					}
				}

			}
		};
	});<commit_msg>now in spect<commit_after><|endoftext|>


<commit_before>/**
 * Created by István on 10/8/2015.
 */
(function () {
  'use strict';

  angular
    .module('app')
    .factory('firebaseService', firebaseService);

  firebaseService.$inject = ['$log', '$firebaseArray', '$firebaseObject'];

  /* @ngInject */
  function firebaseService($log, $firebaseArray, $firebaseObject) {
    var baseURL = "https://netbakery.firebaseio.com";
    var firebaseReference = new Firebase(baseURL);

    var service = {
      getArray: getArray,
      getObject: getObject,
      getReference: getReference
    };
    return service;

    ////////////////

    function getReference(){
      return firebaseReference;
    }

    function getArray(url){
      var currentReference = firebaseReference.child(url);
      $log.info('Getting array for path: ' + currentReference.toString());
      return $firebaseArray(currentReference);
    }

    function getObject(url){
      var currentReference = firebaseReference.child(url);
      $log.info('Getting object for path: ' + currentReference.toString());
      return $firebaseObject(currentReference);
    }
  }

})();

<commit_msg>added update function<commit_after>/**
 * Created by István on 10/8/2015.
 */
(function () {
  'use strict';

  angular
    .module('app')
    .factory('firebaseService', firebaseService);

  firebaseService.$inject = ['$log', '$firebaseArray', '$firebaseObject'];

  /* @ngInject */
  function firebaseService($log, $firebaseArray, $firebaseObject) {
    var baseURL = "https://netbakery.firebaseio.com";
    var firebaseReference = new Firebase(baseURL);

    var service = {
      getArray: getArray,
      getObject: getObject,
      getReference: getReference,
      updateObject: updateObject
    };
    return service;

    ////////////////

    function getReference(){
      return firebaseReference;
    }

    function getArray(url){
      var currentReference = firebaseReference.child(url);
      $log.info('Getting array for path: ' + currentReference.toString());
      return $firebaseArray(currentReference);
    }

    function getObject(url){
      var currentReference = firebaseReference.child(url);
      $log.info('Getting object for path: ' + currentReference.toString());
      return $firebaseObject(currentReference);
    }

    function updateObject(url){
      var currentReference = firebaseReference.child(url);
      $log.info('Updating object for path: ' + currentReference.toString());
      currentReference.update(obj)
    }

  }

})();

<|endoftext|>