<commit_before>import SPELLS from 'common/SPELLS';

/*
 * Fields:
 * int: spell scales with Intellect
 * crit: spell scales with (is able to or procced from) Critical Strike
 * hasteHpm: spell does more healing due to Haste, e.g. HoTs that gain more ticks
 * hasteHpct: spell can be cast more frequently due to Haste, basically any spell except for non haste scaling CDs
 * mastery: spell is boosted by Mastery
 * masteryStack: spell's HoT counts as a Mastery Stack
 * vers: spell scales with Versatility
 * multiplier: spell scales with whatever procs it, should be ignored for purpose of weights and for 'total healing' number
 * ignored: spell should be ignored for purpose of stat weights
 */

// This only works with actual healing events; casts are not recognized.

export default {
  [SPELLS.ENVELOPING_MIST.id]: {
    int: true,
    crit: true,
    hasteHpm: true,
    hasteHpct: true,
    mastery: false, //Procs Gusts
    vers: true,
  },
  [SPELLS.ENVELOPING_MIST_TFT.id]: { // Instant Heal when using TFT-> Enveloping Mist
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.ESSENCE_FONT.id]: {
    int: true,
    crit: true,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.ESSENCE_FONT_BUFF.id]: {
    int: true,
    crit: true,
    hasteHpm: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.RENEWING_MIST_HEAL.id]: {
    int: true,
    crit: true,
    hasteHpm: true,
    hasteHpct: false,
    mastery: false, // Procs Gusts
    vers: true,
  },
  [SPELLS.VIVIFY.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false, // Procs Gusts
    vers: true,
  },
  [SPELLS.CHI_BURST_HEAL.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.GUSTS_OF_MISTS.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: true, // Procs Gusts
    vers: false,
  },
  [SPELLS.SOOTHING_MIST.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.REFRESHING_JADE_WIND_HEAL.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.REVIVAL.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.LIFE_COCOON.id]: {
    int: true,
    crit: false,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.RISING_MIST_HEAL.id]: { // t100 trait
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.HEALING_ELIXIR_TALENT.id]: { // t75 trait
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.SOOTHING_MIST_STATUE.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.ANCIENT_TEACHINGS_OF_THE_MONASTERY_HEAL.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.GUST_OF_MISTS_CHIJI.id]: { // Chi-ji's gusts
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: true,
    vers: true,
  },
  [SPELLS.SOOTHING_BREATH.id]: { //Yu'lon's healing
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.ENVELOPING_BREATH.id]: {
    int: true,
    crit: true,
    hasteHpm: true,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.EXPEL_HARM.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.TEAR_OF_MORNING_HEAL.id]: {
    int: true,
    crit: true,
    hasteHpm: true,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.FALLEN_ORDER_ENVELOPING_MIST.id]: {
    int: true,
    crit: true,
    hasteHpm: true,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.FALLEN_ORDER_SOOTHING_MIST.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.FAELINE_STOMP_HEAL.id]: {
    int: true,
    crit: true,
    hasteHpm: true,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.FAELINE_STOMP_ESSENCE_FONT]: {
    int: true,
    crit: true,
    hasteHpm: true,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.WEAPONS_OF_ORDER_BUFF_AND_HEAL.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.BONEDUST_BREW_HEAL.id]: {
    int: true,
    crit: false,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.BONEDUST_BREW_GUST_OF_MIST.id]: {
    int: true,
    crit: false,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
};
<commit_msg>Anom said change it so here we are<commit_after>import SPELLS from 'common/SPELLS';

/*
 * Fields:
 * int: spell scales with Intellect
 * crit: spell scales with (is able to or procced from) Critical Strike
 * hasteHpm: spell does more healing due to Haste, e.g. HoTs that gain more ticks
 * hasteHpct: spell can be cast more frequently due to Haste, basically any spell except for non haste scaling CDs
 * mastery: spell is boosted by Mastery
 * masteryStack: spell's HoT counts as a Mastery Stack
 * vers: spell scales with Versatility
 * multiplier: spell scales with whatever procs it, should be ignored for purpose of weights and for 'total healing' number
 * ignored: spell should be ignored for purpose of stat weights
 */

// This only works with actual healing events; casts are not recognized.

export default {
  [SPELLS.ENVELOPING_MIST.id]: {
    int: true,
    crit: true,
    hasteHpm: true,
    hasteHpct: true,
    mastery: false, //Procs Gusts
    vers: true,
  },
  [SPELLS.ENVELOPING_MIST_TFT.id]: { // Instant Heal when using TFT-> Enveloping Mist
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.ESSENCE_FONT.id]: {
    int: true,
    crit: true,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.ESSENCE_FONT_BUFF.id]: {
    int: true,
    crit: true,
    hasteHpm: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.RENEWING_MIST_HEAL.id]: {
    int: true,
    crit: true,
    hasteHpm: true,
    hasteHpct: false,
    mastery: false, // Procs Gusts
    vers: true,
  },
  [SPELLS.VIVIFY.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false, // Procs Gusts
    vers: true,
  },
  [SPELLS.CHI_BURST_HEAL.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.GUSTS_OF_MISTS.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: true, // Procs Gusts
    vers: false,
  },
  [SPELLS.SOOTHING_MIST.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.REFRESHING_JADE_WIND_HEAL.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.REVIVAL.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.LIFE_COCOON.id]: {
    int: true,
    crit: false,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.RISING_MIST_HEAL.id]: { // t100 trait
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.HEALING_ELIXIR_TALENT.id]: { // t75 trait
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.SOOTHING_MIST_STATUE.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.ANCIENT_TEACHINGS_OF_THE_MONASTERY_HEAL.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.GUST_OF_MISTS_CHIJI.id]: { // Chi-ji's gusts
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: true,
    vers: true,
  },
  [SPELLS.SOOTHING_BREATH.id]: { //Yu'lon's healing
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.ENVELOPING_BREATH.id]: {
    int: true,
    crit: true,
    hasteHpm: true,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.EXPEL_HARM.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.TEAR_OF_MORNING_HEAL.id]: {
    int: false,
    crit: false,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: false,
  },
  [SPELLS.FALLEN_ORDER_ENVELOPING_MIST.id]: {
    int: true,
    crit: true,
    hasteHpm: true,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.FALLEN_ORDER_SOOTHING_MIST.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: true,
    mastery: false,
    vers: true,
  },
  [SPELLS.FAELINE_STOMP_HEAL.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.FAELINE_STOMP_ESSENCE_FONT]: {
    int: true,
    crit: true,
    hasteHpm: true,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.WEAPONS_OF_ORDER_BUFF_AND_HEAL.id]: {
    int: true,
    crit: true,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.BONEDUST_BREW_HEAL.id]: {
    int: true,
    crit: false,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
  [SPELLS.BONEDUST_BREW_GUST_OF_MIST.id]: {
    int: true,
    crit: false,
    hasteHpm: false,
    hasteHpct: false,
    mastery: false,
    vers: true,
  },
};
<|endoftext|>


<commit_before>
(function (IPython, $, _, MathJax) {
    $.event.special.destroyed = {
	remove: function(o) {
	    if (o.handler) {
		o.handler.apply(this, arguments)
	    }
	}
    }

    var OutputArea = IPython.version >= "4.0.0" ? require("notebook/js/outputarea").OutputArea : IPython.OutputArea;

    var redrawValue = function (container, type, val) {
	var selector = $("<div/>");
	var oa = new OutputArea(_.extend(selector, {
	    selector: selector,
	    prompt_area: true,
	    events: IPython.events,
	    keyboard_manager: IPython.keyboard_manager
	})); // Hack to work with IPython 2.1.0

	switch (type) {
	case "image/png":
            var _src = 'data:' + type + ';base64,' + val;
	    $(container).find("img").attr('src', _src);
	    break;
	default:
	    var toinsert = OutputArea.append_map[type].apply(
		oa, [val, {}, selector]
	    );
	    $(container).empty().append(toinsert.contents());
	    selector.remove();
	}
	if (type === "text/latex" && MathJax) {
	    MathJax.Hub.Queue(["Typeset", MathJax.Hub, toinsert.get(0)]);
	}
    }

    $(document).ready(function() {
	function initComm(evt, data) {
	    var comm_manager = data.kernel.comm_manager;
        //_.extend(comm_manager.targets, require("widgets/js/widget"))
	    comm_manager.register_target("Signal", function (comm) {
            comm.on_msg(function (msg) {
                //Widgets.log("message received", msg);
                var val = msg.content.data.value;
                $(".signal-" + comm.comm_id).each(function() {
                var type = $(this).data("type");
                if (val[type]) {
                    redrawValue(this, type, val[type], type);
                }
                });
                delete val;
                delete msg.content.data.value;
            });
	    });

	    // coordingate with Comm and redraw Signals
	    // XXX: Test using Reactive here to improve performance
	    $([IPython.events]).on(
		'output_appended.OutputArea', function (event, type, value, md, toinsert) {
		    if (md && md.reactive) {
                // console.log(md.comm_id);
                toinsert.addClass("signal-" + md.comm_id);
                toinsert.data("type", type);
                // Signal back indicating the mimetype required
                var comm_manager = IPython.notebook.kernel.comm_manager;
                var comm = comm_manager.comms[md.comm_id];
                comm.then(function (c) {
                    c.send({action: "subscribe_mime",
                       mime: type});
                    toinsert.bind("destroyed", function() {
                        c.send({action: "unsubscribe_mime",
                               mime: type});
                    });
                })
		    }
	    });
	}

	try {
	    // try to initialize right away. otherwise, wait on the status_started event.
	    initComm(undefined, IPython.notebook);
	} catch (e) {
	    $([IPython.events]).on('kernel_created.Kernel kernel_created.Session', initComm);
	}
    });
})(IPython, jQuery, _, MathJax);
<commit_msg>Enables updating plain text output with empty string<commit_after>
(function (IPython, $, _, MathJax) {
    $.event.special.destroyed = {
	remove: function(o) {
	    if (o.handler) {
		o.handler.apply(this, arguments)
	    }
	}
    }

    var OutputArea = IPython.version >= "4.0.0" ? require("notebook/js/outputarea").OutputArea : IPython.OutputArea;

    var redrawValue = function (container, type, val) {
	var selector = $("<div/>");
	var oa = new OutputArea(_.extend(selector, {
	    selector: selector,
	    prompt_area: true,
	    events: IPython.events,
	    keyboard_manager: IPython.keyboard_manager
	})); // Hack to work with IPython 2.1.0

	switch (type) {
	case "image/png":
            var _src = 'data:' + type + ';base64,' + val;
	    $(container).find("img").attr('src', _src);
	    break;
	default:
	    var toinsert = OutputArea.append_map[type].apply(
		oa, [val, {}, selector]
	    );
	    $(container).empty().append(toinsert.contents());
	    selector.remove();
	}
	if (type === "text/latex" && MathJax) {
	    MathJax.Hub.Queue(["Typeset", MathJax.Hub, toinsert.get(0)]);
	}
    }

    $(document).ready(function() {
	function initComm(evt, data) {
	    var comm_manager = data.kernel.comm_manager;
        //_.extend(comm_manager.targets, require("widgets/js/widget"))
	    comm_manager.register_target("Signal", function (comm) {
            comm.on_msg(function (msg) {
                var val = msg.content.data.value;
                $(".signal-" + comm.comm_id).each(function() {
                var type = $(this).data("type");
                if (typeof(val[type]) !== "underfined" && val[type] !== null) {
                    redrawValue(this, type, val[type], type);
                }
                });
                delete val;
                delete msg.content.data.value;
            });
	    });

	    // coordingate with Comm and redraw Signals
	    // XXX: Test using Reactive here to improve performance
	    $([IPython.events]).on(
		'output_appended.OutputArea', function (event, type, value, md, toinsert) {
		    if (md && md.reactive) {
                // console.log(md.comm_id);
                toinsert.addClass("signal-" + md.comm_id);
                toinsert.data("type", type);
                // Signal back indicating the mimetype required
                var comm_manager = IPython.notebook.kernel.comm_manager;
                var comm = comm_manager.comms[md.comm_id];
                comm.then(function (c) {
                    c.send({action: "subscribe_mime",
                       mime: type});
                    toinsert.bind("destroyed", function() {
                        c.send({action: "unsubscribe_mime",
                               mime: type});
                    });
                })
		    }
	    });
	}

	try {
	    // try to initialize right away. otherwise, wait on the status_started event.
	    initComm(undefined, IPython.notebook);
	} catch (e) {
	    $([IPython.events]).on('kernel_created.Kernel kernel_created.Session', initComm);
	}
    });
})(IPython, jQuery, _, MathJax);
<|endoftext|>


<commit_before>import { retrieveData, insertData } from '../network'
import { Link } from '../../children'

/**
 * Retrieve Allocations for a specific Transaction
 * @function retrieve
 * @memberof module:Allocations
 * @static
 * @param {object} params - object of parameters:
 * @param {number} params.AMId - Asset Manager ID of Transaction
 * @param {string} params.resourceId - Transaction ID
 * @param {string} params.token - Authorization token
 */
export function retrieve({ AMId, resourceId, token }, callback) {
  if (!AMId || !resourceId) {
    throw new Error('Asset Manager ID and Transaction ID are required for allocations')
  }
  const params = {
    AMaaSClass: 'allocations',
    AMId,
    resourceId,
    token
  }
  let promise = retrieveData(params).then(result => {
    const allocations = result.map(link => {
      return new Link(link)
    })
    if (typeof callback === 'function') {
      callback(null, allocations)
    }
    return allocations
  })
  if (typeof callback !== 'function') {
    return promise
  }
  promise.catch(error => callback(error))
}

/**
 * Send Allocations for a specific Transaction
 * @memberof module:Allocations
 * @function send
 * @memberof module:Allocations
 * @static
 * @param {object} params - object of parameters:
 * @param {number} params.AMId - Asset Manager ID of Transaction
 * @param {string} params.resourceId - Transaction ID
 * @param {object} params.data - Allocation data for the Transaction of the form [ { book_id: '123', quantity: '50', transaction_id: 'XYZ' }, { book_id: '456', quantity: '50', transaction_id: 'ABC' } ]
   If transaction_id is given, the new Transaction that is created will have this as ID.
 * @param {string} params.token - Authorization token
 */
export function send({ AMId, resourceId, data, token }, callback) {
  if (!AMId || !resourceId) {
    throw new Error('Asset Manager ID and Transaction ID are required for allocations')
  }
  const params = {
    AMaaSClass: 'allocations',
    AMId,
    resourceId,
    data,
    token
  }
  let promise = insertData(params).then(result => {
    const allocated = result
    if (typeof callback === 'function') {
      callback(null, allocated)
    }
    return allocated
  })
  if (typeof callback !== 'function') {
    return promise
  }
  promise.catch(error => callback(error))
}
<commit_msg>Separate api from classes.<commit_after>import { retrieveData, insertData } from '../network'
import { Link } from '../../children'

/**
 * @namespace api
 * @memberof module:Allocations
 */

/**
 * Retrieve Allocations for a specific Transaction
 * @function retrieve
 * @memberof module:Allocations.api
 * @static
 * @param {object} params - object of parameters:
 * @param {number} params.AMId - Asset Manager ID of Transaction
 * @param {string} params.resourceId - Transaction ID
 * @param {string} params.token - Authorization token
 */
export function retrieve({ AMId, resourceId, token }, callback) {
  if (!AMId || !resourceId) {
    throw new Error('Asset Manager ID and Transaction ID are required for allocations')
  }
  const params = {
    AMaaSClass: 'allocations',
    AMId,
    resourceId,
    token
  }
  let promise = retrieveData(params).then(result => {
    const allocations = result.map(link => {
      return new Link(link)
    })
    if (typeof callback === 'function') {
      callback(null, allocations)
    }
    return allocations
  })
  if (typeof callback !== 'function') {
    return promise
  }
  promise.catch(error => callback(error))
}

/**
 * Send Allocations for a specific Transaction
 * @function send
 * @memberof module:Allocations.api
 * @static
 * @param {object} params - object of parameters:
 * @param {number} params.AMId - Asset Manager ID of Transaction
 * @param {string} params.resourceId - Transaction ID
 * @param {object} params.data - Allocation data for the Transaction of the form [ { book_id: '123', quantity: '50', transaction_id: 'XYZ' }, { book_id: '456', quantity: '50', transaction_id: 'ABC' } ]
   If transaction_id is given, the new Transaction that is created will have this as ID.
 * @param {string} params.token - Authorization token
 */
export function send({ AMId, resourceId, data, token }, callback) {
  if (!AMId || !resourceId) {
    throw new Error('Asset Manager ID and Transaction ID are required for allocations')
  }
  const params = {
    AMaaSClass: 'allocations',
    AMId,
    resourceId,
    data,
    token
  }
  let promise = insertData(params).then(result => {
    const allocated = result
    if (typeof callback === 'function') {
      callback(null, allocated)
    }
    return allocated
  })
  if (typeof callback !== 'function') {
    return promise
  }
  promise.catch(error => callback(error))
}
<|endoftext|>


<commit_before>var Path = nodeRequire('path');

var _ = require('underscore');
var Files = require('../files');
var beautify = require('js-beautify').js_beautify;
var beautify_css = require('js-beautify').css;
var beautify_html = require('js-beautify').html;
var ace = require('brace');

require('brace/mode/html');
require('brace/mode/javascript');
require('brace/mode/css');
require('brace/mode/json');
require('brace/mode/text');
require('brace/theme/tomorrow');
require('brace/ext/searchbox');

var modes = {
  ".html": "html",
  ".htm": "html",
  ".js": "javascript",
  ".css": "css",
  ".json": "json",
  ".txt": "text"
};

module.exports = {
  template: require('./template.html'),

  data: {
    newProject: true
  },

  ready: function() {
    this.sessions = [];

    this.$on('open-file', this.openFile);
    this.$on('close-file', this.closeFile);
    this.$on('save-project-as', this.saveProjectAs);
    this.$on('reformat', this.reformat);
    this.$on('settings-changed', this.updateSettings);

    this.ace = window.ace = ace.edit('editor');
    this.ace.setTheme('ace/theme/tomorrow');
    this.ace.setReadOnly(true);
    // this.ace.$worker.send("changeOptions", [{asi: false}]);

    this.customizeCommands();
  },

  methods: {
    openFile: function(fileObject) {
      var session = _.findWhere(this.sessions, {path: fileObject.path});
      if (!session) {
        var doc = ace.createEditSession(fileObject.contents, "ace/mode/" + modes[fileObject.ext]);

        var self = this;
        doc.on('change', function() {
          var file = Files.find(self.$root.files, fileObject.path);
          if (file) file.contents = doc.getValue();
        });

        var session = {
          path: fileObject.path,
          doc: doc
        };

        this.sessions.push(session);
      }

      this.ace.setReadOnly(false);
      this.ace.setSession(session.doc);
      this.updateSettings(this.$root.settings);
      this.ace.focus();

      if (this.newProject) {
        this.ace.gotoLine(2, 2);
        this.newProject = false;
      }
    },

    closeFile: function(fileObject){
      var session = _.findWhere(this.sessions, {path: fileObject.path});
      if(session){
        var index = _.indexOf(this.sessions, session);
        this.sessions.splice(index,1);
      }
    },

    saveProjectAs: function(path) {
      this.sessions.forEach(function(session) {
        session.path = Path.join(path, Path.basename(session.path));
      });
    },

    reformat: function() {
      var ext = this.$root.currentFile.ext;
      var content = this.ace.getValue();
      var opts = {
        "indent_size": this.$root.settings.tabSize,
        "indent_with_tabs": this.$root.settings.tabType === 'tabs',
      };

      var pos = this.ace.getCursorPosition();
      var scrollPos = this.ace.getSession().getScrollTop();

      if (ext == '.js') {
        this.ace.setValue(beautify(content, opts), -1);
      } else if (ext == '.css') {
        this.ace.setValue(beautify_css(content, opts), -1);
      } else if (ext == '.html') {
        this.ace.setValue(beautify_html(content, opts), -1);
      }

      this.ace.moveCursorToPosition(pos);
      this.ace.getSession().setScrollTop(scrollPos);
    },

    updateSettings: function(settings) {
      this.ace.getSession().setTabSize(settings.tabSize);
      this.ace.getSession().setUseSoftTabs(settings.tabType === 'spaces');
      this.ace.getSession().setUseWrapMode(settings.wordWrap === true);
    },

    customizeCommands: function() {
      var self = this;

      var commands = [{
        name: "blockoutdent",
        bindKey: {win: 'Ctrl-[,',  mac: 'Command-['},
        exec: function(editor) { editor.blockOutdent(); },
        multiSelectAction: "forEachLine",
        scrollIntoView: "selectionPart"
      }, {
        name: "blockindent",
        bindKey: {win: 'Ctrl-],',  mac: 'Command-]'},
        exec: function(editor) { editor.blockIndent(); },
        multiSelectAction: "forEachLine",
        scrollIntoView: "selectionPart"
      }, {
        name: 'Preferences',
        bindKey: {win: 'Ctrl-,',  mac: 'Command-,'},
        exec: function(editor) {
          self.$root.toggleSettingsPane();
        }
      }];

      commands.forEach(function(command){
        this.ace.commands.addCommand(command);
      });

    }

  }
};
<commit_msg>color<commit_after>var Path = nodeRequire('path');

var _ = require('underscore');
var Files = require('../files');
var beautify = require('js-beautify').js_beautify;
var beautify_css = require('js-beautify').css;
var beautify_html = require('js-beautify').html;
var ace = require('brace');

require('brace/mode/html');
require('brace/mode/javascript');
require('brace/mode/css');
require('brace/mode/json');
require('brace/mode/text');
require('brace/theme/tomorrow');
require('brace/ext/searchbox');

var modes = {
  ".html": "html",
  ".htm": "html",
  ".js": "javascript",
  ".css": "css",
  ".json": "json",
  ".txt": "text"
};

module.exports = {
  template: require('./template.html'),

  data: {
    newProject: true
  },

  ready: function() {
    this.sessions = [];

    this.$on('open-file', this.openFile);
    this.$on('close-file', this.closeFile);
    this.$on('save-project-as', this.saveProjectAs);
    this.$on('reformat', this.reformat);
    this.$on('settings-changed', this.updateSettings);

    this.ace = window.ace = ace.edit('editor');
    //this.ace.setTheme('ace/theme/tomorrow');
    this.ace.setReadOnly(true);
    // this.ace.$worker.send("changeOptions", [{asi: false}]);

    this.customizeCommands();
  },

  methods: {
    openFile: function(fileObject) {
      var session = _.findWhere(this.sessions, {path: fileObject.path});
      if (!session) {
        var doc = ace.createEditSession(fileObject.contents, "ace/mode/" + modes[fileObject.ext]);

        var self = this;
        doc.on('change', function() {
          var file = Files.find(self.$root.files, fileObject.path);
          if (file) file.contents = doc.getValue();
        });

        var session = {
          path: fileObject.path,
          doc: doc
        };

        this.sessions.push(session);
      }

      this.ace.setReadOnly(false);
      this.ace.setSession(session.doc);
      this.updateSettings(this.$root.settings);
      this.ace.focus();

      if (this.newProject) {
        this.ace.gotoLine(2, 2);
        this.newProject = false;
      }
    },

    closeFile: function(fileObject){
      var session = _.findWhere(this.sessions, {path: fileObject.path});
      if(session){
        var index = _.indexOf(this.sessions, session);
        this.sessions.splice(index,1);
      }
    },

    saveProjectAs: function(path) {
      this.sessions.forEach(function(session) {
        session.path = Path.join(path, Path.basename(session.path));
      });
    },

    reformat: function() {
      var ext = this.$root.currentFile.ext;
      var content = this.ace.getValue();
      var opts = {
        "indent_size": this.$root.settings.tabSize,
        "indent_with_tabs": this.$root.settings.tabType === 'tabs',
      };

      var pos = this.ace.getCursorPosition();
      var scrollPos = this.ace.getSession().getScrollTop();

      if (ext == '.js') {
        this.ace.setValue(beautify(content, opts), -1);
      } else if (ext == '.css') {
        this.ace.setValue(beautify_css(content, opts), -1);
      } else if (ext == '.html') {
        this.ace.setValue(beautify_html(content, opts), -1);
      }

      this.ace.moveCursorToPosition(pos);
      this.ace.getSession().setScrollTop(scrollPos);
    },

    updateSettings: function(settings) {
      this.ace.getSession().setTabSize(settings.tabSize);
      this.ace.getSession().setUseSoftTabs(settings.tabType === 'spaces');
      this.ace.getSession().setUseWrapMode(settings.wordWrap === true);
    },

    customizeCommands: function() {
      var self = this;

      var commands = [{
        name: "blockoutdent",
        bindKey: {win: 'Ctrl-[,',  mac: 'Command-['},
        exec: function(editor) { editor.blockOutdent(); },
        multiSelectAction: "forEachLine",
        scrollIntoView: "selectionPart"
      }, {
        name: "blockindent",
        bindKey: {win: 'Ctrl-],',  mac: 'Command-]'},
        exec: function(editor) { editor.blockIndent(); },
        multiSelectAction: "forEachLine",
        scrollIntoView: "selectionPart"
      }, {
        name: 'Preferences',
        bindKey: {win: 'Ctrl-,',  mac: 'Command-,'},
        exec: function(editor) {
          self.$root.toggleSettingsPane();
        }
      }];

      commands.forEach(function(command){
        this.ace.commands.addCommand(command);
      });

    }

  }
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 */
'use strict';

const { Cu } = require('chrome');
const { gDevTools } = Cu.import('resource:///modules/devtools/gDevTools.jsm', {});

/**
 * Whenever the devtools inspector panel selection changes, pass that node to
 * __REACT_DEVTOOLS_GLOBAL_HOOK__.$0
 */
function trackSelection() {
  var wc;
  gDevTools.on('webconsole-init', function(_, toolbox, panelFrame) {
    toolbox.once('webconsole-ready', (eid, panel) => {
      wc = panel;
    });
  });

  gDevTools.on('inspector-init', (_, toolbox, panelFrame) => {
    toolbox.once('inspector-ready', (eid, panel) => {
      panel.selection.on('new-node-front', (ev, val, reason) => {
        passSelectedNode(wc.hud.ui.jsterm);
      });
    });
  });
}

function passSelectedNode(jsterm) {
  const inspectorSelection = jsterm.hud.owner.getInspectorSelection();
  let selectedNodeActor = null;
  if (inspectorSelection && inspectorSelection.nodeFront) {
    selectedNodeActor = inspectorSelection.nodeFront.actorID;
    jsterm.requestEvaluation('__REACT_DEVTOOLS_GLOBAL_HOOK__.reactDevtoolsAgent.selectFromDOMNode($0, true)', {
      selectedNodeActor: selectedNodeActor,
    });
  }
}

exports.trackSelection = trackSelection;
<commit_msg>Update Firefox shell for path change in Firefox 44 and later<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 */
'use strict';

const { Cu } = require('chrome');

// The path to this file was moved in Firefox 44 and later.
// See https://bugzil.la/912121 for more details.
let gDevTools;
try {
  ({ gDevTools } = Cu.import('resource:///modules/devtools/client/framework/' +
                             'gDevTools.jsm', {}));
} catch (e) {
  ({ gDevTools } = Cu.import('resource:///modules/devtools/gDevTools.jsm', {}));
}

/**
 * Whenever the devtools inspector panel selection changes, pass that node to
 * __REACT_DEVTOOLS_GLOBAL_HOOK__.$0
 */
function trackSelection() {
  var wc;
  gDevTools.on('webconsole-init', function(_, toolbox, panelFrame) {
    toolbox.once('webconsole-ready', (eid, panel) => {
      wc = panel;
    });
  });

  gDevTools.on('inspector-init', (_, toolbox, panelFrame) => {
    toolbox.once('inspector-ready', (eid, panel) => {
      panel.selection.on('new-node-front', (ev, val, reason) => {
        passSelectedNode(wc.hud.ui.jsterm);
      });
    });
  });
}

function passSelectedNode(jsterm) {
  const inspectorSelection = jsterm.hud.owner.getInspectorSelection();
  let selectedNodeActor = null;
  if (inspectorSelection && inspectorSelection.nodeFront) {
    selectedNodeActor = inspectorSelection.nodeFront.actorID;
    jsterm.requestEvaluation('__REACT_DEVTOOLS_GLOBAL_HOOK__.reactDevtoolsAgent.selectFromDOMNode($0, true)', {
      selectedNodeActor: selectedNodeActor,
    });
  }
}

exports.trackSelection = trackSelection;
<|endoftext|>


<commit_before>(function() {
  if (location.hostname === 'localhost') {
    console.log('service worker disabled on localhost');
    return;
  }
  if(!('serviceWorker' in navigator)) {
    console.log('service worker not supported');
    return;
  }
  navigator.serviceWorker.register('./sw.js').then(function(registration) {
    // Registration was successful 😊
    console.log('ServiceWorker registration successful with scope: ',
      registration.scope);
  }).catch(function(err) {
    // registration failed :(
    console.log('ServiceWorker registration failed: ', err);
  });
})();
<commit_msg>allow service worker to be installed with query param<commit_after>(function() {
  let queryParams = new Map(location.search.slice(1).split("&").map(t=>t.split("=")));
  if (location.hostname === 'localhost' && queryParams.get("sw") !== "test") {
    console.log('service worker disabled on localhost');
    return;
  }
  if(!('serviceWorker' in navigator)) {
    console.log('service worker not supported');
    return;
  }
  navigator.serviceWorker.register('./sw.js').then(function(registration) {
    // Registration was successful 😊
    console.log('ServiceWorker registration successful with scope: ',
      registration.scope);
  }).catch(function(err) {
    // registration failed :(
    console.log('ServiceWorker registration failed: ', err);
  });
})();
<|endoftext|>


<commit_before>/*
 * node-pandoc
 *
 * This is the main, and currently only, file. It wraps the `pandoc` command
 * using node's child_process module. Since we still have to support node 0.4.x
 * (latest stable) we have to use spawn instead of fork().
 */

var spawn = require('child_process').spawn;

// The global command line args for pandocs.
var globalArgs = {
  //what the user provided
  provided: null,

  //whether to persist between convert() calls
  persist: false,

  //resets back to defaults
  reset: function() {
    this.provided = null;
    this.persist = false;
  }
};

/*
 * type is the input markup's type
 *
 * input is the input markup
 *
 * types is an array of markup types to convert to or a single type as a string
 *
 * callback will be passed an object mapping markup type to markup, unless
 * there was an error in which case it gets passed (null, statusCode)
 */
exports.convert = function(type, input, types, callback) {
  var res = {};
  var numResponses = 0;
  var targetResponses;

  var pandoc;
  var args;

  var i;

  if(!type || typeof type !== 'string') {
    throw 'Invalid source markup type: must be a string.';
  }

  if(!input || typeof input !== 'string') {
    throw 'Invalid markup type: must be a string.';
  }

  if(typeof types !== 'string' && !Array.isArray(types)) {
    throw 'Invalid destination types: must be a string or an array of strings.';
  }

  if(types.length <= 0) {
    throw 'No destination types provided (empty array).';
  }

  if(typeof callback !== 'function') {
    if(callback) {
      throw 'Invalid callback provided: must be a function.';
    }
    else {
      throw 'No callback provided: must be a function.';
    }
  }

  //what we're going to send to the callback if there are no pandoc errors
  res[type] = input;

  if(typeof types === 'string') {
    types = [ types ];
  }

  targetResponses = types.length;

  for(i in types) {
    if(types.hasOwnProperty(i)) {
      if(typeof types[i] !== 'string') {
        throw 'Invalid destination type provided: non-string value found in array.';
      }

      /*
       * This if-block filters out the target markup type because we already set
       * it on the res object.
       */
      if(!res[types[i]]) {
        args = globalArgs.provided || [];
        args.push('-f', type, '-t', types[i]);

        pandoc = spawn('pandoc', args);

        //so that we have the target type in scope on('data') - love ya some asynch
        pandoc.stdout.targetType = types[i];

        pandoc.stdout.on('data', function(data) {
          //data will be a binary stream if you don't cast it to a string
          res[this.targetType] = data + '';
        });

        pandoc.on('exit', function(code, signal) {
          numResponses++;

          if(code !== 0) {
            callback(null, code);
          }
          else if(numResponses === targetResponses) {
            callback(res);
          }
        });

        //pipe them the input
        pandoc.stdin.write(input, 'utf8');
        pandoc.stdin.end();

        if(!globalArgs.persist) {
          globalArgs.reset();
        }
      }
    }
  }
};

/*
 * args is an array of command line arguments that should be passed to pandoc
 * on the next call. If set to a non-array value, then default args will be
 * used. The default behavior is that they will be thrown away before the next
 * call.
 *
 * persist is a boolean that when set to true will persist the provided args
 * for future calls.
 *
 * Returns this module so you can chain this funciton with convert().
 */
exports.args = function(args, persist) {
  if(Array.isArray(args)) {
    globalArgs.provided = args;
    globalArgs.persist = persist;
  }
  else {
    globalArgs.reset();
  }

  return exports;
};
<commit_msg>Call callback on process close<commit_after>/*
 * node-pandoc
 *
 * This is the main, and currently only, file. It wraps the `pandoc` command
 * using node's child_process module. Since we still have to support node 0.4.x
 * (latest stable) we have to use spawn instead of fork().
 */

var spawn = require('child_process').spawn;

// The global command line args for pandocs.
var globalArgs = {
  //what the user provided
  provided: null,

  //whether to persist between convert() calls
  persist: false,

  //resets back to defaults
  reset: function() {
    this.provided = null;
    this.persist = false;
  }
};

/*
 * type is the input markup's type
 *
 * input is the input markup
 *
 * types is an array of markup types to convert to or a single type as a string
 *
 * callback will be passed an object mapping markup type to markup, unless
 * there was an error in which case it gets passed (null, statusCode)
 */
exports.convert = function(type, input, types, callback) {
  var res = {};
  var numResponses = 0;
  var targetResponses;

  var pandoc;
  var args;

  var i;

  if(!type || typeof type !== 'string') {
    throw 'Invalid source markup type: must be a string.';
  }

  if(!input || typeof input !== 'string') {
    throw 'Invalid markup type: must be a string.';
  }

  if(typeof types !== 'string' && !Array.isArray(types)) {
    throw 'Invalid destination types: must be a string or an array of strings.';
  }

  if(types.length <= 0) {
    throw 'No destination types provided (empty array).';
  }

  if(typeof callback !== 'function') {
    if(callback) {
      throw 'Invalid callback provided: must be a function.';
    }
    else {
      throw 'No callback provided: must be a function.';
    }
  }

  //what we're going to send to the callback if there are no pandoc errors
  res[type] = input;

  if(typeof types === 'string') {
    types = [ types ];
  }

  targetResponses = types.length;

  for(i in types) {
    if(types.hasOwnProperty(i)) {
      if(typeof types[i] !== 'string') {
        throw 'Invalid destination type provided: non-string value found in array.';
      }

      /*
       * This if-block filters out the target markup type because we already set
       * it on the res object.
       */
      if(!res[types[i]]) {
        args = globalArgs.provided || [];
        args.push('-f', type, '-t', types[i]);

        pandoc = spawn('pandoc', args);

        //so that we have the target type in scope on('data') - love ya some asynch
        pandoc.stdout.targetType = types[i];

        pandoc.stdout.on('data', function(data) {
          //data will be a binary stream if you don't cast it to a string
          res[this.targetType] = data + '';
        });

        // catch errors
        pandoc.on('error', function(err) {
          callback(null, err);
        });

        // wait for close, so that I/O is flushed before returning the results
        pandoc.on('close', function(code, signal) {
          numResponses++;

          if(code !== 0) {
            callback(null, code);
          }
          else if(numResponses === targetResponses) {
            callback(res);
          }
        });

        //pipe them the input
        pandoc.stdin.write(input, 'utf8');
        pandoc.stdin.end();

        if(!globalArgs.persist) {
          globalArgs.reset();
        }
      }
    }
  }
};

/*
 * args is an array of command line arguments that should be passed to pandoc
 * on the next call. If set to a non-array value, then default args will be
 * used. The default behavior is that they will be thrown away before the next
 * call.
 *
 * persist is a boolean that when set to true will persist the provided args
 * for future calls.
 *
 * Returns this module so you can chain this funciton with convert().
 */
exports.args = function(args, persist) {
  if(Array.isArray(args)) {
    globalArgs.provided = args;
    globalArgs.persist = persist;
  }
  else {
    globalArgs.reset();
  }

  return exports;
};
<|endoftext|>


<commit_before>PDFDocument = require('pdfkit');
const os = require('os');
const path = require('path');

const dialog = require('electron').remote.dialog;

module.exports.exportPdf = function(questions, question_set_name, showAnswers) {
	dialog.showSaveDialog(function(fileName) {
		if (fileName === undefined) return;
		doc = new PDFDocument();
		doc.pipe(fs.createWriteStream(fileName));

		let text = ''
		questions.forEach(function(question, qIndex) {
			doc.text(`Q-${qIndex+1} [${question.question_point} pts] ${question.question_text}\n\n`);
			question.options.forEach(function(option, oIndex) {
				if (question.question_type === "text") {
					if (showAnswers) {
						doc.text(`Answer:\n${option.context}`);
					} else {
						doc.text("\n\n\n\n\n\n");
					}
				} else if (question.question_type === "multiple") {
					doc.text(`${String.fromCharCode(97 + oIndex)}) ${option.context} \n`);
				} else if (question.question_type === "image") {
					if (showAnswers) {
						doc.text("\n");
						doc.image(option.image_path,{width:300});
					} else {
						doc.text("\n\n\n\n\n\n");
					}
				}
			});

			if (showAnswers && question.question_type === "multiple") {
				doc.text("\nAnswer: \n");
				question.options.forEach(function(option, oIndex) {
					if (option.is_correct) {
						if (oIndex === question.options.length - 2) {
							doc.text(`${String.fromCharCode(97 + oIndex)}) and `);
						} else {
							doc.text(`${String.fromCharCode(97 + oIndex)})  `);
						}
					}
				});
			}
			doc.text("\n\n");
		});

		doc.end()
	});
};
<commit_msg>fix pdf answers<commit_after>PDFDocument = require('pdfkit');
const os = require('os');
const path = require('path');

const dialog = require('electron').remote.dialog;

module.exports.exportPdf = function(questions, question_set_name, showAnswers) {
	dialog.showSaveDialog(function(fileName) {
		if (fileName === undefined) return;
		doc = new PDFDocument();
		doc.pipe(fs.createWriteStream(fileName));

		let text = ''
		questions.forEach(function(question, qIndex) {
			doc.text(`Q-${qIndex+1} [${question.question_point} pts] ${question.question_text}\n\n`);
			question.options.forEach(function(option, oIndex) {
				if (question.question_type === "text") {
					if (showAnswers) {
						doc.text(`Answer:\n${option.context}`);
					} else {
						doc.text("\n\n\n\n\n\n");
					}
				} else if (question.question_type === "multiple") {
					doc.text(`${String.fromCharCode(97 + oIndex)}) ${option.context} \n`);
				} else if (question.question_type === "image") {
					if (showAnswers) {
						doc.text("\n");
						doc.image(option.image_path,{width:300});
					} else {
						doc.text("\n\n\n\n\n\n");
					}
				}
			});

			if (showAnswers && question.question_type === "multiple") {
				doc.text("\nAnswer: \n");

				let answers = question.options.filter(function(option) {
					return option.is_correct;
				});

				let answerText = "";
				question.options.forEach(function(option, oIndex) {
					if (option.is_correct) {
						if (answers.length > 1 && answers.indexOf(option) === answers.length - 2) {
							answerText += `${String.fromCharCode(97 + oIndex)}) and `;
						} else {
							answerText += `${String.fromCharCode(97 + oIndex)})  `;
						}
					}
				});

				doc.text(answerText);
			}
			doc.text("\n\n");
		});

		doc.end()
	});
};
<|endoftext|>


<commit_before>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React from 'react';
import PropTypes from 'prop-types';
import { StyleSheet } from 'react-native';
import { connect } from 'react-redux';

import { SearchBar } from '../SearchBar';
import { PageButton } from '../PageButton';
import { FlexRow } from '../FlexRow';
import { PrescriptionInfo } from '../PrescriptionInfo';
import { SimpleTable } from '../SimpleTable';

import { UIDatabase } from '../../database';
import { getColumns } from '../../pages/dataTableUtilities';
import { selectPrescriber } from '../../reducers/PrescriptionReducer';

/**
 * Layout component used for a tab within the prescription wizard.
 *
 * @props {Func} choosePrescriber   Callback for selecting a supplier.
 */
const PrescriberSelectComponent = ({ choosePrescriber }) => {
  const columns = getColumns('prescriberSelect');

  const tableRef = React.useRef(React.createRef());

  return (
    <>
      <PrescriptionInfo />
      <FlexRow>
        <SearchBar viewStyle={localStyles.searchBar} />
        <PageButton text="Add Prescriber" />
      </FlexRow>
      <SimpleTable
        data={UIDatabase.objects('Prescriber')}
        columns={columns}
        selectRow={choosePrescriber}
        ref={tableRef}
      />
    </>
  );
};

const localStyles = StyleSheet.create({
  searchBar: {
    borderBottomWidth: 1,
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
    flexGrow: 1,
  },
});

const mapDispatchToProps = dispatch => {
  const choosePrescriber = prescriberID => dispatch(selectPrescriber(prescriberID));

  return { choosePrescriber };
};

PrescriberSelectComponent.propTypes = { choosePrescriber: PropTypes.func.isRequired };

export const PrescriberSelect = connect(null, mapDispatchToProps)(PrescriberSelectComponent);
<commit_msg>Add update PrescriberSelect with searchTerm logic<commit_after>/* eslint-disable react/forbid-prop-types */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React from 'react';
import PropTypes from 'prop-types';
import { StyleSheet } from 'react-native';
import { connect } from 'react-redux';

import { SearchBar } from '../SearchBar';
import { PageButton } from '../PageButton';
import { FlexRow } from '../FlexRow';
import { PrescriptionInfo } from '../PrescriptionInfo';
import { SimpleTable } from '../SimpleTable';

import { UIDatabase } from '../../database';
import { getColumns } from '../../pages/dataTableUtilities';
import { selectPrescriber } from '../../reducers/PrescriptionReducer';
import { PrescriberActions } from '../../actions/PrescriberActions';

/**
 * Layout component used for a tab within the prescription wizard.
 *
 * @props {Func} choosePrescriber   Callback for selecting a supplier.
 */
const PrescriberSelectComponent = ({ choosePrescriber, data, onFilterData, searchTerm }) => {
  const columns = React.useMemo(() => getColumns('prescriberSelect'), []);

  return (
    <>
      <PrescriptionInfo />
      <FlexRow>
        <SearchBar
          viewStyle={localStyles.searchBar}
          onChangeText={onFilterData}
          value={searchTerm}
        />
        <PageButton text="Add Prescriber" />
      </FlexRow>
      <SimpleTable data={data} columns={columns} selectRow={choosePrescriber} />
    </>
  );
};

const localStyles = StyleSheet.create({
  searchBar: {
    borderBottomWidth: 1,
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
    flexGrow: 1,
  },
});

const mapDispatchToProps = dispatch => {
  const choosePrescriber = prescriberID => dispatch(selectPrescriber(prescriberID));
  const onFilterData = searchTerm => dispatch(PrescriberActions.filterData(searchTerm));
  return { choosePrescriber, onFilterData };
};

const mapStateToProps = state => {
  const { prescriber } = state;
  const { searchTerm } = prescriber;
  const data = UIDatabase.objects('Prescriber').filtered(
    'firstName CONTAINS[c] $0 OR lastName CONTAINS[c] $0',
    searchTerm
  );
  return { data, searchTerm };
};

PrescriberSelectComponent.propTypes = {
  choosePrescriber: PropTypes.func.isRequired,
  data: PropTypes.object.isRequired,
  onFilterData: PropTypes.func.isRequired,
  searchTerm: PropTypes.string.isRequired,
};

export const PrescriberSelect = connect(
  mapStateToProps,
  mapDispatchToProps
)(PrescriberSelectComponent);
<|endoftext|>


<commit_before>
  console.log('hi!');
<commit_msg>Minimal implementation<commit_after>'use strict';

var XLN = require('./XLN.js');

var x = new XLN({host: '192.168.1.166'}, function() {
  console.log('done');
});

setInterval(function () {
  x.readStatus(function(msg) {
    console.log(msg);
  });
}, 1000);
<|endoftext|>


<commit_before>import { merge } from './updates.js';
import * as symbols from './symbols.js';

/**
 * Manages keyboard handling for a component.
 *
 * This mixin handles several keyboard-related features.
 *
 * First, it wires up a single keydown event handler that can be shared by
 * multiple mixins on a component. The event handler will invoke a `keydown`
 * method with the event object, and any mixin along the prototype chain that
 * wants to handle that method can do so.
 *
 * If a mixin wants to indicate that keyboard event has been handled, and that
 * other mixins should *not* handle it, the mixin's `keydown` handler should
 * return a value of true. The convention that seems to work well is that a
 * mixin should see if it wants to handle the event and, if not, then ask the
 * superclass to see if it wants to handle the event. This has the effect of
 * giving the mixin that was applied last the first chance at handling a
 * keyboard event.
 *
 * Example:
 *
 *     [symbols.keydown](event) {
 *       let handled;
 *       switch (event.key) {
 *         // Handle the keys you want, setting handled = true if appropriate.
 *       }
 *       // Prefer mixin result if it's defined, otherwise use base result.
 *       return handled || (super[symbols.keydown] && super[symbols.keydown](event));
 *     }
 *
 * A second feature provided by this mixin is that it implicitly makes the
 * component a tab stop if it isn't already, by setting `tabindex` to 0. This
 * has the effect of adding the component to the tab order in document order.
 *
 * @module KeyboardMixin
 */
export default function KeyboardMixin(Base) {

  // The class prototype added by the mixin.
  class Keyboard extends Base {

    constructor() {
      // @ts-ignore
      super();
      this.addEventListener('keydown', async (event) => {
        this[symbols.raiseChangeEvents] = true;
        // For use with FocusVisibleMixin.
        if (!this.state.focusVisible) {
          // The user may have begun interacting with this element using the
          // mouse/touch, but has now begun using the keyboard, so show focus.
          this.setState({
            focusVisible: true
          });
        }
        const handled = this[symbols.keydown](event);
        if (handled) {
          event.preventDefault();
          event.stopImmediatePropagation();
        }
        await Promise.resolve();
        this[symbols.raiseChangeEvents] = false;
      });
    }

    get defaultState() {
      // If we're using DelegateFocusMixin, we don't need or want to set a
      // tabindex on the host; we'll rely on the inner shadow elements to take
      // the focus and raise keyboard events. Otherwise, we do set a tabindex on
      // the host, so that we can get keyboard events.
      const tabIndex = this.delegatesFocus ? null : 0;
      const state = Object.assign(super.defaultState, {
        tabIndex
      });

      state.onChange('original', state => {
        if (state.original.attributes && state.original.attributes.tabindex) {
          const parsed = Number(state.original.attributes.tabindex);
          if (!isNaN(parsed)) {
            return {
              tabIndex: parsed
            };
          }
        }
        return null;
      });

      return state;
    }

    /**
     * See the [symbols](symbols#keydown) documentation for details.
     */
    [symbols.keydown](event) {
      if (super[symbols.keydown]) { return super[symbols.keydown](event); }
      return false;
    }

    // Record our own notion of the state of the tabIndex property so we can
    // rerender if necessary.
    get tabIndex() {
      return super.tabIndex;
    }
    set tabIndex(tabIndex) {
      // Parse the passed value, which could be a string or null.
      let parsed = tabIndex !== null ? Number(tabIndex) : null;
      if (parsed !== null && isNaN(parsed)) {
        const defaultTabIndex = this[symbols.defaultTabIndex];
        parsed = defaultTabIndex ? defaultTabIndex : 0;
      }

      // If parsed value isn't null and has changed, invoke the super setter.
      if (parsed !== null && super.tabIndex !== parsed) {
        super.tabIndex = parsed;
      }

      if (this.state.tabIndex !== parsed) {
        // Record the new tabIndex in our state.
        this.setState({
          tabIndex: parsed
        });

        // If tabIndex is set outside of rendering, that's tantamount to setting
        // the tabindex attribute. We update our notion of the "original"
        // attribute value of the tabindex attribute. See
        // RenderUpdatesMixin.setAttribute().
        if (!this[symbols.rendering]) {
          const attributes = Object.assign(
            {},
            this.state.original && this.state.original.attributes
          );
          if (parsed === null) {
            delete attributes.tabindex;
          } else {
            attributes.tabindex = parsed.toString();
          }
          const original = Object.assign(
            {},
            this.state.original,
            {
              attributes
            }
          );
          this.setState({ original });
        }
      }
    }

    get updates() {
      const { tabIndex } = this.state;
      return merge(super.updates, {
        attributes: {
          tabindex: tabIndex
        }
      });
    }

  }

  return Keyboard;
}
<commit_msg>Prefer setting tabIndex property over tabindex attribute, as it's more efficient.<commit_after>import { merge } from './updates.js';
import * as symbols from './symbols.js';

/**
 * Manages keyboard handling for a component.
 *
 * This mixin handles several keyboard-related features.
 *
 * First, it wires up a single keydown event handler that can be shared by
 * multiple mixins on a component. The event handler will invoke a `keydown`
 * method with the event object, and any mixin along the prototype chain that
 * wants to handle that method can do so.
 *
 * If a mixin wants to indicate that keyboard event has been handled, and that
 * other mixins should *not* handle it, the mixin's `keydown` handler should
 * return a value of true. The convention that seems to work well is that a
 * mixin should see if it wants to handle the event and, if not, then ask the
 * superclass to see if it wants to handle the event. This has the effect of
 * giving the mixin that was applied last the first chance at handling a
 * keyboard event.
 *
 * Example:
 *
 *     [symbols.keydown](event) {
 *       let handled;
 *       switch (event.key) {
 *         // Handle the keys you want, setting handled = true if appropriate.
 *       }
 *       // Prefer mixin result if it's defined, otherwise use base result.
 *       return handled || (super[symbols.keydown] && super[symbols.keydown](event));
 *     }
 *
 * A second feature provided by this mixin is that it implicitly makes the
 * component a tab stop if it isn't already, by setting `tabindex` to 0. This
 * has the effect of adding the component to the tab order in document order.
 *
 * @module KeyboardMixin
 */
export default function KeyboardMixin(Base) {

  // The class prototype added by the mixin.
  class Keyboard extends Base {

    constructor() {
      // @ts-ignore
      super();
      this.addEventListener('keydown', async (event) => {
        this[symbols.raiseChangeEvents] = true;
        // For use with FocusVisibleMixin.
        if (!this.state.focusVisible) {
          // The user may have begun interacting with this element using the
          // mouse/touch, but has now begun using the keyboard, so show focus.
          this.setState({
            focusVisible: true
          });
        }
        const handled = this[symbols.keydown](event);
        if (handled) {
          event.preventDefault();
          event.stopImmediatePropagation();
        }
        await Promise.resolve();
        this[symbols.raiseChangeEvents] = false;
      });
    }

    get defaultState() {
      // If we're using DelegateFocusMixin, we don't need or want to set a
      // tabindex on the host; we'll rely on the inner shadow elements to take
      // the focus and raise keyboard events. Otherwise, we do set a tabindex on
      // the host, so that we can get keyboard events.
      const tabIndex = this.delegatesFocus ? null : 0;
      const state = Object.assign(super.defaultState, {
        tabIndex
      });

      state.onChange('original', state => {
        if (state.original.attributes && state.original.attributes.tabindex) {
          const parsed = Number(state.original.attributes.tabindex);
          if (!isNaN(parsed)) {
            return {
              tabIndex: parsed
            };
          }
        }
        return null;
      });

      return state;
    }

    /**
     * See the [symbols](symbols#keydown) documentation for details.
     */
    [symbols.keydown](event) {
      if (super[symbols.keydown]) { return super[symbols.keydown](event); }
      return false;
    }

    // Record our own notion of the state of the tabIndex property so we can
    // rerender if necessary.
    get tabIndex() {
      return super.tabIndex;
    }
    set tabIndex(tabIndex) {
      // Parse the passed value, which could be a string or null.
      let parsed = tabIndex !== null ? Number(tabIndex) : null;
      if (parsed !== null && isNaN(parsed)) {
        const defaultTabIndex = this[symbols.defaultTabIndex];
        parsed = defaultTabIndex ? defaultTabIndex : 0;
      }

      // If parsed value isn't null and has changed, invoke the super setter.
      if (parsed !== null && super.tabIndex !== parsed) {
        super.tabIndex = parsed;
      }

      if (this.state.tabIndex !== parsed) {
        // Record the new tabIndex in our state.
        this.setState({
          tabIndex: parsed
        });

        // If tabIndex is set outside of rendering, that's tantamount to setting
        // the tabindex attribute. We update our notion of the "original"
        // attribute value of the tabindex attribute. See
        // RenderUpdatesMixin.setAttribute().
        if (!this[symbols.rendering]) {
          const attributes = Object.assign(
            {},
            this.state.original && this.state.original.attributes
          );
          if (parsed === null) {
            delete attributes.tabindex;
          } else {
            attributes.tabindex = parsed.toString();
          }
          const original = Object.assign(
            {},
            this.state.original,
            {
              attributes
            }
          );
          this.setState({ original });
        }
      }
    }

    get updates() {
      const { tabIndex } = this.state;
      return merge(super.updates, {
        tabIndex
      });
    }

  }

  return Keyboard;
}
<|endoftext|>


<commit_before>

var nativeLog = console.log

console.log = function(s) {
    nativeLog.apply(console, arguments)
    l4.broadCastMessage({name: 'log', data: '' + s})
}<commit_msg>draft ace editor<commit_after>

// guard againsst wrapping twice and ending in endless recursion
if (!console.log.isWrapped) {
	var nativeLog = console.log

	console.log = function(s) {
	    nativeLog.apply(console, arguments)
	    l4.broadCastMessage({name: 'log', data: '' + s})
	}

	console.log.isWrapped = true
}<|endoftext|>


<commit_before>var make = require('./_make')
var makeIterator = require('../function/makeIterator_')

function arrEvery (arr, fn, thisObj) {
  fn = makeIterator(fn, thisObj)

  var result = true
  if (arr == null) return result

  var i = -1
  var len = arr.length

  while (++i < len) {
    if (!fn(arr[i], i, arr)) {
      result = false
      break
    }
  }
  return result
}

function objEvery (obj, fn, thisObj) {
  fn = makeIterator(fn, thisObj)

  var result = true
  var key

  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (!fn(obj[key], key, obj)) {
        result = false
        break
      }
    }
  }
  return result
}

module.exports = make(arrEvery, objEvery)
<commit_msg>update collection/every -- expose individual functions<commit_after>var make = require('./_make_new')
var makeIterator = require('../function/makeIterator_')

function arrEvery (arr, fn, thisObj) {
  fn = makeIterator(fn, thisObj)

  var result = true
  if (arr == null) return result

  var i = -1
  var len = arr.length

  while (++i < len) {
    if (!fn(arr[i], i, arr)) {
      result = false
      break
    }
  }
  return result
}

function objEvery (obj, fn, thisObj) {
  fn = makeIterator(fn, thisObj)

  var result = true
  var key

  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (!fn(obj[key], key, obj)) {
        result = false
        break
      }
    }
  }
  return result
}

