<commit_before>/**
 * Checkout.com Magento 2 Payment module (https://www.checkout.com)
 *
 * Copyright (c) 2017 Checkout.com (https://www.checkout.com)
 * Author: David Fiaty | integration@checkout.com
 *
 * License GNU/GPL V3 https://www.gnu.org/licenses/gpl-3.0.en.html
 */

/*browser:true*/
/*global define*/

define(
    [
        'jquery',
        'CheckoutCom_Magento2/js/view/payment/method-renderer/cc-form',
        'CheckoutCom_Magento2/js/view/payment/adapter',
        'Magento_Checkout/js/model/quote',
        'mage/url',
        'Magento_Checkout/js/action/set-payment-information',
        'Magento_Checkout/js/model/full-screen-loader',
        'Magento_Checkout/js/model/payment/additional-validators',
        'Magento_Checkout/js/checkout-data',
        'Magento_Checkout/js/model/address-converter',
        'Magento_Checkout/js/action/redirect-on-success',
        'mage/translate'
    ],
    function($, Component, CheckoutCom, quote, url, setPaymentInformationAction, fullScreenLoader, additionalValidators, checkoutData, addressConverter, redirectOnSuccessAction, t, customer) {
        'use strict';

        window.checkoutConfig.reloadOnBillingAddress = true;

        return Component.extend({
            defaults: {
                active: true,
                template: 'CheckoutCom_Magento2/payment/applepay',
                code: 'checkout_com_applepay',
                card_token_id: null,
                redirectAfterPlaceOrder: true,
                button_target: '#cko-applepay-holder button'
            },

            /**
             * @returns {exports}
             */
            initialize: function() {
                this._super();

                return this;
            },

            /**
             * @returns {string}
             */
            getCode: function() {
                return CheckoutCom.getCodeApplePay();
            },

            /**
             * @param {string} card_token_id
             */
            setCardTokenId: function(card_token_id) {
                this.card_token_id = card_token_id;
            },

            /**
             * @returns {bool}
             */
            isActive: function() {
                return CheckoutCom.getPaymentConfigApplePay()['isActive'];
            },

            /**
             * @returns {string}
             */
            getPublicKey: function() {
                return CheckoutCom.getPaymentConfig()['public_key'];
            },

            /**
             * @returns {string}
             */
            getQuoteValue: function() {
                return (quote.getTotals()().grand_total).toFixed(2);
            },

            /**
             * @returns {string}
             */
            getQuoteCurrency: function() {
                return CheckoutCom.getPaymentConfig()['quote_currency'];
            },

            /**
             * @returns {object}
             */
            getSelectedShippingMethod: function() {
                // Prepare the output object
                var result = {};

                // Get the selected shipping method data
                var quoteData = quote.totals().total_segments;

                for (var i = 0, len = quoteData.length; i < len; i++) {
                    if (quoteData[i].code === 'shipping')
                    {
                        result.selected = quoteData[i];
                    }
                }

                // Get the base shipping method data
                result.base = quote.shippingMethod();

                return result;
            },

            /**
             * @returns {object}
             */
            getShippingAddress: function() {
                return quote.shippingAddress();
            },

            /**
             * @returns {object}
             */
            getBillingAddress: function() {
                return quote.billingAddress();
            },

            /**
             * @returns {array}
             */
            getLineItems: function() {
                return [];
            },

            /**
             * @returns {array}
             */
            getShippingMethods: function() {
                var shippingData = this.getSelectedShippingMethod();
                var shippingOptions = [{
                    label: shippingData.base.method_title,
                    amount: shippingData.selected.value,
                    detail: shippingData.base.carrier_title,
                    identifier: shippingData.base.method_code
                }];

                return shippingOptions;
            },

            /**
             * @returns {bool}
             */
            launchApplePay: function() {
                // Prepare the parameters
                var ap = CheckoutCom.getPaymentConfigApplePay();
                var debug = ap['debugMode'];
                var self = this;

                // Apply the button style
                $(self.button_target).addClass('apple-pay-button-' + ap['buttonStyle']);

                // Check if the session is available
                if (window.ApplePaySession) {
                    var merchantIdentifier = ap['merchantId'];
                    var promise = ApplePaySession.canMakePaymentsWithActiveCard(merchantIdentifier);
                    promise.then(function (canMakePayments) {
                        if (canMakePayments) {
                            $(self.button_target).css('display', 'block');
                        } else {
                            $('#got_notactive').css('display', 'block');
                        }
                    });
                } else {
                    $('#notgot').css('display', 'block');
                }

                // Handle the events
                $(self.button_target).click(function(evt) {
                    // Prepare the parameters
                    var runningTotal	= self.getQuoteValue();
                    var billingAddress  = self.getBillingAddress();
                    var shippingAddress = self.getShippingAddress();

                    // Build the payment request
                    var paymentRequest = {
                        currencyCode: CheckoutCom.getPaymentConfig()['quote_currency'],
                        countryCode: billingAddress.countryId,
                        requiredShippingContactFields: ['postalAddress'],
                        requiredBillingContactFields: ['postalAddress'],
                        lineItems: self.getLineItems(),
                        shippingMethods: self.getShippingMethods(),
                        billingContact: {
                            givenName: billingAddress.firstname,
                            familyName: billingAddress.lastname,
                            addressLines: billingAddress.street,
                            postalCode: billingAddress.postcode,
                            locality: billingAddress.city,
                            countryCode: billingAddress.countryId
                        },
                        shippingContact: {
                            givenName: shippingAddress.firstname,
                            familyName: shippingAddress.lastname,
                            addressLines: shippingAddress.street,
                            postalCode: shippingAddress.postcode,
                            locality: shippingAddress.city,
                            countryCode: billingAddress.countryId
                        },
                        total: {
                           label: ap['storeName'],
                           amount: runningTotal
                        },
                        supportedCountries: [], // todo - move to config
                        supportedNetworks: ['amex', 'masterCard', 'visa' ], // todo - move to config
                        merchantCapabilities: [ 'supports3DS', 'supportsEMV', 'supportsCredit', 'supportsDebit' ] // todo - move to config
                    };

                    // Start the payment session
                    var session = new ApplePaySession(1, paymentRequest);

                    // Merchant Validation
                    session.onvalidatemerchant = function (event) {
                        var promise = performValidation(event.validationURL);
                        promise.then(function (merchantSession) {
                            session.completeMerchantValidation(merchantSession);
                        });
                    }

                    // Merchant validation function
                    function performValidation(valURL) {
                        var controllerUrl = url.build('checkout_com/payment/applepayvalidation');
                        var validationUrl = controllerUrl + '?u=' + valURL;

                        return new Promise(function(resolve, reject) {
                            var xhr = new XMLHttpRequest();
                            xhr.onload = function() {
                                var data = JSON.parse(this.responseText);
                                resolve(data);
                            };
                            xhr.onerror = reject;
                            xhr.open('GET', validationUrl);
                            xhr.send();
                        });
                    }

                    // Shipping contact
                    session.onshippingcontactselected = function(event) {
                        var status = ApplePaySession.STATUS_SUCCESS;

                        // Shipping info
                        var shippingOptions = self.getShippingMethods();

                        var newTotal = {
                            type: 'final',
                            label: ap['storeName'],
                            amount: runningTotal
                        };

                        session.completeShippingContactSelection(status, shippingOptions, newTotal, self.getLineItems());
                    }

                    // Shipping method selection
                    session.onshippingmethodselected = function(event) {
                        var status = ApplePaySession.STATUS_SUCCESS;
                        var newTotal = {
                            type: 'final',
                            label: ap['storeName'],
                            amount: runningTotal
                        };

                        session.completeShippingMethodSelection(status, newTotal, self.getLineItems());
                    }

                    // Payment method selection
                    session.onpaymentmethodselected = function(event) {
                        var newTotal = {
                            type: 'final',
                            label: ap['storeName'],
                            amount: runningTotal
                        };

                        session.completePaymentMethodSelection( newTotal, self.getLineItems());
                    }

                    // Payment method authorization
                    session.onpaymentauthorized = function (event) {
                        var promise = sendPaymentToken(event.payment.token);
                        promise.then(function (success) {
                            var status;
                            if (success){
                                status = ApplePaySession.STATUS_SUCCESS;
                                $(self.button_target).css('display', 'none');
                                $('#success').css('display', 'block');
                            } else {
                                status = ApplePaySession.STATUS_FAILURE;
                            }

                            session.completePayment(status);
                        });
                    }

                    // Send payment token
                    function sendPaymentToken(paymentToken) {
                        return new Promise(function(resolve, reject) {
                            if (debug == true)
                            resolve(true);
                            else
                            reject;
                        });
                    }

                    // Session cancellation
                    session.oncancel = function(event) {
                        // Do something if needed
                    }

                    // Begin session
                    session.begin();
                });
            },

        });
    }
);<commit_msg>Apple Pay shipping country id<commit_after>/**
 * Checkout.com Magento 2 Payment module (https://www.checkout.com)
 *
 * Copyright (c) 2017 Checkout.com (https://www.checkout.com)
 * Author: David Fiaty | integration@checkout.com
 *
 * License GNU/GPL V3 https://www.gnu.org/licenses/gpl-3.0.en.html
 */

/*browser:true*/
/*global define*/

