<commit_before>/*
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

var pm_config = {
    debug: false, // set to true for some debug output
    oauth: {
        // OAuth settings

        /* Apache OAuth example
         apache: {
            name: "Apache OAuth",
            oauth_portal: "https://oauth.apache.org/",
            oauth_url: "https://oauth.apache.org/token",
            fullname_key: 'fullname',
            email_key: 'email'
        },
        */
        /* Google example
        google: {
            name: "Google OAuth",
            oauth_portal: "https://accounts.google.com/o/oauth2/auth",
            oauth_url: "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=",
            fullname_key: 'name',
            email_key: 'email',
            client_id: 'your.google.app.id.here'
        }
        */
    },
    persona: {
        enabled: true // Is Mozilla Persona something we'd use?
    },
    indexMode: 'phonebook', // front page view mode:
                            // phonebook: Standard phonebook mode, sort/list by domain name (a.org, b.org, c.org...)
                            // phonebook_short: Same as above, but sort/list by list name (dev@a.org, dev@.org, user@a.org...)
                            // table: A more detailed view meant for smaller list sites (<=20-30 lists or such)
    shortLists: true, // whether to display foo@bar.org or just foo@ in flat view
    shortLinks: true
}

// Localized preferences (defaults)
var prefs = {
    displayMode: 'threaded',        // threaded or flat
    groupBy: 'thread',              // thread or date
    sortOrder: 'forward',           // forward or reverse sort
    compactQuotes: 'yes',           // Show quotes from original email as compacted blocks?
    notifications: 'direct',        // Notify on direct or indirect replies to your posts?
    hideStats: 'no',                // Hide the email statistics window?
    theme: 'default',               // Set to 'social' to default to the social theme
    loggedIn: false
}

// array of prefs we have now. This is needed in case we change/break the existing
// structure saved in elasticsearch for users. Update when needed!
var pref_keys = ['displayMode','groupBy','sortOrder','compactQuotes','notifications','hideStats','theme', 'fullname']<commit_msg>Default to not showing the stats panel<commit_after>/*
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

var pm_config = {
    debug: false, // set to true for some debug output
    oauth: {
        // OAuth settings

        /* Apache OAuth example
         apache: {
            name: "Apache OAuth",
            oauth_portal: "https://oauth.apache.org/",
            oauth_url: "https://oauth.apache.org/token",
            fullname_key: 'fullname',
            email_key: 'email'
        },
        */
        /* Google example
        google: {
            name: "Google OAuth",
            oauth_portal: "https://accounts.google.com/o/oauth2/auth",
            oauth_url: "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=",
            fullname_key: 'name',
            email_key: 'email',
            client_id: 'your.google.app.id.here'
        }
        */
    },
    persona: {
        enabled: true // Is Mozilla Persona something we'd use?
    },
    indexMode: 'phonebook', // front page view mode:
                            // phonebook: Standard phonebook mode, sort/list by domain name (a.org, b.org, c.org...)
                            // phonebook_short: Same as above, but sort/list by list name (dev@a.org, dev@.org, user@a.org...)
                            // table: A more detailed view meant for smaller list sites (<=20-30 lists or such)
    shortLists: true, // whether to display foo@bar.org or just foo@ in flat view
    shortLinks: true
}

// Localized preferences (defaults)
var prefs = {
    displayMode: 'threaded',        // threaded or flat
    groupBy: 'thread',              // thread or date
    sortOrder: 'forward',           // forward or reverse sort
    compactQuotes: 'yes',           // Show quotes from original email as compacted blocks?
    notifications: 'direct',        // Notify on direct or indirect replies to your posts?
    hideStats: 'yes',               // Hide the email statistics window?
    theme: 'default',               // Set to 'social' to default to the social theme
    loggedIn: false
}

// array of prefs we have now. This is needed in case we change/break the existing
// structure saved in elasticsearch for users. Update when needed!
var pref_keys = ['displayMode','groupBy','sortOrder','compactQuotes','notifications','hideStats','theme', 'fullname']<|endoftext|>


<commit_before>const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions

  const blogPost = path.resolve(`./src/templates/blog-post.js`)
  return graphql(
    `
      {
        allMarkdownRemark(
          sort: { fields: [frontmatter___date], order: DESC }
          limit: 1000
        ) {
          edges {
            node {
              fields {
                slug
              }
              frontmatter {
                title
              }
            }
          }
        }
      }
    `
  ).then(result => {
    if (result.errors) {
      throw result.errors
    }

    // Create blog posts pages.
    const posts = result.data.allMarkdownRemark.edges

    posts.forEach((post, index) => {
      const previous = index === posts.length - 1 ? null : posts[index + 1].node
      const next = index === 0 ? null : posts[index - 1].node

      createPage({
        path: post.node.fields.slug,
        component: blogPost,
        context: {
          slug: post.node.fields.slug,
          previous,
          next,
        },
      })
    })
  })
}

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions

  if (node.internal.type === `MarkdownRemark`) {
    const value = createFilePath({ node, getNode })
    createNodeField({
      name: `slug`,
      node,
      value,
    })
  }
}
<commit_msg>chore(starters): Return null in then for blog starter (#12304)<commit_after>const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions

  const blogPost = path.resolve(`./src/templates/blog-post.js`)
  return graphql(
    `
      {
        allMarkdownRemark(
          sort: { fields: [frontmatter___date], order: DESC }
          limit: 1000
        ) {
          edges {
            node {
              fields {
                slug
              }
              frontmatter {
                title
              }
            }
          }
        }
      }
    `
  ).then(result => {
    if (result.errors) {
      throw result.errors
    }

    // Create blog posts pages.
    const posts = result.data.allMarkdownRemark.edges

    posts.forEach((post, index) => {
      const previous = index === posts.length - 1 ? null : posts[index + 1].node
      const next = index === 0 ? null : posts[index - 1].node

      createPage({
        path: post.node.fields.slug,
        component: blogPost,
        context: {
          slug: post.node.fields.slug,
          previous,
          next,
        },
      })
    })

    return null
  })
}

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions

  if (node.internal.type === `MarkdownRemark`) {
    const value = createFilePath({ node, getNode })
    createNodeField({
      name: `slug`,
      node,
      value,
    })
  }
}
<|endoftext|>


<commit_before>//
// Created by Bradley Austin Davis on 2016/12/12
// Copyright 2013-2016 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
/*global print, Resources, Test, MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, Audio, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */
/*global ColorIndicator */

'use strict';

Script.include("./BenchmarkLib.js");
Resources.overrideUrlPrefix(TEST_ROOT, Script.resolvePath(".."));

var TRACE_TOOLBAR = "com.highfidelity.interface.toolbar.trace";
var TRACE_ICON = Script.resolvePath("../assets/traceButton.png");
var TRACE_NAME = "trace-{DATE}_{TIME}";
var TRACE_DURATION = 20;

var traceActive = false;
var button = Toolbars.getToolbar(TRACE_TOOLBAR).addButton({
    objectName: "toggleTrace",
    imageURL: TRACE_ICON,
    alpha: 0.9,
    visible: true
});

function stopTrace() {
    if (!traceActive) {
        return;
    }
    traceActive = false;
    button.writeProperty("buttonState", 0);
    // Test.stopTracing(TRACE_NAME);
}

function startTrace() {
    if (traceActive) {
        return;
    }
    var newTraceName = Window.prompt("Name of trace file", TRACE_NAME);
    if (!newTraceName) {
        return;
    }
    TRACE_NAME = newTraceName;

    var newTraceDuration = Window.prompt("Trace duration in seconds (0 for manual shutdown)", TRACE_DURATION);
    if (newTraceDuration == "") {
        return;
    }
    newTraceDuration = Number(newTraceDuration);
    if (isNaN(newTraceDuration)) {
        return;
    }

    if (newTraceDuration > 60) {
        Window.alert("Max trace time is 60 seconds");
        return;
    }

    TRACE_DURATION = newTraceDuration;
    traceActive = true;
    button.writeProperty("buttonState", 1);
    print("QQQ starting trace " + TRACE_NAME + " for " + TRACE_DURATION + " seconds");
    Test.startTracing(DEFAULT_TRACING_RULES);
    if (TRACE_DURATION > 0) {
        Script.setTimeout(function(){
            stopTrace();
        }, TRACE_DURATION * 1000);
    }
}

function traceToggle() {
    if (traceActive) {
        stopTrace();
    } else {
        startTrace();
    }
}

button.clicked.connect(function () {
    Script.setTimeout(traceToggle, 100);
});

print("QQQ trace script! done init");
<commit_msg>Fix manual benchmark script<commit_after>//
// Created by Bradley Austin Davis on 2016/12/12
// Copyright 2013-2016 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
/*global print, Resources, Test, MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, Audio, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */
/*global ColorIndicator */

'use strict';

Script.include("./BenchmarkLib.js");
Resources.overrideUrlPrefix(TEST_ROOT, Script.resolvePath(".."));

var TRACE_TOOLBAR = "com.highfidelity.interface.toolbar.trace";
var TRACE_ICON = Script.resolvePath("../assets/traceButton.png");
var TRACE_NAME = "trace-{DATE}_{TIME}";
var TRACE_DURATION = 20;

var traceActive = false;
var button = Toolbars.getToolbar(TRACE_TOOLBAR).addButton({
    objectName: "toggleTrace",
    imageURL: TRACE_ICON,
    alpha: 0.9,
    visible: true
});

function stopTrace() {
    if (!traceActive) {
        return;
    }
    traceActive = false;
    button.writeProperty("buttonState", 0);
    Test.stopTracing("traces/" + TRACE_NAME + ".json.gz");
}

function startTrace() {
    if (traceActive) {
        return;
    }
    var newTraceName = Window.prompt("Name of trace file", TRACE_NAME);
    if (!newTraceName) {
        return;
    }
    TRACE_NAME = newTraceName;

    var newTraceDuration = Window.prompt("Trace duration in seconds (0 for manual shutdown)", TRACE_DURATION);
    if (newTraceDuration == "") {
        return;
    }
    newTraceDuration = Number(newTraceDuration);
    if (isNaN(newTraceDuration)) {
        return;
    }

    if (newTraceDuration > 60) {
        Window.alert("Max trace time is 60 seconds");
        return;
    }

    TRACE_DURATION = newTraceDuration;
    traceActive = true;
    button.writeProperty("buttonState", 1);
    print("QQQ starting trace " + TRACE_NAME + " for " + TRACE_DURATION + " seconds");
    Test.startTracing(DEFAULT_TRACING_RULES);
    if (TRACE_DURATION > 0) {
        Script.setTimeout(function(){
            stopTrace();
        }, TRACE_DURATION * 1000);
    }
}

function traceToggle() {
    if (traceActive) {
        stopTrace();
    } else {
        startTrace();
    }
}

button.clicked.connect(function () {
    Script.setTimeout(traceToggle, 100);
});

print("QQQ trace script! done init");
<|endoftext|>