module.exports = make(arrEvery, objEvery)
module.exports.arr = arrEvery
module.exports.obj = objEvery
<|endoftext|>


<commit_before>
let Promise = require('bluebird')

let path = require('path')
let clone = require('clone')
let shell_quote = require('shell-quote')

let os = require('../util/os')
let spawn = require('../util/spawn')
let fs = require('../promised/fs')

let log = require('../util/log')('tasks/launch')
let configure = require('./configure')

let CaveStore = require('../stores/cave-store')
let Crash = require('./errors').Crash

let self = {
  sh: async function (exe_path, full_command, opts) {
    log(opts, `sh ${full_command}`)

    // pretty weak but oh well.
    let forbidden = [';', '&']
    for (let bidden of forbidden) {
      if (full_command.indexOf(bidden) !== -1) {
        throw new Error(`Command-line contains forbidden characters: ${full_command}`)
      }
    }

    let cwd = path.dirname(exe_path)
    log(opts, `Working directory: ${cwd}`)

    let args = shell_quote.parse(full_command)
    let command = args.shift()

    let code = await spawn({
      command,
      args,
      ontoken: (tok) => log(opts, `stdout: ${tok}`),
      onerrtoken: (tok) => log(opts, `stderr: ${tok}`),
      opts: { cwd }
    })

    if (code !== 0) {
      let error = `process exited with code ${code}`
      throw new Crash({ exe_path, error })
    }
    return `child completed successfully`
  },

  escape: function (arg) {
    return `"${arg.replace(/"/g, '\\"')}"`
  },

  sort_by_weight: async function (app_path, execs) {
    let weights = {}

    console.log(`Starting to sort by weight`)
    let t1 = +new Date()
    let f = async (exe) => {
      let exe_path = path.join(app_path, exe)
      let stats = await fs.statAsync(exe_path)
      weights[exe] = stats.size
    }
    await Promise.resolve(execs).map(f, {concurrency: 4})
    console.log(`Done sorting by weight!`)

    let t2 = +new Date()
    console.log(`Took ${t2 - t1} to stat the things`)

    // sort from heaviest to lightest
    return clone(execs).sort((a, b) => weights[b] - weights[a])
  },

  sort_by_depth: function (execs) {
    let depths = {}
    for (let exe of execs) {
      depths[exe] = path.normalize(exe).split(path.sep).length
    }

    // sort from least amount of path elements to most
    return clone(execs).sort((a, b) => depths[a] - depths[b])
  },

  sort_by_score: function (execs) {
    let scores = {}
    for (let exe of execs) {
      let score = 100
      if (/unins/.test(exe)) {
        score = 0
      }
      scores[exe] = score
    }

    // sort from most score to least
    return clone(execs).sort((a, b) => scores[b] - scores[a])
  },

  launch: function (exe_path, args, opts) {
    let platform = os.platform()
    log(opts, `launching '${exe_path}' on '${platform}' with args '${args.join(' ')}'`)
    let arg_string = args.map((x) => self.escape(x)).join(' ')

    if (platform === 'darwin' && /\.app\/?$/.test(exe_path.toLowerCase())) {
      // '-W' waits for app to quit
      // potentially easy to inject something into the command line
      // here but then again we are running executables downloaded
      // from the internet.
      let cmd = `open -W ${self.escape(exe_path)}`
      if (arg_string.length > 0) {
        cmd += ` --args ${arg_string}`
      }
      return self.sh(exe_path, cmd, opts)
    } else {
      let cmd = `${self.escape(exe_path)}`
      if (arg_string.length > 0) {
        cmd += ` ${arg_string}`
      }
      return self.sh(exe_path, cmd, opts)
    }
  },

  launch_cave: async function (opts, cave) {
    let app_path = CaveStore.app_path(cave.install_location, opts.id)

    let by_weight = await self.sort_by_weight(app_path, cave.executables)
    let by_score = self.sort_by_score(by_weight)
    let by_depth = self.sort_by_depth(by_score)
    let sorted = by_depth

    log(opts, `executables (from best to worst): ${JSON.stringify(sorted, null, 2)}`)
    let exe_path = path.join(app_path, sorted[0])
    return self.launch(exe_path, [], opts)
  },

  valid_cave: function (cave) {
    return cave.executables && cave.executables.length > 0
  },

  start: async function (opts) {
    let id = opts.id

    let cave = await CaveStore.find(id)
    if (!self.valid_cave(cave)) {
      await configure.start(opts)
      cave = await CaveStore.find(id)
    }

    if (!self.valid_cave(cave)) {
      throw new Error('No executables found')
    }

    await self.launch_cave(opts, cave)
  }
}

