<commit_before>/*
 * Copyright (c) 2016-2017 Untu, Inc.
 * This code is licensed under Eclipse Public License - v 1.0.
 * The full license text can be found in LICENSE.txt file and
 * on the Eclipse official site (https://www.eclipse.org/legal/epl-v10.html).
 */

'use strict';

var Actor = require('./actor.js');
var MessageSocket = require('./net/message-socket.js');
var ForkedActorChild = require('./forked-actor-child.js');
var net = require('net');
var P = require('bluebird');

/**
 * Remote actor child endpoint.
 */
class RemoteActorChild extends Actor {
  /**
   * @param {ActorSystem} system Actor system.
   * @param {Actor} actor Wrapped actor.
   * @param {Object} definition Actor behaviour definition.
   * @param {String} [parentId] Parent ID.
   */
  constructor(system, actor, definition, parentId) {
    super(system, null, definition, actor.getId(), actor.getName(), actor.getCustomParameters());

    this.system = system;
    this.wrappedActor = actor;
    this.parentId = parentId;
  }

  initialize() {
    return new P((resolve, reject) => {
      this.server = net.createServer();
      this.server.listen();

      this.server.on('listening', () => {
        var addr = this.server.address();
        this.log.info(`Listening on ${addr.address}:${addr.port}`);

        resolve();
      });
      this.server.on('error', err => {
        this.log.error('Net server error: ' + err.message);

        reject(err);
      });
      this.server.on('connection', socket => {
        if (this.socket) {
          // Already have connection, reject.
          this.log.warn('Second incoming connection, rejecting:', socket.address());

          return socket.end();
        }

        this.socket = new MessageSocket(socket);
        this.actorPromise = P.resolve(new ForkedActorChild(this.system, this.socket, this.wrappedActor, this.parentId))
          .tap(actor => actor.initialize());
      });
    });
  }

  getMode() {
    return 'remote';
  }

  /**
   * Synchronously returns this actor's listening port, provided that the actor
   * is initialized.
   *
   * @returns {Number} Listening port number.
   */
  getPort() {
    if (!this.server) throw new Error('Remote actor not initialized yet.');

    return this.server.address().port;
  }

  send0(...args) {
    if (!this.actorPromise) return P.reject(new Error('Network connection has not been established yet.'));

    return this.actorPromise.then(actor => actor.send(...args));
  }

  sendAndReceive0(...args) {
    if (!this.actorPromise) return P.reject(new Error('Network connection has not been established yet.'));

    return this.actorPromise.then(actor => actor.sendAndReceive(...args));
  }

  destroy0() {
    var actorPromise = this.actorPromise || P.resolve();

    return actorPromise
      .then(actor => actor && actor.destroy())
      .then(() => {
        this.socket && this.socket.end();
        this.server && this.server.close();
      });
  }

  toString() {
    var name = this.getName();

    if (name) {
      return 'RemoteActorChild(' + this.getId() + ', ' + name + ')';
    }
    else {
      return 'RemoteActorChild(' + this.getId() + ')';
    }
  }
}

module.exports = RemoteActorChild;<commit_msg>(saymon) forward-all-unknown: Fixed test failures.<commit_after>/*
 * Copyright (c) 2016-2017 Untu, Inc.
 * This code is licensed under Eclipse Public License - v 1.0.
 * The full license text can be found in LICENSE.txt file and
 * on the Eclipse official site (https://www.eclipse.org/legal/epl-v10.html).
 */

'use strict';

var Actor = require('./actor.js');
var MessageSocket = require('./net/message-socket.js');
var ForkedActorChild = require('./forked-actor-child.js');
var net = require('net');
var P = require('bluebird');

/**
 * Remote actor child endpoint.
 */
class RemoteActorChild extends Actor {
  /**
   * @param {ActorSystem} system Actor system.
   * @param {Actor} actor Wrapped actor.
   * @param {Object} definition Actor behaviour definition.
   * @param {String} [parentId] Parent ID.
   */
  constructor(system, actor, definition, parentId) {
    super(system, null, definition, actor.getId(), actor.getName(), actor.getCustomParameters());

    this.system = system;
    this.wrappedActor = actor;
    this.parentId = parentId;
    this.definition = definition;
  }

  initialize() {
    return new P((resolve, reject) => {
      this.server = net.createServer();
      this.server.listen();

      this.server.on('listening', () => {
        var addr = this.server.address();
        this.log.info(`Listening on ${addr.address}:${addr.port}`);

        resolve();
      });
      this.server.on('error', err => {
        this.log.error('Net server error: ' + err.message);

        reject(err);
      });
      this.server.on('connection', socket => {
        if (this.socket) {
          // Already have connection, reject.
          this.log.warn('Second incoming connection, rejecting:', socket.address());

          return socket.end();
        }

        this.socket = new MessageSocket(socket);
        this.actorPromise =
          P.resolve(new ForkedActorChild(this.system, this.socket, this.wrappedActor, this.definition, this.parentId))
            .tap(actor => actor.initialize());
      });
    });
  }

  getMode() {
    return 'remote';
  }

  /**
   * Synchronously returns this actor's listening port, provided that the actor
   * is initialized.
   *
   * @returns {Number} Listening port number.
   */
  getPort() {
    if (!this.server) throw new Error('Remote actor not initialized yet.');

    return this.server.address().port;
  }

  send0(...args) {
    if (!this.actorPromise) return P.reject(new Error('Network connection has not been established yet.'));

    return this.actorPromise.then(actor => actor.send(...args));
  }

  sendAndReceive0(...args) {
    if (!this.actorPromise) return P.reject(new Error('Network connection has not been established yet.'));

    return this.actorPromise.then(actor => actor.sendAndReceive(...args));
  }

  destroy0() {
    var actorPromise = this.actorPromise || P.resolve();

    return actorPromise
      .then(actor => actor && actor.destroy())
      .then(() => {
        this.socket && this.socket.end();
        this.server && this.server.close();
      });
  }

  toString() {
    var name = this.getName();

    if (name) {
      return 'RemoteActorChild(' + this.getId() + ', ' + name + ')';
    }
    else {
      return 'RemoteActorChild(' + this.getId() + ')';
    }
  }
}

module.exports = RemoteActorChild;<|endoftext|>


<commit_before>const uploaderApiURL = 'http://mcmap.sasrai.jp/%E9%85%94%E3%81%84%E3%81%A9%E3%82%8C/uploader/api';
var lastUpdateTime = -1;
var uploadFilesCache = [];

function reloadSchematics() {
  axios.get(uploaderApiURL + '/schematics?' + Date.now())
  .then((response) => {
    schFilesHelper.updateData(response.data);
  })
  .catch((error) => {
    console.log(error);
  });
}

function uploadSchematicFile(file, props, cb) {
  var data = new FormData();
  data.append('title', props['title']);
  data.append('description', props['description']);
  data.append('delete_key', props['delete_key']);
  data.append('sch_file', file);

  axios.post(uploaderApiURL + '/schematics/upload', data)
  .then((response) => {
    setTimeout(() => $('#sch-files').bootstrapTable('refresh'));
    if (cb && typeof cb == 'function') cb(null, response);
  })
  .catch((error) => {
    console.log(error);
    if (cb && typeof cb == 'function') cb(error, null);
  })
}

