<commit_before>/***
|''Requires''|TiddlySpaceConfig|
***/
//{{{
(function($) {

if(config.options.chkBackstage === undefined) {
	config.options.chkBackstage = true;
}

config.backstageTasks = [];

config.tasks.login = {
	text: "login",
	tooltip: "TiddlySpace login",
	content: "<<tiddler BackstageLogin>>"
};
config.backstageTasks.push("login");

config.tasks.user = {
	text: "user: ",
	tooltip: "user control panel",
	content: "<<tiddler BackstageUser>>"
};
config.backstageTasks.push("user");

config.tasks.space = {
	text: "space: "+config.extensions.tiddlyspace.currentSpace.name,
	tooltip: "space control panel",
	content: "<<tiddler BackstageSpace>>",
	className: "right"
};
config.backstageTasks.push("space");

config.messages.backstage.prompt = "";
// initialize state
var _show = backstage.show;
backstage.show = function() {
	// selectively hide backstage tasks based on user status
	var tasks = $("#backstageToolbar .backstageTask").show();
	config.extensions.tiddlyweb.getUserInfo(function(user) {
		if(user.anon) {
			tasks.slice(1, 2).hide();
		} else {
			tasks.eq(0).hide();
		}
	});
	// display backstage
	return _show.apply(this, arguments);
};

var _init = backstage.init;
backstage.init = function(){
	_init.apply(this, arguments);
	// update usernames
	var userButton = $(".backstageTask[task=user]").
	html("").html('%0%1'.
		format([config.tasks.user.text, glyph("downTriangle")]));
	config.macros.option.handler($(".txtUserName",userButton)[0],null,["txtUserName"]);

	// make the backstage become visible when you mouseover it
	var _revealBackstageArea;
	$("#backstageButton").mouseover(function(ev) { // when mouseover the button set a timeout to show backstage
		if(!backstage.isVisible()){
			_revealBackstageArea = window.setTimeout(function() {
				if(!backstage.isVisible()) {
					backstage.show();
				}
			},"600");}
		}
	).
	mouseout(function(ev){ // on a mouseout we prevent showing of the backstage.
		if(_revealBackstageArea) {
			window.clearTimeout(_revealBackstageArea);
		}
	});

	// override show button with an svg image
	var showButton = $("#backstageShow")[0];
	var altText = $(showButton).text();
	$(showButton).empty();
	invokeMacro(showButton, "image", "backstage.svg 60 60 alt:%0".format([altText]), null);

	// override hide button
	var hideButton =$("#backstageHide")[0];
	altText = $(hideButton).text();
	$(hideButton).empty();
	invokeMacro(hideButton, "image", "close.svg 25 25 alt:%0".format([altText]), null);

	var backstageToolbar = $("#backstageToolbar")[0];
	$("

").prependTo(backstageToolbar);
	wikify("<<image tiddlyspace.svg 16 16>> ''{{privateLightText{tiddly}}}{{publicLightText{space}}}''",
		$("#backstageLogo", backstageToolbar)[0]);

	var siteIcon =store.getTiddler("SiteIcon");
	if(siteIcon) {
		var spaceButton = $("[task=space]","#backstageArea");
		var existing = spaceButton.text();
		spaceButton.empty();
		$('').
			attr("src","SiteIcon").appendTo(spaceButton);
		$("").text(existing).appendTo(spaceButton);

	}

	var tiddlyweb = config.extensions.tiddlyweb;
	tiddlyweb.getStatus(function(status) {
		var server_host = status.server_host;
		var tsHost = server_host.scheme + "://" + server_host.host;
		if(server_host.port && server_host.port != "80" &&
			server_host.port != "443") {
			tsHost += ":" + server_host.port;
		}

		tiddlyweb.getUserInfo(function(user) {
			// show avatar in the users public bag
			if(!user.anon) {
				var src = "%0/recipes/%1_public/tiddlers/SiteIcon".
					format([tsHost, user.name]);
				$("").attr("src", src).appendTo("").
					appendTo("[task=user]","#backstageArea");
			}
		});

		// show default avatar for the login button
		var loginButton = $("[task=login]", "#backstageArea");
		var existing = loginButton.text();
		loginButton.html('%0'
			.format([existing]));

		var tasks = $(".backstageTask");
		for(var i = 0; i < tasks.length; i++) {
			var btn = $(tasks[i]);
			var taskName = btn.attr("task");
			btn.addClass("task_%0".format([taskName]));
		}
	});
};

})(jQuery);
//}}}
<commit_msg>code cleanup<commit_after>/***
|''Requires''|TiddlySpaceConfig|
***/
//{{{
(function($) {

if(config.options.chkBackstage === undefined) {
	config.options.chkBackstage = true;
}

config.backstageTasks = [];

config.tasks.login = {
	text: "login",
	tooltip: "TiddlySpace login",
	content: "<<tiddler BackstageLogin>>"
};
config.backstageTasks.push("login");

config.tasks.user = {
	text: "user: ",
	tooltip: "user control panel",
	content: "<<tiddler BackstageUser>>"
};
config.backstageTasks.push("user");

config.tasks.space = {
	text: "space: " + config.extensions.tiddlyspace.currentSpace.name,
	tooltip: "space control panel",
	content: "<<tiddler BackstageSpace>>",
	className: "right"
};
config.backstageTasks.push("space");

config.messages.backstage.prompt = "";
// initialize state
var _show = backstage.show;
backstage.show = function() {
	// selectively hide backstage tasks based on user status
	var tasks = $("#backstageToolbar .backstageTask").show();
	config.extensions.tiddlyweb.getUserInfo(function(user) {
		if(user.anon) {
			tasks.slice(1, 2).hide();
		} else {
			tasks.eq(0).hide();
		}
	});
	// display backstage
	return _show.apply(this, arguments);
};

var _init = backstage.init;
backstage.init = function(){
	_init.apply(this, arguments);
	// update usernames
	var userButton = $(".backstageTask[task=user]").
	html("").html('%0%1'.
		format([config.tasks.user.text, glyph("downTriangle")]));
	config.macros.option.handler($(".txtUserName", userButton)[0], null, ["txtUserName"]);

	// make the backstage become visible when you mouseover it
	var _revealBackstageArea;
	$("#backstageButton").mouseover(function(ev) { // when mouseover the button set a timeout to show backstage
		if(!backstage.isVisible()){
			_revealBackstageArea = window.setTimeout(function() {
				if(!backstage.isVisible()) {
					backstage.show();
				}
			},"600");}
		}
	).
	mouseout(function(ev){ // on a mouseout we prevent showing of the backstage.
		if(_revealBackstageArea) {
			window.clearTimeout(_revealBackstageArea);
		}
	});

	// override show button with an svg image
	var showButton = $("#backstageShow")[0];
	var altText = $(showButton).text();
	$(showButton).empty();
	invokeMacro(showButton, "image", "backstage.svg 60 60 alt:%0".format([altText]), null);

	// override hide button
	var hideButton =$("#backstageHide")[0];
	altText = $(hideButton).text();
	$(hideButton).empty();
	invokeMacro(hideButton, "image", "close.svg 25 25 alt:%0".format([altText]), null);

	var backstageToolbar = $("#backstageToolbar")[0];
	$("
").prependTo(backstageToolbar);
	wikify("<<image tiddlyspace.svg 16 16>> ''{{privateLightText{tiddly}}}{{publicLightText{space}}}''",
		$("#backstageLogo", backstageToolbar)[0]);

	var siteIcon =store.getTiddler("SiteIcon");
	if(siteIcon) {
		var btn = $("[task=space]", "#backstageArea");
		var existing = btn.text();
		btn.empty();
		$('').
			attr("src", "SiteIcon").appendTo(btn);
		$("").text(existing).appendTo(btn);

	}

	var tiddlyweb = config.extensions.tiddlyweb;
	tiddlyweb.getStatus(function(status) {
		var server_host = status.server_host;
		var tsHost = server_host.scheme + "://" + server_host.host;
		if(server_host.port && server_host.port != "80" &&
			server_host.port != "443") {
			tsHost += ":" + server_host.port;
		}

		tiddlyweb.getUserInfo(function(user) {
			// show avatar in the users public bag
			if(!user.anon) {
				var src = "%0/recipes/%1_public/tiddlers/SiteIcon".
					format([tsHost, user.name]);
				$("").attr("src", src).appendTo("").
					appendTo("[task=user]", "#backstageArea");
			}
		});

		// show default avatar for the login button
		var btn = $("[task=login]", "#backstageArea");
		var existing = btn.text();
		btn.html('%0'
			.format([existing]));

		var tasks = $(".backstageTask");
		for(var i = 0; i < tasks.length; i++) {
			var btn = $(tasks[i]);
			var taskName = btn.attr("task");
			btn.addClass("task_%0".format([taskName]));
		}
	});
};

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


<commit_before>/*
 * assemble-contrib-rss
 * https://github.com/assemble/assemble-contrib-rss
 *
 * Copyright (c) 2013 Jon Schlinkert, contributors.
 * Licensed under the MIT license.
 */

// Node.js
var path = require('path'),
    url = require('url');

// node_modules
var chalk = require('chalk'),
    moment = require('moment'),
    RSS = require('rss');

/*
 * @param  {Object}   config
 * @param  {Function} callback
 * @return {String}   The permalink string
 */
module.exports = function(config, callback) {

  'use strict';

  var options = config.context,
      grunt = config.grunt,
      pkg = grunt.file.readJSON(path.join(process.cwd(), 'package.json')),
      feed = options.feed || {};

  var pages = options.pages,
      page = options.page;

  var async = grunt.util.async,
      _ = grunt.util._;

  var Utils = require('./lib/utils');

  /*
   * Moment.js default language
  */
  moment.lang(feed.language || 'en');

  // Skip over the plugin if it isn't defined in the options.
  if(!_.isUndefined(feed)) {

    var failFeed = function(prop) {
      if(feed.logging) {
        return grunt.fail.fatal(('"feed: ' + prop + '"').yellow + ' not defined in gruntfile.js for RSS feed.'.bold);
      } else {
        return;
      }
    }

    /*
     * Generate the main RSS feed.
     */
    var feed = new RSS({
      generator     : feed.generator      || 'Generated by Assemble, JavaScript static site generator. Visit http://assemble.io to learn more.',
      lastBuildDate : moment().format("dddd, MMMM Do YYYY"),
      title         : feed.title          || pkg.name,
      description   : feed.description    || pkg.description,
      pubdate       : feed.pubdate,
      site_url      : feed.siteurl        || pkg.homepage,
      feed_url      : feed.feedurl        || url.resolve(pkg.homepage, feed.dest || 'feed.xml'),
      image_url     : feed.imageurl,
      author        : feed.author         || pkg.author.name || failFeed('author'),
      managingEditor: feed.managingEditor,
      webMaster     : feed.webMaster,
      categories    : feed.categories,
      docs          : feed.docs,
      copyright     : feed.copyright      || 'Copyright' + moment().format("YYYY") + ' ' + pkg.author.name || '',
      language      : feed.language       || 'en',
      ttl           : feed.ttl            || '60',
      geoRSS        : feed.geoRSS         || false
    });

    /*
     * Generate the feeds for each page.
     */
    async.forEachSeries(pages, function(file, next) {

      var failItem = function(prop) {
        if(feed.logging) {
          return grunt.fail.fatal(('"rss: ' + prop + '"').yellow + ' not defined for ' + ('"' + file.filename + '"').bold);
        } else {
          return;
        }
      }

      if (page.src !== file.src) {
        next();
        return;
      }

      // Define defaults for items.
      feed.items = feed.items || {};
      file.feed  = file.feed || {};

      feed.item({
        date        : feed.items.date        || file.feed.date         || file.feed.pubdate || failItem('date'),
        author      : feed.items.author      || file.feed.author       || feed.author       || failItem('author'),
        title       : feed.items.title       || file.feed.title        || failItem('title'),
        description : feed.items.description || file.feed.description,
        url         : feed.items.url         || file.feed.url          || url.resolve(pkg.homepage, file.dest),
        guid        : feed.items.guid        || file.feed.guid         || file.feed.url,
        categories  : feed.items.categories  || file.feed.categories,
        lat         : feed.items.lat         || file.feed.lat,
        long        : feed.items.long        || file.feed.long,
        // enclosure: {
        //   url    : '...',
        //   file   : 'path-to-file'
        // } // optional enclosure
      });

      // cache the xml
      var xml = feed.xml();

      // optionally format XML
      if(options.feed.format === true) {
        xml = Utils.formatXML(xml);
      }

      // For each page that has a feed, write the RSS xml file to the same
      // dest path defined for the page, unless a custom path is defined.
      var dest = path.join(path.dirname(file.dest), feed.dest || 'feed.xml');

      // Write the feed
      grunt.file.write(dest, xml);
      grunt.verbose.success('>> RSS feed generated in '.green + dest.replace(/\\/g, '/'));
      next();

    }, function (err) {
      callback();
    });
  }
};
<commit_msg>Initial cleanup of man lib<commit_after>var path = require('path');
var url = require('url');

var chalk = require('chalk');
var moment = require('moment');
var rss = require('rss');

module.exports = function(config, callback) {

  'use strict';

  var options = config.context;
  var grunt = config.grunt;
  var pkg = grunt.file.readJSON(path.join(process.cwd(), 'package.json'));
  var feed = options.feed || {};

  var pages = options.pages;
  var page = options.page;

  var async = grunt.util.async;
  var _ = grunt.util._;

  var utils = require('./lib/utils');

  // Moment.js default language
  moment.lang(feed.language || 'en');

  // Skip over the plugin if it isn't defined in the options.
  if(!_.isUndefined(feed)) {

    var failFeed = function(prop) {
      if(feed.logging) {
        return grunt.fail.fatal(
          ('"feed: ' + prop + '"').yellow +
          ' not defined in gruntfile.js for RSS feed.'.bold
        );
      } else {
        return;
      }
    }

    var copyright = 'Copyright' + moment().format("YYYY") + ' ' + pkg.author.name;

    var feed = new rss({
      generator: feed.generator || 'Generated by Assemble.js.',
      lastBuildDate: moment().format("dddd, MMMM Do YYYY"),
      title: feed.title || pkg.name,
      description: feed.description || pkg.description,
      pubdate: feed.pubdate,
      site_url: feed.siteurl || pkg.homepage,
      feed_url: feed.feedurl || url.resolve(pkg.homepage, feed.dest || 'feed.xml'),
      image_url: feed.imageurl,
      author: feed.author || pkg.author.name || failFeed('author'),
      managingEditor: feed.managingEditor,
      webMaster: feed.webMaster,
      categories: feed.categories,
      docs: feed.docs,
      copyright: feed.copyright || '',
      language: feed.language || 'en',
      ttl: feed.ttl || '60',
      geoRSS: feed.geoRSS || false
    });

  }
};
<|endoftext|>


<commit_before>var fs = require('fs');
jsbot = require('./jsbot');

///////////////////////////

Array.prototype.random = function() {
    return this[Math.floor((Math.random()*this.length))];
};

///////////////////////////

var admin = 'reality';
var waitingForKarma = false;
var name = 'depressionbot';
var db = JSON.parse(fs.readFileSync('db.json', 'utf-8'));

var instance = jsbot.createJSBot(name, 'elara.ivixor.net', 6667, function() {
    instance.join('#42');
    instance.join('#itonlygetsworse');
}.bind(this));

instance.addListener('JOIN', function(data) {
    if(data.user == 'Lamp') {
        instance.say(data.channel, db.lampPuns.random());
    } else if(data.user == 'reality') {
        instance.say(data.channel, db.realiPuns.random());
    } else if(instance.inChannel(data.channel)) {
        instance.say('aisbot', '.karma ' + data.user);
        waitingForKarma = data.channel;
    }
});

instance.addListener('KICK', function(data) {
    if(data.kickee == name) {
	instance.join(data.channel);
        instance.say(data.channel, 'Thou shalt not kick ' + name);
    } else {
      instance.say(data.channel, data.kickee + '--');
    }
});

instance.addListener('PRIVMSG', function(data) {
    if(data.user == 'aisbot' && data.channel == name && waitingForKarma != false) {
        var split = data.message.split(' ');
        var target = split[0];
        var karma = split[3];

        if(karma.startsWith('-')) {
            instance.say(waitingForKarma, target + db.hatedPhrases.random() + ' (' + karma + ')');
        } else if(karma == '0') {
            instance.say(waitingForKarma, 'All ' + target + ' knows is that their gut says \'maybe.\' (0)');
        } else {
            instance.say(waitingForKarma, target + db.lovedPhrases.random() + ' (' + karma + ')');
        }

        waitingForKarma = false;
    }
});

instance.addListener('PRIVMSG', function(data) {
    if(data.user == admin && data.channel == name) {
        params = data.message.split(' ');
        switch(params[0]) {
            case 'join':
                instance.join(params[1]);
                instance.say(admin, 'Joined ' + params[1]);
                break;
            case 'part':
                instance.part(params[1]);
                instance.say(admin, 'Left ' + params[1]);
                break;
            case 'reload':
                instance.say(admin, 'Reloading DB.');
                try {
                    db = JSON.parse(fs.readFileSync('db.json', 'utf-8'));
                } catch(err) {
                    instance.say(admin, 'DB reload failed.');
                } finally {
                    instance.say(admin, 'DB Reload successful.');
                }
                break;
            case 'say':
                var c = params[1];
                var m = params.slice(2).join(' ');
                instance.say(c, m);
                break;
            case 'add':
                // not very safe, but you're the admin so suck it
                var c = params[1];
                var m = params.slice(2).join(' ');
                db[c].push(m);
                fs.writeFile('db.json', JSON.stringify(db, null, '    '));
                instance.say(admin, 'Added.');
                break;
        }
    }
});

instance.addListener('PRIVMSG', function(data) {
    if(data.channel == name) data.channel = data.user;

    if(data.message.startsWith('~')) {
        var params = data.message.split(' ');
        switch(params[0]) {
            case '~kc':
                instance.say('aisbot', '.karma ' + data.message.split(' ')[1]);
                waitingForKarma = data.channel;
                break;
            case '~qset':
                var qset = data.message.match(/~qset ([\d\w\s]*)=(.+)$/);
                if(qset != null && qset.length >= 3) {
                    db.quotes[qset[1]] = qset[2];
                    instance.say(data.channel, 'Quote saved as \'' + qset[1] + '\'');
                    fs.writeFile('db.json', JSON.stringify(db, null, '    '));
                } else {
                    instance.say(data.channel, 'Burn the invalid syntax!');
                }
                break;
            case '~q':
                var q = data.message.match(/~q ([\d\w\s]*)/)[1].trim();
                instance.say(data.channel, q + ': ' + db.quotes[q]);
                break;
            case '~qa':
                var q = data.message.match(/~qa ([\d\w\s]*)/)[1].trim();
                if(db.quoteArrs[q] != undefined) {
                    instance.say(data.channel, q + ': ' + db.quoteArrs[q].random());
                }
                break;
            case '~qadd':
                var qadd = data.message.match(/~qadd ([\d\w\s]*)=(.+)$/);
                if(qadd != null && qadd.length >= 3) {
                    if(Object.isArray(db.quoteArrs[qadd[1]])) {
                        db.quoteArrs[qadd[1]].push(qadd[2]);
                    } else {
                        db.quoteArrs[qadd[1]] = [qadd[2]];
                    }
                    instance.say(data.channel, 'Quote saved in \'' + qadd[1] + '\'');
                    fs.writeFile('db.json', JSON.stringify(db, null, '    '));
                } else {
                    instance.say(data.channel, 'Burn the invalid syntax!');
                }
                break;
            case '~qcount':
                var qcount = data.message.match(/~qcount ([\d\w\s]*)/)[1].trim();
                if(db.quoteArrs[qcount] != undefined) {
                    instance.say(data.channel, qcount + ' has ' + db.quoteArrs[qcount].length + ' quotes.');
                } else {
                    instance.say(data.channel, qcount + ' doesn\'t exist.');
                }
                break;
            case '~lamp':
                instance.say(data.channel, db.lampPuns.random());
                break;
            case '~reality':
                instance.say(data.channel, db.realiPuns.random());
                break;
	    case '~rq':
                var rQuote = Object.keys(db.quotes).random();
	        instance.say(data.channel, rQuote + ': ' + db.quotes[rQuote]);
                break;
        }
    }
});

instance.addListener('PRIVMSG', function(data) {
    if(data.user == 'reality') {
        var once = data.message.match(/I ([\d\w\s]* once.)/);
        if(once != null) {
            db.realiPuns.push('reality ' + once[1]);
            instance.say(data.channel, '\'reality ' + once[1] + '\' saved.');
            fs.writeFile('db.json', JSON.stringify(db, null, '    '));
        }
    }
});
<commit_msg>Split commands into a seperate structure of functions.<commit_after>var fs = require('fs');
var jsbot = require('./jsbot');

///////////////////////////

Array.prototype.random = function() {
    return this[Math.floor((Math.random()*this.length))];
};

///////////////////////////

var adminCommands = {
    'join': function(data, params) {
        instance.join(params[1]);
        instance.say(admin, 'Joined ' + params[1]);
    },

    'part': function(data, params) {
        instance.part(params[1]);
        instance.say(admin);
    },

    'reload': function(data, params) {
        instance.say(admin, 'Reloading DB.');
        try {
            db = JSON.parse(fs.readFileSync('db.json', 'utf-8'));
        } catch(err) {
            instance.say(admin, 'DB reload failed.');
        } finally {
            instance.say(admin, 'DB Reload successful.');
        }
    },

    'say': function(data, params) {
        var c = params[1];
        var m = params.slice(2).join(' ');
        instance.say(c, m);
    },

    'add': function(data, params) {
        var c = params[1];
        var m = params.slice(2).join(' ');
        db[c].push(m);
        fs.writeFile('db.json', JSON.stringify(db, null, '    '));
        instance.say(admin, 'Added.');
    }
};

var userCommands = {
    '~kc': function(data, params) {
        instance.say('aisbot', '.karma ' + data.message.split(' ')[1]);
        waitingForKarma = data.channel;
    },

    '~qset': function(data, params) {
        var qset = data.message.match(/~qset ([\d\w\s]*)=(.+)$/);
        if(qset != null && qset.length >= 3) {
            db.quotes[qset[1]] = qset[2];
            instance.say(data.channel, 'Quote saved as \'' + qset[1] + '\'');
            fs.writeFile('db.json', JSON.stringify(db, null, '    '));
        } else {
            instance.say(data.channel, 'Burn the invalid syntax!');
        }
    },

    '~q': function(data, params) {
        var q = data.message.match(/~q ([\d\w\s]*)/)[1].trim();
        instance.say(data.channel, q + ': ' + db.quotes[q]);
    },

    '~qa': function(data, params) {
        var q = data.message.match(/~qa ([\d\w\s]*)/)[1].trim();
        if(db.quoteArrs[q] != undefined) {
            instance.say(data.channel, q + ': ' + db.quoteArrs[q].random());
        }
    },

    '~qadd': function(data, params) {
        var qadd = data.message.match(/~qadd ([\d\w\s]*)=(.+)$/);
        if(qadd != null && qadd.length >= 3) {
            if(Object.isArray(db.quoteArrs[qadd[1]])) {
                db.quoteArrs[qadd[1]].push(qadd[2]);
            } else {
                db.quoteArrs[qadd[1]] = [qadd[2]];
            }
            instance.say(data.channel, 'Quote saved in \'' + qadd[1] + '\' (' + db.quoteArrs[qadd[1]].length + ')');
            fs.writeFile('db.json', JSON.stringify(db, null, '    '));
        } else {
            instance.say(data.channel, 'Burn the invalid syntax!');
        }
    },

    '~qcount': function(data, params) {
        var qcount = data.message.match(/~qcount ([\d\w\s]*)/)[1].trim();
        if(db.quoteArrs[qcount] != undefined) {
            instance.say(data.channel, qcount + ' has ' + db.quoteArrs[qcount].length + ' quotes.');
        } else {
            instance.say(data.channel, qcount + ' doesn\'t exist.');
        }
    },

    '~lamp': function(data, params) {
        instance.say(data.channel, db.quoteArrs.lamp.random());
    },

    '~reality': function(data, params) {
        instance.say(data.channel, db.realiPuns.random());
    },

    '~d': function(data, params) {
        instance.say(data.channel,  data.user + ': ' + db.quoteArrs['depressionbot'].random());
    },

    '~rq': function(data, params) {
        var rQuote = Object.keys(db.quotes).random();
        instance.say(data.channel, rQuote + ': ' + db.quotes[rQuote]);
    },

    '~kickcount': function(data, params) {
        if(db.kicks[params[1]] == undefined) {
            instance.say(data.channel, params[1] + ' has either never been kicked or does not exist.');
        } else {
            instance.say(data.channel, params[1] + ' has been kicked ' + db.kicks[params[1]] + ' times.');
        }
    }
};

///////////////////////////

var admin = 'reality';
var waitingForKarma = false;
var name = 'depressionbot';
var db = JSON.parse(fs.readFileSync('db.json', 'utf-8'));

var instance = jsbot.createJSBot(name, 'elara.ivixor.net', 6667, function() {
    instance.join('#42');
    instance.join('#itonlygetsworse');
}.bind(this));

instance.addListener('JOIN', function(data) {
    if(data.user == 'Lamp') {
        instance.say(data.channel, db.quoteArrs.lamp.random());
    } else if(data.user == 'reality') {
        instance.say(data.channel, db.realiPuns.random());
    } else if(instance.inChannel(data.channel)) {
        instance.say('aisbot', '.karma ' + data.user);
        waitingForKarma = data.channel;
    }
});

instance.addListener('KICK', function(data) {
    if(data.kickee == name) {
	instance.join(data.channel);
        instance.say(data.channel, 'Thou shalt not kick ' + name);
        db.kicks[name] += 1;
    } else {
        if(db.kicks[data.kickee] == undefined) {
            db.kicks[data.kickee] = 1;
        } else {
            db.kicks[data.kickee] += 1;
        }
        instance.say(data.channel, data.kickee + '-- (' + data.kickee + ' has been kicked ' + db.kicks[data.kickee] + ' times)');
    }
    fs.writeFile('db.json', JSON.stringify(db, null, '    '));
});

instance.addListener('PRIVMSG', function(data) {
    if(data.user == 'aisbot' && data.channel == name && waitingForKarma != false && data.message.match(/is at/)) {
        var split = data.message.split(' ');
        var target = split[0];
        var karma = split[3];

        if(karma.startsWith('-')) {
            instance.say(waitingForKarma, target + db.hatedPhrases.random() + ' (' + karma + ')');
        } else if(karma == '0') {
            instance.say(waitingForKarma, 'All ' + target + ' knows is that their gut says \'maybe.\' (0)');
        } else {
            instance.say(waitingForKarma, target + db.lovedPhrases.random() + ' (' + karma + ')');
        }

        waitingForKarma = false;
    }
});

instance.addListener('PRIVMSG', function(data) {
    params = data.message.split(' ');
    if(data.user == admin && data.channel == name && adminCommands[params[0]] != undefined) {
        adminCommands[params[0]](data, params);
    } else if(userCommands[params[0]] != undefined) {
        if(data.channel == name) data.channel = data.user;
        userCommands[params[0]](data, params);
    }
});

instance.addListener('PRIVMSG', function(data) {
    if(data.user == 'reality') {
        var once = data.message.match(/I ([\d\w\s]* once.)/);
        if(once != null) {
            db.realiPuns.push('reality ' + once[1]);
            instance.say(data.channel, '\'reality ' + once[1] + '\' saved.');
            fs.writeFile('db.json', JSON.stringify(db, null, '    '));
        }
    }
});
<|endoftext|>


<commit_before>var system = require('system');
var page = require('webpage').create(),
	server = 'http://exam.cusat.ac.in/erp5/cusat/Cusat-Hall-Ticket/form2',
	data = 'regno1='+system.args[1]+'&deg_name=B.Tech&semister=8&month=September&year=2016&reg_type=Supply/Improvement&checktype=check';

page.open(server, 'POST', data, function(status) {
	console.log("Status: " + status);
	if(status === "success") {
	}
	page.render('results/'+system.args[1]+'.pdf');
	phantom.exit();
});<commit_msg>Server<commit_after>var system = require('system');
var page = require('webpage').create(),
	server = 'http://exam.cusat.ac.in/erp5/cusat/Cusat-Hall-Ticket/form2',
	data =		'regno1='		+ system.args[1] +
				'&deg_name='	+ system.args[2] +
				'&semister='	+ system.args[3] +
				'&month='		+ system.args[4] +
				'&year='		+ system.args[5] +
				'&reg_type='	+ system.args[6] +
				'&checktype='	+ system.args[7],
	folder = system.args[3] + system.args[6] + system.args[4] + system.args[5];
page.open(server, 'POST', data, function(status) {
	console.log("Status: " + status);
	if(status === "success") {
	}
	page.render('results/'+ folder +'/'+system.args[1]+'.pdf');
	phantom.exit();
});<|endoftext|>


<commit_before>'use strict'

const Character = require('./character')
const debug = require('debug')('woot')
const invariant = require('invariant')

function Seq (data = [Character.begin, Character.end], index = null) {
  if (!(this instanceof Seq)) return new Seq(data, index)
  this.storage = data

  if (!this.index) {
    this.index = {}
    for (let i = 0; i < data.length; i++) {
      const ch = data[i]
      this.index[Character.getIndexKeyById(ch.id)] = i
    }
  }
}

// Return the length of the sequence.
Seq.prototype.length = function () {
  return this.storage.length
}

// Return true if the sequence has no content
Seq.prototype.isEmpty = function () {
  return this.storage.length === 2
}

// Returns the element at the position p in sequence.
Seq.prototype.at = function (position) {
  return this.storage[position]
}

// Returns the position of the element c in sequence as a natural number.
// Returns -1 if position is not found.
Seq.prototype.position = function (c) {
  for (let i = 0; i < this.storage.length; i++) {
    const el = this.storage[i]
    if (el.id[0] == c.id[0] && el.id[1] == c.id[1]) {
      return i
    }
  }
  return -1
}

// Inserts the element c in sequence at position p.
Seq.prototype.insert = function (c, position) {
  for (let i = this.storage.length-1; i >= position; i--) {
    this.storage[i+1] = this.storage[i]
    this.index[Character.getIndexKeyById(this.storage[i].id)] = i+1
  }
  if (position > 0) {
    this.storage[position-1].n = c.id
  }
  this.storage[position] = c
  if (position < this.storage.length + 1) {
    this.storage[position+1].p = c.id
  }
  this.index[Character.getIndexKeyById(c.id)] = position
}

// Returns the part of the sequence between the elements c and d, both not included.
Seq.prototype.subsequence = function (c, d) {
  const sub = []
  const start = this.position(c)
  const end = this.position(d)
  invariant(start < end, "position of c must be before d")

  if (start+1 <= end-1 && start > -1 && end > -1) {
    for (let i = start+1; i <= end - 1; i++) {
      sub.push(this.storage[i])
    }
  }
  return new Seq(sub)
}

// Returns true if character with id can be found in sequence
Seq.prototype.contains = function (id) {
  for (let el of this.storage) {
    if (el.id[0] == id[0] && el.id[1] == id[1]) {
      return true
    }
  }
  return false
}

// Return the visible representation of sequence.
Seq.prototype.value = function () {
  let value = ""
  for (let el of this.storage) {
    if (el.v) {
      value += el.c
    }
  }
  return value
}

Seq.prototype.toString = Seq.prototype.value

// Return the ith visible character of sequence.
Seq.prototype.visibleCharAt = function (index) {
  let counter = 0
  for (let el of this.storage) {
    if (el.v) {
      if (counter === index) {
        return el
      }
      counter++
    }
  }
  return null
}

// Return the chatacter internally by id
// use the index to quickly get the character
Seq.prototype.getCharacterById = function (id) {
  return this.storage[this.index[Character.getIndexKeyById(id)]]
}

module.exports = Seq<commit_msg>refacotr<commit_after>'use strict'

const Character = require('./character')
const debug = require('debug')('woot')
const invariant = require('invariant')

function Seq (data = [Character.begin, Character.end], index = null) {
  if (!(this instanceof Seq)) return new Seq(data, index)
  this.storage = data

  if (!this.index) {
    this.index = {}
    for (let i = 0; i < data.length; i++) {
      const ch = data[i]
      this.index[Character.getIndexKeyById(ch.id)] = i
    }
  }
}

// Return the length of the sequence.
Seq.prototype.length = function () {
  return this.storage.length
}

// Return true if the sequence has no content
Seq.prototype.isEmpty = function () {
  return this.storage.length === 2
}

// Returns the element at the position p in sequence.
Seq.prototype.at = function (position) {
  return this.storage[position]
}

// Returns the position of the element c in sequence as a natural number.
// Returns -1 if position is not found.
Seq.prototype.position = function (c) {
  for (let i = 0; i < this.storage.length; i++) {
    const el = this.storage[i]
    if (el.id[0] == c.id[0] && el.id[1] == c.id[1]) {
      return i
    }
  }
  return -1
}

// Inserts the element c in sequence at position p.
Seq.prototype.insert = function (c, position) {
  for (let i = this.storage.length-1; i >= position; i--) {
    this.storage[i+1] = this.storage[i]
    this.index[Character.getIndexKeyById(this.storage[i].id)] = i+1
  }
  if (position > 0) {
    this.storage[position-1].n = c.id
  }
  this.storage[position] = c
  if (position < this.storage.length + 1) {
    this.storage[position+1].p = c.id
  }
  this.index[Character.getIndexKeyById(c.id)] = position
}

// Returns the part of the sequence between the elements c and d, both not included.
Seq.prototype.subsequence = function (c, d) {
  const sub = []
  const start = this.position(c)
  const end = this.position(d)
  invariant(start < end, "position of c must be before d")

  if (start+1 <= end-1 && start > -1 && end > -1) {
    for (let i = start+1; i < end; i++) {
      sub.push(this.storage[i])
    }
  }
  return new Seq(sub)
}

// Returns true if character with id can be found in sequence
Seq.prototype.contains = function (id) {
  for (let el of this.storage) {
    if (el.id[0] == id[0] && el.id[1] == id[1]) {
      return true
    }
  }
  return false
}

// Return the visible representation of sequence.
Seq.prototype.value = function () {
  let value = ""
  for (let el of this.storage) {
    if (el.v) {
      value += el.c
    }
  }
  return value
}

Seq.prototype.toString = Seq.prototype.value

// Return the ith visible character of sequence.
Seq.prototype.visibleCharAt = function (index) {
  let counter = 0
  for (let el of this.storage) {
    if (el.v) {
      if (counter === index) {
        return el
      }
      counter++
    }
  }
  return null
}

// Return the chatacter internally by id
// use the index to quickly get the character
Seq.prototype.getCharacterById = function (id) {
  return this.storage[this.index[Character.getIndexKeyById(id)]]
}

module.exports = Seq<|endoftext|>


<commit_before>var Set = function(input){
  var set
    , value = null

  this.contains = function(prop){
    return !!set[prop]
  }

  this.empty = function(){
    return Object.keys(set).length == 0
  }

  this.size = function(){
    throw new Error('not implemented')
  }

  this.get = function(){
    return Object.keys(set)
  }

  this.create = function(){
    throw new Error('not implemented')
  }

  this.add = function(prop){
    set[prop] = value
  }

  this.remove = function(prop){
    throw new Error('not implemented')
  }

  this.union = function(iset){
    throw new Error('not implemented')
  }

  this.intersect = function(iset){
    throw new Error('not implemented')
  }

  this.difference = function(iset){
    throw new Error('not implemented')
  }

  this.subset = function(iset){
    throw new Error('not implemented')
  }

  this.pop = function(){
    throw new Error('not implemented')
  }

  this.find = function(pred){
    throw new Error('not implemented')
  }

  this.clear = function(){
    throw new Error('not implemented')
  }

  this.unique = function(iset){
    var set = {}
      , i = 0
      , l = input.length

    for(; i < l; i++) {
      set[iset[i]] = value
    }

    return set
  }

  set = this.unique(input) || {}
}

module.exports = Set;
<commit_msg>added size function<commit_after>var Set = function(input){
  var set
    , value = null

  this.contains = function(prop){
    return !!set[prop]
  }

  this.empty = function(){
    return Object.keys(set).length == 0
  }

  this.size = function(){
    return Object.keys(set).length
  }

  this.get = function(){
    return Object.keys(set)
  }

  this.create = function(){
    throw new Error('not implemented')
  }

  this.add = function(prop){
    set[prop] = value
  }

  this.remove = function(prop){
    throw new Error('not implemented')
  }

  this.union = function(iset){
    throw new Error('not implemented')
  }

  this.intersect = function(iset){
    throw new Error('not implemented')
  }

  this.difference = function(iset){
    throw new Error('not implemented')
  }

  this.subset = function(iset){
    throw new Error('not implemented')
  }

  this.pop = function(){
    throw new Error('not implemented')
  }

  this.find = function(pred){
    throw new Error('not implemented')
  }

  this.clear = function(){
    throw new Error('not implemented')
  }

  this.unique = function(iset){
    var set = {}
      , i = 0
      , l = input.length

    for(; i < l; i++) {
      set[iset[i]] = value
    }

    return set
  }

  set = this.unique(input) || {}
}

module.exports = Set;
<|endoftext|>


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

var _tools = (function () {

//  P U B L I C   I N T E R F A C E
    var that = {};

    // TODO refactor this !!!!
    that.sort = function ( data, sett ) {
        var id = "idef";
        // TODO what is it for?!
        var new_table_data_object = {};
        _algorithms.prepare_sorting_setting( sett, id );
        _algorithms.sort( data, sett );
    };

    that.prepare_tools = function () {
        prepare_sorting_interface();
        prepare_filtering_interface();
//	prepare_manage_columns_interface();
        prepare_snapshot_interface();
    };

    that.get_full_parents = function ( id ) {
        var par_ids = [];

    };

    return that;

//  P R I V A T E   I N T E R F A C E

    function add_sort_key() {
        var i, key;
        var html = [];
        var schema = _store.basic_schema();
        var columns = schema
                        .filter( function ( e ) {
                            return e['processable'];
                        })
                        .map( function ( e ) {
                            return {
                                name: e['key'],
                                label: e['label']
                            };
                        });

        key = $('#sort-form > div').length;

        if( key === 2 ) {
            $('#add-sort-key' ).remove();
        }

        html.push( '
' );
        // columns select list
        html.push( '<select name="columns" class="key-', key, '">' );
        html.push( '<option value="null" class="key-', key, '" selected>' );
        html.push( 'Wybierz kolumnę</option>' );

        // TODO don't include already selected colmuns
        for( i = 0; i < columns.length; ++i ) {
            html.push( '<option value="', columns[i]['name'], '" class="key-', key, '">' );
            html.push( columns[i]['label'], '</option>' );
        }

        html.push( '</select>' );
        // ascending/descending radio buttons
        html.push( 'Rosnąco <input class="radio key-', key, '" type="radio" ' );
        html.push( 'name="key-', key, '-order" value="-1" checked />' );
        html.push( 'Malejąco <input class="radio key-', key, '" type="radio" ' );
        html.push( 'name="key-', key, '-order" value="1" />' );

        if( key === 0 ) {
            html.push( '
+
' );
            html.push( '<input type="submit" value="Sortuj" />' );
        }
        html.push( '
' );

        $('#sort-form').append( $( html.join('') ));

        if( key === 0 ) {
            $('#add-sort-key').click( function () {
                add_sort_key();
            });
        }
    }

    function add_manage_checkbox()  {
	//add checkboxes to manage columns popup
    }

    function add_filter_key() {
        var i, key;
        var html = [];
        var filter_part;
        var selected_column;
        var type;
        var schema = _store.basic_schema();
        var columns = schema
                        .filter( function ( e ) {
                            return e['processable'];
                        })
                        .map( function ( e ) {
                            return {
                                name: e['key'],
                                label: e['label']
                            };
                        });

        key = $('#filter-form > div').length;

        columns.unshift({
            name: 'null',
            label: 'Wybierz kolumnę'
        });

        html.push( '
' );

        html.push( '<select id="filter-', key, '-columns"' );
        html.push( ' name="columns">');
        for ( i = 0; i < columns.length; i += 1 ) {
            html.push( '<option value="', columns[i]['name']);
            html.push( '" class="filter-', key, '" >');
            html.push( columns[i]['label'], '</option>' );
        }
        html.push( '</select>' );

        html.push( '<select id="filter-', key, '-operations"' );
        html.push( ' name="null-operation" disabled="true">' );
        // not needed because column has not been selected yet

        html.push( '</select>' );

        if ( key === 0 ) {
            html.push( '
+
' );
            html.push( '<input type="submit" value="Filtruj" />' );
        }

        html.push( '
' );
        $('#filter-form').append( $( html.join('') ) );

        if( key === 0 ) {
            //TODO create CSS class for add-filter-key !!!!!!!!!!!
            $('#add-filter-key').click( function () {
                add_filter_key();
            });
        }

        filter_part = $('#filter-' + key + '-columns');
        filter_part.change( function() {
            selected_column = $(this).val();

            $('#filter-' + key + '-query').remove();

            for ( i = 0; i < schema.length; i += 1 ) {
                if ( schema[i]['key'] === selected_column ) {
                    type = schema[i]['type'];

                    $('#filter-' + key + '-operations').remove();

                    html = [ '<select id="filter-', key, '-operations"' ];
                    if ( schema[i]['type'] === 'number' ) {
                        html.push( ' name="number-operation">' );
                        html.push( '<option value="null" class="filter-', key, '" selected>Wybierz operację</option>' );
                        html.push( '<option value="gt" class="filter-', key, '">></option>' );
                        html.push( '<option value="eq" class="filter-', key, '">=</option>' );
                        html.push( '<option value="lt" class="filter-', key, '"><</option>' );
                    } else {
                        html.push( ' name="string-operation">' );
                        html.push( '<option value="null" class="filter-', key, '" selected>Wybierz operację</option>' );
                        html.push( '<option value="cnt" class="filter-', key, '">Zawiera</option>' );
                        html.push( '<option value="st" class="filter-', key, '">Zaczyna się od</option>' );
                        html.push( '<option value="ncnt" class="filter-', key, '">Nie zawiera</option>' );
                        html.push( '<option value="nst" class="filter-', key, '">Nie zaczyna się od</option>' );
                    }
                    html.push( '</select>' );

                    html.push( '<input type="text" name="query" id="filter-', key, '-query" />' );

                    $( html.join('') ).insertAfter( $('#filter-' + key + '-columns') );

                    break;
                }
            }
        });
    }

    function prepare_sorting_interface() {

        $('#sort-button')
            .click( function () {
                $('#filter-form').hide();
                $('#manage-columns-form').hide();
                $('#sort-form').html('').toggle();
                add_sort_key();
            });

        $('#sort-form')
            .submit( function () {

//                _utils.create_preloader('Sortowanie');

                var column, order;
                var settings = [];
                var i, len = $('#sort-form select').length;

                for( i = 0; i < len; i += 1 ) {
                    column = $( '.key-'+ i +' option:selected' ).val();
                    // TODO what does this condition mean?!
                    if( column === "null" ) {
                        if( i === 1 ) {
                            $(this).hide();
                            return false;
                        }
                        else {
                            break;
                        }
                    }
                    order = parseInt( $('.key-'+ i +':radio:checked').val() );

                    settings.push(
                        {
                            "pref": order,
                            "name": column
                        }
                    );
                }

                that.sort( _store.active_rows(), settings );

                _table.clean_table();
                _table.init_table();
                $(this).hide();

                // TODO why false?!
                return false;
            });

        var i;
        for( i = 1; i <= $('#sort-form select').length; ++i ) {
            if( i > 1 ) {
                $('#key-'+i).hide();
            }

            (function (i) {
                $('#sort-form select.key-'+i).change( function () {
                    if( $('.key-'+i+' option:selected').val() !== "null" ) {
                        $('#key-'+(i+1)).show();
                    }
                });
            })(i);
        }
    };

    function prepare_filtering_interface() {

        $('#filter-button')
            .click( function () {
                $('#filter-form').html('').toggle();
                $('#manage-columns-form').hide();
                $('#sort-form').hide();
                add_filter_key();
            });

        $('#filter-form')
            .submit( function () {

                var column, operation, query;
                var mask = [];
                var i, len = $('#filter-form select').length / 2;
                var tmp, type;
                var new_sheet;
                for( i = 0; i < len; ++i ) {
                    column = $('#filter-'+i+'-columns option:selected').val();
                    if( column === "null" ) {
                        if( i === 1 ) {
                            $(this).hide();
                            return false;
                        }
                        else {
                            break;
                        }
                    }

                    type = _store.active_columns().filter( function ( e ) {
                        return e['key'] === column;
                    })[0]['type'];

                    operation = $('#filter-'+i+'-operations option:selected').val();;
                    query = $('#filter-'+i+'-query').val();

                    tmp = parseInt( query, 10 );
                    // if the column if numeric - check if the query is so
                    if( type === 'number' ) {
                        // crazy way to check if tmp is a number!
                        if( !!tmp === true || tmp === 0 ) {
                            query = tmp;
                        }
                        else {
                            // characters for numeric column -- do nothing & quit
                            $(this).hide();
                            return false;
                        }
                    }

                    mask.push(
                        {
                           name: column,
                           pref: operation,
                           value: query
                        }
                    );
                }

                new_sheet = {};
                $.extend( true, new_sheet, _store.active_sheet() );
                new_sheet['rows'] = _algorithms.filter( new_sheet['rows'], mask );
                //new_sheet['filtered'] = true;

                _sheet.create_new_sheet( new_sheet, "Arkusz", true );

                _table.clean_table();
                _table.init_table( true );

                $(this).hide();

                return false;
           });
    };

    function 	prepare_manage_columns_interface(){

        $('#manage-columns-form')
            .click( function () {
                $('#filter-form').hide();
                $('#sort-button').hide();
                $('#sort-form').html('').toggle();
                add_manage_checkbox();
            });

        $('#manage-columns-form')
            .submit( function () {
		// changes in _Store

        });
    };

    function prepare_snapshot_interface() {

        $('#save-snapshot')
            .click( function () {
                _sheet.create_new_sheet( _store.active_sheet(), "Arkusz" );
            });
    }

}) ();

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

var _tools = (function () {

//  P U B L I C   I N T E R F A C E
    var that = {};

    // TODO refactor this !!!!
    that.sort = function ( data, sett ) {
        var id = "idef";
        // TODO what is it for?!
        var new_table_data_object = {};
        _algorithms.prepare_sorting_setting( sett, id );
        _algorithms.sort( data, sett );
    };

    that.prepare_tools = function () {
        prepare_sorting_interface();
        prepare_filtering_interface();
//	prepare_manage_columns_interface();
        prepare_snapshot_interface();
    };

    that.get_full_parents = function ( id ) {
        var par_ids = [];

    };

    return that;

//  P R I V A T E   I N T E R F A C E

    function add_sort_key() {
        var i, key;
        var html = [];
        var schema = _store.basic_schema();
        var columns = schema
                        .filter( function ( e ) {
                            return e['processable'];
                        })
                        .map( function ( e ) {
                            return {
                                name: e['key'],
                                label: e['label']
                            };
                        });

        key = $('#sort-form > div').length;

        if( key === 2 ) {
            $('#add-sort-key' ).remove();
        }

        html.push( '
' );
        // columns select list
        html.push( '<select name="columns" class="key-', key, '">' );
        html.push( '<option value="null" class="key-', key, '" selected>' );
        html.push( 'Wybierz kolumnę</option>' );

        // TODO don't include already selected colmuns
        for( i = 0; i < columns.length; ++i ) {
            html.push( '<option value="', columns[i]['name'], '" class="key-', key, '">' );
            html.push( columns[i]['label'], '</option>' );
        }

        html.push( '</select>' );
        // ascending/descending radio buttons
        html.push( 'Rosnąco <input class="radio key-', key, '" type="radio" ' );
        html.push( 'name="key-', key, '-order" value="-1" checked />' );
        html.push( 'Malejąco <input class="radio key-', key, '" type="radio" ' );
        html.push( 'name="key-', key, '-order" value="1" />' );

        if( key === 0 ) {
            html.push( '
+
' );
            html.push( '<input type="submit" value="Sortuj" />' );
        }
        html.push( '
' );

        $('#sort-form').append( $( html.join('') ));

        if( key === 0 ) {
            $('#add-sort-key').click( function () {
                add_sort_key();
            });
        }
    }

    function add_manage_checkbox()  {
	//add checkboxes to manage columns popup
    }

    function add_filter_key() {
        var i, key;
        var html = [];
        var filter_part;
        var selected_column;
        var type;
        var schema = _store.basic_schema();
        var columns = schema
                        .filter( function ( e ) {
                            return e['processable'];
                        })
                        .map( function ( e ) {
                            return {
                                name: e['key'],
                                label: e['label']
                            };
                        });

        key = $('#filter-form > div').length;

        columns.unshift({
            name: 'null',
            label: 'Wybierz kolumnę'
        });

        html.push( '
' );

        html.push( '<select id="filter-', key, '-columns"' );
        html.push( ' name="columns">');
        for ( i = 0; i < columns.length; i += 1 ) {
            html.push( '<option value="', columns[i]['name']);
            html.push( '" class="filter-', key, '" >');
            html.push( columns[i]['label'], '</option>' );
        }
        html.push( '</select>' );

        html.push( '<select id="filter-', key, '-operations"' );
        html.push( ' name="null-operation" disabled="true">' );
        // not needed because column has not been selected yet

        html.push( '</select>' );

        if ( key === 0 ) {
            html.push( '
+
' );
            html.push( '<input type="submit" value="Filtruj" />' );
        }

        html.push( '
' );
        $('#filter-form').append( $( html.join('') ) );

        if( key === 0 ) {
            //TODO create CSS class for add-filter-key !!!!!!!!!!!
            $('#add-filter-key').click( function () {
                add_filter_key();
            });
        }

        filter_part = $('#filter-' + key + '-columns');
        filter_part.change( function() {
            selected_column = $(this).val();

            $('#filter-' + key + '-query').remove();

            for ( i = 0; i < schema.length; i += 1 ) {
                if ( schema[i]['key'] === selected_column ) {
                    type = schema[i]['type'];

                    $('#filter-' + key + '-operations').remove();

                    html = [ '<select id="filter-', key, '-operations"' ];
                    if ( schema[i]['type'] === 'number' ) {
                        html.push( ' name="number-operation">' );
                        html.push( '<option value="null" class="filter-', key, '" selected>Wybierz operację</option>' );
                        html.push( '<option value="gt" class="filter-', key, '">></option>' );
                        html.push( '<option value="eq" class="filter-', key, '">=</option>' );
                        html.push( '<option value="lt" class="filter-', key, '"><</option>' );
                    } else {
                        html.push( ' name="string-operation">' );
                        html.push( '<option value="null" class="filter-', key, '" selected>Wybierz operację</option>' );
                        html.push( '<option value="cnt" class="filter-', key, '">Zawiera</option>' );
                        html.push( '<option value="st" class="filter-', key, '">Zaczyna się od</option>' );
                        html.push( '<option value="ncnt" class="filter-', key, '">Nie zawiera</option>' );
                        html.push( '<option value="nst" class="filter-', key, '">Nie zaczyna się od</option>' );
                    }
                    html.push( '</select>' );

                    html.push( '<input type="text" name="query" id="filter-', key, '-query" />' );

                    $( html.join('') ).insertAfter( $('#filter-' + key + '-columns') );

                    break;
                }
            }
        });
    }

    function prepare_sorting_interface() {

        $('#sort-button')
            .click( function () {
                $('#filter-form').hide();
                $('#manage-columns-form').hide();
                $('#sort-form').html('').toggle();
                add_sort_key();
            });

        $('#sort-form')
            .submit( function () {

//                _utils.create_preloader('Sortowanie');

                var column, order;
                var settings = [];
                var i, len = $('#sort-form select').length;

                for( i = 0; i < len; i += 1 ) {
                    column = $( '.key-'+ i +' option:selected' ).val();
                    // TODO what does this condition mean?!
                    if( column === "null" ) {
                        if( i === 1 ) {
                            $(this).hide();
                            return false;
                        }
                        else {
                            break;
                        }
                    }
                    order = parseInt( $('.key-'+ i +':radio:checked').val() );

                    settings.push(
                        {
                            "pref": order,
                            "name": column
                        }
                    );
                }

                that.sort( _store.active_rows(), settings );

                _table.clean_table();
                _table.init_table();
                $(this).hide();

                // TODO why false?!
                return false;
            });

        var i;
        for( i = 1; i <= $('#sort-form select').length; ++i ) {
            if( i > 1 ) {
                $('#key-'+i).hide();
            }

            (function (i) {
                $('#sort-form select.key-'+i).change( function () {
                    if( $('.key-'+i+' option:selected').val() !== "null" ) {
                        $('#key-'+(i+1)).show();
                    }
                });
            })(i);
        }
    };

    function prepare_filtering_interface() {

        $('#filter-button')
            .click( function () {
                $('#filter-form').html('').toggle();
                $('#manage-columns-form').hide();
                $('#sort-form').hide();
                add_filter_key();
            });

        $('#filter-form')
            .submit( function () {

                var column, operation, query;
                var mask = [];
                var i, len = $('#filter-form select').length / 2;
                var tmp, type;
                var new_sheet;
                for( i = 0; i < len; ++i ) {
                    column = $('#filter-'+i+'-columns option:selected').val();
                    if( column === "null" ) {
                        if( i === 1 ) {
                            $(this).hide();
                            return false;
                        }
                        else {
                            break;
                        }
                    }

                    type = _store.active_columns().filter( function ( e ) {
                        return e['key'] === column;
                    })[0]['type'];

                    operation = $('#filter-'+i+'-operations option:selected').val();;
                    query = $('#filter-'+i+'-query').val();

                    tmp = parseInt( query, 10 );
                    // if the column if numeric - check if the query is so
                    if( type === 'number' ) {
                        // crazy way to check if tmp is a number!
                        if( !!tmp === true || tmp === 0 ) {
                            query = tmp;
                        }
                        else {
                            // characters for numeric column -- do nothing & quit
                            $(this).hide();
                            return false;
                        }
                    }

                    mask.push(
                        {
                           name: column,
                           pref: operation,
                           value: query
                        }
                    );
                }

                new_sheet = {};
                $.extend( true, new_sheet, _store.active_sheet() );
                new_sheet['rows'] = _algorithms.filter( new_sheet['rows'], mask );
                //new_sheet['filtered'] = true;

                _sheet.create_new_sheet( new_sheet, "Arkusz", true );

                _table.clean_table();
                _table.init_table( true );

                $(this).hide();

                return false;
           });
    };

    function 	prepare_manage_columns_interface(){

        $('#manage-columns-form')
            .click( function () {
                $('#filter-form').hide();
                $('#sort-button').hide();
                $('#sort-form').html('').toggle();
                add_manage_checkbox();
            });

        $('#manage-columns-form')
            .submit( function () {
		// changes in _Store

        });
    };

    function prepare_snapshot_interface() {

        $('#save-snapshot')
            .click( function () {
                _sheet.create_new_sheet( _store.active_sheet(), "Arkusz" );
            });
    }

    function remove_hidden( filtered_list ) {
        return filtered_list.filter( function ( e ) {
                   var idx = e['data']['idef'];
                   return ! $('#'+id).is(':hidden');
        });
    }

    that.create_filter_result = function( visual_list ) {
        var filter_result = [];
        var visual_rows_object = get_filtered_data( visual_list );
        var visual_list = remove_hidden( filtered_list );
        var i;

        for ( i = 0; i < visual_list.length; i += 1 ) {
            id = visual_list[i]['data']['idef'];
            filter_result.push({
                breadcrumb: create_breadcrumb( id ),
                info: visual_rows_object[ id ]
            });
        }
    }

    function get_filtered_data( visual_list ) {
        visual_data_object = {};

        var i;
        var id;
        for ( i = 0; i < visual_list.length; i += 1 ) {
            id = visual_list[i]['data']['idef'];
            visual_data_object[ id ] = visual_list[i];
        }

        return visual_data_object;
    }

    function create_breadcrumb( id ) {
        var tmp_id = id;
        var node;
        var type;
        var full_type;
        var name;

        tmp_id = id;
        var breadcrumb_reversed = [];

        do {
            node = $('tr[id='+ tmp_id +']');
            full_type = node.children('.type').html();
            type = get_type_representation( full_type );
            name = node.children('.name').html();

            tmp_id = get_parent_id( tmp_id );
            breadcrumb_reversed.push({
                type: type,
                name: name
            });
        }
        while ( !!tmp_id );

        return breadcrumb_reversed.reverse();
    }

    function get_type_representation( full_type ) {
        var type;
        var type_list;
        type_list = full_type.split(' ');
        type = type_list.pop();
        return type;
    }

    function get_parent_id( id ) {
        var parent_id;
        var last_index = id.lastIndexOf('-');

        if ( last_index === -1 ) {
            parent_id = '';
        } else {
            parent_id = id.slice( 0, last_index );
        }

        return parent_id;
    }

}) ();

<|endoftext|>


<commit_before>import React from 'react';
import { Machine } from '../../';
import connect from '../connect';
import { mount } from 'enzyme';

var wrapper;
const mapping = sinon.spy();

function getWrapper(once, m) {
  class Component extends React.Component {
    render() {
      return (

{ this.props.message('machine A', this.props.stateA)}

{ this.props.message('machine B', this.props.stateB)}

          <button id='run' onClick={ () => this.props.run() }>run</button>
          <button id='fetch' onClick={ () => this.props.fetch() }>fetch</button>

      );
    }
  }

  const mappingFunc = (A, B) => {
    mapping(A, B);
    return {
      stateA: A.state.name,
      stateB: B.state.name,
      run: A.run,
      fetch: B.fetch
    }
  };
  const ConnectedComponent = connect(Component)
    .with('A', 'B')
    [once ? 'mapOnce' : 'map'](typeof m === 'undefined' ? mappingFunc : m);
  const message = (machineName, state) => `${ machineName } is in a ${ state } state`;

  return mount(<ConnectedComponent message={ message } />);
}

describe('Given the connect React helper', function () {
  beforeEach(() => {
    mapping.reset();
    Machine.flush();
    Machine.create('A', {
      state: { name: 'idle' },
      transitions: {
        idle: { run: 'running' },
        running: { stop: 'idle' }
      }
    });
    Machine.create('B', {
      state: { name: 'waiting' },
      transitions: {
        waiting: { fetch: 'fetching' },
        fetching: { done: 'waiting' }
      }
    });
  });
  describe('when connecting a component', function () {
    it('should call our mapping function', function () {
      wrapper = getWrapper();
      expect(mapping).to.be.calledOnce;
    });
    it('should map machines state and actions properly', function () {
      wrapper = getWrapper();
      expect(wrapper.find('p#A').text()).to.equal('machine A is in a idle state');
      expect(wrapper.find('p#B').text()).to.equal('machine B is in a waiting state');
    });
    it('should get re-rendered if a machine\'s state is changed', function () {
      wrapper = getWrapper();
      const runButton = wrapper.find('button#run');
      const fetchButton = wrapper.find('button#fetch');

      expect(wrapper.find('p#A').text()).to.equal('machine A is in a idle state');
      runButton.simulate('click');
      expect(wrapper.find('p#A').text()).to.equal('machine A is in a running state');
      runButton.simulate('click');
      runButton.simulate('click');
      runButton.simulate('click');

      fetchButton.simulate('click');
      expect(wrapper.find('p#B').text()).to.equal('machine B is in a fetching state');
    });
    it('should NOT get re-rendered if mapped with `mapOnce`', function () {
      wrapper = getWrapper(true);
      wrapper.find('button#run').simulate('click');
      wrapper.find('button#fetch').simulate('click');
      expect(wrapper.find('p#A').text()).to.equal('machine A is in a idle state');
      expect(wrapper.find('p#B').text()).to.equal('machine B is in a waiting state');
    });
  });
  describe('when unmounting the component', function () {
    it('should detach from the machines', function () {
      wrapper = getWrapper();
      Machine.get('A').run();
      expect(wrapper.find('p#A').text()).to.equal('machine A is in a running state');
      Machine.get('A').stop();
      expect(wrapper.find('p#A').text()).to.equal('machine A is in a idle state');
      wrapper.unmount();
      Machine.get('A').run();
      expect(mapping.callCount).to.be.equal(3);
    });
  });
  describe('when we connect without mapping', function () {
    it('should detach from the machines', function () {
      class Component extends React.Component {
        constructor(props) {
          super(props);

          this.counter = 0;
        }
        render() {
          this.counter += 1;
          return
Rendered { this.counter } times
;
        }
      }
      const Connected = connect(Component).with('A', 'B').map();
      const connectedWrapper = mount(<Connected />);
      Machine.get('A').run();
      Machine.get('A').stop();
      // 1 - initial render
      // 2 - default mapping call
      // 3 - because of machine's action run
      // 4 - because of machine's action stop
      expect(connectedWrapper.find('p').text()).to.equal('Rendered 4 times');
    });
  });
  describe('when we use mapSilent', function () {
    it('should only call the mapping function when the machine changes its state', function () {
      class Component extends React.Component {
        constructor(props) {
          super(props);

          this.counter = 0;
        }
        render() {
          this.counter += 1;
          return (

{ this.props.message('machine A', this.props.stateA)}

Rendered { this.counter } times

          );
        }
      }
      const message = (machineName, state) => `${ machineName } is in a ${ state } state`;
      const Connected = connect(Component).with('A', 'B').mapSilent(A => {
        return {
          stateA: A.state.name
        }
      });
      const connectedWrapper = mount(<Connected message={ message }/>);
      expect(connectedWrapper.find('p#A').text()).to.equal('machine A is in a undefined state');
      Machine.get('A').run();
      expect(connectedWrapper.find('p#A').text()).to.equal('machine A is in a running state');
      // 1 - initial render
      // 2 - because of machine's action run
      expect(connectedWrapper.find('p#counter').text()).to.equal('Rendered 2 times');
    });
  });
  describe('and we have a middleware attached', function () {
    it('should call the proper hooks', function () {
      const onMachineConnected = sinon.spy();
      const onMachineDisconnected = sinon.spy();

      Machine.addMiddleware({ onMachineConnected, onMachineDisconnected });

      const machine = Machine.create('foo', { state: {}, transitions: {} });
      const Zoo = () =>
Hello world
;
      const Connected = connect(Zoo).with('foo').map(() => ({}));
      const connectedWrapper = mount(<Connected />);

      expect(onMachineConnected).to.be.calledOnce.and.to.be.calledWith(
        sinon.match.array,
        sinon.match({ component: 'Zoo' })
      );
      expect(onMachineDisconnected).to.not.be.called;
      connectedWrapper.unmount();
      expect(onMachineDisconnected).to.be.calledOnce.and.to.be.calledWith(
        sinon.match.array,
        sinon.match({ component: 'Zoo' })
      );
    });
    describe('and we destroy a machine', function () {
      it('should call the proper hooks', function () {
        const onMachineConnected = sinon.spy();
        const onMachineDisconnected = sinon.spy();

        Machine.addMiddleware({ onMachineConnected, onMachineDisconnected });

        const machine = Machine.create('foo', { state: {}, transitions: {} });
        const Component = () =>
Hello world
;
        const Connected = connect(Component).with('foo').map(() => ({}));
        const connectedWrapper = mount(<Connected />);

        expect(onMachineConnected).to.be.calledOnce;
        expect(onMachineDisconnected).to.not.be.called;
        machine.destroy();
        expect(onMachineDisconnected).to.be.calledOnce;
      });
    });
  });
});<commit_msg>Adding a test<commit_after>import React from 'react';
import { Machine } from '../../';
import connect from '../connect';
import { mount } from 'enzyme';

var wrapper;
const mapping = sinon.spy();

class Component extends React.Component {
  render() {
    return (

{ this.props.message('machine A', this.props.stateA)}

{ this.props.message('machine B', this.props.stateB)}

        <button id='run' onClick={ () => this.props.run() }>run</button>
        <button id='fetch' onClick={ () => this.props.fetch() }>fetch</button>

    );
  }
}

function getWrapper(once, m) {
  const mappingFunc = (A, B) => {
    mapping(A, B);
    return {
      stateA: A.state.name,
      stateB: B.state.name,
      run: A.run,
      fetch: B.fetch
    }
  };
  const ConnectedComponent = connect(Component)
    .with('A', 'B')
    [once ? 'mapOnce' : 'map'](typeof m === 'undefined' ? mappingFunc : m);
  const message = (machineName, state) => `${ machineName } is in a ${ state } state`;

  return mount(<ConnectedComponent message={ message } />);
}

describe('Given the connect React helper', function () {
  beforeEach(() => {
    mapping.reset();
    Machine.flush();
    Machine.create('A', {
      state: { name: 'idle' },
      transitions: {
        idle: { run: 'running' },
        running: { stop: 'idle' }
      }
    });
    Machine.create('B', {
      state: { name: 'waiting' },
      transitions: {
        waiting: { fetch: 'fetching' },
        fetching: { done: 'waiting' }
      }
    });
  });
  describe('when connecting a component', function () {
    it('should call our mapping function', function () {
      wrapper = getWrapper();
      expect(mapping).to.be.calledOnce;
    });
    it('should map machines state and actions properly', function () {
      wrapper = getWrapper();
      expect(wrapper.find('p#A').text()).to.equal('machine A is in a idle state');
      expect(wrapper.find('p#B').text()).to.equal('machine B is in a waiting state');
    });
    it('should get re-rendered if a machine\'s state is changed', function () {
      wrapper = getWrapper();
      const runButton = wrapper.find('button#run');
      const fetchButton = wrapper.find('button#fetch');

      expect(wrapper.find('p#A').text()).to.equal('machine A is in a idle state');
      runButton.simulate('click');
      expect(wrapper.find('p#A').text()).to.equal('machine A is in a running state');
      runButton.simulate('click');
      runButton.simulate('click');
      runButton.simulate('click');

      fetchButton.simulate('click');
      expect(wrapper.find('p#B').text()).to.equal('machine B is in a fetching state');
    });
    it('should NOT get re-rendered if mapped with `mapOnce`', function () {
      wrapper = getWrapper(true);
      wrapper.find('button#run').simulate('click');
      wrapper.find('button#fetch').simulate('click');
      expect(wrapper.find('p#A').text()).to.equal('machine A is in a idle state');
      expect(wrapper.find('p#B').text()).to.equal('machine B is in a waiting state');
    });

    describe('when we update the state of the machine many times in a single frame', function () {
      it('should trigger the mapping function many times', function () {
        const render = sinon.spy();
        const Comp = function () {
          render();
          return
Hello
;
        }
        const machine = Machine.create('C', {
          state: { name: 'idle', counter: 0 },
          transitions: {
            idle: {
              run: function ({ counter }) {
                return { name: 'idle', counter: counter + 1 };
              }
            }
          }
        });
        const mappingFunction = sinon.stub().returns({});
        const ConnectedComponent = connect(Comp).with('C').map(mappingFunction);

        mount(<ConnectedComponent message={ 'Hello' } />)

        machine.run();
        machine.run();
        machine.run();
        machine.run();
        machine.run();
        machine.run();

        expect(mappingFunction)
          .to.be.calledWith(sinon.match({
            state: { counter: 6, name: 'idle' }
          }))
        expect(render.callCount).to.be.equal(7);
      });
    });
  });
  describe('when unmounting the component', function () {
    it('should detach from the machines', function () {
      wrapper = getWrapper();
      Machine.get('A').run();
      expect(wrapper.find('p#A').text()).to.equal('machine A is in a running state');
      Machine.get('A').stop();
      expect(wrapper.find('p#A').text()).to.equal('machine A is in a idle state');
      wrapper.unmount();
      Machine.get('A').run();
      expect(mapping.callCount).to.be.equal(3);
    });
  });
  describe('when we connect without mapping', function () {
    it('should detach from the machines', function () {
      class Component extends React.Component {
        constructor(props) {
          super(props);

          this.counter = 0;
        }
        render() {
          this.counter += 1;
          return
Rendered { this.counter } times
;
        }
      }
      const Connected = connect(Component).with('A', 'B').map();
      const connectedWrapper = mount(<Connected />);
      Machine.get('A').run();
      Machine.get('A').stop();
      // 1 - initial render
      // 2 - default mapping call
      // 3 - because of machine's action run
      // 4 - because of machine's action stop
      expect(connectedWrapper.find('p').text()).to.equal('Rendered 4 times');
    });
  });
  describe('when we use mapSilent', function () {
    it('should only call the mapping function when the machine changes its state', function () {
      class Component extends React.Component {
        constructor(props) {
          super(props);

          this.counter = 0;
        }
        render() {
          this.counter += 1;
          return (

{ this.props.message('machine A', this.props.stateA)}

Rendered { this.counter } times

          );
        }
      }
      const message = (machineName, state) => `${ machineName } is in a ${ state } state`;
      const Connected = connect(Component).with('A', 'B').mapSilent(A => {
        return {
          stateA: A.state.name
        }
      });
      const connectedWrapper = mount(<Connected message={ message }/>);
      expect(connectedWrapper.find('p#A').text()).to.equal('machine A is in a undefined state');
      Machine.get('A').run();
      expect(connectedWrapper.find('p#A').text()).to.equal('machine A is in a running state');
      // 1 - initial render
      // 2 - because of machine's action run
      expect(connectedWrapper.find('p#counter').text()).to.equal('Rendered 2 times');
    });
  });
  describe('and we have a middleware attached', function () {
    it('should call the proper hooks', function () {
      const onMachineConnected = sinon.spy();
      const onMachineDisconnected = sinon.spy();

      Machine.addMiddleware({ onMachineConnected, onMachineDisconnected });

      const machine = Machine.create('foo', { state: {}, transitions: {} });
      const Zoo = () =>
Hello world
;
      const Connected = connect(Zoo).with('foo').map(() => ({}));
      const connectedWrapper = mount(<Connected />);

      expect(onMachineConnected).to.be.calledOnce.and.to.be.calledWith(
        sinon.match.array,
        sinon.match({ component: 'Zoo' })
      );
      expect(onMachineDisconnected).to.not.be.called;
      connectedWrapper.unmount();
      expect(onMachineDisconnected).to.be.calledOnce.and.to.be.calledWith(
        sinon.match.array,
        sinon.match({ component: 'Zoo' })
      );
    });
    describe('and we destroy a machine', function () {
      it('should call the proper hooks', function () {
        const onMachineConnected = sinon.spy();
        const onMachineDisconnected = sinon.spy();

        Machine.addMiddleware({ onMachineConnected, onMachineDisconnected });

        const machine = Machine.create('foo', { state: {}, transitions: {} });
        const Component = () =>
Hello world
;
        const Connected = connect(Component).with('foo').map(() => ({}));
        const connectedWrapper = mount(<Connected />);

        expect(onMachineConnected).to.be.calledOnce;
        expect(onMachineDisconnected).to.not.be.called;
        machine.destroy();
        expect(onMachineDisconnected).to.be.calledOnce;
      });
    });
  });
});<|endoftext|>


<commit_before>'use strict';

const Velocity = require('velocityjs');
const isPlainObject = require('lodash').isPlainObject;

const debugLog = require('./debugLog');
const { polluteStringPrototype, depolluteStringPrototype } = require('./javaHelpers');

const Compile = Velocity.Compile;
const parse = Velocity.parse;

function tryToParseJSON(string) {
  let parsed;
  try {
    parsed = JSON.parse(string);
  }
  catch (err) {
    // nothing! Some things are not meant to be parsed.
  }

  return parsed || string;
}

function renderVelocityString(velocityString, context) {

  // Add Java helpers to String prototype
  polluteStringPrototype();

  // This line can throw, but this function does not handle errors
  // Quick args explanation:
  // { escape: false } --> otherwise would escape &, < and > chars with html (&, < and >)
  // render(context, null, true) --> null: no custom macros; true: silent mode, just like APIG
  const renderResult = (new Compile(parse(velocityString), { escape: false })).render(context, null, true);

  // Remove Java helpers from String prototype
  depolluteStringPrototype();

  debugLog('Velocity rendered:', renderResult || 'undefined');

  // Haaaa Velocity... this language sure loves strings a lot
  switch (renderResult) {

    case 'undefined':
      return undefined; // But we don't, we want JavaScript types

    case 'null':
      return null;

    case 'true':
      return true;

    case 'false':
      return false;

    default:
      return tryToParseJSON(renderResult);
  }
}

/*
  Deeply traverses a Serverless-style JSON (Velocity) template
  When it finds a string, assumes it's Velocity language and renders it.
*/
module.exports = function renderVelocityTemplateObject(templateObject, context) {

  const result = {};
  let toProcess = templateObject;

  // In some projects, the template object is a string, let us see if it's JSON
  if (typeof toProcess === 'string') toProcess = tryToParseJSON(toProcess);

  // Let's check again
  if (isPlainObject(toProcess)) {
    for (let key in toProcess) { // eslint-disable-line prefer-const

      const value = toProcess[key];
      debugLog('Processing key:', key, '- value:', value);

      if (typeof value === 'string') result[key] = renderVelocityString(value, context);

      // Go deeper
      else if (isPlainObject(value)) result[key] = renderVelocityTemplateObject(value, context);

      // This should never happen: value should either be a string or a plain object
      else result[key] = value;
    }
  }

  // Still a string? Maybe it's some complex Velocity stuff
  else if (typeof toProcess === 'string') {

    // If the plugin threw here then you should consider reviewing your template or posting an issue.
    const alternativeResult = tryToParseJSON(renderVelocityString(toProcess, context));

    return isPlainObject(alternativeResult) ? alternativeResult : result;
  }

  return result;
};
<commit_msg>fix test on node v4 and 5<commit_after>'use strict';

const Velocity = require('velocityjs');
const isPlainObject = require('lodash').isPlainObject;

const debugLog = require('./debugLog');
const stringPollution = require('./javaHelpers');

const Compile = Velocity.Compile;
const parse = Velocity.parse;

function tryToParseJSON(string) {
  let parsed;
  try {
    parsed = JSON.parse(string);
  }
  catch (err) {
    // nothing! Some things are not meant to be parsed.
  }

  return parsed || string;
}

function renderVelocityString(velocityString, context) {

  // Add Java helpers to String prototype
  stringPollution.polluteStringPrototype();

  // This line can throw, but this function does not handle errors
  // Quick args explanation:
  // { escape: false } --> otherwise would escape &, < and > chars with html (&, < and >)
  // render(context, null, true) --> null: no custom macros; true: silent mode, just like APIG
  const renderResult = (new Compile(parse(velocityString), { escape: false })).render(context, null, true);

  // Remove Java helpers from String prototype
  stringPollution.depolluteStringPrototype();

  debugLog('Velocity rendered:', renderResult || 'undefined');

  // Haaaa Velocity... this language sure loves strings a lot
  switch (renderResult) {

    case 'undefined':
      return undefined; // But we don't, we want JavaScript types

    case 'null':
      return null;

    case 'true':
      return true;

    case 'false':
      return false;

    default:
      return tryToParseJSON(renderResult);
  }
}

/*
  Deeply traverses a Serverless-style JSON (Velocity) template
  When it finds a string, assumes it's Velocity language and renders it.
*/
module.exports = function renderVelocityTemplateObject(templateObject, context) {

  const result = {};
  let toProcess = templateObject;

  // In some projects, the template object is a string, let us see if it's JSON
  if (typeof toProcess === 'string') toProcess = tryToParseJSON(toProcess);

  // Let's check again
  if (isPlainObject(toProcess)) {
    for (let key in toProcess) { // eslint-disable-line prefer-const

      const value = toProcess[key];
      debugLog('Processing key:', key, '- value:', value);

      if (typeof value === 'string') result[key] = renderVelocityString(value, context);

      // Go deeper
      else if (isPlainObject(value)) result[key] = renderVelocityTemplateObject(value, context);

      // This should never happen: value should either be a string or a plain object
      else result[key] = value;
    }
  }

  // Still a string? Maybe it's some complex Velocity stuff
  else if (typeof toProcess === 'string') {

    // If the plugin threw here then you should consider reviewing your template or posting an issue.
    const alternativeResult = tryToParseJSON(renderVelocityString(toProcess, context));

    return isPlainObject(alternativeResult) ? alternativeResult : result;
  }

  return result;
};
<|endoftext|>