<commit_before>module.exports = {

//---------------------------------------------------------------------
// Action Name
//
// This is the name of the action displayed in the editor.
//---------------------------------------------------------------------

name: "Edit channel",

//---------------------------------------------------------------------
// Action Section
//
// This is the section the action will fall into.
//---------------------------------------------------------------------

section: "Channel Control",

//---------------------------------------------------------------------
// Action Subtitle
//
// This function generates the subtitle displayed next to the name.
//---------------------------------------------------------------------

subtitle: function(data) {
	const names = ['Same Channel', 'Mentioned Channel', 'Default Channel', 'Temp Variable', 'Server Variable', 'Global Variable'];
	const index = parseInt(data.storage);
	return index < 3 ? `${names[index]}` : `${names[index]} - ${data.varName}`;
},

//---------------------------------------------------------------------
// Action Fields
//
// These are the fields for the action. These fields are customized
// by creating elements with corresponding IDs in the HTML. These
// are also the names of the fields stored in the action's JSON data.
//---------------------------------------------------------------------

fields: ["storage", "varName", "toChange", "newState"],

//---------------------------------------------------------------------
// Command HTML
//
// This function returns a string containing the HTML used for
// editting actions.
//
// The "isEvent" parameter will be true if this action is being used
// for an event. Due to their nature, events lack certain information,
// so edit the HTML to reflect this.
//
// The "data" parameter stores constants for select elements to use.
// Each is an array: index 0 for commands, index 1 for events.
// The names are: sendTargets, members, roles, channels,
//                messages, servers, variables
//---------------------------------------------------------------------

html: function(isEvent, data) {
	return `

			Mod Info:

			Created by Lasse!

		Source Channel:

		<select id="storage" class="round" onchange="glob.channelChange(this, 'varNameContainer')">
			${data.channels[isEvent ? 1 : 0]}
		</select>

		Variable Name:

		<input id="varName" class="round" type="text" list="variableList">

		Change:

		<select id="toChange" class="round">
			<option value="name">Name</option>
			<option value="topic">Topic</option>
    	<option value="position">Position</option>
    	<option value="bitrate">Bitrate</option>
    	<option value="userLimit">User Limit</option>
		</select>

		Change to:

		<input id="newState" class="round" type="text">

`
},

//---------------------------------------------------------------------
// Action Editor Init Code
//
// When the HTML is first applied to the action editor, this code
// is also run. This helps add modifications or setup reactionary
// functions for the DOM elements.
//---------------------------------------------------------------------

init: function() {
	const {glob, document} = this;

	glob.channelChange(document.getElementById('storage'), 'varNameContainer');
},

//---------------------------------------------------------------------
// Action Bot Function
//
// This is the function for the action within the Bot's Action class.
// Keep in mind event calls won't have access to the "msg" parameter,
// so be sure to provide checks for variable existance.
//---------------------------------------------------------------------

action: function(cache) {
	const data = cache.actions[cache.index];
	const storage = parseInt(data.storage);
	const varName = this.evalMessage(data.VarName, cache);
	const channel = this.getChannel(storage, varName, cache);
	const toChange = parseInt(data.toChange);
	const newState = parseInt(data.newState);
	const reason = parseInt(data.reason);
	//channel.edit({topic: this.evalMessage(data.newState)});
	//this.callNextAction(cache);
	if(data.toChange === "topic") {
		channel.edit({topic: this.evalMessage(data.newState)});
	}
	if(data.toChange === "name") {
		channel.edit({name: this.evalMessage(data.newState)});
	}
	if(data.toChange === "position") {
		channel.edit({position: this.evalMessage(data.newState)});
	}
	if(data.toChange === "bitrate") {
		channel.edit({bitrate: this.evalMessage(data.newState)});
	}
	if(data.toChange === "userLimit") {
		channel.edit({userLimit: this.evalMessage(data.newState)});
	}
	this.callNextAction(cache);
},

//---------------------------------------------------------------------
// Action Bot Mod
//
// Upon initialization of the bot, this code is run. Using the bot's
// DBM namespace, one can add/modify existing functions if necessary.
// In order to reduce conflictions between mods, be sure to alias
// functions you wish to overwrite.
//---------------------------------------------------------------------

mod: function(DBM) {
}

}; // End of module
<commit_msg>Fixed Edit Channel's `TypeError: Cannot read property 'temp' of undefined` error when inserting dbm variables<commit_after>module.exports = {

//---------------------------------------------------------------------
// Action Name
//
// This is the name of the action displayed in the editor.
//---------------------------------------------------------------------

name: "Edit channel",

//---------------------------------------------------------------------
// Action Section
//
// This is the section the action will fall into.
//---------------------------------------------------------------------

section: "Channel Control",

//---------------------------------------------------------------------
// Action Subtitle
//
// This function generates the subtitle displayed next to the name.
//---------------------------------------------------------------------

subtitle: function(data) {
	const names = ['Same Channel', 'Mentioned Channel', 'Default Channel', 'Temp Variable', 'Server Variable', 'Global Variable'];
	const index = parseInt(data.storage);
	return index < 3 ? `${names[index]}` : `${names[index]} - ${data.varName}`;
},

//---------------------------------------------------------------------
// Action Fields
//
// These are the fields for the action. These fields are customized
// by creating elements with corresponding IDs in the HTML. These
// are also the names of the fields stored in the action's JSON data.
//---------------------------------------------------------------------

fields: ["storage", "varName", "toChange", "newState"],

//---------------------------------------------------------------------
// Command HTML
//
// This function returns a string containing the HTML used for
// editting actions.
//
// The "isEvent" parameter will be true if this action is being used
// for an event. Due to their nature, events lack certain information,
// so edit the HTML to reflect this.
//
// The "data" parameter stores constants for select elements to use.
// Each is an array: index 0 for commands, index 1 for events.
// The names are: sendTargets, members, roles, channels,
//                messages, servers, variables
//---------------------------------------------------------------------

html: function(isEvent, data) {
	return `

			Mod Info:

			Created by Lasse!

		Source Channel:

		<select id="storage" class="round" onchange="glob.channelChange(this, 'varNameContainer')">
			${data.channels[isEvent ? 1 : 0]}
		</select>

		Variable Name:

		<input id="varName" class="round" type="text" list="variableList">

		Change:

		<select id="toChange" class="round">
			<option value="name">Name</option>
			<option value="topic">Topic</option>
    	<option value="position">Position</option>
    	<option value="bitrate">Bitrate</option>
    	<option value="userLimit">User Limit</option>
		</select>

		Change to:

		<input id="newState" class="round" type="text">

`
},

//---------------------------------------------------------------------
// Action Editor Init Code
//
// When the HTML is first applied to the action editor, this code
// is also run. This helps add modifications or setup reactionary
// functions for the DOM elements.
//---------------------------------------------------------------------

init: function() {
	const {glob, document} = this;

	glob.channelChange(document.getElementById('storage'), 'varNameContainer');
},

//---------------------------------------------------------------------
// Action Bot Function
//
// This is the function for the action within the Bot's Action class.
// Keep in mind event calls won't have access to the "msg" parameter,
// so be sure to provide checks for variable existance.
//---------------------------------------------------------------------

action: function(cache) {
	const data = cache.actions[cache.index];
	const storage = parseInt(data.storage);
	const varName = this.evalMessage(data.VarName, cache);
	const channel = this.getChannel(storage, varName, cache);
	const toChange = parseInt(data.toChange);
	const newState = parseInt(data.newState);
	const reason = parseInt(data.reason);
	//channel.edit({topic: this.evalMessage(data.newState)});
	//this.callNextAction(cache);
	if(data.toChange === "topic") {
		channel.edit({topic: this.evalMessage(data.newState, cache)});
	}
	if(data.toChange === "name") {
		channel.edit({name: this.evalMessage(data.newState, cache)});
	}
	if(data.toChange === "position") {
		channel.edit({position: this.evalMessage(data.newState, cache)});
	}
	if(data.toChange === "bitrate") {
		channel.edit({bitrate: this.evalMessage(data.newState, cache)});
	}
	if(data.toChange === "userLimit") {
		channel.edit({userLimit: this.evalMessage(data.newState, cache)});
	}
	this.callNextAction(cache);
},

//---------------------------------------------------------------------
// Action Bot Mod
//
// Upon initialization of the bot, this code is run. Using the bot's
// DBM namespace, one can add/modify existing functions if necessary.
// In order to reduce conflictions between mods, be sure to alias
// functions you wish to overwrite.
//---------------------------------------------------------------------

mod: function(DBM) {
}

}; // End of module
<|endoftext|>


<commit_before>/*
highlight.js v1.0.0
Available via the MIT or new BSD license.
see: http://github.com/jianghai/highlight for details
*/

var Highlight;