function renderOutput(files) {
  // files is a FileList of File objects. List some properties.
  var output = [];
  for (var i = 0, f; f = files[i]; i++) {
    output.push('

',
                '
' + escape(f.name) + '
',
                '
',
                  '
',
                    'タイトル',
                    '<input class="form-control" name="title" id="' + i + '-title" placeholder="表示タイトルを入力してください(必須)">',
                  '
',
                  '
',
                    '詳細',
                    '<textarea class="form-control" name="description" id="' + i + '-description" rows="2" placeholder="ファイルの説明分を入力してください(任意)"></textarea>',
                  '
',
                  '
',
                    '削除キー(処理未実装)',
                    '<input class="form-control" name="delete_key" id="' + i + '-delete_key" placeholder="削除キー(任意)">',
                  '
',
                  '
',
                    '<button type="button" class="btn btn-info upload">アップロード </button>',
                    '<button type="button" class="btn btn-secondary cancel">キャンセル</button>',
                  '
',
                '
',
                // f.size, ' bytes, last modified: ',
                // f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
                '

');
  }
  document.getElementById('list').innerHTML = '
' + output.join('') + '
';

  // 全部のキー操作イベントでバリデーションチェックかける
  $('.sch-upload-items input[name=title]').on('blur keypress keyup', function() {
    if ($(this).val().length > 0) {
      $(this).parents('.form-group').removeClass('has-danger');
      $(this).removeClass('form-control-danger');
      $(this).parents('.sch-upload-items').find('button.upload').removeAttr('disabled');
    } else {
      $(this).parents('.form-group').addClass('has-danger');
      $(this).addClass('form-control-danger');
      $(this).parents('.sch-upload-items').find('button.upload').attr('disabled', 'disabled');
    }
  }).trigger('blur');

  $('.sch-upload-items button.upload').on('click', function (evt) {
    var item = $(this).parents('.sch-upload-items');
    var id = item.data('id');
    var props = {
      title: $('input[name=title]', item).val(),
      description: $('textarea[name=description]', item).val(),
    }

    var delkey = $('input[name=delete_key]', item).val()
    if (delkey) { // 16進数化
      var shainfo = CryptoJS.SHA256(delkey);
      var hashstr = '';
      for (var i = 0; i < shainfo.words.length; i++) {
        hashstr += (shainfo.words[i] >>> 0).toString(16);
      }
      props['delete_key'] = hashstr;
    }

    $('button', item).attr('disabled', 'disabled');

    uploadSchematicFile(uploadFilesCache[id], props, (error, responce) => {
      if (error) {
        $('button', item).removeAttr('disabled');
       console.log('id' + id + 'がアップロードエラー起こしてます');
      } else {
        document.getElementById('list').innerHTML = '';
        uploadFilesCache.splice(id, 1);
        renderOutput(uploadFilesCache);
      }
    });
  })

  $('.sch-upload-items button.cancel').on('click', function (evt) {
    var id = $(this).parents('.sch-upload-items').data('id');

    document.getElementById('list').innerHTML = '';
    uploadFilesCache.splice(id, 1);
    renderOutput(uploadFilesCache);
  })
}

function handleFileSelect(evt) {
  this.className = '';
  evt.stopPropagation();
  evt.preventDefault();

  for (var i = 0, f; f = evt.dataTransfer.files[i]; i++) {
    uploadFilesCache.push(f);
  }

  renderOutput(uploadFilesCache);
}

function handleDragOver(evt) {
  this.className = 'hover';
  evt.stopPropagation();
  evt.preventDefault();
  evt.dataTransfer.dropEffect = 'link'; // Explicitly show this is a copy.
}
function handleDragLeave(evt) {
  this.className = '';
}

// Setup the dnd listeners.
var dropZone = document.getElementById('drop-zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('dragleave', handleDragLeave, false);
dropZone.addEventListener('drop', handleFileSelect, false);

// document.getElementById('sch-reload').addEventListener('click', reloadSchematics, false);
$('#sch-files').bootstrapTable({
  toolbar: '#sch-toolbar',
  columns: [
    { title: '名前', field: 'title' },
    { title: 'ファイル名', field: 'filename' },
    { title: 'アップロード日時', field: 'upload_date', formatter: (d) => {console.log(); return ''} },
    { title: '詳細', field: 'description' },
    { title: 'ダウンロード', field: 'download',
      formatter: (param, record, id) => {
        var downloadUrl = uploaderApiURL + '/schematics/' + record.filename + '/download';
        return 'ダウンロード '} },
  ],
  onRefresh: () => { reloadSchematics(); lastUpdateTime = Date.now(); startUTDisplay(); }
});
$('#sch-files').bootstrapTable('refresh');
$('#sch-toolbar > button.refresh').on('click', () => {
  $('#sch-toolbar > button.refresh').attr('disabled', 'disabled');
  $('#sch-files').bootstrapTable('refresh');
  setTimeout(() => $('#sch-toolbar > button.refresh').removeAttr('disabled'), 1000);
});

var schUTDisplay = $('#sch-toolbar > span.updated-time')[0];
var schUTUpdateTimer = null;
function startUTDisplay() {
  // 多重起動防止
  if (schUTUpdateTimer != null) return;

  schUTUpdateTimer = setInterval( () => {
    if (lastUpdateTime < 1) schUTDisplay.textContent = '';
    else if ((Date.now() - lastUpdateTime) > 3600000) {
      schUTDisplay.innerHTML = '下記のリストは1時間以上更新されていません。';
      clearInterval(schUTUpdateTimer);
      schUTUpdateTimer = null;
    } else {
      var time = Math.floor((Date.now() - lastUpdateTime) / 1000);
      if (time > 300) time = '' + time + '秒';
      else time += '秒';
      schUTDisplay.innerHTML = '最終更新から ' + time + ' 経過しています。';
    }
  }, 500);
}

window.schFilesHelper = {
  updateData: (data) => {
    const sf = $('#sch-files');
    sf.bootstrapTable('removeAll');
    data.forEach((d) => {
      sf.bootstrapTable('append', Object.assign({title:'', filename: '', upload_date: 0, description: '', download: ''}, d));
    });
  }
}
<commit_msg>アップロード時のパラメータ処理を改善<commit_after>const uploaderApiURL = 'http://mcmap.sasrai.jp/%E9%85%94%E3%81%84%E3%81%A9%E3%82%8C/uploader/api';
var lastUpdateTime = -1;
var uploadFilesCache = [];

function reloadSchematics() {
  axios.get(uploaderApiURL + '/schematics?' + Date.now())
  .then((response) => {
    schFilesHelper.updateData(response.data);
  })
  .catch((error) => {
    console.log(error);
  });
}

function uploadSchematicFile(file, props, cb) {
  var data = new FormData();
  for (var k in props) {
    data.append(k, props[k]);
  }
  data.append('sch_file', file);

  axios.post(uploaderApiURL + '/schematics/upload', data)
  .then((response) => {
    setTimeout(() => $('#sch-files').bootstrapTable('refresh'));
    if (cb && typeof cb == 'function') cb(null, response);
  })
  .catch((error) => {
    console.log(error);
    if (cb && typeof cb == 'function') cb(error, null);
  })
}

function renderOutput(files) {
  // files is a FileList of File objects. List some properties.
  var output = [];
  for (var i = 0, f; f = files[i]; i++) {
    output.push('

',
                '
' + escape(f.name) + '
',
                '
',
                  '
',
                    'タイトル',
                    '<input class="form-control" name="title" id="' + i + '-title" placeholder="表示タイトルを入力してください(必須)">',
                  '
',
                  '
',
                    '詳細',
                    '<textarea class="form-control" name="description" id="' + i + '-description" rows="2" placeholder="ファイルの説明分を入力してください(任意)"></textarea>',
                  '
',
                  '
',
                    '削除キー(処理未実装)',
                    '<input class="form-control" name="delete_key" id="' + i + '-delete_key" placeholder="削除キー(任意)">',
                  '
',
                  '
',
                    '<button type="button" class="btn btn-info upload">アップロード </button>',
                    '<button type="button" class="btn btn-secondary cancel">キャンセル</button>',
                  '
',
                '
',
                // f.size, ' bytes, last modified: ',
                // f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
                '

');
  }
  document.getElementById('list').innerHTML = '
' + output.join('') + '
';

  // 全部のキー操作イベントでバリデーションチェックかける
  $('.sch-upload-items input[name=title]').on('blur keypress keyup', function() {
    if ($(this).val().length > 0) {
      $(this).parents('.form-group').removeClass('has-danger');
      $(this).removeClass('form-control-danger');
      $(this).parents('.sch-upload-items').find('button.upload').removeAttr('disabled');
    } else {
      $(this).parents('.form-group').addClass('has-danger');
      $(this).addClass('form-control-danger');
      $(this).parents('.sch-upload-items').find('button.upload').attr('disabled', 'disabled');
    }
  }).trigger('blur');

  $('.sch-upload-items button.upload').on('click', function (evt) {
    var item = $(this).parents('.sch-upload-items');
    var id = item.data('id');
    var props = {
      title: $('input[name=title]', item).val(),
      description: $('textarea[name=description]', item).val(),
    }

    var delkey = $('input[name=delete_key]', item).val()
    if (delkey && delkey != '') { // 16進数化
      var shainfo = CryptoJS.SHA256(delkey);
      var hashstr = '';
      for (var i = 0; i < shainfo.words.length; i++) {
        hashstr += (shainfo.words[i] >>> 0).toString(16);
      }
      props['delete_key'] = hashstr;
    }

    $('button', item).attr('disabled', 'disabled');

    uploadSchematicFile(uploadFilesCache[id], props, (error, responce) => {
      if (error) {
        $('button', item).removeAttr('disabled');
       console.log('id' + id + 'がアップロードエラー起こしてます');
      } else {
        document.getElementById('list').innerHTML = '';
        uploadFilesCache.splice(id, 1);
        renderOutput(uploadFilesCache);
      }
    });
  })

  $('.sch-upload-items button.cancel').on('click', function (evt) {
    var id = $(this).parents('.sch-upload-items').data('id');

    document.getElementById('list').innerHTML = '';
    uploadFilesCache.splice(id, 1);
    renderOutput(uploadFilesCache);
  })
}

function handleFileSelect(evt) {
  this.className = '';
  evt.stopPropagation();
  evt.preventDefault();

  for (var i = 0, f; f = evt.dataTransfer.files[i]; i++) {
    uploadFilesCache.push(f);
  }

  renderOutput(uploadFilesCache);
}

function handleDragOver(evt) {
  this.className = 'hover';
  evt.stopPropagation();
  evt.preventDefault();
  evt.dataTransfer.dropEffect = 'link'; // Explicitly show this is a copy.
}
function handleDragLeave(evt) {
  this.className = '';
}

// Setup the dnd listeners.
var dropZone = document.getElementById('drop-zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('dragleave', handleDragLeave, false);
dropZone.addEventListener('drop', handleFileSelect, false);

// document.getElementById('sch-reload').addEventListener('click', reloadSchematics, false);
$('#sch-files').bootstrapTable({
  toolbar: '#sch-toolbar',
  columns: [
    { title: '名前', field: 'title' },
    { title: 'ファイル名', field: 'filename' },
    { title: 'アップロード日時', field: 'upload_date', formatter: (d) => {console.log(); return ''} },
    { title: '詳細', field: 'description' },
    { title: 'ダウンロード', field: 'download',
      formatter: (param, record, id) => {
        var downloadUrl = uploaderApiURL + '/schematics/' + record.filename + '/download';
        return 'ダウンロード '} },
  ],
  onRefresh: () => { reloadSchematics(); lastUpdateTime = Date.now(); startUTDisplay(); }
});
$('#sch-files').bootstrapTable('refresh');
$('#sch-toolbar > button.refresh').on('click', () => {
  $('#sch-toolbar > button.refresh').attr('disabled', 'disabled');
  $('#sch-files').bootstrapTable('refresh');
  setTimeout(() => $('#sch-toolbar > button.refresh').removeAttr('disabled'), 1000);
});

var schUTDisplay = $('#sch-toolbar > span.updated-time')[0];
var schUTUpdateTimer = null;
function startUTDisplay() {
  // 多重起動防止
  if (schUTUpdateTimer != null) return;

  schUTUpdateTimer = setInterval( () => {
    if (lastUpdateTime < 1) schUTDisplay.textContent = '';
    else if ((Date.now() - lastUpdateTime) > 3600000) {
      schUTDisplay.innerHTML = '下記のリストは1時間以上更新されていません。';
      clearInterval(schUTUpdateTimer);
      schUTUpdateTimer = null;
    } else {
      var time = Math.floor((Date.now() - lastUpdateTime) / 1000);
      if (time > 300) time = '' + time + '秒';
      else time += '秒';
      schUTDisplay.innerHTML = '最終更新から ' + time + ' 経過しています。';
    }
  }, 500);
}

window.schFilesHelper = {
  updateData: (data) => {
    const sf = $('#sch-files');
    sf.bootstrapTable('removeAll');
    data.forEach((d) => {
      sf.bootstrapTable('append', Object.assign({title:'', filename: '', upload_date: 0, description: '', download: ''}, d));
    });
  }
}
<|endoftext|>


<commit_before>var page = require('webpage').create();
var _ = require('underscore');
var fs = require('fs');

function stdout(str) {
  fs.write('/dev/stdout', str, 'w')
}

function stderr(str) {
  fs.write('/dev/stderr', str, 'w')
}

page.onAlert = stdout;
page.onConsoleMessage = stdout;
page.onError = stderr;

page.onLoadFinished = function() {
  phantom.exit();
};

page.open(phantom.args[0]);
<commit_msg>Use `system` module for phantom runner script stdout/stderr<commit_after>var page = require('webpage').create();
var _ = require('underscore');
var system = require('system');

page.onAlert = system.stdout.write;
page.onConsoleMessage = system.stdout.write;
page.onError = system.stderr.write;

page.onLoadFinished = function() {
  phantom.exit(0);
};

page.open(phantom.args[0]);
<|endoftext|>


<commit_before>!( function( factory ) {
  if ( typeof define === "function" && define.amd ) {
    define( factory );
  } else {
    factory( );
  }
}(function(){

  var fn = function(html) {
    //var html = document.getElementById(id).innerHTML;

    var code =  "var p = [], print = Array.prototype.push.bind(p); with(obj) { " +
      "p.push('" +
      html
        .replace(/[\r\n\t]/g, "")
        // Fix bug like: data-keyword='<%=JSON.stringify(obj)%>'
        // Because ' is key word in this string.
        .replace(/'/g, "\t")
        .replace(/<%=(.*?)%>/g, "'); p.push($1); p.push('")
        .replace(/<%/g, "');")
        .replace(/%>/g, "; p.push('") +
      "');}" +

        // Fix bug
      "return p.join('').replace(/\t/g, \"'\");";
    var fn = new Function('obj', code);

    // try {
    //   html = fn(data);
    // } catch (e) {
    //   console.log(e.message);
      // window.T = {};
      // window.T.code = code
      // window.T.fn = fn;
      // window.T.data = data;

    //   html = ""
    // }
    return fn;
  }

  var namespace = '_',
      updateBy = function(d) {
        try {
          var holder = this[namespace + 'holder'] || ( this.getAttribute('data-holder') && document.querySelector(this.getAttribute('data-holder')) );
          if (!holder) {
            console.log('Holder is empty.')
            return;
          }
          holder.innerHTML = this[namespace + 'fn'](d);
        } catch (e) {
          console.log(e);
        }
      },
      appendBy = function(d) {
        try {
          var holder = this[namespace + 'holder'] || ( this.getAttribute('data-holder') && document.querySelector(this.getAttribute('data-holder')) );
          if (!holder) {
            console.log('Holder is empty.')
            return;
          }

          var wrapper = this.getAttribute('data-wrapper');

          if (wrapper) {
            wrapper = document.createElement(wrapper)
            wrapper.innerHTML = this[namespace + 'fn'](d);
            while (wrapper.children.length > 0)
              holder.appendChild(wrapper.children[0])
          } else {
            holder.innerHTML += this[namespace + 'fn'](d);
          }

        } catch (e) {
          console.log(e);
        }
      },
      htmlBy = function(d) {
        try {
          return this[namespace + 'fn'](d);
        } catch (e) {
          console.log(e);
        }
      };

  var init = function() {

    var i         = 0,
        eles      = document.querySelectorAll('[data-role="template"]'),
        max       = eles.length,
        ele;

    for (;i < max; i++) {
      ele = eles[i];

      if (ele[namespace + 'inited'] === undefined) {
        ele[namespace + 'inited'] = true;

        // Cache function code
        ele[namespace + 'fn'] = fn(ele.innerHTML);

        ele[namespace + 'updateBy'] = updateBy.bind(ele);
        ele[namespace + 'appendBy'] = appendBy.bind(ele);
        ele[namespace + 'htmlBy']   = htmlBy.bind(ele);
      }
    }
  }

  if (document.readyState === 'complete' || document.readyState === 'interactive') {
    init()
  } else {
    document.addEventListener('readystatechange', function(e) {
      if (document.readyState === 'interactive') {
        init();
      }
    })
  }

  document.addEventListener('reload', init)
  document.addEventListener('template-reload-it', function(e) {

    if (e.target.getAttribute('data-role') === 'template') {
      e.target[namespace + 'inited'] = true;
      // Cache function code
      e.target[namespace + 'fn'] = fn(e.target.innerHTML);

      e.target[namespace + 'updateBy'] = updateBy.bind(e.target);
      e.target[namespace + 'appendBy'] = appendBy.bind(e.target);
      e.target[namespace + 'htmlBy']   = htmlBy.bind(e.target);
    }
  })

  return null;
}));
<commit_msg>Updated: call reload for webcom after updated template.<commit_after>!( function( factory ) {
  if ( typeof define === "function" && define.amd ) {
    define( factory );
  } else {
    factory( );
  }
}(function(){

  var fn = function(html) {
    //var html = document.getElementById(id).innerHTML;

    var code =  "var p = [], print = Array.prototype.push.bind(p); with(obj) { " +
      "p.push('" +
      html
        .replace(/[\r\n\t]/g, "")
        // Fix bug like: data-keyword='<%=JSON.stringify(obj)%>'
        // Because ' is key word in this string.
        .replace(/'/g, "\t")
        .replace(/<%=(.*?)%>/g, "'); p.push($1); p.push('")
        .replace(/<%/g, "');")
        .replace(/%>/g, "; p.push('") +
      "');}" +

        // Fix bug
      "return p.join('').replace(/\t/g, \"'\");";
    var fn = new Function('obj', code);

    // try {
    //   html = fn(data);
    // } catch (e) {
    //   console.log(e.message);
      // window.T = {};
      // window.T.code = code
      // window.T.fn = fn;
      // window.T.data = data;

    //   html = ""
    // }
    return fn;
  }

  var namespace = '_',
      updateBy = function(d) {
        try {
          var holder = this[namespace + 'holder'] || ( this.getAttribute('data-holder') && document.querySelector(this.getAttribute('data-holder')) );
          if (!holder) {
            console.log('Holder is empty.')
            return;
          }
          holder.innerHTML = this[namespace + 'fn'](d);

          // Trigger Event for webcom
          document.dispatchEvent(new Event('webcom-reload'));
        } catch (e) {
          console.log(e);
        }
      },
      appendBy = function(d) {
        try {
          var holder = this[namespace + 'holder'] || ( this.getAttribute('data-holder') && document.querySelector(this.getAttribute('data-holder')) );
          if (!holder) {
            console.log('Holder is empty.')
            return;
          }

          var wrapper = this.getAttribute('data-wrapper');

          if (wrapper) {
            wrapper = document.createElement(wrapper)
            wrapper.innerHTML = this[namespace + 'fn'](d);
            while (wrapper.children.length > 0)
              holder.appendChild(wrapper.children[0])
          } else {
            holder.innerHTML += this[namespace + 'fn'](d);
          }

          // Trigger Event for webcom
          document.dispatchEvent(new Event('webcom-reload'));
        } catch (e) {
          console.log(e);
        }
      },
      htmlBy = function(d) {
        try {
          return this[namespace + 'fn'](d);
        } catch (e) {
          console.log(e);
        }
      };

  var init = function() {

    var i         = 0,
        eles      = document.querySelectorAll('[data-role="template"]'),
        max       = eles.length,
        ele;

    for (;i < max; i++) {
      ele = eles[i];

      if (ele[namespace + 'inited'] === undefined) {
        ele[namespace + 'inited'] = true;

        // Cache function code
        ele[namespace + 'fn'] = fn(ele.innerHTML);

        ele[namespace + 'updateBy'] = updateBy.bind(ele);
        ele[namespace + 'appendBy'] = appendBy.bind(ele);
        ele[namespace + 'htmlBy']   = htmlBy.bind(ele);
      }
    }
  }

  if (document.readyState === 'complete' || document.readyState === 'interactive') {
    init()
  } else {
    document.addEventListener('readystatechange', function(e) {
      if (document.readyState === 'interactive') {
        init();
      }
    })
  }

  document.addEventListener('reload', init)
  document.addEventListener('template-reload-it', function(e) {

    if (e.target.getAttribute('data-role') === 'template') {
      e.target[namespace + 'inited'] = true;
      // Cache function code
      e.target[namespace + 'fn'] = fn(e.target.innerHTML);

      e.target[namespace + 'updateBy'] = updateBy.bind(e.target);
      e.target[namespace + 'appendBy'] = appendBy.bind(e.target);
      e.target[namespace + 'htmlBy']   = htmlBy.bind(e.target);
    }
  })

  return null;
}));
<|endoftext|>


<commit_before>/* eslint-disable */
'use strict';
(function ($) {
  var WEBSOCKET_ADDRESS = 'ws://localhost:8887';
  var HISTOGRAM_T = 10;

  var chart, histogram, wonIndices, wonChartData, valuesEl, initDone;

  /**
   * Attempt to establish new websockets connection
   * @param {Function} messageCB onmessage function callback.
   */
  function connectWS(messageCB) {
    // Init websockets with globally defined address.
    ws = new WebSocket(WEBSOCKET_ADDRESS);
    ws.onopen = function() {
      // Print a message when connection opens.
      console.log('open on ' + WEBSOCKET_ADDRESS);
    };
    ws.onclose = function() {
      initDone = false;
      // Print a message when connection closes.
      console.log('Websocket closed. Trying to reconnect.');
      // Call this function again (try to reconnect).
      setTimeout(function() {
        connectWS(messageCB);
      }, 1000);
    };
    // Set passed function as onmessage callback.
    ws.onmessage = messageCB;
  }

  /**
   * Websocket onmessage callback function.
   * @param {Object} e Event (with `data`) passed from server.
   */
  function messageRecieved(e) {
    var data = JSON.parse(e.data);
    if (data.message && data.message === 'init' && !initDone) {
      // saveChartToImg();
      saveWon();
      colors = data.colors;
      probabilities = data.p;
      displayProbabilites(probabilities, colors);
      initChart(colors);
      ws.send('init-ok');
      initDone = true;
    } else if (chart && !data.message) {
      updateChart(data);
    }
  }

  function initDatapoints() {
    if (datapoints) {
      for (var i = 0; i < datapoints.length; i++) {
        datapoints[i].splice(0);
      }
    }
  }

  function initChart(colors) {
    datapoints = [];
    var chartData = [];
    for (var i = 0; i < 10; i++) {
      datapoints.push([]);
      chartData.push({
        type: 'line',
        dataPoints: datapoints[i],
        markerType: 'none'
      });
    }
    initDatapoints();

    CanvasJS.addColorSet('graphColors', colors);

    chart = new CanvasJS.Chart('chartContainer', {
      title: {
        text: 'Color percentage'
      },
      colorSet: 'graphColors',
      height: 500,
      axisX: {
        title: 'time [iterations]',
        minimum: 0
      },
      axisY: {
        title: 'percentage',
        minimum: 0,
        maximum: 1.0
      },
      data: chartData
    });

    return chart;
  }

  function saveWon() {
    try {
      if (datapoints) {
        var i;
        for (i = 0; i < datapoints.length; i++) {
          var y = datapoints[i][datapoints[i].length - 1];
          if (y === 1) {
            break;
          }
        }
        wonIndices.push(i);
      }
    } catch (e) {}
  }

  function saveChartToImg() {
    console.log('try save');
    try {
      if (datapoints) {
        var canvas = document.querySelector('#chartContainer canvas');
        var img = canvas.toDataURL('image/png');
        var imageContainer = document.getElementById('slike');
        var newImage = new Image();
        newImage.src = img;
        imageContainer.appendChild(newImage);
        console.log('saved');
      }
    } catch (e) {}
  }

  function updateChart(data) {
    var color = data[0], lastColor = datapoints[0][datapoints[0].length - 1];
    if (color && lastColor && color.x <= lastColor.x) {
      saveChartToImg();
      initDatapoints();
    }
    data.forEach(function(e, i) {
      datapoints[i].push(e);
    });
    chart.render();
  }

  function displayProbabilites(data, colors) {
    valuesEl.empty();
    for (var i = 0; i < data.length; i++) {
      var p = data[i];
      var c = colors[i];
      valuesEl.append($('<span>')
        .addClass('value')
        .text(p)
        .css('border', '8px solid ' + c));
    }
  }

  $(function() {
    chart = null;
    histogram = null;
    wonIndices = [];
    wonChartData = [];
    valuesEl = $('#values');
    initDone = false;
    connectWS(messageRecieved);
  });

})(jQuery);
<commit_msg>Revert "wrap main.js in iife, change globals to iife scoped var"<commit_after>var WEBSOCKET_ADDRESS = 'ws://localhost:8887';
var HISTOGRAM_T = 10;

/**
 * Attempt to establish new websockets connection
 * @param {Function} messageCB onmessage function callback.
 */
function connectWS(messageCB) {
  // Init websockets with globally defined address.
  ws = new WebSocket(WEBSOCKET_ADDRESS);
  ws.onopen = function() {
    // Print a message when connection opens.
    console.log('open on ' + WEBSOCKET_ADDRESS);
  };
  ws.onclose = function() {
    initDone = false;
    // Print a message when connection closes.
    console.log('Websocket closed. Trying to reconnect.');
    // Call this function again (try to reconnect).
    setTimeout(function() {
      connectWS(messageCB);
    }, 1000);
  };
  // Set passed function as onmessage callback.
  ws.onmessage = messageCB;
}

/**
 * Websocket onmessage callback function.
 * @param {Object} e Event (with `data`) passed from server.
 */
function messageRecieved(e) {
  var data = JSON.parse(e.data);
  if (data.message && data.message === 'init' && !initDone) {
    // saveChartToImg();
    saveWon();
    colors = data.colors;
    probabilities = data.p;
    displayProbabilites(probabilities, colors);
    initChart(colors);
    ws.send('init-ok');
    initDone = true;
  } else if (chart && !data.message) {
    updateChart(data);
  }
}

function initDatapoints() {
  if (datapoints) {
    for (var i = 0; i < datapoints.length; i++) {
      datapoints[i].splice(0);
    }
  }
}

function initChart(colors) {
  datapoints = [];
  var chartData = [];
  for (var i = 0; i < 10; i++) {
    datapoints.push([]);
    chartData.push({
      type: 'line',
      dataPoints: datapoints[i],
      markerType: 'none'
    });
  }
  initDatapoints();

  CanvasJS.addColorSet('graphColors', colors);

  chart = new CanvasJS.Chart('chartContainer', {
    title: {
      text: 'Color percentage'
    },
    colorSet: 'graphColors',
    height: 500,
    axisX: {
      title: 'time [iterations]',
      minimum: 0
    },
    axisY: {
      title: 'percentage',
      minimum: 0,
      maximum: 1.0
    },
    data: chartData
  });

  return chart;
}

function saveWon() {
  try {
    if (datapoints) {
      var i;
      for (i = 0; i < datapoints.length; i++) {
        var y = datapoints[i][datapoints[i].length - 1];
        if (y === 1) {
          break;
        }
      }
      wonIndices.push(i);
    }
  } catch (e) {}
}

function saveChartToImg() {
  console.log('try save');
  try {
    if (datapoints) {
      var canvas = document.querySelector('#chartContainer canvas');
      var img = canvas.toDataURL('image/png');
      var imageContainer = document.getElementById('slike');
      var newImage = new Image();
      newImage.src = img;
      imageContainer.appendChild(newImage);
      console.log('saved');
    }
  } catch (e) {}
}

function updateChart(data) {
  var color = data[0],
    lastColor = datapoints[0][datapoints[0].length - 1];
  if (color && lastColor && color.x <= lastColor.x) {
    saveChartToImg();
    initDatapoints();
  }
  data.map(function(e, i) {
    datapoints[i].push(e);
  });
  chart.render();
}

function displayProbabilites(data, colors) {
  valuesEl.empty();
  for (var i = 0; i < data.length; i++) {
    var p = data[i];
    var c = colors[i];
    valuesEl.append($('<span>')
      .addClass('value')
      .text(p)
      .css('border', '8px solid ' + c));
  }
}

$(function() {
  chart = null;
  histogram = null;
  wonIndices = [];
  wonChartData = [];
  valuesEl = $('#values');
  initDone = false;
  connectWS(messageRecieved);
});
<|endoftext|>


<commit_before>const BinarySocket  = require('./socket_base');
const ClientBase    = require('./client_base');
const TrafficSource = require('../../app/common/traffic_source');
const licenseID     = require('../utility').lc_licenseID;

const LiveChat = (() => {
    const utm_data = TrafficSource.getData();
    const utm_source = TrafficSource.getSource(utm_data) || '';
    const utm_campaign = utm_data.utm_campaign || '';
    const utm_medium = utm_data.utm_medium || '';
    let session_variables = { is_logged_in: false, loginid: '', landing_company_shortcode: '', currency: '', residence: '', email: '', utm_source , utm_medium, utm_campaign };
    let client_email, first_name, last_name;

    const setSessionVariables = () => {
        const is_logged_in = !!ClientBase.isLoggedIn();
        const loginid = ClientBase.get('loginid');
        const landing_company_shortcode = ClientBase.get('landing_company_shortcode');
        const currency = ClientBase.get('currency');
        const residence = ClientBase.get('residence');
        const email = ClientBase.get('email');

        session_variables = {
            ...is_logged_in && { is_logged_in },
            ...loginid && { loginid },
            ...landing_company_shortcode && { landing_company_shortcode },
            ...currency && { currency },
            ...residence && { residence },
            ...email && { email },
            ...utm_source && { utm_source },
            ...utm_campaign && { utm_campaign },
            ...utm_medium && { utm_medium },
        };
        window.LiveChatWidget.call('set_session_variables', session_variables);
    };

    const setNameEmail = () => {
        if (client_email) window.LiveChatWidget.call('set_customer_email', client_email);
        if (first_name && last_name) window.LiveChatWidget.call('set_customer_name', `${first_name} ${last_name}`);
    };

    BinarySocket.wait('get_settings').then((response) => {
        const get_settings = response.get_settings || {};
        first_name = get_settings.first_name;
        last_name = get_settings.last_name;
        client_email = ClientBase.get('email');

        setSessionVariables();
        setNameEmail();

        window.LC_API.on_chat_ended = () => {
            setNameEmail();
        };
    });

    const initialize = () => {
        if (window.LiveChatWidget) {
            window.LiveChatWidget.on('ready', () => {
                window.LiveChatWidget.call('set_session_variables', session_variables);
                if (!ClientBase.isLoggedIn()){
                    window.LC_API.on_chat_ended = () => {
                        window.LiveChatWidget.call('set_customer_email', ' ');
                        window.LiveChatWidget.call('set_customer_name', ' ');
                    };
                } else {
                    window.LC_API.on_chat_ended = () => {
                        setNameEmail();
                    };
                }
            });
        }
    };

    // Fallback LiveChat icon
    const livechatFallback = () => {
        let livechat_shell;
        const livechat_id = 'gtm-deriv-livechat';

        if (window.LiveChatWidget){
            window.LiveChatWidget.on('ready', () => {
                livechat_shell = document.getElementById(livechat_id);
                livechat_shell.style.display = 'flex';
                livechat_shell.addEventListener('click', () => window.LC_API.open_chat_window());
            });
        }

    };

    // Delete existing LiveChat instance when there is no chat running
    const livechatDeletion = () => new Promise ((resolve) => {
        if (window.LiveChatWidget){
            window.LiveChatWidget.on('ready', () => {
                try {
                    if (window.LiveChatWidget.get('customer_data').status !== 'chatting') {
                        window.LiveChatWidget.call('destroy');
                        resolve();
                    }
                } catch (e) {
                    resolve();
                }
            });
        } else {
            resolve();
        }
    });

    // LiveChat initialisation code (provided by LiveChat)
    const liveChatInitialization = () => new Promise ((resolve) => {
        window.__lc = window.__lc || {}; // eslint-disable-line
        window.__lc.license = licenseID; // eslint-disable-line
        ;(function(n,t,c){function i(n){return e._h?e._h.apply(null,n):e._q.push(n)}var e={_q:[],_h:null,_v:"2.0",on:function(){i(["on",c.call(arguments)])},once:function(){i(["once",c.call(arguments)])},off:function(){i(["off",c.call(arguments)])},get:function(){if(!e._h)throw new Error("[LiveChatWidget] You can't use getters before load.");return i(["get",c.call(arguments)])},call:function(){i(["call",c.call(arguments)])},init:function(){var n=t.createElement("script");n.async=!0,n.type="text/javascript",n.src="https://cdn.livechatinc.com/tracking.js",t.head.appendChild(n)}};!n.__lc.asyncInit&&e.init(),n.LiveChatWidget=n.LiveChatWidget||e}(window,document,[].slice)) //eslint-disable-line
        resolve();
    });

    // Reroute group
    const rerouteGroup = () => {
        LiveChat.livechatDeletion().then(() => {
            LiveChat.liveChatInitialization().then(() => {
                LiveChat.initialize();
            });
        });
    };

    return {
        initialize,
        livechatDeletion,
        livechatFallback,
        liveChatInitialization,
        rerouteGroup,
    };
})();

module.exports = LiveChat;
<commit_msg>suthesh/livechat-hotfix (#6487)<commit_after>const BinarySocket  = require('./socket_base');
const ClientBase    = require('./client_base');
const TrafficSource = require('../../app/common/traffic_source');
const licenseID     = require('../utility').lc_licenseID;

const LiveChat = (() => {

    let client_email, first_name, last_name;

    const setSessionVariables = () => {
        const utm_data = TrafficSource.getData();
        const utm_source = TrafficSource.getSource(utm_data);
        const utm_campaign = utm_data.utm_campaign;
        const utm_medium = utm_data.utm_medium;
        const is_logged_in = !!ClientBase.isLoggedIn();
        const loginid = ClientBase.get('loginid');
        const landing_company_shortcode = ClientBase.get('landing_company_shortcode');
        const currency = ClientBase.get('currency');
        const residence = ClientBase.get('residence');
        const email = ClientBase.get('email');

        const session_variables = {
            is_logged_in,
            ...loginid && { loginid },
            ...landing_company_shortcode && { landing_company_shortcode },
            ...currency && { currency },
            ...residence && { residence },
            ...email && { email },
            ...utm_source && { utm_source },
            ...utm_campaign && { utm_campaign },
            ...utm_medium && { utm_medium },
        };
        window.LiveChatWidget.call('set_session_variables', session_variables);
    };

    const setNameEmail = () => {
        if (client_email) window.LiveChatWidget.call('set_customer_email', client_email);
        if (first_name && last_name) window.LiveChatWidget.call('set_customer_name', `${first_name} ${last_name}`);
    };

    BinarySocket.wait('get_settings').then((response) => {
        const get_settings = response.get_settings || {};
        first_name = get_settings.first_name;
        last_name = get_settings.last_name;
        client_email = ClientBase.get('email');

        setSessionVariables();
        setNameEmail();

        window.LC_API.on_chat_ended = () => {
            setNameEmail();
        };
    });

    const initialize = () => {
        if (window.LiveChatWidget) {
            window.LiveChatWidget.on('ready', () => {
                setSessionVariables();
                if (!ClientBase.isLoggedIn()){
                    window.LC_API.on_chat_ended = () => {
                        window.LiveChatWidget.call('set_customer_email', ' ');
                        window.LiveChatWidget.call('set_customer_name', ' ');
                    };
                } else {
                    window.LC_API.on_chat_ended = () => {
                        setNameEmail();
                    };
                }
            });
        }
    };

    // Fallback LiveChat icon
    const livechatFallback = () => {
        let livechat_shell;
        const livechat_id = 'gtm-deriv-livechat';

        if (window.LiveChatWidget){
            window.LiveChatWidget.on('ready', () => {
                livechat_shell = document.getElementById(livechat_id);
                livechat_shell.style.display = 'flex';
                livechat_shell.addEventListener('click', () => window.LC_API.open_chat_window());
            });
        }

    };

    // Delete existing LiveChat instance when there is no chat running
    const livechatDeletion = () => new Promise ((resolve) => {
        if (window.LiveChatWidget){
            window.LiveChatWidget.on('ready', () => {
                try {
                    if (window.LiveChatWidget.get('customer_data').status !== 'chatting') {
                        window.LiveChatWidget.call('destroy');
                        resolve();
                    }
                } catch (e) {
                    resolve();
                }
            });
        } else {
            resolve();
        }
    });

    // LiveChat initialisation code (provided by LiveChat)
    const liveChatInitialization = () => new Promise ((resolve) => {
        window.__lc = window.__lc || {}; // eslint-disable-line
        window.__lc.license = licenseID; // eslint-disable-line
        ;(function(n,t,c){function i(n){return e._h?e._h.apply(null,n):e._q.push(n)}var e={_q:[],_h:null,_v:"2.0",on:function(){i(["on",c.call(arguments)])},once:function(){i(["once",c.call(arguments)])},off:function(){i(["off",c.call(arguments)])},get:function(){if(!e._h)throw new Error("[LiveChatWidget] You can't use getters before load.");return i(["get",c.call(arguments)])},call:function(){i(["call",c.call(arguments)])},init:function(){var n=t.createElement("script");n.async=!0,n.type="text/javascript",n.src="https://cdn.livechatinc.com/tracking.js",t.head.appendChild(n)}};!n.__lc.asyncInit&&e.init(),n.LiveChatWidget=n.LiveChatWidget||e}(window,document,[].slice)) //eslint-disable-line
        resolve();
    });

    // Reroute group
    const rerouteGroup = () => {
        LiveChat.livechatDeletion().then(() => {
            LiveChat.liveChatInitialization().then(() => {
                LiveChat.initialize();
            });
        });
    };

    return {
        initialize,
        livechatDeletion,
        livechatFallback,
        liveChatInitialization,
        rerouteGroup,
    };
})();

module.exports = LiveChat;
<|endoftext|>


<commit_before>'use strict'
module.exports = stdoutToComments

const acorn = require('acorn')
const walk = require('acorn/dist/walk')
const fs = require('fs')
const spawn = require('cross-spawn-async')
const path = require('path')
const SourceMapConsumer = require('source-map').SourceMapConsumer
const normalizePath = require('normalize-path')
const hookPath = normalizePath(path.resolve(__dirname, './hook-console-log'))
const position = require('file-position')
const normalizeNewline = require('normalize-newline')
const consoleStringify = require('./console-stringify')

function stdoutToComments (opts) {
  if (typeof opts === 'string') opts = { code: opts }

  const cwd = opts.cwd || process.cwd()

  return new Promise((resolve, reject) => {
    const content = normalizeNewline(opts.code)

    const tmpFileName = normalizePath(path.resolve(cwd, `_${Math.random()}.js`))
    fs.writeFileSync(tmpFileName, addHook({
      code: content,
      filePath: tmpFileName,
    }), 'utf8')

    const outputs = []
    let failed = false

    const cp = spawn('node', [tmpFileName])
    cp.stdout.setEncoding('utf8')
    cp.stderr.setEncoding('utf8')
    cp.stdout.on('data', data => {
      try {
        data.split('\n$\n')
          .filter(outputJSON => !!outputJSON)
          .map(outputJSON => JSON.parse(outputJSON))
          .forEach(outputInfo => outputs.push(outputInfo))
      } catch (err) {
        failed = true
        reject(err)
      }
    })
    let errData = ''
    cp.stderr.on('data', data => { errData += data })
    cp.on('close', code => {
      fs.unlinkSync(tmpFileName)

      if (errData) {
        return reject(new Error(errData))
      }

      if (failed) {
        return
      }

      if (!opts.map) {
        return resolve(insertOutputsToCode(content, outputs))
      }
      const consumer = new SourceMapConsumer(opts.map)
      const originalOutputs = outputs
        .map(output => Object.assign({}, output, consumer.originalPositionFor({
          line: output.line,
          column: output.column,
        })))
      const sourcesContent = JSON.parse(opts.map).sourcesContent
      const sourceContent = sourcesContent[sourcesContent.length - 1]
      resolve(insertOutputsToCode(sourceContent, originalOutputs))
    })
  })
}

function insertOutputsToCode (content, outputs) {
  const codeLines = splitIntoLines(content)
  const sOutputs = moveOutputsBeloveStatement(outputs, codeLines, content)

  return codeLines.reduce((contentLines, line, index) => {
    contentLines.push(line)
    const lineNo = index + 1
    while (sOutputs.length && sOutputs[0].line === lineNo) {
      const matches = (contentLines[contentLines.length - 1] || '').match(/^(\s*)/)
      const linePadding = matches && matches[0] || ''
      const output = consoleStringify.apply(null, sOutputs.shift().args)
      contentLines.push(outputToComment(output, linePadding))
    }
    return contentLines
  }, []).join('\n')
}

function outputToComment (output, padding) {
  return `${padding}//> ${output.replace(/\r?\n/g, `\n${padding}//  `)}`
}

function moveOutputsBeloveStatement (outputs, codeLines, content) {
  const ast = acorn.parse(content, {locations: true, sourceType: 'module'})
  const getPosition = position(content)

  let semanticLineNo = 0
  const newOutputs = []
  for (let i = 0, lineNo = 0; i < outputs.length; i++) {
    if (outputs[i].line !== lineNo) {
      const pos = getPosition(outputs[i].line - 1, outputs[i].column)
      semanticLineNo = outputSemanticPosition(ast, pos)
    }
    newOutputs[i] = Object.assign(
      {},
      outputs[i],
      {
        line: semanticLineNo,
      }
    )
  }
  return newOutputs
}

function splitIntoLines (txt) {
  return txt.split('\n')
}

function outputSemanticPosition (ast, pos) {
  const node = walk.findNodeAround(ast, pos, 'ExpressionStatement')
  return node.node.loc.end.line
}

function addHook (opts) {
  if (!opts.code.match(/['"]use strict['"]/)) {
    return `require('${hookPath}')('${opts.filePath}');\n` + opts.code
  }
  return `'use strict';require('${hookPath}')('${opts.filePath}');\n` + opts.code
}
<commit_msg>refactor(stdout-to-comments): use reduse in moveOutputsBeloveStatement<commit_after>'use strict'
module.exports = stdoutToComments

const acorn = require('acorn')
const walk = require('acorn/dist/walk')
const fs = require('fs')
const spawn = require('cross-spawn-async')
const path = require('path')
const SourceMapConsumer = require('source-map').SourceMapConsumer
const normalizePath = require('normalize-path')
const hookPath = normalizePath(path.resolve(__dirname, './hook-console-log'))
const position = require('file-position')
const normalizeNewline = require('normalize-newline')
const consoleStringify = require('./console-stringify')

function stdoutToComments (opts) {
  if (typeof opts === 'string') opts = { code: opts }

  const cwd = opts.cwd || process.cwd()

  return new Promise((resolve, reject) => {
    const content = normalizeNewline(opts.code)

    const tmpFileName = normalizePath(path.resolve(cwd, `_${Math.random()}.js`))
    fs.writeFileSync(tmpFileName, addHook({
      code: content,
      filePath: tmpFileName,
    }), 'utf8')

    const outputs = []
    let failed = false

    const cp = spawn('node', [tmpFileName])
    cp.stdout.setEncoding('utf8')
    cp.stderr.setEncoding('utf8')
    cp.stdout.on('data', data => {
      try {
        data.split('\n$\n')
          .filter(outputJSON => !!outputJSON)
          .map(outputJSON => JSON.parse(outputJSON))
          .forEach(outputInfo => outputs.push(outputInfo))
      } catch (err) {
        failed = true
        reject(err)
      }
    })
    let errData = ''
    cp.stderr.on('data', data => { errData += data })
    cp.on('close', code => {
      fs.unlinkSync(tmpFileName)

      if (errData) {
        return reject(new Error(errData))
      }

      if (failed) {
        return
      }

      if (!opts.map) {
        return resolve(insertOutputsToCode(content, outputs))
      }
      const consumer = new SourceMapConsumer(opts.map)
      const originalOutputs = outputs
        .map(output => Object.assign({}, output, consumer.originalPositionFor({
          line: output.line,
          column: output.column,
        })))
      const sourcesContent = JSON.parse(opts.map).sourcesContent
      const sourceContent = sourcesContent[sourcesContent.length - 1]
      resolve(insertOutputsToCode(sourceContent, originalOutputs))
    })
  })
}

function insertOutputsToCode (content, outputs) {
  const codeLines = splitIntoLines(content)
  const sOutputs = moveOutputsBeloveStatement(outputs, codeLines, content)

  return codeLines.reduce((contentLines, line, index) => {
    contentLines.push(line)
    const lineNo = index + 1
    while (sOutputs.length && sOutputs[0].line === lineNo) {
      const matches = (contentLines[contentLines.length - 1] || '').match(/^(\s*)/)
      const linePadding = matches && matches[0] || ''
      const output = consoleStringify.apply(null, sOutputs.shift().args)
      contentLines.push(outputToComment(output, linePadding))
    }
    return contentLines
  }, []).join('\n')
}

function outputToComment (output, padding) {
  return `${padding}//> ${output.replace(/\r?\n/g, `\n${padding}//  `)}`
}

function moveOutputsBeloveStatement (outputs, codeLines, content) {
  const ast = acorn.parse(content, {locations: true, sourceType: 'module'})
  const getPosition = position(content)

  return outputs.reduce((semanticOutput, output) => {
    const pos = getPosition(output.line - 1, output.column)
    const semanticLineNo = outputSemanticPosition(ast, pos)
    return semanticOutput.concat(Object.assign(
      {},
      output,
      {
        line: semanticLineNo,
      }
    ))
  }, [])
}

function splitIntoLines (txt) {
  return txt.split('\n')
}

function outputSemanticPosition (ast, pos) {
  const node = walk.findNodeAround(ast, pos, 'ExpressionStatement')
  return node.node.loc.end.line
}

function addHook (opts) {
  if (!opts.code.match(/['"]use strict['"]/)) {
    return `require('${hookPath}')('${opts.filePath}');\n` + opts.code
  }
  return `'use strict';require('${hookPath}')('${opts.filePath}');\n` + opts.code
}
<|endoftext|>


<commit_before>var slider = function() {
    var slider = $('#slider');
    if (slider.size()) {
        $('.invisibleslides').show();
        slider.slides({
            container: 'slides-container',
            paginationClass: 'slides-pagination',
            generatePagination: false,
            generateNextPrev: false,
            start: 1,
            preload: true,
            play: 10000,
            slideSpeed: 800,
        });
        if ($('.slides_control').height() < 300) {
            $('.slides_control').css('min-height', '300px');
        }
    }
};

var sidebar_scroll = function(elm_selector) {
    elm_selector.on('click', '#sidebar-nav li', function() {
        var clicked_li = $(this);
        $.scrollTo($('.section:eq(' + clicked_li.index() + ')'), 500);
        return false;
    }).addClass('unbind_later');

    if (elm_selector.size()) {
        // grab the initial top offset of the navigation
        var selector = elm_selector.find('.sidebar');
        var width = selector.width();
        var sticky_navigation_offset_top = selector.offset().top;
        // With thanks:
        // http://www.backslash.gr/content/blog/webdevelopment/6-navigation-menu-that-stays-on-top-with-jquery

        // our function that decides weather the navigation bar should have "fixed" css position or not.
        var sticky_navigation = function() {
            var scroll_top = $(window).scrollTop(); // our current vertical position from the top

            // if we've scrolled more than the navigation, change its position to fixed to stick to top,
            // otherwise change it back to relative
            if (scroll_top > sticky_navigation_offset_top) {
                selector.css({'position': 'fixed', 'top': 0, 'width': width});
            } else {
                selector.css({'position': 'relative'});
            }
        };

        //run our function on load
        sticky_navigation();

        var sidebar_nav = selector.find('#sidebar-nav');
        var length = elm_selector.find('.section').length;
        $(window).on('scroll', function() {
            // and run it again every time you scroll
            sticky_navigation();

            for (var i = 0; i < length; i++) {
                if ($(window).scrollTop() === 0 || $(this).scrollTop() >= $('.section:eq(' + i + ')').offset().top - 5) {
                    sidebar_nav.find('li').removeClass('selected');

                    if ($(window).scrollTop() === 0) {
                        // We're at the top of the screen, so highlight first nav item
                        sidebar_nav.find('li:first-child').addClass('selected');
                    } else if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
                        // We're at bottom of screen so highlight last nav item.
                        sidebar_nav.find('li:last-child').addClass('selected');
                    } else {
                        sidebar_nav.find('li:eq(' + i + ')').addClass('selected');
                    }
                }
            }
        });
    }
};

var get_started_behaviour = function() {
    // Get Started behaviour:
    var update_active_subsection = function(to_show) {
        var fragment;
        var subsection = $('.subsection');
        subsection.addClass('hidden');
        to_show.removeClass('hidden');
        var nav_back = $('.subsection-navigation .back');
        var nav_next = $('.subsection-navigation .next');

        if (to_show.hasClass('first')) {
            nav_back.addClass('disabled');
            nav_next.removeClass('disabled');
        } else if (to_show.hasClass('last')) {
            nav_back.removeClass('disabled');
            nav_next.addClass('disabled');
        } else {
            nav_back.removeClass('disabled');
            nav_next.removeClass('disabled');
        }

        fragment = to_show.find('a[name]').attr('name').slice(0, -8);
        document.location.hash = fragment;

        return false;
    };
    var to_show;
    var nav = $('.get-started').find('.subsection-navigation');
    var fragment;
    var len = nav.length;

    if (len) {
        nav.on('click', 'a', function() {
            var button = $(this);
            if (button.hasClass('disabled')) {
                return false;
            }
            var now_showing = $('.subsection:not(.hidden)');
            var show = button.hasClass('next') ? now_showing.next('.subsection') : now_showing.prev('.subsection');
            return update_active_subsection(show);
        });

        fragment = (location.href.split('#'))[1];
        to_show = fragment ? $('a[name=' + fragment + '-section]').parent('.subsection') : $('.subsection.first');
        update_active_subsection(to_show);
    }

    var random_market = $('.random-markets');
    if (random_market.length > 0) {
        sidebar_scroll(random_market);
    }
};

var get_ticker = function() {
    var ticker = $('#hometicker');
    if (ticker.size()) {
        $.ajax({ crossDomain: true, url: page.url.url_for('ticker'), async: true, dataType: "html" }).done(function(ticks) {
            ticker.html(ticks);
            ticker.find('ul').simplyScroll();
        });
    }
};

var select_user_country = function() {
    if($('#residence').length > 0) {
        get_user_country(function() {
            var restricted_countries = new RegExp(page.settings.get('restricted_countries'));
            if(restricted_countries.test(this.country)) {
                $('#residence').val('default').change();
            } else {
                $('#residence').val(this.country).change();
            }
        });
    }
};

var Charts = function(charts) {
    window.open(charts, 'DetWin', 'width=580,height=710,scrollbars=yes,location=no,status=no,menubar=no');
};

var home_bomoverlay = {
    url : {
	    param : {
            get : function(name) {
                name = name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
                var regexS = "[\\?&]"+name+"=([^&#]*)";
                var regex = new RegExp(regexS);
                var results = regex.exec(window.location.href);
                return (results === null)? null:results[1];
            }
        }
    },

    init : function() {
        if (! this.url.param.get('frombom')) return;
        var obj = document.getElementById('banner').getElementsByClassName('wrapper')[0];
        var div = document.createElement('div');
        div.className = 'bomoverlay';
        obj.appendChild(div);
        div.addEventListener('click', function() { this.parentNode.removeChild(this); });
    }
};

var display_cs_contacts = function () {
    $('.contact-content').on("change", '#cs_telephone_number', function () {
        var val = $(this).val();
        $('#display_cs_telephone').text(val);
    });
    $('#cs_contact_eaddress').html("<n uers=\"znvygb:fhccbeg@ovanel.pbz\" ery=\"absbyybj\">fhccbeg@ovanel.pbz</n>".replace(/[a-zA-Z]/g, function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);}));
};

var change_chat_icon = function () {
  // desk.com change icon - crude way
  var len = $('#live-chat-icon').length;
  if( len > 0 ) {
      var timer = null;
      var updateIcon =  function () {
          var image_link = page.settings.get('image_link');
          var desk_widget = $('.a-desk-widget');
          var image_str = desk_widget.css('background-image');
          if(image_str) {
              desk_widget.css({
                  'background-image': 'url("' + image_link['livechaticon'] + '")',
                  'background-size': 'contain',
                  'min-width': 50,
                  'min-height': 50,
                  'width': 'auto'
              });
              desk_widget.hover(function() {
                  $(this).css({
                      'background': 'url("' + image_link['livechaticon'] + '") no-repeat scroll 0 0',
                      'background-size': 'contain',
                  });
              });

              if(image_str.match(/live-chat-icon/g)){
                  clearInterval(timer);
              }
          }
      };
      timer = setInterval(updateIcon, 500);
  }
};

var render_desk_widget = function() {
       new DESK.Widget({
                version: 1,
                site: 'binary.desk.com',
                port: '80',
                type: 'chat',
                id: 'live-chat-icon',
                displayMode: 0,  //0 for popup, 1 for lightbox
                features: {
                        offerAlways: true,
                        offerAgentsOnline: false,
                        offerRoutingAgentsAvailable: false,
                        offerEmailIfChatUnavailable: false
                },
                fields: {
                        ticket: {
                                // desc: '',
                // labels_new: '',
                // priority: '',
                // subject: '',
                // custom_loginid: ''
                        },
                        interaction: {
                                // email: '',
                // name: ''
                        },
                        chat: {
                                //subject: ''
                        },
                        customer: {
                                // company: '',
                // desc: '',
                // first_name: '',
                // last_name: '',
                // locale_code: '',
                // title: '',
                // custom_loginid: ''
                        }
                }
        }).render();
};

var show_live_chat_icon = function() {
    if(typeof DESK === 'undefined') {
        loadCSS("https://d3jyn100am7dxp.cloudfront.net/assets/widget_embed_191.cssgz?1367387331");
        loadJS("https://d3jyn100am7dxp.cloudfront.net/assets/widget_embed_libraries_191.jsgz?1367387332");
    }

    var desk_load = setInterval(function() {
        if(typeof DESK !== "undefined") {
            render_desk_widget();
            change_chat_icon();
            clearInterval(desk_load);
        }
    }, 80);
}

pjax_config_page('/$|/home', function() {
    return {
        onLoad: function() {
            slider();
            select_user_country();
            get_ticker();
            home_bomoverlay.init();
        }
    };
});

pjax_config_page('/why-us', function() {
    return {
        onLoad: function() {
            var whyus = $('.why-us');
            sidebar_scroll(whyus);
        },
        onUnload: function() {
            $(window).off('scroll');
        }
    };
});

pjax_config_page('/smart-indices', function() {
    return {
        onLoad: function() {
            sidebar_scroll($('.smart-indices'));
        },
        onUnload: function() {
            $(window).off('scroll');
        }
    };
});

pjax_config_page('/open-source-projects', function() {
    return {
        onLoad: function() {
            sidebar_scroll($('.open-source-projects'));
        },
        onUnload: function() {
            $(window).off('scroll');
        }
    };
});

pjax_config_page('/white-labels', function() {
    return {
        onLoad: function() {
            sidebar_scroll($('.white-labels'));
        },
        onUnload: function() {
            $(window).off('scroll');
        }
    };
});

pjax_config_page('/partnerapi', function() {
    return {
        onLoad: function() {
            var partnerapi = $('.partnerapi-content');
            sidebar_scroll(partnerapi);
        },
        onUnload: function() {
            $(window).off('scroll');
        }
    };
});

pjax_config_page('/get-started', function() {
    return {
        onLoad: function() {
            get_started_behaviour();
        },
        onUnload: function() {
            $(window).off('scroll');
        },
    };
});

pjax_config_page('/contact', function() {
    return {
        onLoad: function() {
            display_cs_contacts();
            show_live_chat_icon();
        },
    };
});
<commit_msg>Fix missing semicolon error<commit_after>var slider = function() {
    var slider = $('#slider');
    if (slider.size()) {
        $('.invisibleslides').show();
        slider.slides({
            container: 'slides-container',
            paginationClass: 'slides-pagination',
            generatePagination: false,
            generateNextPrev: false,
            start: 1,
            preload: true,
            play: 10000,
            slideSpeed: 800,
        });
        if ($('.slides_control').height() < 300) {
            $('.slides_control').css('min-height', '300px');
        }
    }
};

var sidebar_scroll = function(elm_selector) {
    elm_selector.on('click', '#sidebar-nav li', function() {
        var clicked_li = $(this);
        $.scrollTo($('.section:eq(' + clicked_li.index() + ')'), 500);
        return false;
    }).addClass('unbind_later');

    if (elm_selector.size()) {
        // grab the initial top offset of the navigation
        var selector = elm_selector.find('.sidebar');
        var width = selector.width();
        var sticky_navigation_offset_top = selector.offset().top;
        // With thanks:
        // http://www.backslash.gr/content/blog/webdevelopment/6-navigation-menu-that-stays-on-top-with-jquery

        // our function that decides weather the navigation bar should have "fixed" css position or not.
        var sticky_navigation = function() {
            var scroll_top = $(window).scrollTop(); // our current vertical position from the top

            // if we've scrolled more than the navigation, change its position to fixed to stick to top,
            // otherwise change it back to relative
            if (scroll_top > sticky_navigation_offset_top) {
                selector.css({'position': 'fixed', 'top': 0, 'width': width});
            } else {
                selector.css({'position': 'relative'});
            }
        };

        //run our function on load
        sticky_navigation();

        var sidebar_nav = selector.find('#sidebar-nav');
        var length = elm_selector.find('.section').length;
        $(window).on('scroll', function() {
            // and run it again every time you scroll
            sticky_navigation();

            for (var i = 0; i < length; i++) {
                if ($(window).scrollTop() === 0 || $(this).scrollTop() >= $('.section:eq(' + i + ')').offset().top - 5) {
                    sidebar_nav.find('li').removeClass('selected');

                    if ($(window).scrollTop() === 0) {
                        // We're at the top of the screen, so highlight first nav item
                        sidebar_nav.find('li:first-child').addClass('selected');
                    } else if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
                        // We're at bottom of screen so highlight last nav item.
                        sidebar_nav.find('li:last-child').addClass('selected');
                    } else {
                        sidebar_nav.find('li:eq(' + i + ')').addClass('selected');
                    }
                }
            }
        });
    }
};

var get_started_behaviour = function() {
    // Get Started behaviour:
    var update_active_subsection = function(to_show) {
        var fragment;
        var subsection = $('.subsection');
        subsection.addClass('hidden');
        to_show.removeClass('hidden');
        var nav_back = $('.subsection-navigation .back');
        var nav_next = $('.subsection-navigation .next');

        if (to_show.hasClass('first')) {
            nav_back.addClass('disabled');
            nav_next.removeClass('disabled');
        } else if (to_show.hasClass('last')) {
            nav_back.removeClass('disabled');
            nav_next.addClass('disabled');
        } else {
            nav_back.removeClass('disabled');
            nav_next.removeClass('disabled');
        }

        fragment = to_show.find('a[name]').attr('name').slice(0, -8);
        document.location.hash = fragment;

        return false;
    };
    var to_show;
    var nav = $('.get-started').find('.subsection-navigation');
    var fragment;
    var len = nav.length;

    if (len) {
        nav.on('click', 'a', function() {
            var button = $(this);
            if (button.hasClass('disabled')) {
                return false;
            }
            var now_showing = $('.subsection:not(.hidden)');
            var show = button.hasClass('next') ? now_showing.next('.subsection') : now_showing.prev('.subsection');
            return update_active_subsection(show);
        });

        fragment = (location.href.split('#'))[1];
        to_show = fragment ? $('a[name=' + fragment + '-section]').parent('.subsection') : $('.subsection.first');
        update_active_subsection(to_show);
    }

    var random_market = $('.random-markets');
    if (random_market.length > 0) {
        sidebar_scroll(random_market);
    }
};

var get_ticker = function() {
    var ticker = $('#hometicker');
    if (ticker.size()) {
        $.ajax({ crossDomain: true, url: page.url.url_for('ticker'), async: true, dataType: "html" }).done(function(ticks) {
            ticker.html(ticks);
            ticker.find('ul').simplyScroll();
        });
    }
};

var select_user_country = function() {
    if($('#residence').length > 0) {
        get_user_country(function() {
            var restricted_countries = new RegExp(page.settings.get('restricted_countries'));
            if(restricted_countries.test(this.country)) {
                $('#residence').val('default').change();
            } else {
                $('#residence').val(this.country).change();
            }
        });
    }
};

var Charts = function(charts) {
    window.open(charts, 'DetWin', 'width=580,height=710,scrollbars=yes,location=no,status=no,menubar=no');
};

var home_bomoverlay = {
    url : {
	    param : {
            get : function(name) {
                name = name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
                var regexS = "[\\?&]"+name+"=([^&#]*)";
                var regex = new RegExp(regexS);
                var results = regex.exec(window.location.href);
                return (results === null)? null:results[1];
            }
        }
    },

    init : function() {
        if (! this.url.param.get('frombom')) return;
        var obj = document.getElementById('banner').getElementsByClassName('wrapper')[0];
        var div = document.createElement('div');
        div.className = 'bomoverlay';
        obj.appendChild(div);
        div.addEventListener('click', function() { this.parentNode.removeChild(this); });
    }
};

var display_cs_contacts = function () {
    $('.contact-content').on("change", '#cs_telephone_number', function () {
        var val = $(this).val();
        $('#display_cs_telephone').text(val);
    });
    $('#cs_contact_eaddress').html("<n uers=\"znvygb:fhccbeg@ovanel.pbz\" ery=\"absbyybj\">fhccbeg@ovanel.pbz</n>".replace(/[a-zA-Z]/g, function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);}));
};

var change_chat_icon = function () {
  // desk.com change icon - crude way
  var len = $('#live-chat-icon').length;
  if( len > 0 ) {
      var timer = null;
      var updateIcon =  function () {
          var image_link = page.settings.get('image_link');
          var desk_widget = $('.a-desk-widget');
          var image_str = desk_widget.css('background-image');
          if(image_str) {
              desk_widget.css({
                  'background-image': 'url("' + image_link['livechaticon'] + '")',
                  'background-size': 'contain',
                  'min-width': 50,
                  'min-height': 50,
                  'width': 'auto'
              });
              desk_widget.hover(function() {
                  $(this).css({
                      'background': 'url("' + image_link['livechaticon'] + '") no-repeat scroll 0 0',
                      'background-size': 'contain',
                  });
              });

              if(image_str.match(/live-chat-icon/g)){
                  clearInterval(timer);
              }
          }
      };
      timer = setInterval(updateIcon, 500);
  }
};

var render_desk_widget = function() {
       new DESK.Widget({
                version: 1,
                site: 'binary.desk.com',
                port: '80',
                type: 'chat',
                id: 'live-chat-icon',
                displayMode: 0,  //0 for popup, 1 for lightbox
                features: {
                        offerAlways: true,
                        offerAgentsOnline: false,
                        offerRoutingAgentsAvailable: false,
                        offerEmailIfChatUnavailable: false
                },
                fields: {
                        ticket: {
                                // desc: '',
                // labels_new: '',
                // priority: '',
                // subject: '',
                // custom_loginid: ''
                        },
                        interaction: {
                                // email: '',
                // name: ''
                        },
                        chat: {
                                //subject: ''
                        },
                        customer: {
                                // company: '',
                // desc: '',
                // first_name: '',
                // last_name: '',
                // locale_code: '',
                // title: '',
                // custom_loginid: ''
                        }
                }
        }).render();
};

var show_live_chat_icon = function() {
    if(typeof DESK === 'undefined') {
        loadCSS("https://d3jyn100am7dxp.cloudfront.net/assets/widget_embed_191.cssgz?1367387331");
        loadJS("https://d3jyn100am7dxp.cloudfront.net/assets/widget_embed_libraries_191.jsgz?1367387332");
    }

    var desk_load = setInterval(function() {
        if(typeof DESK !== "undefined") {
            render_desk_widget();
            change_chat_icon();
            clearInterval(desk_load);
        }
    }, 80);
};

pjax_config_page('/$|/home', function() {
    return {
        onLoad: function() {
            slider();
            select_user_country();
            get_ticker();
            home_bomoverlay.init();
        }
    };
});

pjax_config_page('/why-us', function() {
    return {
        onLoad: function() {
            var whyus = $('.why-us');
            sidebar_scroll(whyus);
        },
        onUnload: function() {
            $(window).off('scroll');
        }
    };
});

pjax_config_page('/smart-indices', function() {
    return {
        onLoad: function() {
            sidebar_scroll($('.smart-indices'));
        },
        onUnload: function() {
            $(window).off('scroll');
        }
    };
});

pjax_config_page('/open-source-projects', function() {
    return {
        onLoad: function() {
            sidebar_scroll($('.open-source-projects'));
        },
        onUnload: function() {
            $(window).off('scroll');
        }
    };
});

pjax_config_page('/white-labels', function() {
    return {
        onLoad: function() {
            sidebar_scroll($('.white-labels'));
        },
        onUnload: function() {
            $(window).off('scroll');
        }
    };
});

pjax_config_page('/partnerapi', function() {
    return {
        onLoad: function() {
            var partnerapi = $('.partnerapi-content');
            sidebar_scroll(partnerapi);
        },
        onUnload: function() {
            $(window).off('scroll');
        }
    };
});

pjax_config_page('/get-started', function() {
    return {
        onLoad: function() {
            get_started_behaviour();
        },
        onUnload: function() {
            $(window).off('scroll');
        },
    };
});

pjax_config_page('/contact', function() {
    return {
        onLoad: function() {
            display_cs_contacts();
            show_live_chat_icon();
        },
    };
});
<|endoftext|>


<commit_before>(function() {
  var userStoryUuid = "ParallelEditWithoutConflicts";
  var testName = "basic";
  console.log("Running " + userStoryUuid + ":" + testName);

  var testResult = false;

  var commonAPI = new CommonAPI();
  var userStory = getUserStory(userStoryUuid);
  var test = getTest(userStory,testName);
  var inputFolder = "/" + userStoryUuid + "/" + testName + "/input/";

  console.log("input files");
  console.log(test.input);

  var initialFile = test.input[0],
  initialFileMessage = "I HAVE 3 ELEMENTS: a,b,c",
  alicesFile = test.input[1],
  alicesFileMessage = "I HAVE 2 ELEMENTS: a,c",
  bobsFile = test.input[2],
  bobsFileMessage = "I HAVE 3 ELEMENTS: a,b,c AND d WITHIN a",
  expectedFile = test.input[3],
  expectedFileMessage = "I HAVE 2 ELEMENTS: a,c AND d WITHIN a",
  actualFile;

  // console.log("initialFile:" + initialFile);
  // console.log("alicesFile:" + alicesFile);
  // console.log("bobsFile:" + bobsFile);
  // console.log("expectedFile:" + expectedFile);

  //PRECONDITIONS
  // "Repository exists"
  commonAPI.initRepo().then(
    function(data){
      // "File exists" and "File Content exists"
      return commonAPI.commitFile("nanme", inputFolder+initialFile, initialFileMessage, 0);
    },
    function(data){
      console.log("Failed to initRepo");
      reportIn(userStoryUuid,testName,"error");
    }
  ).then(
    //SCENARIO
    // "Alice checkouts repository" and "Alice edits file" -> alicesFile
    // "Bob checkouts repository" and "Bob edits same file in different place" -> bobsFile
    function(data) {
      // "Alice commits changes"
      return commonAPI.commitFile("alicesFile", inputFolder+alicesFile, alicesFileMessage, 0);
    },
    function(data){
      console.log("Failed to commit initialFile");
      reportIn(userStoryUuid,testName,"error");
    }
  ).then(
    function(data){
      // "Bob commits changes"
      return commonAPI.commitFile("bobsFile", inputFolder+bobsFile, bobsFileMessage, 1);
    },
    function(data){
      console.log("Failed to commit alicesFile");
      reportIn(userStoryUuid,testName,"error");
    }
  ).then(
  //OUTCOME
  //testResult is true iff both commits are successful and Bob's commit includes Alice's changes as well.
    function(data) {
      return commonAPI.getHEAD();
    },
    function(data){
      console.log("Failed to commit bobsFile");
      reportIn(userStoryUuid,testName,"error");
    }
  ).then(
    function(data){
      //do comparison with expectedFile and actualFile
      //TODO: get the contents of the expected and actualFile
      return compare(expected, actual);
    },
    function(data){
      console.log("Failed to getHEAD");
      reportIn(userStoryUuid,testName,"error");
    }
  ).then(
    function(data){reportIn(userStoryUuid,testName,"success");},
    function(data){
      console.log("Failed to Compare");
      reportIn(userStoryUuid,testName,"error");
    }
  );
}());
<commit_msg>fixes commit to different files<commit_after>(function() {
  var userStoryUuid = "ParallelEditWithoutConflicts";
  var testName = "basic";
  console.log("Running " + userStoryUuid + ":" + testName);

  var testResult = false;

  var commonAPI = new CommonAPI();
  var userStory = getUserStory(userStoryUuid);
  var test = getTest(userStory,testName);
  var inputFolder = "/" + userStoryUuid + "/" + testName + "/input/";

  console.log("input files");
  console.log(test.input);

  var fileName = testName,
  initialFile = test.input[0],
  initialFileMessage = "I HAVE 3 ELEMENTS: a,b,c",
  alicesFile = test.input[1],
  alicesFileMessage = "I HAVE 2 ELEMENTS: a,c",
  bobsFile = test.input[2],
  bobsFileMessage = "I HAVE 3 ELEMENTS: a,b,c AND d WITHIN a",
  expectedFile = test.input[3],
  expectedFileMessage = "I HAVE 2 ELEMENTS: a,c AND d WITHIN a",
  actualFile;

  // console.log("initialFile:" + initialFile);
  // console.log("alicesFile:" + alicesFile);
  // console.log("bobsFile:" + bobsFile);
  // console.log("expectedFile:" + expectedFile);

  //PRECONDITIONS
  // "Repository exists"
  commonAPI.initRepo().then(
    function(data){
      // "File exists" and "File Content exists"
      return commonAPI.commitFile(fileName, inputFolder+initialFile, initialFileMessage, 0);
    },
    function(data){
      console.log("Failed to initRepo");
      reportIn(userStoryUuid,testName,"error");
    }
  ).then(
    //SCENARIO
    // "Alice checkouts repository" and "Alice edits file" -> alicesFile
    // "Bob checkouts repository" and "Bob edits same file in different place" -> bobsFile
    function(data) {
      // "Alice commits changes"
      return commonAPI.commitFile(fileName, inputFolder+alicesFile, alicesFileMessage, 0);
    },
    function(data){
      console.log("Failed to commit initialFile");
      reportIn(userStoryUuid,testName,"error");
    }
  ).then(
    function(data){
      // "Bob commits changes"
      return commonAPI.commitFile(fileName, inputFolder+bobsFile, bobsFileMessage, 1);
    },
    function(data){
      console.log("Failed to commit alicesFile");
      reportIn(userStoryUuid,testName,"error");
    }
  ).then(
  //OUTCOME
  //testResult is true iff both commits are successful and Bob's commit includes Alice's changes as well.
    function(data) {
      return commonAPI.getHEAD();
    },
    function(data){
      console.log("Failed to commit bobsFile");
      reportIn(userStoryUuid,testName,"error");
    }
  ).then(
    function(data){
      //do comparison with expectedFile and actualFile
      //TODO: get the contents of the expected and actualFile
      return compare(expected, actual);
    },
    function(data){
      console.log("Failed to getHEAD");
      reportIn(userStoryUuid,testName,"error");
    }
  ).then(
    function(data){reportIn(userStoryUuid,testName,"success");},
    function(data){
      console.log("Failed to Compare");
      reportIn(userStoryUuid,testName,"error");
    }
  );
}());
<|endoftext|>


<commit_before>(function($) {
  function downloadUrl(groupId, artifactId, version, type) {
    var groupPath = groupId.replace('.', '/');
    var artifactPath = artifactId.replace('.', '/');
    return 'http://search.maven.org/remotecontent?filepath=' + groupPath + '/' + artifactPath + '/' + version + '/' + artifactId + '-' + version + type;
  }

  $.fn.artifactVersion = function(groupId, artifactId, callback) {
    if (typeof(groupId) !== 'string' || typeof(artifactId) !== 'string') {
      console.log('Error: groupId and artifactId are required.');
      return;
    }
    if (typeof(callback) === 'undefined') {
      console.log('Error: callback function required.');
      return;
    }

    var url = 'http://search.maven.org/solrsearch/select/?q=g:"' + groupId + '"+AND+a:"' + artifactId + '"&wt=json&json.wrf=?';
    $.getJSON(url, function(response) {
      var versions = response.response.docs;
      var version = versions[0].latestVersion;
      var versionUrl = downloadUrl(groupId, artifactId, version, '.jar');
      callback(version, versionUrl);
    });
  };

  $.fn.artifactVersions = function(groupId, artifactId, callback) {
    if (typeof(groupId) !== 'string' || typeof(artifactId) !== 'string') {
      console.log('Error: groupId and artifactId are required.');
      return;
    }
    if (typeof(callback) === 'undefined') {
      console.log('Error: callback function required.');
      return;
    }

    var url = 'http://search.maven.org/solrsearch/select/?q=g:"' + groupId + '"+AND+a:"' + artifactId + '"&wt=json&rows=10&core=gav&json.wrf=?';
    $.getJSON(url, function(response) {
      var versions = response.response.docs;
      versions.sort(function(o1, o2) {
        return o1.v > o2.v ? -1 : 1;
      });
      var newVersions = [];
      for (var i = 0; i < versions.length; i++) {
        var version = versions[i].v;
        newVersions.push({
          name: version,
          url: downloadUrl(groupId, artifactId, version, '.jar')
        });
      }
      callback(newVersions);
    });
  }
})(jQuery);<commit_msg>Use direct Maven download url to avoid wget filename borking<commit_after>(function($) {
  function downloadUrl(groupId, artifactId, version, type) {
    var groupPath = groupId.replace('.', '/');
    var artifactPath = artifactId.replace('.', '/');
    return 'http://repo1.maven.org/maven2/' + groupPath + '/' + artifactPath + '/' + version + '/' + artifactId + '-' + version + type;
  }

  $.fn.artifactVersion = function(groupId, artifactId, callback) {
    if (typeof(groupId) !== 'string' || typeof(artifactId) !== 'string') {
      console.log('Error: groupId and artifactId are required.');
      return;
    }
    if (typeof(callback) === 'undefined') {
      console.log('Error: callback function required.');
      return;
    }

    var url = 'http://search.maven.org/solrsearch/select/?q=g:"' + groupId + '"+AND+a:"' + artifactId + '"&wt=json&json.wrf=?';
    $.getJSON(url, function(response) {
      var versions = response.response.docs;
      var version = versions[0].latestVersion;
      var versionUrl = downloadUrl(groupId, artifactId, version, '.jar');
      callback(version, versionUrl);
    });
  };

  $.fn.artifactVersions = function(groupId, artifactId, callback) {
    if (typeof(groupId) !== 'string' || typeof(artifactId) !== 'string') {
      console.log('Error: groupId and artifactId are required.');
      return;
    }
    if (typeof(callback) === 'undefined') {
      console.log('Error: callback function required.');
      return;
    }

    var url = 'http://search.maven.org/solrsearch/select/?q=g:"' + groupId + '"+AND+a:"' + artifactId + '"&wt=json&rows=10&core=gav&json.wrf=?';
    $.getJSON(url, function(response) {
      var versions = response.response.docs;
      versions.sort(function(o1, o2) {
        return o1.v > o2.v ? -1 : 1;
      });
      var newVersions = [];
      for (var i = 0; i < versions.length; i++) {
        var version = versions[i].v;
        newVersions.push({
          name: version,
          url: downloadUrl(groupId, artifactId, version, '.jar')
        });
      }
      callback(newVersions);
    });
  }
})(jQuery);<|endoftext|>


<commit_before>/**
 * jQuery Form Space
 *
 * Copyright 2017, Heath Dutton
 * Licensed under the MIT license.
 *
 * Hides fixed navigation when form fields are focused to conserve space on smaller screens.
 *
 *   Usage: $('body').formSpace();
 */
!function(e){e.fn.formSpace=function(t){var o=e.extend({header:".navbar-fixed-top, .navbar-static-top",footer:".navbar-fixed-bottom, .navbar-static-bottom",delay:1e3,fields:"input[type=text], input[type=password], input[type=tel], input[type=image], input[type=file], select, textarea",speed:100,class:"formspace_hidden",mobileOnly:!0},t);if(o.mobileOnly&&(function(e){(jQuery.browser=jQuery.browser||{}).mobile=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))}(navigator.userAgent||navigator.vendor||window.opera),!jQuery.browser.mobile))return this;for(var i,a,n=this,s=e(o.header),c=e(o.footer),r=!0,p=function(){r&&(s.removeClass(o.class).each(function(){e(this).stop().animate({top:-1*e(this).outerHeight()},o.speed)}),c.addClass(o.class).each(function(){e(this).stop().animate({bottom:-1*e(this).outerHeight()},o.speed)}),u(),r=!1)},m=function(){r||(d(),s.removeClass(o.class).each(function(){e(this).stop().animate({top:e(this).data("formSpace.top")+"px"},o.speed)}),c.removeClass(o.class).each(function(){e(this).stop().animate({top:e(this).data("formSpace.bottom")+"px"},o.speed)}),u(),r=!0)},l=function(t){"number"!=typeof t&&(t=Math.ceil(o.delay/5)),i=setTimeout(function(){var t=e(":focus");t.length&&t.first().is(o.fields)?p():m()},t)},f=function(t){"number"!=typeof t&&(t=o.delay),a=setTimeout(function(){e(o.fields).off("focus.formSpace.focus").off("blur.formSpace.blur").on("focus.formSpace.focus",function(){l(0)}).on("blur.formSpace.blur",function(){l()})},t),l(0)},d=function(){n.off("DOMSubtreeModified.formSpace")},u=function(){n.off("DOMSubtreeModified.formSpace").on("DOMSubtreeModified.formSpace",function(){f()})},b=o.fields.split(","),h=0;h<b.length;h++)b[h]=n.selector+" "+b[h].trim();return o.fields=b.join(","),(s.length||c.length)&&(s.each(function(){e(this).data("formSpace.top",e(this).position().top)}),c.each(function(){e(this).data("formSpace.bottom",e(this).position().bottom)}),f(0),u()),this}}(jQuery);
<commit_msg>Added repository link.<commit_after>/**
 * jQuery Form Space
 * https://github.com/heathdutton/jquery-formspace
 *
 * Copyright 2017, Heath Dutton
 * Licensed under the MIT license.
 *
 * Hides fixed navigation when form fields are focused to conserve space on smaller screens.
 *
 *   Usage: $('body').formSpace();
 */
!function(e){e.fn.formSpace=function(t){var o=e.extend({header:".navbar-fixed-top, .navbar-static-top",footer:".navbar-fixed-bottom, .navbar-static-bottom",delay:1e3,fields:"input[type=text], input[type=password], input[type=tel], input[type=image], input[type=file], select, textarea",speed:100,class:"formspace_hidden",mobileOnly:!0},t);if(o.mobileOnly&&(function(e){(jQuery.browser=jQuery.browser||{}).mobile=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))}(navigator.userAgent||navigator.vendor||window.opera),!jQuery.browser.mobile))return this;for(var i,a,n=this,s=e(o.header),c=e(o.footer),r=!0,p=function(){r&&(s.removeClass(o.class).each(function(){e(this).stop().animate({top:-1*e(this).outerHeight()},o.speed)}),c.addClass(o.class).each(function(){e(this).stop().animate({bottom:-1*e(this).outerHeight()},o.speed)}),u(),r=!1)},m=function(){r||(d(),s.removeClass(o.class).each(function(){e(this).stop().animate({top:e(this).data("formSpace.top")+"px"},o.speed)}),c.removeClass(o.class).each(function(){e(this).stop().animate({top:e(this).data("formSpace.bottom")+"px"},o.speed)}),u(),r=!0)},l=function(t){"number"!=typeof t&&(t=Math.ceil(o.delay/5)),i=setTimeout(function(){var t=e(":focus");t.length&&t.first().is(o.fields)?p():m()},t)},f=function(t){"number"!=typeof t&&(t=o.delay),a=setTimeout(function(){e(o.fields).off("focus.formSpace.focus").off("blur.formSpace.blur").on("focus.formSpace.focus",function(){l(0)}).on("blur.formSpace.blur",function(){l()})},t),l(0)},d=function(){n.off("DOMSubtreeModified.formSpace")},u=function(){n.off("DOMSubtreeModified.formSpace").on("DOMSubtreeModified.formSpace",function(){f()})},b=o.fields.split(","),h=0;h<b.length;h++)b[h]=n.selector+" "+b[h].trim();return o.fields=b.join(","),(s.length||c.length)&&(s.each(function(){e(this).data("formSpace.top",e(this).position().top)}),c.each(function(){e(this).data("formSpace.bottom",e(this).position().bottom)}),f(0),u()),this}}(jQuery);
<|endoftext|>