<commit_before>/*jshint latedef: nofunc */

$(function() {
   var settings = {
      xmpp: {
         url: '/http-bind/',
         domain: 'localhost',
         resource: 'example',
         overwrite: true
      }
   };

   // Initialize core functions, intercept login form
   // and attach connection if possible.
   jsxc.init({
      loginForm: {
         form: '#form',
         jid: '#username',
         pass: '#password'
      },
      logoutElement: $('#logout'),
      rosterAppend: 'body',
      root: window.location.pathname.replace(/\/[^/]+$/, "/") + (window.location.pathname.match(/dev\.html/) ? '../dev' : '../build'),
      displayRosterMinimized: function() {
         return true;
      },
      loadSettings: function(username, password, cb) {
         cb(settings);
      },
      xmpp: {
         url: settings.xmpp.url
      }
   });

   // helper variable
   var source = '#form';

   // AJAX login
   $('#form2').submit(function(ev) {
      ev.preventDefault();

      source = $(this);
      $('#submit2').button('loading');

      jsxc.start($('#username2').val() + '@' + settings.xmpp.domain, $('#password2').val());
   });

   // Box Login
   $('#form3 .submit').click(jsxc.gui.showLoginBox);

   // ============================================
   // Below you find only some helper to show/hide
   // logout buttons and similiar stuff.
   // ============================================

   // form elements which needs to be enabled/disabled
   var formElements = $('#form2, #form').find('input');

   $(document).on('connecting.jsxc', function() {
      formElements.prop('disabled', true);
   });

   $(document).on('authfail.jsxc', function() {
      formElements.prop('disabled', false);
      $(source).find('.alert').show();
      $(source).find('.submit').button('reset');
   });

   $(document).on('attached.jsxc', function() {
      formElements.prop('disabled', true);
      $('.submit').hide();
      $('form .alert').hide();

      $('.logout').show().click(jsxc.xmpp.logout);
   });

   $(document).on('disconnected.jsxc', function() {
      $(source).find('button').button('reset');
      formElements.prop('disabled', false);
      $('.submit').show();
      $('.logout').hide().off('click');
   });

   // load bosh url from storage
   if (typeof localStorage.getItem('bosh-url') === 'string') {
      $('#bosh-url').val(localStorage.getItem('bosh-url'));
   }

   // load xmpp domain from storage
   if (typeof localStorage.getItem('xmpp-domain') === 'string') {
      $('#xmpp-domain').val(localStorage.getItem('xmpp-domain'));
   }

   // Check bosh url, if input changed
   $('#bosh-url, #xmpp-domain').on('input', function(){
      var self = $(this);
      var timeout = self.data('timeout');

      if (timeout) {
         clearTimeout(timeout);
      }

      var url = $('#bosh-url').val();
      var domain = $('#xmpp-domain').val();

      if (!url || !domain) {
         // we need url and domain to test BOSH server
         return;
      }

      localStorage.setItem('bosh-url', url);
      localStorage.setItem('xmpp-domain', domain);

      settings.xmpp.url = url;
      settings.xmpp.domain = domain;

      $('#server-flash').removeClass('success fail').text('Testing...');

      // test only every 2 seconds
      timeout = setTimeout(function() {
         testBoshServer($('#bosh-url').val(), $('#xmpp-domain').val(), function(result) {
            $('#server-flash').removeClass('success fail').addClass(result.status).html(result.msg);
         });
      }, 2000);

      self.data('timeout', timeout);
   });

   // check initial bosh url
   $('#bosh-url').trigger('input');
});