define(
    [
        'jquery',
        'CheckoutCom_Magento2/js/view/payment/method-renderer/cc-form',
        'CheckoutCom_Magento2/js/view/payment/adapter',
        'Magento_Checkout/js/model/quote',
        'mage/url',
        'Magento_Checkout/js/action/set-payment-information',
        'Magento_Checkout/js/model/full-screen-loader',
        'Magento_Checkout/js/model/payment/additional-validators',
        'Magento_Checkout/js/checkout-data',
        'Magento_Checkout/js/model/address-converter',
        'Magento_Checkout/js/action/redirect-on-success',
        'mage/translate'
    ],
    function($, Component, CheckoutCom, quote, url, setPaymentInformationAction, fullScreenLoader, additionalValidators, checkoutData, addressConverter, redirectOnSuccessAction, t, customer) {
        'use strict';

        window.checkoutConfig.reloadOnBillingAddress = true;

        return Component.extend({
            defaults: {
                active: true,
                template: 'CheckoutCom_Magento2/payment/applepay',
                code: 'checkout_com_applepay',
                card_token_id: null,
                redirectAfterPlaceOrder: true,
                button_target: '#cko-applepay-holder button'
            },

            /**
             * @returns {exports}
             */
            initialize: function() {
                this._super();

                return this;
            },

            /**
             * @returns {string}
             */
            getCode: function() {
                return CheckoutCom.getCodeApplePay();
            },

            /**
             * @param {string} card_token_id
             */
            setCardTokenId: function(card_token_id) {
                this.card_token_id = card_token_id;
            },

            /**
             * @returns {bool}
             */
            isActive: function() {
                return CheckoutCom.getPaymentConfigApplePay()['isActive'];
            },

            /**
             * @returns {string}
             */
            getPublicKey: function() {
                return CheckoutCom.getPaymentConfig()['public_key'];
            },

            /**
             * @returns {string}
             */
            getQuoteValue: function() {
                return (quote.getTotals()().grand_total).toFixed(2);
            },

            /**
             * @returns {string}
             */
            getQuoteCurrency: function() {
                return CheckoutCom.getPaymentConfig()['quote_currency'];
            },

            /**
             * @returns {object}
             */
            getSelectedShippingMethod: function() {
                // Prepare the output object
                var result = {};

                // Get the selected shipping method data
                var quoteData = quote.totals().total_segments;

                for (var i = 0, len = quoteData.length; i < len; i++) {
                    if (quoteData[i].code === 'shipping')
                    {
                        result.selected = quoteData[i];
                    }
                }

                // Get the base shipping method data
                result.base = quote.shippingMethod();

                return result;
            },

            /**
             * @returns {object}
             */
            getShippingAddress: function() {
                return quote.shippingAddress();
            },

            /**
             * @returns {object}
             */
            getBillingAddress: function() {
                return quote.billingAddress();
            },

            /**
             * @returns {array}
             */
            getLineItems: function() {
                return [];
            },

            /**
             * @returns {array}
             */
            getShippingMethods: function() {
                var shippingData = this.getSelectedShippingMethod();
                var shippingOptions = [{
                    label: shippingData.base.method_title,
                    amount: shippingData.selected.value,
                    detail: shippingData.base.carrier_title,
                    identifier: shippingData.base.method_code
                }];

                return shippingOptions;
            },

            /**
             * @returns {bool}
             */
            launchApplePay: function() {
                // Prepare the parameters
                var ap = CheckoutCom.getPaymentConfigApplePay();
                var debug = ap['debugMode'];
                var self = this;

                // Apply the button style
                $(self.button_target).addClass('apple-pay-button-' + ap['buttonStyle']);

                // Check if the session is available
                if (window.ApplePaySession) {
                    var merchantIdentifier = ap['merchantId'];
                    var promise = ApplePaySession.canMakePaymentsWithActiveCard(merchantIdentifier);
                    promise.then(function (canMakePayments) {
                        if (canMakePayments) {
                            $(self.button_target).css('display', 'block');
                        } else {
                            $('#got_notactive').css('display', 'block');
                        }
                    });
                } else {
                    $('#notgot').css('display', 'block');
                }

                // Handle the events
                $(self.button_target).click(function(evt) {
                    // Prepare the parameters
                    var runningTotal	= self.getQuoteValue();
                    var billingAddress  = self.getBillingAddress();
                    var shippingAddress = self.getShippingAddress();

                    // Build the payment request
                    var paymentRequest = {
                        currencyCode: CheckoutCom.getPaymentConfig()['quote_currency'],
                        countryCode: billingAddress.countryId,
                        requiredShippingContactFields: ['postalAddress'],
                        requiredBillingContactFields: ['postalAddress'],
                        lineItems: self.getLineItems(),
                        shippingMethods: self.getShippingMethods(),
                        billingContact: {
                            givenName: billingAddress.firstname,
                            familyName: billingAddress.lastname,
                            addressLines: billingAddress.street,
                            postalCode: billingAddress.postcode,
                            locality: billingAddress.city,
                            countryCode: billingAddress.countryId
                        },
                        shippingContact: {
                            givenName: shippingAddress.firstname,
                            familyName: shippingAddress.lastname,
                            addressLines: shippingAddress.street,
                            postalCode: shippingAddress.postcode,
                            locality: shippingAddress.city,
                            countryCode: shippingAddress.countryId
                        },
                        total: {
                           label: ap['storeName'],
                           amount: runningTotal
                        },
                        supportedCountries: [], // todo - move to config
                        supportedNetworks: ['amex', 'masterCard', 'visa' ], // todo - move to config
                        merchantCapabilities: [ 'supports3DS', 'supportsEMV', 'supportsCredit', 'supportsDebit' ] // todo - move to config
                    };

                    // Start the payment session
                    var session = new ApplePaySession(1, paymentRequest);

                    // Merchant Validation
                    session.onvalidatemerchant = function (event) {
                        var promise = performValidation(event.validationURL);
                        promise.then(function (merchantSession) {
                            session.completeMerchantValidation(merchantSession);
                        });
                    }

                    // Merchant validation function
                    function performValidation(valURL) {
                        var controllerUrl = url.build('checkout_com/payment/applepayvalidation');
                        var validationUrl = controllerUrl + '?u=' + valURL;

                        return new Promise(function(resolve, reject) {
                            var xhr = new XMLHttpRequest();
                            xhr.onload = function() {
                                var data = JSON.parse(this.responseText);
                                resolve(data);
                            };
                            xhr.onerror = reject;
                            xhr.open('GET', validationUrl);
                            xhr.send();
                        });
                    }

                    // Shipping contact
                    session.onshippingcontactselected = function(event) {
                        var status = ApplePaySession.STATUS_SUCCESS;

                        // Shipping info
                        var shippingOptions = self.getShippingMethods();

                        var newTotal = {
                            type: 'final',
                            label: ap['storeName'],
                            amount: runningTotal
                        };

                        session.completeShippingContactSelection(status, shippingOptions, newTotal, self.getLineItems());
                    }

                    // Shipping method selection
                    session.onshippingmethodselected = function(event) {
                        var status = ApplePaySession.STATUS_SUCCESS;
                        var newTotal = {
                            type: 'final',
                            label: ap['storeName'],
                            amount: runningTotal
                        };

                        session.completeShippingMethodSelection(status, newTotal, self.getLineItems());
                    }

                    // Payment method selection
                    session.onpaymentmethodselected = function(event) {
                        var newTotal = {
                            type: 'final',
                            label: ap['storeName'],
                            amount: runningTotal
                        };

                        session.completePaymentMethodSelection( newTotal, self.getLineItems());
                    }

                    // Payment method authorization
                    session.onpaymentauthorized = function (event) {
                        var promise = sendPaymentToken(event.payment.token);
                        promise.then(function (success) {
                            var status;
                            if (success){
                                status = ApplePaySession.STATUS_SUCCESS;
                                $(self.button_target).css('display', 'none');
                                $('#success').css('display', 'block');
                            } else {
                                status = ApplePaySession.STATUS_FAILURE;
                            }

                            session.completePayment(status);
                        });
                    }

                    // Send payment token
                    function sendPaymentToken(paymentToken) {
                        return new Promise(function(resolve, reject) {
                            if (debug == true)
                            resolve(true);
                            else
                            reject;
                        });
                    }

                    // Session cancellation
                    session.oncancel = function(event) {
                        // Do something if needed
                    }

                    // Begin session
                    session.begin();
                });
            },

        });
    }
);<|endoftext|>


<commit_before>/*!
 * --------------
 * LysinsDB®-Data
 * --------------
 * Data of LysinsDB — A manually curated dedicated database of Lysins.
 * ___________________________________________________________________________
 *
 * Grunt, http://gruntjs.com/ — The JavaScript Task Runner.
 * ___________________________________________________________________________
 *
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Sequømics Research [http://research.sequomics.com/].
 * @copyright : Sequømics Corporation [http://sequomics.com/].
 * ___________________________________________________________________________
 *
 * @date      : 06-Dec-2016
 * @license   : Apache, version 2.0
 * @require   : Node.js®
 * @require   : NPM
 * @require   : grunt-contrib-compress
 * @build     : SEED™ — Örebro
 *              └────── A Sequømics Product — http://sequomics.com/.
 * ___________________________________________________________________________
 *
 * --/The Heart of Build System/-- of "LysinsDB®-Data".
 * ___________________________________________________________________________
 */
<commit_msg>Initial commit<commit_after>/*!
 * --------------
 * LysinsDB®-Data
 * --------------
 * Data of LysinsDB — A manually curated dedicated database of Lysins.
 * ___________________________________________________________________________
 *
 * Grunt, http://gruntjs.com/ — The JavaScript Task Runner.
 * ___________________________________________________________________________
 *
 * Architecture and Code Handcrafted by Prabhat Kumar.
 * Architectuur en Code handgemaakt door Prabhat Kumar.
 * @author    : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Prabhat Kumar [http://prabhatkumar.org/].
 * @copyright : Sequømics Research [http://research.sequomics.com/].
 * @copyright : Sequømics Corporation [http://sequomics.com/].
 * ___________________________________________________________________________
 *
 * @date      : 06-Dec-2016
 * @license   : Apache, version 2.0
 * @require   : Node.js®
 * @require   : NPM
 * @require   : grunt-contrib-compress
 * @build     : SEED™ — Örebro
 *              └────── A Sequømics Product — http://sequomics.com/.
 * ___________________________________________________________________________
 *
 * --/The Heart of Build System/-- of "LysinsDB®-Data".
 * ___________________________________________________________________________
 */

module.exports = {
  // Used a default pattern of compression for LysinsDB®-Data.
  main: {
    options: {
      // output: --> lysinsdb-data-0.0.1-2016-12-06-dist.zip
      archive: '<%= pkg.name %>-<%= pkg.version %>-<%= pkg.author %><%= grunt.template.today("yyyy-mm-dd") %>-data.zip',
      level: 9,
      pretty: true
    },
    files: [
      {
        expand: true,
        src: ['data/**/*.json'],
        dest: './'
      }
    ]
  }
};
<|endoftext|>


<commit_before>$(document).ready(getposts);
function getposts(){
    $.getJSON('entries.json', function(data) {
		$.each(data.entries, function(key, val) {
                var output="
";
				    output+="
" + val.date +"
";
				    output+="
" + val.title +"
";
				    output+="
" + val.text +"
";
				    output+="
";
					output+="
";

				$("#blog").append(output);
      	});
    });
}

