<commit_before>/* jslint node: true, esnext: true */
"use strict";

const llm = require('loglevel-mixin'),
	stm = require('statetransition-mixin');

const actions = stm.prepareActions({
	start: {
		stopped: {
			target: "running",
			during: "starting",
			timeout: 5000
		}
	},
	stop: {
		running: {
			target: "stopped",
			during: "stopping",
			timeout: 5000
		},
		starting: {
			target: "stopped",
			during: "stopping",
			timeout: 5000
		}
	}
});

const BaseService = {

	/**
	 * To be overwritten
	 * Called when the state changes
	 * @param {String} oldState
	 * @param {String} newState
	 */
	stateChanged(oldState, newState) {
			this.trace(level => `${this} transitioned from ${oldState} -> ${newState}`);
		},

		/**
		 * Called when state transition is not allowed
		 * @param {String} action
		 * @return {Promise} rejecting with an Error
		 */
		rejectWrongState(action) {
			return Promise.reject(new Error(`Can't ${action} ${this} in ${this.state} state`));
		},

		/**
		 * Returns the string representation of this step
		 * @return {String} human readable name
		 */
		toString() {
			return this.name;
		},

		log(level, arg) {
			const logevent = {
				"timestamp": Date.now(),
				"level": level,
				"service": this.name,
				"service-state": this.state
			};

			if (typeof arg === 'string') {
				logevent.message = arg;
			} else {
				Object.assign(logevent, arg);
			}
			// TODO
			console.log(logevent);
		}
};

llm.defineLoggerMethods(BaseService, llm.defaultLogLevels);
stm.defineActionMethods(BaseService, actions);

/**
 * Create a new service
 * The initial state is 'stopped'
 * @param {String} name
 * @param {Object} values used to form the service
 * @param {Service} optional base service to use
 * @return {Service} newly created service
 */
exports.createService = function (name, values, baseService) {

	const props = {
		name: {
			value: name
		}
	};

	let logLevel = llm.defaultLogLevels.info;

	for (let key in values) {
		if (key === 'logLevel') {
			logLevel = llm.defaultLogLevels[values[key]] ||  defaultLogLevels.info;
		} else if (key !== 'name') {
			props[key] = {
				value: values[key]
			};
		}
	}

	const service = Object.create(baseService ? baseService : BaseService, props);

	llm.defineLogLevelProperties(service, llm.defaultLogLevels, logLevel);
	stm.defineStateTransitionProperties(service, actions, "stopped");

	return service;
};
<commit_msg>fix: typo when trying to resolve unknown logLevel<commit_after>/* jslint node: true, esnext: true */
"use strict";

const llm = require('loglevel-mixin'),
	stm = require('statetransition-mixin');

const actions = stm.prepareActions({
	start: {
		stopped: {
			target: "running",
			during: "starting",
			timeout: 5000
		}
	},
	stop: {
		running: {
			target: "stopped",
			during: "stopping",
			timeout: 5000
		},
		starting: {
			target: "stopped",
			during: "stopping",
			timeout: 5000
		}
	}
});

const BaseService = {

	/**
	 * To be overwritten
	 * Called when the state changes
	 * @param {String} oldState
	 * @param {String} newState
	 */
	stateChanged(oldState, newState) {
			this.trace(level => `${this} transitioned from ${oldState} -> ${newState}`);
		},

		/**
		 * Called when state transition is not allowed
		 * @param {String} action
		 * @return {Promise} rejecting with an Error
		 */
		rejectWrongState(action) {
			return Promise.reject(new Error(`Can't ${action} ${this} in ${this.state} state`));
		},

		/**
		 * Returns the string representation of this step
		 * @return {String} human readable name
		 */
		toString() {
			return this.name;
		},

		log(level, arg) {
			const logevent = {
				"timestamp": Date.now(),
				"level": level,
				"service": this.name,
				"service-state": this.state
			};

			if (typeof arg === 'string') {
				logevent.message = arg;
			} else {
				Object.assign(logevent, arg);
			}
			// TODO
			console.log(logevent);
		}
};

llm.defineLoggerMethods(BaseService, llm.defaultLogLevels);
stm.defineActionMethods(BaseService, actions);

/**
 * Create a new service
 * The initial state is 'stopped'
 * @param {String} name
 * @param {Object} values used to form the service
 * @param {Service} optional base service to use
 * @return {Service} newly created service
 */
exports.createService = function (name, values, baseService) {

	const props = {
		name: {
			value: name
		}
	};

	let logLevel = llm.defaultLogLevels.info;

	for (let key in values) {
		if (key === 'logLevel') {
			logLevel = llm.defaultLogLevels[values[key]] ||  llm.defaultLogLevels.info;
		} else if (key !== 'name') {
			props[key] = {
				value: values[key]
			};
		}
	}

	const service = Object.create(baseService ? baseService : BaseService, props);

	llm.defineLogLevelProperties(service, llm.defaultLogLevels, logLevel);
	stm.defineStateTransitionProperties(service, actions, "stopped");

	return service;
};
<|endoftext|>


<commit_before>/*
*(c) Copyright 2011 Simone Masiero. Some Rights Reserved.
*This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License
*/

$(
	function () {
	    $(document).keydown(
			function (event) {
			    Typer.addText(event); //Capture the keydown event and call the addText, this is executed on page load
			}
		);
	}
);