(function() {

    /**
     * Pass an html element which you want to highlight.
     * Example:
     *     var el = document.getElementById('myCode');
     *     new Highlight(el);
     */
    Highlight = function(el) {
        this.el = el;
        this.source = el.textContent;
        this.lang = el.getAttribute('lang') || 'js';

        // '\s' contains '\n', so just use ' '
        this.source = this.source.replace(/ /g, '\u00a0');

        // remove start and end '\n'
        this.source = this.source.replace(/^\s+|\s+$/g, '');

        this.render();
    };

    /**
     * Language syntax highlight rules.
     * Just wrap the matched or the return of callback with span element, the span
     * element has a className which is value of key name for custom your css style.
     * You can add or edit by yourself.
     */
    // html
    Highlight.html = [{
        name: 'tag', // markup tag
        rule: '(<\\/?[\\w\\d]+|>)',
        callback: function(str) {
            return str.replace('<', '<');
        }
    }, {
        name: 'str', // attribute value
        rule: '(\"[\\s\\S]*?\")'
    }];

    // javascript
    Highlight.js = [{
        name: 'com', // comment
        rule: '(\\/\\/.*|\\/\\*[\\s\\S]*?\\*\\/)'
    }, {
        name: 'str', // string
        rule: '(\'[\\s\\S]*?\'|\"[\\s\\S]*?\")',
        callback: function(str) {
            // Some js string has html tags
            return str.replace('<', '<');
        }
    }, {
        name: 'kwd', // keyword
        rule: '\\b(break|case|catch|continue|debugger|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|this|throw|try|typeof|var|void|while|with)\\b'
    }, {
        name: 'opt', // operator
        rule: '(\\+|-|\\*|\\/|%|<|>|=|==|===|!=|!==|!|&&|\\|\\||&|\\|)'
    }];

    // Another language

    // Get all regexp rules of this lang.
    var getReg = function(lang, rules) {
        if (getReg[lang]) return getReg[lang];
        var reg = [];
        for (var i = 0; i < rules.length; i++) {
            reg.push(rules[i].rule);
        }
        reg = reg.join('|');

        getReg[lang] = reg;

        return reg;
    };

    /**
     * This is the key action that convert normal code string with all kinds of
     * syntax rules.
     */
    Highlight.prototype.convert = function() {
        var lang = this.lang;
        var rules = Highlight[lang];
        var reg = new RegExp(getReg(lang, rules), 'g');
        this.source = this.source.replace(reg, function() {
            var args = arguments;
            var len = args.length - 1;
            var i = 1;
            for (; i < len; i++) {
                if (args[i] && rules[i - 1]) {
                    if (rules[i - 1].callback) {
                        args[i] = rules[i - 1].callback.call(null, args[i])
                    }
                    return '' + args[i] + '';
                }
            }
        });
        return this.source.replace(/\n/g, '
');
    };

    /**
     * Here is the last step, show it in the page.
     */
    Highlight.prototype.render = function() {
        this.el.innerHTML = this.convert();
    };

})();<commit_msg>escape all html tags in js string<commit_after>/*
highlight.js v1.0.0
Available via the MIT or new BSD license.
see: http://github.com/jianghai/highlight for details
*/

var Highlight;

(function() {

    /**
     * Pass an html element which you want to highlight.
     * Example:
     *     var el = document.getElementById('myCode');
     *     new Highlight(el);
     */
    Highlight = function(el) {
        this.el = el;
        this.source = el.textContent;
        this.lang = el.getAttribute('lang') || 'js';

        // '\s' contains '\n', so just use ' '
        this.source = this.source.replace(/ /g, '\u00a0');

        // remove start and end '\n'
        this.source = this.source.replace(/^\s+|\s+$/g, '');

        this.render();
    };

    /**
     * Language syntax highlight rules.
     * Just wrap the matched or the return of callback with span element, the span
     * element has a className which is value of key name for custom your css style.
     * You can add or edit by yourself.
     */
    // html
    Highlight.html = [{
        name: 'tag', // markup tag
        rule: '(<\\/?[\\w\\d]+|>)',
        callback: function(str) {
            return str.replace('<', '<');
        }
    }, {
        name: 'str', // attribute value
        rule: '(\"[\\s\\S]*?\")'
    }];

    // javascript
    Highlight.js = [{
        name: 'com', // comment
        rule: '(\\/\\/.*|\\/\\*[\\s\\S]*?\\*\\/)'
    }, {
        name: 'str', // string
        rule: '(\'[\\s\\S]*?\'|\"[\\s\\S]*?\")',
        callback: function(str) {
            // Some js string has html tags
            return str.replace(/</g, '<');
        }
    }, {
        name: 'kwd', // keyword
        rule: '\\b(break|case|catch|continue|debugger|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|this|throw|try|typeof|var|void|while|with)\\b'
    }, {
        name: 'opt', // operator
        rule: '(\\+|-|\\*|\\/|%|<|>|=|==|===|!=|!==|!|&&|\\|\\||&|\\|)'
    }];

    // Another language

    // Get all regexp rules of this lang.
    var getReg = function(lang, rules) {
        if (getReg[lang]) return getReg[lang];
        var reg = [];
        for (var i = 0; i < rules.length; i++) {
            reg.push(rules[i].rule);
        }
        reg = reg.join('|');

        getReg[lang] = reg;

        return reg;
    };

    /**
     * This is the key action that convert normal code string with all kinds of
     * syntax rules.
     */
    Highlight.prototype.convert = function() {
        var lang = this.lang;
        var rules = Highlight[lang];
        var reg = new RegExp(getReg(lang, rules), 'g');
        this.source = this.source.replace(reg, function() {
            var args = arguments;
            var len = args.length - 1;
            var i = 1;
            for (; i < len; i++) {
                if (args[i] && rules[i - 1]) {
                    if (rules[i - 1].callback) {
                        args[i] = rules[i - 1].callback.call(null, args[i])
                    }
                    return '' + args[i] + '';
                }
            }
        });
        return this.source.replace(/\n/g, '
');
    };

    /**
     * Here is the last step, show it in the page.
     */
    Highlight.prototype.render = function() {
        this.el.innerHTML = this.convert();
    };

})();<|endoftext|>


<commit_before>var Buffer = require('buffer').Buffer;
var fs = require('fs');
var path = require('path');
var Q = require('q');
// TODO(davidben): This library is ridiculous. If you create a
// temporary file per-request you slowly grow your memory usage over
// the lifetime of your program and never actually delete your
// temporaries anyway.
var temp = require('temp');
var zephyr = require('zephyr');

var krb_proto = require('../lib/krb_proto.js');
var message = require('../lib/message.js');

var principal = process.argv[2];
var directory = temp.mkdirSync(
  'inner-demon-' + principal.replace(/[^a-zA-Z0-9]/g, '_'));
var ccachePath = path.join(directory, 'ccache');
process.env['KRB5CCNAME'] = 'FILE:' + ccachePath;

zephyr.openPort();

var commands = {};

function updateCredentialCacheSync(cred) {
  // Write the credential to the ccache. We do this synchronously to avoid
  // dealing having to deal with synchronization here. This should be
  // on a tmpfs, and everything here is for a single user anyway.
  //
  // This is taken from ssh-krb-wrapper in the shell-in-a-box hack in
  // Webathena.
  //
  // TODO(davidben): We could probably also do this with the Kerberos
  // API. Maybe even GSSAPI credential delegation? An awful lot of
  // machinery though.
  //
  // TODO(davidben): do a temporary+rename thing.

  try {
    fs.unlinkSync(ccachePath);
  } catch (e) {
  }
  var fd = fs.openSync(ccachePath, 'wx+', 0600);
  try {
    // Write the header.
    var header = new Buffer(2 + 2 + 2 + 2 + 4 + 4);
    header.writeUInt16BE(0x0504, 0);  // file_format_version
    header.writeUInt16BE(12, 2);  // headerlen
    header.writeUInt16BE(1, 4);  // tag (DeltaTime)
    header.writeUInt16BE(8, 6);  // taglen (two uint32_ts)
    header.writeUInt32BE(0, 8);  // time_offset
    header.writeUInt32BE(0, 12);  // uset_offset
    fs.writeSync(fd, header, 0, header.length);

    writePrincipalSync(fd, cred.cname, cred.crealm);
    writeCredentialSync(fd, cred);
  } catch(e) {
    fs.unlinkSync(ccachePath);
    throw e;
  } finally {
    fs.closeSync(fd);
  }
}

commands.subscribeTo = function(subs, cred) {
  updateCredentialCacheSync(cred);
  return Q.nfcall(zephyr.subscribeTo, subs);
};

commands.expel = function() {
  console.log('Inner demon exiting');
  // Attempt to cancel subs if we can from our tickets, just so I
  // don't leave all these things open in development.
  //
  // TODO(davidben): Session resumption and everything.
  return Q.nfcall(zephyr.cancelSubscriptions).then(
    function() {
      // node-temp is messed up and can't delete temporary
      // directories. Blow away our ccache first.
      //
      // TODO(davidben): Just write your own thing. Really.
      try {
        fs.unlinkSync(ccachePath);
      } catch (e) {
      }
    },
    function(err) {
      console.error("Could not cancel subs", principal, err);
    });
};

process.on('message', function(m) {
  console.dir(m);
  var id = m.id;
  if (commands[m.cmd]) {
    Q.fapply(commands[m.cmd], m.args).then(function(ret) {
      process.send({
        id: id,
        cmd: 'response',
        value: ret
      });
    }, function(err) {
      console.error(err);
      process.send({
        id: id,
        cmd: 'error',
        error: err
      });
    }).finally(function() {
      if (m.cmd === 'expel')
        process.exit();
    }).done();
  } else {
    process.send({
      id: id,
      cmd: 'error',
      error: 'Unknown command'
    });
    console.error('Unknown command', m);
  }
});

zephyr.on('notice', function(notice) {
  var msg = message.noticeToMessage(notice);
  if (msg) {
    process.send({
      cmd: 'message',
      message: msg
    });
  }
});

function writeUInt8Sync(fd, value) {
  var buf = new Buffer(1);
  buf.writeUInt8(value, 0);
  fs.writeSync(fd, buf, 0, buf.length);
}

function writeUInt16BESync(fd, value) {
  var buf = new Buffer(2);
  buf.writeUInt16BE(value, 0);
  fs.writeSync(fd, buf, 0, buf.length);
}

function writeUInt32BESync(fd, value) {
  var buf = new Buffer(4);
  buf.writeUInt32BE(value, 0);
  fs.writeSync(fd, buf, 0, buf.length);
}

function writeCountedOctetStringSync(fd, buf) {
  writeUInt32BESync(fd, buf.length);
  fs.writeSync(fd, buf, 0, buf.length);
}

function writePrincipalSync(fd, name, realm) {
  writeUInt32BESync(fd, Number(name.nameType));
  writeUInt32BESync(fd, Number(name.nameString.length));
  writeCountedOctetStringSync(fd, new Buffer(String(realm), "utf8"));
  name.nameString.forEach(function(component) {
    writeCountedOctetStringSync(fd, new Buffer(String(component), "utf8"));
  });
}

function writeCredentialSync(fd, cred) {
  writePrincipalSync(fd, cred.cname, cred.crealm);
  writePrincipalSync(fd, cred.sname, cred.srealm);
  writeUInt16BESync(fd, Number(cred.key.keytype));
  writeCountedOctetStringSync(fd, new Buffer(cred.key.keyvalue, "base64"));
  writeUInt32BESync(fd, (cred.authtime / 1000)|0);
  writeUInt32BESync(fd, ((cred.authtime || cred.starttime) / 1000)|0);
  writeUInt32BESync(fd, (cred.endtime / 1000)|0);
  writeUInt32BESync(fd, ((cred.renewTill || 0) / 1000)|0);
  writeUInt8Sync(fd, 0);
  var flags = 0;
  for (var i = 0; i < cred.flags.length; i++) {
    if (cred.flags[i])
      flags |= 1 << (31 - i);
  }
  writeUInt32BESync(fd, flags >>> 0);
  writeUInt32BESync(fd, 0);
  writeUInt32BESync(fd, 0);

  // Convert base64-encoded cipher to use ArrayBuffers.
  cred.ticket.encPart.cipher = new Uint8Array(
    new Buffer(cred.ticket.encPart.cipher, "base64"));
  var ticketDER = krb_proto.Ticket.encodeDER(cred.ticket);
  // And convert the output back to a node buffer.
  ticketDER = new Buffer(new Uint8Array(
    ticketDER.buffer, ticketDER.byteOffset, ticketDER.byteLength));
  writeCountedOctetStringSync(fd, ticketDER);

  writeCountedOctetStringSync(fd, new Buffer(0));
}

// Bahh... I want to ^C the outer guy and have it kill the inner guys.
process.on('SIGINT', function() {
  console.log('Inner demon ignoring SIGINT');
});
<commit_msg>Still clean up if cancel subs fails<commit_after>var Buffer = require('buffer').Buffer;
var fs = require('fs');
var path = require('path');
var Q = require('q');
// TODO(davidben): This library is ridiculous. If you create a
// temporary file per-request you slowly grow your memory usage over
// the lifetime of your program and never actually delete your
// temporaries anyway.
var temp = require('temp');
var zephyr = require('zephyr');

var krb_proto = require('../lib/krb_proto.js');
var message = require('../lib/message.js');

var principal = process.argv[2];
var directory = temp.mkdirSync(
  'inner-demon-' + principal.replace(/[^a-zA-Z0-9]/g, '_'));
var ccachePath = path.join(directory, 'ccache');
process.env['KRB5CCNAME'] = 'FILE:' + ccachePath;

zephyr.openPort();

var commands = {};

function updateCredentialCacheSync(cred) {
  // Write the credential to the ccache. We do this synchronously to avoid
  // dealing having to deal with synchronization here. This should be
  // on a tmpfs, and everything here is for a single user anyway.
  //
  // This is taken from ssh-krb-wrapper in the shell-in-a-box hack in
  // Webathena.
  //
  // TODO(davidben): We could probably also do this with the Kerberos
  // API. Maybe even GSSAPI credential delegation? An awful lot of
  // machinery though.
  //
  // TODO(davidben): do a temporary+rename thing.

  try {
    fs.unlinkSync(ccachePath);
  } catch (e) {
  }
  var fd = fs.openSync(ccachePath, 'wx+', 0600);
  try {
    // Write the header.
    var header = new Buffer(2 + 2 + 2 + 2 + 4 + 4);
    header.writeUInt16BE(0x0504, 0);  // file_format_version
    header.writeUInt16BE(12, 2);  // headerlen
    header.writeUInt16BE(1, 4);  // tag (DeltaTime)
    header.writeUInt16BE(8, 6);  // taglen (two uint32_ts)
    header.writeUInt32BE(0, 8);  // time_offset
    header.writeUInt32BE(0, 12);  // uset_offset
    fs.writeSync(fd, header, 0, header.length);

    writePrincipalSync(fd, cred.cname, cred.crealm);
    writeCredentialSync(fd, cred);
  } catch(e) {
    fs.unlinkSync(ccachePath);
    throw e;
  } finally {
    fs.closeSync(fd);
  }
}

commands.subscribeTo = function(subs, cred) {
  updateCredentialCacheSync(cred);
  return Q.nfcall(zephyr.subscribeTo, subs);
};

commands.expel = function() {
  console.log('Inner demon exiting');
  // Attempt to cancel subs if we can from our tickets, just so I
  // don't leave all these things open in development.
  //
  // TODO(davidben): Session resumption and everything.
  return Q.nfcall(zephyr.cancelSubscriptions).then(function() {
  }, function(err) {
    console.error("Could not cancel subs", principal, err);
  }).finally(function() {
    // node-temp is messed up and can't delete temporary
    // directories. Blow away our ccache first.
    //
    // TODO(davidben): Just write your own thing. Really.
    try {
      fs.unlinkSync(ccachePath);
    } catch (e) {
    }
  });
};

process.on('message', function(m) {
  console.dir(m);
  var id = m.id;
  if (commands[m.cmd]) {
    Q.fapply(commands[m.cmd], m.args).then(function(ret) {
      process.send({
        id: id,
        cmd: 'response',
        value: ret
      });
    }, function(err) {
      console.error(err);
      process.send({
        id: id,
        cmd: 'error',
        error: err
      });
    }).finally(function() {
      if (m.cmd === 'expel')
        process.exit();
    }).done();
  } else {
    process.send({
      id: id,
      cmd: 'error',
      error: 'Unknown command'
    });
    console.error('Unknown command', m);
  }
});

zephyr.on('notice', function(notice) {
  var msg = message.noticeToMessage(notice);
  if (msg) {
    process.send({
      cmd: 'message',
      message: msg
    });
  }
});

function writeUInt8Sync(fd, value) {
  var buf = new Buffer(1);
  buf.writeUInt8(value, 0);
  fs.writeSync(fd, buf, 0, buf.length);
}

function writeUInt16BESync(fd, value) {
  var buf = new Buffer(2);
  buf.writeUInt16BE(value, 0);
  fs.writeSync(fd, buf, 0, buf.length);
}

function writeUInt32BESync(fd, value) {
  var buf = new Buffer(4);
  buf.writeUInt32BE(value, 0);
  fs.writeSync(fd, buf, 0, buf.length);
}

function writeCountedOctetStringSync(fd, buf) {
  writeUInt32BESync(fd, buf.length);
  fs.writeSync(fd, buf, 0, buf.length);
}

function writePrincipalSync(fd, name, realm) {
  writeUInt32BESync(fd, Number(name.nameType));
  writeUInt32BESync(fd, Number(name.nameString.length));
  writeCountedOctetStringSync(fd, new Buffer(String(realm), "utf8"));
  name.nameString.forEach(function(component) {
    writeCountedOctetStringSync(fd, new Buffer(String(component), "utf8"));
  });
}

function writeCredentialSync(fd, cred) {
  writePrincipalSync(fd, cred.cname, cred.crealm);
  writePrincipalSync(fd, cred.sname, cred.srealm);
  writeUInt16BESync(fd, Number(cred.key.keytype));
  writeCountedOctetStringSync(fd, new Buffer(cred.key.keyvalue, "base64"));
  writeUInt32BESync(fd, (cred.authtime / 1000)|0);
  writeUInt32BESync(fd, ((cred.authtime || cred.starttime) / 1000)|0);
  writeUInt32BESync(fd, (cred.endtime / 1000)|0);
  writeUInt32BESync(fd, ((cred.renewTill || 0) / 1000)|0);
  writeUInt8Sync(fd, 0);
  var flags = 0;
  for (var i = 0; i < cred.flags.length; i++) {
    if (cred.flags[i])
      flags |= 1 << (31 - i);
  }
  writeUInt32BESync(fd, flags >>> 0);
  writeUInt32BESync(fd, 0);
  writeUInt32BESync(fd, 0);

  // Convert base64-encoded cipher to use ArrayBuffers.
  cred.ticket.encPart.cipher = new Uint8Array(
    new Buffer(cred.ticket.encPart.cipher, "base64"));
  var ticketDER = krb_proto.Ticket.encodeDER(cred.ticket);
  // And convert the output back to a node buffer.
  ticketDER = new Buffer(new Uint8Array(
    ticketDER.buffer, ticketDER.byteOffset, ticketDER.byteLength));
  writeCountedOctetStringSync(fd, ticketDER);

  writeCountedOctetStringSync(fd, new Buffer(0));
}

// Bahh... I want to ^C the outer guy and have it kill the inner guys.
process.on('SIGINT', function() {
  console.log('Inner demon ignoring SIGINT');
});
<|endoftext|>


<commit_before>"use strict";

var fs   = require("fs"),
    path = require("path"),

    Graph   = require("dependency-graph").DepGraph,
    postcss = require("postcss"),
    slug    = require("unique-slug"),
    series  = require("p-each-series"),
    unique  = require("lodash.uniq"),

    output   = require("./lib/output.js"),
    message  = require("./lib/message.js"),
    relative = require("./lib/relative.js"),
    tiered   = require("./lib/graph-tiers.js"),
    resolve  = require("./lib/resolve.js");

function params(processor, args) {
    return Object.assign(
        Object.create(null),
        processor._options,
        {
            files   : processor._files,
            graph   : processor._graph,
            resolve : processor._resolve
        },
        args || Object.create(null)
    );
}

function Processor(opts) {
    /* eslint consistent-return: off, max-statements: off */
    if(!(this instanceof Processor)) {
        return new Processor(opts);
    }

    this._options = Object.assign(
        Object.create(null),
        {
            cwd : process.cwd(),
            map : false
        },
        opts || Object.create(null)
    );

    if(!path.isAbsolute(this._options.cwd)) {
        this._options.cwd = path.resolve(this._options.cwd);
    }

    if(typeof this._options.namer === "string") {
        this._options.namer = require(this._options.namer)();
    }

    if(typeof this._options.namer !== "function") {
        this._options.namer = (file, selector) =>
            `mc${slug(relative(this._options.cwd, file))}_${selector}`;
    }

    if(!Array.isArray(this._options.resolvers)) {
        this._options.resolvers = [];
    }

    this._resolve = resolve.resolvers(this._options.resolvers);

    this._absolute = (file) => (path.isAbsolute(file) ? file : path.join(this._options.cwd, file));

    this._files = Object.create(null);
    this._graph = new Graph();

    this._before = postcss((this._options.before || []).concat(
        require("./plugins/values-local.js"),
        require("./plugins/values-export.js"),
        require("./plugins/values-replace.js"),
        require("./plugins/graph-nodes.js")
    ));

    this._process = postcss([
        require("./plugins/values-composed.js"),
        require("./plugins/values-export.js"),
        require("./plugins/values-namespaced.js"),
        require("./plugins/values-replace.js"),
        require("./plugins/scoping.js"),
        require("./plugins/externals.js"),
        require("./plugins/composition.js"),
        require("./plugins/keyframes.js")
    ]);

    this._after = postcss(this._options.after || [
        require("postcss-url")
    ]);

    this._done = postcss(this._options.done || []);
}

Processor.prototype = {
    // Add a file on disk to the dependency graph
    file : function(file) {
        if(!path.isAbsolute(file)) {
            file = path.join(this._options.cwd, file);
        }

        return this.string(path.normalize(file), fs.readFileSync(file, "utf8"));
    },

    // Add a file by name + contents to the dependency graph
    string : function(start, text) {
        if(!path.isAbsolute(start)) {
            start = path.join(this._options.cwd, start);
        }

        return this._walk(start, text).then(() => {
            var deps = this._graph.dependenciesOf(start).concat(start);

            return series(deps, (dep) => {
                var file = this._files[dep];

                if(!file.processed) {
                    file.processed = this._process.process(
                        file.result,
                        params(this, {
                            from  : dep,
                            namer : this._options.namer
                        })
                    );
                }

                return file.processed.then((result) => {
                    file.exports = message(result, "classes");
                    file.result  = result;
                });
            });
        })
        .then(() => ({
            id      : start,
            file    : start,
            files   : this._files,
            details : this._files[start],
            exports : this._files[start].exports
        }));
    },

    // Remove a file from the dependency graph
    remove : function(input) {
        var files = input;

        if(!Array.isArray(files)) {
            files = [ files ];
        }

        files = files
            .map(this._absolute)
            .filter((file) => this._graph.hasNode(file))
            // Remove everything that depends on files to be removed as well
            // since it will also have to be recalculated
            .reduce(
                (prev, curr) =>
                    prev.concat(
                        this._graph.dependantsOf(curr)
                            .concat(curr)
                    )
                ,
                files
            );

        unique(files).forEach((file) => {
            delete this._files[file];

            this._graph.removeNode(file);
        });
    },

    // Get the dependency order for a file or the entire tree
    dependencies : function(file) {
        if(file) {
            return this._graph.dependenciesOf(
                file
            );
        }

        return this._graph.overallOrder();
    },

    // Get the ultimate output for specific files or the entire tree
    output : function(args) {
        var opts  = args || false,
            files = opts.files;

        if(!Array.isArray(files)) {
            files = tiered(this._graph);
        }

        // Rewrite relative URLs before adding
        // Have to do this every time because target file might be different!
        //
        return Promise.all(
            files
            .map(this._absolute)
            // Protect from any files that errored out (#248)
            .filter((dep) => dep in this._files && this._files[dep].result)
            .map((dep) => this._after.process(
                // NOTE: the call to .clone() is really important here, otherwise this call
                // modifies the .result root itself and you process URLs multiple times
                // See https://github.com/tivac/modular-css/issues/35
                //
                this._files[dep].result.root.clone(),

                params(this, {
                    from : dep,
                    to   : opts.to
                })
            ))
        )
        .then((results) => {
            var root = postcss.root();

            results.forEach((result) => {
                // Add file path comment
                root.append(postcss.comment({
                    text : relative(this._options.cwd, result.opts.from),

                    // Add a bogus-ish source property so postcss won't make weird-looking
                    // source-maps that break the visualizer
                    //
                    // https://github.com/postcss/postcss/releases/tag/5.1.0
                    // https://github.com/postcss/postcss/pull/761
                    // https://github.com/tivac/modular-css/pull/157
                    //
                    source : Object.assign(
                        {},
                        result.root.source,
                        {
                            end : result.root.source.start
                        }
                    )
                }));

                root.append(result.root);
            });

            return this._done.process(
                root,
                params(this, args)
            );
        })
        .then((result) => {
            result.compositions = output.compositions(this._options.cwd, this);

            return result;
        });
    },

    // Expose files
    get files() {
        return this._files;
    },

    // Expose combined options object
    get options() {
        return this._options;
    },

    // Process files and walk their composition/value dependency tree to find
    // new files we need to process
    _walk : function(name, text) {
        // No need to re-process files
        if(this._files[name]) {
            return Promise.resolve();
        }

        this._graph.addNode(name);

        this._files[name] = {
            text    : text,
            exports : false,
            values  : false
        };

        return this._before.process(
            text,
            params(this, {
                from : name,

                // Run parsers in loose mode for this first pass
                strict : false
            })
        )
        .then((result) => {
            this._files[name].result = result;

            // Walk this node's dependencies, reading new files from disk as necessary
            return Promise.all(
                this._graph.dependenciesOf(name).map((dependency) => this._walk(
                    dependency,
                    this._files[dependency] ?
                        null :
                        fs.readFileSync(dependency, "utf8")
                ))
            );
        });
    }
};

module.exports = Processor;
<commit_msg>refactor: Rework .remove(), again (#307)<commit_after>"use strict";

var fs   = require("fs"),
    path = require("path"),

    Graph   = require("dependency-graph").DepGraph,
    postcss = require("postcss"),
    slug    = require("unique-slug"),
    series  = require("p-each-series"),
    unique  = require("lodash.uniq"),

    output   = require("./lib/output.js"),
    message  = require("./lib/message.js"),
    relative = require("./lib/relative.js"),
    tiered   = require("./lib/graph-tiers.js"),
    resolve  = require("./lib/resolve.js");

function params(processor, args) {
    return Object.assign(
        Object.create(null),
        processor._options,
        {
            files   : processor._files,
            graph   : processor._graph,
            resolve : processor._resolve
        },
        args || Object.create(null)
    );
}

function Processor(opts) {
    /* eslint consistent-return: off, max-statements: off */
    if(!(this instanceof Processor)) {
        return new Processor(opts);
    }

    this._options = Object.assign(
        Object.create(null),
        {
            cwd : process.cwd(),
            map : false
        },
        opts || Object.create(null)
    );

    if(!path.isAbsolute(this._options.cwd)) {
        this._options.cwd = path.resolve(this._options.cwd);
    }

    if(typeof this._options.namer === "string") {
        this._options.namer = require(this._options.namer)();
    }

    if(typeof this._options.namer !== "function") {
        this._options.namer = (file, selector) =>
            `mc${slug(relative(this._options.cwd, file))}_${selector}`;
    }

    if(!Array.isArray(this._options.resolvers)) {
        this._options.resolvers = [];
    }

    this._resolve = resolve.resolvers(this._options.resolvers);

    this._absolute = (file) => (path.isAbsolute(file) ? file : path.join(this._options.cwd, file));

    this._files = Object.create(null);
    this._graph = new Graph();

    this._before = postcss((this._options.before || []).concat(
        require("./plugins/values-local.js"),
        require("./plugins/values-export.js"),
        require("./plugins/values-replace.js"),
        require("./plugins/graph-nodes.js")
    ));

    this._process = postcss([
        require("./plugins/values-composed.js"),
        require("./plugins/values-export.js"),
        require("./plugins/values-namespaced.js"),
        require("./plugins/values-replace.js"),
        require("./plugins/scoping.js"),
        require("./plugins/externals.js"),
        require("./plugins/composition.js"),
        require("./plugins/keyframes.js")
    ]);

    this._after = postcss(this._options.after || [
        require("postcss-url")
    ]);

    this._done = postcss(this._options.done || []);
}

Processor.prototype = {
    // Add a file on disk to the dependency graph
    file : function(file) {
        if(!path.isAbsolute(file)) {
            file = path.join(this._options.cwd, file);
        }

        return this.string(path.normalize(file), fs.readFileSync(file, "utf8"));
    },

    // Add a file by name + contents to the dependency graph
    string : function(start, text) {
        if(!path.isAbsolute(start)) {
            start = path.join(this._options.cwd, start);
        }

        return this._walk(start, text).then(() => {
            var deps = this._graph.dependenciesOf(start).concat(start);

            return series(deps, (dep) => {
                var file = this._files[dep];

                if(!file.processed) {
                    file.processed = this._process.process(
                        file.result,
                        params(this, {
                            from  : dep,
                            namer : this._options.namer
                        })
                    );
                }

                return file.processed.then((result) => {
                    file.exports = message(result, "classes");
                    file.result  = result;
                });
            });
        })
        .then(() => ({
            id      : start,
            file    : start,
            files   : this._files,
            details : this._files[start],
            exports : this._files[start].exports
        }));
    },

    // Remove a file from the dependency graph
    remove : function(input) {
        var order = this._graph.overallOrder(),
            files;

        // Only want files actually in the array
        files = (Array.isArray(input) ? input : [ input ])
            .map(this._absolute)
            .filter((file) => this._graph.hasNode(file));

        if(!files.length) {
            return;
        }

        // Remove everything that depends on files to be removed as well
        // since it will also have to be recalculated
        files = files
            .reduce(
                (prev, curr) => prev.concat(
                    this._graph.dependantsOf(curr)
                        .concat(curr)
                ),
                []
            )
            .sort((a, b) => order.indexOf(a) - order.indexOf(b));

        unique(files).forEach((file) => {
            delete this._files[file];

            this._graph.removeNode(file);
        });
    },

    // Get the dependency order for a file or the entire tree
    dependencies : function(file) {
        if(file) {
            return this._graph.dependenciesOf(
                file
            );
        }

        return this._graph.overallOrder();
    },

    // Get the ultimate output for specific files or the entire tree
    output : function(args) {
        var opts  = args || false,
            files = opts.files;

        if(!Array.isArray(files)) {
            files = tiered(this._graph);
        }

        // Rewrite relative URLs before adding
        // Have to do this every time because target file might be different!
        //
        return Promise.all(
            files
            .map(this._absolute)
            // Protect from any files that errored out (#248)
            .filter((dep) => dep in this._files && this._files[dep].result)
            .map((dep) => this._after.process(
                // NOTE: the call to .clone() is really important here, otherwise this call
                // modifies the .result root itself and you process URLs multiple times
                // See https://github.com/tivac/modular-css/issues/35
                //
                this._files[dep].result.root.clone(),

                params(this, {
                    from : dep,
                    to   : opts.to
                })
            ))
        )
        .then((results) => {
            var root = postcss.root();

            results.forEach((result) => {
                // Add file path comment
                root.append(postcss.comment({
                    text : relative(this._options.cwd, result.opts.from),

                    // Add a bogus-ish source property so postcss won't make weird-looking
                    // source-maps that break the visualizer
                    //
                    // https://github.com/postcss/postcss/releases/tag/5.1.0
                    // https://github.com/postcss/postcss/pull/761
                    // https://github.com/tivac/modular-css/pull/157
                    //
                    source : Object.assign(
                        {},
                        result.root.source,
                        {
                            end : result.root.source.start
                        }
                    )
                }));

                root.append(result.root);
            });

            return this._done.process(
                root,
                params(this, args)
            );
        })
        .then((result) => {
            result.compositions = output.compositions(this._options.cwd, this);

            return result;
        });
    },

    // Expose files
    get files() {
        return this._files;
    },

    // Expose combined options object
    get options() {
        return this._options;
    },

    // Process files and walk their composition/value dependency tree to find
    // new files we need to process
    _walk : function(name, text) {
        // No need to re-process files
        if(this._files[name]) {
            return Promise.resolve();
        }

        this._graph.addNode(name);

        this._files[name] = {
            text    : text,
            exports : false,
            values  : false
        };

        return this._before.process(
            text,
            params(this, {
                from : name,

                // Run parsers in loose mode for this first pass
                strict : false
            })
        )
        .then((result) => {
            this._files[name].result = result;

            // Walk this node's dependencies, reading new files from disk as necessary
            return Promise.all(
                this._graph.dependenciesOf(name).map((dependency) => this._walk(
                    dependency,
                    this._files[dependency] ?
                        null :
                        fs.readFileSync(dependency, "utf8")
                ))
            );
        });
    }
};

module.exports = Processor;
<|endoftext|>


<commit_before>'use strict';
module.exports = 'publish-please@3.0.3';<commit_msg>style(publish): apply prettier<commit_after>'use strict';
module.exports = 'publish-please@3.0.3';
<|endoftext|>


<commit_before>(function () {

    $(".sourceLink, button").click(function (event) {
        event.preventDefault();
        const anchorName = $(this).attr("data-target") + "Heading";
        $("html, body").animate({scrollTop: $(anchorName).offset().top});
        let currentButton = this;
        window.setTimeout(function () {
            /* I am exploiting Bootstrap's ARIA functionality for the
            purposes of this application*/
            let isOpen = $(currentButton).attr("aria-expanded") === "true";
            if (isOpen) {
                $(currentButton).removeAttr("data-toggle");
            }
        }, 200);

    });

    $(".accordionLink").click(function () {
        let currentDataTarget = "button[data-target=\'" + $(this).attr("href") + "\']";
        $(currentDataTarget).attr("data-toggle", "collapse");

        window.setTimeout(function () {
            let isOpen = $(currentDataTarget).attr("aria-expanded") === "true";
            if (isOpen) {
                $(currentDataTarget).removeAttr("data-toggle");
            }
        }, 200);
    });

    // object for gene page API calls
    const search = location.search.substring(1);
    const obj = {
        symbol: search.match(/symbol=(.*?)(?=&)/)[1],
        species: search.match(/species=(.*?)(?=&)/)[1],
        jaspar: search.match(/jaspar=(.*?)(?=&)/)[1],
        uniprot: search.match(/uniprot=(.*?)/)[1]
    };

    document.title = "GRNsight - " + obj.symbol;
    $("#gene-name").text(obj.symbol);
    // This is cite used to find the parsing:
    // https://stackoverflow.com/questions/8648892/convert-url-parameters-to-a-javascript-object

    const api = window.api;

    api.getGeneInformation(obj).done(function (gene) {

        const locusTag = gene.ncbi.locusTag;

        const sgdHrefTemplate = "https://www.yeastgenome.org/locus/";
        const sgdId = gene.sgd.sgdID;
        $(".sgd-link").text(sgdId);
        if (sgdId !== "Not found") {
            $(".sgd-link").attr({ href: sgdHrefTemplate + sgdId });
        }

        const ncbiHrefTemplate = "https://www.ncbi.nlm.nih.gov/gene/";
        const ncbiId = gene.ncbi.ncbiID;
        $(".ncbi-link").text(ncbiId);
        if (ncbiId !== "Not found") {
            $(".ncbi-link").attr({ href: ncbiHrefTemplate + ncbiId });
        }

        const ensemblHrefTemplate = "https://www.ensembl.org/Saccharomyces_cerevisiae/Gene/Summary?g=";
        const ensemblId = locusTag;
        $(".ensembl-link").text(ensemblId);
        if (ensemblId !== "Not found") {
            $(".ensembl-link").attr({ href: ensemblHrefTemplate + ensemblId });
        }

        const uniprotHrefTemplate = "http://www.uniprot.org/uniprot/";
        const uniprotId = gene.uniprot.uniprotID;
        $(".uniprot-link").text(uniprotId);
        if (uniprotId !== "Not found") {
            $(".uniprot-link").attr({ href: uniprotHrefTemplate + uniprotId });
        }

        const jasparHrefTemplate = "http://jaspar.genereg.net/matrix/";
        const jasparId = gene.jaspar.jasparID;
        $(".jaspar-link").text(jasparId);
        if (jasparId !== "Not found") {
            $(".jaspar-link").attr({ href: jasparHrefTemplate + jasparId });
        }

        // General Information Section
        const geneDescription = gene.sgd.description;
        $(".geneDescription").text(geneDescription).attr({ href: sgdHrefTemplate + geneDescription });

        const uniSpecies = gene.uniprot.species;
        $(".uniProtSpecies").text(uniSpecies).attr({ href: uniprotHrefTemplate + uniSpecies });

        // This has been moved to top of function
        $(".ncbiLocusTag").text(locusTag).attr({ href: ncbiHrefTemplate + locusTag });

        const jasparClass = gene.jaspar.class;
        $(".jasparClass").text(jasparClass).attr({ href: jasparHrefTemplate + jasparClass });

        const jasparFam = gene.jaspar.family;
        $(".jasparFamily").text(jasparFam).attr({ href: jasparHrefTemplate + jasparFam });

        const ncbiChromosome = gene.ncbi.chromosomeSequence;
        $(".chromosomeSequence").text(ncbiChromosome).attr({ href: ncbiHrefTemplate + ncbiChromosome });

        // Protein Information

        const uniprotProteinType = gene.uniprot.proteinType;
        $(".proteinType").text(uniprotProteinType).attr({ href: uniprotHrefTemplate + uniprotProteinType });

        const uniprotProteinSequence = gene.uniprot.proteinSequence;
        if (uniprotProteinSequence !== "Not found") {
            $(".proteinSequence").text(uniprotProteinSequence.replace(/\s/g, "")).attr({ href: uniprotHrefTemplate
            + uniprotProteinSequence });
        } else {
            $(".proteinSequence").text("Not found").attr({ href: uniprotHrefTemplate
            + uniprotProteinSequence });
        }

        // Regulation Information
        const regulators = gene.regulators.regulators;

        if (regulators !== "Not found") {
            $(".regulators").append("

");
            for (let k = 0; k < regulators.length; k++) {
                $(".regulatorsTable").append("
" + regulators[k].regulator + "
");
                $(".regulatorsTable").append("
"
                + regulators[k].regulationOf + "
");
            }
        } else {
            $(".regulators").text("Not found").attr({ class : "sgdSource  col-sm-9"});
        }

        const targets = gene.regulators.targets;

        if (targets !== "Not found") {
            $(".targets").append("

");
            for (let k = 0; k < targets.length; k++) {
                $(".targetsTable").append("
" + targets[k].target + "
");
                $(".targetsTable").append("
"
                + targets[k].regulationOf + "
");
            }
        } else {
            $(".targets").text("Not found").attr({ class : "sgdSource  col-sm-9"});
        }

        // Interaction: Physical Reaction

        const sgdInteractions = gene.sgd.totalInteractions;
        $(".totalInteractions").text(sgdInteractions).attr({ href: sgdHrefTemplate + sgdInteractions });

        const sgdAffinityCaptureMS = gene.sgd.affinityCaptureMS;
        $(".affinityCaptureMS").text(sgdAffinityCaptureMS).attr({ href: sgdHrefTemplate + sgdAffinityCaptureMS });

        const sgdAffinityCaptureRNA = gene.sgd.affinityCaptureRNA;
        $(".affinityCaptureRNA").text(sgdAffinityCaptureRNA).attr({ href: sgdHrefTemplate + sgdAffinityCaptureRNA });

        const sgdAffinityCaptureWesterns = gene.sgd.affinityCaptureWestern;
        $(".affinityCaptureWestern").text(sgdAffinityCaptureWesterns).attr(
            { href: sgdHrefTemplate + sgdAffinityCaptureWesterns });

        const sgdBiochemicalActivity = gene.sgd.biochemicalActivity;
        $(".biochemicalActivity").text(sgdBiochemicalActivity).attr({ href: sgdHrefTemplate + sgdBiochemicalActivity });

        const sgdColocalization = gene.sgd.colocalization;
        $(".colocalization").text(sgdColocalization).attr({ href: sgdHrefTemplate + sgdColocalization });

        const sgdReconstitutedComplex = gene.sgd.reconstitutedComplex;
        $(".reconstitutedComplex").text(sgdReconstitutedComplex).attr(
            { href: sgdHrefTemplate + sgdReconstitutedComplex });

        const sgdTwoHybrid = gene.sgd.twoHybrid;
        $(".twoHybrid").text(sgdTwoHybrid).attr({ href: sgdHrefTemplate + sgdTwoHybrid });

        // Genetic Interactions

        const sgdDosage = gene.sgd.dosageRescue;
        $(".dosageRescue").text(sgdDosage).attr({ href: sgdHrefTemplate + sgdDosage });

        const sgdNegGen = gene.sgd.negativeGenetic;
        $(".negativeGenetic").text(sgdNegGen).attr({ href: sgdHrefTemplate + sgdNegGen });

        const sgdEnhance = gene.sgd.phenotypicEnhancement;
        $(".phenotypicEnhancement").text(sgdEnhance).attr({ href: sgdHrefTemplate + sgdEnhance });

        const sgdSuppress = gene.sgd.phenotypicSuppression;
        $(".phenotypicSuppression").text(sgdSuppress).attr({ href: sgdHrefTemplate + sgdSuppress });

        const sgdGrowthDefect = gene.sgd.syntheticGrowthDefect;
        $(".syntheticGrowthDefect").text(sgdGrowthDefect).attr({ href: sgdHrefTemplate + sgdGrowthDefect });

        const sgdHaploin = gene.sgd.syntheticHaploinsufficiency;
        $(".syntheticHaploinsufficiency").text(sgdHaploin).attr({ href: sgdHrefTemplate + sgdHaploin });

        const sgdLethality = gene.sgd.syntheticLethality;
        $(".syntheticLethality").text(sgdLethality).attr({ href: sgdHrefTemplate + sgdLethality });

        const sgdRescue = gene.sgd.syntheticRescue;
        $(".syntheticRescue").text(sgdRescue).attr({ href: sgdHrefTemplate + sgdRescue });

        // Gene Ontology
        const sgdSummary = gene.sgd.geneOntologySummary;
        $(".geneSummary").text(sgdSummary).attr({ href: sgdHrefTemplate + sgdSummary });

        const molecularFunction = gene.geneOntology.molecularFunction;
        let link;
        if (molecularFunction !== "Not found") {
            $(".molecularFunction").append("

");
            for (let k = 0; k < molecularFunction.length; k++) {
                link = "https://www.yeastgenome.org" + molecularFunction[k].link;
                $(".molecularFunctionTable").append("
" + molecularFunction[k].id + "
");
                $(".molecularFunctionTable").append("
"
                + molecularFunction[k].displayName + "
");
            }
        } else {
            $(".molecularFunction").text("Not found").attr({ class : "sgdSource col-sm-9"});
        }

        let biologicalProcess = gene.geneOntology.biologicalProcess;
        if (biologicalProcess !== "Not found") {
            $(".biologicalProcess").append("

");
            for (let k = 0; k < biologicalProcess.length; k++) {
                link = "https://www.yeastgenome.org" + biologicalProcess[k].link;
                $(".biologicalProcessTable").append("
" + biologicalProcess[k].id + "
");
                $(".biologicalProcessTable").append("
"
                + biologicalProcess[k].displayName + "
");
            }
        } else {
            $(".biologicalProcess").text("Not found").attr({ class : "sgdSource  col-sm-9"});
        }

        let cellularComponent = gene.geneOntology.cellularComponent;
        if (cellularComponent !== "Not found") {
            $(".cellularComponent").append("

");
            for (let k = 0; k < cellularComponent.length; k++) {
                link = "https://www.yeastgenome.org" +  cellularComponent[k].link;
                $(".cellularComponentTable").append("
" + cellularComponent[k].id + "
");
                $(".cellularComponentTable").append("
"
                + cellularComponent[k].displayName + "
");
            }
        } else {
            $(".cellularComponent").text("Not found").attr({ class : "sgdSource  col-sm-9"});
        }

        // Fequency Matrix and Sequence Logo
        const sequenceLogo = gene.jaspar.sequenceLogo;
        if (sequenceLogo !== "Not found") {
            $(".sequenceLogoImage").attr({ src : sequenceLogo });
        } else {
            $(".sequenceLogo").replaceWith("
Not found
");
            $(".logo").removeClass("jasparSource");
        }

        const frequencyMatrix = gene.jaspar.frequencyMatrix;

        let a = "";
        try {
            for (let i = 0; i < frequencyMatrix.A.length; i++) {
                a += "" + frequencyMatrix.A[i] + "	";
            }
        } catch (e) {
            a += " Not found 	";
        }

        $(".frequencyOfA").append($(a));

        let c = "";
        try {
            for (let k = 0; k < frequencyMatrix.C.length; k++) {
                c += "" + frequencyMatrix.C[k] + "	";
            }
        } catch (e) {
            c += " Not found 	";
        }
        $(".frequencyOfC").append($(c));

        let g = "";
        try {
            for (let j = 0; j < frequencyMatrix.C.length; j++) {
                g += "" + frequencyMatrix.C[j] + "	";
            }
        } catch (e) {
            g += " Not found 	";
        }
        $(".frequencyOfG").append($(g));

        let t = "";
        try {
            for (let h = 0; h < frequencyMatrix.C.length; h++) {
                t += "" + frequencyMatrix.C[h] + "	";
            }
        } catch (e) {
            t += " Not found 	";
        }
        $(".frequencyOfT").append($(t));

        $("#sgdSource").text("1. Saccharomyces Genome Database");
        $("#uniprotSource").text("2. UniProt");
        $("#ensemblSource").text("3. Ensembl");
        $("#ncbiSource").text("4. NCBI Gene Database");
        $("#jasparSource").text("5. JASPAR Database");

        $(" [1]").appendTo(".sgdSource");
        $("[2]").appendTo(".uniprotSource");
        $("[3]").appendTo(".ensemblSource");
        $("[4]").appendTo(".ncbiSource");
        $("[5]").appendTo(".jasparSource");

        $("a").attr("target", "blank");

    });
})();
<commit_msg>Implement native query string parsing.<commit_after>(function () {

    $(".sourceLink, button").click(function (event) {
        event.preventDefault();
        const anchorName = $(this).attr("data-target") + "Heading";
        $("html, body").animate({scrollTop: $(anchorName).offset().top});
        let currentButton = this;
        window.setTimeout(function () {
            /* I am exploiting Bootstrap's ARIA functionality for the
            purposes of this application*/
            let isOpen = $(currentButton).attr("aria-expanded") === "true";
            if (isOpen) {
                $(currentButton).removeAttr("data-toggle");
            }
        }, 200);

    });

    $(".accordionLink").click(function () {
        let currentDataTarget = "button[data-target=\'" + $(this).attr("href") + "\']";
        $(currentDataTarget).attr("data-toggle", "collapse");

        window.setTimeout(function () {
            let isOpen = $(currentDataTarget).attr("aria-expanded") === "true";
            if (isOpen) {
                $(currentDataTarget).removeAttr("data-toggle");
            }
        }, 200);
    });

    // object for gene page API calls
    // Thank you https://gist.github.com/pirate/9298155edda679510723
    const query = new URLSearchParams(location.search);
    const obj = {
        symbol: query.get('symbol'),
        species: query.get('species'),
        jaspar: query.get('jaspar'),
        uniprot: query.get('uniprot')
    };

    document.title = "GRNsight - " + obj.symbol;
    $("#gene-name").text(obj.symbol);
    // This is cite used to find the parsing:
    // https://stackoverflow.com/questions/8648892/convert-url-parameters-to-a-javascript-object

    const api = window.api;

    api.getGeneInformation(obj).done(function (gene) {

        const locusTag = gene.ncbi.locusTag;

        const sgdHrefTemplate = "https://www.yeastgenome.org/locus/";
        const sgdId = gene.sgd.sgdID;
        $(".sgd-link").text(sgdId);
        if (sgdId !== "Not found") {
            $(".sgd-link").attr({ href: sgdHrefTemplate + sgdId });
        }

        const ncbiHrefTemplate = "https://www.ncbi.nlm.nih.gov/gene/";
        const ncbiId = gene.ncbi.ncbiID;
        $(".ncbi-link").text(ncbiId);
        if (ncbiId !== "Not found") {
            $(".ncbi-link").attr({ href: ncbiHrefTemplate + ncbiId });
        }

        const ensemblHrefTemplate = "https://www.ensembl.org/Saccharomyces_cerevisiae/Gene/Summary?g=";
        const ensemblId = locusTag;
        $(".ensembl-link").text(ensemblId);
        if (ensemblId !== "Not found") {
            $(".ensembl-link").attr({ href: ensemblHrefTemplate + ensemblId });
        }

        const uniprotHrefTemplate = "http://www.uniprot.org/uniprot/";
        const uniprotId = gene.uniprot.uniprotID;
        $(".uniprot-link").text(uniprotId);
        if (uniprotId !== "Not found") {
            $(".uniprot-link").attr({ href: uniprotHrefTemplate + uniprotId });
        }

        const jasparHrefTemplate = "http://jaspar.genereg.net/matrix/";
        const jasparId = gene.jaspar.jasparID;
        $(".jaspar-link").text(jasparId);
        if (jasparId !== "Not found") {
            $(".jaspar-link").attr({ href: jasparHrefTemplate + jasparId });
        }

        // General Information Section
        const geneDescription = gene.sgd.description;
        $(".geneDescription").text(geneDescription).attr({ href: sgdHrefTemplate + geneDescription });

        const uniSpecies = gene.uniprot.species;
        $(".uniProtSpecies").text(uniSpecies).attr({ href: uniprotHrefTemplate + uniSpecies });

        // This has been moved to top of function
        $(".ncbiLocusTag").text(locusTag).attr({ href: ncbiHrefTemplate + locusTag });

        const jasparClass = gene.jaspar.class;
        $(".jasparClass").text(jasparClass).attr({ href: jasparHrefTemplate + jasparClass });

        const jasparFam = gene.jaspar.family;
        $(".jasparFamily").text(jasparFam).attr({ href: jasparHrefTemplate + jasparFam });

        const ncbiChromosome = gene.ncbi.chromosomeSequence;
        $(".chromosomeSequence").text(ncbiChromosome).attr({ href: ncbiHrefTemplate + ncbiChromosome });

        // Protein Information

        const uniprotProteinType = gene.uniprot.proteinType;
        $(".proteinType").text(uniprotProteinType).attr({ href: uniprotHrefTemplate + uniprotProteinType });

        const uniprotProteinSequence = gene.uniprot.proteinSequence;
        if (uniprotProteinSequence !== "Not found") {
            $(".proteinSequence").text(uniprotProteinSequence.replace(/\s/g, "")).attr({ href: uniprotHrefTemplate
            + uniprotProteinSequence });
        } else {
            $(".proteinSequence").text("Not found").attr({ href: uniprotHrefTemplate
            + uniprotProteinSequence });
        }

        // Regulation Information
        const regulators = gene.regulators.regulators;

        if (regulators !== "Not found") {
            $(".regulators").append("

");
            for (let k = 0; k < regulators.length; k++) {
                $(".regulatorsTable").append("
" + regulators[k].regulator + "
");
                $(".regulatorsTable").append("
"
                + regulators[k].regulationOf + "
");
            }
        } else {
            $(".regulators").text("Not found").attr({ class : "sgdSource  col-sm-9"});
        }

        const targets = gene.regulators.targets;

        if (targets !== "Not found") {
            $(".targets").append("

");
            for (let k = 0; k < targets.length; k++) {
                $(".targetsTable").append("
" + targets[k].target + "
");
                $(".targetsTable").append("
"
                + targets[k].regulationOf + "
");
            }
        } else {
            $(".targets").text("Not found").attr({ class : "sgdSource  col-sm-9"});
        }

        // Interaction: Physical Reaction

        const sgdInteractions = gene.sgd.totalInteractions;
        $(".totalInteractions").text(sgdInteractions).attr({ href: sgdHrefTemplate + sgdInteractions });

        const sgdAffinityCaptureMS = gene.sgd.affinityCaptureMS;
        $(".affinityCaptureMS").text(sgdAffinityCaptureMS).attr({ href: sgdHrefTemplate + sgdAffinityCaptureMS });

        const sgdAffinityCaptureRNA = gene.sgd.affinityCaptureRNA;
        $(".affinityCaptureRNA").text(sgdAffinityCaptureRNA).attr({ href: sgdHrefTemplate + sgdAffinityCaptureRNA });

        const sgdAffinityCaptureWesterns = gene.sgd.affinityCaptureWestern;
        $(".affinityCaptureWestern").text(sgdAffinityCaptureWesterns).attr(
            { href: sgdHrefTemplate + sgdAffinityCaptureWesterns });

        const sgdBiochemicalActivity = gene.sgd.biochemicalActivity;
        $(".biochemicalActivity").text(sgdBiochemicalActivity).attr({ href: sgdHrefTemplate + sgdBiochemicalActivity });

        const sgdColocalization = gene.sgd.colocalization;
        $(".colocalization").text(sgdColocalization).attr({ href: sgdHrefTemplate + sgdColocalization });

        const sgdReconstitutedComplex = gene.sgd.reconstitutedComplex;
        $(".reconstitutedComplex").text(sgdReconstitutedComplex).attr(
            { href: sgdHrefTemplate + sgdReconstitutedComplex });

        const sgdTwoHybrid = gene.sgd.twoHybrid;
        $(".twoHybrid").text(sgdTwoHybrid).attr({ href: sgdHrefTemplate + sgdTwoHybrid });

        // Genetic Interactions

        const sgdDosage = gene.sgd.dosageRescue;
        $(".dosageRescue").text(sgdDosage).attr({ href: sgdHrefTemplate + sgdDosage });

        const sgdNegGen = gene.sgd.negativeGenetic;
        $(".negativeGenetic").text(sgdNegGen).attr({ href: sgdHrefTemplate + sgdNegGen });

        const sgdEnhance = gene.sgd.phenotypicEnhancement;
        $(".phenotypicEnhancement").text(sgdEnhance).attr({ href: sgdHrefTemplate + sgdEnhance });

        const sgdSuppress = gene.sgd.phenotypicSuppression;
        $(".phenotypicSuppression").text(sgdSuppress).attr({ href: sgdHrefTemplate + sgdSuppress });

        const sgdGrowthDefect = gene.sgd.syntheticGrowthDefect;
        $(".syntheticGrowthDefect").text(sgdGrowthDefect).attr({ href: sgdHrefTemplate + sgdGrowthDefect });

        const sgdHaploin = gene.sgd.syntheticHaploinsufficiency;
        $(".syntheticHaploinsufficiency").text(sgdHaploin).attr({ href: sgdHrefTemplate + sgdHaploin });

        const sgdLethality = gene.sgd.syntheticLethality;
        $(".syntheticLethality").text(sgdLethality).attr({ href: sgdHrefTemplate + sgdLethality });

        const sgdRescue = gene.sgd.syntheticRescue;
        $(".syntheticRescue").text(sgdRescue).attr({ href: sgdHrefTemplate + sgdRescue });

        // Gene Ontology
        const sgdSummary = gene.sgd.geneOntologySummary;
        $(".geneSummary").text(sgdSummary).attr({ href: sgdHrefTemplate + sgdSummary });

        const molecularFunction = gene.geneOntology.molecularFunction;
        let link;
        if (molecularFunction !== "Not found") {
            $(".molecularFunction").append("

");
            for (let k = 0; k < molecularFunction.length; k++) {
                link = "https://www.yeastgenome.org" + molecularFunction[k].link;
                $(".molecularFunctionTable").append("
" + molecularFunction[k].id + "
");
                $(".molecularFunctionTable").append("
"
                + molecularFunction[k].displayName + "
");
            }
        } else {
            $(".molecularFunction").text("Not found").attr({ class : "sgdSource col-sm-9"});
        }

        let biologicalProcess = gene.geneOntology.biologicalProcess;
        if (biologicalProcess !== "Not found") {
            $(".biologicalProcess").append("

");
            for (let k = 0; k < biologicalProcess.length; k++) {
                link = "https://www.yeastgenome.org" + biologicalProcess[k].link;
                $(".biologicalProcessTable").append("
" + biologicalProcess[k].id + "
");
                $(".biologicalProcessTable").append("
"
                + biologicalProcess[k].displayName + "
");
            }
        } else {
            $(".biologicalProcess").text("Not found").attr({ class : "sgdSource  col-sm-9"});
        }

        let cellularComponent = gene.geneOntology.cellularComponent;
        if (cellularComponent !== "Not found") {
            $(".cellularComponent").append("

");
            for (let k = 0; k < cellularComponent.length; k++) {
                link = "https://www.yeastgenome.org" +  cellularComponent[k].link;
                $(".cellularComponentTable").append("
" + cellularComponent[k].id + "
");
                $(".cellularComponentTable").append("
"
                + cellularComponent[k].displayName + "
");
            }
        } else {
            $(".cellularComponent").text("Not found").attr({ class : "sgdSource  col-sm-9"});
        }

        // Fequency Matrix and Sequence Logo
        const sequenceLogo = gene.jaspar.sequenceLogo;
        if (sequenceLogo !== "Not found") {
            $(".sequenceLogoImage").attr({ src : sequenceLogo });
        } else {
            $(".sequenceLogo").replaceWith("
Not found
");
            $(".logo").removeClass("jasparSource");
        }

        const frequencyMatrix = gene.jaspar.frequencyMatrix;

        let a = "";
        try {
            for (let i = 0; i < frequencyMatrix.A.length; i++) {
                a += "" + frequencyMatrix.A[i] + "	";
            }
        } catch (e) {
            a += " Not found 	";
        }

        $(".frequencyOfA").append($(a));

        let c = "";
        try {
            for (let k = 0; k < frequencyMatrix.C.length; k++) {
                c += "" + frequencyMatrix.C[k] + "	";
            }
        } catch (e) {
            c += " Not found 	";
        }
        $(".frequencyOfC").append($(c));

        let g = "";
        try {
            for (let j = 0; j < frequencyMatrix.C.length; j++) {
                g += "" + frequencyMatrix.C[j] + "	";
            }
        } catch (e) {
            g += " Not found 	";
        }
        $(".frequencyOfG").append($(g));

        let t = "";
        try {
            for (let h = 0; h < frequencyMatrix.C.length; h++) {
                t += "" + frequencyMatrix.C[h] + "	";
            }
        } catch (e) {
            t += " Not found 	";
        }
        $(".frequencyOfT").append($(t));

        $("#sgdSource").text("1. Saccharomyces Genome Database");
        $("#uniprotSource").text("2. UniProt");
        $("#ensemblSource").text("3. Ensembl");
        $("#ncbiSource").text("4. NCBI Gene Database");
        $("#jasparSource").text("5. JASPAR Database");

        $(" [1]").appendTo(".sgdSource");
        $("[2]").appendTo(".uniprotSource");
        $("[3]").appendTo(".ensemblSource");
        $("[4]").appendTo(".ncbiSource");
        $("[5]").appendTo(".jasparSource");

        $("a").attr("target", "blank");

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


<commit_before>"use strict";
var log = console.log.bind(console);
//var g, gl, program;
var g, gl, program;

g = {
	surface: {width:640, height:360},
	isOddFrame: false
};

// =================================================================
window.onload = function(){

	gl = getContext("glCanvas", 640, 360);
	program = getProgram(gl);

	loadImages(["atlas2048_32.png","atlas2048_32.png"], render);
}

// =================================================================
function render(images) {
	var renderWrapper = function(){render(images);};
	requestAnimationFrame(renderWrapper);
	//console.log("test");

	// look up where the vertex data needs to go.
	var positionLocation = gl.getAttribLocation(program, "a_position");
	var texCoordLocation = gl.getAttribLocation(program, "a_texCoord");

	// provide texture coordinates for the rectangle.
	var texCoordBuffer = gl.createBuffer();
	gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);

	var n = 1.0/64.0; // 2048/64 = 32
	gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
		// 0.0,  0.0,
		// 1.0,  0.0,
		// 0.0,  1.0,
		// 0.0,  1.0,
		// 1.0,  0.0,
		// 1.0,  1.0
		0.0,  0.0,
		n,  0.0,
		0.0,  n,
		0.0,  n,
		n,  0.0,
		n,  n
	]), gl.STATIC_DRAW);
	gl.enableVertexAttribArray(texCoordLocation);
	gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);

	  // create 2 textures
	var textures = [];
	for (var ii = 0; ii < 2; ++ii) {
		var texture = gl.createTexture();
		gl.bindTexture(gl.TEXTURE_2D, texture);

		// Set the parameters so we can render any size image.
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

		// Upload the image into the texture.
		gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, images[ii]);

		// add the texture to the array of textures.
		textures.push(texture);
	}

	// lookup uniforms
	var resolutionLocation = gl.getUniformLocation(program, "u_resolution");

	// lookup the sampler locations.
	var u_image0Location = gl.getUniformLocation(program, "u_image0");
	var u_image1Location = gl.getUniformLocation(program, "u_image1");

	// set the resolution
	gl.uniform2f(resolutionLocation, g.surface.width, g.surface.height);

	// set which texture units to render with.
	gl.uniform1i(u_image0Location, 0);  // texture unit 0
	gl.uniform1i(u_image1Location, 1);  // texture unit 1

	// Set each texture unit to use a particular texture.
	gl.activeTexture(gl.TEXTURE0);
	gl.bindTexture(gl.TEXTURE_2D, textures[0]);

	gl.activeTexture(gl.TEXTURE1);
	gl.bindTexture(gl.TEXTURE_2D, textures[1]);

	// Create a buffer for the position of the rectangle corners.
	var positionBuffer = gl.createBuffer();
	gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
	gl.enableVertexAttribArray(positionLocation);
	gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);

	// Set a rectangle the same size as the images.
	//setRectangle(gl, 0, 0, images[0].width, images[0].height);
	setRectangle(gl, 0, 0, 32,32);
	gl.drawArrays(gl.TRIANGLES, 0, 6);

	// Draw the rectangle.

}

function randomInt(range) {
	return Math.floor(Math.random() * range);
}

function setRectangle(gl, x, y, width, height) {
	var x1 = x;
	var x2 = x + width;
	var y1 = y;
	var y2 = y + height;
	gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
		x1, y1,
		x2, y1,
		x1, y2,
		x1, y2,
		x2, y1,
		x2, y2
	]), gl.STATIC_DRAW);
}

// =================================================================
<commit_msg>draw part of atlas to screen<commit_after>"use strict";
var log = console.log.bind(console);
//var g, gl, program;
var g, gl, program;

g = {
	surface: {width:640, height:360},
	tile: {width:32, height:32},
	atlas: {width:2048, height:2048},
	isOddFrame: false
};

// =================================================================
window.onload = function(){

	gl = getContext("glCanvas", 640, 360);
	program = getProgram(gl);

	loadImages(["atlas2048_32.png","atlas2048_32.png"], render); // load as if there were a second image
}

// =================================================================
function render(images) {
	var renderWrapper = function(){render(images);};
	requestAnimationFrame(renderWrapper);

	// find vertex data destination
	var positionLocation = gl.getAttribLocation(program, "a_position");
	var texCoordLocation = gl.getAttribLocation(program, "a_texCoord");

	// texture coordinates for the rectangle
	var texCoordBuffer = gl.createBuffer();
	gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);

	var xScale,yScale,xZoom,yZoom,x,y;
	x = g.surface.width/g.atlas.width;
	y = g.surface.height/g.atlas.height;
	gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
		0.0,  0.0,
		x,    0.0,
		0.0,  y,
		0.0,  y,
		x,    0.0,
		x,    y
	]), gl.STATIC_DRAW);
	gl.enableVertexAttribArray(texCoordLocation);
	gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);

	var textures = [];
	for (var i = 0; i < 1; ++i) { // create n textures
		var texture = gl.createTexture();
		gl.bindTexture(gl.TEXTURE_2D, texture);

		// set parameters to render any size image.
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
		gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

		gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, images[i]); // Upload the image into the texture.

		textures.push(texture); // array of textures
	}

	var resolutionLocation = gl.getUniformLocation(program, "u_resolution"); // lookup uniforms

	// lookup sampler locations.
	var u_image0Location = gl.getUniformLocation(program, "u_image0");
	var u_image1Location = gl.getUniformLocation(program, "u_image1");

	// set the resolution
	gl.uniform2f(resolutionLocation, g.surface.width, g.surface.height);

	// set which texture units to render with.
	gl.uniform1i(u_image0Location, 0);  // texture unit 0
	gl.uniform1i(u_image1Location, 1);  // texture unit 1

	// Set each texture unit to use a particular texture.
	gl.activeTexture(gl.TEXTURE0);
	gl.bindTexture(gl.TEXTURE_2D, textures[0]);

	gl.activeTexture(gl.TEXTURE1);
	gl.bindTexture(gl.TEXTURE_2D, textures[1]);

	// Create a buffer for the position of the rectangle corners.
	var positionBuffer = gl.createBuffer();
	gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
	gl.enableVertexAttribArray(positionLocation);
	gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);

	// Set a rectangle the same size as the images.
	//setRectangle(gl, 0, 0, images[0].width, images[0].height);
	//setRectangle(gl, 0, 0, 32,32);
	setRectangle(gl, 0, 0, g.surface.width,g.surface.height);
	gl.drawArrays(gl.TRIANGLES, 0, 6);

	// Draw the rectangle.

}

function randomInt(range) {
	return Math.floor(Math.random() * range);
}

function setRectangle(gl, x, y, width, height) {
	var x1 = x;
	var x2 = x + width;
	var y1 = y;
	var y2 = y + height;
	gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
		x1, y1,
		x2, y1,
		x1, y2,
		x1, y2,
		x2, y1,
		x2, y2
	]), gl.STATIC_DRAW);
}

// =================================================================
<|endoftext|>