<commit_before>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2012-2014 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

/**
  Separate browser event handling into its own extension for cleaner
  code and testing.

  @module juju.browser
*/

YUI.add('subapp-browser-events', function(Y) {
  var browser = Y.namespace('juju.browser');

  /**
    Event handling for the browser subapp.

    @method BrowserEventsExtension
  */
  function BrowserEventsExtension() {}

  BrowserEventsExtension.prototype = {
    /**
      Handle changes in state, typically navigation requests.

      @method _onChangeState
      @param {Object} e The event facade.
    */
    _onChangeState: function(e) {
      // Cancel the inspectorRetryTimer, if there is one.
      // The user may be navigating away from the inspector, but first
      // triggered the inspector's retry mechanism. This makes sure the timer
      // won't suddenly have the inspector show up after the user navigates
      // away.
      var timer = this.get('inspectorRetryTimer');
      if (timer) {
        timer.cancel();
        this.set('inspectorRetries', 0);
      }
      this.state.set('allowInspector', true);
      var state = e.details[0];
      var url = this.state.generateUrl(state);
      this.navigate(url);
    },

    /**
      Handle service deploys by opening up the appropriate inspector.

      @method _onServiceDeployed
      @param {Object} e The event facade.
    */
    _onServiceDeployed: function(e) {
      var activeInspector = this._inspector;
      if (activeInspector && !activeInspector.get('destroyed')) {
        var activeClientId = activeInspector.get('model')
          .get('clientId');
        // Because multiple services can be deployed at once we only want to
        // switch to a deployed inspector if there is currently one open.
        // And we only want to switch to that specific inspector.
        if (activeClientId === e.clientId) {
          this.fire('changeState', {
            sectionA: {
              component: 'inspector',
              metadata: { id: e.serviceName }
            }});
        }
      }
    },

    /**
      Fire a change event on all machine models associated with a service.

      @method _fireMachineChanges
      @param {Object} service The service that the machines are associated with
          via units.
    */
    _fireMachineChanges: function(service) {
      var db = this.get('db'),
          services;
      if (service) {
        services = [service];
      } else {
        services = db.services.toArray();
      }
      // We also need to fire change events for the related machines in order
      // to trigger re-rendering in machine view
      services.forEach(function(service) {
        var changedMachines = [];
        service.get('units').each(function(unit) {
          var machine = unit.machine;
          if (changedMachines.indexOf(machine) < 0) {
            changedMachines.push(machine);
          }
        });
        changedMachines.forEach(function(machineId) {
          db.machines.fire('change', {
            changed: true,
            instance: db.machines.getById(machineId)
          });
        });
      });
    },

    /**
      Handle highlight events for services/units.

      @method _onHighlight
      @param {Object} e The event facade.
    */
    _onHighlight: function(e) {
      var serviceName = e.serviceName,
          db = this.get('db'),
          changedMachines = [];
      var service = db.services.getServiceByName(serviceName);
      service.set('highlight', true);
      db.updateUnitFlags(service, 'highlight');
      // Need to toggle fade off.
      this._onShow({serviceNames: [serviceName]});
      // Unrelated services need to be faded.
      var unrelated = db.findUnrelatedServices(service);
      unrelated.each(function(model) {
        model.set('hide', true);
      });
      db.setMVVisibility(serviceName, true);
    },

    /**
      Handle unhighlight events for services/units.

      @method _onUnhighlight
      @param {Object} e The event facade.
    */
    _onUnhighlight: function(e) {
      var db = this.get('db'),
          serviceName = e.serviceName,
          changedMachines = [];
      var service = db.services.getServiceByName(serviceName);
      service.set('highlight', false);
      db.updateUnitFlags(service, 'highlight');
      // Unrelated services need to be unfaded.
      var unrelated = db.findUnrelatedServices(service);
      unrelated.each(function(model) {
        model.set('hide', false);
      });
      db.setMVVisibility(serviceName, false);
    },

    /**
      Handle fade events for services/units.

      @method _onFade
      @param {Object} e The event facade.
    */
    _onFade: function(e) {
      var serviceNames = e.serviceNames,
          db = this.get('db'),
          service;
      serviceNames.forEach(function(serviceName) {
        service = db.services.getServiceByName(serviceName);
        service.set('fade', true);
        db.updateUnitFlags(service, 'fade');
        // Need to toggle highlight off.
        this._onUnhighlight({serviceName: service.get('name')});
        this._fireMachineChanges(service);
      }, this);
    },

    /**
      Handle show events for services/units.

      @method _onShow
      @param {Object} e The event facade.
    */
    _onShow: function(e) {
      var serviceNames = e.serviceNames,
          db = this.get('db'),
          service;
      serviceNames.forEach(function(serviceName) {
        service = db.services.getServiceByName(serviceName);
        service.set('fade', false);
        db.updateUnitFlags(service, 'fade');
        this._fireMachineChanges(service);
      }, this);
    }
  };

  browser.BrowserEventsExtension = BrowserEventsExtension;

});
<commit_msg>Only unhighlight when the user clicks fade if the service isn't already hidden<commit_after>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2012-2014 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

/**
  Separate browser event handling into its own extension for cleaner
  code and testing.

  @module juju.browser
*/

YUI.add('subapp-browser-events', function(Y) {
  var browser = Y.namespace('juju.browser');

  /**
    Event handling for the browser subapp.

    @method BrowserEventsExtension
  */
  function BrowserEventsExtension() {}

  BrowserEventsExtension.prototype = {
    /**
      Handle changes in state, typically navigation requests.

      @method _onChangeState
      @param {Object} e The event facade.
    */
    _onChangeState: function(e) {
      // Cancel the inspectorRetryTimer, if there is one.
      // The user may be navigating away from the inspector, but first
      // triggered the inspector's retry mechanism. This makes sure the timer
      // won't suddenly have the inspector show up after the user navigates
      // away.
      var timer = this.get('inspectorRetryTimer');
      if (timer) {
        timer.cancel();
        this.set('inspectorRetries', 0);
      }
      this.state.set('allowInspector', true);
      var state = e.details[0];
      var url = this.state.generateUrl(state);
      this.navigate(url);
    },

    /**
      Handle service deploys by opening up the appropriate inspector.

      @method _onServiceDeployed
      @param {Object} e The event facade.
    */
    _onServiceDeployed: function(e) {
      var activeInspector = this._inspector;
      if (activeInspector && !activeInspector.get('destroyed')) {
        var activeClientId = activeInspector.get('model')
          .get('clientId');
        // Because multiple services can be deployed at once we only want to
        // switch to a deployed inspector if there is currently one open.
        // And we only want to switch to that specific inspector.
        if (activeClientId === e.clientId) {
          this.fire('changeState', {
            sectionA: {
              component: 'inspector',
              metadata: { id: e.serviceName }
            }});
        }
      }
    },

    /**
      Fire a change event on all machine models associated with a service.

      @method _fireMachineChanges
      @param {Object} service The service that the machines are associated with
          via units.
    */
    _fireMachineChanges: function(service) {
      var db = this.get('db'),
          services;
      if (service) {
        services = [service];
      } else {
        services = db.services.toArray();
      }
      // We also need to fire change events for the related machines in order
      // to trigger re-rendering in machine view
      services.forEach(function(service) {
        var changedMachines = [];
        service.get('units').each(function(unit) {
          var machine = unit.machine;
          if (changedMachines.indexOf(machine) < 0) {
            changedMachines.push(machine);
          }
        });
        changedMachines.forEach(function(machineId) {
          db.machines.fire('change', {
            changed: true,
            instance: db.machines.getById(machineId)
          });
        });
      });
    },

    /**
      Handle highlight events for services/units.

      @method _onHighlight
      @param {Object} e The event facade.
    */
    _onHighlight: function(e) {
      var serviceName = e.serviceName,
          db = this.get('db'),
          changedMachines = [];
      var service = db.services.getServiceByName(serviceName);
      service.set('highlight', true);
      db.updateUnitFlags(service, 'highlight');
      // Need to toggle fade off.
      this._onShow({serviceNames: [serviceName]});
      // Unrelated services need to be faded.
      var unrelated = db.findUnrelatedServices(service);
      unrelated.each(function(model) {
        model.set('hide', true);
      });
      db.setMVVisibility(serviceName, true);
    },

    /**
      Handle unhighlight events for services/units.

      @method _onUnhighlight
      @param {Object} e The event facade.
    */
    _onUnhighlight: function(e) {
      var db = this.get('db'),
          serviceName = e.serviceName,
          changedMachines = [];
      var service = db.services.getServiceByName(serviceName);
      service.set('highlight', false);
      db.updateUnitFlags(service, 'highlight');
      // Unrelated services need to be unfaded.
      var unrelated = db.findUnrelatedServices(service);
      unrelated.each(function(model) {
        model.set('hide', false);
      });
      db.setMVVisibility(serviceName, false);
    },

    /**
      Handle fade events for services/units.

      @method _onFade
      @param {Object} e The event facade.
    */
    _onFade: function(e) {
      var serviceNames = e.serviceNames,
          db = this.get('db'),
          service;
      serviceNames.forEach(function(serviceName) {
        service = db.services.getServiceByName(serviceName);
        service.set('fade', true);
        db.updateUnitFlags(service, 'fade');
        // Need to toggle highlight off but only if it's not already hidden.
        if (!service.get('hide')) {
          this._onUnhighlight({serviceName: service.get('name')});
          this._fireMachineChanges(service);
        }
      }, this);
    },

    /**
      Handle show events for services/units.

      @method _onShow
      @param {Object} e The event facade.
    */
    _onShow: function(e) {
      var serviceNames = e.serviceNames,
          db = this.get('db'),
          service;
      serviceNames.forEach(function(serviceName) {
        service = db.services.getServiceByName(serviceName);
        service.set('fade', false);
        db.updateUnitFlags(service, 'fade');
        this._fireMachineChanges(service);
      }, this);
    }
  };

  browser.BrowserEventsExtension = BrowserEventsExtension;

});
<|endoftext|>