$(document).ready(function()    {
	$('#key').paginate({itemsPerPage: 5});

	$.getJSON('data.json', function(data) {
		var items = [];
		$.each(data.items, function(i, item) {
			items.push('
' + item + '
');
		});
		$('#example4').append(items.join(''));
		$('#example4').paginate({itemsPerPage: 10});
	});
});<commit_msg>Updated JSON data file in JS<commit_after>$(document).ready(getposts);
$('#key').paginate({itemsPerPage: 5});
function getposts(){
    $.getJSON('entries.json', function(data) {
		$.each(data.entries, function(key, val) {
                var output="
";
				    output+="
" + val.date +"
";
				    output+="
" + val.title +"
";
				    output+="
" + val.text +"
";
				    output+="
";
					output+="
";

				$("#blog").append(output);
      	});
    });
}<|endoftext|>


<commit_before>"use strict";
var px = require("../px");
var etg = require("../etg");
var gfx = require("../gfx");
var chat = require("../chat");
var sock = require("../sock");
var Cards = require("../Cards");
var etgutil = require("../etgutil");
var userutil = require("../userutil");
module.exports = function(reward, numberofcopies, code) {
	if (!numberofcopies) numberofcopies = 1;
	var rewardList, chosenReward;
	if (typeof reward == "string") {
		var shiny = reward.charAt(0) == "!";
		if (shiny) reward = reward.slice(1);
		var upped = reward.slice(0, 5) == "upped";
		var rarity = userutil.rewardwords[upped ? reward.slice(5) : reward];
		rewardList = etg.filtercards(upped, function(x) { return x.rarity == rarity }).map(function(card){ return card.asShiny(shiny).code });
	}else if (reward instanceof Array){
		rewardList = reward;
	}else{
		console.log("Unknown reward", reward);
		return;
	}
	var rewardui = px.mkView(),
		dom = px.dom.div([10, 40, ["Done", function() {
			if (chosenReward) {
				if (code === undefined) {
					sock.userExec("addbound", { c: etgutil.encodeCount(numberofcopies) + chosenReward });
					require("./MainMenu")();
				}
				else {
					sock.userEmit("codesubmit2", { code: code, card: chosenReward });
				}
			}else chat("Choose a reward");
		}]]);

	if (numberofcopies > 1) {
		px.dom.add(div, [20, 100, "You will get " + numberofcopies + " copies of the card you choose"]);
	}
	if (code){
		px.dom.add(div, [10, 10, ["Exit", require("./MainMenu")]]);
	}

	var chosenRewardImage = new PIXI.Sprite(gfx.nopic);
	chosenRewardImage.position.set(233, 10);
	rewardui.addChild(chosenRewardImage);
	rewardList.forEach(function(reward, i){
		var card = new PIXI.Sprite(gfx.getCardImage(reward));
		card.position.set(100 + Math.floor(i/12) * 133, 272 + (i%12) * 19);
		px.setClick(card, function(){
			chosenReward = reward;
			chosenRewardImage.texture = gfx.getArt(chosenReward);
		}, "cardClick");
		rewardui.addChild(card);
		px.setInteractive(card);
	});

	var cmds = {
		codedone:function(data) {
			sock.user.pool = etgutil.addcard(sock.user.pool, data.card);
			chat(Cards.Codes[data.card].name + " added!");
			require("./MainMenu")();
		},
	}

	px.view({view:rewardui, dom:dom, cmds:cmds});
}<commit_msg>Stray variable named dom<commit_after>"use strict";
var px = require("../px");
var etg = require("../etg");
var gfx = require("../gfx");
var chat = require("../chat");
var sock = require("../sock");
var Cards = require("../Cards");
var etgutil = require("../etgutil");
var userutil = require("../userutil");
module.exports = function(reward, numberofcopies, code) {
	if (!numberofcopies) numberofcopies = 1;
	var rewardList, chosenReward;
	if (typeof reward == "string") {
		var shiny = reward.charAt(0) == "!";
		if (shiny) reward = reward.slice(1);
		var upped = reward.slice(0, 5) == "upped";
		var rarity = userutil.rewardwords[upped ? reward.slice(5) : reward];
		rewardList = etg.filtercards(upped, function(x) { return x.rarity == rarity }).map(function(card){ return card.asShiny(shiny).code });
	}else if (reward instanceof Array){
		rewardList = reward;
	}else{
		console.log("Unknown reward", reward);
		return;
	}
	var rewardui = px.mkView(),
		div = px.dom.div([10, 40, ["Done", function() {
			if (chosenReward) {
				if (code === undefined) {
					sock.userExec("addbound", { c: etgutil.encodeCount(numberofcopies) + chosenReward });
					require("./MainMenu")();
				}
				else {
					sock.userEmit("codesubmit2", { code: code, card: chosenReward });
				}
			}else chat("Choose a reward");
		}]]);

	if (numberofcopies > 1) {
		px.dom.add(div, [20, 100, "You will get " + numberofcopies + " copies of the card you choose"]);
	}
	if (code){
		px.dom.add(div, [10, 10, ["Exit", require("./MainMenu")]]);
	}

	var chosenRewardImage = new PIXI.Sprite(gfx.nopic);
	chosenRewardImage.position.set(233, 10);
	rewardui.addChild(chosenRewardImage);
	rewardList.forEach(function(reward, i){
		var card = new PIXI.Sprite(gfx.getCardImage(reward));
		card.position.set(100 + Math.floor(i/12) * 133, 272 + (i%12) * 19);
		px.setClick(card, function(){
			chosenReward = reward;
			chosenRewardImage.texture = gfx.getArt(chosenReward);
		}, "cardClick");
		card.interactive = true;
		rewardui.addChild(card);
	});

	var cmds = {
		codedone:function(data) {
			sock.user.pool = etgutil.addcard(sock.user.pool, data.card);
			chat(Cards.Codes[data.card].name + " added!");
			require("./MainMenu")();
		},
	}

	px.view({view:rewardui, dom:div, cmds:cmds});
}<|endoftext|>


<commit_before>let React = require("react")
let Colr = require('colr')
let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js")
let {div, input, img} = React.DOM
let cx = require("classnames")

let colorMap = React.createFactory(require("./color/map"))
let sample =  React.createFactory(require("./color/sample"))
let hue_slider =  React.createFactory(require("./color/hue_slider"))

export default class extends React.Component {

  static displayName = "Frig.friggingBootstrap.Color"

  static defaultProps = Object.assign(require("../default_props.js"), {
    color: "#000000",
  })

  propTypes: {
    color: React.PropTypes.string,
  }

  state = this._getStateFrom(this.props.color)

  componentDidMount() {
   this.setState({ showPopup: false })
  }

  // generate state object from a hex string
  _getStateFrom(color) {
    color = Colr.fromHex(color)
    return {
      color: color,
      hsv: color.toRawHsvObject(),
    }
  }

  _onInputClick() {
    this.setState({
      showPopup: !this.state.showPopup,
    })
  }

  // replace current color with another one
  _loadColor(color) {
    this.setState(this._getStateFrom(color))
  }

  // update the current color using the raw hsv values
  _update() {
    let color = Colr.fromHsvObject(this.state.hsv)
    this.setState({ color: color })
  }

  // set the hue
  _setHue(hue) {
    this.state.hsv.h = hue
    this._update()
  }

  // set the saturation
  _setSaturation(saturation) {
    this.state.hsv.s = saturation
    this._update()
  }

  // set the value
  _setValue(value) {
    this.state.hsv.v = value
    this._update()
  }

  // set the saturation and the value
  _setSaturationAndValue(saturation, value) {
    this.state.hsv.s = saturation
    this.state.hsv.v = value
    this._update()
  }

  _getBackgroundHue() {
    return Colr.fromHsv(this.state.hsv.h, 100, 100).toHex()
  }

  _inputMap() {
    let hue = this._getBackgroundHue()
    let luminosity = this.state.color.toGrayscale()

    return colorMap({
      x: this.state.hsv.s,
      y: this.state.hsv.v,
      max: 100,
      backgroundColor: hue,
      className: cx({
        dark: luminosity <= 128,
        light: luminosity > 128,
      }),
      onChange: this._setSaturationAndValue.bind(this),
    })
  }

  _displayColorMap(){
    if (this.state.showPopup === false) return false
    return div({className: "controls colorpicker"},
      div({ className: "hue-slider" },
        hue_slider({
          value: this.state.hsv.h,
          max: 360,
          onChange: this._setHue.bind(this),
        })
      ),
      this._inputMap(),
    )
  }

  _getCurrentHex() {
    return Colr.fromHsvObject(this.state.hsv).toHex()
  }

  _getContrastYIQ(hexcolor){
    var r = parseInt(hexcolor.substr(1,2),16)
    var g = parseInt(hexcolor.substr(3,2),16)
    var b = parseInt(hexcolor.substr(5,2),16)
    var yiq = ((r*299)+(g*587)+(b*114))/1000

    return (yiq >= 128) ? 'black' : 'white'
  }

  render() {
    return div({className: cx(sizeClassNames(this.props))},
      div({className: formGroupCx(this.props)},
        label(this.props),
        input(Object.assign({}, this.props.inputHtml, {
            valueLink: {
              value: this._getCurrentHex(),
              requestChange: this._update.bind(this),
            },
            disabled: true,
            className: cx(this.props.inputHtml.className, "form-control"),
            onClick: this._onInputClick.bind(this),
            style: {
               backgroundColor: this._getCurrentHex(),
               color: this._getContrastYIQ(this._getCurrentHex()),
            },
          }),
        ),
        this._displayColorMap(),
        errorList(this.props.errors),
      )
    )
  }

}
<commit_msg>Fix Name Of Method _displayColor<commit_after>let React = require("react")
let Colr = require('colr')
let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js")
let {div, input, img} = React.DOM
let cx = require("classnames")

let colorMap = React.createFactory(require("./color/map"))
let sample =  React.createFactory(require("./color/sample"))
let hue_slider =  React.createFactory(require("./color/hue_slider"))

export default class extends React.Component {

  static displayName = "Frig.friggingBootstrap.Color"

  static defaultProps = Object.assign(require("../default_props.js"), {
    color: "#000000",
  })

  propTypes: {
    color: React.PropTypes.string,
  }

  state = this._getStateFrom(this.props.color)

  componentDidMount() {
   this.setState({ showPopup: false })
  }

  // generate state object from a hex string
  _getStateFrom(color) {
    color = Colr.fromHex(color)
    return {
      color: color,
      hsv: color.toRawHsvObject(),
    }
  }

  _onInputClick() {
    this.setState({
      showPopup: !this.state.showPopup,
    })
  }

  // replace current color with another one
  _loadColor(color) {
    this.setState(this._getStateFrom(color))
  }

  // update the current color using the raw hsv values
  _update() {
    let color = Colr.fromHsvObject(this.state.hsv)
    this.setState({ color: color })
  }

  // set the hue
  _setHue(hue) {
    this.state.hsv.h = hue
    this._update()
  }

  // set the saturation
  _setSaturation(saturation) {
    this.state.hsv.s = saturation
    this._update()
  }

  // set the value
  _setValue(value) {
    this.state.hsv.v = value
    this._update()
  }

  // set the saturation and the value
  _setSaturationAndValue(saturation, value) {
    this.state.hsv.s = saturation
    this.state.hsv.v = value
    this._update()
  }

  _getBackgroundHue() {
    return Colr.fromHsv(this.state.hsv.h, 100, 100).toHex()
  }

  _inputMap() {
    let hue = this._getBackgroundHue()
    let luminosity = this.state.color.toGrayscale()

    return colorMap({
      x: this.state.hsv.s,
      y: this.state.hsv.v,
      max: 100,
      backgroundColor: hue,
      className: cx({
        dark: luminosity <= 128,
        light: luminosity > 128,
      }),
      onChange: this._setSaturationAndValue.bind(this),
    })
  }

  _displayColor(){
    if (this.state.showPopup === false) return false
    return div({className: "controls colorpicker"},
      div({ className: "hue-slider" },
        hue_slider({
          value: this.state.hsv.h,
          max: 360,
          onChange: this._setHue.bind(this),
        })
      ),
      this._inputMap(),
    )
  }

  _getCurrentHex() {
    return Colr.fromHsvObject(this.state.hsv).toHex()
  }

  _getContrastYIQ(hexcolor){
    var r = parseInt(hexcolor.substr(1,2),16)
    var g = parseInt(hexcolor.substr(3,2),16)
    var b = parseInt(hexcolor.substr(5,2),16)
    var yiq = ((r*299)+(g*587)+(b*114))/1000

    return (yiq >= 128) ? 'black' : 'white'
  }

  render() {
    return div({className: cx(sizeClassNames(this.props))},
      div({className: formGroupCx(this.props)},
        label(this.props),
        input(Object.assign({}, this.props.inputHtml, {
            valueLink: {
              value: this._getCurrentHex(),
              requestChange: this._update.bind(this),
            },
            disabled: true,
            className: cx(this.props.inputHtml.className, "form-control"),
            onClick: this._onInputClick.bind(this),
            style: {
               backgroundColor: this._getCurrentHex(),
               color: this._getContrastYIQ(this._getCurrentHex()),
            },
          }),
        ),
        this._displayColor(),
        errorList(this.props.errors),
      )
    )
  }

}
<|endoftext|>


<commit_before>var current_id = null;

$(document).ready(function () {
  $('#shares-select').select2({
    ajax: {
      url: "/study/sharing/autocomplete/",
      dataType: 'json',
      delay: 250,
      data: function (params) {
        return {text: params.term};
      },
      cache: true
    },
    minimumInputLength: 1,
    formatResult: function (data, term) {
      return data;
    }
  });

  $('#shares-select').on("select2:select", function (e) {
    update_share(e.target.classList[0], {selected: e.params.data.text});
  });

  $('#shares-select').on("select2:unselect", function (e) {
    update_share(e.target.classList[0], {deselected: e.params.data.text});
  });
});

function modify_sharing(share_type, id) {
var shared_list;
current_id = id;
$.get('/' + share_type + '/sharing/', {id: id})
    .done(function(data) {
      var users_links = JSON.parse(data);
      var users = users_links.users;
      //empty dropdown and repopulate with new study shared values
      $('#shares-select').html('');
      for(var i=0;i<users.length;i++) {
        var shared = new Option(users[i], users[i], true, true);
        $("#shares-select").append(shared).trigger('change');
      }
      $("#shares-select").trigger("change");
    });
}

function update_share(share_type, params) {
  data = params || {};
  data.id = current_id;
  $.get('/' + share_type + '/sharing/', data)
    .done(function(data) {
      users_links = JSON.parse(data);
      links = users_links.links;
      $("#shared_html_"+current_id).html(links);
    });
}<commit_msg>indentation<commit_after>var current_id = null;

$(document).ready(function () {
  $('#shares-select').select2({
    ajax: {
      url: "/study/sharing/autocomplete/",
      dataType: 'json',
      delay: 250,
      data: function (params) {
        return {text: params.term};
      },
      cache: true
    },
    minimumInputLength: 1,
    formatResult: function (data, term) {
      return data;
    }
  });

  $('#shares-select').on("select2:select", function (e) {
    update_share(e.target.classList[0], {selected: e.params.data.text});
  });

  $('#shares-select').on("select2:unselect", function (e) {
    update_share(e.target.classList[0], {deselected: e.params.data.text});
  });
});

function modify_sharing(share_type, id) {
  var shared_list;
  current_id = id;
  $.get('/' + share_type + '/sharing/', {id: id})
    .done(function(data) {
      var users_links = JSON.parse(data);
      var users = users_links.users;
      //empty dropdown and repopulate with new study shared values
      $('#shares-select').html('');
      for(var i=0;i<users.length;i++) {
        var shared = new Option(users[i], users[i], true, true);
        $("#shares-select").append(shared).trigger('change');
      }
      $("#shares-select").trigger("change");
    });
}

function update_share(share_type, params) {
  data = params || {};
  data.id = current_id;
  $.get('/' + share_type + '/sharing/', data)
    .done(function(data) {
      users_links = JSON.parse(data);
      links = users_links.links;
      $("#shared_html_"+current_id).html(links);
    });
}<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Panel, Col, Row, Button } from 'react-bootstrap';
import { VictoryBar, VictoryChart, VictoryAxis } from 'victory';
var moment = require('moment');