<commit_before>// Data Tree Dependencies
define(['polytree/DataNode'],
function (DataNode) {
return {

// Data Tree Builder
build : function () {
  var proto = this.proto;
  var propertiesObject = {
    library: {
      value: {}
    },
    nodeIndex: {
      value: {}
    },
    nodesToRecalculate: {
      value: []
    }
  };

  var dataTree = Object.create(proto, propertiesObject);
  return dataTree;
},

// Data Tree Prototype
proto : {

  initialize : function (ctx) {
    this.ctx = ctx;
  },

  configure : function (config) {
    var ctx = this.ctx;
    var cc = ctx.configConstants;
    var dToCreate = config[cc.MEDIAL_NODES];
    _.each(dToCreate, function (obj, i) {
      var d = ctx.d.configureOrCreate(obj);
      ctx.d.nodeIndex[d.id] = i;
      ctx.d.registerNodesToRecalculate([d.id]);
    });
  },

  configureOrCreate : function (obj) {
    var ctx = this.ctx;
    var cc = ctx.configConstants;
    var d = this.lookup(obj[cc.MN_ID]);
    if (d) {
      d.configure(obj);
    } else {
      d = DataNode.build(obj[cc.MN_ID]);
      d.initialize(ctx);
      d.configure(obj);
      this.library[d.id] = d;
    }
    return d;
  },

  notify : function (watcher, value) {
    var d = this.lookup(watcher[1]);
    if (d) {
      d.notify(watcher, value);
    } else {
      console.log('error');
    }
  },

  lookup : function (id) {
    return this.library[id];
  },

  registerNodesToRecalculate : function (idArr) {
    Array.prototype.push.apply(this.nodesToRecalculate, idArr);
  },

  recalculate : function () {
    var collection = this;
    while (this.nodesToRecalculate.length > 0) {
      collection.sortNodeSet('nodesToRecalculate');
      this.nodesToRecalculate = _.uniq(this.nodesToRecalculate, true);
      var nodeId = this.nodesToRecalculate.shift();
      var node = this.lookup(nodeId);
      node.recalculate();
    }
  },

  sortNodeSet : function (nodeSetName) {
    var collection = this;
    this[nodeSetName].sort(function (idA, idB) {
      if (collection.nodeIndex[idA] > collection.nodeIndex[idB]) {
        return 1;
      } else {
        return -1;
      }
    });
  }
}

};});
<commit_msg>issue #24 de-dupe properly<commit_after>// Data Tree Dependencies
define(['polytree/DataNode'],
function (DataNode) {
return {

// Data Tree Builder
build : function () {
  var proto = this.proto;
  var propertiesObject = {
    library: {
      value: {}
    },
    nodeIndex: {
      value: {}
    },
    nodesToRecalculate: {
      value: []
    }
  };

  var dataTree = Object.create(proto, propertiesObject);
  return dataTree;
},

// Data Tree Prototype
proto : {

  initialize : function (ctx) {
    this.ctx = ctx;
  },

  configure : function (config) {
    var ctx = this.ctx;
    var cc = ctx.configConstants;
    var dToCreate = config[cc.MEDIAL_NODES];
    _.each(dToCreate, function (obj, i) {
      var d = ctx.d.configureOrCreate(obj);
      ctx.d.nodeIndex[d.id] = i;
      ctx.d.registerNodesToRecalculate([d.id]);
    });
  },

  configureOrCreate : function (obj) {
    var ctx = this.ctx;
    var cc = ctx.configConstants;
    var d = this.lookup(obj[cc.MN_ID]);
    if (d) {
      d.configure(obj);
    } else {
      d = DataNode.build(obj[cc.MN_ID]);
      d.initialize(ctx);
      d.configure(obj);
      this.library[d.id] = d;
    }
    return d;
  },

  notify : function (watcher, value) {
    var d = this.lookup(watcher[1]);
    if (d) {
      d.notify(watcher, value);
    } else {
      console.log('error');
    }
  },

  lookup : function (id) {
    return this.library[id];
  },

  registerNodesToRecalculate : function (idArr) {
    Array.prototype.push.apply(this.nodesToRecalculate, idArr);
  },

  recalculate : function () {
    var collection = this;
    while (this.nodesToRecalculate.length > 0) {
      collection.sortNodeSet('nodesToRecalculate');
      collection.deDupeSortedNodeSet('nodesToRecalculate');
      var nodeId = this.nodesToRecalculate.shift();
      var node = this.lookup(nodeId);
      node.recalculate();
    }
  },

  sortNodeSet : function (nodeSetName) {
    var collection = this;
    this[nodeSetName].sort(function (idA, idB) {
      if (collection.nodeIndex[idA] > collection.nodeIndex[idB]) {
        return 1;
      } else {
        return -1;
      }
    });
  },

  deDupeSortedNodeSet : function (nodeSetName) {
    var i = 1;
    var nodeSet = this[nodeSetName];
    while (i < nodeSet.length) {
      if (nodeSet[i - 1] === nodeSet[i]) {
        nodeSet.splice(i, 1);
      } else {
        i++;
      }
    }
  }
}

};});
<|endoftext|>