module.exports = self
<commit_msg>:checkered_flag: Exclude dxwebsetup for now. Closes #186<commit_after>
let Promise = require('bluebird')

let path = require('path')
let clone = require('clone')
let shell_quote = require('shell-quote')

let os = require('../util/os')
let spawn = require('../util/spawn')
let fs = require('../promised/fs')

let log = require('../util/log')('tasks/launch')
let configure = require('./configure')

let CaveStore = require('../stores/cave-store')
let Crash = require('./errors').Crash

let self = {
  sh: async function (exe_path, full_command, opts) {
    log(opts, `sh ${full_command}`)

    // pretty weak but oh well.
    let forbidden = [';', '&']
    for (let bidden of forbidden) {
      if (full_command.indexOf(bidden) !== -1) {
        throw new Error(`Command-line contains forbidden characters: ${full_command}`)
      }
    }

    let cwd = path.dirname(exe_path)
    log(opts, `Working directory: ${cwd}`)

    let args = shell_quote.parse(full_command)
    let command = args.shift()

    let code = await spawn({
      command,
      args,
      ontoken: (tok) => log(opts, `stdout: ${tok}`),
      onerrtoken: (tok) => log(opts, `stderr: ${tok}`),
      opts: { cwd }
    })

    if (code !== 0) {
      let error = `process exited with code ${code}`
      throw new Crash({ exe_path, error })
    }
    return `child completed successfully`
  },

  escape: function (arg) {
    return `"${arg.replace(/"/g, '\\"')}"`
  },

  sort_by_weight: async function (app_path, execs) {
    let weights = {}

    console.log(`Starting to sort by weight`)
    let t1 = +new Date()
    let f = async (exe) => {
      let exe_path = path.join(app_path, exe)
      let stats = await fs.statAsync(exe_path)
      weights[exe] = stats.size
    }
    await Promise.resolve(execs).map(f, {concurrency: 4})
    console.log(`Done sorting by weight!`)

    let t2 = +new Date()
    console.log(`Took ${t2 - t1} to stat the things`)

    // sort from heaviest to lightest
    return clone(execs).sort((a, b) => weights[b] - weights[a])
  },

  sort_by_depth: function (execs) {
    let depths = {}
    for (let exe of execs) {
      depths[exe] = path.normalize(exe).split(path.sep).length
    }

    // sort from least amount of path elements to most
    return clone(execs).sort((a, b) => depths[a] - depths[b])
  },

  sort_by_score: function (execs) {
    let scores = {}
    for (let exe of execs) {
      let score = 100
      if (/unins/.test(exe)) {
        score = 0
      } else if (/dxwebsetup\.exe/i.test(exe)) {
        score = 0
      }
      scores[exe] = score
    }

    // sort from most score to least
    return clone(execs).sort((a, b) => scores[b] - scores[a])
  },

  launch: function (exe_path, args, opts) {
    let platform = os.platform()
    log(opts, `launching '${exe_path}' on '${platform}' with args '${args.join(' ')}'`)
    let arg_string = args.map((x) => self.escape(x)).join(' ')

    if (platform === 'darwin' && /\.app\/?$/.test(exe_path.toLowerCase())) {
      // '-W' waits for app to quit
      // potentially easy to inject something into the command line
      // here but then again we are running executables downloaded
      // from the internet.
      let cmd = `open -W ${self.escape(exe_path)}`
      if (arg_string.length > 0) {
        cmd += ` --args ${arg_string}`
      }
      return self.sh(exe_path, cmd, opts)
    } else {
      let cmd = `${self.escape(exe_path)}`
      if (arg_string.length > 0) {
        cmd += ` ${arg_string}`
      }
      return self.sh(exe_path, cmd, opts)
    }
  },

  launch_cave: async function (opts, cave) {
    let app_path = CaveStore.app_path(cave.install_location, opts.id)

    let by_weight = await self.sort_by_weight(app_path, cave.executables)
    let by_score = self.sort_by_score(by_weight)
    let by_depth = self.sort_by_depth(by_score)
    let sorted = by_depth

    log(opts, `executables (from best to worst): ${JSON.stringify(sorted, null, 2)}`)
    let exe_path = path.join(app_path, sorted[0])
    return self.launch(exe_path, [], opts)
  },

  valid_cave: function (cave) {
    return cave.executables && cave.executables.length > 0
  },

  start: async function (opts) {
    let id = opts.id

    let cave = await CaveStore.find(id)
    if (!self.valid_cave(cave)) {
      await configure.start(opts)
      cave = await CaveStore.find(id)
    }

    if (!self.valid_cave(cave)) {
      throw new Error('No executables found')
    }

    await self.launch_cave(opts, cave)
  }
}