/**
* Test if bosh server is up and running.
*
* @param  {string}   url    BOSH url
* @param  {string}   domain host domain for BOSH server
* @param  {Function} cb     called if test is done
*/
function testBoshServer(url, domain, cb) {
   var rid = jsxc.storage.getItem('rid') || '123456';

   function fail(m) {
      var msg = 'BOSH server NOT reachable or misconfigured.';

      if (typeof m === 'string') {
         msg += '

' + m;
      }

      cb({
         status: 'fail',
         msg: msg
      });
   }

   $.ajax({
      type: 'POST',
      url: url,
      data: "",
      global: false,
      dataType: 'xml'
   }).done(function(stanza) {
      if (typeof stanza === 'string') {
         // shouldn't be needed anymore, because of dataType
         stanza = $.parseXML(stanza);
      }

      var body = $(stanza).find('body[xmlns="http://jabber.org/protocol/httpbind"]');
      var condition = (body) ? body.attr('condition') : null;
      var type = (body) ? body.attr('type') : null;

      // we got a valid xml response, but we have test for errors

      if (body.length > 0 && type !== 'terminate') {
         cb({
            status: 'success',
            msg: 'BOSH Server reachable.'
         });
      } else {
         if (condition === 'internal-server-error') {
            fail('Internal server error: ' + body.text());
         } else if (condition === 'host-unknown') {
            if (url) {
               fail('Host unknown: ' + domain + ' is unknown to your XMPP server.');
            } else {
               fail('Host unknown: Please provide a XMPP domain.');
            }
         } else {
            fail(condition);
         }
      }
   }).fail(function(xhr, textStatus) {
      // no valid xml, not found or csp issue

      var fullurl;
      if (url.match(/^https?:\/\//)) {
         fullurl = url;
      } else {
         fullurl = window.location.protocol + '//' + window.location.host;
         if (url.match(/^\//)) {
            fullurl += url;
         } else {
            fullurl += window.location.pathname.replace(/[^/]+$/, "") + url;
         }
      }

      if(xhr.status === 0) {
         // cross-side
         fail('Cross domain request was not possible. Either your BOSH server does not send any ' +
            'Access-Control-Allow-Origin header or the content-security-policy (CSP) blocks your request. ' +
            'Starting from Owncloud 9.0 your CSP will be updated in any app which uses the appframework (e.g. files) ' +
            'after you save these settings and reload.' +
            'The savest way is still to use Apache ProxyRequest or Nginx proxy_pass.');
      } else if (xhr.status === 404) {
         // not found
         fail('Your server responded with "404 Not Found". Please check if your BOSH server is running and reachable via ' + fullurl + '.');
      } else if (textStatus === 'parsererror') {
         fail('Invalid XML received. Maybe ' + fullurl + ' was redirected. You should use an absolute url.');
      } else {
         fail(xhr.status + ' ' + xhr.statusText);
      }
   });
}
<commit_msg>beautify example.js<commit_after>/*jshint latedef: nofunc */

$(function() {
   var settings = {
      xmpp: {
         url: '/http-bind/',
         domain: 'localhost',
         resource: 'example',
         overwrite: true
      }
   };

   // Initialize core functions, intercept login form
   // and attach connection if possible.
   jsxc.init({
      loginForm: {
         form: '#form',
         jid: '#username',
         pass: '#password'
      },
      logoutElement: $('#logout'),
      rosterAppend: 'body',
      root: window.location.pathname.replace(/\/[^/]+$/, "/") + (window.location.pathname.match(/dev\.html/) ? '../dev' : '../build'),
      displayRosterMinimized: function() {
         return true;
      },
      loadSettings: function(username, password, cb) {
         cb(settings);
      },
      xmpp: {
         url: settings.xmpp.url
      }
   });

   // helper variable
   var source = '#form';

   // AJAX login
   $('#form2').submit(function(ev) {
      ev.preventDefault();

      source = $(this);
      $('#submit2').button('loading');

      jsxc.start($('#username2').val() + '@' + settings.xmpp.domain, $('#password2').val());
   });

   // Box Login
   $('#form3 .submit').click(jsxc.gui.showLoginBox);

   // ============================================
   // Below you find only some helper to show/hide
   // logout buttons and similiar stuff.
   // ============================================

   // form elements which needs to be enabled/disabled
   var formElements = $('#form2, #form').find('input');

   $(document).on('connecting.jsxc', function() {
      formElements.prop('disabled', true);
   });

   $(document).on('authfail.jsxc', function() {
      formElements.prop('disabled', false);
      $(source).find('.alert').show();
      $(source).find('.submit').button('reset');
   });

   $(document).on('attached.jsxc', function() {
      formElements.prop('disabled', true);
      $('.submit').hide();
      $('form .alert').hide();

      $('.logout').show().click(jsxc.xmpp.logout);
   });

   $(document).on('disconnected.jsxc', function() {
      $(source).find('button').button('reset');
      formElements.prop('disabled', false);
      $('.submit').show();
      $('.logout').hide().off('click');
   });

   // load bosh url from storage
   if (typeof localStorage.getItem('bosh-url') === 'string') {
      $('#bosh-url').val(localStorage.getItem('bosh-url'));
   }

   // load xmpp domain from storage
   if (typeof localStorage.getItem('xmpp-domain') === 'string') {
      $('#xmpp-domain').val(localStorage.getItem('xmpp-domain'));
   }

   // Check bosh url, if input changed
   $('#bosh-url, #xmpp-domain').on('input', function() {
      var self = $(this);
      var timeout = self.data('timeout');

      if (timeout) {
         clearTimeout(timeout);
      }

      var url = $('#bosh-url').val();
      var domain = $('#xmpp-domain').val();

      if (!url || !domain) {
         // we need url and domain to test BOSH server
         return;
      }

      localStorage.setItem('bosh-url', url);
      localStorage.setItem('xmpp-domain', domain);

      settings.xmpp.url = url;
      settings.xmpp.domain = domain;

      $('#server-flash').removeClass('success fail').text('Testing...');

      // test only every 2 seconds
      timeout = setTimeout(function() {
         testBoshServer($('#bosh-url').val(), $('#xmpp-domain').val(), function(result) {
            $('#server-flash').removeClass('success fail').addClass(result.status).html(result.msg);
         });
      }, 2000);

      self.data('timeout', timeout);
   });

   // check initial bosh url
   $('#bosh-url').trigger('input');
});

/**
 * Test if bosh server is up and running.
 *
 * @param  {string}   url    BOSH url
 * @param  {string}   domain host domain for BOSH server
 * @param  {Function} cb     called if test is done
 */
function testBoshServer(url, domain, cb) {
   var rid = jsxc.storage.getItem('rid') || '123456';

   function fail(m) {
      var msg = 'BOSH server NOT reachable or misconfigured.';

      if (typeof m === 'string') {
         msg += '

' + m;
      }

      cb({
         status: 'fail',
         msg: msg
      });
   }

   $.ajax({
      type: 'POST',
      url: url,
      data: "",
      global: false,
      dataType: 'xml'
   }).done(function(stanza) {
      if (typeof stanza === 'string') {
         // shouldn't be needed anymore, because of dataType
         stanza = $.parseXML(stanza);
      }

      var body = $(stanza).find('body[xmlns="http://jabber.org/protocol/httpbind"]');
      var condition = (body) ? body.attr('condition') : null;
      var type = (body) ? body.attr('type') : null;

      // we got a valid xml response, but we have test for errors

      if (body.length > 0 && type !== 'terminate') {
         cb({
            status: 'success',
            msg: 'BOSH Server reachable.'
         });
      } else {
         if (condition === 'internal-server-error') {
            fail('Internal server error: ' + body.text());
         } else if (condition === 'host-unknown') {
            if (url) {
               fail('Host unknown: ' + domain + ' is unknown to your XMPP server.');
            } else {
               fail('Host unknown: Please provide a XMPP domain.');
            }
         } else {
            fail(condition);
         }
      }
   }).fail(function(xhr, textStatus) {
      // no valid xml, not found or csp issue

      var fullurl;
      if (url.match(/^https?:\/\//)) {
         fullurl = url;
      } else {
         fullurl = window.location.protocol + '//' + window.location.host;
         if (url.match(/^\//)) {
            fullurl += url;
         } else {
            fullurl += window.location.pathname.replace(/[^/]+$/, "") + url;
         }
      }

      if (xhr.status === 0) {
         // cross-side
         fail('Cross domain request was not possible. Either your BOSH server does not send any ' +
            'Access-Control-Allow-Origin header or the content-security-policy (CSP) blocks your request. ' +
            'Starting from Owncloud 9.0 your CSP will be updated in any app which uses the appframework (e.g. files) ' +
            'after you save these settings and reload.' +
            'The savest way is still to use Apache ProxyRequest or Nginx proxy_pass.');
      } else if (xhr.status === 404) {
         // not found
         fail('Your server responded with "404 Not Found". Please check if your BOSH server is running and reachable via ' + fullurl + '.');
      } else if (textStatus === 'parsererror') {
         fail('Invalid XML received. Maybe ' + fullurl + ' was redirected. You should use an absolute url.');
      } else {
         fail(xhr.status + ' ' + xhr.statusText);
      }
   });
}
<|endoftext|>


<commit_before>var taskResult = require('./taskresult');
var logger = require('./../../Common/sources/logger');
var utils = require('./../../Common/sources/utils');
var constants = require('./../../Common/sources/constants');
var commonDefines = require('./../../Common/sources/commondefines');
var docsCoServer = require('./DocsCoServer');
var storage = require('./../../Common/sources/storage-base');
var formatChecker = require('./../../Common/sources/formatchecker');
var statsDClient = require('./../../Common/sources/statsdclient');

//todo
var CONVERT_TIMEOUT = 6 * 60 * 1000;
var CONVERT_ASYNC_DELAY = 1000;

var clientStatsD = statsDClient.getClient();

function* getConvertStatus(cmd, selectRes, req) {
  var status = {url: undefined, err: constants.NO_ERROR};
  if (selectRes.length > 0) {
    var row = selectRes[0];
    switch (row.tr_status) {
      case taskResult.FileStatus.Ok:
        status.url = yield storage.getSignedUrl(utils.getBaseUrlByRequest(req), cmd.getDocId() + '/' + cmd.getTitle());
        break;
      case taskResult.FileStatus.Err:
      case taskResult.FileStatus.ErrToReload:
        status.err = row.tr_status_info;
        break;
    }
    var lastOpenDate = row.tr_last_open_date;
    //todo
    if (new Date().getTime() - lastOpenDate.getTime() > CONVERT_TIMEOUT) {
      status.err = constants.UNKNOWN;
    }
  }
  return status;
}

exports.convert = function(req, res) {
  utils.spawn(function* () {
    try {
      var startDate = null;
      if(clientStatsD) {
        startDate = new Date();
      }
      logger.debug('Start convert request');
      var cmd = new commonDefines.InputCommand();
      cmd.setCommand('conv');
      cmd.setVKey(req.query['vkey']);
      cmd.setUrl(req.query['url']);
      cmd.setEmbeddedFonts(false);//req.query['embeddedfonts'];
      cmd.setFormat(req.query['filetype']);
      var outputtype = req.query['outputtype'];
      cmd.setDocId('conv_' + req.query['key'] + '_' + outputtype);
      cmd.setTitle(constants.OUTPUT_NAME + '.' + outputtype);
      cmd.setOutputFormat(formatChecker.getFormatFromString(outputtype));
      cmd.setCodepage(req.query['codePage']);
      cmd.setCodepage(req.query['delimiter']);
      var async = 'true' == req.query['async'];

      var task = new taskResult.TaskResultData();
      task.key = cmd.getDocId();
      task.format = cmd.getFormat();
      task.status = taskResult.FileStatus.WaitQueue;
      task.statusInfo = constants.NO_ERROR;
      task.title = cmd.getTitle();

      var upsertRes = yield taskResult.upsert(task);
      //var bCreate = (upsertRes.affectedRows == 1);
      var bExist = (upsertRes.affectedRows > 1);
      var selectRes;
      var status;
      if (bExist) {
        selectRes = yield taskResult.select(task);
        status = yield* getConvertStatus(cmd, selectRes, req);
      } else {
        var queueData = new commonDefines.TaskQueueData();
        queueData.setCmd(cmd);
        queueData.setToFile(cmd.getTitle());
        yield* docsCoServer.addTask(queueData, constants.QUEUE_PRIORITY_LOW);
        //wait
        if (!async) {
          var waitTime = 0;
          while (true) {
            yield utils.sleep(CONVERT_ASYNC_DELAY);
            selectRes = yield taskResult.select(task);
            status = yield* getConvertStatus(cmd, selectRes, req);
            waitTime += CONVERT_ASYNC_DELAY;
            if (waitTime > CONVERT_TIMEOUT) {
              status.err = constants.CONVERT_TIMEOUT;
            }
            if (status.url || constants.NO_ERROR != status.err) {
              break;
            }
          }
        } else {
          status = {url: undefined, percent: 0, err: constants.NO_ERROR};
        }
      }
      utils.fillXmlResponse(res, status.url, status.err);
      logger.debug('End convert request');
      if(clientStatsD) {
        clientStatsD.timing('coauth.convertservice', new Date() - startDate);
      }
    }
    catch (e) {
      logger.error('error convert:\r\n%s', e.stack);
      utils.fillXmlResponse(res, undefined, constants.UNKNOWN);
    }
  });
};
<commit_msg>add log<commit_after>var taskResult = require('./taskresult');
var logger = require('./../../Common/sources/logger');
var utils = require('./../../Common/sources/utils');
var constants = require('./../../Common/sources/constants');
var commonDefines = require('./../../Common/sources/commondefines');
var docsCoServer = require('./DocsCoServer');
var storage = require('./../../Common/sources/storage-base');
var formatChecker = require('./../../Common/sources/formatchecker');
var statsDClient = require('./../../Common/sources/statsdclient');

//todo
var CONVERT_TIMEOUT = 6 * 60 * 1000;
var CONVERT_ASYNC_DELAY = 1000;

var clientStatsD = statsDClient.getClient();

function* getConvertStatus(cmd, selectRes, req) {
  var status = {url: undefined, err: constants.NO_ERROR};
  if (selectRes.length > 0) {
    var row = selectRes[0];
    switch (row.tr_status) {
      case taskResult.FileStatus.Ok:
        status.url = yield storage.getSignedUrl(utils.getBaseUrlByRequest(req), cmd.getDocId() + '/' + cmd.getTitle());
        break;
      case taskResult.FileStatus.Err:
      case taskResult.FileStatus.ErrToReload:
        status.err = row.tr_status_info;
        break;
    }
    var lastOpenDate = row.tr_last_open_date;
    //todo
    if (new Date().getTime() - lastOpenDate.getTime() > CONVERT_TIMEOUT) {
      status.err = constants.UNKNOWN;
    }
  }
  return status;
}

exports.convert = function(req, res) {
  utils.spawn(function* () {
    try {
      var startDate = null;
      if(clientStatsD) {
        startDate = new Date();
      }
      var cmd = new commonDefines.InputCommand();
      cmd.setCommand('conv');
      cmd.setVKey(req.query['vkey']);
      cmd.setUrl(req.query['url']);
      cmd.setEmbeddedFonts(false);//req.query['embeddedfonts'];
      cmd.setFormat(req.query['filetype']);
      var outputtype = req.query['outputtype'];
      cmd.setDocId('conv_' + req.query['key'] + '_' + outputtype);
      cmd.setTitle(constants.OUTPUT_NAME + '.' + outputtype);
      cmd.setOutputFormat(formatChecker.getFormatFromString(outputtype));
      cmd.setCodepage(req.query['codePage']);
      cmd.setCodepage(req.query['delimiter']);
      var async = 'true' == req.query['async'];
      logger.debug('Start convert request docId = %s', cmd.getDocId());

      var task = new taskResult.TaskResultData();
      task.key = cmd.getDocId();
      task.format = cmd.getFormat();
      task.status = taskResult.FileStatus.WaitQueue;
      task.statusInfo = constants.NO_ERROR;
      task.title = cmd.getTitle();

      var upsertRes = yield taskResult.upsert(task);
      //var bCreate = (upsertRes.affectedRows == 1);
      var bExist = (upsertRes.affectedRows > 1);
      var selectRes;
      var status;
      if (bExist) {
        selectRes = yield taskResult.select(task);
        status = yield* getConvertStatus(cmd, selectRes, req);
      } else {
        var queueData = new commonDefines.TaskQueueData();
        queueData.setCmd(cmd);
        queueData.setToFile(cmd.getTitle());
        yield* docsCoServer.addTask(queueData, constants.QUEUE_PRIORITY_LOW);
        //wait
        if (!async) {
          var waitTime = 0;
          while (true) {
            yield utils.sleep(CONVERT_ASYNC_DELAY);
            selectRes = yield taskResult.select(task);
            status = yield* getConvertStatus(cmd, selectRes, req);
            waitTime += CONVERT_ASYNC_DELAY;
            if (waitTime > CONVERT_TIMEOUT) {
              status.err = constants.CONVERT_TIMEOUT;
            }
            if (status.url || constants.NO_ERROR != status.err) {
              break;
            }
          }
        } else {
          status = {url: undefined, percent: 0, err: constants.NO_ERROR};
        }
      }
      utils.fillXmlResponse(res, status.url, status.err);
      logger.debug('End convert request url %s status %s docId = %s', status.url, status.err, cmd.getDocId());
      if(clientStatsD) {
        clientStatsD.timing('coauth.convertservice', new Date() - startDate);
      }
    }
    catch (e) {
      logger.error('error convert:\r\n%s', e.stack);
      utils.fillXmlResponse(res, undefined, constants.UNKNOWN);
    }
  });
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Stack Exchange - Add link to network and chat profiles
// @namespace   https://github.com/Glorfindel83/
// @description Adds a link to the network profile for all user profile pages (even if they've hidden the current community) and a link to the chat profile
// @author      Glorfindel
// @updateURL   https://raw.githubusercontent.com/Glorfindel83/SE-Userscripts/master/add-network-profile-link/add-network-profile-link.user.js
// @downloadURL https://raw.githubusercontent.com/Glorfindel83/SE-Userscripts/master/add-network-profile-link/add-network-profile-link.user.js
// @supportURL  https://stackapps.com/q/9328/34061
// @version     1.0
// @match       *://*.stackexchange.com/users/*
// @match       *://*.stackoverflow.com/users/*
// @match       *://*.superuser.com/users/*
// @match       *://*.serverfault.com/users/*
// @match       *://*.askubuntu.com/users/*
// @match       *://*.stackapps.com/users/*
// @match       *://*.mathoverflow.net/users/*
// @exclude     *://stackexchange.com/users/*
// @exclude     *://chat.stackexchange.com/users/*
// @exclude     *://chat.stackoverflow.com/users/*
// @exclude     *://chat.meta.stackexchange.com/users/*
// @grant       none
// ==/UserScript==
(function () {
  'use strict';

  StackExchange.ready(function() {
    // Some pages (e.g. https://*.stackexchange.com/users/message/create/*) need to be skipped
    if (typeof(StackExchange.user) == 'undefined' ||
        typeof(StackExchange.user.options) == 'undefined') // unregistered users
      return;

    // Find user IDs
    let userID = StackExchange.user.options.userId;
    let accountID = StackExchange.user.options.accountId;

    // Check if link already present
    let user = $(".user-show-new");
    var existingButton = user.find("button[aria-controls='profiles-menu']");
    if (existingButton.length == 0) {
      existingButton = user.find("a.s-btn[href^='https://stackexchange.com/users/']").parents("ul");
    }
    if (existingButton.length == 0) {
      // Add link to network profile
      let profile = user[0].children[0];
      if (profile.classList.contains("system-alert")) {
        // Suspension message, take the next one
        profile = user[0].children[1];
      }
      let container = profile.children[profile.children.length - 1];
      let networkProfileButton = '\n' +
        '<svg aria-hidden="true" class="native mln2 mr2 svg-icon iconLogoSEXxs" width="18" height="18" viewBox="0 0 18 18"><path d="M3 4c0-1.1.9-2 2-2h8a2 2 0 012 2H3Z" fill="#8FD8F7"></path><path d="M15 11H3c0 1.1.9 2 2 2h5v3l3-3a2 2 0 002-2Z" fill="#155397"></path><path fill="#46A2D9" d="M3 5h12v2H3z"></path><path fill="#2D6DB5" d="M3 8h12v2H3z"></path></svg>\n' +
        'Network profile';
      // Main/meta profile switcher?
      existingButton = user.find("a.s-btn[href*='/users/']").parents("ul");
      if (existingButton.length == 0) {
        container.innerHTML = networkProfileButton;
        existingButton = $(container).children();
      } else {
        existingButton.after(networkProfileButton);
      }
    }

    // Add link to chat profile
    var chatHost;
    var chatLogo;
    switch (location.host) {
      case 'meta.stackexchange.com':
        chatHost = 'chat.meta.stackexchange.com';
        chatLogo = '
';
        break;
      case 'stackoverflow.com':
      case 'meta.stackoverflow.com':
        chatHost = 'chat.stackoverflow.com';
        chatLogo = '
';
        break;
      default:
        chatHost = 'chat.stackexchange.com';
        chatLogo = '
';
        break;
    }
    // If the profile has a dropdown available, insert the link as an item in the dropdown list
    if(existingButton[0].classList.contains('s-btn__dropdown')) {
        let profileItems = $('#profiles-menu').find('.s-menu');
        let teamsSeparatorIndex = profileItems.find('.s-menu--title').index();
        if(teamsSeparatorIndex > -1) {
            profileItems.find('li').eq(teamsSeparatorIndex).before('
' + chatLogo + '  Chat profile
');
        }
        else {
            profileItems.append('
' + chatLogo + '  Chat profile
');
        }
    }
    else {
        existingButton.before('\n' +
        'Chat profile');
    }
  });
})();
<commit_msg>Add network profile link v1.1<commit_after>// ==UserScript==
// @name        Stack Exchange - Add link to network and chat profiles
// @namespace   https://github.com/Glorfindel83/
// @description Adds a link to the network profile for all user profile pages (even if they've hidden the current community) and a link to the chat profile
// @author      Glorfindel
// @contributor Spevacus
// @updateURL   https://raw.githubusercontent.com/Glorfindel83/SE-Userscripts/master/add-network-profile-link/add-network-profile-link.user.js
// @downloadURL https://raw.githubusercontent.com/Glorfindel83/SE-Userscripts/master/add-network-profile-link/add-network-profile-link.user.js
// @supportURL  https://stackapps.com/q/9328/34061
// @version     1.1
// @match       *://*.stackexchange.com/users/*
// @match       *://*.stackoverflow.com/users/*
// @match       *://*.superuser.com/users/*
// @match       *://*.serverfault.com/users/*
// @match       *://*.askubuntu.com/users/*
// @match       *://*.stackapps.com/users/*
// @match       *://*.mathoverflow.net/users/*
// @exclude     *://stackexchange.com/users/*
// @exclude     *://chat.stackexchange.com/users/*
// @exclude     *://chat.stackoverflow.com/users/*
// @exclude     *://chat.meta.stackexchange.com/users/*
// @grant       none
// ==/UserScript==
(function () {
  'use strict';

  StackExchange.ready(function() {
    // Some pages (e.g. https://*.stackexchange.com/users/message/create/*) need to be skipped
    if (typeof(StackExchange.user) == 'undefined' ||
        typeof(StackExchange.user.options) == 'undefined') // unregistered users
      return;

    // Find user IDs
    let userID = StackExchange.user.options.userId;
    let accountID = StackExchange.user.options.accountId;

    // Check if link already present
    let user = $(".user-show-new");
    var existingButton = user.find("button[aria-controls='profiles-menu']");
    if (existingButton.length == 0) {
      existingButton = user.find("a.s-btn[href^='https://stackexchange.com/users/']").parents("ul");
    }
    if (existingButton.length == 0) {
      // Add link to network profile
      let profile = user[0].children[0];
      if (profile.classList.contains("system-alert")) {
        // Suspension message, take the next one
        profile = user[0].children[1];
      }
      let container = profile.children[profile.children.length - 1];
      let networkProfileButton = '\n' +
        '<svg aria-hidden="true" class="native mln2 mr2 svg-icon iconLogoSEXxs" width="18" height="18" viewBox="0 0 18 18"><path d="M3 4c0-1.1.9-2 2-2h8a2 2 0 012 2H3Z" fill="#8FD8F7"></path><path d="M15 11H3c0 1.1.9 2 2 2h5v3l3-3a2 2 0 002-2Z" fill="#155397"></path><path fill="#46A2D9" d="M3 5h12v2H3z"></path><path fill="#2D6DB5" d="M3 8h12v2H3z"></path></svg>\n' +
        'Network profile';
      // Main/meta profile switcher?
      existingButton = user.find("a.s-btn[href*='/users/']").parents("ul");
      if (existingButton.length == 0) {
        container.innerHTML = networkProfileButton;
        existingButton = $(container).children();
      } else {
        existingButton.after(networkProfileButton);
      }
    }

    // Add link to chat profile
    var chatHost;
    var chatLogo;
    switch (location.host) {
      case 'meta.stackexchange.com':
        chatHost = 'chat.meta.stackexchange.com';
        chatLogo = '
';
        break;
      case 'stackoverflow.com':
      case 'meta.stackoverflow.com':
        chatHost = 'chat.stackoverflow.com';
        chatLogo = '
';
        break;
      default:
        chatHost = 'chat.stackexchange.com';
        chatLogo = '
';
        break;
    }
    // If the profile has a dropdown available, insert the link as an item in the dropdown list
    if(existingButton[0].classList.contains('s-btn__dropdown')) {
        let profileItems = $('#profiles-menu').find('.s-menu');
        let teamsSeparatorIndex = profileItems.find('.s-menu--title').index();
        if(teamsSeparatorIndex > -1) {
            profileItems.find('li').eq(teamsSeparatorIndex).before('
' + chatLogo + '  Chat profile
');
        }
        else {
            profileItems.append('
' + chatLogo + '  Chat profile
');
        }
    }
    else {
        existingButton.before('\n' +
        'Chat profile');
    }
  });
})();
<|endoftext|>


<commit_before>ddescribe('Initial FreeScroll events', function(){

	var addEventSpy = jasmine.createSpy('addEvent');
	var readyEventSpy = jasmine.createSpy('ready');
	var noMoreSpy = jasmine.createSpy('noMore');
	FreeScroll.fn.addEvent = addEventSpy;
	FreeScroll.helper.ready = readyEventSpy;
	FreeScroll.noMore = noMoreSpy;

	beforeEach(function(){
		setFixtures('

');
		fs = FreeScroll('.className');//spyOn(fs, 'addEvent');
	});

	it('scroll is added to FreeScroll', function(){
		expect(fs.addEvent).toHaveBeenCalledWith('scroll', jasmine.any(Function));
	});

	it('ready is called', function(){
		expect(FreeScroll.helper.ready).toHaveBeenCalledWith(jasmine.any(Function));
	});

	it('noMore is false when scroll event is fired', function(){
		FreeScroll.noMore.and.returnValue(false);
		spyOn(fs.promise, 'more');
		$(fs[0]).trigger('scroll');
		expect(FreeScroll.noMore).toHaveBeenCalled();
		expect(fs.promise.more).not.toHaveBeenCalled();
	});
});<commit_msg>view all tests, need to add react jsx compiler in.<commit_after>describe('Initial FreeScroll events', function(){

	var addEventSpy = jasmine.createSpy('addEvent');
	var readyEventSpy = jasmine.createSpy('ready');
	var noMoreSpy = jasmine.createSpy('noMore');
	FreeScroll.fn.addEvent = addEventSpy;
	FreeScroll.helper.ready = readyEventSpy;
	FreeScroll.noMore = noMoreSpy;

	beforeEach(function(){
		setFixtures('

Testing

');
		fs = FreeScroll('.className');//spyOn(fs, 'addEvent');
	});

	it('scroll is added to FreeScroll', function(){
		expect(fs.addEvent).toHaveBeenCalledWith('scroll', jasmine.any(Function));
	});

	it('ready is called', function(){
		expect(FreeScroll.helper.ready).toHaveBeenCalledWith(jasmine.any(Function));
	});

	xit('noMore is false when scroll event is fired', function(){
		FreeScroll.noMore.and.returnValue(false);
		spyOn(fs.promise, 'more');
		$('.className').animate({
          scrollTop: 80
        }, 20);
		//fs[0].scroll();
		setTimeout(function(){
			debugger;
			expect(FreeScroll.noMore).toHaveBeenCalled();
			expect(fs.promise.more).not.toHaveBeenCalled();
		}, 50);

	});
});<|endoftext|>


<commit_before>define(
  [
    'collections/application_search_results',
    'rsvp'
  ],
  function (SearchResults, RSVP) {

    var searchApplications = function (query) {

      var apps = new SearchResults([], {
        query: query
      });

      return new RSVP.Promise(function (resolve, reject) {
        apps.fetch({
          success: function (coll) {
            resolve(coll);
          },
          error: function (coll, response) {
            reject(response.responseText);
          }
        });
      });
    };

    return {
      searchApplications: searchApplications
    };
  });
<commit_msg>Remove unused controller applications<commit_after><|endoftext|>


<commit_before>// ==UserScript==
// @name        WME Bookmarklets
// @author      Tom 'Glodenox' Puttemans
// @namespace   http://www.tomputtemans.com/
// @description Put bookmarklets in a tab and provide a better code execution environment
// @include     /^https:\/\/(www|editor-beta)\.waze\.com\/(?!user\/)(.{2,6}\/)?editor\/.*$/
// @version     0.0.2
// @grant       none
// ==/UserScript==
(function() {
  var bookmarklets = [];
  if (localStorage.WME_Bookmarklets) {
    importBookmarklets(JSON.parse(localStorage.WME_Bookmarklets).bookmarklets);
  }

  function init(e) {
    if (e && e.user == null) {
      return;
    }
    if (document.getElementById('user-info') == null) {
      setTimeout(init, 500);
      log('user-info element not yet available, page still loading');
      return;
    }
    if (typeof Waze.loginManager === 'undefined') {
      setTimeout(init, 300);
      return;
    }
    if (!Waze.loginManager.hasUser()) {
      Waze.loginManager.events.register('login', null, init);
      Waze.loginManager.events.register('loginStatus', null, init);
      // Double check as event might have triggered already
      if (!Waze.loginManager.hasUser()) {
        return;
      }
    }

    // Deal with events mode
    if (Waze.app.modeController) {
      Waze.app.modeController.model.bind('change:mode', function(model, modeId) {
        if (modeId == 0) {
          addTab(tab);
        }
      });
    }

    var om_strings = {
      en: {
        tab_title: 'Bookmarklets',
        add_bookmarklet: 'Add bookmarklet',
        empty_list: 'No bookmarklets added yet',
        bookmarklet_name: 'Name',
        bookmarklet_script: 'Script',
        bookmarklet_error: 'Bookmarklet threw an error',
        message: 'Activate a bookmarklet or add a new one:',
        bookmarklet_sources: 'Many Wazers have created bookmarklets to perform small tasks within the WME. Most of these can be found on the wiki or by seaching the forums'
      }
    };
    om_strings.en_GB = om_strings.en;
    for (var i = 0; i < I18n.availableLocales.length; i++) {
      var locale = I18n.availableLocales[i];
      if (I18n.translations[locale]) {
        I18n.translations[locale].bookmarklets = om_strings[locale];
      }
    }

    var tab = addTab();
    /*var versionInfo = document.createElement('a');
    versionInfo.appendChild(document.createTextNode('v' + GM_info.script.version));
    versionInfo.href = 'https://greasyfork.org/nl/scripts/20379-wme-bookmarklets/'; // TODO: to replace with forum link once published
    versionInfo.style.float = 'right';
    tab.appendChild(versionInfo);*/
    var message = document.createElement('p');
    message.appendChild(document.createTextNode(I18n.t('bookmarklets.message')));
    tab.appendChild(message);

    var emptyList = document.createElement('span');
    emptyList.id = 'emptyBookmarklets';
    emptyList.style.fontStyle = 'italic';
    emptyList.style.display = (bookmarklets.length == 0 ? 'block' : 'none');
    emptyList.appendChild(document.createTextNode(I18n.t('bookmarklets.empty_list')));
    tab.appendChild(emptyList);

    var bookmarkletList = document.createElement('div');
    bookmarkletList.className = 'result-list';
    bookmarkletList.style.borderTop = '1px solid #e0e0e0';
    bookmarkletList.style.marginBottom = '5px';
    bookmarklets.forEach(function(bookmarklet) {
      addBookmarklet(bookmarklet);
    });
    tab.appendChild(bookmarkletList);

    var addBookmarkletForm = document.createElement('form');
    var addBookmarkletTitle = document.createElement('h4');
    addBookmarkletTitle.appendChild(document.createTextNode(I18n.t('bookmarklets.add_bookmarklet')));
    addBookmarkletForm.appendChild(addBookmarkletTitle);
    addBookmarkletForm.style.display = 'none';
    var nameGroup = document.createElement('div');
    nameGroup.className = 'form-group';
    var nameFieldLabel = document.createElement('label');
    nameFieldLabel.htmlFor = 'name';
    nameFieldLabel.appendChild(document.createTextNode(I18n.t('bookmarklets.bookmarklet_name')));
    nameGroup.appendChild(nameFieldLabel);
    var nameField = document.createElement('input');
    nameField.type = 'text';
    nameField.autocomplete = 'off';
    nameField.style.width = '100%';
    nameField.name = 'name';
    nameField.className = 'from-control';
    nameGroup.appendChild(nameField);
    addBookmarkletForm.appendChild(nameGroup);
    var scriptGroup = document.createElement('div');
    scriptGroup.className = 'form-group';
    var scriptFieldLabel = document.createElement('label');
    scriptFieldLabel.htmlFor = 'script';
    scriptFieldLabel.appendChild(document.createTextNode(I18n.t('bookmarklets.bookmarklet_script')));
    scriptGroup.appendChild(scriptFieldLabel);
    var scriptField = document.createElement('textarea');
    scriptField.name = 'script';
    scriptField.className = 'from-control';
    scriptField.style.width = '100%';
    scriptField.style.height = 'auto';
    scriptGroup.appendChild(scriptField);
    addBookmarkletForm.appendChild(scriptGroup);
    var createBookmarklet = document.createElement('input');
    createBookmarklet.type = 'submit';
    createBookmarklet.className = 'btn btn-default';
    createBookmarklet.value = I18n.t('bookmarklets.add_bookmarklet');
    addBookmarkletForm.appendChild(createBookmarklet);

    var addBookmarkletButton = document.createElement('button');
    addBookmarkletButton.className = 'btn btn-default';
    var addSpan = document.createElement('span');
    addSpan.appendChild(document.createTextNode('?'));
    addSpan.className = 'fa';
    addSpan.style.marginRight = '5px';
    addBookmarkletButton.appendChild(addSpan);
    addBookmarkletButton.appendChild(document.createTextNode(I18n.t('bookmarklets.add_bookmarklet')));
    addBookmarkletButton.addEventListener('click', function() {
      addBookmarkletButton.style.display = 'none';
      addBookmarkletForm.style.display = 'block';
    });
    tab.appendChild(addBookmarkletButton);
    tab.appendChild(addBookmarkletForm);
    var bookmarkletSources = document.createElement('p');
    bookmarkletSources.innerHTML = I18n.t('bookmarklets.bookmarklet_sources');
    tab.appendChild(bookmarkletSources);

    addBookmarkletForm.addEventListener('submit', function(e) {
      e.preventDefault();
      addBookmarkletForm.style.display = 'none';
      addBookmarkletButton.style.display = 'block';
      var newBookmarklet = {};
      newBookmarklet.name = nameField.value;
      newBookmarklet.script = scriptField.value;
      addBookmarklet(newBookmarklet);
      bookmarklets.push(newBookmarklet);
      saveBookmarklets();
      return false;
    }, true);

    // Create a tab and possibly receive a previous tab to restore (usually in case of a mode change)
    function addTab(recoveredTab) {
      var userInfo = document.getElementById('user-info'),
          tabHandles = userInfo.querySelector('.nav-tabs'),
          tabs = userInfo.querySelector('.tab-content'),
          tabHandle = document.createElement('li'),
          tab = document.createElement('div');
      tabHandle.innerHTML = '?';
      if (recoveredTab) {
        tab = recoveredTab;
      } else {
        tab.id = 'sidepanel-bookmarklets';
        tab.className = 'tab-pane';
      }
      tabHandles.appendChild(tabHandle);
      $(tabHandle.childNodes[0]).tooltip();
      tabs.appendChild(tab);
      return tab;
    }

    function addBookmarklet(bookmarklet) {
      document.getElementById('emptyBookmarklets').style.display = 'none';
      var bookmarkletContainer = document.createElement('div');
      bookmarkletContainer.className = 'result session-available';
      var bookmarkletName = document.createElement('div');
      bookmarkletName.appendChild(document.createTextNode(bookmarklet.name));
      bookmarkletContainer.appendChild(bookmarkletName);
      var bookmarkletError = document.createElement('div');
      bookmarkletError.style.display = 'none';
      bookmarkletError.style.backgroundColor = 'red';
      bookmarkletError.style.color = '#f2dede';
      bookmarkletError.style.border = '2px solid #f2dede';
      bookmarkletError.style.padding = '4px';
      bookmarkletError.style.margin = '4px 0 4px 0';
      bookmarkletContainer.appendChild(bookmarkletError);
      var bookmarkletErrorClose = document.createElement('button');
      bookmarkletErrorClose.style.fontFamily = 'FontAwesome';
      bookmarkletErrorClose.style.color = '#f2dede';
      bookmarkletErrorClose.style.border = 'none';
      bookmarkletErrorClose.style.background = 'none';
      bookmarkletErrorClose.style.padding = '3px';
      bookmarkletErrorClose.style.float = 'right';
      bookmarkletErrorClose.style.cursor = 'pointer';
      bookmarkletErrorClose.style.height = 'auto';
      bookmarkletErrorClose.style.outline = 'none';
      bookmarkletErrorClose.appendChild(document.createTextNode('?'));
      bookmarkletErrorClose.addEventListener('click', function(e) {
        e.stopPropagation();
        bookmarkletError.style.display = 'none';
      }, true);
      bookmarkletError.appendChild(bookmarkletErrorClose);
      var bookmarkletErrorTitle = document.createElement('strong');
      bookmarkletErrorTitle.appendChild(document.createTextNode(I18n.t('bookmarklets.bookmarklet_error')));
      bookmarkletError.appendChild(bookmarkletErrorTitle);
      bookmarkletError.appendChild(document.createElement('br'));
      bookmarkletContainer.addEventListener('click', function() {
        try {
          var cleanedUpScript = decodeURI(bookmarklet.script);
          cleanedUpScript = cleanedUpScript.replace('javascript:', '');
          eval(cleanedUpScript);
        } catch (e) {
          log(e);
          if (bookmarkletError.childNodes[3]) { // Remove previous error message
            bookmarkletError.removeChild(bookmarkletError.childNodes[3]);
          }
          bookmarkletError.appendChild(document.createTextNode((e && e.message ? e.message : e)));
          bookmarkletError.style.display = 'block';
        }
      });
      bookmarkletList.appendChild(bookmarkletContainer);
    }

    function removeBookmarklet(name) {
      // TODO: implement
      if (bookmarklets.length == 0) {
        document.getElementById('emptyBookmarklets').style.display = 'none';
      }
    }
  }

  function importBookmarklets(data) {
    data.forEach(function(bookmarklet) {
      bookmarklets.push(bookmarklet);
    });
  }

  function saveBookmarklets() {
    var storage;
    if (typeof localStorage.WME_Bookmarklets == 'undefined') {
      storage = {};
    } else {
      storage = JSON.parse(localStorage.WME_Bookmarklets);
    }
    storage.bookmarklets = bookmarklets;
    localStorage.WME_Bookmarklets = JSON.stringify(storage);
  }

  function log(message) {
    if (typeof message === 'string') {
      console.log('%c' + GM_info.script.name + ' (v' + GM_info.script.version + '): %c' + message, 'color:black', 'color:#d97e00');
    } else {
      console.log('%c' + GM_info.script.name + ' (v' + GM_info.script.version + ')', 'color:black', message);
    }
  }

  init();
})();<commit_msg>Bad Notepad++! If I say UTF-8, don't change it to ANSI...<commit_after>// ==UserScript==
// @name        WME Bookmarklets
// @author      Tom 'Glodenox' Puttemans
// @namespace   http://www.tomputtemans.com/
// @description Put bookmarklets in a tab and provide a better code execution environment
// @include     /^https:\/\/(www|editor-beta)\.waze\.com\/(?!user\/)(.{2,6}\/)?editor\/.*$/
// @version     0.0.3
// @grant       none
// ==/UserScript==
(function() {
  var bookmarklets = [];
  if (localStorage.WME_Bookmarklets) {
    importBookmarklets(JSON.parse(localStorage.WME_Bookmarklets).bookmarklets);
  }

  function init(e) {
    if (e && e.user == null) {
      return;
    }
    if (document.getElementById('user-info') == null) {
      setTimeout(init, 500);
      log('user-info element not yet available, page still loading');
      return;
    }
    if (typeof Waze.loginManager === 'undefined') {
      setTimeout(init, 300);
      return;
    }
    if (!Waze.loginManager.hasUser()) {
      Waze.loginManager.events.register('login', null, init);
      Waze.loginManager.events.register('loginStatus', null, init);
      // Double check as event might have triggered already
      if (!Waze.loginManager.hasUser()) {
        return;
      }
    }

    // Deal with events mode
    if (Waze.app.modeController) {
      Waze.app.modeController.model.bind('change:mode', function(model, modeId) {
        if (modeId == 0) {
          addTab(tab);
        }
      });
    }

    var om_strings = {
      en: {
        tab_title: 'Bookmarklets',
        add_bookmarklet: 'Add bookmarklet',
        empty_list: 'No bookmarklets added yet',
        bookmarklet_name: 'Name',
        bookmarklet_script: 'Script',
        bookmarklet_error: 'Bookmarklet threw an error',
        message: 'Activate a bookmarklet or add a new one:',
        bookmarklet_sources: 'Many Wazers have created bookmarklets to perform small tasks within the WME. Most of these can be found on the wiki or by seaching the forums'
      }
    };
    om_strings.en_GB = om_strings.en;
    for (var i = 0; i < I18n.availableLocales.length; i++) {
      var locale = I18n.availableLocales[i];
      if (I18n.translations[locale]) {
        I18n.translations[locale].bookmarklets = om_strings[locale];
      }
    }

    var tab = addTab();
    /*var versionInfo = document.createElement('a');
    versionInfo.appendChild(document.createTextNode('v' + GM_info.script.version));
    versionInfo.href = 'https://greasyfork.org/nl/scripts/20379-wme-bookmarklets/'; // TODO: to replace with forum link once published
    versionInfo.style.float = 'right';
    tab.appendChild(versionInfo);*/
    var message = document.createElement('p');
    message.appendChild(document.createTextNode(I18n.t('bookmarklets.message')));
    tab.appendChild(message);

    var emptyList = document.createElement('span');
    emptyList.id = 'emptyBookmarklets';
    emptyList.style.fontStyle = 'italic';
    emptyList.style.display = (bookmarklets.length == 0 ? 'block' : 'none');
    emptyList.appendChild(document.createTextNode(I18n.t('bookmarklets.empty_list')));
    tab.appendChild(emptyList);

    var bookmarkletList = document.createElement('div');
    bookmarkletList.className = 'result-list';
    bookmarkletList.style.borderTop = '1px solid #e0e0e0';
    bookmarkletList.style.marginBottom = '5px';
    bookmarklets.forEach(function(bookmarklet) {
      addBookmarklet(bookmarklet);
    });
    tab.appendChild(bookmarkletList);

    var addBookmarkletForm = document.createElement('form');
    var addBookmarkletTitle = document.createElement('h4');
    addBookmarkletTitle.appendChild(document.createTextNode(I18n.t('bookmarklets.add_bookmarklet')));
    addBookmarkletForm.appendChild(addBookmarkletTitle);
    addBookmarkletForm.style.display = 'none';
    var nameGroup = document.createElement('div');
    nameGroup.className = 'form-group';
    var nameFieldLabel = document.createElement('label');
    nameFieldLabel.htmlFor = 'name';
    nameFieldLabel.appendChild(document.createTextNode(I18n.t('bookmarklets.bookmarklet_name')));
    nameGroup.appendChild(nameFieldLabel);
    var nameField = document.createElement('input');
    nameField.type = 'text';
    nameField.autocomplete = 'off';
    nameField.style.width = '100%';
    nameField.name = 'name';
    nameField.className = 'from-control';
    nameGroup.appendChild(nameField);
    addBookmarkletForm.appendChild(nameGroup);
    var scriptGroup = document.createElement('div');
    scriptGroup.className = 'form-group';
    var scriptFieldLabel = document.createElement('label');
    scriptFieldLabel.htmlFor = 'script';
    scriptFieldLabel.appendChild(document.createTextNode(I18n.t('bookmarklets.bookmarklet_script')));
    scriptGroup.appendChild(scriptFieldLabel);
    var scriptField = document.createElement('textarea');
    scriptField.name = 'script';
    scriptField.className = 'from-control';
    scriptField.style.width = '100%';
    scriptField.style.height = 'auto';
    scriptGroup.appendChild(scriptField);
    addBookmarkletForm.appendChild(scriptGroup);
    var createBookmarklet = document.createElement('input');
    createBookmarklet.type = 'submit';
    createBookmarklet.className = 'btn btn-default';
    createBookmarklet.value = I18n.t('bookmarklets.add_bookmarklet');
    addBookmarkletForm.appendChild(createBookmarklet);

    var addBookmarkletButton = document.createElement('button');
    addBookmarkletButton.className = 'btn btn-default';
    var addSpan = document.createElement('span');
    addSpan.appendChild(document.createTextNode(''));
    addSpan.className = 'fa';
    addSpan.style.marginRight = '5px';
    addBookmarkletButton.appendChild(addSpan);
    addBookmarkletButton.appendChild(document.createTextNode(I18n.t('bookmarklets.add_bookmarklet')));
    addBookmarkletButton.addEventListener('click', function() {
      addBookmarkletButton.style.display = 'none';
      addBookmarkletForm.style.display = 'block';
    });
    tab.appendChild(addBookmarkletButton);
    tab.appendChild(addBookmarkletForm);
    var bookmarkletSources = document.createElement('p');
    bookmarkletSources.innerHTML = I18n.t('bookmarklets.bookmarklet_sources');
    tab.appendChild(bookmarkletSources);

    addBookmarkletForm.addEventListener('submit', function(e) {
      e.preventDefault();
      addBookmarkletForm.style.display = 'none';
      addBookmarkletButton.style.display = 'block';
      var newBookmarklet = {};
      newBookmarklet.name = nameField.value;
      newBookmarklet.script = scriptField.value;
      addBookmarklet(newBookmarklet);
      bookmarklets.push(newBookmarklet);
      saveBookmarklets();
      return false;
    }, true);

    // Create a tab and possibly receive a previous tab to restore (usually in case of a mode change)
    function addTab(recoveredTab) {
      var userInfo = document.getElementById('user-info'),
          tabHandles = userInfo.querySelector('.nav-tabs'),
          tabs = userInfo.querySelector('.tab-content'),
          tabHandle = document.createElement('li'),
          tab = document.createElement('div');
      tabHandle.innerHTML = '';
      if (recoveredTab) {
        tab = recoveredTab;
      } else {
        tab.id = 'sidepanel-bookmarklets';
        tab.className = 'tab-pane';
      }
      tabHandles.appendChild(tabHandle);
      $(tabHandle.childNodes[0]).tooltip();
      tabs.appendChild(tab);
      return tab;
    }

    function addBookmarklet(bookmarklet) {
      document.getElementById('emptyBookmarklets').style.display = 'none';
      var bookmarkletContainer = document.createElement('div');
      bookmarkletContainer.className = 'result session-available';
      var bookmarkletName = document.createElement('div');
      bookmarkletName.appendChild(document.createTextNode(bookmarklet.name));
      bookmarkletContainer.appendChild(bookmarkletName);
      var bookmarkletError = document.createElement('div');
      bookmarkletError.style.display = 'none';
      bookmarkletError.style.backgroundColor = 'red';
      bookmarkletError.style.color = '#f2dede';
      bookmarkletError.style.border = '2px solid #f2dede';
      bookmarkletError.style.padding = '4px';
      bookmarkletError.style.margin = '4px 0 4px 0';
      bookmarkletContainer.appendChild(bookmarkletError);
      var bookmarkletErrorClose = document.createElement('button');
      bookmarkletErrorClose.style.fontFamily = 'FontAwesome';
      bookmarkletErrorClose.style.color = '#f2dede';
      bookmarkletErrorClose.style.border = 'none';
      bookmarkletErrorClose.style.background = 'none';
      bookmarkletErrorClose.style.padding = '3px';
      bookmarkletErrorClose.style.float = 'right';
      bookmarkletErrorClose.style.cursor = 'pointer';
      bookmarkletErrorClose.style.height = 'auto';
      bookmarkletErrorClose.style.outline = 'none';
      bookmarkletErrorClose.appendChild(document.createTextNode(''));
      bookmarkletErrorClose.addEventListener('click', function(e) {
        e.stopPropagation();
        bookmarkletError.style.display = 'none';
      }, true);
      bookmarkletError.appendChild(bookmarkletErrorClose);
      var bookmarkletErrorTitle = document.createElement('strong');
      bookmarkletErrorTitle.appendChild(document.createTextNode(I18n.t('bookmarklets.bookmarklet_error')));
      bookmarkletError.appendChild(bookmarkletErrorTitle);
      bookmarkletError.appendChild(document.createElement('br'));
      bookmarkletContainer.addEventListener('click', function() {
        try {
          var cleanedUpScript = decodeURI(bookmarklet.script);
          cleanedUpScript = cleanedUpScript.replace('javascript:', '');
          eval(cleanedUpScript);
        } catch (e) {
          log(e);
          if (bookmarkletError.childNodes[3]) { // Remove previous error message
            bookmarkletError.removeChild(bookmarkletError.childNodes[3]);
          }
          bookmarkletError.appendChild(document.createTextNode((e && e.message ? e.message : e)));
          bookmarkletError.style.display = 'block';
        }
      });
      bookmarkletList.appendChild(bookmarkletContainer);
    }

    function removeBookmarklet(name) {
      // TODO: implement
      if (bookmarklets.length == 0) {
        document.getElementById('emptyBookmarklets').style.display = 'none';
      }
    }
  }

  function importBookmarklets(data) {
    data.forEach(function(bookmarklet) {
      bookmarklets.push(bookmarklet);
    });
  }

  function saveBookmarklets() {
    var storage;
    if (typeof localStorage.WME_Bookmarklets == 'undefined') {
      storage = {};
    } else {
      storage = JSON.parse(localStorage.WME_Bookmarklets);
    }
    storage.bookmarklets = bookmarklets;
    localStorage.WME_Bookmarklets = JSON.stringify(storage);
  }

  function log(message) {
    if (typeof message === 'string') {
      console.log('%c' + GM_info.script.name + ' (v' + GM_info.script.version + '): %c' + message, 'color:black', 'color:#d97e00');
    } else {
      console.log('%c' + GM_info.script.name + ' (v' + GM_info.script.version + ')', 'color:black', message);
    }
  }

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


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

"use strict";
import APIClientFactory from "./APIClientFactory";
import Resource from "./Resource";
import Utils from "./Utils";

/***
 * Class to expose Subscription {Resource} related operations
 */

export default class Subscription extends Resource {

    constructor() {
        super();
        this.client = new APIClientFactory().getAPIClient(Utils.getEnvironment().label).client;
    }

    /**
     * Get all Subscriptions
     * @param apiId id of the API
     * @param applicationId id of the application
     * @returns {promise} With all subscription for given applicationId or apiId.
     */
    getSubscriptions(apiId, applicationId, callback = null) {
        var promise_get = this.client.then((client) => {
            return client.apis["Subscription (Collection)"].get_subscriptions(
                { apiId: apiId, applicationId: applicationId });
        }
        );
        if (callback) {
            return promise_get.then(callback);
        } else {
            return promise_get;
        }
    }

    /**
    * Delete subscription
    * @param subscriptionId id of the subscription
    * @returns {promise} With 200 OK.
    */
    deleteSubscription(subscriptionId) {
        const promised_delete_subscription = this.client.then((client) => {
            return client.apis["Subscription (Individual)"].delete_subscriptions__subscriptionId_(
                {
                    subscriptionId: subscriptionId,
                }
            );
        });
        return promised_delete_subscription;
    }
}

<commit_msg>Remove Callback from getSubscription<commit_after>/**
 * Copyright (c) 2018, WSO2 Inc. (http://wso2.com) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

"use strict";
import APIClientFactory from "./APIClientFactory";
import Resource from "./Resource";
import Utils from "./Utils";

/***
 * Class to expose Subscription {Resource} related operations
 */

export default class Subscription extends Resource {

    constructor() {
        super();
        this.client = new APIClientFactory().getAPIClient(Utils.getEnvironment().label).client;
    }

    /**
     * Get all Subscriptions
     * @param apiId id of the API
     * @param applicationId id of the application
     * @returns {promise} With all subscription for given applicationId or apiId.
     */
    getSubscriptions(apiId, applicationId) {
        var promise_get = this.client.then((client) => {
            return client.apis["Subscription (Collection)"].get_subscriptions(
                { apiId: apiId, applicationId: applicationId });
        }
        );
        return promise_get;
    }

    /**
    * Delete subscription
    * @param subscriptionId id of the subscription
    * @returns {promise} With 200 OK.
    */
    deleteSubscription(subscriptionId) {
        const promised_delete_subscription = this.client.then((client) => {
            return client.apis["Subscription (Individual)"].delete_subscriptions__subscriptionId_(
                {
                    subscriptionId: subscriptionId,
                }
            );
        });
        return promised_delete_subscription;
    }
}

<|endoftext|>


<commit_before>'use strict';
angular.module('slick', []).directive('slick', [
  '$timeout',
  '$rootScope',
  function ($timeout, $rootScope) {
    return {
      restrict: 'AEC',
      scope: {
        initOnload: '@',
        data: '=',
        currentIndex: '=',
        accessibility: '@',
        adaptiveHeight: '@',
        arrows: '@',
        asNavFor: '@',
        appendArrows: '@',
        appendDots: '@',
        autoplay: '@',
        autoplaySpeed: '@',
        centerMode: '@',
        centerPadding: '@',
        cssEase: '@',
        customPaging: '&',
        dots: '@',
        draggable: '@',
        easing: '@',
        fade: '@',
        focusOnSelect: '@',
        infinite: '@',
        initialSlide: '@',
        lazyLoad: '@',
        onBeforeChange: '&',
        onAfterChange: '&',
        onInit: '&',
        onReInit: '&',
        onSetPosition: '&',
        pauseOnHover: '@',
        pauseOnDotsHover: '@',
        responsive: '=',
        rtl: '@',
        slide: '@',
        slidesToShow: '@',
        slidesToScroll: '@',
        speed: '@',
        swipe: '@',
        swipeToSlide: '@',
        touchMove: '@',
        touchThreshold: '@',
        useCSS: '@',
        variableWidth: '@',
        vertical: '@',
        prevArrow: '@',
        nextArrow: '@'
      },
      link: function (scope, element, attrs) {
        var destroySlick, initializeSlick, isInitialized;

        destroySlick = function () {
          return $timeout(function () {
            var slider;
            slider = $(element);
            slider.slick('unslick');
            slider.find('.slick-list').remove();
            return slider;
          });
        };
        initializeSlick = function () {
          return $timeout(function () {
            var currentIndex, customPaging, slider;
            slider = $(element);
            if (scope.currentIndex != null) {
              currentIndex = scope.currentIndex;
            }
            customPaging = function (slick, index) {
              return scope.customPaging({
                slick: slick,
                index: index
              });
            };
            slider.slick({
              accessibility: scope.accessibility !== 'false',
              adaptiveHeight: scope.adaptiveHeight === 'true',
              arrows: scope.arrows !== 'false',
              asNavFor: scope.asNavFor ? scope.asNavFor : void 0,
              appendArrows: scope.appendArrows ? $(scope.appendArrows) : $(element),
              appendDots: scope.appendDots ? $(scope.appendDots) : $(element),
              autoplay: scope.autoplay === 'true',
              autoplaySpeed: scope.autoplaySpeed != null ? parseInt(scope.autoplaySpeed, 10) : 3000,
              centerMode: scope.centerMode === 'true',
              centerPadding: scope.centerPadding || '50px',
              cssEase: scope.cssEase || 'ease',
              customPaging: attrs.customPaging ? customPaging : void 0,
              dots: scope.dots === 'true',
              draggable: scope.draggable !== 'false',
              easing: scope.easing || 'linear',
              fade: scope.fade === 'true',
              focusOnSelect: scope.focusOnSelect === 'true',
              infinite: scope.infinite !== 'false',
              initialSlide: scope.initialSlide || 0,
              lazyLoad: scope.lazyLoad || 'ondemand',
              beforeChange: attrs.onBeforeChange ? scope.onBeforeChange : void 0,
              onReInit: attrs.onReInit ? scope.onReInit : void 0,
              onSetPosition: attrs.onSetPosition ? scope.onSetPosition : void 0,
              pauseOnHover: scope.pauseOnHover !== 'false',
              responsive: scope.responsive || void 0,
              rtl: scope.rtl === 'true',
              slide: scope.slide || 'div',
              slidesToShow: scope.slidesToShow != null ? parseInt(scope.slidesToShow, 10) : 1,
              slidesToScroll: scope.slidesToScroll != null ? parseInt(scope.slidesToScroll, 10) : 1,
              speed: scope.speed != null ? parseInt(scope.speed, 10) : 300,
              swipe: scope.swipe !== 'false',
              swipeToSlide: scope.swipeToSlide === 'true',
              touchMove: scope.touchMove !== 'false',
              touchThreshold: scope.touchThreshold ? parseInt(scope.touchThreshold, 10) : 5,
              useCSS: scope.useCSS !== 'false',
              variableWidth: scope.variableWidth === 'true',
              vertical: scope.vertical === 'true',
              prevArrow: scope.prevArrow ? scope.prevArrow.toString() : void 0,
              nextArrow: scope.nextArrow ? scope.nextArrow.toString() : void 0
            });
            slider.on('init', function (sl) {
              if (attrs.onInit) {
                scope.onInit();
              }
              if (currentIndex != null) {
                return sl.slideHandler(currentIndex);
              }
            });
            slider.on('afterChange', function (event, slick, currentSlide, nextSlide) {
              $rootScope.$broadcast('angular:slick:currentSlide', currentSlide);
              if (scope.onAfterChange) {
                scope.onAfterChange();
              }
              if (currentIndex != null) {
                return scope.$apply(function () {
                  currentIndex = currentSlide;
                  return scope.currentIndex = currentSlide;
                });
              }
            });
            return scope.$watch('currentIndex', function (newVal, oldVal) {
              if (currentIndex != null && newVal != null && newVal !== currentIndex) {
                return slider.slick('slickGoTo', newVal);
              }
            });
          });
        };
        if (scope.initOnload) {
          isInitialized = false;
          return scope.$watch('data', function (newVal, oldVal) {
            if (newVal != null) {
              if (isInitialized) {
                destroySlick();
              }
              initializeSlick();
              return isInitialized = true;
            }
          });
        } else {
          return initializeSlick();
        }
      }
    };
  }
]);
<commit_msg>[Update] $digest problem with SlickGoTo dontanimate<commit_after>'use strict';
angular.module('slick', []).directive('slick', [
  '$timeout',
  '$rootScope',
  function ($timeout, $rootScope) {
    return {
      restrict: 'AEC',
      scope: {
        initOnload: '@',
        data: '=',
        currentIndex: '=',
        accessibility: '@',
        adaptiveHeight: '@',
        arrows: '@',
        asNavFor: '@',
        appendArrows: '@',
        appendDots: '@',
        autoplay: '@',
        autoplaySpeed: '@',
        centerMode: '@',
        centerPadding: '@',
        cssEase: '@',
        customPaging: '&',
        dots: '@',
        draggable: '@',
        easing: '@',
        fade: '@',
        focusOnSelect: '@',
        infinite: '@',
        initialSlide: '@',
        lazyLoad: '@',
        onBeforeChange: '&',
        onAfterChange: '&',
        onInit: '&',
        onReInit: '&',
        onSetPosition: '&',
        pauseOnHover: '@',
        pauseOnDotsHover: '@',
        responsive: '=',
        rtl: '@',
        slide: '@',
        slidesToShow: '@',
        slidesToScroll: '@',
        speed: '@',
        swipe: '@',
        swipeToSlide: '@',
        touchMove: '@',
        touchThreshold: '@',
        useCSS: '@',
        variableWidth: '@',
        vertical: '@',
        prevArrow: '@',
        nextArrow: '@'
      },
      link: function (scope, element, attrs) {
        var destroySlick, initializeSlick, isInitialized;

        destroySlick = function () {
          return $timeout(function () {
            var slider;
            slider = $(element);
            slider.slick('unslick');
            slider.find('.slick-list').remove();
            return slider;
          });
        };
        initializeSlick = function () {
          return $timeout(function () {
            var currentIndex, customPaging, slider;
            slider = $(element);
            if (scope.currentIndex != null) {
              currentIndex = scope.currentIndex;
            }
            customPaging = function (slick, index) {
              return scope.customPaging({
                slick: slick,
                index: index
              });
            };
            slider.slick({
              accessibility: scope.accessibility !== 'false',
              adaptiveHeight: scope.adaptiveHeight === 'true',
              arrows: scope.arrows !== 'false',
              asNavFor: scope.asNavFor ? scope.asNavFor : void 0,
              appendArrows: scope.appendArrows ? $(scope.appendArrows) : $(element),
              appendDots: scope.appendDots ? $(scope.appendDots) : $(element),
              autoplay: scope.autoplay === 'true',
              autoplaySpeed: scope.autoplaySpeed != null ? parseInt(scope.autoplaySpeed, 10) : 3000,
              centerMode: scope.centerMode === 'true',
              centerPadding: scope.centerPadding || '50px',
              cssEase: scope.cssEase || 'ease',
              customPaging: attrs.customPaging ? customPaging : void 0,
              dots: scope.dots === 'true',
              draggable: scope.draggable !== 'false',
              easing: scope.easing || 'linear',
              fade: scope.fade === 'true',
              focusOnSelect: scope.focusOnSelect === 'true',
              infinite: scope.infinite !== 'false',
              initialSlide: scope.initialSlide || 0,
              lazyLoad: scope.lazyLoad || 'ondemand',
              beforeChange: attrs.onBeforeChange ? scope.onBeforeChange : void 0,
              onReInit: attrs.onReInit ? scope.onReInit : void 0,
              onSetPosition: attrs.onSetPosition ? scope.onSetPosition : void 0,
              pauseOnHover: scope.pauseOnHover !== 'false',
              responsive: scope.responsive || void 0,
              rtl: scope.rtl === 'true',
              slide: scope.slide || 'div',
              slidesToShow: scope.slidesToShow != null ? parseInt(scope.slidesToShow, 10) : 1,
              slidesToScroll: scope.slidesToScroll != null ? parseInt(scope.slidesToScroll, 10) : 1,
              speed: scope.speed != null ? parseInt(scope.speed, 10) : 300,
              swipe: scope.swipe !== 'false',
              swipeToSlide: scope.swipeToSlide === 'true',
              touchMove: scope.touchMove !== 'false',
              touchThreshold: scope.touchThreshold ? parseInt(scope.touchThreshold, 10) : 5,
              useCSS: scope.useCSS !== 'false',
              variableWidth: scope.variableWidth === 'true',
              vertical: scope.vertical === 'true',
              prevArrow: scope.prevArrow ? scope.prevArrow.toString() : void 0,
              nextArrow: scope.nextArrow ? scope.nextArrow.toString() : void 0
            });
            slider.on('init', function (sl) {
              if (attrs.onInit) {
                scope.onInit();
              }
              if (currentIndex != null) {
                return sl.slideHandler(currentIndex);
              }
            });
            slider.on('afterChange', function (event, slick, currentSlide, nextSlide) {
              $rootScope.$broadcast('angular:slick:currentSlide', currentSlide);
              if (scope.onAfterChange) {
                scope.onAfterChange();
              }
              if (currentIndex != null) {
                // return scope.$apply(function () {
                //   currentIndex = currentSlide;
                //   return scope.currentIndex = currentSlide;
                // });
                return function () {
                  currentIndex = currentSlide;
                  return scope.currentIndex = currentSlide;
                };
              }
            });
            return scope.$watch('currentIndex', function (newVal, oldVal) {
              // if (currentIndex != null && newVal != null && newVal !== currentIndex) {
                return slider.slick('slickGoTo', newVal, true);
              // }
            });
          });
        };
        if (scope.initOnload) {
          isInitialized = false;
          return scope.$watch('data', function (newVal, oldVal) {
            if (newVal != null) {
              if (isInitialized) {
                destroySlick();
              }
              initializeSlick();
              return isInitialized = true;
            }
          });
        } else {
          return initializeSlick();
        }
      }
    };
  }
]);
<|endoftext|>


<commit_before>var os = require('os');
var io = require('socket.io-client');
var SerialDevice = require('serialdevice');
var logger = require('./logger').getLogger('hub');

logger.info('Starting hub');

var socket = io('http://home-control.herokuapp.com');
var airControl = new SerialDevice('/dev/rfcomm0');

var heartbeatId = undefined;
function heartbeat() {
    socket.emit('heartbeat');
}

socket.on('connect', function () {
    logger.info('Connected to cloud server');

    socket.emit('who', {name: os.hostname()});

    if (airControl.isConnected()) {
        socket.emit('device-register', {name: 'air-control'});
    }

    heartbeatId = setInterval(heartbeat, 60000);
});

socket.on('disconnect', function () {
    logger.info('Disconnected from cloud server');
    if (heartbeatId) {
        clearInterval(heartbeatId);
    };
});

socket.on('command', function (data) {
    logger.info('Received command from cloud server', data);

    if (data && data.command && airControl.isConnected()) {
        airControl.sendData(data.command);
    }
});

function connectAirControl () {
    airControl.connect(function (err) {
        if (err) {
            logger.error('Error during connection with air control, retrying in 30 seconds.');
            setTimeout(connectAirControl, 30000);
            return;
        }

        logger.info('Air control connected');
        socket.emit('device-register', {name: 'air-control'});
    });
}

airControl.on('disconnect', function () {
    socket.emit('device-unregister', {name: 'air-control'});
    logger.info('Air control disconnected, trying to reconnect in 30 seconds.');
    setTimeout(connectAirControl, 30000);
});

connectAirControl();

logger.info('Hub ready');
<commit_msg>replace logger with debug<commit_after>var os = require('os');
var io = require('socket.io-client');
var SerialDevice = require('serialdevice');
var debug = require('debug')('chezmoi');

debug('Starting hub');

var socket = io('http://home-control.herokuapp.com');
var airControl = new SerialDevice('/dev/rfcomm0');

var heartbeatId = undefined;
function heartbeat() {
    socket.emit('heartbeat');
}

socket.on('connect', function () {
    debug('Connected to cloud server');

    socket.emit('who', {name: os.hostname()});

    if (airControl.isConnected()) {
        socket.emit('device-register', {name: 'air-control'});
    }

    heartbeatId = setInterval(heartbeat, 60000);
});

socket.on('disconnect', function () {
    debug('Disconnected from cloud server');
    if (heartbeatId) {
        clearInterval(heartbeatId);
    };
});

socket.on('command', function (data) {
    debug('Received command from cloud server', data);

    if (data && data.command && airControl.isConnected()) {
        airControl.sendData(data.command);
    }
});

function connectAirControl () {
    airControl.connect(function (err) {
        if (err) {
            logger.error('Error during connection with air control, retrying in 30 seconds.');
            setTimeout(connectAirControl, 30000);
            return;
        }

        debug('Air control connected');
        socket.emit('device-register', {name: 'air-control'});
    });
}

airControl.on('disconnect', function () {
    socket.emit('device-unregister', {name: 'air-control'});
    debug('Air control disconnected, trying to reconnect in 30 seconds.');
    setTimeout(connectAirControl, 30000);
});

connectAirControl();

debug('Hub ready');
<|endoftext|>


<commit_before>var fs = require('fs');

module.exports = function(grunt) {
    'use strict';
    //load npmtask
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-htmlmin');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-jsonmin');
    grunt.loadNpmTasks('grunt-contrib-concat-sourcemaps');
    grunt.loadNpmTasks('grunt-processhtml');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-aws');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-angular-templates');
    grunt.loadNpmTasks('grunt-karma');
    grunt.loadNpmTasks('grunt-protractor-runner');
    grunt.loadNpmTasks('grunt-exec');

    //configure task
    grunt.initConfig({

       srcjsFiles: [
           'src/core-module/store-app.js', 'src/core-module/scripts/**/*.js',
           'src/product-module/product-app.js', 'src/product-module/scripts/**/*.js',
           'src/user-module/user-app.js', 'src/user-module/scripts/**/*.js'
       ],
       vendorjsFiles: [
           'src/vendor/angular-input-match/dist/angular-input-match.js',
           'src/vendor/angular-translate/angular-translate.min.js',
           'src/vendor/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js',
           'src/vendor/spin.js/spin.js',
           'src/vendor/angular-spinner/angular-spinner.min.js',
           'src/vendor/lf-cookies/lf-cookies.js',
           'src/vendor/lf-firebase-auth/lf-firebase-auth-service.js'
       ],
       testjsFiles: ['tests/unit/**/*.js'],
       e2ejsFiles: ['tests/e2e/**/*.js'],
       srchtmlFiles: ['src/**/*.html'],
       srccssFiles: ['src/core-module/styles/**/*.css'],

       concat: {
           thestore: {
               dest: 'src/js/thestore.js',
               src: '<%= srcjsFiles %>'
           },
           vendors: {
               dest: 'src/js/vendors.js',
               src: ['<%= vendorjsFiles %>']
           }
       },

       processhtml: {
           build: {
               files: {'build/index.html': ['src/index.html']}
           }
       },

       jsonmin: {
           data: {
               files: [ {expand: true, cwd: 'src/storeData', src: ['**/*.json'], dest: 'build/storeData/'} ]
           },
           i18n: {
               files: [ {expand: true, cwd: 'src/i18n', src: ['**/*.json'], dest: 'build/i18n/'} ]
           }
       },

       cssmin: {
           thestore: {
               files: {
                   'build/css/thestore.min.css': ['<%= srccssFiles %>']
               }
           }
       },

       htmlmin: {
           options: {
                removeComments: true,
                collapseWhitespace: true,
                collapseBooleanAttributes: true,
                removeAttributeQuotes: true,
                removeRedundantAttributes: true,
                removeOptionalTags: true,
                removeScriptTypeAttributes:     true,
                removeStyleLinkTypeAttributes:  true,
                removeEmptyAttributes:          true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true
           },
           index: {
               files: {'build/index.html': 'build/index.html'}
           }
       },

       copy: {
           favicon: {
               dest: 'build/favicon.ico',
               src: 'src/favicon.ico'
           },
           vendors: {
               dest: 'build/vendors.min.js',
               src: 'src/js/vendors.js'
           }
       },

       jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            src: ['Gruntfile.js','<%= srcjsFiles %>'],
            tests:  ['<%= testjsFiles %>'],
            e2e:  ['<%= e2ejsFiles %>']
       },

       uglify: {
           options: {
               mangle: true,
               preserveComments: false,
               compress: true
           },
           js: {
               files: {'build/thestore.min.js': ['<%= concat.thestore.dest %>']}
           }
       },

       clean: {
           build: ['build'],
           postbuild: ['<%= ngtemplates.storeApp.dest %>', 'src/js'],
           js: ['src/js'],
           coverage: ['coverage']
       },

       aws: (grunt.file.exists('../aws.json')) ? grunt.file.readJSON('../aws.json') : null,
       s3: {
           options: {
               accessKeyId: '<%= aws.accessKeyId %>',
               secretAccessKey: '<%= aws.secretAccessKey %>',
               bucket: 'gostore'
           },
           build: {
               cwd: 'build/',
               src: '**'
           }
       },

        // The actual grunt server settings
        connect: {
            options: {
                // Change this to '0.0.0.0' to access the server from outside.
                hostname: 'localhost',
                livereload: 35729
            },
            livereload: {
                options: {
                    port: 9000,
                    open: true,
                    base: 'src'
                }
            },
            build: {
                options: {
                    livereload: true,
                    keepalive: true,
                    port: 9001,
                    open: true,
                    base: 'build'
                }
            },
            travis: {
                base: 'src',
                hostname: 'localhost',
                port: 9000
            }
        },

       watch: {
           js: {
               files: ['<%= srcjsFiles %>', '<%= testjsFiles %>'],
               tasks: ['lintjs', 'concat:thestore']
           },
           livereload: {
               options: {
                   livereload: '<%= connect.options.livereload %>'
               },
               files: [
                   'src/js/thestore.js',
                   '<%= srchtmlFiles %>',
                   '<%= srccssFiles %>',
                   'i18n/messages_en.json'
               ]
           }
       },

        ngtemplates:  {
            storeApp:        {
                cwd: 'src',
                src:      '**/views/**/*.html',
                dest:     'src/core-module/scripts/templates.js',
                options: {
                    htmlmin: {
                        removeComments: true,
                        collapseWhitespace: true,
                        collapseBooleanAttributes: true,
                        removeAttributeQuotes: true,
                        removeRedundantAttributes: true,
                        removeOptionalTags: true,
                        removeScriptTypeAttributes: true,
                        removeStyleLinkTypeAttributes: true,
                        removeEmptyAttributes: true
                    }
                }
            }
        },

        karma: {
            test: {
                configFile: 'karma.conf.js'
            },
            build: {
                configFile: 'karma.conf.js',
                browsers: ['PhantomJS'],
                singleRun: true
            }
        },

        protractor: {
            options: {
                configFile: "node_modules/protractor/referenceConf.js", // Default config file
                keepAlive: false, // If false, the grunt process stops when the test fails.
                noColor: false, // If true, protractor will not use colors in its output.
                args: {
                    // Arguments passed to the command
                }
            },
            test: {   // Grunt requires at least one target to run so you can simply put 'all: {}' here too.
                options: {
                    configFile: "protractor.conf.js", // Target-specific config file
                    args: {
                    } // Target-specific arguments
                }
            },
            travis: {   // Grunt requires at least one target to run so you can simply put 'all: {}' here too.
                options: {
                    configFile: "saucelabs.protractor.conf.js", // Target-specific config file
                    args: {
                        sauceUser: process.env.SAUCE_USERNAME,
                        sauceKey: process.env.SAUCE_ACCESS_KEY
                    } // Target-specific arguments
                }
            }
        },

        exec: {
            selenium: 'webdriver-manager start'
        }
    });

    grunt.registerTask('log-build', function() {
        this.requires('karma:build');
        this.requires('ngtemplates');
        this.requires('clean:build');
        this.requires('concat');
        this.requires('processhtml');
        this.requires('jsonmin');
        this.requires('cssmin');
        this.requires('htmlmin');
        this.requires('copy');
        this.requires('lintjs');
        this.requires('uglify');
        grunt.task.run('clean:postbuild');

        var message = 'Built on ' + new Date();
        fs.appendFileSync('build.log', message + '\n');
        grunt.log.writeln(message);
    });

    // makes jshint optional
    grunt.registerTask('lintjs', function() {
        if (grunt.file.exists('.jshintrc')) {
            grunt.task.run('jshint');
        }
        else {
            grunt.log.writeln('Warning: .jshintrc file not found. Javascript not linted!');
        }
    });

    grunt.registerTask('log-deployAWS', function() {
        var message = 'Deployed on ' + new Date();
        fs.appendFileSync('deployAWS.log', message + '\n');
        grunt.log.writeln(message);
    });

    grunt.registerTask('serve', 'start a connect web server', function () {
        grunt.task.run([
            'lintjs',
            'clean:js',
            'concat',
            'connect:livereload',
            'watch'
        ]);
    });

    grunt.registerTask('build', ['karma:build', 'ngtemplates', 'clean:build', 'concat', 'processhtml', 'jsonmin', 'cssmin', 'htmlmin', 'lintjs', 'uglify', 'copy', 'clean:postbuild', 'log-build',
        'connect:build']);
    grunt.registerTask('default', 'build');
    grunt.registerTask('deployAWS', ['s3', 'log-deployAWS']);

    grunt.registerTask('CITest', ['connect:travis', 'karma:build', 'protractor:travis']);

};<commit_msg>added travis ci<commit_after>var fs = require('fs');

module.exports = function(grunt) {
    'use strict';
    //load npmtask
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-htmlmin');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-jsonmin');
    grunt.loadNpmTasks('grunt-contrib-concat-sourcemaps');
    grunt.loadNpmTasks('grunt-processhtml');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-aws');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-angular-templates');
    grunt.loadNpmTasks('grunt-karma');
    grunt.loadNpmTasks('grunt-protractor-runner');
    grunt.loadNpmTasks('grunt-exec');

    //configure task
    grunt.initConfig({

       srcjsFiles: [
           'src/core-module/store-app.js', 'src/core-module/scripts/**/*.js',
           'src/product-module/product-app.js', 'src/product-module/scripts/**/*.js',
           'src/user-module/user-app.js', 'src/user-module/scripts/**/*.js'
       ],
       vendorjsFiles: [
           'src/vendor/angular-input-match/dist/angular-input-match.js',
           'src/vendor/angular-translate/angular-translate.min.js',
           'src/vendor/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js',
           'src/vendor/spin.js/spin.js',
           'src/vendor/angular-spinner/angular-spinner.min.js',
           'src/vendor/lf-cookies/lf-cookies.js',
           'src/vendor/lf-firebase-auth/lf-firebase-auth-service.js'
       ],
       testjsFiles: ['tests/unit/**/*.js'],
       e2ejsFiles: ['tests/e2e/**/*.js'],
       srchtmlFiles: ['src/**/*.html'],
       srccssFiles: ['src/core-module/styles/**/*.css'],

       concat: {
           thestore: {
               dest: 'src/js/thestore.js',
               src: '<%= srcjsFiles %>'
           },
           vendors: {
               dest: 'src/js/vendors.js',
               src: ['<%= vendorjsFiles %>']
           }
       },

       processhtml: {
           build: {
               files: {'build/index.html': ['src/index.html']}
           }
       },

       jsonmin: {
           data: {
               files: [ {expand: true, cwd: 'src/storeData', src: ['**/*.json'], dest: 'build/storeData/'} ]
           },
           i18n: {
               files: [ {expand: true, cwd: 'src/i18n', src: ['**/*.json'], dest: 'build/i18n/'} ]
           }
       },

       cssmin: {
           thestore: {
               files: {
                   'build/css/thestore.min.css': ['<%= srccssFiles %>']
               }
           }
       },

       htmlmin: {
           options: {
                removeComments: true,
                collapseWhitespace: true,
                collapseBooleanAttributes: true,
                removeAttributeQuotes: true,
                removeRedundantAttributes: true,
                removeOptionalTags: true,
                removeScriptTypeAttributes:     true,
                removeStyleLinkTypeAttributes:  true,
                removeEmptyAttributes:          true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true
           },
           index: {
               files: {'build/index.html': 'build/index.html'}
           }
       },

       copy: {
           favicon: {
               dest: 'build/favicon.ico',
               src: 'src/favicon.ico'
           },
           vendors: {
               dest: 'build/vendors.min.js',
               src: 'src/js/vendors.js'
           }
       },

       jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            src: ['Gruntfile.js','<%= srcjsFiles %>'],
            tests:  ['<%= testjsFiles %>'],
            e2e:  ['<%= e2ejsFiles %>']
       },

       uglify: {
           options: {
               mangle: true,
               preserveComments: false,
               compress: true
           },
           js: {
               files: {'build/thestore.min.js': ['<%= concat.thestore.dest %>']}
           }
       },

       clean: {
           build: ['build'],
           postbuild: ['<%= ngtemplates.storeApp.dest %>', 'src/js'],
           js: ['src/js'],
           coverage: ['coverage']
       },

       aws: (grunt.file.exists('../aws.json')) ? grunt.file.readJSON('../aws.json') : null,
       s3: {
           options: {
               accessKeyId: '<%= aws.accessKeyId %>',
               secretAccessKey: '<%= aws.secretAccessKey %>',
               bucket: 'gostore'
           },
           build: {
               cwd: 'build/',
               src: '**'
           }
       },

        // The actual grunt server settings
        connect: {
            options: {
                // Change this to '0.0.0.0' to access the server from outside.
                hostname: 'localhost',
                livereload: 35729
            },
            livereload: {
                options: {
                    port: 9000,
                    open: true,
                    base: 'src'
                }
            },
            build: {
                options: {
                    livereload: true,
                    keepalive: true,
                    port: 9001,
                    open: true,
                    base: 'build'
                }
            },
            travis: {
                base: 'src',
                hostname: 'localhost',
                port: 9000
            }
        },

       watch: {
           js: {
               files: ['<%= srcjsFiles %>', '<%= testjsFiles %>'],
               tasks: ['lintjs', 'concat:thestore']
           },
           livereload: {
               options: {
                   livereload: '<%= connect.options.livereload %>'
               },
               files: [
                   'src/js/thestore.js',
                   '<%= srchtmlFiles %>',
                   '<%= srccssFiles %>',
                   'i18n/messages_en.json'
               ]
           }
       },

        ngtemplates:  {
            storeApp:        {
                cwd: 'src',
                src:      '**/views/**/*.html',
                dest:     'src/core-module/scripts/templates.js',
                options: {
                    htmlmin: {
                        removeComments: true,
                        collapseWhitespace: true,
                        collapseBooleanAttributes: true,
                        removeAttributeQuotes: true,
                        removeRedundantAttributes: true,
                        removeOptionalTags: true,
                        removeScriptTypeAttributes: true,
                        removeStyleLinkTypeAttributes: true,
                        removeEmptyAttributes: true
                    }
                }
            }
        },

        karma: {
            test: {
                configFile: 'karma.conf.js'
            },
            build: {
                configFile: 'karma.conf.js',
                browsers: ['PhantomJS'],
                singleRun: true
            }
        },

        protractor: {
            options: {
                configFile: "node_modules/protractor/referenceConf.js", // Default config file
                keepAlive: false, // If false, the grunt process stops when the test fails.
                noColor: false, // If true, protractor will not use colors in its output.
                args: {
                    // Arguments passed to the command
                }
            },
            test: {   // Grunt requires at least one target to run so you can simply put 'all: {}' here too.
                options: {
                    configFile: "protractor.conf.js", // Target-specific config file
                    args: {
                    } // Target-specific arguments
                }
            },
            travis: {   // Grunt requires at least one target to run so you can simply put 'all: {}' here too.
                options: {
                    configFile: "saucelabs.protractor.conf.js", // Target-specific config file
                    args: {
                        sauceUser: process.env.SAUCE_USERNAME,
                        sauceKey: process.env.SAUCE_ACCESS_KEY
                    } // Target-specific arguments
                }
            }
        },

        exec: {
            selenium: 'webdriver-manager start'
        }
    });

    grunt.registerTask('log-build', function() {
        this.requires('karma:build');
        this.requires('ngtemplates');
        this.requires('clean:build');
        this.requires('concat');
        this.requires('processhtml');
        this.requires('jsonmin');
        this.requires('cssmin');
        this.requires('htmlmin');
        this.requires('copy');
        this.requires('lintjs');
        this.requires('uglify');
        grunt.task.run('clean:postbuild');

        var message = 'Built on ' + new Date();
        fs.appendFileSync('build.log', message + '\n');
        grunt.log.writeln(message);
    });

    // makes jshint optional
    grunt.registerTask('lintjs', function() {
        if (grunt.file.exists('.jshintrc')) {
            grunt.task.run('jshint');
        }
        else {
            grunt.log.writeln('Warning: .jshintrc file not found. Javascript not linted!');
        }
    });

    grunt.registerTask('log-deployAWS', function() {
        var message = 'Deployed on ' + new Date();
        fs.appendFileSync('deployAWS.log', message + '\n');
        grunt.log.writeln(message);
    });

    grunt.registerTask('serve', 'start a connect web server', function () {
        grunt.task.run([
            'lintjs',
            'clean:js',
            'concat',
            'connect:livereload',
            'watch'
        ]);
    });

    grunt.registerTask('build', ['karma:build', 'ngtemplates', 'clean:build', 'concat', 'processhtml', 'jsonmin', 'cssmin', 'htmlmin', 'lintjs', 'uglify', 'copy', 'clean:postbuild', 'log-build',
        'connect:build']);
    grunt.registerTask('default', 'build');
    grunt.registerTask('deployAWS', ['s3', 'log-deployAWS']);

    grunt.registerTask('CITest', ['concat', 'connect:travis', 'karma:build', 'protractor:travis']);

};<|endoftext|>


<commit_before>// LICENSE : MIT
"use strict";
import assert from "power-assert";
import TextLintCore from "../src/textlint-core";
import ruleAdd from "./fixtures/fixer-rules/fixer-rule-add";
import ruleReplace from "./fixtures/fixer-rules/fixer-rule-replace";
describe("textlint-fixer", function () {
    context("when use fixer-rule-add", function () {
        it("should return text added and replaced", function () {
            var textlint = new TextLintCore();
            textlint.setupRules({
                "fixer-rule-add": ruleAdd,
                "fixer-rule-replace": ruleReplace
            });
            return textlint.fixText("This is fix", ".md").then(result => {
                assert(typeof result.text === "string");
                assert.equal(result.text, "This is fixed.");
            });
        });
    });
});<commit_msg>fix(test): rename text to output<commit_after>// LICENSE : MIT
"use strict";
import assert from "power-assert";
import TextLintCore from "../src/textlint-core";
import ruleAdd from "./fixtures/fixer-rules/fixer-rule-add";
import ruleReplace from "./fixtures/fixer-rules/fixer-rule-replace";
describe("textlint-fixer", function () {
    context("when use fixer-rule-add", function () {
        it("should return text added and replaced", function () {
            var textlint = new TextLintCore();
            textlint.setupRules({
                "fixer-rule-add": ruleAdd,
                "fixer-rule-replace": ruleReplace
            });
            return textlint.fixText("This is fix", ".md").then(result => {
                assert(typeof result.output === "string");
                assert.equal(result.output, "This is fixed.");
            });
        });
    });
});<|endoftext|>