var Typer = {
    text: null,
    accessCountimer: null,
    index: 0, // current cursor position
    speed: 2, // speed of the Typer
    file: "", //file, must be setted
    accessCount: 0, //times alt is pressed for Access Granted
    deniedCount: 0, //times caps is pressed for Access Denied
    init: function () {// inizialize Hacker Typer
        accessCountimer = setInterval(function () { Typer.updLstChr(); }, 500); // inizialize timer for blinking cursor
        $.get(Typer.file, function (data) {// get the text file
            Typer.text = data;// save the textfile in Typer.text
        });
    },

    content: function () {
        return $("#console").html();// get console content
    },

    write: function (str) {// append to console content
        $("#console").append(str);
        return false;
    },

    makeAccess: function () {//create Access Granted popUp      FIXME: popup is on top of the page and doesn't show is the page is scrolled
        Typer.hidepop(); // hide all popups
        Typer.accessCount = 0; //reset count
        var ddiv = $("
").html(""); // create new blank div and id "gran"
        ddiv.addClass("accessGranted"); // add class to the div
        ddiv.html("
ACCESS GRANTED
"); // set content of div
        $(document.body).prepend(ddiv); // prepend div to body
        return false;
    },
    makeDenied: function () {//create Access Denied popUp      FIXME: popup is on top of the page and doesn't show is the page is scrolled
        Typer.hidepop(); // hide all popups
        Typer.deniedCount = 0; //reset count
        var ddiv = $("
").html(""); // create new blank div and id "deni"
        ddiv.addClass("accessDenied");// add class to the div
        ddiv.html("
ACCESS DENIED
");// set content of div
        $(document.body).prepend(ddiv);// prepend div to body
        return false;
    },

    hidepop: function () {// remove all existing popups
        $("#deni").remove();
        $("#gran").remove();
    },

    addText: function (key) {//Main function to add the code
        if (key.keyCode == 18) {// key 18 = alt key
            Typer.accessCount++; //increase counter
            if (Typer.accessCount >= 3) {// if it's presed 3 times
                Typer.makeAccess(); // make access popup
            }
        } else if (key.keyCode == 20) {// key 20 = caps lock
            Typer.deniedCount++; // increase counter
            if (Typer.deniedCount >= 3) { // if it's pressed 3 times
                Typer.makeDenied(); // make denied popup
            }
        } else if (key.keyCode == 27) { // key 27 = esc key
            Typer.hidepop(); // hide all popups
        } else if (Typer.text) { // otherway if text is loaded
            var cont = Typer.content(); // get the console content
            if (cont.substring(cont.length - 1, cont.length) == "|") // if the last char is the blinking cursor
                $("#console").html($("#console").html().substring(0, cont.length - 1)); // remove it before adding the text
            if (key.keyCode != 8) { // if key is not backspace
                Typer.index += Typer.speed;	// add to the index the speed
            } else {
                if (Typer.index > 0) // else if index is not less than 0
                    Typer.index -= Typer.speed;//	remove speed for deleting text
            }
            var text = $("
").text(Typer.text.substring(0, Typer.index)).html();// parse the text for stripping html enities
            var rtn = new RegExp("\n", "g"); // newline regex
            var rts = new RegExp("\\s", "g"); // whitespace regex
            var rtt = new RegExp("\\t", "g"); // tab regex
            $("#console").html(text.replace(rtn, "
").replace(rtt, "    ").replace(rts, " "));// replace newline chars with br, tabs with 4 space and blanks with an html blank
            window.scrollBy(0, 50); // scroll to make sure bottom is always visible
        }
        if (key.preventDefault && key.keyCode != 122) { // prevent F11(fullscreen) from being blocked
            key.preventDefault()
        };
        if (key.keyCode != 122) { // otherway prevent keys default behavior
            key.returnValue = false;
        }
    },

    updLstChr: function () { // blinking cursor
        var cont = this.content(); // get console
        if (cont.substring(cont.length - 1, cont.length) == "|") // if last char is the cursor
            $("#console").html($("#console").html().substring(0, cont.length - 1)); // remove it
        else
            this.write("|"); // else write it
    }
}<commit_msg>tab4 -> space2<commit_after>/*
*(c) Copyright 2011 Simone Masiero. Some Rights Reserved.
*This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License
*/

$(
  function () {
    $(document).keydown(
      function (event) {
        Typer.addText(event); //Capture the keydown event and call the addText, this is executed on page load
      }
    );
  }
);

var Typer = {
  text: null,
  accessCountimer: null,
  index: 0, // current cursor position
  speed: 2, // speed of the Typer
  file: "", //file, must be setted
  accessCount: 0, //times alt is pressed for Access Granted
  deniedCount: 0, //times caps is pressed for Access Denied
  init: function () {// inizialize Hacker Typer
    accessCountimer = setInterval(function () { Typer.updLstChr(); }, 500); // inizialize timer for blinking cursor
    $.get(Typer.file, function (data) {// get the text file
      Typer.text = data;// save the textfile in Typer.text
    });
  },

  content: function () {
    return $("#console").html();// get console content
  },

  write: function (str) {// append to console content
    $("#console").append(str);
    return false;
  },

  makeAccess: function () {//create Access Granted popUp      FIXME: popup is on top of the page and doesn't show is the page is scrolled
    Typer.hidepop(); // hide all popups
    Typer.accessCount = 0; //reset count
    var ddiv = $("
").html(""); // create new blank div and id "gran"
    ddiv.addClass("accessGranted"); // add class to the div
    ddiv.html("
ACCESS GRANTED
"); // set content of div
    $(document.body).prepend(ddiv); // prepend div to body
    return false;
  },
  makeDenied: function () {//create Access Denied popUp      FIXME: popup is on top of the page and doesn't show is the page is scrolled
    Typer.hidepop(); // hide all popups
    Typer.deniedCount = 0; //reset count
    var ddiv = $("
").html(""); // create new blank div and id "deni"
    ddiv.addClass("accessDenied");// add class to the div
    ddiv.html("
ACCESS DENIED
");// set content of div
    $(document.body).prepend(ddiv);// prepend div to body
    return false;
  },

  hidepop: function () {// remove all existing popups
    $("#deni").remove();
    $("#gran").remove();
  },

  addText: function (key) {//Main function to add the code
    if (key.keyCode == 18) {// key 18 = alt key
      Typer.accessCount++; //increase counter
      if (Typer.accessCount >= 3) {// if it's presed 3 times
        Typer.makeAccess(); // make access popup
      }
    } else if (key.keyCode == 20) {// key 20 = caps lock
      Typer.deniedCount++; // increase counter
      if (Typer.deniedCount >= 3) { // if it's pressed 3 times
        Typer.makeDenied(); // make denied popup
      }
    } else if (key.keyCode == 27) { // key 27 = esc key
      Typer.hidepop(); // hide all popups
    } else if (Typer.text) { // otherway if text is loaded
      var cont = Typer.content(); // get the console content
      if (cont.substring(cont.length - 1, cont.length) == "|") // if the last char is the blinking cursor
        $("#console").html($("#console").html().substring(0, cont.length - 1)); // remove it before adding the text
      if (key.keyCode != 8) { // if key is not backspace
        Typer.index += Typer.speed; // add to the index the speed
      } else {
        if (Typer.index > 0) // else if index is not less than 0
          Typer.index -= Typer.speed;// remove speed for deleting text
      }
      var text = $("
").text(Typer.text.substring(0, Typer.index)).html();// parse the text for stripping html enities
      var rtn = new RegExp("\n", "g"); // newline regex
      var rts = new RegExp("\\s", "g"); // whitespace regex
      var rtt = new RegExp("\\t", "g"); // tab regex
      $("#console").html(text.replace(rtn, "
").replace(rtt, "    ").replace(rts, " "));// replace newline chars with br, tabs with 4 space and blanks with an html blank
      window.scrollBy(0, 50); // scroll to make sure bottom is always visible
    }
    if (key.preventDefault && key.keyCode != 122) { // prevent F11(fullscreen) from being blocked
      key.preventDefault()
    };
    if (key.keyCode != 122) { // otherway prevent keys default behavior
      key.returnValue = false;
    }
  },

  updLstChr: function () { // blinking cursor
    var cont = this.content(); // get console
    if (cont.substring(cont.length - 1, cont.length) == "|") // if last char is the cursor
      $("#console").html($("#console").html().substring(0, cont.length - 1)); // remove it
    else
      this.write("|"); // else write it
  }
}<|endoftext|>


<commit_before>/*!
 * OS.js - JavaScript Operating System
 *
 * Copyright (c) 2011-2015, Anders Evenrud <andersevenrud@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @licence Simplified BSD License
 */
(function(Application, Window, GUI, Dialogs, Utils, API, VFS) {
  'use strict';

  /////////////////////////////////////////////////////////////////////////////
  // WINDOWS
  /////////////////////////////////////////////////////////////////////////////

  var ApplicationSettingsWindow = function(app, metadata) {
    Window.apply(this, ['ApplicationSettingsWindow', {
      icon: metadata.icon,
      title: metadata.name,
      width: 580,
      height: 450,
      allow_maximize: false,
      allow_resize: false
    }, app]);

    this.$side = null;
    this.$content = null;
    this.$header = null;
    this.modules = {};
    this.settings = {};
  };

  ApplicationSettingsWindow.prototype = Object.create(Window.prototype);

  ApplicationSettingsWindow.prototype.init = function(wmRef, app) {
    var _ = OSjs.Applications.ApplicationSettings._;
    var root = Window.prototype.init.apply(this, arguments);
    var self = this;

    function _createIcon(iter) {
      iter = iter || 'status/gtk-dialog-question.png';
      return OSjs.API.getIcon(iter, null, '32x32');
    }

    var columns = [
      {key: 'name', title: 'name', visible: false},
      {key: 'icon', title: 'Icon', type: 'image', domProperties: {width: 32}},
      {key: 'title', title: 'Title'}
    ];

    this.settings = Utils.cloneObject(wmRef.getSettings());
    delete this.settings.desktopIcons;
    delete this.settings.fullscreen;
    delete this.settings.moveOnResize;

    this.$side = document.createElement('div');
    this.$side.className = 'Side';

    this.$content = document.createElement('div');
    this.$content.className = 'Content';

    this.$header = document.createElement('div');
    this.$header.className = 'Header';

    var sidePanel = this._addGUIElement(new GUI.ListView('SettingsNewSideView', {
      singleClick: true,
      columns: columns,
      onSelect: function(ev, el, item) {
        self.setCategory(item);
      }
    }), this.$side);

    var modules = OSjs.Applications.ApplicationSettings.Modules;
    var rows = [];

    modules.forEach(function(m, i) {
      rows.push({
        name: m.name,
        title: m.title.match(/^[A-Z]*_/) ? API._(m.title) : _(m.title),
        icon: _createIcon(m.icon)
      });
      self.modules[m.name] = m.onCreate(self, self.$content, self.settings);
    });
    sidePanel.setRows(rows);
    sidePanel.render();

    root.appendChild(this.$side);
    root.appendChild(this.$header);
    root.appendChild(this.$content);

    this._addGUIElement(new GUI.Button('SettingsNewSave', {label: API._('LBL_SAVE'), onClick: function() {
      self.applySettings();
    }}), root);

    return root;
  };

  ApplicationSettingsWindow.prototype._inited = function() {
    Window.prototype._inited.apply(this, arguments);

    var sidePanel = this._getGUIElement('SettingsNewSideView');
    if ( sidePanel ) {
      var found = false;
      var set = this._appRef._getArgument('category');
      if ( set ) {
        var modules = OSjs.Applications.ApplicationSettings.Modules;
        modules.forEach(function(m, i) {
          if ( m.name === set ) {
            sidePanel.setSelectedIndex(i);
            found = true;
          }
          return found ? false : true;
        });
      }

      if ( !found ) {
        sidePanel.setSelectedIndex(0);
      }
    }
  };

  ApplicationSettingsWindow.prototype.destroy = function() {
    Window.prototype.destroy.apply(this, arguments);

    this.$side = null;
    this.$content = null;
    this.$header = null;
    this.modules = [];
  };

  ApplicationSettingsWindow.prototype.applySettings = function() {
    var self = this;
    var modules = OSjs.Applications.ApplicationSettings.Modules;
    modules.forEach(function(m) {
      m.applySettings(self, self.settings);
    });

    var wm = OSjs.Core.getWindowManager();
    wm.applySettings(this.settings, false, true);
  };

  ApplicationSettingsWindow.prototype.createColorDialog = function(cur, callback) {
    var self = this;
    this._appRef._createDialog('Color', [{color: cur}, function(btn, rgb, hex) {
      self._focus();
      if ( btn !== 'ok' ) {return; }

      callback(hex);
    }], this);
  };

  ApplicationSettingsWindow.prototype.createFileDialog = function(cur, callback) {
    var curf = cur ? Utils.dirname(cur) : API.getDefaultPath('/');
    var curn = cur ? Utils.filename(cur) : '';

    var self = this;
    this._appRef._createDialog('File', [{type: 'open', path: curf, filename: curn, mimes: ['^image']}, function(btn, file) {
      self._focus();
      if ( btn !== 'ok' ) {return; }
      callback(file.path);
    }], this);
  };

  ApplicationSettingsWindow.prototype.createFontDialog = function(cur, callback) {
    var self = this;
    this._appRef._createDialog('Font', [{name: cur, minSize: 0, maxSize: 0}, function(btn, fontName, fontSize) {
      self._focus();
      if ( btn !== 'ok' ) {return; }
      callback(fontName);
    }], this);
  };

  ApplicationSettingsWindow.prototype.setCategory = function(item) {
    Utils.$empty(this.$header);
    this.$content.childNodes.forEach(function(node) {
      node.style.display = 'none';
    });

    if ( this.modules[item.name] ) {
      this.modules[item.name].style.display = 'block';
      var title = OSjs.Applications.ApplicationSettings._(item.title);
      this.$header.appendChild(document.createTextNode(title));
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // APPLICATION
  /////////////////////////////////////////////////////////////////////////////

  var ApplicationSettings = function(args, metadata) {
    Application.apply(this, ['ApplicationSettings', args, metadata]);
  };

  ApplicationSettings.prototype = Object.create(Application.prototype);

  ApplicationSettings.prototype.destroy = function() {
    return Application.prototype.destroy.apply(this, arguments);
  };

  ApplicationSettings.prototype.init = function(settings, metadata) {
    Application.prototype.init.apply(this, arguments);
    this._addWindow(new ApplicationSettingsWindow(this, metadata));
  };

  ApplicationSettings.prototype._onMessage = function(obj, msg, args) {
    Application.prototype._onMessage.apply(this, arguments);
    if ( msg === 'destroyWindow' && obj._name === 'ApplicationSettingsWindow' ) {
      this.destroy();
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // EXPORTS
  /////////////////////////////////////////////////////////////////////////////

  OSjs.Applications = OSjs.Applications || {};
  OSjs.Applications.ApplicationSettings = OSjs.Applications.ApplicationSettings || {};
  OSjs.Applications.ApplicationSettings.Class = ApplicationSettings;
  OSjs.Applications.ApplicationSettings.Modules = OSjs.Applications.ApplicationSettings.Modules || [];

})(OSjs.Core.Application, OSjs.Core.Window, OSjs.GUI, OSjs.Dialogs, OSjs.Utils, OSjs.API, OSjs.VFS);
<commit_msg>Settings: Made window a bit smaller<commit_after>/*!
 * OS.js - JavaScript Operating System
 *
 * Copyright (c) 2011-2015, Anders Evenrud <andersevenrud@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @licence Simplified BSD License
 */
(function(Application, Window, GUI, Dialogs, Utils, API, VFS) {
  'use strict';

  /////////////////////////////////////////////////////////////////////////////
  // WINDOWS
  /////////////////////////////////////////////////////////////////////////////

  var ApplicationSettingsWindow = function(app, metadata) {
    Window.apply(this, ['ApplicationSettingsWindow', {
      icon: metadata.icon,
      title: metadata.name,
      width: 500,
      height: 450,
      allow_maximize: false,
      allow_resize: false
    }, app]);

    this.$side = null;
    this.$content = null;
    this.$header = null;
    this.modules = {};
    this.settings = {};
  };

  ApplicationSettingsWindow.prototype = Object.create(Window.prototype);

  ApplicationSettingsWindow.prototype.init = function(wmRef, app) {
    var _ = OSjs.Applications.ApplicationSettings._;
    var root = Window.prototype.init.apply(this, arguments);
    var self = this;

    function _createIcon(iter) {
      iter = iter || 'status/gtk-dialog-question.png';
      return OSjs.API.getIcon(iter, null, '32x32');
    }

    var columns = [
      {key: 'name', title: 'name', visible: false},
      {key: 'icon', title: 'Icon', type: 'image', domProperties: {width: 32}},
      {key: 'title', title: 'Title'}
    ];

    this.settings = Utils.cloneObject(wmRef.getSettings());
    delete this.settings.desktopIcons;
    delete this.settings.fullscreen;
    delete this.settings.moveOnResize;

    this.$side = document.createElement('div');
    this.$side.className = 'Side';

    this.$content = document.createElement('div');
    this.$content.className = 'Content';

    this.$header = document.createElement('div');
    this.$header.className = 'Header';

    var sidePanel = this._addGUIElement(new GUI.ListView('SettingsNewSideView', {
      singleClick: true,
      columns: columns,
      onSelect: function(ev, el, item) {
        self.setCategory(item);
      }
    }), this.$side);

    var modules = OSjs.Applications.ApplicationSettings.Modules;
    var rows = [];

    modules.forEach(function(m, i) {
      rows.push({
        name: m.name,
        title: m.title.match(/^[A-Z]*_/) ? API._(m.title) : _(m.title),
        icon: _createIcon(m.icon)
      });
      self.modules[m.name] = m.onCreate(self, self.$content, self.settings);
    });
    sidePanel.setRows(rows);
    sidePanel.render();

    root.appendChild(this.$side);
    root.appendChild(this.$header);
    root.appendChild(this.$content);

    this._addGUIElement(new GUI.Button('SettingsNewSave', {label: API._('LBL_SAVE'), onClick: function() {
      self.applySettings();
    }}), root);

    return root;
  };

  ApplicationSettingsWindow.prototype._inited = function() {
    Window.prototype._inited.apply(this, arguments);

    var sidePanel = this._getGUIElement('SettingsNewSideView');
    if ( sidePanel ) {
      var found = false;
      var set = this._appRef._getArgument('category');
      if ( set ) {
        var modules = OSjs.Applications.ApplicationSettings.Modules;
        modules.forEach(function(m, i) {
          if ( m.name === set ) {
            sidePanel.setSelectedIndex(i);
            found = true;
          }
          return found ? false : true;
        });
      }

      if ( !found ) {
        sidePanel.setSelectedIndex(0);
      }
    }
  };

  ApplicationSettingsWindow.prototype.destroy = function() {
    Window.prototype.destroy.apply(this, arguments);

    this.$side = null;
    this.$content = null;
    this.$header = null;
    this.modules = [];
  };

  ApplicationSettingsWindow.prototype.applySettings = function() {
    var self = this;
    var modules = OSjs.Applications.ApplicationSettings.Modules;
    modules.forEach(function(m) {
      m.applySettings(self, self.settings);
    });

    var wm = OSjs.Core.getWindowManager();
    wm.applySettings(this.settings, false, true);
  };

  ApplicationSettingsWindow.prototype.createColorDialog = function(cur, callback) {
    var self = this;
    this._appRef._createDialog('Color', [{color: cur}, function(btn, rgb, hex) {
      self._focus();
      if ( btn !== 'ok' ) {return; }

      callback(hex);
    }], this);
  };

  ApplicationSettingsWindow.prototype.createFileDialog = function(cur, callback) {
    var curf = cur ? Utils.dirname(cur) : API.getDefaultPath('/');
    var curn = cur ? Utils.filename(cur) : '';

    var self = this;
    this._appRef._createDialog('File', [{type: 'open', path: curf, filename: curn, mimes: ['^image']}, function(btn, file) {
      self._focus();
      if ( btn !== 'ok' ) {return; }
      callback(file.path);
    }], this);
  };

  ApplicationSettingsWindow.prototype.createFontDialog = function(cur, callback) {
    var self = this;
    this._appRef._createDialog('Font', [{name: cur, minSize: 0, maxSize: 0}, function(btn, fontName, fontSize) {
      self._focus();
      if ( btn !== 'ok' ) {return; }
      callback(fontName);
    }], this);
  };

  ApplicationSettingsWindow.prototype.setCategory = function(item) {
    Utils.$empty(this.$header);
    this.$content.childNodes.forEach(function(node) {
      node.style.display = 'none';
    });

    if ( this.modules[item.name] ) {
      this.modules[item.name].style.display = 'block';
      var title = OSjs.Applications.ApplicationSettings._(item.title);
      this.$header.appendChild(document.createTextNode(title));
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // APPLICATION
  /////////////////////////////////////////////////////////////////////////////

  var ApplicationSettings = function(args, metadata) {
    Application.apply(this, ['ApplicationSettings', args, metadata]);
  };

  ApplicationSettings.prototype = Object.create(Application.prototype);

  ApplicationSettings.prototype.destroy = function() {
    return Application.prototype.destroy.apply(this, arguments);
  };

  ApplicationSettings.prototype.init = function(settings, metadata) {
    Application.prototype.init.apply(this, arguments);
    this._addWindow(new ApplicationSettingsWindow(this, metadata));
  };

  ApplicationSettings.prototype._onMessage = function(obj, msg, args) {
    Application.prototype._onMessage.apply(this, arguments);
    if ( msg === 'destroyWindow' && obj._name === 'ApplicationSettingsWindow' ) {
      this.destroy();
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // EXPORTS
  /////////////////////////////////////////////////////////////////////////////

  OSjs.Applications = OSjs.Applications || {};
  OSjs.Applications.ApplicationSettings = OSjs.Applications.ApplicationSettings || {};
  OSjs.Applications.ApplicationSettings.Class = ApplicationSettings;
  OSjs.Applications.ApplicationSettings.Modules = OSjs.Applications.ApplicationSettings.Modules || [];

})(OSjs.Core.Application, OSjs.Core.Window, OSjs.GUI, OSjs.Dialogs, OSjs.Utils, OSjs.API, OSjs.VFS);
<|endoftext|>


<commit_before>/* eslint-env node */

"use strict";

module.exports = function(config) {
  config.set({
    frameworks: ["browserify", "mocha", "es5-shim"],

    files: [
      "test/**/*_test.js"
    ],

    preprocessors: {
      "test/**/*_test.js": "browserify"
    },

    browserify: {
      debug: true
    },

    client: {
      mocha: {
        ui: "tdd"
      }
    },

    reporters: ["progress"],

    logLevel: config.LOG_INFO,

    browsers: ["PhantomJS"],

    singleRun: true
  });
};
<commit_msg>Add browser configurations for Sauce Labs<commit_after>/* eslint-env node */

"use strict";

module.exports = function(config) {
  config.set({
    frameworks: ["browserify", "mocha", "es5-shim"],

    files: [
      "test/**/*_test.js"
    ],

    preprocessors: {
      "test/**/*_test.js": "browserify"
    },

    browserify: {
      debug: true
    },

    client: {
      mocha: {
        ui: "tdd"
      }
    },

    reporters: ["progress"],

    logLevel: config.LOG_INFO,

    customLaunchers: {
      Firefox: {
        base: "SauceLabs",
        browserName: "Firefox",
        platform: "Windows 7"
      },

      Chrome: {
        base: "SauceLabs",
        browserName: "Chrome",
        platform: "Windows 7"
      },

      Opera: {
        base: "SauceLabs",
        browserName: "Opera",
        platform: "Windows 7"
      },

      Safari: {
        base: "SauceLabs",
        browserName: "Safari",
        platform: "OS X 10.11"
      },

      IE11: {
        base: "SauceLabs",
        browserName: "Internet Explorer",
        version: "11",
        platform: "Windows 7"
      },

      IE10: {
        base: "SauceLabs",
        browserName: "Internet Explorer",
        version: "10",
        platform: "Windows 7"
      },

      IE9: {
        base: "SauceLabs",
        browserName: "Internet Explorer",
        version: "9",
        platform: "Windows 7"
      },

      IE8: {
        base: "SauceLabs",
        browserName: "Internet Explorer",
        version: "8",
        platform: "Windows 7"
      }
    },

    browsers: ["PhantomJS"],

    singleRun: true
  });
};
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

var rapidScoreControllers = angular.module('rapidScoreControllers', []);

rapidScoreControllers.controller('ScoreListCtrl', ['$scope', 'ScoreAPI', 'InstrumentAPI', 'Composer', 'GenreAPI',
    function($scope, Score, Instrument, Composer, Genre) {
        $scope.scores = Score.getAll();

        $scope.getInstruments = Instrument.getAll();
        $scope.getComposers = Composer.getAll();
        $scope.getGenres = Genre.getAll();
    }]);

rapidScoreControllers.controller('ScoreDetailCtrl', ['$scope', '$routeParams', 'ScoreAPI',
    function($scope, $routeParams, Score) {
        $scope.score = Score.getOne({scoreId: $routeParams.scoreId});
    }]);

/*
rapidScoreControllers.controller('ScoreListCtrl', ['$scope', 'Score', 'Instrument', 'Composer', 'Genre',
    function($scope, List, Instrument, Composer, Genre) {
        $scope.scores = List.query();
        $scope.getInstruments = Instrument.query();
        $scope.getComposers = Composer.query();
        $scope.getGenres = Genre.query();
    }]);
    */

rapidScoreControllers.controller('InstrumentCtrl', ['$scope', 'InstrumentAPI',
    function($scope, List) {
        $scope.itemname = "Instruments";
        $scope.uri = "instruments";
        $scope.categories = List.getAll();
    }]);

rapidScoreControllers.controller('ComposerCtrl', ['$scope', 'ComposerAPI',
    function($scope, List) {
        $scope.itemname = "Composers";
        $scope.uri = "composers";
        $scope.categories = List.getAll();
    }]);

rapidScoreControllers.controller('GenreCtrl', ['$scope', 'GenreAPI',
    function($scope, List) {
        $scope.itemname = "Genres";
        $scope.uri = "genres";
        $scope.categories = List.getAll();
    }]);

rapidScoreControllers.controller('UserCtrl', ['$scope', 'UserAPI',
    function($scope, List) {
        $scope.users = List.getAll();
    }]);

rapidScoreControllers.controller('UserDetailCtrl', ['$scope', '$routeParams', 'UserAPI',
    function($scope, $routeParams, User) {
        $scope.user = User.getOne({userId: $routeParams.userId});

    }]);
<commit_msg>Update controllers.js<commit_after>'use strict';

/* Controllers */

var rapidScoreControllers = angular.module('rapidScoreControllers', []);

rapidScoreControllers.controller('ScoreListCtrl', ['$scope', 'ScoreAPI', 'InstrumentAPI', 'ComposerAPI', 'GenreAPI',
    function($scope, Score, Instrument, Composer, Genre) {
        $scope.scores = Score.getAll();

        $scope.getInstruments = Instrument.getAll();
        $scope.getComposers = Composer.getAll();
        $scope.getGenres = Genre.getAll();
    }]);

rapidScoreControllers.controller('ScoreDetailCtrl', ['$scope', '$routeParams', 'ScoreAPI',
    function($scope, $routeParams, Score) {
        $scope.score = Score.getOne({scoreId: $routeParams.scoreId});
    }]);

/*
rapidScoreControllers.controller('ScoreListCtrl', ['$scope', 'Score', 'Instrument', 'Composer', 'Genre',
    function($scope, List, Instrument, Composer, Genre) {
        $scope.scores = List.query();
        $scope.getInstruments = Instrument.query();
        $scope.getComposers = Composer.query();
        $scope.getGenres = Genre.query();
    }]);
    */

rapidScoreControllers.controller('InstrumentCtrl', ['$scope', 'InstrumentAPI',
    function($scope, List) {
        $scope.itemname = "Instruments";
        $scope.uri = "instruments";
        $scope.categories = List.getAll();
    }]);

rapidScoreControllers.controller('ComposerCtrl', ['$scope', 'ComposerAPI',
    function($scope, List) {
        $scope.itemname = "Composers";
        $scope.uri = "composers";
        $scope.categories = List.getAll();
    }]);

rapidScoreControllers.controller('GenreCtrl', ['$scope', 'GenreAPI',
    function($scope, List) {
        $scope.itemname = "Genres";
        $scope.uri = "genres";
        $scope.categories = List.getAll();
    }]);

rapidScoreControllers.controller('UserCtrl', ['$scope', 'UserAPI',
    function($scope, List) {
        $scope.users = List.getAll();
    }]);

rapidScoreControllers.controller('UserDetailCtrl', ['$scope', '$routeParams', 'UserAPI',
    function($scope, $routeParams, User) {
        $scope.user = User.getOne({userId: $routeParams.userId});

    }]);
<|endoftext|>


<commit_before>// Load modules

var Crypto = require('crypto');
var Oz = require('oz');
var Utils = require('./utils');
var Err = require('./error');
var Log = require('./log');
var Types = require('joi').Types;

// Declare internals

var internals = {};

// Token Authentication

exports.authenticate = function (request, next) {

    if (request._route.config.auth.mode === 'none') {
        return next();
    }

//        exports.loadToken(request.server.settings.authentication.aes256Keys.oauthToken, token, callback);

    var validate = function (err, ticket, attributes) {

        // Unauthenticated

        if (err) {
            if (request._route.config.auth.mode === 'optional' &&
                !request.raw.req.headers.authorization) {

                request.session = null;
                request.log(['auth', 'unauthenticated']);
                return next();
            }

            request.log(['auth', 'unauthenticated', 'error'], err.wwwAuthenticateHeader);
            request.raw.res.setHeader('WWW-Authenticate', err.wwwAuthenticateHeader);
            return next(Err.unauthorized(err.message));
        }

        // Authenticated

        request.session = ticket;

        // Check scope

        if (request._route.config.auth.scope &&
            request.session.scope.indexOf(request._route.config.auth.scope) === -1) {

            request.log(['auth', 'error', 'scope'], { got: request.session.scope, need: request._route.config.auth.scope });
            return next(Err.forbidden('Insufficient scope (\'' + request._route.config.auth.scope + '\' expected for application ' + request.session.app + ')'));
        }

        // User Mode: any

        if (request._route.config.auth.entity === 'any') {
            request.log(['auth']);
            return next();
        }

        // User Mode: required

        if (request._route.config.auth.entity === 'user') {
            if (!request.session.user) {
                request.log(['auth', 'error'], 'User ticket required');
                return next(Err.forbidden('Application ticket cannot be used on a user endpoint'));
            }

            // Check TOS

            if (request._route.config.auth.tos !== 'none' &&
                (!request.session.ext || !request.session.ext.tos || request.session.ext.tos < request._route.config.auth.tos)) {

                request.log(['auth', 'error'], 'Insufficient TOS');
                return next(Err.forbidden('Insufficient TOS accepted'));
            }

            request.log(['auth']);
            return next();
        }

        // User Mode: none

        if (request._route.config.auth.entity === 'app') {
            if (request.session.user) {
                request.log(['auth', 'error'], 'App ticket required');
                return next(Err.forbidden('User ticket cannot be used on an application endpoint'));
            }

            request.log(['auth']);
            return next();
        }

        // User Mode: unknown

        request.log(['auth', 'error'], 'Unknown entity mode: ' + request._route.config.auth.entity);
        return next(Err.internal('Unknown endpoint entity mode'));
    };

    if (request.session) {
        return validate(null, request.session, null);
    }

    Oz.Request.authenticate(request.raw.req, { isHttps: request.server.settings.tls }, validate);
};

// Get session token

exports.token = {
    schema: {
        grant_type: Types.String().required(),
        client_id: Types.String().required(),
        client_secret: Types.String().emptyOk(),
        rsvp: Types.String(),
        x_user_id: Types.String(),
        x_email_token: Types.String()
    },
    auth: {
        mode: 'optional',
        entity: 'any'
    },
    handler: function (request) {

        var serverSettings = request.server.settings.authentication;

        // Load app information

        serverSettings.loadClientFunc(request.payload.client_id, function (err, app) {

            if (err || !app) {
                return request.reply(exports.error('invalid_client', 'Invalid application identifier or secret'));
            }

            // Check app secret

            if ((app.secret || '') !== (request.payload.client_secret || '')) {
                // Bad app authentication
                return request.reply(exports.error('invalid_client', 'Invalid application identifier or secret'));
            }

            // Switch on grant type

            if (request.payload.grant_type === 'client_credentials') {

                // Client credentials (no user context)
                return getOrCreate(null, app);
            }
            else if (request.payload.grant_type === 'rsvp') {

                // Refresh token

                if (!request.payload.rsvp) {
                    return request.reply(exports.error('invalid_request', 'Missing rsvp'));
                }

                serverSettings.checkRsvpFunc(app, request.payload.rsvp, function (err, user) {

                    if (err || !user) {
                        return request.reply(err);
                    }

                    return getOrCreate(user, app);
                });
            }
            else if (serverSettings.extensionFunc) {
                serverSettings.extensionFunc(request, app, function (err, user, action) {

                    if (err || !user) {
                        // Unknown local account
                        return request.reply(err);
                    }

                    return getOrCreate(user, app, action);
                });
            }
            else {
                // Unsupported grant type
                return request.reply(exports.error('unsupported_grant_type', 'Unknown or unsupported grant type'));
            }
        });

        function getOrCreate(user, app, customResponseFields) {

            var issue = function (rsvp) {

                // Issue a new token

                var ticketAttr = {
                    app: {
                        id: app.id,
                        scope: app.scope
                    },
                    options: {
                        ttl: serverSettings.tokenLifetimeSec * 1000,
                        ext: {
                            tos: internals.getLatestTOS(user)
                        }
                    }
                };

                if (user) {
                    ticketAttr.user = { id: user.id };
                }

                Oz.Ticket.issue(ticketAttr.app, ticketAttr.user, ticketAttr.options, function (err, ticket) {

                    if (err) {
                        return request.reply(err);
                    }

                    ticket.x_tos = ticketAttr.options.ext.tos
                    if (customResponseFields) {
                        for (var i in customResponseFields) {
                            if (customResponseFields.hasOwnProperty(i)) {
                                ticket[i] = customResponseFields[i];
                            }
                        }
                    }

                    if (rsvp) {
                        ticket.rsvp = rsvp;
                    }

                    return request.reply(ticket);
                });
            };

            // Application ticket

            if (!user) {
                return issue();
            }

            // User ticket

            serverSettings.checkAuthorizationFunc(request.session, app, user, function (err, rsvp) {

                if (err) {
                    return request.reply(err);
                }

                return issue(rsvp);
            });
        }
    }
};

exports.parseTicket = function (id, callback) {

    Oz.Ticket.parse(id, callback);
};

// Find latest accepted TOS

internals.getLatestTOS = function (user) {

    if (user &&
        user.tos &&
        typeof user.tos === 'object') {

        var versions = Object.keys(user.tos);
        if (versions.length > 0) {
            versions.sort();
            return versions[versions.length - 1];
        }
    }

    return 0;
};

// Compare scopes

internals.compareScope = function (a, b) {

    a = a || null;
    b = b || null;

    if (a === null && b === null) {
        return true;
    }

    if ((a === null && b !== null) ||
        (a !== null && b === null)) {

        return false;
    }

    if (Object.keys(a).length !== Object.keys(b).length) {
        return false;
    }

    for (var i in a) {
        if (a.hasOwnProperty(i)) {
            if (a[i] !== b[i]) {
                return false;
            }
        }
    }

    return true;
};

exports.error = function (type, description) {

    var err = new Err(400, 'OAuth', {
        toResponse: function () {

            return { code: 400, payload: { error: type, error_description: description } };
        }
    });

    err.description = description;
    err.type = type;
    return err;
};

<commit_msg>more cleanup<commit_after>// Load modules

var Crypto = require('crypto');
var Oz = require('oz');
var Utils = require('./utils');
var Err = require('./error');
var Log = require('./log');
var Types = require('joi').Types;

// Declare internals

var internals = {};

// Token Authentication

exports.authenticate = function (request, next) {

    if (request._route.config.auth.mode === 'none') {
        return next();
    }

//        exports.loadToken(request.server.settings.authentication.aes256Keys.oauthToken, token, callback);

    var validate = function (err, ticket, attributes) {

        // Unauthenticated

        if (err) {
            if (request._route.config.auth.mode === 'optional' &&
                !request.raw.req.headers.authorization) {

                request.session = null;
                request.log(['auth', 'unauthenticated']);
                return next();
            }

            request.log(['auth', 'unauthenticated', 'error'], err.wwwAuthenticateHeader);
            request.raw.res.setHeader('WWW-Authenticate', err.wwwAuthenticateHeader);
            return next(Err.unauthorized(err.message));
        }

        // Authenticated

        request.session = ticket;

        // Check scope

        if (request._route.config.auth.scope &&
            request.session.scope.indexOf(request._route.config.auth.scope) === -1) {

            request.log(['auth', 'error', 'scope'], { got: request.session.scope, need: request._route.config.auth.scope });
            return next(Err.forbidden('Insufficient scope (\'' + request._route.config.auth.scope + '\' expected for application ' + request.session.app + ')'));
        }

        // User Mode: any

        if (request._route.config.auth.entity === 'any') {
            request.log(['auth']);
            return next();
        }

        // User Mode: required

        if (request._route.config.auth.entity === 'user') {
            if (!request.session.user) {
                request.log(['auth', 'error'], 'User ticket required');
                return next(Err.forbidden('Application ticket cannot be used on a user endpoint'));
            }

            // Check TOS

            if (request._route.config.auth.tos !== 'none' &&
                (!request.session.ext || !request.session.ext.tos || request.session.ext.tos < request._route.config.auth.tos)) {

                request.log(['auth', 'error'], 'Insufficient TOS');
                return next(Err.forbidden('Insufficient TOS accepted'));
            }

            request.log(['auth']);
            return next();
        }

        // User Mode: none

        if (request._route.config.auth.entity === 'app') {
            if (request.session.user) {
                request.log(['auth', 'error'], 'App ticket required');
                return next(Err.forbidden('User ticket cannot be used on an application endpoint'));
            }

            request.log(['auth']);
            return next();
        }

        // User Mode: unknown

        request.log(['auth', 'error'], 'Unknown entity mode: ' + request._route.config.auth.entity);
        return next(Err.internal('Unknown endpoint entity mode'));
    };

    if (request.session) {
        return validate(null, request.session, null);
    }

    Oz.Request.authenticate(request.raw.req, { isHttps: request.server.settings.tls }, validate);
};

// Get session token

exports.token = {
    schema: {
        grant_type: Types.String().required(),
        client_id: Types.String().required(),
        client_secret: Types.String().emptyOk(),
        rsvp: Types.String(),
        x_user_id: Types.String(),
        x_email_token: Types.String()
    },
    auth: {
        mode: 'optional',
        entity: 'any'
    },
    handler: function (request) {

        var serverSettings = request.server.settings.authentication;

        // Load app information

        serverSettings.loadClientFunc(request.payload.client_id, function (err, app) {

            if (err || !app) {
                return request.reply(exports.error('invalid_client', 'Invalid application identifier or secret'));
            }

            // Check app secret

            if ((app.secret || '') !== (request.payload.client_secret || '')) {
                // Bad app authentication
                return request.reply(exports.error('invalid_client', 'Invalid application identifier or secret'));
            }

            // Switch on grant type

            if (request.payload.grant_type === 'client_credentials') {

                // Client credentials (no user context)
                return getOrCreate(null, app);
            }
            else if (request.payload.grant_type === 'rsvp') {

                // Refresh token

                if (!request.payload.rsvp) {
                    return request.reply(exports.error('invalid_request', 'Missing rsvp'));
                }

                serverSettings.checkRsvpFunc(app, request.payload.rsvp, function (err, user) {

                    if (err || !user) {
                        return request.reply(err);
                    }

                    return getOrCreate(user, app);
                });
            }
            else if (serverSettings.extensionFunc) {
                serverSettings.extensionFunc(request, app, function (err, user, action) {

                    if (err || !user) {
                        // Unknown local account
                        return request.reply(err);
                    }

                    return getOrCreate(user, app, action);
                });
            }
            else {
                // Unsupported grant type
                return request.reply(exports.error('unsupported_grant_type', 'Unknown or unsupported grant type'));
            }
        });

        function getOrCreate(user, app, customResponseFields) {

            var issue = function (rsvp) {

                // Issue a new token

                var ticketAttr = {
                    app: {
                        id: app.id,
                        scope: app.scope
                    },
                    options: {
                        ttl: serverSettings.tokenLifetimeSec * 1000
                    }
                };

                if (user) {
                    ticketAttr.user = { id: user.id };
                    ticketAttr.options.ext = {
                        tos: user.tos
                    };
                }

                Oz.Ticket.issue(ticketAttr.app, ticketAttr.user, ticketAttr.options, function (err, ticket) {

                    if (err) {
                        return request.reply(err);
                    }

                    if (user) {
                        ticket.x_tos = ticketAttr.options.ext.tos
                    }

                    if (customResponseFields) {
                        for (var i in customResponseFields) {
                            if (customResponseFields.hasOwnProperty(i)) {
                                ticket[i] = customResponseFields[i];
                            }
                        }
                    }

                    if (rsvp) {
                        ticket.rsvp = rsvp;
                    }

                    return request.reply(ticket);
                });
            };

            // Application ticket

            if (!user) {
                return issue();
            }

            // User ticket

            serverSettings.checkAuthorizationFunc(request.session, app, user, function (err, rsvp) {

                if (err) {
                    return request.reply(err);
                }

                return issue(rsvp);
            });
        }
    }
};

exports.parseTicket = function (id, callback) {

    Oz.Ticket.parse(id, callback);
};

exports.error = function (type, description) {

    var err = new Err(400, 'OAuth', {
        toResponse: function () {

            return { code: 400, payload: { error: type, error_description: description } };
        }
    });

    err.description = description;
    err.type = type;
    return err;
};

<|endoftext|>


<commit_before>import React from 'react';

import { HawkCorrigan } from 'CONTRIBUTORS';
import SPECS from 'game/SPECS';

import CHANGELOG from './CHANGELOG';

export default {
  // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion.
  contributors: [HawkCorrigan],
  // The WoW client patch this spec was last updated to be fully compatible with.
  patchCompatibility: '8.0.1',
  // If set to  false`, the spec will show up as unsupported.
  isSupported: true,
  // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more.
  // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component.
  description: (
    <>
      Hello there! Welcome to the analyzer for Elemental Shaman! This analyzer has functionalities that I hope you find useful when playing the spec. If you have any input or suggestions please contact HawkCorrigan(HawkCorrigan#1811) on Discord.

More resources for Elemental:

      Shaman Class Discord

      Storm, Earth and Lava

      Wowhead Guide

      Icy Veins Guide

    </>
  ),
  // A recent example report to see interesting parts of the spec. Will be shown on the homepage.
  exampleReport: '/report/67LHQfJjCFzgyXBr/8-Normal+Stormwall+Blockade+-+Kill+(7:17)/10-Khalidmd',

  // Don't change anything below this line;
  // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about.
  spec: SPECS.ELEMENTAL_SHAMAN,
  // The contents of your changelog.
  changelog: CHANGELOG,
  // The CombatLogParser class for your spec.
  parser: () => import('./CombatLogParser' /* webpackChunkName: "ElementalShaman" */).then(exports => exports.default),
  // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code.
  path: __dirname,
};
<commit_msg>update elemental shaman config to indicate 8.2.5 readiness and update sample report<commit_after>import React from 'react';

import { HawkCorrigan, Draenal } from 'CONTRIBUTORS';
import SPECS from 'game/SPECS';

import CHANGELOG from './CHANGELOG';

export default {
  // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion.
  contributors: [HawkCorrigan, Draenal],
  // The WoW client patch this spec was last updated to be fully compatible with.
  patchCompatibility: '8.2.5',
  // If set to  false`, the spec will show up as unsupported.
  isSupported: true,
  // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more.
  // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component.
  description: (
    <>
      Hello there! Welcome to the analyzer for Elemental Shaman! This analyzer has functionalities that I hope you find useful when playing the spec. If you have any input or suggestions please contact HawkCorrigan(HawkCorrigan#1811) or Draenal(Draenal#4089) on Discord.

More resources for Elemental:

      Shaman Class Discord

      Storm, Earth and Lava

      Wowhead Guide

      Icy Veins Guide

    </>
  ),
  // A recent example report to see interesting parts of the spec. Will be shown on the homepage.
  exampleReport: '/report/QFbdLCMHtxzTjfZ1/5-Heroic+Abyssal+Commander+Sivara+-+Kill+(2:43)/Goff',

  // Don't change anything below this line;
  // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about.
  spec: SPECS.ELEMENTAL_SHAMAN,
  // The contents of your changelog.
  changelog: CHANGELOG,
  // The CombatLogParser class for your spec.
  parser: () => import('./CombatLogParser' /* webpackChunkName: "ElementalShaman" */).then(exports => exports.default),
  // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code.
  path: __dirname,
};
<|endoftext|>


<commit_before>(function($) {
	$(document).ready(function() {
	  $('#jenkins-head-icon').attr('src', 'http://ericduran.github.io/jenkins-ci-ui-improvements/imgs/headshot.png');
	});

    setInterval(function() {
        replaceFloatyBall("img[src*='/aborted.png']", "aborted");
        replaceFloatyBall("img[src*='/blue.png']", "success");
        replaceFloatyBall("img[src*='/red.png']", "failure");
        replaceFloatyBall("img[src*='/yellow.png']", "warning");
        replaceFloatyBall("img[src*='/grey.png']", "aborted");
        replaceFloatyBall("img[src*='/nobuilt.png']", "notbuilt");
        replaceFloatyBall("img[src*='/disabled.png']", "notbuilt");
    }, 10);

    // Replace the floaty ball with a Doony balls, slightly modified.
    var replaceFloatyBall = function(selector, type) {
        $(selector).each(function() {
            var wrapper = document.createElement('div');
            wrapper.className = 'doony-circle doony-circle-' + type;
            wrapper.style.display = 'inline-block';
            var dimension;

            if (this.classList.contains("icon-xlg")) {
                // an overly large ball is scary
                dimension = 30;
                wrapper.style.marginRight = "15px";
                wrapper.style.verticalAlign = "bottom";

            } else if (this.classList.contains("icon-lg")) {
                // an overly large ball is scary
                dimension = 24;
                wrapper.style.marginRight = "15px";
                wrapper.style.verticalAlign = "middle";
            // XXX hack, this is for the main page job list
        	}
            else {
                dimension = this.getAttribute('width') || 12;
            }
            $(wrapper).css('width', dimension);
            $(wrapper).css('height', dimension);

            $(this).after(wrapper).remove();
        });
    };

})(jQuery);
<commit_msg>Adding progress circle<commit_after>/*
 * ProgressCircle.js
 * http://qiao.github.io/ProgressCircle.js/
 *
 * © 2011-2013 Xueqiao Xu <xueqiaoxu@gmail.com>

 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
(function(window, document, undefined) {

    /**
     * Find the absolute position of an element
     */
    var absPos = function(element) {
        var offsetLeft, offsetTop;
        offsetLeft = offsetTop = 0;
        if (element.offsetParent) {
            do {
                offsetLeft += element.offsetLeft;
                offsetTop += element.offsetTop;
            } while ((element = element.offsetParent) !== null);
        }
        return [offsetLeft, offsetTop];
    };

    /**
     * @constructor Progress Circle class
     * @param params.canvas Canvas on which the circles will be drawn.
     * @param params.minRadius Inner radius of the innermost circle, in px.
     * @param params.arcWidth Width of each circle(to be more accurate, ring).
     * @param params.gapWidth Space between each circle.
     * @param params.centerX X coordinate of the center of circles.
     * @param params.centerY Y coordinate of the center of circles.
     * @param params.infoLineBaseAngle Base angle of the info line.
     * @param params.infoLineAngleInterval Angles between the info lines.
     */
    var ProgressCircle = function(params) {
        this.canvas = params.canvas;
        this.minRadius = params.minRadius || 15;
        this.arcWidth = params.arcWidth || 5;
        this.gapWidth = params.gapWidth || 3;
        this.centerX = params.centerX || this.canvas.width / 2;
        this.centerY = params.centerY || this.canvas.height / 2;
        this.infoLineLength = params.infoLineLength || 60;
        this.horizLineLength = params.horizLineLength || 10;
        this.infoLineAngleInterval = params.infoLineAngleInterval || Math.PI / 8;
        this.infoLineBaseAngle = params.infoLineBaseAngle || Math.PI / 6;

        this.context = this.canvas.getContext('2d');

        this.width = this.canvas.width;
        this.height = this.canvas.height;

        this.circles = [];
        this.runningCount = 0;
    };

    ProgressCircle.prototype = {
        constructor: ProgressCircle,

        /**
         * @method Adds an progress monitor entry.
         * @param params.fillColor Color to fill in the circle.
         * @param params.outlineColor Color to outline the circle.
         * @param params.progressListener Callback function to fetch the progress.
         * @param params.infoListener Callback function to fetch the info.
         * @returns this
         */
        addEntry: function(params) {
            this.circles.push(new Circle({
                canvas: this.canvas,
                context: this.context,
                centerX: this.centerX,
                centerY: this.centerY,
                innerRadius: this.minRadius + this.circles.length *
                    (this.gapWidth + this.arcWidth),
                arcWidth: this.arcWidth,
                infoLineLength: this.infoLineLength,
                horizLineLength: this.horizLineLength,

                id: this.circles.length,
                fillColor: params.fillColor,
                outlineColor: params.outlineColor,
                progressListener: params.progressListener,
                infoListener: params.infoListener,
                infoLineAngle: this.infoLineBaseAngle +
                    this.circles.length * this.infoLineAngleInterval,
            }));

            return this;
        },

        /**
         * @method Starts the monitor and updates with the given interval.
         * @param interval Interval between updates, in millisecond.
         * @returns this
         */
        start: function(interval) {
            var self = this;
            this.timer = setInterval(function() {
                self._update();
            }, interval || 33);

            return this;
        },

        /**
         * @method Stop the animation.
         */
        stop: function() {
            clearTimeout(this.timer);
        },

        /**
         * @private
         * @method Call update on each circle and redraw them.
         * @returns this
         */
        _update: function() {
            this._clear();
            this.circles.forEach(function(circle) {
                circle.update();
            });

            return this;
        },

        /**
         * @private
         * @method Clear the canvas.
         * @returns this
         */
        _clear: function() {
            this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);

            return this;
        },

    };

    /**
     * @private
     * @class Individual progress circle.
     * @param params.canvas Canvas on which the circle will be drawn.
     * @param params.context Context of the canvas.
     * @param params.innerRadius Inner radius of the circle, in px.
     * @param params.arcWidth Width of each arc(circle).
     * @param params.gapWidth Distance between each arc.
     * @param params.centerX X coordinate of the center of circles.
     * @param params.centerY Y coordinate of the center of circles.
     * @param params.fillColor Color to fill in the circle.
     * @param params.outlineColor Color to outline the circle.
     * @param params.progressListener Callback function to fetch the progress.
     * @param params.infoListener Callback function to fetch the info.
     * @param params.infoLineAngle Angle of info line.
     */
    var Circle = function(params) {
        this.id = params.id;
        this.canvas = params.canvas;
        this.context = params.context;
        this.centerX = params.centerX;
        this.centerY = params.centerY;
        this.arcWidth = params.arcWidth;
        this.innerRadius = params.innerRadius || 0;
        this.fillColor = params.fillColor || '#fff';
        this.outlineColor = params.outlineColor || this.fillColor;
        this.progressListener = params.progressListener;
        this.infoLineLength = params.infoLineLength || 250;
        this.horizLineLength = params.horizLineLength || 50;
        this.infoListener = params.infoListener;
        this.infoLineAngle = params.infoLineAngle;

        this.outerRadius = this.innerRadius + this.arcWidth;

        // If the info listener is not registered, then don't calculate
        // the related coordinates
        if (!this.infoListener) return;

        // calculate the info-line turning points
        var angle = this.infoLineAngle,
            arcDistance = (this.innerRadius + this.outerRadius) / 2,

            sinA = Math.sin(angle),
            cosA = Math.cos(angle);

        this.infoLineStartX = this.centerX + sinA * arcDistance;
        this.infoLineStartY = this.centerY - cosA * arcDistance;

        this.infoLineMidX = this.centerX + sinA * this.infoLineLength;
        this.infoLineMidY = this.centerY - cosA * this.infoLineLength;

        this.infoLineEndX = this.infoLineMidX +
             (sinA < 0 ? -this.horizLineLength : this.horizLineLength);
        this.infoLineEndY = this.infoLineMidY;

        var infoText = document.createElement('div'),
            style = infoText.style;

        style.color = this.fillColor;
        style.position = 'absolute';
        style.left = this.infoLineEndX + absPos(this.canvas)[0] + 'px';
        // style.top will be calculated in the `drawInfo` method. Since
        // user may want to change the size of the font, so the top offset
        // must be updated in each loop.
        infoText.className = 'ProgressCircleInfo'; // For css styling
        infoText.id = 'progress_circle_info_' + this.id;
        document.body.appendChild(infoText);
        this.infoText = infoText;
    };

    Circle.prototype = {
        constructor: Circle,

        update: function() {
            this.progress = this.progressListener();
            this._draw();

            if (this.infoListener) {
                this.info = this.infoListener();
                this._drawInfo();
            }
        },

        /**
         * @private
         * @method Draw the circle on the canvas.
         * @returns this
         */
        _draw: function() {
            var ctx = this.context,

                ANGLE_OFFSET = -Math.PI / 2,

                startAngle = 0 + ANGLE_OFFSET,
                endAngle= startAngle + this.progress * Math.PI * 2,

                x = this.centerX,
                y = this.centerY,

                innerRadius = this.innerRadius,
                outerRadius = this.outerRadius;

            ctx.fillStyle = this.fillColor;
            ctx.strokeStyle = this.outlineColor;

            ctx.beginPath();
            ctx.arc(x, y, innerRadius, startAngle, endAngle, false);
            ctx.arc(x, y, outerRadius, endAngle, startAngle, true);
            ctx.closePath();
            ctx.stroke();
            ctx.fill();

            return this;
        },

        /**
         * @private
         * @method Draw the info lines and info text.
         * @returns this
         */
        _drawInfo: function() {

            var pointList, lineHeight;

            pointList = [
                [this.infoLineStartX, this.infoLineStartY],
                [this.infoLineMidX, this.infoLineMidY],
                [this.infoLineEndX, this.infoLineEndY],
            ];
            this._drawSegments(pointList, false);

            this.infoText.innerHTML = this.info;

            lineHeight = this.infoText.offsetHeight;
            this.infoText.style.top = this.infoLineEndY +
                absPos(this.canvas)[1] - lineHeight / 2 + 'px';

            return this;
        },

        /**
         * @private
         * @method Helper function to draw the segments
         * @param pointList An array of points in the form of [x, y].
         * @param close Whether to connect the first and last point.
         */
        _drawSegments: function(pointList, close) {
            var ctx = this.context;

            ctx.beginPath();
            ctx.moveTo(pointList[0][0], pointList[0][1]);
            for (var i = 1; i < pointList.length; ++i) {
                ctx.lineTo(pointList[i][0], pointList[i][1]);
            }

            if (close) {
                ctx.closePath();
            }
            ctx.stroke();
        },
    };

    window.ProgressCircle = ProgressCircle;

})(window, document);

(function($) {
	$(document).ready(function() {
	  $('#jenkins-head-icon').attr('src', 'http://ericduran.github.io/jenkins-ci-ui-improvements/imgs/headshot.png');
	});

    setInterval(function() {
        replaceBouncingFloatyBall("img[src*='red_anime.gif']", '#d9534f');
        replaceBouncingFloatyBall("img[src*='blue_anime.gif']", '#4f9f4f');
        replaceBouncingFloatyBall("img[src*='grey_anime.gif']", '#999');
        replaceBouncingFloatyBall("img[src*='aborted_anime.gif']", '#999');
        replaceBouncingFloatyBall("img[src*='yellow_anime.gif']", '#f0ad4e');
    }, 10);
    setInterval(function() {
        replaceFloatyBall("img[src*='/aborted.png']", "aborted");
        replaceFloatyBall("img[src*='/blue.png']", "success");
        replaceFloatyBall("img[src*='/red.png']", "failure");
        replaceFloatyBall("img[src*='/yellow.png']", "warning");
        replaceFloatyBall("img[src*='/grey.png']", "aborted");
        replaceFloatyBall("img[src*='/nobuilt.png']", "notbuilt");
        replaceFloatyBall("img[src*='/disabled.png']", "notbuilt");
    }, 10);

    // Replace the floaty ball with a Doony balls, slightly modified.
    var replaceFloatyBall = function(selector, type) {
        $(selector).each(function() {
            var wrapper = document.createElement('div');
            wrapper.className = 'doony-circle doony-circle-' + type;
            wrapper.style.display = 'inline-block';
            var dimension;

            if (this.classList.contains("icon-xlg")) {
                // an overly large ball is scary
                dimension = 30;
                wrapper.style.marginRight = "15px";
                wrapper.style.verticalAlign = "bottom";

            } else if (this.classList.contains("icon-lg")) {
                // an overly large ball is scary
                dimension = 24;
                wrapper.style.marginRight = "15px";
                wrapper.style.verticalAlign = "middle";
            // XXX hack, this is for the main page job list
        	}
            else {
                dimension = this.getAttribute('width') || 12;
            }
            $(wrapper).css('width', dimension);
            $(wrapper).css('height', dimension);

            $(this).after(wrapper).remove();
        });
    };

    var replaceBouncingFloatyBall = function(selector, color) {
        $(selector).each(function() {

            if ($(this).next(".doony-canvas").length) {
                return;
            }
            var canvas = document.createElement('canvas');
            canvas.className = 'doony-canvas';

            // 48 -> dimension 32.
            // radius should be 12, plus 4 width
            // 16 -> dimension 16, radius 4
            var dimension;
            if (this.getAttribute('width') === "48" || this.getAttribute('width') === "24") {
                // an overly large ball is scary
                dimension = this.getAttribute('width') * 0.5 + 8;
                canvas.style.marginRight = "15px";
                canvas.style.verticalAlign = "middle";
            // XXX hack, this is for the main page job list
            } else if (this.classList.contains("icon32x32")) {
                dimension = 24;
                canvas.style.marginTop = "4px";
                canvas.style.marginLeft = "4px";
            } else {
                dimension = this.getAttribute('width') || 12;
            }
            canvas.setAttribute('width', dimension);
            canvas.setAttribute('height', dimension);

            var circle = new ProgressCircle({
                canvas: canvas,
                minRadius: dimension * 3 / 8 - 2,
                arcWidth: dimension / 8 + 1
            });

            var x = 0;
            circle.addEntry({
                fillColor: color,
                progressListener: function() {
                    if (x >= 1) { x = 0; }
                    x = x + 0.005;
                    return x; // between 0 and 1
                },
            });
            // jenkins does ajax every 5 seconds, this should time it perfectly
            circle.start(24);
            $(this).after(canvas).css('display', 'none');
        });
    };

})(jQuery);
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var SqlHighlightRules = function() {

    var keywords = (
        "select|insert|update|delete|from|where|and|or|group|by|order|limit|offset|having|as|case|" +
        "when|else|end|type|left|right|join|on|outer|desc|asc|union|create|table|primary|key|if|" +
        "foreign|not|references|default|null"
    );

    var builtinConstants = (
        "true|false"
    );

    var builtinFunctions = (
        "count|min|max|avg|sum|rank|now|coalesce"
    );

    var dataTypes = (
        "int|numeric|decimal|date|varchar|char|bigint|" +
        "float|double|bit|binary|text|set|timestamp|money|real|number"
    );

    var keywordMapper = this.createKeywordMapper({
        "support.function": builtinFunctions,
        "keyword": keywords,
        "constant.language": builtinConstants,
        "storage.type": dataTypes
    }, "identifier", true);

    this.$rules = {
        "start" : [ {
            token : "comment",
            regex : "--.*$"
        },  {
            token : "comment",
            start : "/\\*",
            end : "\\*/"
        }, {
            token : "string",           // " string
            regex : '".*?"'
        }, {
            token : "string",           // ' string
            regex : "'.*?'"
        }, {
            token : "constant.numeric", // float
            regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
        }, {
            token : keywordMapper,
            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
        }, {
            token : "keyword.operator",
            regex : "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="
        }, {
            token : "paren.lparen",
            regex : "[\\(]"
        }, {
            token : "paren.rparen",
            regex : "[\\)]"
        }, {
            token : "text",
            regex : "\\s+"
        }, {
            token : "entity.name.function",
            regex : "\\s+"
        } ]
    };
    this.normalizeRules();
};

oop.inherits(SqlHighlightRules, TextHighlightRules);

exports.SqlHighlightRules = SqlHighlightRules;
});

<commit_msg>formatting<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var SqlHighlightRules = function() {

    var keywords = (
        "select|insert|update|delete|from|where|and|or|group|by|order|limit|offset|having|as|case|" +
        "when|else|end|type|left|right|join|on|outer|desc|asc|union|create|table|primary|key|if|" +
        "foreign|not|references|default|null"
    );

    var builtinConstants = (
        "true|false"
    );

    var builtinFunctions = (
        "count|min|max|avg|sum|rank|now|coalesce"
    );

    var dataTypes = (
        "int|numeric|decimal|date|varchar|char|bigint|float|double|bit|binary|text|set|timestamp|" +
        "money|real|number"
    );

    var keywordMapper = this.createKeywordMapper({
        "support.function": builtinFunctions,
        "keyword": keywords,
        "constant.language": builtinConstants,
        "storage.type": dataTypes
    }, "identifier", true);

    this.$rules = {
        "start" : [ {
            token : "comment",
            regex : "--.*$"
        },  {
            token : "comment",
            start : "/\\*",
            end : "\\*/"
        }, {
            token : "string",           // " string
            regex : '".*?"'
        }, {
            token : "string",           // ' string
            regex : "'.*?'"
        }, {
            token : "constant.numeric", // float
            regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
        }, {
            token : keywordMapper,
            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
        }, {
            token : "keyword.operator",
            regex : "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="
        }, {
            token : "paren.lparen",
            regex : "[\\(]"
        }, {
            token : "paren.rparen",
            regex : "[\\)]"
        }, {
            token : "text",
            regex : "\\s+"
        } ]
    };
    this.normalizeRules();
};

oop.inherits(SqlHighlightRules, TextHighlightRules);

exports.SqlHighlightRules = SqlHighlightRules;
});

<|endoftext|>


<commit_before>/**
 * SearchConsoleDashboardWidgetSiteStats 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.
 */

/**
 * WordPress dependencies
 */
import { __, sprintf } from '@wordpress/i18n';
import { Component } from '@wordpress/element';

/**
 * Internal dependencies
 */
import { decodeHTMLEntity, getTimeInSeconds } from '../../../../util';
import withData from '../../../../components/higherorder/withData';
import { TYPE_MODULES } from '../../../../components/data';
import GoogleChart from '../../../../components/GoogleChart';
import PreviewBlock from '../../../../components/PreviewBlock';
import { extractSearchConsoleDashboardData } from '../../util';

class SearchConsoleDashboardWidgetSiteStats extends Component {
	constructor( props ) {
		super( props );

		this.setOptions = this.setOptions.bind( this );
	}

	setOptions() {
		const { selectedStats, series, vAxes } = this.props;
		const { pageTitle } = global._googlesitekitLegacyData;

		let title = __( 'Search Traffic Summary', 'google-site-kit' );

		if ( pageTitle && pageTitle.length ) {
			/* translators: %s: page title */
			title = sprintf( __( 'Search Traffic Summary for %s', 'google-site-kit' ), decodeHTMLEntity( pageTitle ) );
		}

		const options = {
			chart: {
				title,
			},
			curveType: 'line',
			height: 270,
			width: '100%',
			chartArea: {
				height: '80%',
				width: '87%',
			},
			legend: {
				position: 'top',
				textStyle: {
					color: '#616161',
					fontSize: 12,
				},
			},
			hAxis: {
				format: 'M/d/yy',
				gridlines: {
					color: '#fff',
				},
				textStyle: {
					color: '#616161',
					fontSize: 12,
				},
			},
			vAxis: {
				gridlines: {
					color: '#eee',
				},
				minorGridlines: {
					color: '#eee',
				},
			},
		};

		options.series = series;
		options.vAxes = vAxes;

		if ( selectedStats.length < 3 ) {
			options.vAxis.textStyle = {
				color: '#616161',
				fontSize: 12,
			};
			options.vAxis.titleTextStyle = {
				color: '#616161',
				fontSize: 12,
				italic: false,
			};
		} else {
			// Clean up chart if three or more stats are selected.
			options.vAxis.gridlines.color = '#fff';
			options.vAxis.minorGridlines.color = '#fff';
			options.chartArea.width = '98%';
		}

		return options;
	}

	render() {
		const { data, selectedStats } = this.props;

		if ( ! data || ! data.length ) {
			return null;
		}

		const options = this.setOptions();
		const processedData = extractSearchConsoleDashboardData( data );

		return (

						<GoogleChart
							chartType="line"
							selectedStats={ selectedStats }
							data={ processedData.dataMap }
							options={ options }
							singleStat={ false }
						/>

		);
	}
}

export default withData(
	SearchConsoleDashboardWidgetSiteStats,
	[
		{
			type: TYPE_MODULES,
			identifier: 'search-console',
			datapoint: 'searchanalytics',
			data: {
				dimensions: 'date',
				compareDateRanges: true,
			},
			priority: 1,
			maxAge: getTimeInSeconds( 'day' ),
			context: 'Single',
		},
	],
	<PreviewBlock width="100%" height="270px" padding />,
	{ createGrid: true }
);
<commit_msg>Fix label truncation Search Console.<commit_after>/**
 * SearchConsoleDashboardWidgetSiteStats 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.
 */

/**
 * WordPress dependencies
 */
import { __, sprintf } from '@wordpress/i18n';
import { Component } from '@wordpress/element';

/**
 * Internal dependencies
 */
import { decodeHTMLEntity, getTimeInSeconds } from '../../../../util';
import withData from '../../../../components/higherorder/withData';
import { TYPE_MODULES } from '../../../../components/data';
import GoogleChart from '../../../../components/GoogleChart';
import PreviewBlock from '../../../../components/PreviewBlock';
import { extractSearchConsoleDashboardData } from '../../util';

class SearchConsoleDashboardWidgetSiteStats extends Component {
	constructor( props ) {
		super( props );

		this.setOptions = this.setOptions.bind( this );
	}

	setOptions() {
		const { selectedStats, series, vAxes } = this.props;
		const { pageTitle } = global._googlesitekitLegacyData;

		let title = __( 'Search Traffic Summary', 'google-site-kit' );

		if ( pageTitle && pageTitle.length ) {
			/* translators: %s: page title */
			title = sprintf( __( 'Search Traffic Summary for %s', 'google-site-kit' ), decodeHTMLEntity( pageTitle ) );
		}

		const options = {
			chart: {
				title,
			},
			curveType: 'line',
			height: 270,
			width: '100%',
			chartArea: {
				height: '77%',
				width: '87%',
			},
			legend: {
				position: 'top',
				textStyle: {
					color: '#616161',
					fontSize: 12,
				},
			},
			hAxis: {
				format: 'M/d/yy',
				gridlines: {
					color: '#fff',
				},
				textStyle: {
					color: '#616161',
					fontSize: 12,
				},
			},
			vAxis: {
				gridlines: {
					color: '#eee',
				},
				minorGridlines: {
					color: '#eee',
				},
			},
		};

		options.series = series;
		options.vAxes = vAxes;

		if ( selectedStats.length < 3 ) {
			options.vAxis.textStyle = {
				color: '#616161',
				fontSize: 12,
			};
			options.vAxis.titleTextStyle = {
				color: '#616161',
				fontSize: 12,
				italic: false,
			};
		} else {
			// Clean up chart if three or more stats are selected.
			options.vAxis.gridlines.color = '#fff';
			options.vAxis.minorGridlines.color = '#fff';
			options.chartArea.width = '98%';
		}

		return options;
	}

	render() {
		const { data, selectedStats } = this.props;

		if ( ! data || ! data.length ) {
			return null;
		}

		const options = this.setOptions();
		const processedData = extractSearchConsoleDashboardData( data );

		return (

						<GoogleChart
							chartType="line"
							selectedStats={ selectedStats }
							data={ processedData.dataMap }
							options={ options }
							singleStat={ false }
						/>

		);
	}
}

export default withData(
	SearchConsoleDashboardWidgetSiteStats,
	[
		{
			type: TYPE_MODULES,
			identifier: 'search-console',
			datapoint: 'searchanalytics',
			data: {
				dimensions: 'date',
				compareDateRanges: true,
			},
			priority: 1,
			maxAge: getTimeInSeconds( 'day' ),
			context: 'Single',
		},
	],
	<PreviewBlock width="100%" height="270px" padding />,
	{ createGrid: true }
);
<|endoftext|>