import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom';

const moment = require('moment');

export default class RoomPage extends Component {
	constructor(props) {
		super(props)
		this.state = {

		}
	}

	render() {
		const roomName = this.props.match.params.roomName;
		return (

				<Row>
					<StatusPanel roomName={roomName} />
					<ButtonGroup roomName={roomName} />
				</Row>
				<Row>
					<DailyPanel roomName={roomName} />
					<WeeklyPanel roomName={roomName} />
				</Row>

		)
	}
}

class ButtonGroup extends Component {
	render() {
		return (
			<Col md={4}>
				<Link to="/reportmatch"><Button block bsSize="large">Report Match</Button></Link>
				<Link to={`/matches/${this.props.roomName}`}><Button block bsSize="large">View Match History</Button></Link>
			</Col>
		)
	}
}

class WeeklyPanel extends Component {
	constructor(props) {
		super(props)
		this.state = {

		}
	}

	render() {
		const roomName = this.props.roomName;
		return (
			<Col md={6}>
				<Panel header={
Weekly Use
} style={{textAlign:"center"}}>
					<WeeklyChart roomName={roomName} />
				</Panel>
			</Col>
		)
	}
}

class WeeklyChart extends Component {
	constructor() {
		super();
		this.state = {
			data: null,
			updatedAt:null
		}
	}

	componentDidMount() {
		const query = '/api/rooms/' + this.props.roomName + '/currentWeekDataPoints';
	    console.log(query);
	    fetch(query)
	      .then(response => {
	        if (!response.ok) {
	          console.log('response')
	          console.log(response.status)
	          throw new Error(`status ${response.status}`);
	        }
	        return response.json();
	      }).then(json => {
	        console.log(json);
	        this.setState({
	          data: json,
	        })
	      }).catch(e => {
	        throw e;
	      });
	  }

	render() {
		if (!this.state.data) {
			return

		}

		const updatedAt = this.state.updatedAt;

		// console.log(updatedAt);
		// updatedAt.setDay(updatedAt.getDay() - 1);
		// console.log(updatedAt);

		const formattedData = this.state.data.map((dp, index) => {
			return {
				hour: index+1,
				value: dp
			}
		});

		// console.log(formattedData);

		const ticks = [...Array(7).keys()].map(dp => dp+1);

		return (

			    <VictoryChart
			        domainPadding={20} >
			        <VictoryAxis
			          tickValues={ticks}
			          label="Days"
			          // tickFormat={["Quarter 1", "Quarter 2", "Quarter 3", "Quarter 4"]}
			        />
			        <VictoryAxis
			          dependentAxis
			          label="% Utilization"
			        />
			        <VictoryBar
			          data={formattedData}
			          style={{ data: { fill: "#005cb3" } }}
			          x="hour"
			          y="value"
			        />
			      </VictoryChart>

		)
	}
}

class DailyPanel extends Component {
	constructor(props) {
		super(props)
		this.state = {

		}
	}

	render() {
		const roomName = this.props.roomName;
		return (
			<Col md={6}>
				<Panel header={
Daily Use
} style={{textAlign:"center"}}>
					<DailyChart roomName={roomName} />
				</Panel>
			</Col>
		)
	}
}

class DailyChart extends Component {
	constructor() {
		super();
		this.state = {
			data: null,
			updatedAt:null
		}
	}

	componentDidMount() {
		const query = '/api/rooms/' + this.props.roomName + '/currentDayDataPoints';
	    console.log(query);
	    fetch(query)
	      .then(response => {
	        if (!response.ok) {
	          console.log('response')
	          console.log(response.status)
	          throw new Error(`status ${response.status}`);
	        }
	        return response.json();
	      }).then(json => {
	        console.log(json);
	        this.setState({
	          data: json.data,
	          updatedAt: json.updated_at
	        })
	      }).catch(e => {
	        throw e;
	      });
	  }

	render() {
		if (!this.state.data) {
			return

		}

		const updatedAt = this.state.updatedAt;

		// console.log(updatedAt);
		// updatedAt.setDay(updatedAt.getDay() - 1);
		// console.log(updatedAt);

		const formattedData = this.state.data.map((dp, index) => {
			return {
				hour: index + 1,
				value: dp
			}
		});

		// console.log(formattedData);

		const ticks = [...Array(4).keys()].map(dp => (dp) * 6);

		const timeTicks = this.state.data.map((dp, index) => {
			const t = moment(this.state.updatedAt).subtract(index, 'hours');
			return t.fromNow();
		})
		// .filter((dp, index) => {
		// 	return index % 6 == 0;
		// });

		console.log(timeTicks);

		return (

			    <VictoryChart
			        domainPadding={20} >
			        <VictoryAxis
			          fixLabelOverlap={true}
			          tickValues={timeTicks}
			          tickFormat={(t) => t.toString()}
			          label="Hours"
			          // tickFormat={["Quarter 1", "Quarter 2", "Quarter 3", "Quarter 4"]}
			        />
			        <VictoryAxis
			          dependentAxis
			          label="% Utilization"

			        />
			        <VictoryBar
			          data={formattedData}
			          style={{ data: { fill: "#005cb3" } }}
			          x="hour"
			          y="value"
			        />
			      </VictoryChart>

		)
	}
}