<commit_before>// Application found and translatable!
$web_link = $(".field-name-field-app-web-link");

$("

Available languages:

{{ translations }}   (Translate this app)

").insertAfter($web_link);
<commit_msg>Support also labs<commit_after>// Application found and translatable!
$web_link = $(".field-name-field-app-web-link");

$("

Available languages:

{{ translations }}   (Translate this app)

").insertAfter($web_link);

$web_link = $(".field-name-field-weblink");

$("

Available languages:

{{ translations }}   (Translate this app)

").insertAfter($web_link);
<|endoftext|>


<commit_before>// ==UserScript==
// @name        ShortCutHelp
// @namespace   stackuserflow
// @version     0.0.1
// @description Adiciona um menu interativo para referenciar um usuario alem de criar um atalho para ultimo referenciado
// @author      Guilherme Lautert
// @match       *://chat.stackoverflow.com/rooms/*
// @match       *://chat.stackexchange.com/rooms/*
// @exclude     *://chat.stackoverflow.com/rooms/info/*
// @exclude     *://chat.stackexchange.com/rooms/info/*
// @grant       none
// ==/UserScript==

(function(doc, $){

    var styleUrl = 'https://raw.githubusercontent.com/stackuserflow/stackoverflow-tampermonkey-greasemonkey/master/assets/sch.css';

    var init = function(){
        this.div = null;
        this.lastUserReport = null;
    }

    init.prototype = {
        init : function(){

            // CREATE DIV TO NAMES
            var div = doc.createElement('div');
            div.className = 'sch content_menu';
            var ul = doc.createElement('ul');
            div.appendChild(ul);
            doc.body.appendChild(div);

            // ADD STYLE
            var style = doc.createElement('style');
            style.rel ="stylesheet";
            style.type ="text/css";
            style.href=styleUrl;

            doc.head.appendChild(style);

            this.div = div;
        },
        addUser : function(userName, userId){
            var name = userName;
            var avatar = this.getUserAvatar(userId);

            var li = doc.createElement('li');
            var img = doc.createElement('img');
            img.src = avatar;
            var span = doc.createElement('span');

            li.appendChild(img);
            li.appendChild(span);

            this.div.appendChild(li);

            this.lastUserReport = userName;
        },
        getUserAvatar : function (userId){
            var li = $('#present-users').find('li[class*="user-'+userId+'"]');
            return li.find('div.avatar img').attr('src');
        },
        checkBox : function(){

            var text = $('.chat-input textarea#input').val();
            var matchs = text.match(/@([a-z]+)/ig);

            for(var i in matchs){
                var match = matchs[i];
                var name = match.substr(1).replace(/([A-Z])/g, ' $1').trim();

                var userId = $('.user-container.monologue').find('.username:contains('+name+')');
                if(userId.length > 0){
                    userId = parseInt(userId.parents('a.signature').attr('class').replace(/\D/g, ''));
                }

                if(typeof userId == 'number'){
                    this.addUser(name, userId);
                }
            }
        },
        addLastUserToBox : function(){
            var text = $('.chat-input textarea#input');
            var content = text.val();
            content += ('@'+this.lastUserReport.replace(/ /g, ''));
            text.val(content);
        }
    }

    var newInit = new init();
    newInit.init();

    $('.chat-input').on('keydown', 'textarea#input', function(e){
        if(e.keyCode == 13){
            newInit.checkBox();
        }
    });

    $('#chat-buttons').on('click', '#sayit-button', function(e){
        newInit.checkBox();
    });

}(document, jQuery))<commit_msg>Fix error create element<commit_after>// ==UserScript==
// @name        ShortCutHelp
// @namespace   stackuserflow
// @version     0.0.1
// @description Adiciona um menu interativo para referenciar um usuario alem de criar um atalho para ultimo referenciado
// @author      Guilherme Lautert
// @match       *://chat.stackoverflow.com/rooms/*
// @match       *://chat.stackexchange.com/rooms/*
// @exclude     *://chat.stackoverflow.com/rooms/info/*
// @exclude     *://chat.stackexchange.com/rooms/info/*
// @grant       none
// ==/UserScript==

(function(doc, $){

    var styleUrl = 'https://raw.githubusercontent.com/stackuserflow/stackoverflow-tampermonkey-greasemonkey/master/assets/sch.css';

    var init = function(){
        this.div = null;
        this.lastUserReport = null;
    }

    init.prototype = {
        init : function(){

            // CREATE DIV TO NAMES
            var div = doc.createElement('div');
            div.className = 'sch content_menu';
            var ul = doc.createElement('ul');
            div.appendChild(ul);
            doc.body.appendChild(div);

            // ADD STYLE
            var style = doc.createElement('link');
            style.rel ="stylesheet";
            style.type ="text/css";
            style.href=styleUrl;

            doc.head.appendChild(style);

            this.div = div;
        },
        addUser : function(userName, userId){
            var name = userName;
            var avatar = this.getUserAvatar(userId);

            var li = doc.createElement('li');
            var img = doc.createElement('img');
            img.src = avatar;
            var span = doc.createElement('span');

            li.appendChild(img);
            li.appendChild(span);

            this.div.appendChild(li);

            this.lastUserReport = userName;
        },
        getUserAvatar : function (userId){
            var li = $('#present-users').find('li[class*="user-'+userId+'"]');
            return li.find('div.avatar img').attr('src');
        },
        checkBox : function(){

            var text = $('.chat-input textarea#input').val();
            var matchs = text.match(/@([a-z]+)/ig);

            for(var i in matchs){
                var match = matchs[i];
                var name = match.substr(1).replace(/([A-Z])/g, ' $1').trim();

                var userId = $('.user-container.monologue').find('.username:contains('+name+')');
                if(userId.length > 0){
                    userId = parseInt(userId.parents('a.signature').attr('class').replace(/\D/g, ''));
                }

                if(typeof userId == 'number'){
                    this.addUser(name, userId);
                }
            }
        },
        addLastUserToBox : function(){
            var text = $('.chat-input textarea#input');
            var content = text.val();
            content += ('@'+this.lastUserReport.replace(/ /g, ''));
            text.val(content);
        }
    }

    var newInit = new init();
    newInit.init();

    $('.chat-input').on('keydown', 'textarea#input', function(e){
        if(e.keyCode == 13){
            newInit.checkBox();
        }
    });

    $('#chat-buttons').on('click', '#sayit-button', function(e){
        newInit.checkBox();
    });

}(document, jQuery))<|endoftext|>


<commit_before>'use strict';
/* global describe */
/* global beforeEach */
/* global it */
/* global $ */

var testUtils = require('../util/testUtils');
testUtils.setupLocale('netsim');
var assert = testUtils.assert;
var netsimTestUtils = require('../util/netsimTestUtils');
var fakeShard = netsimTestUtils.fakeShard;

var NetSimLocalClientNode = require('@cdo/apps/netsim/NetSimLocalClientNode');
var NetSim = require('@cdo/apps/netsim/netsim');
var NetSimWire = require('@cdo/apps/netsim/NetSimWire');
var NetSimRouterNode = require('@cdo/apps/netsim/NetSimRouterNode');
var NetSimVizNode = require('@cdo/apps/netsim/NetSimVizNode');
var NetSimVizWire = require('@cdo/apps/netsim/NetSimVizWire');
var NetSimVizSimulationNode = require('@cdo/apps/netsim/NetSimVizSimulationNode');
var NetSimVizSimulationWire = require('@cdo/apps/netsim/NetSimVizSimulationWire');
var NetSimVisualization = require('@cdo/apps/netsim/NetSimVisualization');

var netsimConstants = require('@cdo/apps/netsim/netsimConstants');
var DnsMode = netsimConstants.DnsMode;

describe("NetSimVisualization", function () {

  var testShard, alphaNode, betaNode, deltaNode, router,
      alphaToRouterWire, betaToRouterWire, deltaToAlphaWire, netSimVis;

  /**
   * Synchronous client creation on shard for test
   * @param {string} displayName
   * @returns {NetSimVizSimulationNode}
   */
  var makeRemoteClient = function (displayName) {
    var newClient;
    NetSimLocalClientNode.create(testShard, displayName, function (e, n) {
      newClient = n;
    });
    assert(newClient !== undefined, "Failed to create a remote client.");
    return new NetSimVizSimulationNode(newClient);
  };

  /**
   * Synchronous router creation on shard for test
   * @returns {NetSimVizSimulationNode}
   */
  var makeRemoteRouter = function () {
    var newRouter;
    NetSimRouterNode.create(testShard, function (e, r) {
      newRouter = r;
    });
    assert(newRouter !== undefined, "Failed to create a remote router.");
    return new NetSimVizSimulationNode(newRouter);
  };

  /**
   * Synchronous wire creation on shard for test
   * @param {number} localNodeID
   * @param {number} remoteNodeID
   * @returns {NetSimVizSimulationWire}
   */
  var makeRemoteWire = function (localVizNode, remoteVizNode, elements) {
    var newWire;
    NetSimWire.create(testShard, localVizNode.getCorrespondingEntityID(), remoteVizNode.getCorrespondingEntityID(), function (e, w) {
      newWire = w;
    });
    assert(newWire !== undefined, "Failed to create a remote wire.");
    return new NetSimVizSimulationWire(newWire, getVizNodeByEntityID_.bind(elements));
  };

  var getVizNodeByEntityID_ = function (_type, id) {
    return this.filter(function(element){
      return element instanceof NetSimVizNode &&
          element.getCorrespondingEntityID &&
          element.getCorrespondingEntityID() === id;
    })[0];
  };

  /**
    * Creates the following test networks with the capitalized N as the
    * vizNode:
    *
    * 1) n -> N = r = n
    *    (two nodes attached to a router, with a third node trying to
    *    connect to one of them)
    *
    * Could (probably should) also create networks that look like this:
    *
    * 1) n -> N = n
    *    (two nodes attached to each other, with a third node trying to
    *    connect to one of them)
    * 2) n -> N <- n
    *    (two nodes trying to connect to a third node)
    */
  beforeEach(function () {
    netsimTestUtils.initializeGlobalsToDefaultValues();
    testShard = fakeShard();

    alphaNode = makeRemoteClient('alpha');
    betaNode = makeRemoteClient('beta');
    deltaNode = makeRemoteClient('delta');
    router = makeRemoteRouter();
    var elements = [alphaNode, betaNode, deltaNode, router];

    alphaToRouterWire = makeRemoteWire(alphaNode, router, elements);
    betaToRouterWire = makeRemoteWire(betaNode, router, elements);
    deltaToAlphaWire = makeRemoteWire(deltaNode, alphaNode, elements);
    elements = elements.concat([alphaToRouterWire, betaToRouterWire, deltaToAlphaWire]);

    // Create an empty NetSim for the runLoop and an svg placeholder so
    // that NetSimVisualization's foreground and background searches
    // work.
    var netsim = new NetSim();
    var svg = $("<svg version=\"1.1\" width=\"298\" height=\"298\" xmlns=\"http://www.w3.org/2000/svg\">" +
        "<g id=\"centered-group\">" +
          "<g id=\"background-group\"></g>" +
          "<g id=\"foreground-group\"></g>" +
        "</g>" +
      "</svg>");
    netSimVis = new NetSimVisualization(svg, netsim.runLoop_);
    netSimVis.elements_ = elements;
    netSimVis.localNode = alphaNode;
  });

  describe("router network with peripheral connection", function () {

    it("correctly retrieves all attached wires", function () {
      var alphaWires = netSimVis.getWiresAttachedToNode(alphaNode);
      assert.sameMembers(alphaWires, [alphaToRouterWire, deltaToAlphaWire]);

      var routerWires = netSimVis.getWiresAttachedToNode(router);
      assert.sameMembers(routerWires, [alphaToRouterWire, betaToRouterWire]);
    });

    it("correctly retrieves all locally attached wires", function () {
      var alphaWires = netSimVis.getLocalWiresAttachedToNode(alphaNode);
      assert.sameMembers(alphaWires, [alphaToRouterWire]);

      var routerWires = netSimVis.getLocalWiresAttachedToNode(router);
      assert.sameMembers(routerWires, []);
    });

    it("correctly retrieves all reciprocated wires", function () {
      var alphaWires = netSimVis.getReciprocatedWiresAttachedToNode(alphaNode);
      assert.sameMembers(alphaWires, [alphaToRouterWire]);

      var betaWires = netSimVis.getReciprocatedWiresAttachedToNode(betaNode);
      assert.sameMembers(betaWires, [betaToRouterWire]);

      var deltaWires = netSimVis.getReciprocatedWiresAttachedToNode(deltaNode);
      assert.sameMembers(deltaWires, []);

      var routerWires = netSimVis.getReciprocatedWiresAttachedToNode(router);
      assert.sameMembers(routerWires, [alphaToRouterWire, betaToRouterWire]);
    });

    it("pulls the correct elements to the foreground", function () {
      netSimVis.pullElementsToForeground();

      // Foreground elements
      assert.isTrue(alphaNode.isForeground);
      assert.isTrue(betaNode.isForeground);
      assert.isTrue(router.isForeground);
      assert.isTrue(alphaToRouterWire.isForeground);
      assert.isTrue(betaToRouterWire.isForeground);

      // background elements
      assert.isFalse(deltaNode.isForeground);
      assert.isFalse(deltaToAlphaWire.isForeground);
    });

  });

  describe ("DNS Mode", function () {

    it ("updates all viznodes when DNS mode changes", function () {
      netSimVis.setDnsMode(DnsMode.AUTOMATIC);
      assert.equal(DnsMode.AUTOMATIC, alphaNode.dnsMode_);
      assert.equal(DnsMode.AUTOMATIC, betaNode.dnsMode_);
      assert.equal(DnsMode.AUTOMATIC, deltaNode.dnsMode_);
      netSimVis.setDnsMode(DnsMode.MANUAL);
      assert.equal(DnsMode.MANUAL, alphaNode.dnsMode_);
      assert.equal(DnsMode.MANUAL, betaNode.dnsMode_);
      assert.equal(DnsMode.MANUAL, deltaNode.dnsMode_);
    });

    it ("creates new viznodes with the current DNS mode", function () {
      netSimVis.setDnsMode(DnsMode.AUTOMATIC);
      var gammaNode = makeRemoteClient('gamma');

      // Synchronous in tests.
      testShard.nodeTable.readAll(function (_, data) {
        netSimVis.onNodeTableChange_(data);
      });
      assert.equal(DnsMode.AUTOMATIC, gammaNode.dnsMode_);
    });

  });

});
<commit_msg>New test to confirm vizwires are created with current encodings, and fix other new test<commit_after>'use strict';
/* global describe */
/* global beforeEach */
/* global it */
/* global $ */

var testUtils = require('../util/testUtils');
testUtils.setupLocale('netsim');
var assert = testUtils.assert;
var netsimTestUtils = require('../util/netsimTestUtils');
var fakeShard = netsimTestUtils.fakeShard;

var NetSimLocalClientNode = require('@cdo/apps/netsim/NetSimLocalClientNode');
var NetSim = require('@cdo/apps/netsim/netsim');
var NetSimWire = require('@cdo/apps/netsim/NetSimWire');
var NetSimRouterNode = require('@cdo/apps/netsim/NetSimRouterNode');
var NetSimVizNode = require('@cdo/apps/netsim/NetSimVizNode');
var NetSimVizWire = require('@cdo/apps/netsim/NetSimVizWire');
var NetSimVizSimulationNode = require('@cdo/apps/netsim/NetSimVizSimulationNode');
var NetSimVizSimulationWire = require('@cdo/apps/netsim/NetSimVizSimulationWire');
var NetSimVisualization = require('@cdo/apps/netsim/NetSimVisualization');

var netsimConstants = require('@cdo/apps/netsim/netsimConstants');
var DnsMode = netsimConstants.DnsMode;
var EncodingType = netsimConstants.EncodingType;

describe("NetSimVisualization", function () {

  var testShard, alphaNode, betaNode, deltaNode, router,
      alphaToRouterWire, betaToRouterWire, deltaToAlphaWire, netSimVis;

  /**
   * Synchronous client creation on shard for test
   * @param {string} displayName
   * @returns {NetSimVizSimulationNode}
   */
  var makeRemoteClient = function (displayName) {
    var newClient;
    NetSimLocalClientNode.create(testShard, displayName, function (e, n) {
      newClient = n;
    });
    assert(newClient !== undefined, "Failed to create a remote client.");
    return new NetSimVizSimulationNode(newClient);
  };

  /**
   * Synchronous router creation on shard for test
   * @returns {NetSimVizSimulationNode}
   */
  var makeRemoteRouter = function () {
    var newRouter;
    NetSimRouterNode.create(testShard, function (e, r) {
      newRouter = r;
    });
    assert(newRouter !== undefined, "Failed to create a remote router.");
    return new NetSimVizSimulationNode(newRouter);
  };

  /**
   * Synchronous wire creation on shard for test
   * @param {number} localNodeID
   * @param {number} remoteNodeID
   * @returns {NetSimVizSimulationWire}
   */
  var makeRemoteWire = function (localVizNode, remoteVizNode, elements) {
    var newWire;
    NetSimWire.create(testShard, localVizNode.getCorrespondingEntityID(), remoteVizNode.getCorrespondingEntityID(), function (e, w) {
      newWire = w;
    });
    assert(newWire !== undefined, "Failed to create a remote wire.");
    return new NetSimVizSimulationWire(newWire, getVizNodeByEntityID_.bind(elements));
  };

  var getVizNodeByEntityID_ = function (_type, id) {
    return this.filter(function(element){
      return element instanceof NetSimVizNode &&
          element.getCorrespondingEntityID &&
          element.getCorrespondingEntityID() === id;
    })[0];
  };

  /**
    * Creates the following test networks with the capitalized N as the
    * vizNode:
    *
    * 1) n -> N = r = n
    *    (two nodes attached to a router, with a third node trying to
    *    connect to one of them)
    *
    * Could (probably should) also create networks that look like this:
    *
    * 1) n -> N = n
    *    (two nodes attached to each other, with a third node trying to
    *    connect to one of them)
    * 2) n -> N <- n
    *    (two nodes trying to connect to a third node)
    */
  beforeEach(function () {
    netsimTestUtils.initializeGlobalsToDefaultValues();
    testShard = fakeShard();

    alphaNode = makeRemoteClient('alpha');
    betaNode = makeRemoteClient('beta');
    deltaNode = makeRemoteClient('delta');
    router = makeRemoteRouter();
    var elements = [alphaNode, betaNode, deltaNode, router];

    alphaToRouterWire = makeRemoteWire(alphaNode, router, elements);
    betaToRouterWire = makeRemoteWire(betaNode, router, elements);
    deltaToAlphaWire = makeRemoteWire(deltaNode, alphaNode, elements);
    elements = elements.concat([alphaToRouterWire, betaToRouterWire, deltaToAlphaWire]);

    // Create an empty NetSim for the runLoop and an svg placeholder so
    // that NetSimVisualization's foreground and background searches
    // work.
    var netsim = new NetSim();
    var svg = $("<svg version=\"1.1\" width=\"298\" height=\"298\" xmlns=\"http://www.w3.org/2000/svg\">" +
        "<g id=\"centered-group\">" +
          "<g id=\"background-group\"></g>" +
          "<g id=\"foreground-group\"></g>" +
        "</g>" +
      "</svg>");
    netSimVis = new NetSimVisualization(svg, netsim.runLoop_);
    netSimVis.elements_ = elements;
    netSimVis.localNode = alphaNode;
  });

  describe("router network with peripheral connection", function () {

    it("correctly retrieves all attached wires", function () {
      var alphaWires = netSimVis.getWiresAttachedToNode(alphaNode);
      assert.sameMembers(alphaWires, [alphaToRouterWire, deltaToAlphaWire]);

      var routerWires = netSimVis.getWiresAttachedToNode(router);
      assert.sameMembers(routerWires, [alphaToRouterWire, betaToRouterWire]);
    });

    it("correctly retrieves all locally attached wires", function () {
      var alphaWires = netSimVis.getLocalWiresAttachedToNode(alphaNode);
      assert.sameMembers(alphaWires, [alphaToRouterWire]);

      var routerWires = netSimVis.getLocalWiresAttachedToNode(router);
      assert.sameMembers(routerWires, []);
    });

    it("correctly retrieves all reciprocated wires", function () {
      var alphaWires = netSimVis.getReciprocatedWiresAttachedToNode(alphaNode);
      assert.sameMembers(alphaWires, [alphaToRouterWire]);

      var betaWires = netSimVis.getReciprocatedWiresAttachedToNode(betaNode);
      assert.sameMembers(betaWires, [betaToRouterWire]);

      var deltaWires = netSimVis.getReciprocatedWiresAttachedToNode(deltaNode);
      assert.sameMembers(deltaWires, []);

      var routerWires = netSimVis.getReciprocatedWiresAttachedToNode(router);
      assert.sameMembers(routerWires, [alphaToRouterWire, betaToRouterWire]);
    });

    it("pulls the correct elements to the foreground", function () {
      netSimVis.pullElementsToForeground();

      // Foreground elements
      assert.isTrue(alphaNode.isForeground);
      assert.isTrue(betaNode.isForeground);
      assert.isTrue(router.isForeground);
      assert.isTrue(alphaToRouterWire.isForeground);
      assert.isTrue(betaToRouterWire.isForeground);

      // background elements
      assert.isFalse(deltaNode.isForeground);
      assert.isFalse(deltaToAlphaWire.isForeground);
    });

  });

  describe ("DNS Mode", function () {

    it ("updates all viznodes when DNS mode changes", function () {
      netSimVis.setDnsMode(DnsMode.AUTOMATIC);
      assert.equal(DnsMode.AUTOMATIC, alphaNode.dnsMode_);
      assert.equal(DnsMode.AUTOMATIC, betaNode.dnsMode_);
      assert.equal(DnsMode.AUTOMATIC, deltaNode.dnsMode_);

      netSimVis.setDnsMode(DnsMode.MANUAL);
      assert.equal(DnsMode.MANUAL, alphaNode.dnsMode_);
      assert.equal(DnsMode.MANUAL, betaNode.dnsMode_);
      assert.equal(DnsMode.MANUAL, deltaNode.dnsMode_);
    });

    it ("creates new viznodes with the current DNS mode", function () {
      netSimVis.setDnsMode(DnsMode.AUTOMATIC);
      var newNode = makeRemoteClient('gamma');

      // Trigger visualization update, synchronous in tests.
      testShard.nodeTable.readAll(function (_, data) {
        netSimVis.onNodeTableChange_(data);
      });

      // Check that newly created node has correct DNS mode.
      var gammaNode = netSimVis.getElementByEntityID(NetSimVizSimulationNode,
          newNode.getCorrespondingEntityID());
      assert.equal(DnsMode.AUTOMATIC, gammaNode.dnsMode_);
    });

  });

  describe ("Encodings", function () {
    var DECIMAL_ONLY = [EncodingType.DECIMAL];
    var BINARY_AND_ASCII = [EncodingType.BINARY, EncodingType.ASCII];

    it ("updates all vizwires when encodings change", function () {
      netSimVis.setEncodings(DECIMAL_ONLY);
      assert.sameMembers(DECIMAL_ONLY, alphaToRouterWire.encodings_);
      assert.sameMembers(DECIMAL_ONLY, betaToRouterWire.encodings_);
      assert.sameMembers(DECIMAL_ONLY, deltaToAlphaWire.encodings_);

      netSimVis.setEncodings(BINARY_AND_ASCII);
      assert.sameMembers(BINARY_AND_ASCII, alphaToRouterWire.encodings_);
      assert.sameMembers(BINARY_AND_ASCII, betaToRouterWire.encodings_);
      assert.sameMembers(BINARY_AND_ASCII, deltaToAlphaWire.encodings_);
    });

    it ("creates new vizwires with the current encodings", function () {
      netSimVis.setEncodings(DECIMAL_ONLY);

      // Confirm that delta has no reciprocal wires.
      var oldWires = netSimVis.getReciprocatedWiresAttachedToNode(deltaNode);
      assert.equal(0, oldWires.length);

      // Connect delta to the router
      makeRemoteWire(deltaNode, router, [deltaNode, router]);

      // Trigger visualization update, synchronous in tests.
      testShard.wireTable.readAll(function (_, data) {
        netSimVis.onWireTableChange_(data);
      });

      // Check that newly created wire has the encodings we originally set.
      var newWires = netSimVis.getReciprocatedWiresAttachedToNode(deltaNode);
      assert.equal(1, newWires.length);
      assert.sameMembers(DECIMAL_ONLY, newWires[0].encodings_);
    });

  });

});
<|endoftext|>


<commit_before>/** @jsx React.DOM */

'use strict';

var React = require('react');
var ReactCanvas = require('react-canvas');
var Group = ReactCanvas.Group;
var tweenState = require('react-tween-state');
var Text = ReactCanvas.Text;
var FontFace = ReactCanvas.FontFace;
var measureText = ReactCanvas.measureText;
var StarsNum = 30;
var items = [];
var increase = true;
var blinks = [];//starItemIndex
var blinkNum = 3;
var Stars = React.createClass({
  mixins: [tweenState.Mixin],
  getInitialState: function () {
    return {
      starsAlpha:0.3,
      increaseLock:false,
      fStarsPosTop:0,
      fStarsPosLeft:0,
      fStarsAlpha:0
    };
  },
  componentWillMount: function() {
    for (var i = 0; i < StarsNum; i++) {
      var titleStyle = this.getTitleStyle();
      items.push(this.renderStar('blink'+i, titleStyle));
    }
    // this.fallingLock=false;
  },
  changeAlpha : function(){
    var _a = this.state.starsAlpha;
    var _step = 0.1;
    var _lock = true;
    if(_a >= 0.9 && increase){
      increase = !increase;
    }else if(_a <= 0.2 && !increase){
      increase = !increase;
      _lock = false;
    }
    var _newValue = increase?_a+_step:_a-_step;
    console.log('This is stars call setState');
    // this.setState({starsAlpha:_newValue,increaseLock:_lock});
    //待检测是否有重复
    // this._pendingAnimationFrame = requestAnimationFrame(this.changeAlpha);
    this.blinkLoop = setTimeout(this.changeAlpha,40);
    this.regStop();
  },
  regStop:function(){
    var self = this;
    setTimeout(function() {
      self.stopAni();
    }, 50000);
  },
  stopAni:function(){
    // cancelAnimationFrame(this._pendingAnimationFrame);
    clearTimeout(this.blinkLoop)
    items = [];
  },
  componentWillUnmount:function(){
    this.stopAni();
    items=[];
  },
  componentDidMount: function() {
    this.firstTime = true;
  },
  componentDidUpdate:function(){
    if (this.props.scrollTop == 0 && this.firstTime == true && this.props.ANIMATIONON) {
      this.firstTime = false;
      this.falling();
    }
  },
  render: function() {
    if(this.props.scrollTop!==0){
      this.stopAni();
    }
    console.log('this is Stars rendering',this.state);
    var _a = this.state.starsAlpha;
    if(items.length != 0){
      if (!this.state.increaseLock) {
        blinks = [];
        for (var i = 0; i < blinkNum; i++) {

          blinks.push(items[Math.floor(Math.random() * StarsNum)]);
        }
      }
      blinks.map(function(star) {
        star.props.style.alpha = _a;
      });
    }
    return (
      <Group style={this.getTextGroupStyle()}>
        {items}
      </Group>
    );
  },
  renderStar : function (index,titleStyle) {
    return (
      <Text style = {titleStyle} key={index} > . < /Text>
    );
  },

  // Styles
  // ======

  getTitleStyle: function() {
    var size = Math.ceil(Math.random()*2);
    return {
      alpha:this.state.starsAlpha,
      backgroundColor:'#fff',
      shadowColor: '#999',
      shadowBlur:20,
      borderRadius:size*2,//size/2
      left: 50*Math.random()*10,
      width: size,
      height: size,
      fontSize: size,
      lineHeight: size,
      top: 50*Math.random()*10,
      color: '#ff0',
      fontFace: FontFace('Avenir Next Condensed, Helvetica, sans-serif', null, {
        weight: 400
      })
    };
  },
  getTextGroupStyle: function () {
    // var imageHeight = this.getImageHeight();
    var translateY = 0;
    // var alphaMultiplier = (this.props.scrollTop <= 0) ? -TEXT_ALPHA_SPEED_OUT_MULTIPLIER : TEXT_ALPHA_SPEED_IN_MULTIPLIER;
    // var alpha = 1 - (this.props.scrollTop / this.props.height) * alphaMultiplier;
    // alpha = Math.min(Math.max(alpha, 0), 1);
    // translateY = -this.props.scrollTop * TEXT_SCROLL_SPEED_MULTIPLIER;
    return {
      width: this.props.width,
      height: this.props.height,
      top: 0,
      left: 0,
      alpha: 1,
      translateY: translateY,
      zIndex: 2
    };
  }
});

module.exports = Stars;<commit_msg>fix a wrong function<commit_after>/** @jsx React.DOM */

'use strict';

var React = require('react');
var ReactCanvas = require('react-canvas');
var Group = ReactCanvas.Group;
var tweenState = require('react-tween-state');
var Text = ReactCanvas.Text;
var FontFace = ReactCanvas.FontFace;
var measureText = ReactCanvas.measureText;
var StarsNum = 30;
var items = [];
var increase = true;
var blinks = [];//starItemIndex
var blinkNum = 3;
var Stars = React.createClass({
  mixins: [tweenState.Mixin],
  getInitialState: function () {
    return {
      starsAlpha:0.3,
      increaseLock:false,
      fStarsPosTop:0,
      fStarsPosLeft:0,
      fStarsAlpha:0
    };
  },
  componentWillMount: function() {
    for (var i = 0; i < StarsNum; i++) {
      var titleStyle = this.getTitleStyle();
      items.push(this.renderStar('blink'+i, titleStyle));
    }
    // this.fallingLock=false;
  },
  changeAlpha : function(){
    var _a = this.state.starsAlpha;
    var _step = 0.1;
    var _lock = true;
    if(_a >= 0.9 && increase){
      increase = !increase;
    }else if(_a <= 0.2 && !increase){
      increase = !increase;
      _lock = false;
    }
    var _newValue = increase?_a+_step:_a-_step;
    console.log('This is stars call setState');
    // this.setState({starsAlpha:_newValue,increaseLock:_lock});
    //待检测是否有重复
    // this._pendingAnimationFrame = requestAnimationFrame(this.changeAlpha);
    this.blinkLoop = setTimeout(this.changeAlpha,40);
    this.regStop();
  },
  regStop:function(){
    var self = this;
    setTimeout(function() {
      self.stopAni();
    }, 50000);
  },
  stopAni:function(){
    // cancelAnimationFrame(this._pendingAnimationFrame);
    clearTimeout(this.blinkLoop)
    items = [];
  },
  componentWillUnmount:function(){
    this.stopAni();
    items=[];
  },
  componentDidMount: function() {
    this.firstTime = true;
  },
  componentDidUpdate:function(){
    if (this.props.scrollTop == 0 && this.firstTime == true && this.props.ANIMATIONON) {
      this.firstTime = false;
      this.changeAlpha();
    }
  },
  render: function() {
    if(this.props.scrollTop!==0){
      this.stopAni();
    }
    console.log('this is Stars rendering',this.state);
    var _a = this.state.starsAlpha;
    if(items.length != 0){
      if (!this.state.increaseLock) {
        blinks = [];
        for (var i = 0; i < blinkNum; i++) {

          blinks.push(items[Math.floor(Math.random() * StarsNum)]);
        }
      }
      blinks.map(function(star) {
        star.props.style.alpha = _a;
      });
    }
    return (
      <Group style={this.getTextGroupStyle()}>
        {items}
      </Group>
    );
  },
  renderStar : function (index,titleStyle) {
    return (
      <Text style = {titleStyle} key={index} > . < /Text>
    );
  },

  // Styles
  // ======

  getTitleStyle: function() {
    var size = Math.ceil(Math.random()*2);
    return {
      alpha:this.state.starsAlpha,
      backgroundColor:'#fff',
      shadowColor: '#999',
      shadowBlur:20,
      borderRadius:size*2,//size/2
      left: 50*Math.random()*10,
      width: size,
      height: size,
      fontSize: size,
      lineHeight: size,
      top: 50*Math.random()*10,
      color: '#ff0',
      fontFace: FontFace('Avenir Next Condensed, Helvetica, sans-serif', null, {
        weight: 400
      })
    };
  },
  getTextGroupStyle: function () {
    // var imageHeight = this.getImageHeight();
    var translateY = 0;
    // var alphaMultiplier = (this.props.scrollTop <= 0) ? -TEXT_ALPHA_SPEED_OUT_MULTIPLIER : TEXT_ALPHA_SPEED_IN_MULTIPLIER;
    // var alpha = 1 - (this.props.scrollTop / this.props.height) * alphaMultiplier;
    // alpha = Math.min(Math.max(alpha, 0), 1);
    // translateY = -this.props.scrollTop * TEXT_SCROLL_SPEED_MULTIPLIER;
    return {
      width: this.props.width,
      height: this.props.height,
      top: 0,
      left: 0,
      alpha: 1,
      translateY: translateY,
      zIndex: 2
    };
  }
});

module.exports = Stars;<|endoftext|>


<commit_before>//Set up the click event for the button
document.addEventListener("DOMContentLoaded", function(){
  //Get the button and add the listener to update the post count
  document.getElementById("button").addEventListener("click", update);
});
//Function called each time the check button is clicked
function update(){
  //Figure out how many posts the user has made today
  getPostsToday(function(count){
    //...and subtract that from 250 (post limit), and display it
    document.getElementById("count").innerHTML = 250 - count;
  });
}
//Function for a lot of the payload logic
function getPostsToday(input){
  //Set up the function on first call
  if(typeof input === "function"){
    //When input is a function, it will be the first time the function will have been called, so there's guaranteed to be no first post found yet
    getPostsToday.found = false;
    //Store the input to call when we're really done
    getPostsToday.callback = input;
    //Initialize an array static variable to hold all the posts
    getPostsToday.posts = [];
    //Initialize the search offset to 0, so we're starting with the most recent
    getPostsToday.searchOffset = 0;
  }
  //If it's an object returned by tumblr's API, then we need to analyze it
  else if(typeof input === "object"){
    //Figure out when midnight today is
    getPostsToday.midnight = new Date();
    getPostsToday.midnight.setHours(0, 0, 0, 0);
    //Serialize the response into a JavaScript object
    var data = JSON.parse(this.response);
    console.log(data);
    console.log(getPostsToday.searchOffset);
    getPostsToday.found = true;
    getPostsToday.callback();
    return;
  }
  //We only want to continue if the first post hasn't been found yet
  if(!getPostsToday.found){
    //Create an API call to tumblr to get post data
    var request = new XMLHttpRequest();
    //Set the callback to recursively call this function
    request.onload = getPostsToday;
    //Make sure tumblr recognizes the MIME
    request.overrideMimeType("application/json; charset=utf8");
    //Start the interaction with tumblr's servers, and make it asynchronous
    request.open("GET", "http://api.tumblr.com/v2/blog/themanpagesoflife.tumblr.com/posts?api_key=" + oauth + "&offset=" + getPostsToday.searchOffset.toString(), true);
    //Ask for the API data
    request.send();
    //Increment the offset by 20 for the next call
    getPostsToday.searchOffset += 20;
  }
}<commit_msg>Got extension working, for my blog<commit_after>//Set up the click event for the button
document.addEventListener("DOMContentLoaded", function(){
  //Get the button and add the listener to update the post count
  document.getElementById("button").addEventListener("click", update);
});
//Function called each time the check button is clicked
function update(){
  //Figure out how many posts the user has made today
  getPostsToday(function(count){
    //...and subtract that from 250 (post limit), and display it
    document.getElementById("count").innerHTML = 250 - count;
  });
}
//Function for a lot of the payload logic
function getPostsToday(input){
  //Set up the function on first call
  if(typeof input === "function"){
    //When input is a function, it will be the first time the function will have been called, so there's guaranteed to be no first post found yet
    getPostsToday.found = false;
    //Store the input to call when we're really done
    getPostsToday.callback = input;
    //Initialize an array static variable to hold all the posts
    getPostsToday.posts = [];
    //Initialize the search offset to 0, so we're starting with the most recent
    getPostsToday.searchOffset = 0;
  }
  //If it's an object returned by tumblr's API, then we need to analyze it
  else if(typeof input === "object"){
    //Figure out when midnight today is
    var midnight = new Date();
    midnight.setHours(0, 0, 0, 0);
    //Serialize the response into a JavaScript object
    var data = JSON.parse(this.response);
    for(var i = 0; i < data.response.posts.length; i++){
      //Check if the post was posted today
      if((data.response.posts[i].timestamp * 1000) >= midnight.getTime()){
        //If it was, append it to the array storing such posts
        getPostsToday.posts.push(data.response.posts[i]);
      }
      else{
        //Otherwise, say we've found our limit
        getPostsToday.found = true;
      }
    }
    //Increment the offset by the number of posts in this call, for the next call
    getPostsToday.searchOffset += data.response.posts.length;
  }
  //We only want to continue if the first post hasn't been found yet
  if(!getPostsToday.found){
    //Create an API call to tumblr to get post data
    var request = new XMLHttpRequest();
    //Set the callback to recursively call this function
    request.onload = getPostsToday;
    //Make sure tumblr recognizes the MIME
    request.overrideMimeType("application/json; charset=utf8");
    //Start the interaction with tumblr's servers, and make it asynchronous
    request.open("GET", "http://api.tumblr.com/v2/blog/themanpagesoflife.tumblr.com/posts?api_key=" + oauth + "&offset=" + getPostsToday.searchOffset.toString(), true);
    //Ask for the API data
    request.send();
  }
  //If the most recent post has been found...
  else{
    //Call the callback function, and tell it how many posts there were today
    getPostsToday.callback(getPostsToday.posts.length);
  }
}<|endoftext|>


<commit_before>/**
 * ModulesList component.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import classnames from 'classnames';

/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Link from './Link';
import ModuleIcon from './ModuleIcon';
import ModuleSettingsWarning from './legacy-notifications/module-settings-warning';
import Data from 'googlesitekit-data';
import { CORE_MODULES } from '../googlesitekit/modules/datastore/constants';
const { useSelect } = Data;

const ModulesListItem = ( { module, handleSetupModule } ) => {
	const { slug, name, connected, active } = module;
	const setupComplete = connected && active;

	const canActivateModule = useSelect( ( select ) =>
		select( CORE_MODULES ).canActivateModule( slug )
	);

	return (
		<div
			className={ classnames(
				'googlesitekit-modules-list__module',
				`googlesitekit-modules-list__module--${ slug }`,
				{
					'googlesitekit-settings-connect-module--disabled': ! canActivateModule,
				}
			) }
		>

					<ModuleIcon slug={ slug } />

					{ name }

			<ModuleSettingsWarning slug={ slug } context="modules-list" />
			{ setupComplete && (

					{ __( 'Connected', 'google-site-kit' ) }

			) }
			{ ! setupComplete && (
				<Link
					onClick={ () => handleSetupModule( slug ) }
					arrow
					small
					inherit
					disabled={ ! canActivateModule }
				>
					{ __( 'Connect Service', 'google-site-kit' ) }
				</Link>
			) }

	);
};

export default ModulesListItem;
<commit_msg>Update description in file header.<commit_after>/**
 * ModulesListItem component.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import classnames from 'classnames';

/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Link from './Link';
import ModuleIcon from './ModuleIcon';
import ModuleSettingsWarning from './legacy-notifications/module-settings-warning';
import Data from 'googlesitekit-data';
import { CORE_MODULES } from '../googlesitekit/modules/datastore/constants';
const { useSelect } = Data;

const ModulesListItem = ( { module, handleSetupModule } ) => {
	const { slug, name, connected, active } = module;
	const setupComplete = connected && active;

	const canActivateModule = useSelect( ( select ) =>
		select( CORE_MODULES ).canActivateModule( slug )
	);

	return (
		<div
			className={ classnames(
				'googlesitekit-modules-list__module',
				`googlesitekit-modules-list__module--${ slug }`,
				{
					'googlesitekit-settings-connect-module--disabled': ! canActivateModule,
				}
			) }
		>

					<ModuleIcon slug={ slug } />

					{ name }

			<ModuleSettingsWarning slug={ slug } context="modules-list" />
			{ setupComplete && (

					{ __( 'Connected', 'google-site-kit' ) }

			) }
			{ ! setupComplete && (
				<Link
					onClick={ () => handleSetupModule( slug ) }
					arrow
					small
					inherit
					disabled={ ! canActivateModule }
				>
					{ __( 'Connect Service', 'google-site-kit' ) }
				</Link>
			) }

	);
};

export default ModulesListItem;
<|endoftext|>


<commit_before>$(document).ready(function() {
	$('#reservation-table').DataTable({});
});

$('.btn-cancel').on('click', function() {
	var button = $(this);
	var id = button.data('rev-id');
	if (confirm('Are you sure to cancel this reservation?')) {
		$.post(reservationCancelUrl, {id:id}, function(data) {
			if (data['result']) {
				button.hide();
				$('[data-reservation="'+id+'"]').find('.status').text(data['status']);
				successMessage(data['message']);
			} else {
				errorMessage(data['message']);
			}
		}, 'JSON');
	}
});

$('.btn-view').on('click', function() {
	var id = $(this).data('rev-id');
	$.post(reservationDetailUrl, {id:id}, function(data) {
		if (data['result']) {
			$('#reservation-modal').find('.modal-body').html(data['view']);
			$('#reservation-modal').modal('show');
		} else {
			errorMessage(data['message']);
		}
	}, 'JSON');
});

var resId = 0;

$('.btn-rent').on('click', function() {
	resId = $(this).data('rev-id');
	var balance = $('[data-reservation="'+resId+'"]').find('.total-balance').html();
	var amount = $('[data-reservation="'+resId+'"]').find('.total-amount').html();
	if (parseFloat(balance) < parseFloat(amount)) {
		proceedPay('half');
	} else {
		$('#confirm-modal').modal('show');
	}
});

$('.btn-confirm').on('click', function() {
	var type = $(this).data('payment-type');
	if (type == 'full' || type == 'half') {
		proceedPay(type);
	} else {
		errorMessage('Invalid payment type');
	}
});

function proceedPay(type) {
	successMessage('Please wait while connecting to paypal');
	$.post(rentUrl, {id: resId, type: type}, function(data) {
		if (data['result']) {
			if (data['paypal']['result']) {
				$('#paykey').val(data['paypal']['packet']['payKey']);
				$('#btn-pay').click();
			} else {
				errorMessage(data['paypal']['message']);
			}
		} else {
			errorMessage(data['message']);
		}
	}, 'JSON');
}

function closePaypal()  {
	dgFlow.closeFlow();
	top.close();
	location.reload();
}<commit_msg>Add script for btn-payment<commit_after>$(document).ready(function() {
	$('#reservation-table').DataTable({});
});

$('.btn-cancel').on('click', function() {
	var button = $(this);
	var id = button.data('rev-id');
	if (confirm('Are you sure to cancel this reservation?')) {
		$.post(reservationCancelUrl, {id:id}, function(data) {
			if (data['result']) {
				button.hide();
				$('[data-reservation="'+id+'"]').find('.status').text(data['status']);
				successMessage(data['message']);
			} else {
				errorMessage(data['message']);
			}
		}, 'JSON');
	}
});

$('.btn-view').on('click', function() {
	var id = $(this).data('rev-id');
	$.post(reservationDetailUrl, {id:id}, function(data) {
		if (data['result']) {
			$('#reservation-modal').find('.modal-body').html(data['view']);
			$('#reservation-modal').modal('show');
		} else {
			errorMessage(data['message']);
		}
	}, 'JSON');
});

var resId = 0;

$('.btn-rent').on('click', function() {
	resId = $(this).data('rev-id');
	var balance = $('[data-reservation="'+resId+'"]').find('.total-balance').html();
	var amount = $('[data-reservation="'+resId+'"]').find('.total-amount').html();
	if (parseFloat(balance) < parseFloat(amount)) {
		proceedPay('half');
	} else {
		$('#confirm-modal').modal('show');
	}
});

$('.btn-confirm').on('click', function() {
	var type = $(this).data('payment-type');
	if (type == 'full' || type == 'half') {
		proceedPay(type);
	} else {
		errorMessage('Invalid payment type');
	}
});

$('.btn-payment').on('click', function() {
	resId = $(this).data('rev-id');
	$.post(paymentUrl, {id: resId}, function(data) {
		if (data['result']) {
			$('#payments-modal').find('.modal-body').html(data['view']);
			$('#payments-modal').modal('show');
		} else {
			errorMessage(data['message']);
		}
	}, 'JSON');
});

function proceedPay(type) {
	successMessage('Please wait while connecting to paypal');
	$.post(rentUrl, {id: resId, type: type}, function(data) {
		if (data['result']) {
			if (data['paypal']['result']) {
				$('#paykey').val(data['paypal']['packet']['payKey']);
				$('#btn-pay').click();
			} else {
				errorMessage(data['paypal']['message']);
			}
		} else {
			errorMessage(data['message']);
		}
	}, 'JSON');
}

function closePaypal()  {
	dgFlow.closeFlow();
	top.close();
	location.reload();
}<|endoftext|>


<commit_before>import $ from 'jquery';
import utils from 'bigcommerce/stencil-utils';
import _ from 'lodash';
import {insertStateHiddenField} from './form-utils';

/**
 * If there are no options from bcapp, a text field will be sent. This will create a select element to hold options after the remote request.
 * @returns {jQuery|HTMLElement}
 */
function makeStateRequired(stateElement, context) {
    let attrs,
        $newElement,
        $hiddenInput;

    attrs = _.transform(stateElement.prop('attributes'), (result, item) => {
        result[item.name] = item.value;
        return result;
    });

    let replacementAttributes = {
        id: attrs.id,
        'data-label': attrs['data-label'],
        class: 'form-select',
        name: attrs.name,
        'data-field-type': attrs['data-field-type']
    };

    stateElement.replaceWith($('<select></select>', replacementAttributes));

    $newElement = $('[data-field-type="State"]');
    $hiddenInput = $('[name*="FormFieldIsText"]');

    if ($hiddenInput.length !== 0) {
        $hiddenInput.remove();
    }

    if ($newElement.prev().find('small').length === 0) {

        // String is injected from localizer
        $newElement.prev().append($('', context.required));
    } else {
        $newElement.prev().find('small').show();
    }

    return $newElement;
}

/**
 * If a country with states is the default, a select will be sent,
 * In this case we need to be able to switch to an input field and hide the required field
 */
function makeStateOptional(stateElement) {
    let attrs,
        $newElement;

    attrs = _.transform(stateElement.prop('attributes'), (result, item) => {
        result[item.name] = item.value;
        return result;
    });

    let replacementAttributes = {
        type: 'text',
        id: attrs.id,
        'data-label': attrs['data-label'],
        class: 'form-input',
        name: attrs.name,
        'data-field-type': attrs['data-field-type']
    };

    stateElement.replaceWith($('<input />', replacementAttributes));

    $newElement = $('[data-field-type="State"]');

    if ($newElement.length !== 0) {
        insertStateHiddenField($newElement);
        $newElement.prev().find('small').hide();
    }

    return $newElement;
}

/**
 * Adds the array of options from the remote request to the newly created select box.
 * @param statesArray
 * @param $selectElement
 */
function addOptions(statesArray, $selectElement) {
    let container = [];
    container.push(`<option value="">${statesArray.prefix}</option>`);
    if (!_.isEmpty($selectElement)) {
        _.each(statesArray.states, (stateObj)  => {
            container.push(`<option value="${stateObj.name}">${stateObj.name}</option>`);
        });
        $selectElement.html(container.join(' '));
    }
}

export default function (stateElement, context, callback) {
    context = context || {};

    $('select[data-field-type="Country"]').on('change', (event) => {
        let countryName = $(event.currentTarget).val();

        if (countryName === '') {
            return;
        }

        utils.api.country.getByName(countryName, (err, response) => {
            let $currentInput;

            if (err) {
                alert(context.state_error);
                callback(err);
            }

            $currentInput = $('[data-field-type="State"]');

            if (!_.isEmpty(response.data.states)) {
                // The element may have been replaced with a select, reselect it
                let $selectElement = makeStateRequired($currentInput, context);
                addOptions(response.data, $selectElement);
                callback(null, $selectElement);

            } else {
                let newElement = makeStateOptional($currentInput, context);
                callback(null, newElement);
            }
        })
    });
}
<commit_msg>Add return to callback in error state.<commit_after>import $ from 'jquery';
import utils from 'bigcommerce/stencil-utils';
import _ from 'lodash';
import {insertStateHiddenField} from './form-utils';

/**
 * If there are no options from bcapp, a text field will be sent. This will create a select element to hold options after the remote request.
 * @returns {jQuery|HTMLElement}
 */
function makeStateRequired(stateElement, context) {
    let attrs,
        $newElement,
        $hiddenInput;

    attrs = _.transform(stateElement.prop('attributes'), (result, item) => {
        result[item.name] = item.value;
        return result;
    });

    let replacementAttributes = {
        id: attrs.id,
        'data-label': attrs['data-label'],
        class: 'form-select',
        name: attrs.name,
        'data-field-type': attrs['data-field-type']
    };

    stateElement.replaceWith($('<select></select>', replacementAttributes));

    $newElement = $('[data-field-type="State"]');
    $hiddenInput = $('[name*="FormFieldIsText"]');

    if ($hiddenInput.length !== 0) {
        $hiddenInput.remove();
    }

    if ($newElement.prev().find('small').length === 0) {

        // String is injected from localizer
        $newElement.prev().append($('', context.required));
    } else {
        $newElement.prev().find('small').show();
    }

    return $newElement;
}

/**
 * If a country with states is the default, a select will be sent,
 * In this case we need to be able to switch to an input field and hide the required field
 */
function makeStateOptional(stateElement) {
    let attrs,
        $newElement;

    attrs = _.transform(stateElement.prop('attributes'), (result, item) => {
        result[item.name] = item.value;
        return result;
    });

    let replacementAttributes = {
        type: 'text',
        id: attrs.id,
        'data-label': attrs['data-label'],
        class: 'form-input',
        name: attrs.name,
        'data-field-type': attrs['data-field-type']
    };

    stateElement.replaceWith($('<input />', replacementAttributes));

    $newElement = $('[data-field-type="State"]');

    if ($newElement.length !== 0) {
        insertStateHiddenField($newElement);
        $newElement.prev().find('small').hide();
    }

    return $newElement;
}

/**
 * Adds the array of options from the remote request to the newly created select box.
 * @param statesArray
 * @param $selectElement
 */
function addOptions(statesArray, $selectElement) {
    let container = [];
    container.push(`<option value="">${statesArray.prefix}</option>`);
    if (!_.isEmpty($selectElement)) {
        _.each(statesArray.states, (stateObj)  => {
            container.push(`<option value="${stateObj.name}">${stateObj.name}</option>`);
        });
        $selectElement.html(container.join(' '));
    }
}

export default function (stateElement, context, callback) {
    context = context || {};

    $('select[data-field-type="Country"]').on('change', (event) => {
        let countryName = $(event.currentTarget).val();

        if (countryName === '') {
            return;
        }

        utils.api.country.getByName(countryName, (err, response) => {
            let $currentInput;

            if (err) {
                alert(context.state_error);
                return callback(err);
            }

            $currentInput = $('[data-field-type="State"]');

            if (!_.isEmpty(response.data.states)) {
                // The element may have been replaced with a select, reselect it
                let $selectElement = makeStateRequired($currentInput, context);
                addOptions(response.data, $selectElement);
                callback(null, $selectElement);

            } else {
                let newElement = makeStateOptional($currentInput, context);
                callback(null, newElement);
            }
        })
    });
}
<|endoftext|>


<commit_before>var net = require('net');
var events = require('events');
var util = require('util');

var log = function (in, msg) {
    var date = new Date();
    console.log(Date().toString() + "|" + (in ? "<-" : "->") + "|" + msg;
};

var create = function (prototype, properties) {
    if (typeof properties !== 'object') {
        return Object.create(prototype);
    }

    var props = {};
    Object.keys(properties).forEach(function (key) {
        props[key] = { value: properties[key] };
    });
    return Object.create(prototype, props);
};

var Socket = module.exports = function Socket (network, GenericSocket) {
    GenericSocket = GenericSocket || net.Socket;

    var socket = create(Socket.prototype); // no new needed.
    socket.port = network.port || 6667;
    socket.netname = network.server;
    socket.genericSocket = new GenericSocket();
    socket.connected = false;

    /**
     * @FIXME Do not send last message if not finished
     */
     var onData = function onData (data) {
        data
        .split('\r\n')
        .filter(function (line) { return line !== ''; })
        .filter(function (line) {
            if (line.slice(0, 4) === 'PING') {
                socket.raw(['PONG', line.slice(line.indexOf(':'))]);
                return false;
            }

            return true;
        })
        .forEach(function (line) {
            log(true, line);
            socket.emit('data', line);
        });
    };

    void function readyEvent () {
        var emitWhenReady = function (data) {
            if (Socket.isReady(data)) {
                socket.emit('ready');
            }
        };

        socket.genericSocket.on('data', emitWhenReady);
        socket.on('ready', function remove () {
            socket.genericSocket.removeListener('data', emitWhenReady);
        });
    }();

    socket.genericSocket.once('connect', function () {
        socket.connected = true;
        socket.raw(["NICK", network.nick]);
        socket.raw(["USER", network.user || "user", "8 * :" + network.realname]);
    });

    socket.genericSocket.once('close', function () {
        socket.connected = false;
    });

    socket.genericSocket.on('data', onData);
    socket.genericSocket.setEncoding('ascii');
    socket.genericSocket.setNoDelay();

    return socket;
};

Socket.isReady = function (data) {
    // We are 'ready' when we get a 001 message.
    return data.split('\r\n')
    .filter(function (line) { return line !== ''; })
    .some(function (line) { return line.split(' ')[1] === '001'; });
};

Socket.prototype = create(events.EventEmitter.prototype, {
    connect : function () {
        if (this.isConnected()) {
            return;
        }

        this.genericSocket.connect(this.port, this.netname);
    },

    end : function () {
        if (!this.isConnected()) {
            return;
        }

        this.genericSocket.end();
    },

    raw : function (message) {
        if (!this.connected) {
            return;
        }

        if (util.isArray(message)) {
            message = message.join(" ");
        }

        if (message.indexOf('\n') !== -1) {
            throw new Error('Newline detected in message. Use multiple raws instead.');
        }

        log(false, message);
        this.genericSocket.write(message + '\n', 'ascii');
    },

    isConnected : function () {
        return this.connected;
    },

    getRealName : function () {
        return this._realname;
    }
});
<commit_msg>in is a reserved word<commit_after>var net = require('net');
var events = require('events');
var util = require('util');

var log = function (input, msg) {
    var date = new Date();
    console.log(Date().toString() + "|" + (input ? "<-" : "->") + "|" + msg;
};

var create = function (prototype, properties) {
    if (typeof properties !== 'object') {
        return Object.create(prototype);
    }

    var props = {};
    Object.keys(properties).forEach(function (key) {
        props[key] = { value: properties[key] };
    });
    return Object.create(prototype, props);
};

var Socket = module.exports = function Socket (network, GenericSocket) {
    GenericSocket = GenericSocket || net.Socket;

    var socket = create(Socket.prototype); // no new needed.
    socket.port = network.port || 6667;
    socket.netname = network.server;
    socket.genericSocket = new GenericSocket();
    socket.connected = false;

    /**
     * @FIXME Do not send last message if not finished
     */
     var onData = function onData (data) {
        data
        .split('\r\n')
        .filter(function (line) { return line !== ''; })
        .filter(function (line) {
            if (line.slice(0, 4) === 'PING') {
                socket.raw(['PONG', line.slice(line.indexOf(':'))]);
                return false;
            }

            return true;
        })
        .forEach(function (line) {
            log(true, line);
            socket.emit('data', line);
        });
    };

    void function readyEvent () {
        var emitWhenReady = function (data) {
            if (Socket.isReady(data)) {
                socket.emit('ready');
            }
        };

        socket.genericSocket.on('data', emitWhenReady);
        socket.on('ready', function remove () {
            socket.genericSocket.removeListener('data', emitWhenReady);
        });
    }();

    socket.genericSocket.once('connect', function () {
        socket.connected = true;
        socket.raw(["NICK", network.nick]);
        socket.raw(["USER", network.user || "user", "8 * :" + network.realname]);
    });

    socket.genericSocket.once('close', function () {
        socket.connected = false;
    });

    socket.genericSocket.on('data', onData);
    socket.genericSocket.setEncoding('ascii');
    socket.genericSocket.setNoDelay();

    return socket;
};

Socket.isReady = function (data) {
    // We are 'ready' when we get a 001 message.
    return data.split('\r\n')
    .filter(function (line) { return line !== ''; })
    .some(function (line) { return line.split(' ')[1] === '001'; });
};

Socket.prototype = create(events.EventEmitter.prototype, {
    connect : function () {
        if (this.isConnected()) {
            return;
        }

        this.genericSocket.connect(this.port, this.netname);
    },

    end : function () {
        if (!this.isConnected()) {
            return;
        }

        this.genericSocket.end();
    },

    raw : function (message) {
        if (!this.connected) {
            return;
        }

        if (util.isArray(message)) {
            message = message.join(" ");
        }

        if (message.indexOf('\n') !== -1) {
            throw new Error('Newline detected in message. Use multiple raws instead.');
        }

        log(false, message);
        this.genericSocket.write(message + '\n', 'ascii');
    },

    isConnected : function () {
        return this.connected;
    },

    getRealName : function () {
        return this._realname;
    }
});
<|endoftext|>


<commit_before>/*****************************************************************************/
/*                          Main JS for whileaway                            */
/*****************************************************************************/

$(document).ready(function(){
    // Form UI fixes
/*    $('#keyword').change(function() {
    	option_val = $('#keyword > option:selected').val();
    	$('#keyword-span').html(option_val);
    	$('#keyword').width($('#keyword-span').width());
    });
    $('#keyword').change();*/

    $('#section').change(function() {
    	option_val = $('#section > option:selected').text();
    	$('#section-span').html(option_val);
    	$('#section').width($('#section-span').width());
    });

    $('#section').change();

    $('#date').change(function() {
    	option_val = $('#date > option:selected').val();
    	$('#date-span').html(option_val);
    	$('#date').width($('#date-span').width());
    });

    $('#date').change();

    window.onresize = function() {
    	$('#section').change();
    	$('#date').change();
    	inputWidth();
    }

    function inputWidth() {
    	$('#number-span').html($('#number').val());
    	$('#number').css('width', $('#number-span').width());
    }

    inputWidth();

    $('#number').bind('keyup input paste', inputWidth);

    window.onresize = function() {
    	$('#keyword').change();
    	$('#date').change();
    	inputWidth();
    }

    // Fetching and displaying stories
    getNews();

    // onchange of input fields, call getNews()
    $('#number').bind('keyup input paste', function(){getNews();});
    $('#date').change(function(){getNews();});
    $('#keyword').change(function(){getNews();});
});

function getNews(){
	amount = $('#number').val();
	scope = $('#date option:selected').val();
	section = $('#section option:selected').val();
    // keyword $('#keyword').val()
    keyword = '';

    console.log(section);

	try {
        keyword = $.trim(keyword);
		validate(amount, scope, section, keyword);

        // make asynchronous request
        getGuardianNews(amount, scope, section, keyword);
	} catch (e) {
		alert(e); // To-Do: Error handling
		return;
	}
}

function handleGuardianNews(news){
	str = '
';
	$.each(news, function(index, story) {
		headline = story[0];
		link = story[1];
		date = story[2];
		// summary = story[3];

		// str += '
' + headline + ' (more…, ' + date.f('d MMM yyyy HH:mm') + ')
';
        str += '
';
		str += '' + headline + '';
        str += '

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

<time datetime="' + date.toJSON() + '"> ' + date.f('d MMM yyyy HH:mm') + '</time> | Read more…

'
        str += '
  '
	});
	str += '
';
	$('#headlines').html(str);

    // display summary on headline click
    $('.headline > a').click(function(e){
        e.preventDefault();
        $(this).next('div').toggle(300);
    });
}

function validate(amount, scope, section, keyword) {
	scopes = ['days', 'weeks', 'months'];
	if (scopes.indexOf(scope) < 0) {
		throw 'Invalid scope';
	}

	if (isNaN(amount)) {
		throw 'Invalid amount';
	}
}
<commit_msg>Code cleanup<commit_after>/*****************************************************************************/
/*                          Main JS for whileaway                            */
/*****************************************************************************/

$(document).ready(function(){
    // Form UI fixes

    $('#section').change(function() {
    	option_val = $('#section > option:selected').text();
    	$('#section-span').html(option_val);
    	$('#section').width($('#section-span').width());
    });

    $('#section').change();

    $('#date').change(function() {
    	option_val = $('#date > option:selected').val();
    	$('#date-span').html(option_val);
    	$('#date').width($('#date-span').width());
    });

    $('#date').change();

    window.onresize = function() {
    	$('#section').change();
    	$('#date').change();
    	inputWidth();
    }

    function inputWidth() {
    	$('#number-span').html($('#number').val());
    	$('#number').css('width', $('#number-span').width());
    }

    inputWidth();

    $('#number').bind('keyup input paste', inputWidth);

    window.onresize = function() {
    	$('#keyword').change();
    	$('#date').change();
    	inputWidth();
    }

    // Fetching and displaying stories
    getNews();

    // onchange of input fields, call getNews()
    $('#number').bind('keyup input paste', function(){getNews();});
    $('#date').change(function(){getNews();});
    $('#keyword').change(function(){getNews();});
});

function getNews(){
	amount = $('#number').val();
	scope = $('#date option:selected').val();
	section = $('#section option:selected').val();
    // keyword $('#keyword').val()
    keyword = '';

    console.log(section);

	try {
        keyword = $.trim(keyword);
		validate(amount, scope, section, keyword);

        // make asynchronous request
        getGuardianNews(amount, scope, section, keyword);
	} catch (e) {
		alert(e); // To-Do: Error handling
		return;
	}
}

function handleGuardianNews(news){
	str = '
';
	$.each(news, function(index, story) {
		headline = story[0];
		link = story[1];
		date = story[2];
		// summary = story[3];

		// str += '
' + headline + ' (more…, ' + date.f('d MMM yyyy HH:mm') + ')
';
        str += '
';
		str += '' + headline + '';
        str += '

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

<time datetime="' + date.toJSON() + '"> ' + date.f('d MMM yyyy HH:mm') + '</time> | Read more…

'
        str += '
  '
	});
	str += '
';
	$('#headlines').html(str);

    // display summary on headline click
    $('.headline > a').click(function(e){
        e.preventDefault();
        $(this).next('div').toggle(300);
    });
}

function validate(amount, scope, section, keyword) {
	scopes = ['days', 'weeks', 'months'];
	if (scopes.indexOf(scope) < 0) {
		throw 'Invalid scope';
	}

	if (isNaN(amount)) {
		throw 'Invalid amount';
	}
}
<|endoftext|>