module.exports = self
<|endoftext|>


<commit_before>var siteLinks = {
	"column one" : {
		"reddit" : "https://www.reddit.com",
		"twitter" : "https://www.twitter.com"
	},
	"column two" : {
		"apple" : "http://apple.com",
		"google" : "http://google.com"
	}
};

var table = "<table id=\"linktable\" class=\"linktable\">";

function loadLinks() {
	for (var key in siteLinks) {
		// key = "column number"
		// siteLinks[key] = {'page':'address'}
		for (var link in siteLinks[key]) {

		}
	}
}
<commit_msg>Removed table.js<commit_after><|endoftext|>


<commit_before>type('TouchSensitive', [],
     {
         addSense : function(element) {

             var self = this;
             element.observeEvent('mouseover', function(event) {
                 if (self.enabled) {
                     if (!element.ancestorOf($E(eventTarget(event)))) {
                         return;
                     }

                     each(self.actionOnList, function(action) {
                         action();
                     });
                 }
                 event.preventDefault();
             });

             element.observeEvent('mouseout', function(event) {
                 if (self.enabled) {
                     if (element.ancestorOf($E(event.relatedTarget))) {
                         return;
                     }

                     each(self.actionOffList, function(action) {
                         action();
                     });
                 }
                 event.preventDefault();
             });

             return element;
         },

         disable : function() {
             this.enabled = false;
         },

         enable : function() {
             this.enabled = true;
         },

         addActionOn : function(action) {
             this.actionOnList.push(action);
         },

         addActionOff : function(action) {
             this.actionOffList.push(action);
         }

     },
     function() {
         this.enabled = true;
         this.actionOnList = [];
         this.actionOffList = [];
     });