class StatusPanel extends Component {
	constructor(props) {
		super(props)
		this.state = {
			occupied: null,
			lastOpen: null,
			averageUseTime:null
		}
	}

	componentDidMount() {
		const query = '/api/rooms/' + this.props.roomName;
	    console.log(query);
	    fetch(query)
	      .then(response => {
	        if (!response.ok) {
	          console.log('response')
	          console.log(response.status)
	          throw new Error(`status ${response.status}`);
	        }
	        return response.json();
	      }).then(json => {
	        console.log(json);
	        this.setState({
	        	occupied: json.occupied,
	        	lastOpen: json.lastOpen,
	        	averageUseTime: json.averageUseTime
	        });
	      }).catch(e => {
	        throw e;
	      });
	}

	render() {
		const roomName = this.props.roomName;
		console.log("this.state.occupied");
		console.log(this.state.occupied);
		if (this.state.occupied === null) {
			return

;
		}

		return (
			<Col md={8}>
				<Panel header={
{roomName}
} style={{textAlign:"center"}}>
					<Col md={4}>

						<svg>
							<circle cx={75} cy={75} r={75} fill={this.state.occupied ? "red" : "green"} />
						</svg>

					</Col>
					<Col md={8}>
						{this.state.occupied ?

OCCUPIED

Last Open: {moment(this.state.lastOpen).calendar()}

Average Use: {this.state.averageUseTime}

 :

OPEN

Last Open: {moment(this.state.lastOpen).calendar()}

Average Use: {this.state.averageUseTime}

					}
					</Col>
				</Panel>
			</Col>
		)
	}
}

<commit_msg>Bug Fix<commit_after>import React, { Component } from 'react';
import { Panel, Col, Row, Button } from 'react-bootstrap';
import { VictoryBar, VictoryChart, VictoryAxis } from 'victory';
var moment = require('moment');

import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom';

const moment = require('moment');

export default class RoomPage extends Component {
	constructor(props) {
		super(props)
		this.state = {

		}
	}

	render() {
		const roomName = this.props.match.params.roomName;
		return (

				<Row>
					<StatusPanel roomName={roomName} />
					<ButtonGroup roomName={roomName} />
				</Row>
				<Row>
					<DailyPanel roomName={roomName} />
					<WeeklyPanel roomName={roomName} />
				</Row>

		)
	}
}

class ButtonGroup extends Component {
	render() {
		return (
			<Col md={4}>
				<Link to="/reportmatch"><Button block bsSize="large">Report Match</Button></Link>
				<Link to={`/matches/${this.props.roomName}`}><Button block bsSize="large">View Match History</Button></Link>
			</Col>
		)
	}
}

class WeeklyPanel extends Component {
	constructor(props) {
		super(props)
		this.state = {

		}
	}

	render() {
		const roomName = this.props.roomName;
		return (
			<Col md={6}>
				<Panel header={
Weekly Use
} style={{textAlign:"center"}}>
					<WeeklyChart roomName={roomName} />
				</Panel>
			</Col>
		)
	}
}

class WeeklyChart extends Component {
	constructor() {
		super();
		this.state = {
			data: null,
			updatedAt:null
		}
	}

	componentDidMount() {
		const query = '/api/rooms/' + this.props.roomName + '/currentWeekDataPoints';
	    console.log(query);
	    fetch(query)
	      .then(response => {
	        if (!response.ok) {
	          console.log('response')
	          console.log(response.status)
	          throw new Error(`status ${response.status}`);
	        }
	        return response.json();
	      }).then(json => {
	        console.log(json);
	        this.setState({
	          data: json,
	        })
	      }).catch(e => {
	        throw e;
	      });
	  }

	render() {
		if (!this.state.data) {
			return

		}

		const updatedAt = this.state.updatedAt;

		// console.log(updatedAt);
		// updatedAt.setDay(updatedAt.getDay() - 1);
		// console.log(updatedAt);

		const formattedData = this.state.data.map((dp, index) => {
			return {
				hour: index+1,
				value: dp
			}
		});

		// console.log(formattedData);

		const ticks = [...Array(7).keys()].map(dp => dp+1);

		return (

			    <VictoryChart
			        domainPadding={20} >
			        <VictoryAxis
			          tickValues={ticks}
			          label="Days"
			          // tickFormat={["Quarter 1", "Quarter 2", "Quarter 3", "Quarter 4"]}
			        />
			        <VictoryAxis
			          dependentAxis
			          label="% Utilization"
			        />
			        <VictoryBar
			          data={formattedData}
			          style={{ data: { fill: "#005cb3" } }}
			          x="hour"
			          y="value"
			        />
			      </VictoryChart>

		)
	}
}

class DailyPanel extends Component {
	constructor(props) {
		super(props)
		this.state = {

		}
	}

	render() {
		const roomName = this.props.roomName;
		return (
			<Col md={6}>
				<Panel header={
Daily Use
} style={{textAlign:"center"}}>
					<DailyChart roomName={roomName} />
				</Panel>
			</Col>
		)
	}
}

class DailyChart extends Component {
	constructor() {
		super();
		this.state = {
			data: null,
			updatedAt:null
		}
	}

	componentDidMount() {
		const query = '/api/rooms/' + this.props.roomName + '/currentDayDataPoints';
	    console.log(query);
	    fetch(query)
	      .then(response => {
	        if (!response.ok) {
	          console.log('response')
	          console.log(response.status)
	          throw new Error(`status ${response.status}`);
	        }
	        return response.json();
	      }).then(json => {
	        console.log(json);
	        this.setState({
	          data: json.data,
	          updatedAt: json.updated_at
	        })
	      }).catch(e => {
	        throw e;
	      });
	  }

	render() {
		if (!this.state.data) {
			return

		}

		const updatedAt = this.state.updatedAt;

		// console.log(updatedAt);
		// updatedAt.setDay(updatedAt.getDay() - 1);
		// console.log(updatedAt);

		const formattedData = this.state.data.map((dp, index) => {
			return {
				hour: index + 1,
				value: dp
			}
		});

		// console.log(formattedData);

		const ticks = [...Array(4).keys()].map(dp => (dp) * 6);

		const timeTicks = this.state.data.map((dp, index) => {
			const t = moment(this.state.updatedAt).subtract(index, 'hours');
			return t.fromNow();
		}).reverse();
		// .filter((dp, index) => {
		// 	return index % 6 == 0;
		// });

		console.log(timeTicks);

		return (

			    <VictoryChart
			        domainPadding={20} >
			        <VictoryAxis
			          fixLabelOverlap={true}
			          tickValues={timeTicks}
			          tickFormat={(t) => t.toString()}
			          label="Hours"
			          // tickFormat={["Quarter 1", "Quarter 2", "Quarter 3", "Quarter 4"]}
			        />
			        <VictoryAxis
			          dependentAxis
			          label="% Utilization"

			        />
			        <VictoryBar
			          data={formattedData}
			          style={{ data: { fill: "#005cb3" } }}
			          x="hour"
			          y="value"
			        />
			      </VictoryChart>

		)
	}
}

class StatusPanel extends Component {
	constructor(props) {
		super(props)
		this.state = {
			occupied: null,
			lastOpen: null,
			averageUseTime:null
		}
	}

	componentDidMount() {
		const query = '/api/rooms/' + this.props.roomName;
	    console.log(query);
	    fetch(query)
	      .then(response => {
	        if (!response.ok) {
	          console.log('response')
	          console.log(response.status)
	          throw new Error(`status ${response.status}`);
	        }
	        return response.json();
	      }).then(json => {
	        console.log(json);
	        this.setState({
	        	occupied: json.occupied,
	        	lastOpen: json.lastOpen,
	        	averageUseTime: json.averageUseTime
	        });
	      }).catch(e => {
	        throw e;
	      });
	}

	render() {
		const roomName = this.props.roomName;
		console.log("this.state.occupied");
		console.log(this.state.occupied);
		if (this.state.occupied === null) {
			return

;
		}

		return (
			<Col md={8}>
				<Panel header={
{roomName}
} style={{textAlign:"center"}}>
					<Col md={4}>

						<svg>
							<circle cx={75} cy={75} r={75} fill={this.state.occupied ? "red" : "green"} />
						</svg>

					</Col>
					<Col md={8}>
						{this.state.occupied ?

OCCUPIED

Last Open: {moment(this.state.lastOpen).calendar()}

Average Use: {this.state.averageUseTime}

 :

OPEN

Last Open: {moment(this.state.lastOpen).calendar()}

Average Use: {this.state.averageUseTime}

					}
					</Col>
				</Panel>
			</Col>
		)
	}
}

<|endoftext|>


<commit_before><commit_msg>allow numerical strings where numbers are required.<commit_after><|endoftext|>


<commit_before>N.Template({},
  function(context, src, sink) {
    var display = {
      className: 'N.UI.PiNetwork',
      width: 1.0,
      height: 2.5,
      neurons: [{
        name: src,
        x: 0.5,
        y: 0.75,
        radius: 0.39
      },{
        name: sink,
        x: 0.5,
        y: 1.75,
        radius: 0.35
      }],
      connections: [

      ],
      renderMappings: {
        'columnSpacing': 0.3,
        'rowSpacing': 0.3,
        'SS'  : { template: 'N.UI.StandardNeuronTemplates.Stellate',              radius: 0.3 },
        'IN'  : { template: 'N.UI.StandardNeuronTemplates.InhibitoryInterneuron', radius: 0.3 },
        'SRC' : { template: 'N.UI.StandardNeuronTemplates.InputSource',           radius: 0.2 },
        'IP'  : { template: 'N.UI.StandardNeuronTemplates.InputSource',           radius: 0.2 },
        'SNK' : { template: 'N.UI.StandardNeuronTemplates.OutputSink',            radius: 0.2 },
        'OP'  : { template: 'N.UI.StandardNeuronTemplates.OutputSink',            radius: 0.2 },
        'RN'  : { template: 'N.UI.StandardNeuronTemplates.ExcitatoryInterneuron', radius: 0.3 },
        'Default' :  { template: 'N.UI.StandardNeuronTemplates.ExcitatoryInterneuron', radius: 0.2 }
      }
    };
    context.self.display = display;
  }
);
<commit_msg>Naming and sizes.<commit_after>N.Template({},
  function(context, src, sink) {
    var display = {
      className: 'N.UI.PiNetwork',
      width: 1.0,
      height: 2.5,
      grid: { display: true, spacing: 0.05 },
      backgroundColor: '#FF0000',
      neurons: [{
        name: "SRC",
        x: 0.5,
        y: 0.75,
        radius: 0.25
      },{
        name: sink,
        x: 0.5,
        y: 1.75,
        radius: 0.175
      }],
      connections: [{
        name: ":" + src + ">OP->:" + sink + ">IP",
        route: "s"
      }],
      renderMappings: {
        'columnSpacing': 0.3,
        'rowSpacing': 0.3,
        'SS'  : { template: 'N.UI.StandardNeuronTemplates.Stellate',              radius: 0.3 },
        'IN'  : { template: 'N.UI.StandardNeuronTemplates.InhibitoryInterneuron', radius: 0.3 },
        'SRC' : { template: 'N.UI.StandardNeuronTemplates.InputSource',           radius: 0.2 },
        'IP'  : { template: 'N.UI.StandardNeuronTemplates.InputSource',           radius: 0.2 },
        'SNK' : { template: 'N.UI.StandardNeuronTemplates.OutputSink',            radius: 0.2 },
        'OP'  : { template: 'N.UI.StandardNeuronTemplates.OutputSink',            radius: 0.2 },
        'RN'  : { template: 'N.UI.StandardNeuronTemplates.ExcitatoryInterneuron', radius: 0.3 },
        'Default' :  { template: 'N.UI.StandardNeuronTemplates.ExcitatoryInterneuron', radius: 0.2 }
      }
    };
    context.self.display = display;
  }
);
<|endoftext|>