<commit_before>(function($) {

$.getSync = function(url, data, success, dataType) {
	return $.ajax({
		url: url,
		data: data,
		success: success,
		dataType: dataType,
		async: false,
	});
}

$.postSync = function(url, data, success, dataType) {
	return $.ajax({
		type: "POST",
		url: url,
		data: data,
		success: success,
		dataType: dataType,
		async: false,
	});
}

//TODO: see if this style sheet is already loaded, and if so, don't load again!
$.afGetStyles = function(url) {
	$('<link>')
		.appendTo($('head'))
		.attr({type:'text/css', rel:'stylesheet'})
		.attr('href', url);
};

$.afGetScript = function(url, p1, p2) {
	var options = $.isFunction(p1) ? {} : p1;
	var success = $.isFunction(p1) ? p1 : p2;
	console.log(url);
	console.log(p1);
	return $.ajax($.extend(options || {}, {
		dataType: 'script',
		//cache: true,
		cache: false,
		url: url,
		success: success,
	}));
}

$.updateClass = function(name, value) {
	// we need invisible container to store additional css definitions
	var parent = $('#af-css-container');
	if (parent.length == 0) {
		parent = $('

');
		parent.hide();
		parent.appendTo('body');
	}

	// and we need one div for each class
	var child = parent.find('div[data-class="' + name + '"]');
	if (child.length == 0) {
		child = $('

');
		child.appendTo(parent);
	}

	// append additional style
	child.html('');
}

//Allow for input serialization from non form elements
$.fn.afSerialize = function() {
	return $(this).find('select, input, textarea, datalist, keygen').serialize();
};

$.fn.afNextInput = function() {
	$(this).each(function(index, item) {
		if ($(item).hasClass('afNextInput')) return;
		$(item).addClass('afNextInput');

		$(item).keyup(function(){
			if ($(item).val().length == $(item).attr('size')) {
				if ($(item).data('val') == $(item).val()) return;
				$(item).data('val', $(item).val());
				$(':input:eq('+($(':input').index(item)+1)+')').focus();
			}
		});

		$(item).change(function(){ $(item).data('val', $(item).val()); })

	});

	return this;
};

$.fn.afSelectOption = function(value) {
	var val = value.trim();
	$(this).each(function(index, item) {
		$(item).children('option').prop('selected', false);
		$(item).children('option').filter(function() {
			return $(this).text().trim() == val;
		}).prop('selected', true);
	});
	return this;
};

$.fn.afClickEdit = function(url, id, callback) {
	$(this).each(function(index, item) {
		item = $(item);
		if (item.hasClass('af-edit-field')) return;
		item.addClass('af-edit-field');

		var input = $('<input class="af-edit-input" type="text" />').insertAfter(item);

		input
		.hide()
		.attr('name', item.data('name'))
		.val(item.text().trim())
		.keypress(function(e){if(e.which==13){$(this).blur()}})

		.blur(function(){
			if (!!$('.ui-autocomplete.ui-widget:visible').length) return;
			if (item.text() != input.val()) {
				item.text( input.val() );
				var thisid = id;
				if (!isNumber(thisid)) thisid = $(item).closest('[data-'+thisid+']').data(id);
				if (typeof url == 'string') {
					$.post(
						url,
						{ id: thisid,	text: input.val() },
						function(data) {
							item.html(data);
							if (typeof callback == 'function') {
								callback.call(this, item, input);
							}
						}
					);
				} else if (typeof url == 'function') {
					url.call(this, input.val());
				}
			}
			input.hide();
			item.show();
		});

		item.click(function(event){
			if (event.which != 1) return;
			event.preventDefault();
			event.stopPropagation();
			var css = [
				'font', 'display', 'width', 'height', 'position', 'left', 'top',
				'right', 'bottom', 'border', 'padding', 'margin', 'float',
				'vertical-align', 'text-align'
			];
			css.forEach(function(attr) {
				input.css( attr, item.css(attr) );
			});
			input.val( item.text().trim().replace(/\s\s+/g, ' ') ).focus();
			item.hide();
		});
	});

	return this;
};

var afResizeBody = false;
$.fn.afResize = function() {
	if (!afResizeBody) afResizeBody = $('
').hide().appendTo('body');
	$(this).each(function(index, item) {
		$(item).on('keyup', function(){
			afResizeBody.css('overflow', 'hidden');
			afResizeBody.css('width', $(this).width());
			afResizeBody.css('margin', $(this).css('margin'));
			afResizeBody.css('padding', $(this).css('padding'));
			afResizeBody.css('line-height', $(this).css('line-height'));
			afResizeBody.css('font-size', $(this).css('font-size'));
			afResizeBody.css('word-wrap', $(this).css('word-wrap'));
			afResizeBody.html( $(this).val().replace(/\n/g, '
') +  '
' );
			$(this).css('height', afResizeBody.outerHeight());
		});
	});
	return this;
};

})(jQuery);
<commit_msg>Cleanup<commit_after>(function($) {

$.getSync = function(url, data, success, dataType) {
	return $.ajax({
		url: url,
		data: data,
		success: success,
		dataType: dataType,
		async: false,
	});
}

$.postSync = function(url, data, success, dataType) {
	return $.ajax({
		type: "POST",
		url: url,
		data: data,
		success: success,
		dataType: dataType,
		async: false,
	});
}

$.afGetStyles = function(url) {
	$('<link>')
		.appendTo($('head'))
		.attr({type:'text/css', rel:'stylesheet'})
		.attr('href', url);
};

$.afGetScript = function(url, p1, p2) {
	var options = $.isFunction(p1) ? {} : p1;
	var success = $.isFunction(p1) ? p1 : p2;
	console.log(url);
	console.log(p1);
	return $.ajax($.extend(options || {}, {
		dataType: 'script',
		cache: true,
		url: url,
		success: success,
	}));
}

$.updateClass = function(name, value) {
	//WE NEED INVISIBLE CONTAINERS TO STORE ADDITIONAL CSS DEFINITIONS
	var parent = $('#af-css-container');
	if (parent.length == 0) {
		parent = $('

');
		parent.hide();
		parent.appendTo('body');
	}

	//AND WE NEED ONE DIV FOR EACH CLASS
	var child = parent.find('div[data-class="' + name + '"]');
	if (child.length == 0) {
		child = $('

');
		child.appendTo(parent);
	}

	//APPEND ADDITIONAL STYLE
	child.html('');
}

//ALLOW FOR INPUT SERIALIZATION FROM NON FORM ELEMENTS
$.fn.afSerialize = function() {
	return $(this).find('select, input, textarea, datalist, keygen').serialize();
};

$.fn.afNextInput = function() {
	$(this).each(function(index, item) {
		if ($(item).hasClass('afNextInput')) return;
		$(item).addClass('afNextInput');

		$(item).keyup(function(){
			if ($(item).val().length == $(item).attr('size')) {
				if ($(item).data('val') == $(item).val()) return;
				$(item).data('val', $(item).val());
				$(':input:eq('+($(':input').index(item)+1)+')').focus();
			}
		});

		$(item).change(function(){ $(item).data('val', $(item).val()); })

	});

	return this;
};

$.fn.afSelectOption = function(value) {
	var val = value.trim();
	$(this).each(function(index, item) {
		$(item).children('option').prop('selected', false);
		$(item).children('option').filter(function() {
			return $(this).text().trim() == val;
		}).prop('selected', true);
	});
	return this;
};

$.fn.afClickEdit = function(url, id, callback) {
	$(this).each(function(index, item) {
		item = $(item);
		if (item.hasClass('af-edit-field')) return;
		item.addClass('af-edit-field');

		var input = $('<input class="af-edit-input" type="text" />').insertAfter(item);

		input
		.hide()
		.attr('name', item.data('name'))
		.val(item.text().trim())
		.keypress(function(e){if(e.which==13){$(this).blur()}})

		.blur(function(){
			if (!!$('.ui-autocomplete.ui-widget:visible').length) return;
			if (item.text() != input.val()) {
				item.text( input.val() );
				var thisid = id;
				if (!isNumber(thisid)) thisid = $(item).closest('[data-'+thisid+']').data(id);
				if (typeof url == 'string') {
					$.post(
						url,
						{ id: thisid,	text: input.val() },
						function(data) {
							item.html(data);
							if (typeof callback == 'function') {
								callback.call(this, item, input);
							}
						}
					);
				} else if (typeof url == 'function') {
					url.call(this, input.val());
				}
			}
			input.hide();
			item.show();
		});

		item.click(function(event){
			if (event.which != 1) return;
			event.preventDefault();
			event.stopPropagation();
			var css = [
				'font', 'display', 'width', 'height', 'position', 'left', 'top',
				'right', 'bottom', 'border', 'padding', 'margin', 'float',
				'vertical-align', 'text-align'
			];
			css.forEach(function(attr) {
				input.css( attr, item.css(attr) );
			});
			input.val( item.text().trim().replace(/\s\s+/g, ' ') ).focus();
			item.hide();
		});
	});

	return this;
};

var afResizeBody = false;
$.fn.afResize = function() {
	if (!afResizeBody) afResizeBody = $('
').hide().appendTo('body');
	$(this).each(function(index, item) {
		$(item).on('keyup', function(){
			afResizeBody.css('overflow', 'hidden');
			afResizeBody.css('width', $(this).width());
			afResizeBody.css('margin', $(this).css('margin'));
			afResizeBody.css('padding', $(this).css('padding'));
			afResizeBody.css('line-height', $(this).css('line-height'));
			afResizeBody.css('font-size', $(this).css('font-size'));
			afResizeBody.css('word-wrap', $(this).css('word-wrap'));
			afResizeBody.html( $(this).val().replace(/\n/g, '
') +  '
' );
			$(this).css('height', afResizeBody.outerHeight());
		});
	});
	return this;
};

})(jQuery);
<|endoftext|>


<commit_before>var fs = require('fs-extra'),
    url = require('url'),
    path = require('path');
var Model = require('./model');
var DB = require('./db');

var videoPath = '/data/hupba/Datasets/YoutubeMonk/outputs/clips';
var exportPath = './export_last';

var labelTag = ['Error', 'Valid', 'NoValid', 'ValidCuts'];

var exportFile = function (inFile, outFile, videoID) {
    fs.copy(inFile, outFile, function (err) {
        if (err) {
            console.error(err)
        } else {
            // Update export flag
            var expVideoModel = new Model.Video({ videoId: videoID, exported: '1' });
            expVideoModel.save().then(function (model) {
                if (!model) {
                    console.error('Error updating exportation flag of video ' + videoID);
                }
                return;
            });
        }
    });
    return;
}

try {
    fs.ensureDirSync(exportPath);
    for (var i = 0, len = labelTag.length; i < len; i++) {
        fs.ensureDirSync(path.resolve(exportPath, labelTag[i]));
    }
} catch (err) {
    console.error('There was an error creating output files!', err);
}

var videoReq = new Model.Videos().query({ where: { exported: '0', labeled: '1' } }).fetch();
return videoReq.then(function (model) {
    if (model) {
        for (var i = 0, len = model.length; i < len; i++) {
            var inFile = path.resolve(videoPath, model.models[i].attributes.path);
            var outFile = path.resolve(path.resolve(exportPath, labelTag[model.models[i].attributes.label]), model.models[i].attributes.path);
            var videoID = model.models[i].attributes.videoId;
            exportFile(inFile, outFile, videoID);
        }
        console.print(model.length + ' videos will be exported.');
    } else {
        console.error('No remaining labeled videos to export', {});
    }
    return;
});

<commit_msg>Solved issue in export.js<commit_after>var fs = require('fs-extra'),
    url = require('url'),
    path = require('path');
var Model = require('./model');
var DB = require('./db');

var videoPath = '/data/hupba/Datasets/YoutubeMonk/outputs/clips';
var exportPath = './export_last';

var labelTag = ['Error', 'Valid', 'NoValid', 'ValidCuts'];
var exportFile = function (inFile, outFile, videoID) {
    fs.copy(inFile, outFile, function (err) {
        if (err) {
            console.error(err)
        } else {
            // Update export flag
            var expVideoModel = new Model.Video({ videoId: videoID, exported: '1' });
            expVideoModel.save().then(function (model) {
                if (!model) {
                    console.error('Error updating exportation flag of video ' + videoID);
                }
                return;
            });
        }
    });
    return;
}

try {
    fs.ensureDirSync(exportPath);
    for (var i = 0, len = labelTag.length; i < len; i++) {
        fs.ensureDirSync(path.resolve(exportPath, labelTag[i]));
    }
} catch (err) {
    console.error('There was an error creating output files!', err);
}

var videoReq = new Model.Videos().query({ where: { exported: '0', labeled: '1' } }).fetch();
return videoReq.then(function (model) {
    if (model) {
        for (var i = 0, len = model.length; i < len; i++) {
            var inFile = path.resolve(videoPath, model.models[i].attributes.path);
            var outFile = path.resolve(path.resolve(exportPath, labelTag[model.models[i].attributes.label]), model.models[i].attributes.path);
            var videoID = model.models[i].attributes.videoId;
            exportFile(inFile, outFile, videoID);
        }
        console.log(model.length + ' videos will be exported.');
    } else {
        console.error('No remaining labeled videos to export', {});
    }
    return;
});

<|endoftext|>


<commit_before>// $Revision$

Ensembl.LayoutManager = new Base();

Ensembl.LayoutManager.extend({
  constructor: null,

  /**
   * Creates events on elements outside of the domain of panels
   */
  initialize: function () {
    this.id = 'LayoutManager';

    Ensembl.EventManager.register('reloadPage',    this, this.reloadPage);
    Ensembl.EventManager.register('validateForms', this, this.validateForms);
    Ensembl.EventManager.register('makeZMenu',     this, this.makeZMenu);
    Ensembl.EventManager.register('relocateTools', this, this.relocateTools);
    Ensembl.EventManager.register('hashChange',    this, this.hashChange);
    Ensembl.EventManager.register('toggleContent', this, this.toggleContent);

    $('#page_nav .tool_buttons > p').show();

    $('#header a:not(#tabs a)').addClass('constant');

    if ((window.location.hash.replace(/^#/, '?') + ';').match(Ensembl.hashRegex)) {
      $('.ajax_load').val(function () {
        return Ensembl.urlFromHash(this.value);
      });

      this.hashChange(Ensembl.urlFromHash(window.location.href, true));
    }

    $('.modal_link').show().live('click', function () {
      if (Ensembl.EventManager.trigger('modalOpen', this)) {
        return false;
      }
    });

    $('.popup').live('click', function () {
      if (window.name.match(/^popup_/)) {
        return true;
      }

      window.open(this.href, 'popup_' + window.name, 'width=950,height=500,resizable,scrollbars');
      return false;
    });

    $('a[rel="external"]').live('click', function () {
      this.target = '_blank';
    });

    this.validateForms(document);

    // Close modal window if the escape key is pressed
    $(document).bind({
      keyup: function (event) {
        if (event.keyCode == 27) {
          Ensembl.EventManager.trigger('modalClose', true);
        }
      },
      mouseup: function (e) {
        // only fired on left click
        if (!e.which || e.which == 1) {
          Ensembl.EventManager.trigger('mouseUp', e);
        }
      }
    });

    $(window).bind({
      resize: function () {
        Ensembl.EventManager.trigger('windowResize');
      },
      hashchange: function (e) {
        if ((window.location.hash.replace(/^#/, '?') + ';').match(Ensembl.hashRegex) || !window.location.hash && Ensembl.hash.match(Ensembl.hashRegex)) {
          Ensembl.setCoreParams();
          Ensembl.EventManager.trigger('hashChange', Ensembl.urlFromHash(window.location.href, true));
        }
      }
    });

    var userMessage = unescape(Ensembl.cookie.get('user_message'));

    if (userMessage) {
      userMessage = userMessage.split('\n');

      $([
        '
',
        '
', userMessage[0], '
',
        '
', userMessage[1], '
',
        '
'
      ].join('')).prependTo('#main').find('h3 img, a').click(function () {
        $(this).parents('div.hint').remove();
        Ensembl.cookie.set('user_message', '', -1);
      });
    }
  },

  reloadPage: function (args) {
    if (typeof args == 'string') {
      Ensembl.EventManager.triggerSpecific('updatePanel', args);
    } else if (typeof args == 'object') {
      for (var i in args) {
        Ensembl.EventManager.triggerSpecific('updatePanel', i);
      }
    } else {
      Ensembl.redirect();
    }
  },

  validateForms: function (context) {
    $('form.check', context).validate().bind('submit', function () {
      return $(this).parents('#modal_panel').length ? Ensembl.EventManager.trigger('modalFormSubmit', $(this)) : true;
    });
  },

  makeZMenu: function (id, params) {
    if (!$('#' + id).length) {
      $([
        '
',
        ' ',
        '
',
        '
',
        '

',
        '
',
        '
',
        '

',
        '
',
        '

',
        '
',
        '
'
      ].join('')).draggable({ handle: 'thead' }).appendTo('body');
    }

    Ensembl.EventManager.trigger('addPanel', id, 'ZMenu', undefined, undefined, params, 'showExistingZMenu');
  },

  relocateTools: function (tools) {
    var toolButtons = $('#page_nav .tool_buttons');

    tools.each(function () {
      var a = $(this).find('a');
      var existing = $('.additional .' + a[0].className.replace(' ', '.'), toolButtons);

      if (existing.length) {
        existing.replaceWith(a);
      } else {
        $(this).children().addClass('additional').appendTo(toolButtons).not('.hidden').show();
      }

      a = null;
      existing = null;
    }).remove();

    $('a.seq_blast', toolButtons).click(function () {
      $('form.seq_blast', toolButtons).submit();
      return false;
    });
  },

  hashChange: function (r) {
    if (!r) {
      return;
    }

    var text = r.split(/\W/);
    text     = text[0] + ': ' + Ensembl.thousandify(text[1]) + '-' + Ensembl.thousandify(text[2]);

    $('a:not(.constant)').attr('href', function () {
      var r;

      if (this.title == 'UCSC') {
        this.href = this.href.replace(/(&?position=)[^&]+(.?)/, '$1chr' + Ensembl.urlFromHash(this.href, true) + '$2');
      } else if (this.title == 'NCBI') {
        r = Ensembl.urlFromHash(this.href, true).split(/[:-]/);
        this.href = this.href.replace(/(&?CHR=).+&BEG=.+&END=[^&]+(.?)/, '$1' + r[0] + '&BEG=' + r[1] + '&END=' + r[2] + '$2');
      } else {
        return Ensembl.urlFromHash(this.href);
      }
    });

    $('input[name=r]', 'form:not(#core_params)').val(r);

    $('h2.caption').html(function (i, html) {
      return html.replace(/^(Chromosome ).+/, '$1' + text);
    });
  },

  toggleContent: function (rel) {
    $('a.toggle[rel="' + rel + '"]').toggleClass('open closed');
  }
});

<commit_msg>added changeWidth function<commit_after>// $Revision$

Ensembl.LayoutManager = new Base();

Ensembl.LayoutManager.extend({
  constructor: null,

  /**
   * Creates events on elements outside of the domain of panels
   */
  initialize: function () {
    this.id = 'LayoutManager';

    Ensembl.EventManager.register('reloadPage',    this, this.reloadPage);
    Ensembl.EventManager.register('validateForms', this, this.validateForms);
    Ensembl.EventManager.register('makeZMenu',     this, this.makeZMenu);
    Ensembl.EventManager.register('relocateTools', this, this.relocateTools);
    Ensembl.EventManager.register('hashChange',    this, this.hashChange);
    Ensembl.EventManager.register('toggleContent', this, this.toggleContent);
    Ensembl.EventManager.register('changeWidth',   this, this.changeWidth);

    $('#page_nav .tool_buttons > p').show();

    $('#header a:not(#tabs a)').addClass('constant');

    if ((window.location.hash.replace(/^#/, '?') + ';').match(Ensembl.hashRegex)) {
      $('.ajax_load').val(function () {
        return Ensembl.urlFromHash(this.value);
      });

      this.hashChange(Ensembl.urlFromHash(window.location.href, true));
    }

    $('.modal_link').show().live('click', function () {
      if (Ensembl.EventManager.trigger('modalOpen', this)) {
        return false;
      }
    });

    $('.popup').live('click', function () {
      if (window.name.match(/^popup_/)) {
        return true;
      }

      window.open(this.href, 'popup_' + window.name, 'width=950,height=500,resizable,scrollbars');
      return false;
    });

    $('a[rel="external"]').live('click', function () {
      this.target = '_blank';
    });

    this.validateForms(document);

    // Close modal window if the escape key is pressed
    $(document).bind({
      keyup: function (event) {
        if (event.keyCode == 27) {
          Ensembl.EventManager.trigger('modalClose', true);
        }
      },
      mouseup: function (e) {
        // only fired on left click
        if (!e.which || e.which == 1) {
          Ensembl.EventManager.trigger('mouseUp', e);
        }
      }
    });

    $(window).bind({
      resize: function () {
        Ensembl.EventManager.trigger('windowResize');
      },
      hashchange: function (e) {
        if ((window.location.hash.replace(/^#/, '?') + ';').match(Ensembl.hashRegex) || !window.location.hash && Ensembl.hash.match(Ensembl.hashRegex)) {
          Ensembl.setCoreParams();
          Ensembl.EventManager.trigger('hashChange', Ensembl.urlFromHash(window.location.href, true));
        }
      }
    });

    var userMessage = unescape(Ensembl.cookie.get('user_message'));

    if (userMessage) {
      userMessage = userMessage.split('\n');

      $([
        '
',
        '
', userMessage[0], '
',
        '
', userMessage[1], '
',
        '
'
      ].join('')).prependTo('#main').find('h3 img, a').click(function () {
        $(this).parents('div.hint').remove();
        Ensembl.cookie.set('user_message', '', -1);
      });
    }
  },

  reloadPage: function (args) {
    if (typeof args == 'string') {
      Ensembl.EventManager.triggerSpecific('updatePanel', args);
    } else if (typeof args == 'object') {
      for (var i in args) {
        Ensembl.EventManager.triggerSpecific('updatePanel', i);
      }
    } else {
      Ensembl.redirect();
    }
  },

  validateForms: function (context) {
    $('form.check', context).validate().bind('submit', function () {
      return $(this).parents('#modal_panel').length ? Ensembl.EventManager.trigger('modalFormSubmit', $(this)) : true;
    });
  },

  makeZMenu: function (id, params) {
    if (!$('#' + id).length) {
      $([
        '
',
        ' ',
        '
',
        '
',
        '

',
        '
',
        '
',
        '

',
        '
',
        '

',
        '
',
        '
'
      ].join('')).draggable({ handle: 'thead' }).appendTo('body');
    }

    Ensembl.EventManager.trigger('addPanel', id, 'ZMenu', undefined, undefined, params, 'showExistingZMenu');
  },

  relocateTools: function (tools) {
    var toolButtons = $('#page_nav .tool_buttons');

    tools.each(function () {
      var a = $(this).find('a');
      var existing = $('.additional .' + a[0].className.replace(' ', '.'), toolButtons);

      if (existing.length) {
        existing.replaceWith(a);
      } else {
        $(this).children().addClass('additional').appendTo(toolButtons).not('.hidden').show();
      }

      a = null;
      existing = null;
    }).remove();

    $('a.seq_blast', toolButtons).click(function () {
      $('form.seq_blast', toolButtons).submit();
      return false;
    });
  },

  hashChange: function (r) {
    if (!r) {
      return;
    }

    var text = r.split(/\W/);
    text     = text[0] + ': ' + Ensembl.thousandify(text[1]) + '-' + Ensembl.thousandify(text[2]);

    $('a:not(.constant)').attr('href', function () {
      var r;

      if (this.title == 'UCSC') {
        this.href = this.href.replace(/(&?position=)[^&]+(.?)/, '$1chr' + Ensembl.urlFromHash(this.href, true) + '$2');
      } else if (this.title == 'NCBI') {
        r = Ensembl.urlFromHash(this.href, true).split(/[:-]/);
        this.href = this.href.replace(/(&?CHR=).+&BEG=.+&END=[^&]+(.?)/, '$1' + r[0] + '&BEG=' + r[1] + '&END=' + r[2] + '$2');
      } else {
        return Ensembl.urlFromHash(this.href);
      }
    });

    $('input[name=r]', 'form:not(#core_params)').val(r);

    $('h2.caption').html(function (i, html) {
      return html.replace(/^(Chromosome ).+/, '$1' + text);
    });
  },

  toggleContent: function (rel) {
    $('a.toggle[rel="' + rel + '"]').toggleClass('open closed');
  },

  changeWidth: function () {
    $('.navbar, div.info, div.hint, div.warning, div.error').width(Ensembl.width);
  }
});

<|endoftext|>


<commit_before>/* private */
var _options = require('./options');
var Mode = require('./mode');
var Command = require('./wrapper').Command;

var state; // current builder state
var stack; // result builder
var staticArraysHolder = {}; // holder for static arrays
var wrapper; // external wrapper functionality
var helpers; // keys for helpers

var empty = '', quote = '\'', comma = ', \''; // auxiliary

function makeKey() {
    var text = new Array(12), possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgijklmnopqrstuvwxyz';
    for (var i = 0; i < 12; i++)
        text.push(possible.charAt(Math.floor(Math.random() * possible.length)));

    return text.join(empty);
}

function decodeAccessory(string) {
    var regex = new RegExp(_options.accessory.open + '|' + _options.accessory.close, 'g');
    var code;
    var isStatic = true, openStub, closeStub;

    code = string.split(regex).map(function (piece, i) {
        openStub = '';
        closeStub = '';

        if (i % 2) {
            isStatic = false;
            piece = piece.trim();
            if (_options.emptyString) { // undefined as empty string
                if (piece.indexOf(' ') !== -1) {
                    openStub = '(';
                    closeStub = ')';
                }
                return ' + ' + openStub + piece + closeStub + '||\'\' + ';
            } else
                return ' + ' + piece + ' + ';
        } else {
            return JSON.stringify(piece);
        }
    }).join('');

    // micro-optimizations (remove appending empty strings)
    code = code.replace(/^"" \+ | \+ ""$/g, '').replace(/ \+ "" \+ /g, ' + ');

    return {value: code, isStatic: isStatic};
}

function formatText(tag, text) {
    return text
        .replace(_options.BREAK_LINE, ((_options.textSaveTags.indexOf(tag) !== -1) ? '\n' : ' '))
        .replace(/&#(\d+);/g, function (match, dec) {
            return String.fromCharCode(dec);
        })
        .trim();
}

function prepareKey(command, attributes) {
    var result = empty;
    if (command === Command.elementOpen || command === Command.elementVoid) {
        if (attributes && attributes.hasOwnProperty(_options.staticKey)) {
            result = comma + (attributes[_options.staticKey] || makeKey()) + '\', ';
            delete attributes[_options.staticKey];
        } else {
            result = ', null, ';
        }
    }
    return result;
}

function prepareAttr(command, attributes) {
    var result = empty, attr, decode, arrayStaticKey = false;
    if (command === Command.elementOpen || command === Command.elementVoid) {
        if (attributes && attributes.hasOwnProperty(_options.staticArray)) {
            arrayStaticKey = attributes[_options.staticArray] || makeKey();
            staticArraysHolder[arrayStaticKey] = [];
            delete attributes[_options.staticArray];
        }

        result = arrayStaticKey || null;
        for (var key in attributes) {
            attr = attributes[key];
            attr = (attr === null) ? key : attr;
            decode = decodeAccessory(attr);
            if (decode.isStatic) {
                if (arrayStaticKey)
                    staticArraysHolder[arrayStaticKey].push(quote + key + quote, quote + attr + quote);
                else
                    result += comma + key + '\', \'' + attr + quote;
            } else {
                result += comma + key + '\', ' + decode.value;
            }
        }
    }
    return result;
}

function decodeAttrs(obj) {
    var result = ['{'];
    for (var key in obj)
        result.push(((result.length > 1) ? ',' : empty) + key + ':' + decodeAccessory(obj[key]).value);
    result.push('}');

    return result.join(empty);
}

function writeCommand(command, tag, attributes) {
    stack.push(command + tag + quote + prepareKey(command, attributes) + prepareAttr(command, attributes)
        + Command.close);
}

function writeText(text) {
    text = formatText(state.tag, text);
    if (text.length > 0) {
        var decode = decodeAccessory(text);
        text = decode.isStatic ? (quote + text + quote) : decode.value;
        stack.push(Command.text + text + Command.close);
    }
}

function writeCode(text) {
    stack.push(formatText(state.tag, text));
}

function writeComment(text) {
    stack.push('\n// ' + text.replace(_options.BREAK_LINE, ' ') + '\n');
}

function writeAndCloseOpenState(isClosed) {
    var isShouldClose = true;
    if (state.tag) {
        if (helpers.indexOf(state.tag) !== -1) { // helper case
            stack.push('helpers[\'' + state.tag + '\'](' + decodeAttrs(state.attributes) + ');');
            isShouldClose = false;
        } else if (isClosed || _options.voidRequireTags.indexOf(state.tag) !== -1) { // void mode
            writeCommand(Command.elementVoid, state.tag, state.attributes);
            isShouldClose = false;
        } else if (state.tag !== _options.evaluate.name) { // standard mode
            writeCommand(Command.elementOpen, state.tag, state.attributes);
        } // if we write code, do nothing
    }

    // clear builder state for next tag
    state.tag = null;
    state.attributes = {};

    return isShouldClose; // should we close this tag: no if we have void element
}

/* public */
function Builder(functionWrapper) {
    wrapper = functionWrapper;
    this.reset();
}

Builder.prototype.reset = function () {
    stack = [];
    state = {
        tag: null,
        attributes: {}
    };
    staticArraysHolder = {};
};

Builder.prototype.set = function (helpersKeys) {
    helpers = helpersKeys;
};

Builder.prototype.write = function (command) {
    var tag;
    switch (command.type) {
        case Mode.Tag:
            tag = command.name.replace('/', empty);
            if (command.name.indexOf('/') === 0) { // close tag case
                if (writeAndCloseOpenState(true) && tag !== _options.evaluate.name)
                    writeCommand(Command.elementClose, tag);
            } else { // open tag case
                writeAndCloseOpenState();
                state.tag = tag;
                state.attributes = {};
            }
            break;
        case Mode.Attr: // push attribute in state
            state.attributes[command.name] = command.data;
            break;
        case Mode.Text: // write text
            tag = state.tag;
            writeAndCloseOpenState();
            if (tag === _options.evaluate.name) {
                writeCode(command.data);
            } else {
                writeText(command.data);
            }
            break;
        case Mode.Comment: // write comments immediately
            writeComment(command.data);
            break;
    }
};

Builder.prototype.done = function () {
    return wrapper(stack, staticArraysHolder);
};

module.exports = Builder;<commit_msg>helpers attributes with empty string<commit_after>/* private */
var _options = require('./options');
var Mode = require('./mode');
var Command = require('./wrapper').Command;

var state; // current builder state
var stack; // result builder
var staticArraysHolder = {}; // holder for static arrays
var wrapper; // external wrapper functionality
var helpers; // keys for helpers

var empty = '', quote = '\'', comma = ', \''; // auxiliary

function makeKey() {
    var text = new Array(12), possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgijklmnopqrstuvwxyz';
    for (var i = 0; i < 12; i++)
        text.push(possible.charAt(Math.floor(Math.random() * possible.length)));

    return text.join(empty);
}

function decodeAccessory(string, force) {
    var regex = new RegExp(_options.accessory.open + '|' + _options.accessory.close, 'g');
    var code;
    var isStatic = true, openStub, closeStub;

    code = string.split(regex).map(function (piece, i) {
        openStub = '';
        closeStub = '';

        if (i % 2) {
            isStatic = false;
            piece = piece.trim();
            if (_options.emptyString && !force) { // undefined as empty string
                if (piece.indexOf(' ') !== -1) {
                    openStub = '(';
                    closeStub = ')';
                }
                return ' + ' + openStub + piece + closeStub + '||\'\' + ';
            } else
                return ' + ' + piece + ' + ';
        } else {
            return JSON.stringify(piece);
        }
    }).join('');

    // micro-optimizations (remove appending empty strings)
    code = code.replace(/^"" \+ | \+ ""$/g, '').replace(/ \+ "" \+ /g, ' + ');

    return {value: code, isStatic: isStatic};
}

function formatText(tag, text) {
    return text
        .replace(_options.BREAK_LINE, ((_options.textSaveTags.indexOf(tag) !== -1) ? '\n' : ' '))
        .replace(/&#(\d+);/g, function (match, dec) {
            return String.fromCharCode(dec);
        })
        .trim();
}

function prepareKey(command, attributes) {
    var result = empty;
    if (command === Command.elementOpen || command === Command.elementVoid) {
        if (attributes && attributes.hasOwnProperty(_options.staticKey)) {
            result = comma + (attributes[_options.staticKey] || makeKey()) + '\', ';
            delete attributes[_options.staticKey];
        } else {
            result = ', null, ';
        }
    }
    return result;
}

function prepareAttr(command, attributes) {
    var result = empty, attr, decode, arrayStaticKey = false;
    if (command === Command.elementOpen || command === Command.elementVoid) {
        if (attributes && attributes.hasOwnProperty(_options.staticArray)) {
            arrayStaticKey = attributes[_options.staticArray] || makeKey();
            staticArraysHolder[arrayStaticKey] = [];
            delete attributes[_options.staticArray];
        }

        result = arrayStaticKey || null;
        for (var key in attributes) {
            attr = attributes[key];
            attr = (attr === null) ? key : attr;
            decode = decodeAccessory(attr);
            if (decode.isStatic) {
                if (arrayStaticKey)
                    staticArraysHolder[arrayStaticKey].push(quote + key + quote, quote + attr + quote);
                else
                    result += comma + key + '\', \'' + attr + quote;
            } else {
                result += comma + key + '\', ' + decode.value;
            }
        }
    }
    return result;
}

function decodeAttrs(obj) {
    var result = ['{'];
    for (var key in obj)
        result.push(((result.length > 1) ? ',' : empty) + key + ':' + decodeAccessory(obj[key], true).value);
    result.push('}');

    return result.join(empty);
}

function writeCommand(command, tag, attributes) {
    stack.push(command + tag + quote + prepareKey(command, attributes) + prepareAttr(command, attributes)
        + Command.close);
}

function writeText(text) {
    text = formatText(state.tag, text);
    if (text.length > 0) {
        var decode = decodeAccessory(text);
        text = decode.isStatic ? (quote + text + quote) : decode.value;
        stack.push(Command.text + text + Command.close);
    }
}

function writeCode(text) {
    stack.push(formatText(state.tag, text));
}

function writeComment(text) {
    stack.push('\n// ' + text.replace(_options.BREAK_LINE, ' ') + '\n');
}

function writeAndCloseOpenState(isClosed) {
    var isShouldClose = true;
    if (state.tag) {
        if (helpers.indexOf(state.tag) !== -1) { // helper case
            stack.push('helpers[\'' + state.tag + '\'](' + decodeAttrs(state.attributes) + ');');
            isShouldClose = false;
        } else if (isClosed || _options.voidRequireTags.indexOf(state.tag) !== -1) { // void mode
            writeCommand(Command.elementVoid, state.tag, state.attributes);
            isShouldClose = false;
        } else if (state.tag !== _options.evaluate.name) { // standard mode
            writeCommand(Command.elementOpen, state.tag, state.attributes);
        } // if we write code, do nothing
    }

    // clear builder state for next tag
    state.tag = null;
    state.attributes = {};

    return isShouldClose; // should we close this tag: no if we have void element
}

/* public */
function Builder(functionWrapper) {
    wrapper = functionWrapper;
    this.reset();
}

Builder.prototype.reset = function () {
    stack = [];
    state = {
        tag: null,
        attributes: {}
    };
    staticArraysHolder = {};
};

Builder.prototype.set = function (helpersKeys) {
    helpers = helpersKeys;
};

Builder.prototype.write = function (command) {
    var tag;
    switch (command.type) {
        case Mode.Tag:
            tag = command.name.replace('/', empty);
            if (command.name.indexOf('/') === 0) { // close tag case
                if (writeAndCloseOpenState(true) && tag !== _options.evaluate.name)
                    writeCommand(Command.elementClose, tag);
            } else { // open tag case
                writeAndCloseOpenState();
                state.tag = tag;
                state.attributes = {};
            }
            break;
        case Mode.Attr: // push attribute in state
            state.attributes[command.name] = command.data;
            break;
        case Mode.Text: // write text
            tag = state.tag;
            writeAndCloseOpenState();
            if (tag === _options.evaluate.name) {
                writeCode(command.data);
            } else {
                writeText(command.data);
            }
            break;
        case Mode.Comment: // write comments immediately
            writeComment(command.data);
            break;
    }
};

Builder.prototype.done = function () {
    return wrapper(stack, staticArraysHolder);
};

module.exports = Builder;<|endoftext|>


<commit_before>const settings = require("../settings.json");
exports.run = (client, message, params) => {
  if (!params[0]) {
    const commandNames = Array.from(client.commands.keys());
    const longest = commandNames.reduce((long, str) => Math.max(long, str.length), 0);
    message.channel.send(`= Command List =\n\nUse ${settings.prefix}help <commandname> for details.\n\n${client.commands.map(c => `${settings.prefix}${c.help.name}${" ".repeat(longest - c.help.name.length)} :: ${c.help.description}`).join('\n')}`, {code: 'asciidoc'});
  } else {
    let command = params[0];
    if (client.commands.has(command)) {
      command = client.commands.get(command);
      message.channel.send(`= ${command.help.name} = \n${command.help.description}\nusage::${command.help.usage}`, {code: "asciidoc"});
    }
  }
};

exports.conf = {
  enabled: true,
  guildOnly: false,
  aliases: ["h", "help"],
  permLevel: 0
};

exports.help = {
  name: "Help",
  description: "Displays all the available commands for your permission level.",
  usage: "help <command>"
};
<commit_msg>Update help.js<commit_after>const settings = require("../settings.json");
exports.run = (client, message, params) => {
  if (!params[0]) {
    const commandNames = Array.from(client.commands.keys());
    const longest = commandNames.reduce((long, str) => Math.max(long, str.length), 0);
    message.channel.send(`= Command List =\n\nUse ${settings.prefix}help <commandname> for details.\n\n${client.commands.map(c => `${settings.prefix}${c.help.name}${" ".repeat(longest - c.help.name.length)} :: ${c.help.description}`).join('\n')}`, {code: "asciidoc"});
  } else {
    let command = params[0];
    if (client.commands.has(command)) {
      command = client.commands.get(command);
      message.channel.send(`= ${command.help.name} = \n${command.help.description}\nusage::${command.help.usage}`, {code: "asciidoc"});
    }
  }
};

exports.conf = {
  enabled: true,
  guildOnly: false,
  aliases: ["h", "help"],
  permLevel: 0
};

exports.help = {
  name: "Help",
  description: "Displays all the available commands for your permission level.",
  usage: "help <command>"
};
<|endoftext|>


<commit_before>function validateEmail(email) {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return re.test(email);
}
function lettersOnly(param){
    var letters = /^[a-zA-Z]*$/;
    return letters.test(param);
}
function onlyNumbers(num){
    var numbers = /^[0-9]*$/;
    return numbers.test(num);
}
function profileForm2() {
    var fname = document.forms["profileForm"]["firstName"].value;
    var lname = document.forms["profileForm"]["lastName"].value;
    var country = document.forms["profileForm"]["country"].value;
    var city = document.forms["profileForm"]["city"].value;
    var streetName = document.forms["profileForm"]["streetName"].value;
    var streetNumber = document.forms["profileForm"]["streetNumber"].value;
    var phoneNumber = document.forms["profileForm"]["phoneNumber"].value;
    var email = document.forms["profileForm"]["email"].value;
    var pass = document.forms["profileForm"]["password"].value;
    var passconf = document.forms["profileForm"]["passwordconf"].value;
    var antispam = document.forms["profileForm"]["antispam"].value;
    var validatedEmail = validateEmail(email);

    if (fname == null || fname == "") {
        alert("First Name must be filled in");
        return false;
    } else {
        if(!lettersOnly(fname)){
            alert ("Only letters and spaces allowed in first name");
            return false;
        }
        if(fname.length < 2){
            alert("First name too short");
            return false;
        }
    }
    if (lname == null || lname == "") {
        alert("Last Name must be filled");
        return false;
    } else {
        if(!lettersOnly(lname)){
            alert ("Only letters and spaces allowed in last name");
            return false;
        }
        if(lname.length < 2){
            alert("Last name too short");
            return false;
        }
    }
    if (country == null || country == "") {
        alert("Country name must be filled in");
        return false;
    } else {
        if(!lettersOnly(country)){
            alert ("Only letters and spaces allowedin country name");
            return false;
        }
        if(country.length < 2){
            alert("Country name too short");
            return false;
        }
    }
    if (city == null || city == "") {
        alert("City name must be filled in");
        return false;
    } else {
        if(!lettersOnly(city)){
            alert ("Only letters and spaces allowed in city name");
            return false;
        }
        if(city.length < 2){
            alert("City name too short");
            return false;
        }
    }
    if (streetNumber == null || streetNumber == "") {
        alert("Street Number must be filled in");
        return false;
    }

    if (streetName == null || streetName == "") {
        alert("Street Name must be filled");
        return false;
    } else {
        if(!lettersOnly(streetName)){
            alert ("Only letters and spaces allowed in street name");
            return false;
        }
        if(streetName.length < 2){
            alert("Street name too short");
            return false;
        }
    }
    if (phoneNumber == null || phoneNumber == "") {
        alert("Phone Number must be filled in");
        return false;
    } else {
        if(phoneNumber.length != 10){
            alert("Phone number must have 10 numbers");
            return false;
        }
        if(!onlyNumbers(phoneNumber)){
            alert("Please insert only numbers in phone number field");
            return false;
        }
    }
    if (!validatedEmail) {
        alert("Invalid email format");
        return false;
    }
    if (email == null || email == "") {
        alert("Email must be filled in");
        return false;
    }
    if (pass == null || pass == "") {
        alert("Password must be filled in");
        return false;
    }
    if (passconf == null || passconf == "") {
        alert("Password Confirm must be filled in");
        return false;
    }
    if (pass != passconf) {
        alert("Passwords do not match");
        return false;
    }
    if (antispam == null || antispam == "" || antispam != 6) {
        alert("Antispam must be filled in or value incorrect");
        return false;
    }
}<commit_msg>profilevalidation  debugged<commit_after>function validateEmail(email) {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return re.test(email);
}
function lettersOnly(param){
    var letters = /^[a-zA-Z\s]*$/;
    return letters.test(param);
}
function onlyNumbers(num){
    var numbers = /^[0-9]*$/;
    return numbers.test(num);
}
function profileForm2() {
    var fname = document.forms["profileForm"]["firstName"].value;
    var lname = document.forms["profileForm"]["lastName"].value;
    var country = document.forms["profileForm"]["country"].value;
    var city = document.forms["profileForm"]["city"].value;
    var streetName = document.forms["profileForm"]["streetName"].value;
    var streetNumber = document.forms["profileForm"]["streetNumber"].value;
    var phoneNumber = document.forms["profileForm"]["phoneNumber"].value;
    var email = document.forms["profileForm"]["email"].value;
    var pass = document.forms["profileForm"]["password"].value;
    var passconf = document.forms["profileForm"]["passwordconf"].value;
    var antispam = document.forms["profileForm"]["antispam"].value;
    var validatedEmail = validateEmail(email);

    if (fname == null || fname == "") {
        alert("First Name must be filled in");
        return false;
    } else {
        if(!lettersOnly(fname)){
            alert ("Only letters and spaces allowed in first name");
            return false;
        }
        if(fname.length < 2){
            alert("First name too short");
            return false;
        }
    }
    if (lname == null || lname == "") {
        alert("Last Name must be filled");
        return false;
    } else {
        if(!lettersOnly(lname)){
            alert ("Only letters and spaces allowed in last name");
            return false;
        }
        if(lname.length < 2){
            alert("Last name too short");
            return false;
        }
    }
    if (country == null || country == "") {
        alert("Country name must be filled in");
        return false;
    } else {
        if(!lettersOnly(country)){
            alert ("Only letters and spaces allowedin country name");
            return false;
        }
        if(country.length < 2){
            alert("Country name too short");
            return false;
        }
    }
    if (city == null || city == "") {
        alert("City name must be filled in");
        return false;
    } else {
        if(!lettersOnly(city)){
            alert ("Only letters and spaces allowed in city name");
            return false;
        }
        if(city.length < 2){
            alert("City name too short");
            return false;
        }
    }
    if (streetNumber == null || streetNumber == "") {
        alert("Street Number must be filled in");
        return false;
    }

    if (streetName == null || streetName == "") {
        alert("Street Name must be filled");
        return false;
    } else {
        if(!lettersOnly(streetName)){
            alert ("Only letters and spaces allowed in street name");
            return false;
        }
        if(streetName.length < 2){
            alert("Street name too short");
            return false;
        }
    }
    if (phoneNumber == null || phoneNumber == "") {
        alert("Phone Number must be filled in");
        return false;
    } else {
        if(phoneNumber.length != 10){
            alert("Phone number must have 10 numbers");
            return false;
        }
        if(!onlyNumbers(phoneNumber)){
            alert("Please insert only numbers in phone number field");
            return false;
        }
    }
    if (!validatedEmail) {
        alert("Invalid email format");
        return false;
    }
    if (email == null || email == "") {
        alert("Email must be filled in");
        return false;
    }
    if (pass == null || pass == "") {
        alert("Password must be filled in");
        return false;
    }
    if (passconf == null || passconf == "") {
        alert("Password Confirm must be filled in");
        return false;
    }
    if (pass != passconf) {
        alert("Passwords do not match");
        return false;
    }
    if (antispam == null || antispam == "" || antispam != 6) {
        alert("Antispam must be filled in or value incorrect");
        return false;
    }
}<|endoftext|>


<commit_before>/** @author Michael Murphy */

var mongoose = require('mongoose');
var schema = require('../admin/role-manager');
var _ = require('underscore')

schema.add({
   classNumber: {
      type: String,
      match: /[1-5]\d{2}/
   },
   classCode: {
      type: String,
      enum: ["AERO","AGB","AEPS","AGC","AGED","AG","ASCI","ANT","ARCE","ARCH","ART","ASTR","BIO","BMED","BRAE","BOT","BUS","CHEM","CD","CHIN","CRP","CE","COMS","CPE","CSC","CM","DSCI","DANC","DATA","DMHS","ESE","ESM","ERSC","ECON","EDUC","EE","ENGR","ENGL","EDES","ENVE","ES","FPE","FSN","FR","GEOG","GEOL","GER","GS","GSA","GSB","GSE","GRC","HIST","HNRC","HNRS","IME","IT","ISLA","IS","ITAL","JPNS","JOUR","KINE","LA","LAES","LS","MSCI","MATE","MATH","ME","MCRO","MSL","MLL","MU","NR","PHIL","PEM","PEW","PSC","PHYS","POLS","PSY","RPTA","RELS","SCM","SOCS","SOC","SS","SPAN","STAT","SIE","TH","UNIV","WVIT","WGS","ZOO"]
   },
   section: {
      type: String,
      match: /\d+/
   },
   start: Date,
   end: Date,
   year: {
      type: String,
      required: true,
      "default": function(){
         return (new Date()).getFullYear().toString();
      },
      match: /\d{4}/
   },
   term: {
      type: String,
      enum: ['Winter', 'Spring', 'Summer', 'Fall'],
      required: true,
      "default": getTermByMonth
   },
   coursePath: {
      type: String,
      index: {
         unique: true
      },
      required: true,
      select: true,
      match: /[A-Z][-A-Z0-9]*/
   }
});
schema.index({ coursePath: 1, term: 1, year: -1});
schema.set('autoIndex', false);

function getTermByMonth(month) {
   var legend = [
      {'Winter': [12, 1, 2]},
      {'Spring': [3,4,5]},
      {'Summer': [6,7,8]},
      {'Fall': [9,10,11]}
   ];
   var m = month || (new Date()).getMonth() + 1;
   var result = legend.filter(function(e){
      return e[_.keys(e)[0]].indexOf(m) != -1;
   });
   return _.keys(result[0])[_.keys(result)[0]].toString();
}

function mkCourse(admin) {
   var defaultRoles = [
      {name: "INSTRUCTOR", permissions: [], users: [admin]},
      {name: "TEACHER_ASSISTANT", permissions: [], users: [admin]},
      {name: "STUDENT", permissions: [], users: [admin]},
      {name: "NONE", permissions: [], users: [admin]}
   ];
   var codes = ["AERO","AGB","AEPS","AGC","AGED","AG","ASCI","ANT","ARCE","ARCH","ART","ASTR","BIO","BMED","BRAE","BOT","BUS","CHEM","CD","CHIN","CRP","CE","COMS","CPE","CSC","CM","DSCI","DANC","DATA","DMHS","ESE","ESM","ERSC","ECON","EDUC","EE","ENGR","ENGL","EDES","ENVE","ES","FPE","FSN","FR","GEOG","GEOL","GER","GS","GSA","GSB","GSE","GRC","HIST","HNRC","HNRS","IME","IT","ISLA","IS","ITAL","JPNS","JOUR","KINE","LA","LAES","LS","MSCI","MATE","MATH","ME","MCRO","MSL","MLL","MU","NR","PHIL","PEM","PEW","PSC","PHYS","POLS","PSY","RPTA","RELS","SCM","SOCS","SOC","SS","SPAN","STAT","SIE","TH","UNIV","WVIT","WGS","ZOO"];
   function genStr(all, len) {
      var result = "";
      for (var i = 0; i < len; ++i) {
         result += all.charAt(Math.floor(Math.random() * all.length));
      }
      return result;
   }
   function COURSE_CODE_GENERATOR() {
      return codes[Math.floor(Math.random() * codes.length)];
   }
   function COURSE_NUMBER_GENERATOR() {
      return genStr('12345',1) + genStr('1234567890', 2);
      //var all = '0123456789';
      //var result = all.charAt(Math.floor(Math.random() * (all.length-1))+1);
      //for (var i = 0; i < 2; ++i) {
      //   result += all.charAt(Math.floor(Math.random() * all.length));
      //}
      //return result;
   }
   function COURSE_SECTION_GENERATOR() {
      var all = '0123456789';
      var result = all.charAt(Math.floor(Math.random() * (all.length-1))+1);
      return result;
   }
   var result = {
      classCode: COURSE_CODE_GENERATOR(),
      classNumber: COURSE_NUMBER_GENERATOR(),
      section: COURSE_SECTION_GENERATOR(),
      //start: new Date(2015, 3, 30),
      //end: new Date(2015, 6, 14),
      roles: defaultRoles,
      term: getTermByMonth(Math.ceil(Math.random() * 12)),
      year: 2015 + Math.ceil(Math.random() * 9)
   };
   result.coursePath =  result.classCode + "-" + result.classNumber + "-" + result.section + "-" + result.term + result.year;
   return result;
}

schema.statics.getTermByMonth = getTermByMonth;
schema.statics.getRestOptions = function() {
   return {idProperty: "coursePath"};
}
schema.statics.makeRandomCourse = mkCourse;

module.exports = mongoose.model('Course', schema);<commit_msg>generateRandomCourse() now sets start and end dates.<commit_after>/** @author Michael Murphy */

var mongoose = require('mongoose');
var schema = require('../admin/role-manager');
var _ = require('underscore')

schema.add({
   classNumber: {
      type: String,
      match: /[1-5]\d{2}/
   },
   classCode: {
      type: String,
      enum: ["AERO","AGB","AEPS","AGC","AGED","AG","ASCI","ANT","ARCE","ARCH","ART","ASTR","BIO","BMED","BRAE","BOT","BUS","CHEM","CD","CHIN","CRP","CE","COMS","CPE","CSC","CM","DSCI","DANC","DATA","DMHS","ESE","ESM","ERSC","ECON","EDUC","EE","ENGR","ENGL","EDES","ENVE","ES","FPE","FSN","FR","GEOG","GEOL","GER","GS","GSA","GSB","GSE","GRC","HIST","HNRC","HNRS","IME","IT","ISLA","IS","ITAL","JPNS","JOUR","KINE","LA","LAES","LS","MSCI","MATE","MATH","ME","MCRO","MSL","MLL","MU","NR","PHIL","PEM","PEW","PSC","PHYS","POLS","PSY","RPTA","RELS","SCM","SOCS","SOC","SS","SPAN","STAT","SIE","TH","UNIV","WVIT","WGS","ZOO"]
   },
   section: {
      type: String,
      match: /\d+/
   },
   start: Date,
   end: Date,
   year: {
      type: String,
      required: true,
      "default": function(){
         return (new Date()).getFullYear().toString();
      },
      match: /\d{4}/
   },
   term: {
      type: String,
      enum: ['Winter', 'Spring', 'Summer', 'Fall'],
      required: true,
      "default": getTermByMonth
   },
   coursePath: {
      type: String,
      index: {
         unique: true
      },
      required: true,
      select: true,
      match: /[A-Z][-A-Z0-9]*/
   }
});
schema.index({ coursePath: 1, term: 1, year: -1});
schema.set('autoIndex', false);

function getTermByMonth(month) {
   var legend = [
      {'Winter': [12, 1, 2]},
      {'Spring': [3,4,5]},
      {'Summer': [6,7,8]},
      {'Fall': [9,10,11]}
   ];
   var m = month || (new Date()).getMonth() + 1;
   var result = legend.filter(function(e){
      return e[_.keys(e)[0]].indexOf(m) != -1;
   });
   return _.keys(result[0])[_.keys(result)[0]].toString();
}

function generateRandomCourse(admin) {
   var defaultRoles = [
      {name: "INSTRUCTOR", permissions: [], users: [admin]},
      {name: "TEACHER_ASSISTANT", permissions: [], users: [admin]},
      {name: "STUDENT", permissions: [], users: [admin]},
      {name: "NONE", permissions: [], users: [admin]}
   ];
   var codes = ["AERO","AGB","AEPS","AGC","AGED","AG","ASCI","ANT","ARCE","ARCH","ART","ASTR","BIO","BMED","BRAE","BOT","BUS","CHEM","CD","CHIN","CRP","CE","COMS","CPE","CSC","CM","DSCI","DANC","DATA","DMHS","ESE","ESM","ERSC","ECON","EDUC","EE","ENGR","ENGL","EDES","ENVE","ES","FPE","FSN","FR","GEOG","GEOL","GER","GS","GSA","GSB","GSE","GRC","HIST","HNRC","HNRS","IME","IT","ISLA","IS","ITAL","JPNS","JOUR","KINE","LA","LAES","LS","MSCI","MATE","MATH","ME","MCRO","MSL","MLL","MU","NR","PHIL","PEM","PEW","PSC","PHYS","POLS","PSY","RPTA","RELS","SCM","SOCS","SOC","SS","SPAN","STAT","SIE","TH","UNIV","WVIT","WGS","ZOO"];
   function genStr(all, len) {
      var result = "";
      for (var i = 0; i < len; ++i) {
         result += all.charAt(Math.floor(Math.random() * all.length));
      }
      return result;
   }
   function COURSE_CODE_GENERATOR() {
      return codes[Math.floor(Math.random() * codes.length)];
   }
   function COURSE_NUMBER_GENERATOR() {
      return genStr('12345',1) + genStr('1234567890', 2);
   }
   function COURSE_SECTION_GENERATOR() {
      var all = '0123456789';
      var result = all.charAt(Math.floor(Math.random() * (all.length-1))+1);
      return result;
   }
   function genDates(term, year) {
      function date(m1, d1, m2, d2) {
         return {start: new Date(year, m1, d1), end: new Date(year, m2, d2)}
      }
      return {
         'Winter': date(0, 5, 2, 20),
         'Spring': date(2, 30, 5, 12),
         'Summer': date(5, 19, 7, 29),
         'Fall': date(8, 22, 11, 12)
      }[term];
   }
   var result = {
      classCode: COURSE_CODE_GENERATOR(),
      classNumber: COURSE_NUMBER_GENERATOR(),
      section: COURSE_SECTION_GENERATOR(),
      //start: new Date(2015, 3, 30),
      //end: new Date(2015, 6, 14),
      roles: defaultRoles,
      term: getTermByMonth(Math.ceil(Math.random() * 12)),
      year: 2015 + Math.ceil(Math.random() * 9)
   };
   _.extend(result, genDates(result.term, Number(result.year)));
   result.coursePath =  result.classCode + "-" + result.classNumber + "-" + result.section + "-" + result.term + result.year;
   return result;
}

schema.statics.getTermByMonth = getTermByMonth;
schema.statics.getRestOptions = function() {
   return {idProperty: "coursePath"};
}
schema.statics.makeRandomCourse = generateRandomCourse;

module.exports = mongoose.model('Course', schema);<|endoftext|>


<commit_before><commit_msg>Update ogario.v4.js<commit_after><|endoftext|>


<commit_before>function showOfflineToast() {
	if (navigator.serviceWorker) {
  		navigator.serviceWorker.register('/sw.js').then(function(reg) {
      		if (!reg.installing) return;
      		console.log("[*] ServiceWorker is installing...");
       		var worker = reg.installing;
 			worker.addEventListener('statechange', function() {
          		if (worker.state == 'redundant') {
              		console.log('[*] Install failed');
          		}
          		if (worker.state == 'installed') {
              		console.log('[*] Install successful!');
          		}
          		if (worker.state == 'activated' && !navigator.serviceWorker.controller) {
            		setInterval(showOfflineToast(),30);
          		}
      		});
  		});
	}
}
<commit_msg>Update web-application.js<commit_after>if('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js').then(function(registration) {
    // Registration was successful
  }).catch(function(err) {
    // registration failed :(
    console.log('ServiceWorker registration failed: ', err);
  });
}
<|endoftext|>


<commit_before>var
	moment   = require('moment'),
	Table    = require('cli-table2'),
	Registry = require('../lib/registry'),
	report   = require('../lib/report')
	;

function hooks(argv)
{
	// set this here and it's set for all the subcommands
	argv._handled = true;
}

hooks.add = function add(argv)
{
    var pkg = argv.pkg + '';
    // if the package is just a scope name set type to scope and save it!
	// @npm
	// not @npm/foo
	if(pkg.indexOf('@') === 0 && pkg.indexOf('/') === -1)
	{
		argv.type = 'scope';
	}

	// wacky way to support owner type without more args
	if(pkg.indexOf('~') === 0)
	{
		argv.pkg = pkg.replace('~','');
		argv.type = 'owner';
	}
	else if(pkg === process.env.HOME)
	{
		// bash expands ~ and ~username to process.env.HOME
		// no package begins with / so this is safe but wacky
		console.error('this module name matches your home directory.\nif you intended on making an owner hook for your own username you need to escape the ~ like \\~' + process.env.USER);
		process.exit(1);
	}
	else if(pkg.indexOf('owner:') === 0)
	{
		argv.pkg = pkg.replace('owner:','');
		argv.type = 'owner';
	}

	var reg = new Registry(argv);
	var opts = {
		method: 'POST',
		uri: '/v1/hooks/hook/',
		body: {
			type: argv.type || 'package',
			name:   argv.pkg,
			endpoint:    argv.url,
			secret: argv.secret
		}
	};

	reg.authed(opts, function(err, res, hook)
	{
		if (err)
			return report.failure('hook add', err.message);
		if (!hook || res.statusCode < 200 || res.statusCode >= 400)
			return report.failure('hook add', res.statusCode + ' ' + JSON.stringify(hook));

		if (argv.json)
			report.json(hook);
		else
			report.success('+', hook.name + ' ➜ ' + hook.endpoint);
	});
};

hooks.rm = function rm(argv)
{
	var reg = new Registry(argv);
	var opts = {
		method: 'DELETE',
		uri: '/v1/hooks/hook/' + encodeURIComponent(argv.id),
	};

	reg.authed(opts, function(err, res, hook)
	{
		if (err)
			return report.failure('hook rm', err.message);
		if (!hook || res.statusCode < 200 || res.statusCode >= 400)
			return report.failure('hook rm', res.statusCode + ' ' + JSON.stringify(hook));

		if (argv.json)
			report.json(hook);
		else
			report.success('–', hook.name + ' ✘ ' + hook.endpoint);
	});
};

hooks.ls = function ls(argv)
{
	var reg = new Registry(argv);
	var uri = '/v1/hooks';
	if (argv.pkg)
		uri += '?package=' + encodeURIComponent(argv.pkg);

	reg.authed({ uri: uri }, function(err, res, body)
	{
		if (err)
			return report.failure('hook ls', err.message);
		if (!body || res.statusCode < 200 || res.statusCode >= 400)
			return report.failure('hook ls', res.statusCode + ' ' + JSON.stringify(body));

		if (argv.json)
			report.json(body.objects);
		else
		{
			if (body.objects.length === 0)
			{
				report.success('hooks', 'you do not have any hooks configured yet.');
				return;
			}

			if (body.objects.length === 1)
				report.success('hooks', 'you have one hook');
			else
				report.success('hooks', 'you have ' + body.objects.length + ' hooks');

			var table = new Table({ head: ['id', 'type', 'target', 'endpoint'], });
			body.objects.forEach(function eachHook(hook)
			{
				table.push([
						{rowSpan: 2, content: hook.id},
						hook.type,
						hook.name,
						hook.endpoint]);
				if (hook.delivered)
				{
					table.push([{
						colSpan: 2,
						content: 'triggered ' + moment(hook.last_delivery).format('lll')},
						hook.response_code]);
				}
				else
					table.push([{colSpan:3, content:'never triggered'}]);
			});
			console.log(table.toString());
		}
	});
};

hooks.update = function update(argv)
{
	var reg = new Registry(argv);
	var opts = {
		method: 'PUT',
		uri: '/v1/hooks/hook/' + encodeURIComponent(argv.id),
		body: {
			endpoint: argv.url,
			secret: argv.secret
		}
	};

	reg.authed(opts, function(err, res, hook)
	{
		if (err)
			return report.failure('hook update', err.message);
		if (!hook || res.statusCode < 200 || res.statusCode >= 400)
			return report.failure('hook update', res.statusCode + ' ' + JSON.stringify(hook));

		if (argv.json)
			report.json(hook);
		else
		{
			report.success('+', hook.name + ' ➜ ' + hook.endpoint);
		}
	});
};

function noop() {}

function builder(yargs)
{
	return yargs
		.command('ls [pkg]', 'list your hooks', noop, hooks.ls)
		.command('add <pkg> <url> <secret>', 'add a hook to the named package', noop, hooks.add)
		.command('update <id> <url> [secret]', 'update an existing hook', noop, hooks.update)
		.command('rm <id>', 'remove a hook', noop, hooks.rm)
		.example('$0 hook add lodash https://example.com/ my-shared-secret')
		.example('$0 hook ls lodash')
		.example('$0 hook rm id-ers83f')
		.demand(2)
	;
}

module.exports = {
	command: 'hook',
	describe: 'control your hooks',
	builder: builder,
	handler: hooks,
	aliases: [ 'hooks' ]
};
<commit_msg>refactor fot --type<commit_after>var
	moment   = require('moment'),
	Table    = require('cli-table2'),
	Registry = require('../lib/registry'),
	report   = require('../lib/report')
	;

function hooks(argv)
{
	// set this here and it's set for all the subcommands
	argv._handled = true;
}

hooks.add = function add(argv)
{
	var pkg = argv.pkg + '';
	// if the package is just a scope name set type to scope and save it!
	var type = argv.type;

	// @npm
	// not @npm/foo
	if(pkg.indexOf('@') === 0 && pkg.indexOf('/') === -1)
	{
		argv.type = 'scope';
	}

        if(type) argv.type = type;

	var reg = new Registry(argv);
	var opts = {
		method: 'POST',
		uri: '/v1/hooks/hook/',
		body: {
			type: argv.type || 'package',
			name:   argv.pkg,
			endpoint:    argv.url,
			secret: argv.secret
		}
	};

	reg.authed(opts, function(err, res, hook)
	{
		if (err)
			return report.failure('hook add', err.message);
		if (!hook || res.statusCode < 200 || res.statusCode >= 400)
			return report.failure('hook add', res.statusCode + ' ' + JSON.stringify(hook));

		if (argv.json)
			report.json(hook);
		else
			report.success('+', hook.name + ' ➜ ' + hook.endpoint);
	});
};

hooks.rm = function rm(argv)
{
	var reg = new Registry(argv);
	var opts = {
		method: 'DELETE',
		uri: '/v1/hooks/hook/' + encodeURIComponent(argv.id),
	};

	reg.authed(opts, function(err, res, hook)
	{
		if (err)
			return report.failure('hook rm', err.message);
		if (!hook || res.statusCode < 200 || res.statusCode >= 400)
			return report.failure('hook rm', res.statusCode + ' ' + JSON.stringify(hook));

		if (argv.json)
			report.json(hook);
		else
			report.success('–', hook.name + ' ✘ ' + hook.endpoint);
	});
};

hooks.ls = function ls(argv)
{
	var reg = new Registry(argv);
	var uri = '/v1/hooks';
	if (argv.pkg)
		uri += '?package=' + encodeURIComponent(argv.pkg);

	reg.authed({ uri: uri }, function(err, res, body)
	{
		if (err)
			return report.failure('hook ls', err.message);
		if (!body || res.statusCode < 200 || res.statusCode >= 400)
			return report.failure('hook ls', res.statusCode + ' ' + JSON.stringify(body));

		if (argv.json)
			report.json(body.objects);
		else
		{
			if (body.objects.length === 0)
			{
				report.success('hooks', 'you do not have any hooks configured yet.');
				return;
			}

			if (body.objects.length === 1)
				report.success('hooks', 'you have one hook');
			else
				report.success('hooks', 'you have ' + body.objects.length + ' hooks');

			var table = new Table({ head: ['id', 'type', 'target', 'endpoint'], });
			body.objects.forEach(function eachHook(hook)
			{
				table.push([
						{rowSpan: 2, content: hook.id},
						hook.type,
						hook.name,
						hook.endpoint]);
				if (hook.last_delivery)
				{
					table.push([{
						colSpan: 2,
						content: 'triggered ' + moment(hook.last_delivery).format('lll')},
						hook.response_code]);
				}
				else
					table.push([{colSpan:3, content:'never triggered'}]);
			});
			console.log(table.toString());
		}
	});
};

hooks.update = function update(argv)
{
	var reg = new Registry(argv);
	var opts = {
		method: 'PUT',
		uri: '/v1/hooks/hook/' + encodeURIComponent(argv.id),
		body: {
			endpoint: argv.url,
			secret: argv.secret
		}
	};

	reg.authed(opts, function(err, res, hook)
	{
		if (err)
			return report.failure('hook update', err.message);
		if (!hook || res.statusCode < 200 || res.statusCode >= 400)
			return report.failure('hook update', res.statusCode + ' ' + JSON.stringify(hook));

		if (argv.json)
			report.json(hook);
		else
		{
			report.success('+', hook.name + ' ➜ ' + hook.endpoint);
		}
	});
};

function noop() {}

function builder(yargs)
{
	return yargs
		.command('ls [pkg]', 'list your hooks', noop, hooks.ls)
		.command('add <pkg> <url> <secret>', 'add a hook to the named package or object',function()
		{
			return yargs.option('type', {
				alias: 't',
				description:"owner, scope, and package.\nyou can hook specific packages but also objects that are related to many packages.\t@scope and package are taken care of for you, but to make an owner hook (like all packages substack maintains) don't forget --type owner"
			});
		}, hooks.add)
		.command('update <id> <url> [secret]', 'update an existing hook', noop, hooks.update)
		.command('rm <id>', 'remove a hook', noop, hooks.rm)
		.example('$0 hook add lodash https://example.com/ my-shared-secret')
		.example('$0 hook ls lodash')
		.example('$0 hook rm id-ers83f')
		.demand(2)
	;
}

module.exports = {
	command: 'hook',
	describe: 'control your hooks',
	builder: builder,
	handler: hooks,
	aliases: [ 'hooks' ]
};
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const config = require("./config.json");

exports.run = async (bot, message, args) => {
  if (!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send(`__**Access Denied**__\nYou must have __KICK_MEMBERS__ perms to use this command.`);

    let member = message.mentions.members.first();
    if(!member)
      return message.reply("Please mention a valid member of this server");
   if(member.id == config.ownerID) return message.channel.send("You shall not kick the all mighty majestic!")
    if(!member.bannable)
      return message.reply("I cannot kick this user! Do they have a higher role? Do I have ban permissions?");

    let reason = args.slice(1).join(' ');
    if(!reason)
      return message.reply("Please indicate a reason for the kick!");

        const channel = member.guild.channels.find('name', 'mod-log');
      if (!channel) return message.reply("Make sure you have a channel called mod-log!");

    await member.ban(reason)
      .catch(error => message.reply(`Sorry ${message.author} I couldn't kick because of : ${error}`));
    message.reply(`${member.user.tag} has been kicked by ${message.author.tag} because: ${reason} \n https://gyazo.com/af59ec17c89eec2c02bbc13dcb38a842`);
    var embed = new Discord.RichEmbed()
    .setTitle("Kick")
    .setColor("#80d4ff")
    .addField(`${member.user.tag} has been kicked`, `has been kicked by ${message.author.tag}`)
    .addField("The reason is:", `${reason}`)
    channel.send({ embed: embed });
  };
<commit_msg>Update kick.js<commit_after>const Discord = require('discord.js');
const config = require("./config.json");

exports.run = async (bot, message, args, channel) => {
  if (!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send(`__**Access Denied**__\nYou must have __KICK_MEMBERS__ perms to use this command.`);

    let member = message.mentions.members.first();
    if(!member)
      return message.reply("Please mention a valid member of this server");
   if(member.id == config.ownerID) return message.channel.send("You shall not kick the all mighty majestic!")
    if(!member.bannable)
      return message.reply("I cannot kick this user! Do they have a higher role? Do I have ban permissions?");

    let reason = args.slice(1).join(' ');
    if(!reason)
      return message.reply("Please indicate a reason for the kick!");

    await member.ban(reason)
      .catch(error => message.reply(`Sorry ${message.author} I couldn't kick because of : ${error}`));
    message.reply(`${member.user.tag} has been kicked by ${message.author.tag} because: ${reason} \n https://gyazo.com/af59ec17c89eec2c02bbc13dcb38a842`);
    var embed = new Discord.RichEmbed()
    .setTitle("Kick")
    .setColor("#80d4ff")
    .addField(`${member.user.tag} has been kicked`, `has been kicked by ${message.author.tag}`)
    .addField("The reason is:", `${reason}`)
    channel.send({ embed: embed });
  };
<|endoftext|>


<commit_before>const Discord = require('discord.js');
exports.run = (client, message, args) => {
    let reason = args.slice(1).join(' ');
    let user = message.mentions.users.first();
    let modlog = client.channels.find('name', 'delet-this');
    if (!modlog) return message.reply('I cannot find a mod-log channel!')
    if (reason.length < 1) return message.reply('you must supply a reason to kick the mentioned user.');
    if (message.mentions.users.size < 1) return message.reply('you must mention a user to kick.').catch(console.error);

    if (!message.guild.member(user).kickable) return message.reply('I cannot kick that user from the server.');
    message.guild.member(user).kick();

    const embed = new Discord.RichEmbed()
    .setColor(0x00AE86)
    .setTimestamp()
    .addField('Action:', 'Kick')
    .addField('Target:', `${user.username}#${user.discriminator} [ID: ${user.id}]`)
    .addField('Responsible moderator:', `${message.author.username}#${message.author.discriminator}`);
    return client.channels.get(modlog.id).sendEmbed(embed);
};

exports.conf = {
    enabled: true,
    guildOnly: false,
    aliases: [],
    permLevel: 2
};

exports.help = {
    name: 'kick',
    description: 'Kicks the mentioned user from the server.',
    usage: 'kick [user] [reason]'
};<commit_msg>Update kick.js<commit_after>const Discord = require('discord.js');
exports.run = (client, message, args) => {
    let reason = args.slice(1).join(' ');
    let user = message.mentions.users.first();
    let modlog = client.channels.find('name', 'delet-this');
    let modRole = message.guild.roles.find('name', 'delet Mod');
    if (!message.member.roles.has(modRole.id)) {
        return message.reply('you have insufficient permissions to use this command.').catch(console.error);
    }
    if (!modlog) return message.reply('I cannot find a mod-log channel!')
    if (reason.length < 1) return message.reply('you must supply a reason to kick the mentioned user.');
    if (message.mentions.users.size < 1) return message.reply('you must mention a user to kick.').catch(console.error);

    if (!message.guild.member(user).kickable) return message.reply('I cannot kick that user from the server.');
    message.guild.member(user).kick();

    client.channels.get(modlog.id).send({embed: {
        color: 13174317,
        author: {
        name: `👢 Kicked ${user.username}#${user.discriminator} (${user.id})`,
        icon_url: user.avatarURL
        },
        title: "",
        url: "",
        description: `\`\`\`js\nReason: ${reason}\nResponsible moderator: ${message.author.tag} (${message.author.id})\`\`\``,
        // fields: [{
        //     name: "Fields",
        //     value: "They can have different fields with small headlines."
        // },
        // {
        //     name: "Masked links",
        //     value: "You can put [masked links](http://google.com) inside of rich embeds."
        // },
        // {
        //     name: "Markdown",
        //     value: "You can put all the *usual* **__Markdown__** inside of them."
        // }
        // ],
        timestamp: new Date(),
        footer: {
        //icon_url: client.user.avatarURL,
        text: "Moderation system powered by delet"
        }
    }
});

message.channel.send(`You successfully **kicked** ${user.tag} for "${reason}". :ok_hand:`);

};

exports.conf = {
    enabled: true,
    guildOnly: false,
    aliases: [],
    permLevel: 0
};

exports.help = {
    name: 'kick',
    description: 'Kicks the mentioned user from the server.',
    usage: 'kick [user] [reason]'
};
<|endoftext|>


<commit_before>//handles playing and downloading a song from youtube
module.exports = function command(bot, info)
{
    "use strict";
    //load in the required files and create a Downloader object to handle downloading audio
    const yti = require('youtube-info');
    const Downloader = require("../lib/Downloader.js");
    var dl = new Downloader(info.config.ffmpeg_loc);
    const fs = require('fs');
    return {
        alias: ['p'],
        description: "[<YouTube URL>] Gets info from a YouTube link",
        permissions: "public",
        action: function(details)
        {
          //handles getting youtube information and initiates a download
          //the song gets added to the playlist AFTER it's downloaded
          const getData = function(parsed)
          {
            //get in the information from the youtube ID
            const yID = parsed || "noID";
            yti(yID, function(err, songInfo)
            {
              if(err)
              {
                console.log("Error occurred, the YID is: " + yID);
              }
              else
              {
                //gets rid of any spaces in the file name
                let title = songInfo.title.replace(/ /g, "").replace(/[\/\\]/g, "_")+".mp3";
                console.log("Recieved info for " + songInfo.title);
                //looks to see if the song requested is already downloaded
                //if it is, don't redownload it
                if(info.audio.searchSong(songInfo.title))
                {
                  info.audio.playlist.push({"song_name": songInfo.title, "file": title});
                  console.log("Song exists on playlist, file is present. No need to download it again");
                }
                else
                {
                   //send info to the downloader process to download a song.
                   info.audio.downloader.send({id: yID, title: songInfo.title, file: title});
                }
              }
            });
          }
          if(details.input === "") {return;}
          switch(details.args.length)
          {
            case 1:
              return;
            case 2:
              if(details.args[1].includes("https://youtu.be/"))
              {
                getData(details.args[1].replace(/https:\/\/youtu.be\//g,""));
              }
              else
              {
                getData(details.args[1].split('=')[1] || "noid");
              }
              return;
          }
        }
    };
};<commit_msg>Added some output<commit_after>//handles playing and downloading a song from youtube
module.exports = function command(bot, info)
{
    "use strict";
    //load in the required files and create a Downloader object to handle downloading audio
    const yti = require('youtube-info');
    const Downloader = require("../lib/Downloader.js");
    var dl = new Downloader(info.config.ffmpeg_loc);
    const fs = require('fs');
    return {
        alias: ['p'],
        description: "[<YouTube URL>] Gets info from a YouTube link",
        permissions: "public",
        action: function(details)
        {
          //handles getting youtube information and initiates a download
          //the song gets added to the playlist AFTER it's downloaded
          const getData = function(parsed)
          {
            //get in the information from the youtube ID
            const yID = parsed || "noID";
            yti(yID, function(err, songInfo)
            {
              if(err)
              {
                console.log("Error occurred, the YID is: " + yID);
              }
              else
              {
                //gets rid of any spaces in the file name
                let title = songInfo.title.replace(/ /g, "").replace(/[\/\\]/g, "_")+".mp3";
                console.log("Recieved info for " + songInfo.title);
                //looks to see if the song requested is already downloaded
                //if it is, don't redownload it
                if(info.audio.searchSong(songInfo.title))
                {
                  info.audio.playlist.push({"song_name": songInfo.title, "file": title});
                  console.log("Song exists on playlist, file is present. No need to download it again");
                }
                else
                {
                   //send info to the downloader process to download a song.
                   console.log("Downloading " + songInfo.title);
                   info.audio.downloader.send({id: yID, title: songInfo.title, file: title});
                }
              }
            });
          }
          if(details.input === "") {return;}
          switch(details.args.length)
          {
            case 1:
              return;
            case 2:
              if(details.args[1].includes("https://youtu.be/"))
              {
                getData(details.args[1].replace(/https:\/\/youtu.be\//g,""));
              }
              else
              {
                getData(details.args[1].split('=')[1] || "noid");
              }
              return;
          }
        }
    };
};<|endoftext|>