type('TooltipLike', ['TouchSensitive'],
     {
         triggerOn: function() {
             if (!this.state) {
                 this._triggerOn();
                 this.state = true;
             }
         },

         triggerOff: function() {
             if (this.state) {
                 this._triggerOff();
                 this.state = false;
             }
         }

     },
     function() {
         var self = this;

         this.state = false;

         this.TouchSensitive();
         this.addActionOn(function(){
             self.triggerOn();
         });
         this.addActionOff(function(){
             self.triggerOff();
         });

     });

function highlightWithMouse(observable, target) {

    /*
     * observable - trigger element (mouse over, out)
     * target - target element (will look brighter)
     */

    if (target.__highlightSet) {
        return observable;
    }

    observable.observeEvent('mouseover', function(event) {

        target.__tmpColor = target.dom.style.backgroundColor;
        if (target.__tmpColor === ''){
            return;
        }

        var bgColor = target.dom.style.backgroundColor;
        var s = bgColor.match(/rgb\((\d+), (\d+), (\d+)\)/);
        if (!s) {
            s = bgColor.match(/#(..)(..)(..)/);
            if (!s) {
                return;
            }
            s[1] = parseInt('0x'+s[1],16);
            s[2] = parseInt('0x'+s[2],16);
            s[3] = parseInt('0x'+s[3],16);
        }

        s[1] = Math.floor(s[1]*1.05);
        s[2] = Math.floor(s[2]*1.05);
        s[3] = Math.floor(s[3]*1.05);
        target.setStyle('backgroundColor', 'rgb(' + s[1] + ',' + s[2] + ',' + s[3] + ')');

    });

    observable.observeEvent('mouseout', function(event) {
        target.setStyle('backgroundColor', target.__tmpColor);
    });

    target.__highlightSet = true;

    return observable;
}

type('Printable', [], {
    print: function(element, title) {
        var body = $E(document.body);
        var bodyCSSClasses = body.dom.className;
        var elementCSSClasses = element.dom.className;

        // Make sure element is visible when printing
        element.dom.className = elementCSSClasses + " print";

        // Make sure body is invisible
        body.dom.className = bodyCSSClasses += " noprint";

        window.print();

        // Restore
        //body.dom.className = bodyCSSClasses;
        //element.dom.className = elementCSSClasses
    }
    }
)<commit_msg>[IMPROVEMENT] Refactored some decorators<commit_after>
function mouseOverSwitch(observable, overAction, outAction) {

    observable.observeEvent('mouseover', function(event) {
        overAction(event);
    });

    observable.observeEvent('mouseout', function(event) {
        outAction(event);
    });

}

function showWithMouse(observable, target) {

    var stored = target.dom.style.display;
    target.dom.style.display = 'none';

    mouseOverSwitch(observable,
                    function() {
                        target.dom.style.display = stored;
                    },
                    function() {
                        target.dom.style.display = 'none';
                    });

}

function highlightWithMouse(observable, target) {

    /*
     * observable - trigger element (mouse over, out)
     * target - target element (will look brighter)
     */

    if (target.__highlightSet) {
        return observable;
    }

    mouseOverSwitch(observable,
                    function() {
                        target.__tmpColor = target.dom.style.backgroundColor;
                        if (target.__tmpColor === ''){
                            return;
                        }

                        var bgColor = target.dom.style.backgroundColor;
                        var s = bgColor.match(/rgb\((\d+), (\d+), (\d+)\)/);
                        if (!s) {
                            s = bgColor.match(/#(..)(..)(..)/);
                            if (!s) {
                                return;
                            }
                            s[1] = parseInt('0x'+s[1],16);
                            s[2] = parseInt('0x'+s[2],16);
                            s[3] = parseInt('0x'+s[3],16);
                        }

                        s[1] = Math.floor(s[1]*1.05);
                        s[2] = Math.floor(s[2]*1.05);
                        s[3] = Math.floor(s[3]*1.05);
                        target.setStyle('backgroundColor', 'rgb(' + s[1] + ',' + s[2] + ',' + s[3] + ')');
                    },
                    function() {
                        target.setStyle('backgroundColor', target.__tmpColor);
                    });

    target.__highlightSet = true;

    return observable;
}

type('Printable', [], {
    print: function(element, title) {
        var body = $E(document.body);
        var bodyCSSClasses = body.dom.className;
        var elementCSSClasses = element.dom.className;

        // Make sure element is visible when printing
        element.dom.className = elementCSSClasses + " print";

        // Make sure body is invisible
        body.dom.className = bodyCSSClasses += " noprint";

        window.print();

        // Restore
        //body.dom.className = bodyCSSClasses;
        //element.dom.className = elementCSSClasses
    }
});<|endoftext|>