<commit_before>// -*- coding: utf-8 -*-
//
// (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
//
// See LICENSE comming with the source of 'trex' for details.
//
'use strict';

var trexServices = angular.module('trex.services', ['ngResource']);

trexServices.factory('Conf', function($location) {
    function getRootUrl() {
        var rootUrl = $location.protocol() + '://' + $location.host();
        if ($location.port())
            rootUrl += ':' + $location.port();
        return rootUrl;
    };

    return {
        'apiBase': '/api/1',
        'rootUrl': getRootUrl(),
    };
});

trexServices.factory('Project', ['$resource', 'Conf',
    function($resource, Conf) {
        return $resource(Conf.apiBase + '/projects/:projectId',
            {projectId: '@id'},
            {entries: {method: 'GET', isArray: true,
                       url: Conf.apiBase + '/projects/:projectId/entries',
                       params: {projectId:'@id'}
                      }
           }
        );
    }
]);

trexServices.factory('Entry', ['$resource', 'Conf',
    function($resource, Conf) {
        return $resource(Conf.apiBase + '/entries/:entryId', {entryId: '@id'}, {
        });
    }
]);
<commit_msg>Update coding style<commit_after>// -*- coding: utf-8 -*-
//
// (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
//
// See LICENSE comming with the source of 'trex' for details.
//
'use strict';

var trexServices = angular.module('trex.services', ['ngResource']);

trexServices.factory('Conf', function($location) {
    function getRootUrl() {
        var rootUrl = $location.protocol() + '://' + $location.host();
        if ($location.port())
            rootUrl += ':' + $location.port();
        return rootUrl;
    };

    return {
        'apiBase': '/api/1',
        'rootUrl': getRootUrl()
    };
});

trexServices.factory('Project', ['$resource', 'Conf',
    function($resource, Conf) {
        return $resource(Conf.apiBase + '/projects/:projectId',
            {projectId: '@id'},
            {entries: {method: 'GET', isArray: true,
                       url: Conf.apiBase + '/projects/:projectId/entries',
                       params: {projectId: '@id'}
                      }
           }
        );
    }
]);

trexServices.factory('Entry', ['$resource', 'Conf',
    function($resource, Conf) {
        return $resource(Conf.apiBase + '/entries/:entryId', {entryId: '@id'}, {
        });
    }
]);
<|endoftext|>


<commit_before>// Define compose URL <to> will be replaces with a CSV list of e-mails
var composeURL = 'https://mail.google.com/mail/u/<accountNumber>/?view=cm&fs=1&tf=1&source=mailto&bcc=<to>';

// Batch reply button
function getBatchReplyButton() {
    return $("div[gh='mtb'] .batch-reply");
}

// Get checked conversations
function getCheckedConversations() {
    return $("div[aria-checked='true']");
}

// Get conversation e-mails
function getConversationEmails(message) {
    return message.parents('tr').find("span[email]");
}

// Conversations list view
function getConversationsListView() {
    return $(".UI[gh='tl']");
}

// Conversations menu cont.
function getMenuContainer() {
    return $("div[gh='mtb']").children(":first").children(":first");
}

// Batch reply button HTML
function getBatchReplyButtonHTML() {
    return '
' +
        '
' +
        'Reply' +
        '
' +
        '
';
}

// Inject batch-reply button (called multiple times)
function refreshBatchReplyButton() {
    // Get batch reply button if already injected
    var batchReply = getBatchReplyButton();

    // Get conversations view to check if visible
    var conversationsView = getConversationsListView();

    // Not injected?
    if (!batchReply.length) {
        // Conversations view visible?
        if (conversationsView.length) {
            // Get menu container (options above list)
            var menuContainer = getMenuContainer();

            // Inject batch reply button
            menuContainer.append(getBatchReplyButtonHTML());

            // Handle batch-reply click
            getBatchReplyButton().click(function () {
                // Call batch reply function
                prepareBatchReply();
            });
        }
    }

    // Not in message list?
    if (!conversationsView.length) {
        // Hide batch reply
        batchReply.parent().hide();
    }
    else {
        // Show batch reply
        batchReply.parent().show();
    }
}

function prepareBatchReply() {
    // Prepare unique emails array
    var emails = [];

    // Loop over checked items
    getCheckedConversations().each(function () {
        // Get checked item
        var conversation = $(this);

        // Get all e-mails related to this conversation
        getConversationEmails(conversation).each(function () {
            // Get email
            var email = $(this);

            // Is it my e-mail?
            if (email.attr('name') == 'me') {
                // Skip it
                return;
            }

            // Get e-mail address
            var email = email.attr('email');

            // Not already added?
            if (emails.indexOf(email) == -1) {
                // Add it to emails array
                emails.push(email);
            }
        });
    });

    // Got anything?
    if (emails.length > 0) {
        // Convert to string and URL-encode
        emails = encodeURIComponent(emails.join(', '));

        // Prepare URL
        var url = composeURL;

        // Insert <to> (list of csv e-mails)
        url = url.replace('<to>', emails);

        // Insert logged in account number
        url = url.replace('<accountNumber>', getLoggedInAccountNumber());

        // Open window
        window.open(url);
    }
}

function getLoggedInAccountNumber() {
    // Extract account number from page path
    var result = /mail\/u\/([0-9]+)\//g.exec(window.location.pathname);

    // All done
    return result[1];
}

// Listen for events from the background script
chrome.extension.onMessage.addListener(
    function (request, sender, sendResponse) {
        // Injection requested?
        if (request.inject) {
            // Refresh button
            refreshBatchReplyButton();
        }
    }
);

// Handle HTML5 page change
window.onpopstate = history.onpushstate = function (e) {
    // Refresh button
    refreshBatchReplyButton();
}<commit_msg>Improve button text color<commit_after>// Define compose URL <to> will be replaces with a CSV list of e-mails
var composeURL = 'https://mail.google.com/mail/u/<accountNumber>/?view=cm&fs=1&tf=1&source=mailto&bcc=<to>';

// Batch reply button
function getBatchReplyButton() {
    return $("div[gh='mtb'] .batch-reply");
}

// Get checked conversations
function getCheckedConversations() {
    return $("div[aria-checked='true']");
}

// Get conversation e-mails
function getConversationEmails(message) {
    return message.parents('tr').find("span[email]");
}

// Conversations list view
function getConversationsListView() {
    return $(".UI[gh='tl']");
}

// Conversations menu cont.
function getMenuContainer() {
    return $("div[gh='mtb']").children(":first").children(":first");
}

// Batch reply button HTML
function getBatchReplyButtonHTML() {
    return '
' +
        '
' +
        'Reply' +
        '
' +
        '
';
}

// Inject batch-reply button (called multiple times)
function refreshBatchReplyButton() {
    // Get batch reply button if already injected
    var batchReply = getBatchReplyButton();

    // Get conversations view to check if visible
    var conversationsView = getConversationsListView();

    // Not injected?
    if (!batchReply.length) {
        // Conversations view visible?
        if (conversationsView.length) {
            // Get menu container (options above list)
            var menuContainer = getMenuContainer();

            // Inject batch reply button
            menuContainer.append(getBatchReplyButtonHTML());

            // Handle batch-reply click
            getBatchReplyButton().click(function () {
                // Call batch reply function
                prepareBatchReply();
            });
        }
    }

    // Not in message list?
    if (!conversationsView.length) {
        // Hide batch reply
        batchReply.parent().hide();
    }
    else {
        // Show batch reply
        batchReply.parent().show();
    }
}

function prepareBatchReply() {
    // Prepare unique emails array
    var emails = [];

    // Loop over checked items
    getCheckedConversations().each(function () {
        // Get checked item
        var conversation = $(this);

        // Get all e-mails related to this conversation
        getConversationEmails(conversation).each(function () {
            // Get email
            var email = $(this);

            // Is it my e-mail?
            if (email.attr('name') == 'me') {
                // Skip it
                return;
            }

            // Get e-mail address
            var email = email.attr('email');

            // Not already added?
            if (emails.indexOf(email) == -1) {
                // Add it to emails array
                emails.push(email);
            }
        });
    });

    // Got anything?
    if (emails.length > 0) {
        // Convert to string and URL-encode
        emails = encodeURIComponent(emails.join(', '));

        // Prepare URL
        var url = composeURL;

        // Insert <to> (list of csv e-mails)
        url = url.replace('<to>', emails);

        // Insert logged in account number
        url = url.replace('<accountNumber>', getLoggedInAccountNumber());

        // Open window
        window.open(url);
    }
}

function getLoggedInAccountNumber() {
    // Extract account number from page path
    var result = /mail\/u\/([0-9]+)\//g.exec(window.location.pathname);

    // All done
    return result[1];
}

// Listen for events from the background script
chrome.extension.onMessage.addListener(
    function (request, sender, sendResponse) {
        // Injection requested?
        if (request.inject) {
            // Refresh button
            refreshBatchReplyButton();
        }
    }
);

// Handle HTML5 page change
window.onpopstate = history.onpushstate = function (e) {
    // Refresh button
    refreshBatchReplyButton();
}<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var JSDOM = require('jsdom').JSDOM;

module.exports = function makeSchema(plotlyPath, schemaPath) {
    return function() {
        var plotlyjsCode = fs.readFileSync(plotlyPath, 'utf-8');

        var w = new JSDOM('', {runScripts: 'dangerously'}).window;

        // jsdom by itself doesn't support getContext, and adding the npm canvas
        // package is annoying and platform-dependent.
        // see https://github.com/tmpvar/jsdom/issues/1782
        w.HTMLCanvasElement.prototype.getContext = function() { return null; };

        w.eval(plotlyjsCode);

        var plotSchema = w.Plotly.PlotSchema.get();
        var plotSchemaStr = JSON.stringify(plotSchema, null, 4);
        fs.writeFileSync(schemaPath, plotSchemaStr);

        console.log('ok ' + path.basename(schemaPath));
    };
};
<commit_msg>mock out createObjectURL for makeSchema task<commit_after>var fs = require('fs');
var path = require('path');
var JSDOM = require('jsdom').JSDOM;

module.exports = function makeSchema(plotlyPath, schemaPath) {
    return function() {
        var plotlyjsCode = fs.readFileSync(plotlyPath, 'utf-8');

        var w = new JSDOM('', {runScripts: 'dangerously'}).window;

        // jsdom by itself doesn't support getContext, and adding the npm canvas
        // package is annoying and platform-dependent.
        // see https://github.com/tmpvar/jsdom/issues/1782
        w.HTMLCanvasElement.prototype.getContext = function() { return null; };
        w.URL.createObjectURL = function() { return null; };

        w.eval(plotlyjsCode);

        var plotSchema = w.Plotly.PlotSchema.get();
        var plotSchemaStr = JSON.stringify(plotSchema, null, 4);
        fs.writeFileSync(schemaPath, plotSchemaStr);

        console.log('ok ' + path.basename(schemaPath));
    };
};
<|endoftext|>


<commit_before>/* ***********************************************************************************************

    Unify Project

    Homepage: unify-project.org
    License: MIT + Apache (V2)
    Copyright: 2009-2011 Deutsche Telekom AG, Germany, http://telekom.com

*********************************************************************************************** */

qx.Class.define("unify.view.PopOverManager",
{
  extend : qx.core.Object,
  type : "singleton",

  /*
  *****************************************************************************
     CONSTRUCTOR
  *****************************************************************************
  */

  construct : function()
  {
    this.base(arguments);

    this.__root = document.body;
    this.__viewManagers = {};
  },

  /*
  *****************************************************************************
     MEMBERS
  *****************************************************************************
  */

  members :
  {
    /** {Map} ID to view manager registry */
    __viewManagers : null,

    /**
     * Whether the given view manager is registered
     *
     * @param {unify.view.ViewManager} The view manager to query for
     * @return {Boolean} Whether the view manager is registered
     */
    has : function(viewManager) {
      return !!this.__viewManagers[viewManager.getId()];
    },

    /**
     * Adds a view manager to the registry
     *
     * @param viewManager {unify.view.ViewManager} View manager to add
     */
    add : function(viewManager)
    {
      var registry = this.__viewManagers;
      var id = viewManager.getId();

      if (qx.core.Variant.isSet("qx.debug", "on"))
      {
        if (registry[id]) {
          throw new Error("Already registered: " + id);
        }
      }

      this.debug("Register ViewManager: " + viewManager);
      registry[id] = viewManager;

      // Move to root
      if (viewManager.isCreated()) {
        this.__root.appendChild(viewManager.getElement());
      }
    },

    /**
     * Removes a view manager to the registry
     *
     * @param viewManager {unify.view.ViewManager} View manager to remove
     */
    remove : function(viewManager)
    {
      var registry = this.__viewManagers;
      var id = viewManager.getId();

      if (qx.core.Variant.isSet("qx.debug", "on"))
      {
        if (!registry[id]) {
          throw new Error("Unknown view manager: " + id);
        }
      }

      this.debug("Unregister ViewManager: " + viewManager);
      delete registry[id];

      if (viewManager.isCreated()) {
        this.__root.removeChild(viewManager.getElement());
      }
    },

    /**
     * Shows the view manager with the given ID.
     *
     * @param id {String} ID of view manager
     */
    show : function(id)
    {
      var registry = this.__viewManagers;
      var viewManager = registry[id];

      if (qx.core.Variant.isSet("qx.debug", "on"))
      {
        if (!viewManager) {
          throw new Error("Unknown view manager: " + id);
        }
      }

      var elem = viewManager.getElement();
      if (elem.parentNode != this.__root) {
        this.__root.appendChild(elem);
      }

      elem.style.display = "block";
    },

    /**
     * Hides the view manager with the given ID.
     *
     * @param id {String} ID of view manager
     */
    hide : function(id)
    {
      var registry = this.__viewManagers;
      var viewManager = registry[id];

      if (qx.core.Variant.isSet("qx.debug", "on"))
      {
        if (!viewManager) {
          throw new Error("Unknown view manager: " + id);
        }
      }

      if (viewManager.isCreated())
      {
        var elem = viewManager.getElement();
        elem.style.display = "none";
      }
    }
  },

  /*
  *****************************************************************************
     DESTRUCTOR
  *****************************************************************************
  */

  destruct : function() {
    this.__root = this.__viewManager = null;
  }
})<commit_msg>Added init() call to view manager<commit_after>/* ***********************************************************************************************

    Unify Project

    Homepage: unify-project.org
    License: MIT + Apache (V2)
    Copyright: 2009-2011 Deutsche Telekom AG, Germany, http://telekom.com

*********************************************************************************************** */

qx.Class.define("unify.view.PopOverManager",
{
  extend : qx.core.Object,
  type : "singleton",

  /*
  *****************************************************************************
     CONSTRUCTOR
  *****************************************************************************
  */

  construct : function()
  {
    this.base(arguments);

    this.__root = document.body;
    this.__viewManagers = {};
  },

  /*
  *****************************************************************************
     MEMBERS
  *****************************************************************************
  */

  members :
  {
    /** {Map} ID to view manager registry */
    __viewManagers : null,

    /**
     * Whether the given view manager is registered
     *
     * @param {unify.view.ViewManager} The view manager to query for
     * @return {Boolean} Whether the view manager is registered
     */
    has : function(viewManager) {
      return !!this.__viewManagers[viewManager.getId()];
    },

    /**
     * Adds a view manager to the registry
     *
     * @param viewManager {unify.view.ViewManager} View manager to add
     */
    add : function(viewManager)
    {
      var registry = this.__viewManagers;
      var id = viewManager.getId();

      if (qx.core.Variant.isSet("qx.debug", "on"))
      {
        if (registry[id]) {
          throw new Error("Already registered: " + id);
        }
      }

      this.debug("Register ViewManager: " + viewManager);
      registry[id] = viewManager;

      // Move to root
      if (viewManager.isCreated()) {
        this.__root.appendChild(viewManager.getElement());
      }
    },

    /**
     * Removes a view manager to the registry
     *
     * @param viewManager {unify.view.ViewManager} View manager to remove
     */
    remove : function(viewManager)
    {
      var registry = this.__viewManagers;
      var id = viewManager.getId();

      if (qx.core.Variant.isSet("qx.debug", "on"))
      {
        if (!registry[id]) {
          throw new Error("Unknown view manager: " + id);
        }
      }

      this.debug("Unregister ViewManager: " + viewManager);
      delete registry[id];

      if (viewManager.isCreated()) {
        this.__root.removeChild(viewManager.getElement());
      }
    },

    /**
     * Shows the view manager with the given ID.
     *
     * @param id {String} ID of view manager
     */
    show : function(id)
    {
      var registry = this.__viewManagers;
      var viewManager = registry[id];

      if (qx.core.Variant.isSet("qx.debug", "on"))
      {
        if (!viewManager) {
          throw new Error("Unknown view manager: " + id);
        }
      }

      var elem = viewManager.getElement();
      if (elem.parentNode != this.__root) {
        this.__root.appendChild(elem);
      }

      if (!viewManager.isInitialized()) {
        viewManager.init();
      }

      elem.style.display = "block";
    },

    /**
     * Hides the view manager with the given ID.
     *
     * @param id {String} ID of view manager
     */
    hide : function(id)
    {
      var registry = this.__viewManagers;
      var viewManager = registry[id];

      if (qx.core.Variant.isSet("qx.debug", "on"))
      {
        if (!viewManager) {
          throw new Error("Unknown view manager: " + id);
        }
      }

      if (viewManager.isCreated())
      {
        var elem = viewManager.getElement();
        elem.style.display = "none";
      }
    }
  },

  /*
  *****************************************************************************
     DESTRUCTOR
  *****************************************************************************
  */

  destruct : function() {
    this.__root = this.__viewManager = null;
  }
})<|endoftext|>


<commit_before><commit_msg>honor tapSvgToRunAndReset for endGame/reset, use protagonistSpriteIndex properly<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node

// 1. get species in reactome from /data/species/main
// 2. for each species get the pathways hierarchy from /data/eventsHierarchy/{species}
// 3. walk each TopLevelPathway and generate a pathway document keyed off of the stId, but
//    strip the species prefix off. We'll keep track of ancestors for each species.
//    That way, a gene from species x involved in reaction r will be associated only with pathways that were
//    successfully projected to species x.
// 4. Once this finishes, load the event documents into the pathways mongoDB collection.
// 5. Next, get xrefs for the gene product
// 6. Finally, go through the Ensembl2PlantToReactomeReactions.txt file and populate the pathway annotations
//    The output of the script is a JSON formatted object with gene stable id keys that will be used later
//    to update gene docs extracted from ensembl cores.

var argv = require('minimist')(process.argv.slice(2));
var request = require('sync-request');
var _ = require('lodash');
var readline = require('readline');
var fs = require('fs');
var collections = require('gramene-mongodb-config');

var genesToReactionsFile = argv.gtr || 'Ensembl2PlantReactomeReactions.txt';
var geneProductMappingFile = argv.gtp || 'gene_ids_by_pathway_and_species.tab';
var api = argv.api || 'http://plantreactomedev.oicr.on.ca/ContentService';

var docs = {};
var taxonLUT = {}; // key is speciesCode, value is taxon id
var speciesResponse = request('GET', api + '/data/species/main');
if (speciesResponse.statusCode == 200) {
  var species = JSON.parse(speciesResponse.getBody());
  species.forEach(function(s) {
    console.error('GET', api + '/data/eventsHierarchy/' + s.taxId);
    var hierarchyResponse = request('GET', api + '/data/eventsHierarchy/' + s.taxId);
    if (hierarchyResponse.statusCode !== 200) {
      throw hierarchyResponse;
    }
    var topLevelEvents = JSON.parse(hierarchyResponse.getBody());
    topLevelEvents.forEach(function(tle) {
      function parseEvent(event, taxon, pathFromRoot) {
        [r,speciesCode,id] = event.stId.split('-');
        if(!taxonLUT.hasOwnProperty(speciesCode)) {
          taxonLUT[speciesCode] = taxon;
        }
        if (!docs.hasOwnProperty(id)) {
          docs[id] = {
            _id: +id,
            name: event.name,
            type: event.type
          };
        }
        var ancestorField = 'ancestors_' + taxon;
        var lineageField = 'lineage_' + taxon;
        pathFromRoot.push(+id);
        if (! docs[id].hasOwnProperty(lineageField)) {
          docs[id][lineageField] = [];
        }
        docs[id][lineageField].push(_.clone(pathFromRoot));
        docs[id][ancestorField] = _.uniq(_.flatten(docs[id][lineageField]));
        if (event.children) {
          event.children.forEach(function(child) {
            parseEvent(child, taxon, _.clone(pathFromRoot));
          });
        }
      }
      parseEvent(tle,s.taxId,[]);
    });
  });
}
// create an ancestors field for each doc that is the union of all the species specific fields
_.forEach(docs, function(doc, id) {
  var ancestors = _.reduce(doc, function(result, value, key) {
    if (key[0] === 'a') {
      value.forEach(function(v) {
        result[v] =1;
      })
    }
    return result;
  },{});
  doc.ancestors = Object.keys(ancestors).map(function(id){return +id});
});

// insert docs to mongo
collections.pathways.mongoCollection().then(function(pathwaysCollection) {
  pathwaysCollection.remove({},function(err) {
    if (err) {
      throw err;
    }
    pathwaysCollection.insertMany(Object.values(docs),function(err, res) {
      if (err) {
        throw err;
      }
      console.error(`inserted ${res.insertedCount} events to pathways collection`);
      collections.closeMongoDatabase();
    });
  });
});
// get the plant reactome gene xrefs from the geneProductMappingFile
var genes = {};
readline.createInterface({
  input: fs.createReadStream(geneProductMappingFile),
  terminal: false
})
.on('line', function(line) {
  var fields = line.split("\t");
  /*
0  plant reactome gene product id
1  pathway
2  species
3  gene id
  */
  genes[fields[3]] = {
    xrefs: [
      {
        db: 'notGramene_Plant_Reactome',
        ids: [fields[0]]
      }
    ],
    annotations: {
      pathways: {
        ancestors: [],
        entries: []
      }
    }
  };
})
.on('close', function() {
  console.error('loaded geneProductMappings');
  // add ancestors to genes based on the hierarchy and the genesToReactionsFile
  readline.createInterface({
    input: require('fs').createReadStream(genesToReactionsFile),
    terminal: false
  })
  .on('line', function(line) {
    var fields = line.split("\t");
    /*
      fields are
  0  gene id
  1  reaction stable id
  2  pr link
  3  reaction name
  4  evidence code (always IEA?)
  5  species name
    */
    [r,speciesCode,id] = fields[1].split('-');
    if (docs.hasOwnProperty(id)) {
      if (!genes.hasOwnProperty(fields[0])) {
        genes[fields[0]] = {
          annotations: {
            pathways: {
              ancestors: [],
              entries: []
            }
          }
        };
      }
      var reactionAncestors = docs[id]['ancestors_' + taxonLUT[speciesCode]];
      if (!!genes[fields[0]].annotations.pathways.ancestors) {
        reactionAncestors = _.uniq(_.concat(genes[fields[0]].annotations.pathways.ancestors, reactionAncestors));
      }
      // remove id from the reactionAncestors and put it in entries
      _.pull(reactionAncestors,+id);
      genes[fields[0]].annotations.pathways.ancestors = reactionAncestors;
      genes[fields[0]].annotations.pathways.entries.push({
        id: fields[1],
        link: fields[2],
        name: fields[3]
      });
    }
  })
  .on('close', function() {
    console.error('loaded genesToReactions');
    console.log(JSON.stringify(genes,null,'  '));
  });
});

//
// Object.values(docs).forEach(function(doc) {
//   console.log(JSON.stringify(doc));
// });

<commit_msg>handle the taxonomy mismatch between ensembl and reactome.<commit_after>#!/usr/bin/env node

// 1. get species in reactome from /data/species/main
// 2. for each species get the pathways hierarchy from /data/eventsHierarchy/{species}
// 3. walk each TopLevelPathway and generate a pathway document keyed off of the stId, but
//    strip the species prefix off. We'll keep track of ancestors for each species.
//    That way, a gene from species x involved in reaction r will be associated only with pathways that were
//    successfully projected to species x.
// 4. Once this finishes, load the event documents into the pathways mongoDB collection.
// 5. Next, get xrefs for the gene product
// 6. Finally, go through the Ensembl2PlantToReactomeReactions.txt file and populate the pathway annotations
//    The output of the script is a JSON formatted object with gene stable id keys that will be used later
//    to update gene docs extracted from ensembl cores.

var argv = require('minimist')(process.argv.slice(2));
var request = require('sync-request');
var _ = require('lodash');
var readline = require('readline');
var fs = require('fs');
var collections = require('gramene-mongodb-config');

var genesToReactionsFile = argv.gtr || 'Ensembl2PlantReactomeReactions.txt';
var geneProductMappingFile = argv.gtp || 'gene_ids_by_pathway_and_species.tab';
var api = argv.api || 'http://plantreactomedev.oicr.on.ca/ContentService';

var docs = {};
var taxonLUT = {}; // key is speciesCode, value is taxon id
var speciesPrefixes = require('./merge_into_taxonomy.json');
_.forEach(speciesPrefixes, function(value,key) {
  taxonLUT[value.reactomePrefix] = +key;
});
var speciesResponse = request('GET', api + '/data/species/main');
if (speciesResponse.statusCode == 200) {
  var species = JSON.parse(speciesResponse.getBody());
  species.forEach(function(s) {
    console.error('GET', api + '/data/eventsHierarchy/' + s.taxId);
    var hierarchyResponse = request('GET', api + '/data/eventsHierarchy/' + s.taxId);
    if (hierarchyResponse.statusCode !== 200) {
      throw hierarchyResponse;
    }
    var topLevelEvents = JSON.parse(hierarchyResponse.getBody());
    topLevelEvents.forEach(function(tle) {
      function parseEvent(event, taxon, pathFromRoot) {
        [r,speciesCode,id] = event.stId.split('-');
        if(!taxonLUT.hasOwnProperty(speciesCode)) {
          console.error(`speciesCode ${speciesCode} not in taxonLUT`);
          taxonLUT[speciesCode] = taxon;
        }
        else if (taxon !== taxonLUT[speciesCode]) {
          console.error(`ensembl-reactome taxon mismatch resolved for ${speciesCode} ${taxonLUT[speciesCode]}-${taxon}`);
          taxon = taxonLUT[speciesCode];
        }
        if (!docs.hasOwnProperty(id)) {
          docs[id] = {
            _id: +id,
            name: event.name,
            type: event.type
          };
        }
        var ancestorField = 'ancestors_' + taxon;
        var lineageField = 'lineage_' + taxon;
        pathFromRoot.push(+id);
        if (! docs[id].hasOwnProperty(lineageField)) {
          docs[id][lineageField] = [];
        }
        docs[id][lineageField].push(_.clone(pathFromRoot));
        docs[id][ancestorField] = _.uniq(_.flatten(docs[id][lineageField]));
        if (event.children) {
          event.children.forEach(function(child) {
            parseEvent(child, taxon, _.clone(pathFromRoot));
          });
        }
      }
      parseEvent(tle,+s.taxId,[]);
    });
  });
}
// create an ancestors field for each doc that is the union of all the species specific fields
_.forEach(docs, function(doc, id) {
  var ancestors = _.reduce(doc, function(result, value, key) {
    if (key[0] === 'a') {
      value.forEach(function(v) {
        result[v] =1;
      })
    }
    return result;
  },{});
  doc.ancestors = Object.keys(ancestors).map(function(id){return +id});
});

// insert docs to mongo
collections.pathways.mongoCollection().then(function(pathwaysCollection) {
  pathwaysCollection.remove({},function(err) {
    if (err) {
      throw err;
    }
    pathwaysCollection.insertMany(Object.values(docs),function(err, res) {
      if (err) {
        throw err;
      }
      console.error(`inserted ${res.insertedCount} events to pathways collection`);
      collections.closeMongoDatabase();
    });
  });
});
// get the plant reactome gene xrefs from the geneProductMappingFile
var genes = {};
readline.createInterface({
  input: fs.createReadStream(geneProductMappingFile),
  terminal: false
})
.on('line', function(line) {
  var fields = line.split("\t");
  /*
0  plant reactome gene product id
1  pathway
2  species
3  gene id
  */
  genes[fields[3]] = {
    xrefs: [
      {
        db: 'notGramene_Plant_Reactome',
        ids: [fields[0]]
      }
    ],
    annotations: {
      pathways: {
        ancestors: [],
        entries: []
      }
    }
  };
})
.on('close', function() {
  console.error('loaded geneProductMappings');
  // add ancestors to genes based on the hierarchy and the genesToReactionsFile
  readline.createInterface({
    input: require('fs').createReadStream(genesToReactionsFile),
    terminal: false
  })
  .on('line', function(line) {
    var fields = line.split("\t");
    /*
      fields are
  0  gene id
  1  reaction stable id
  2  pr link
  3  reaction name
  4  evidence code (always IEA?)
  5  species name
    */
    [r,speciesCode,id] = fields[1].split('-');
    if (docs.hasOwnProperty(id)) {
      if (!genes.hasOwnProperty(fields[0])) {
        genes[fields[0]] = {
          annotations: {
            pathways: {
              ancestors: [],
              entries: []
            }
          }
        };
      }
      var reactionAncestors = docs[id]['ancestors_' + taxonLUT[speciesCode]];
      if (!!genes[fields[0]].annotations.pathways.ancestors) {
        reactionAncestors = _.uniq(_.concat(genes[fields[0]].annotations.pathways.ancestors, reactionAncestors));
      }
      // remove id from the reactionAncestors and put it in entries
      _.pull(reactionAncestors,+id);
      genes[fields[0]].annotations.pathways.ancestors = reactionAncestors;
      genes[fields[0]].annotations.pathways.entries.push({
        id: fields[1],
        link: fields[2],
        name: fields[3]
      });
    }
  })
  .on('close', function() {
    console.error('loaded genesToReactions');
    console.log(JSON.stringify(genes,null,'  '));
  });
});

//
// Object.values(docs).forEach(function(doc) {
//   console.log(JSON.stringify(doc));
// });

<|endoftext|>